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"
46 #define MAX_GET_SD_ACCESS_DENIED_WARNINGS 1
47 #define MAX_GET_SACL_PRIV_NOTHELD_WARNINGS 1
48 struct win32_capture_state {
49 unsigned long num_get_sd_access_denied;
50 unsigned long num_get_sacl_priv_notheld;
53 #define MAX_SET_SD_ACCESS_DENIED_WARNINGS 1
54 #define MAX_SET_SACL_PRIV_NOTHELD_WARNINGS 1
56 #ifdef ENABLE_ERROR_MESSAGES
58 win32_error(u32 err_code)
62 nchars = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
63 FORMAT_MESSAGE_ALLOCATE_BUFFER,
65 (wchar_t*)&buffer, 0, NULL);
67 ERROR("Error printing error message! "
68 "Computer will self-destruct in 3 seconds.");
70 ERROR("Win32 error: %ls", buffer);
74 #else /* ENABLE_ERROR_MESSAGES */
75 # define win32_error(err_code)
76 #endif /* !ENABLE_ERROR_MESSAGES */
78 /* Pointers to functions that are not available on all targetted versions of
79 * Windows (XP and later). NOTE: The WINAPI annotations seem to be important; I
80 * assume it specifies a certain calling convention. */
83 static HANDLE (WINAPI *win32func_FindFirstStreamW)(LPCWSTR lpFileName,
84 STREAM_INFO_LEVELS InfoLevel,
85 LPVOID lpFindStreamData,
86 DWORD dwFlags) = NULL;
89 static BOOL (WINAPI *win32func_FindNextStreamW)(HANDLE hFindStream,
90 LPVOID lpFindStreamData) = NULL;
92 static HMODULE hKernel32 = NULL;
94 /* Try to dynamically load some functions */
100 if (hKernel32 == NULL) {
101 DEBUG("Loading Kernel32.dll");
102 hKernel32 = LoadLibraryW(L"Kernel32.dll");
103 if (hKernel32 == NULL) {
104 err = GetLastError();
105 WARNING("Can't load Kernel32.dll");
111 DEBUG("Looking for FindFirstStreamW");
112 win32func_FindFirstStreamW = (void*)GetProcAddress(hKernel32, "FindFirstStreamW");
113 if (!win32func_FindFirstStreamW) {
114 WARNING("Could not find function FindFirstStreamW() in Kernel32.dll!");
115 WARNING("Capturing alternate data streams will not be supported.");
119 DEBUG("Looking for FindNextStreamW");
120 win32func_FindNextStreamW = (void*)GetProcAddress(hKernel32, "FindNextStreamW");
121 if (!win32func_FindNextStreamW) {
122 WARNING("Could not find function FindNextStreamW() in Kernel32.dll!");
123 WARNING("Capturing alternate data streams will not be supported.");
124 win32func_FindFirstStreamW = NULL;
129 win32_global_cleanup()
131 if (hKernel32 != NULL) {
132 DEBUG("Closing Kernel32.dll");
133 FreeLibrary(hKernel32);
138 static const wchar_t *capture_access_denied_msg =
139 L" If you are not running this program as the administrator, you may\n"
140 " need to do so, so that all data and metadata can be backed up.\n"
141 " Otherwise, there may be no way to access the desired data or\n"
142 " metadata without taking ownership of the file or directory.\n"
145 static const wchar_t *apply_access_denied_msg =
146 L"If you are not running this program as the administrator, you may\n"
147 " need to do so, so that all data and metadata can be extracted\n"
148 " exactly as the origignal copy. However, if you do not care that\n"
149 " the security descriptors are extracted correctly, you could run\n"
150 " `wimlib-imagex apply' with the --no-acls flag instead.\n"
154 win32_open_existing_file(const wchar_t *path, DWORD dwDesiredAccess)
156 return CreateFileW(path,
159 NULL, /* lpSecurityAttributes */
161 FILE_FLAG_BACKUP_SEMANTICS |
162 FILE_FLAG_OPEN_REPARSE_POINT,
163 NULL /* hTemplateFile */);
167 win32_open_file_data_only(const wchar_t *path)
169 return win32_open_existing_file(path, FILE_READ_DATA);
173 read_win32_file_prefix(const struct wim_lookup_table_entry *lte,
175 consume_data_callback_t cb,
184 HANDLE hFile = win32_open_file_data_only(lte->file_on_disk);
185 if (hFile == INVALID_HANDLE_VALUE) {
186 err = GetLastError();
187 ERROR("Failed to open \"%ls\"", lte->file_on_disk);
189 return WIMLIB_ERR_OPEN;
193 out_buf = alloca(WIM_CHUNK_SIZE);
195 out_buf = ctx_or_buf;
197 bytes_remaining = size;
198 while (bytes_remaining) {
199 DWORD bytesToRead, bytesRead;
201 bytesToRead = min(WIM_CHUNK_SIZE, bytes_remaining);
202 if (!ReadFile(hFile, out_buf, bytesToRead, &bytesRead, NULL) ||
203 bytesRead != bytesToRead)
205 err = GetLastError();
206 ERROR("Failed to read data from \"%ls\"", lte->file_on_disk);
208 ret = WIMLIB_ERR_READ;
211 bytes_remaining -= bytesRead;
213 ret = (*cb)(out_buf, bytesRead, ctx_or_buf);
217 out_buf += bytesRead;
224 struct win32_encrypted_read_ctx {
225 consume_data_callback_t read_prefix_cb;
226 void *read_prefix_ctx_or_buf;
234 win32_encrypted_export_cb(unsigned char *_data, void *_ctx, unsigned long len)
236 const void *data = _data;
237 struct win32_encrypted_read_ctx *ctx = _ctx;
240 DEBUG("len = %lu", len);
241 if (ctx->read_prefix_cb) {
242 /* The length of the buffer passed to the ReadEncryptedFileRaw()
243 * export callback is undocumented, so we assume it may be of
245 size_t bytes_to_buffer = min(ctx->bytes_remaining - ctx->buf_filled,
247 while (bytes_to_buffer) {
248 size_t bytes_to_copy_to_buf =
249 min(bytes_to_buffer, WIM_CHUNK_SIZE - ctx->buf_filled);
251 memcpy(ctx->buf + ctx->buf_filled, data,
252 bytes_to_copy_to_buf);
253 ctx->buf_filled += bytes_to_copy_to_buf;
254 data += bytes_to_copy_to_buf;
255 bytes_to_buffer -= bytes_to_copy_to_buf;
257 if (ctx->buf_filled == WIM_CHUNK_SIZE ||
258 ctx->buf_filled == ctx->bytes_remaining)
260 ret = (*ctx->read_prefix_cb)(ctx->buf,
262 ctx->read_prefix_ctx_or_buf);
264 ctx->wimlib_err_code = ret;
265 /* Shouldn't matter what error code is returned
266 * here, as long as it isn't ERROR_SUCCESS. */
267 return ERROR_READ_FAULT;
269 ctx->bytes_remaining -= ctx->buf_filled;
274 size_t len_to_copy = min(len, ctx->bytes_remaining);
275 memcpy(ctx->read_prefix_ctx_or_buf, data, len_to_copy);
276 ctx->bytes_remaining -= len_to_copy;
277 ctx->read_prefix_ctx_or_buf += len_to_copy;
279 return ERROR_SUCCESS;
283 read_win32_encrypted_file_prefix(const struct wim_lookup_table_entry *lte,
285 consume_data_callback_t cb,
289 struct win32_encrypted_read_ctx export_ctx;
294 DEBUG("Reading %"PRIu64" bytes from encryted file \"%ls\"",
295 size, lte->file_on_disk);
297 export_ctx.read_prefix_cb = cb;
298 export_ctx.read_prefix_ctx_or_buf = ctx_or_buf;
299 export_ctx.wimlib_err_code = 0;
301 export_ctx.buf = MALLOC(WIM_CHUNK_SIZE);
303 return WIMLIB_ERR_NOMEM;
305 export_ctx.buf = NULL;
307 export_ctx.bytes_remaining = size;
309 err = OpenEncryptedFileRawW(lte->file_on_disk, 0, &file_ctx);
310 if (err != ERROR_SUCCESS) {
311 ERROR("Failed to open encrypted file \"%ls\" for raw read",
314 ret = WIMLIB_ERR_OPEN;
317 err = ReadEncryptedFileRaw(win32_encrypted_export_cb,
318 &export_ctx, file_ctx);
319 if (err != ERROR_SUCCESS) {
320 ERROR("Failed to read encrypted file \"%ls\"",
323 ret = export_ctx.wimlib_err_code;
325 ret = WIMLIB_ERR_READ;
326 } else if (export_ctx.bytes_remaining != 0) {
327 ERROR("Only could read %"PRIu64" of %"PRIu64" bytes from "
328 "encryted file \"%ls\"",
329 size - export_ctx.bytes_remaining, size,
331 ret = WIMLIB_ERR_READ;
335 CloseEncryptedFileRaw(file_ctx);
337 FREE(export_ctx.buf);
341 /* Given a path, which may not yet exist, get a set of flags that describe the
342 * features of the volume the path is on. */
344 win32_get_vol_flags(const wchar_t *path, unsigned *vol_flags_ret)
350 if (path[0] != L'\0' && path[0] != L'\\' &&
351 path[0] != L'/' && path[1] == L':')
353 /* Path starts with a drive letter; use it. */
354 volume = alloca(4 * sizeof(wchar_t));
360 /* Path does not start with a drive letter; use the volume of
361 * the current working directory. */
364 bret = GetVolumeInformationW(volume, /* lpRootPathName */
365 NULL, /* lpVolumeNameBuffer */
366 0, /* nVolumeNameSize */
367 NULL, /* lpVolumeSerialNumber */
368 NULL, /* lpMaximumComponentLength */
369 &vol_flags, /* lpFileSystemFlags */
370 NULL, /* lpFileSystemNameBuffer */
371 0); /* nFileSystemNameSize */
373 DWORD err = GetLastError();
374 WARNING("Failed to get volume information for path \"%ls\"", path);
376 vol_flags = 0xffffffff;
379 DEBUG("using vol_flags = %x", vol_flags);
380 *vol_flags_ret = vol_flags;
386 FILETIME_to_u64(const FILETIME *ft)
388 return ((u64)ft->dwHighDateTime << 32) | (u64)ft->dwLowDateTime;
392 win32_get_short_name(struct wim_dentry *dentry, const wchar_t *path)
394 WIN32_FIND_DATAW dat;
395 if (FindFirstFileW(path, &dat) && dat.cAlternateFileName[0] != L'\0') {
396 DEBUG("\"%ls\": short name \"%ls\"", path, dat.cAlternateFileName);
397 size_t short_name_nbytes = wcslen(dat.cAlternateFileName) *
399 size_t n = short_name_nbytes + sizeof(wchar_t);
400 dentry->short_name = MALLOC(n);
401 if (!dentry->short_name)
402 return WIMLIB_ERR_NOMEM;
403 memcpy(dentry->short_name, dat.cAlternateFileName, n);
404 dentry->short_name_nbytes = short_name_nbytes;
406 /* If we can't read the short filename for some reason, we just ignore
407 * the error and assume the file has no short name. I don't think this
408 * should be an issue, since the short names are essentially obsolete
414 win32_get_security_descriptor(struct wim_dentry *dentry,
415 struct sd_set *sd_set,
417 struct win32_capture_state *state,
420 SECURITY_INFORMATION requestedInformation;
426 requestedInformation = DACL_SECURITY_INFORMATION |
427 SACL_SECURITY_INFORMATION |
428 OWNER_SECURITY_INFORMATION |
429 GROUP_SECURITY_INFORMATION;
431 /* Request length of security descriptor */
432 status = GetFileSecurityW(path, requestedInformation,
433 NULL, 0, &lenNeeded);
434 err = GetLastError();
435 if (!status && err == ERROR_INSUFFICIENT_BUFFER) {
436 DWORD len = lenNeeded;
438 if (GetFileSecurityW(path, requestedInformation,
439 (PSECURITY_DESCRIPTOR)buf, len, &lenNeeded))
441 int security_id = sd_set_add_sd(sd_set, buf, len);
443 return WIMLIB_ERR_NOMEM;
445 dentry->d_inode->i_security_id = security_id;
449 err = GetLastError();
453 if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_STRICT_ACLS)
457 case ERROR_PRIVILEGE_NOT_HELD:
458 if (requestedInformation & SACL_SECURITY_INFORMATION) {
459 n = state->num_get_sacl_priv_notheld++;
460 requestedInformation &= ~SACL_SECURITY_INFORMATION;
461 if (n < MAX_GET_SACL_PRIV_NOTHELD_WARNINGS) {
463 "We don't have enough privileges to read the full security\n"
464 " descriptor of \"%ls\"!\n"
465 " Re-trying with SACL omitted.\n", path);
466 } else if (n == MAX_GET_SACL_PRIV_NOTHELD_WARNINGS) {
468 "Suppressing further privileges not held error messages when reading\n"
469 " security descriptors.");
474 case ERROR_ACCESS_DENIED:
475 n = state->num_get_sd_access_denied++;
476 if (n < MAX_GET_SD_ACCESS_DENIED_WARNINGS) {
477 WARNING("Failed to read security descriptor of \"%ls\": "
478 "Access denied!\n%ls", path, capture_access_denied_msg);
479 } else if (n == MAX_GET_SD_ACCESS_DENIED_WARNINGS) {
480 WARNING("Suppressing further access denied errors messages i"
481 "when reading security descriptors");
486 ERROR("Failed to read security descriptor of \"%ls\"", path);
488 return WIMLIB_ERR_READ;
493 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
495 size_t path_num_chars,
496 struct wim_lookup_table *lookup_table,
497 struct wim_inode_table *inode_table,
498 struct sd_set *sd_set,
499 const struct wimlib_capture_config *config,
501 wimlib_progress_func_t progress_func,
502 struct win32_capture_state *state,
505 /* Reads the directory entries of directory using a Win32 API and recursively
506 * calls win32_build_dentry_tree() on them. */
508 win32_recurse_directory(struct wim_dentry *root,
510 size_t dir_path_num_chars,
511 struct wim_lookup_table *lookup_table,
512 struct wim_inode_table *inode_table,
513 struct sd_set *sd_set,
514 const struct wimlib_capture_config *config,
516 wimlib_progress_func_t progress_func,
517 struct win32_capture_state *state,
520 WIN32_FIND_DATAW dat;
525 DEBUG("Recurse to directory \"%ls\"", dir_path);
527 /* Begin reading the directory by calling FindFirstFileW. Unlike UNIX
528 * opendir(), FindFirstFileW has file globbing built into it. But this
529 * isn't what we actually want, so just add a dummy glob to get all
531 dir_path[dir_path_num_chars] = L'/';
532 dir_path[dir_path_num_chars + 1] = L'*';
533 dir_path[dir_path_num_chars + 2] = L'\0';
534 hFind = FindFirstFileW(dir_path, &dat);
535 dir_path[dir_path_num_chars] = L'\0';
537 if (hFind == INVALID_HANDLE_VALUE) {
538 err = GetLastError();
539 if (err == ERROR_FILE_NOT_FOUND) {
542 ERROR("Failed to read directory \"%ls\"", dir_path);
544 return WIMLIB_ERR_READ;
549 /* Skip . and .. entries */
550 if (dat.cFileName[0] == L'.' &&
551 (dat.cFileName[1] == L'\0' ||
552 (dat.cFileName[1] == L'.' &&
553 dat.cFileName[2] == L'\0')))
555 size_t filename_len = wcslen(dat.cFileName);
557 dir_path[dir_path_num_chars] = L'/';
558 wmemcpy(dir_path + dir_path_num_chars + 1,
562 struct wim_dentry *child;
563 size_t path_len = dir_path_num_chars + 1 + filename_len;
564 ret = win32_build_dentry_tree_recursive(&child,
575 dir_path[dir_path_num_chars] = L'\0';
579 dentry_add_child(root, child);
580 } while (FindNextFileW(hFind, &dat));
581 err = GetLastError();
582 if (err != ERROR_NO_MORE_FILES) {
583 ERROR("Failed to read directory \"%ls\"", dir_path);
586 ret = WIMLIB_ERR_READ;
593 /* Load a reparse point into a WIM inode. It is just stored in memory.
595 * @hFile: Open handle to a reparse point, with permission to read the reparse
598 * @inode: WIM inode for the reparse point.
600 * @lookup_table: Stream lookup table for the WIM; an entry will be added to it
601 * for the reparse point unless an entry already exists for
602 * the exact same data stream.
604 * @path: External path to the reparse point. Used for error messages only.
606 * Returns 0 on success; nonzero on failure. */
608 win32_capture_reparse_point(HANDLE hFile,
609 struct wim_inode *inode,
610 struct wim_lookup_table *lookup_table,
613 DEBUG("Capturing reparse point \"%ls\"", path);
615 /* "Reparse point data, including the tag and optional GUID,
616 * cannot exceed 16 kilobytes." - MSDN */
617 char reparse_point_buf[16 * 1024];
620 if (!DeviceIoControl(hFile, FSCTL_GET_REPARSE_POINT,
621 NULL, /* "Not used with this operation; set to NULL" */
622 0, /* "Not used with this operation; set to 0" */
623 reparse_point_buf, /* "A pointer to a buffer that
624 receives the reparse point data */
625 sizeof(reparse_point_buf), /* "The size of the output
630 DWORD err = GetLastError();
631 ERROR("Failed to get reparse data of \"%ls\"", path);
633 return WIMLIB_ERR_READ;
635 if (bytesReturned < 8) {
636 ERROR("Reparse data on \"%ls\" is invalid", path);
637 return WIMLIB_ERR_READ;
639 inode->i_reparse_tag = le32_to_cpu(*(u32*)reparse_point_buf);
640 return inode_add_ads_with_data(inode, L"",
641 reparse_point_buf + 8,
642 bytesReturned - 8, lookup_table);
645 /* Scans an unnamed or named stream of a Win32 file (not a reparse point
646 * stream); calculates its SHA1 message digest and either creates a `struct
647 * wim_lookup_table_entry' in memory for it, or uses an existing 'struct
648 * wim_lookup_table_entry' for an identical stream.
650 * @path: Path to the file (UTF-16LE).
652 * @path_num_chars: Number of 2-byte characters in @path.
654 * @inode: WIM inode to save the stream into.
656 * @lookup_table: Stream lookup table for the WIM.
658 * @dat: A `WIN32_FIND_STREAM_DATA' structure that specifies the
661 * Returns 0 on success; nonzero on failure.
664 win32_capture_stream(const wchar_t *path,
665 size_t path_num_chars,
666 struct wim_inode *inode,
667 struct wim_lookup_table *lookup_table,
668 WIN32_FIND_STREAM_DATA *dat)
670 struct wim_ads_entry *ads_entry;
671 struct wim_lookup_table_entry *lte;
673 wchar_t *stream_name, *colon;
674 size_t stream_name_nchars;
675 bool is_named_stream;
678 size_t spath_buf_nbytes;
679 const wchar_t *relpath_prefix;
680 const wchar_t *colonchar;
682 DEBUG("Capture \"%ls\" stream \"%ls\"", path, dat->cStreamName);
684 /* The stream name should be returned as :NAME:TYPE */
685 stream_name = dat->cStreamName;
686 if (*stream_name != L':')
687 goto out_invalid_stream_name;
689 colon = wcschr(stream_name, L':');
691 goto out_invalid_stream_name;
693 if (wcscmp(colon + 1, L"$DATA")) {
694 /* Not a DATA stream */
701 stream_name_nchars = colon - stream_name;
702 is_named_stream = (stream_name_nchars != 0);
704 if (is_named_stream) {
705 /* Allocate an ADS entry for the named stream. */
706 ads_entry = inode_add_ads_utf16le(inode, stream_name,
707 stream_name_nchars * sizeof(wchar_t));
709 ret = WIMLIB_ERR_NOMEM;
714 /* Create a UTF-16LE string @spath that gives the filename, then a
715 * colon, then the stream name. Or, if it's an unnamed stream, just the
716 * filename. It is MALLOC()'ed so that it can be saved in the
717 * wim_lookup_table_entry if needed.
719 * As yet another special case, relative paths need to be changed to
720 * begin with an explicit "./" so that, for example, a file t:ads, where
721 * :ads is the part we added, is not interpreted as a file on the t:
723 spath_nchars = path_num_chars;
724 relpath_prefix = L"";
726 if (is_named_stream) {
727 spath_nchars += 1 + stream_name_nchars;
729 if (path_num_chars == 1 &&
734 relpath_prefix = L"./";
738 spath_buf_nbytes = (spath_nchars + 1) * sizeof(wchar_t);
739 spath = MALLOC(spath_buf_nbytes);
741 swprintf(spath, L"%ls%ls%ls%ls",
742 relpath_prefix, path, colonchar, stream_name);
744 /* Make a new wim_lookup_table_entry */
745 lte = new_lookup_table_entry();
747 ret = WIMLIB_ERR_NOMEM;
750 lte->file_on_disk = spath;
752 if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED && !is_named_stream)
753 lte->resource_location = RESOURCE_WIN32_ENCRYPTED;
755 lte->resource_location = RESOURCE_WIN32;
756 lte->resource_entry.original_size = (u64)dat->StreamSize.QuadPart;
759 if (is_named_stream) {
760 stream_id = ads_entry->stream_id;
761 ads_entry->lte = lte;
766 lookup_table_insert_unhashed(lookup_table, lte, inode, stream_id);
772 out_invalid_stream_name:
773 ERROR("Invalid stream name: \"%ls:%ls\"", path, dat->cStreamName);
774 ret = WIMLIB_ERR_READ;
778 /* Scans a Win32 file for unnamed and named data streams (not reparse point
781 * @path: Path to the file (UTF-16LE).
783 * @path_num_chars: Number of 2-byte characters in @path.
785 * @inode: WIM inode to save the stream into.
787 * @lookup_table: Stream lookup table for the WIM.
789 * @file_size: Size of unnamed data stream. (Used only if alternate
790 * data streams API appears to be unavailable.)
792 * @vol_flags: Flags that specify features of the volume being
795 * Returns 0 on success; nonzero on failure.
798 win32_capture_streams(const wchar_t *path,
799 size_t path_num_chars,
800 struct wim_inode *inode,
801 struct wim_lookup_table *lookup_table,
805 WIN32_FIND_STREAM_DATA dat;
810 DEBUG("Capturing streams from \"%ls\"", path);
812 if (win32func_FindFirstStreamW == NULL ||
813 !(vol_flags & FILE_NAMED_STREAMS))
816 hFind = win32func_FindFirstStreamW(path, FindStreamInfoStandard, &dat, 0);
817 if (hFind == INVALID_HANDLE_VALUE) {
818 err = GetLastError();
819 if (err == ERROR_CALL_NOT_IMPLEMENTED)
822 /* Seems legal for this to return ERROR_HANDLE_EOF on reparse
823 * points and directories */
824 if ((inode->i_attributes &
825 (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
826 && err == ERROR_HANDLE_EOF)
828 DEBUG("ERROR_HANDLE_EOF (ok)");
831 if (err == ERROR_ACCESS_DENIED) {
832 ERROR("Failed to look up data streams "
833 "of \"%ls\": Access denied!\n%ls",
834 path, capture_access_denied_msg);
835 return WIMLIB_ERR_READ;
837 ERROR("Failed to look up data streams "
840 return WIMLIB_ERR_READ;
845 ret = win32_capture_stream(path,
851 } while (win32func_FindNextStreamW(hFind, &dat));
852 err = GetLastError();
853 if (err != ERROR_HANDLE_EOF) {
854 ERROR("Win32 API: Error reading data streams from \"%ls\"", path);
856 ret = WIMLIB_ERR_READ;
862 /* FindFirstStreamW() API is not available, or the volume does not
863 * support named streams. Only capture the unnamed data stream. */
864 DEBUG("Only capturing unnamed data stream");
865 if (inode->i_attributes &
866 (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
870 /* Just create our own WIN32_FIND_STREAM_DATA for an unnamed
871 * stream to reduce the code to a call to the
872 * already-implemented win32_capture_stream() */
873 wcscpy(dat.cStreamName, L"::$DATA");
874 dat.StreamSize.QuadPart = file_size;
875 ret = win32_capture_stream(path,
884 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
886 size_t path_num_chars,
887 struct wim_lookup_table *lookup_table,
888 struct wim_inode_table *inode_table,
889 struct sd_set *sd_set,
890 const struct wimlib_capture_config *config,
892 wimlib_progress_func_t progress_func,
893 struct win32_capture_state *state,
896 struct wim_dentry *root = NULL;
897 struct wim_inode *inode;
902 if (exclude_path(path, path_num_chars, config, true)) {
903 if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT) {
904 ERROR("Cannot exclude the root directory from capture");
905 ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
908 if ((add_image_flags & WIMLIB_ADD_IMAGE_FLAG_EXCLUDE_VERBOSE)
911 union wimlib_progress_info info;
912 info.scan.cur_path = path;
913 info.scan.excluded = true;
914 progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
919 if ((add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
922 union wimlib_progress_info info;
923 info.scan.cur_path = path;
924 info.scan.excluded = false;
925 progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
928 HANDLE hFile = win32_open_existing_file(path,
929 FILE_READ_DATA | FILE_READ_ATTRIBUTES);
930 if (hFile == INVALID_HANDLE_VALUE) {
931 err = GetLastError();
932 ERROR("Win32 API: Failed to open \"%ls\"", path);
934 ret = WIMLIB_ERR_OPEN;
938 BY_HANDLE_FILE_INFORMATION file_info;
939 if (!GetFileInformationByHandle(hFile, &file_info)) {
940 err = GetLastError();
941 ERROR("Win32 API: Failed to get file information for \"%ls\"",
944 ret = WIMLIB_ERR_STAT;
945 goto out_close_handle;
948 /* Create a WIM dentry with an associated inode, which may be shared */
949 ret = inode_table_new_dentry(inode_table,
950 path_basename_with_len(path, path_num_chars),
951 ((u64)file_info.nFileIndexHigh << 32) |
952 (u64)file_info.nFileIndexLow,
953 file_info.dwVolumeSerialNumber,
956 goto out_close_handle;
958 ret = win32_get_short_name(root, path);
960 goto out_close_handle;
962 inode = root->d_inode;
964 if (inode->i_nlink > 1) /* Shared inode; nothing more to do */
965 goto out_close_handle;
967 inode->i_attributes = file_info.dwFileAttributes;
968 inode->i_creation_time = FILETIME_to_u64(&file_info.ftCreationTime);
969 inode->i_last_write_time = FILETIME_to_u64(&file_info.ftLastWriteTime);
970 inode->i_last_access_time = FILETIME_to_u64(&file_info.ftLastAccessTime);
971 inode->i_resolved = 1;
973 add_image_flags &= ~(WIMLIB_ADD_IMAGE_FLAG_ROOT | WIMLIB_ADD_IMAGE_FLAG_SOURCE);
975 if (!(add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NO_ACLS)
976 && (vol_flags & FILE_PERSISTENT_ACLS))
978 ret = win32_get_security_descriptor(root, sd_set, path, state,
981 goto out_close_handle;
984 file_size = ((u64)file_info.nFileSizeHigh << 32) |
985 (u64)file_info.nFileSizeLow;
987 if (inode_is_directory(inode)) {
988 /* Directory (not a reparse point) --- recurse to children */
990 /* But first... directories may have alternate data streams that
991 * need to be captured. */
992 ret = win32_capture_streams(path,
999 goto out_close_handle;
1000 ret = win32_recurse_directory(root,
1011 } else if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1012 /* Reparse point: save the reparse tag and data. Alternate data
1013 * streams are not captured, if it's even possible for a reparse
1014 * point to have alternate data streams... */
1015 ret = win32_capture_reparse_point(hFile,
1020 /* Not a directory, not a reparse point; capture the default
1021 * file contents and any alternate data streams. */
1022 ret = win32_capture_streams(path,
1035 free_dentry_tree(root, lookup_table);
1040 win32_do_capture_warnings(const struct win32_capture_state *state,
1041 int add_image_flags)
1043 if (state->num_get_sacl_priv_notheld == 0 &&
1044 state->num_get_sd_access_denied == 0)
1048 WARNING("Built dentry tree successfully, but with the following problem(s):");
1049 if (state->num_get_sacl_priv_notheld != 0) {
1050 WARNING("Could not capture SACL (System Access Control List)\n"
1051 " on %lu files or directories.",
1052 state->num_get_sacl_priv_notheld);
1054 if (state->num_get_sd_access_denied != 0) {
1055 WARNING("Could not capture security descriptor at all\n"
1056 " on %lu files or directories.",
1057 state->num_get_sd_access_denied);
1060 "Try running the program as the Administrator to make sure all the\n"
1061 " desired metadata has been captured exactly. However, if you\n"
1062 " do not care about capturing security descriptors correctly, then\n"
1063 " nothing more needs to be done%ls\n",
1064 (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NO_ACLS) ? L"." :
1065 L", although you might consider\n"
1066 " passing the --no-acls flag to `wimlib-imagex capture' or\n"
1067 " `wimlib-imagex append' to explicitly capture no security\n"
1071 /* Win32 version of capturing a directory tree */
1073 win32_build_dentry_tree(struct wim_dentry **root_ret,
1074 const wchar_t *root_disk_path,
1075 struct wim_lookup_table *lookup_table,
1076 struct wim_inode_table *inode_table,
1077 struct sd_set *sd_set,
1078 const struct wimlib_capture_config *config,
1079 int add_image_flags,
1080 wimlib_progress_func_t progress_func,
1086 struct win32_capture_state state;
1089 path_nchars = wcslen(root_disk_path);
1090 if (path_nchars > 32767)
1091 return WIMLIB_ERR_INVALID_PARAM;
1093 win32_get_vol_flags(root_disk_path, &vol_flags);
1095 /* There is no check for overflow later when this buffer is being used!
1096 * But the max path length on NTFS is 32767 characters, and paths need
1097 * to be written specially to even go past 260 characters, so we should
1098 * be okay with 32770 characters. */
1099 path = MALLOC(32770 * sizeof(wchar_t));
1101 return WIMLIB_ERR_NOMEM;
1103 wmemcpy(path, root_disk_path, path_nchars + 1);
1105 memset(&state, 0, sizeof(state));
1106 ret = win32_build_dentry_tree_recursive(root_ret,
1119 win32_do_capture_warnings(&state, add_image_flags);
1124 win32_set_reparse_data(HANDLE h,
1126 const struct wim_lookup_table_entry *lte,
1127 const wchar_t *path)
1134 WARNING("\"%ls\" is marked as a reparse point but had no reparse data",
1138 len = wim_resource_size(lte);
1139 if (len > 16 * 1024 - 8) {
1140 WARNING("\"%ls\": reparse data too long!", path);
1144 /* The WIM stream omits the ReparseTag and ReparseDataLength fields, so
1145 * leave 8 bytes of space for them at the beginning of the buffer, then
1146 * set them manually. */
1147 buf = alloca(len + 8);
1148 ret = read_full_resource_into_buf(lte, buf + 8, false);
1151 *(u32*)(buf + 0) = cpu_to_le32(reparse_tag);
1152 *(u16*)(buf + 4) = cpu_to_le16(len);
1153 *(u16*)(buf + 6) = 0;
1155 /* Set the reparse data on the open file using the
1156 * FSCTL_SET_REPARSE_POINT ioctl.
1158 * There are contradictions in Microsoft's documentation for this:
1160 * "If hDevice was opened without specifying FILE_FLAG_OVERLAPPED,
1161 * lpOverlapped is ignored."
1163 * --- So setting lpOverlapped to NULL is okay since it's ignored.
1165 * "If lpOverlapped is NULL, lpBytesReturned cannot be NULL. Even when an
1166 * operation returns no output data and lpOutBuffer is NULL,
1167 * DeviceIoControl makes use of lpBytesReturned. After such an
1168 * operation, the value of lpBytesReturned is meaningless."
1170 * --- So lpOverlapped not really ignored, as it affects another
1171 * parameter. This is the actual behavior: lpBytesReturned must be
1172 * specified, even though lpBytesReturned is documented as:
1174 * "Not used with this operation; set to NULL."
1176 DWORD bytesReturned;
1177 if (!DeviceIoControl(h, FSCTL_SET_REPARSE_POINT, buf, len + 8,
1179 &bytesReturned /* lpBytesReturned */,
1180 NULL /* lpOverlapped */))
1182 DWORD err = GetLastError();
1183 ERROR("Failed to set reparse data on \"%ls\"", path);
1185 return WIMLIB_ERR_WRITE;
1191 win32_set_compressed(HANDLE hFile, const wchar_t *path)
1193 USHORT format = COMPRESSION_FORMAT_DEFAULT;
1194 DWORD bytesReturned = 0;
1195 if (!DeviceIoControl(hFile, FSCTL_SET_COMPRESSION,
1196 &format, sizeof(USHORT),
1198 &bytesReturned, NULL))
1200 /* Could be a warning only, but we only call this if the volume
1201 * supports compression. So I'm calling this an error. */
1202 DWORD err = GetLastError();
1203 ERROR("Failed to set compression flag on \"%ls\"", path);
1205 return WIMLIB_ERR_WRITE;
1211 win32_set_sparse(HANDLE hFile, const wchar_t *path)
1213 DWORD bytesReturned = 0;
1214 if (!DeviceIoControl(hFile, FSCTL_SET_SPARSE,
1217 &bytesReturned, NULL))
1219 /* Could be a warning only, but we only call this if the volume
1220 * supports sparse files. So I'm calling this an error. */
1221 DWORD err = GetLastError();
1222 WARNING("Failed to set sparse flag on \"%ls\"", path);
1224 return WIMLIB_ERR_WRITE;
1230 * Sets the security descriptor on an extracted file.
1233 win32_set_security_data(const struct wim_inode *inode,
1234 const wchar_t *path,
1235 struct apply_args *args)
1237 PSECURITY_DESCRIPTOR descriptor;
1241 descriptor = wim_const_security_data(args->w)->descriptors[inode->i_security_id];
1243 SECURITY_INFORMATION securityInformation = DACL_SECURITY_INFORMATION |
1244 SACL_SECURITY_INFORMATION |
1245 OWNER_SECURITY_INFORMATION |
1246 GROUP_SECURITY_INFORMATION;
1248 if (SetFileSecurityW(path, securityInformation, descriptor))
1250 err = GetLastError();
1251 if (args->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS)
1254 case ERROR_PRIVILEGE_NOT_HELD:
1255 if (securityInformation & SACL_SECURITY_INFORMATION) {
1256 n = args->num_set_sacl_priv_notheld++;
1257 securityInformation &= ~SACL_SECURITY_INFORMATION;
1258 if (n < MAX_SET_SACL_PRIV_NOTHELD_WARNINGS) {
1260 "We don't have enough privileges to set the full security\n"
1261 " descriptor on \"%ls\"!\n", path);
1262 if (args->num_set_sd_access_denied +
1263 args->num_set_sacl_priv_notheld == 1)
1265 WARNING("%ls", apply_access_denied_msg);
1267 WARNING("Re-trying with SACL omitted.\n", path);
1268 } else if (n == MAX_GET_SACL_PRIV_NOTHELD_WARNINGS) {
1270 "Suppressing further 'privileges not held' error messages when setting\n"
1271 " security descriptors.");
1276 case ERROR_INVALID_OWNER:
1277 case ERROR_ACCESS_DENIED:
1278 n = args->num_set_sd_access_denied++;
1279 if (n < MAX_SET_SD_ACCESS_DENIED_WARNINGS) {
1280 WARNING("Failed to set security descriptor on \"%ls\": "
1281 "Access denied!\n", path);
1282 if (args->num_set_sd_access_denied +
1283 args->num_set_sacl_priv_notheld == 1)
1285 WARNING("%ls", apply_access_denied_msg);
1287 } else if (n == MAX_SET_SD_ACCESS_DENIED_WARNINGS) {
1289 "Suppressing further access denied error messages when setting\n"
1290 " security descriptors");
1295 ERROR("Failed to set security descriptor on \"%ls\"", path);
1297 return WIMLIB_ERR_WRITE;
1303 win32_extract_chunk(const void *buf, size_t len, void *arg)
1305 HANDLE hStream = arg;
1307 DWORD nbytes_written;
1308 wimlib_assert(len <= 0xffffffff);
1310 if (!WriteFile(hStream, buf, len, &nbytes_written, NULL) ||
1311 nbytes_written != len)
1313 DWORD err = GetLastError();
1314 ERROR("WriteFile(): write error");
1316 return WIMLIB_ERR_WRITE;
1322 do_win32_extract_stream(HANDLE hStream, struct wim_lookup_table_entry *lte)
1324 return extract_wim_resource(lte, wim_resource_size(lte),
1325 win32_extract_chunk, hStream);
1329 do_win32_extract_encrypted_stream(const wchar_t *path,
1330 const struct wim_lookup_table_entry *lte)
1332 ERROR("Extrat encryted streams not implemented");
1333 return WIMLIB_ERR_INVALID_PARAM;
1337 path_is_root_of_drive(const wchar_t *path)
1342 if (*path != L'/' && *path != L'\\') {
1343 if (*(path + 1) == L':')
1348 while (*path == L'/' || *path == L'\\')
1350 return (*path == L'\0');
1354 win32_get_create_flags_and_attributes(DWORD i_attributes)
1359 * Some attributes cannot be set by passing them to CreateFile(). In
1362 * FILE_ATTRIBUTE_DIRECTORY:
1363 * CreateDirectory() must be called instead of CreateFile().
1365 * FILE_ATTRIBUTE_SPARSE_FILE:
1367 * See: win32_set_sparse().
1369 * FILE_ATTRIBUTE_COMPRESSED:
1370 * Not clear from the documentation, but apparently this needs an
1372 * See: win32_set_compressed().
1374 * FILE_ATTRIBUTE_REPARSE_POINT:
1375 * Needs an ioctl, with the reparse data specified.
1376 * See: win32_set_reparse_data().
1378 * In addition, clear any file flags in the attributes that we don't
1379 * want, but also specify FILE_FLAG_OPEN_REPARSE_POINT and
1380 * FILE_FLAG_BACKUP_SEMANTICS as we are a backup application.
1382 attributes = i_attributes & ~(FILE_ATTRIBUTE_SPARSE_FILE |
1383 FILE_ATTRIBUTE_COMPRESSED |
1384 FILE_ATTRIBUTE_REPARSE_POINT |
1385 FILE_ATTRIBUTE_DIRECTORY |
1386 FILE_FLAG_DELETE_ON_CLOSE |
1387 FILE_FLAG_NO_BUFFERING |
1388 FILE_FLAG_OPEN_NO_RECALL |
1389 FILE_FLAG_OVERLAPPED |
1390 FILE_FLAG_RANDOM_ACCESS |
1391 /*FILE_FLAG_SESSION_AWARE |*/
1392 FILE_FLAG_SEQUENTIAL_SCAN |
1393 FILE_FLAG_WRITE_THROUGH);
1395 FILE_FLAG_OPEN_REPARSE_POINT |
1396 FILE_FLAG_BACKUP_SEMANTICS;
1400 inode_has_special_attributes(const struct wim_inode *inode)
1402 return (inode->i_attributes & (FILE_ATTRIBUTE_COMPRESSED |
1403 FILE_ATTRIBUTE_REPARSE_POINT |
1404 FILE_ATTRIBUTE_SPARSE_FILE)) != 0;
1407 /* Set compression or sparse attributes, and reparse data, if supported by the
1410 win32_set_special_attributes(HANDLE hFile, const struct wim_inode *inode,
1411 struct wim_lookup_table_entry *unnamed_stream_lte,
1412 const wchar_t *path, unsigned vol_flags)
1416 if (inode->i_attributes & FILE_ATTRIBUTE_COMPRESSED) {
1417 if (vol_flags & FILE_FILE_COMPRESSION) {
1418 DEBUG("Setting compression flag on \"%ls\"", path);
1419 ret = win32_set_compressed(hFile, path);
1423 DEBUG("Cannot set compression attribute on \"%ls\": "
1424 "volume does not support transparent compression",
1429 if (inode->i_attributes & FILE_ATTRIBUTE_SPARSE_FILE) {
1430 if (vol_flags & FILE_SUPPORTS_SPARSE_FILES) {
1431 DEBUG("Setting sparse flag on \"%ls\"", path);
1432 ret = win32_set_sparse(hFile, path);
1436 DEBUG("Cannot set sparse attribute on \"%ls\": "
1437 "volume does not support sparse files",
1442 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1443 if (vol_flags & FILE_SUPPORTS_REPARSE_POINTS) {
1444 DEBUG("Setting reparse data on \"%ls\"", path);
1445 ret = win32_set_reparse_data(hFile, inode->i_reparse_tag,
1446 unnamed_stream_lte, path);
1450 DEBUG("Cannot set reparse data on \"%ls\": volume "
1451 "does not support reparse points", path);
1459 win32_extract_stream(const struct wim_inode *inode,
1460 const wchar_t *path,
1461 const wchar_t *stream_name_utf16,
1462 struct wim_lookup_table_entry *lte,
1465 wchar_t *stream_path;
1469 DWORD creationDisposition = CREATE_ALWAYS;
1471 if (stream_name_utf16) {
1472 /* Named stream. Create a buffer that contains the UTF-16LE
1473 * string [.\]@path:@stream_name_utf16. This is needed to
1474 * create and open the stream using CreateFileW(). I'm not
1475 * aware of any other APIs to do this. Note: the '$DATA' suffix
1476 * seems to be unneeded. Additional note: a "./" prefix needs
1477 * to be added when the path is not absolute to avoid ambiguity
1478 * with drive letters. */
1479 size_t stream_path_nchars;
1481 size_t stream_name_nchars;
1482 const wchar_t *prefix;
1484 path_nchars = wcslen(path);
1485 stream_name_nchars = wcslen(stream_name_utf16);
1486 stream_path_nchars = path_nchars + 1 + stream_name_nchars;
1487 if (path[0] != cpu_to_le16(L'\0') &&
1488 path[0] != cpu_to_le16(L'/') &&
1489 path[0] != cpu_to_le16(L'\\') &&
1490 path[1] != cpu_to_le16(L':'))
1493 stream_path_nchars += 2;
1497 stream_path = alloca((stream_path_nchars + 1) * sizeof(wchar_t));
1498 swprintf(stream_path, L"%ls%ls:%ls",
1499 prefix, path, stream_name_utf16);
1501 /* Unnamed stream; its path is just the path to the file itself.
1503 stream_path = (wchar_t*)path;
1505 /* Directories must be created with CreateDirectoryW(). Then
1506 * the call to CreateFileW() will merely open the directory that
1507 * was already created rather than creating a new file. */
1508 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1509 if (!CreateDirectoryW(stream_path, NULL)) {
1510 err = GetLastError();
1512 case ERROR_ALREADY_EXISTS:
1514 case ERROR_ACCESS_DENIED:
1515 if (path_is_root_of_drive(path))
1519 ERROR("Failed to create directory \"%ls\"",
1522 ret = WIMLIB_ERR_MKDIR;
1526 DEBUG("Created directory \"%ls\"", stream_path);
1527 if (!inode_has_special_attributes(inode)) {
1531 DEBUG("Directory \"%ls\" has special attributes!",
1533 creationDisposition = OPEN_EXISTING;
1537 DEBUG("Opening \"%ls\"", stream_path);
1538 h = CreateFileW(stream_path,
1539 GENERIC_READ | GENERIC_WRITE,
1542 creationDisposition,
1543 win32_get_create_flags_and_attributes(inode->i_attributes),
1545 if (h == INVALID_HANDLE_VALUE) {
1546 err = GetLastError();
1547 ERROR("Failed to create \"%ls\"", stream_path);
1549 ret = WIMLIB_ERR_OPEN;
1553 if (stream_name_utf16 == NULL && inode_has_special_attributes(inode)) {
1554 ret = win32_set_special_attributes(h, inode, lte, path,
1557 goto fail_close_handle;
1560 if (!(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
1562 DEBUG("Extracting \"%ls\" (len = %"PRIu64")",
1563 stream_path, wim_resource_size(lte));
1564 if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED
1565 && stream_name_utf16 == NULL
1566 && (vol_flags & FILE_SUPPORTS_ENCRYPTION))
1568 ret = do_win32_extract_encrypted_stream(stream_path,
1571 ret = do_win32_extract_stream(h, lte);
1574 goto fail_close_handle;
1578 DEBUG("Closing \"%ls\"", stream_path);
1579 if (!CloseHandle(h)) {
1580 err = GetLastError();
1581 ERROR("Failed to close \"%ls\"", stream_path);
1583 ret = WIMLIB_ERR_WRITE;
1591 ERROR("Error extracting %ls", stream_path);
1597 * Creates a file, directory, or reparse point and extracts all streams to it
1598 * (unnamed data stream and/or reparse point stream, plus any alternate data
1599 * streams). This in Win32-specific code.
1601 * @inode: WIM inode for this file or directory.
1602 * @path: UTF-16LE external path to extract the inode to.
1604 * Returns 0 on success; nonzero on failure.
1607 win32_extract_streams(const struct wim_inode *inode,
1608 const wchar_t *path, u64 *completed_bytes_p,
1611 struct wim_lookup_table_entry *unnamed_lte;
1614 unnamed_lte = inode_unnamed_lte_resolved(inode);
1615 ret = win32_extract_stream(inode, path, NULL, unnamed_lte,
1620 *completed_bytes_p += wim_resource_size(unnamed_lte);
1622 if (!(vol_flags & FILE_NAMED_STREAMS))
1624 for (u16 i = 0; i < inode->i_num_ads; i++) {
1625 const struct wim_ads_entry *ads_entry = &inode->i_ads_entries[i];
1626 if (ads_entry->stream_name_nbytes != 0) {
1627 /* Skip special UNIX data entries (see documentation for
1628 * WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA) */
1629 if (ads_entry->stream_name_nbytes == WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES
1630 && !memcmp(ads_entry->stream_name,
1631 WIMLIB_UNIX_DATA_TAG_UTF16LE,
1632 WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES))
1634 ret = win32_extract_stream(inode,
1636 ads_entry->stream_name,
1642 *completed_bytes_p += wim_resource_size(ads_entry->lte);
1649 /* Extract a file, directory, reparse point, or hard link to an
1650 * already-extracted file using the Win32 API */
1652 win32_do_apply_dentry(const wchar_t *output_path,
1653 size_t output_path_num_chars,
1654 struct wim_dentry *dentry,
1655 struct apply_args *args)
1658 struct wim_inode *inode = dentry->d_inode;
1661 if (!args->have_vol_flags) {
1662 win32_get_vol_flags(output_path, &args->vol_flags);
1663 args->have_vol_flags = true;
1664 /* Warn the user about data that may not be extracted. */
1665 if (!(args->vol_flags & FILE_SUPPORTS_SPARSE_FILES))
1666 WARNING("Volume does not support sparse files!\n"
1667 " Sparse files will be extracted as non-sparse.");
1668 if (!(args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS))
1669 WARNING("Volume does not support reparse points!\n"
1670 " Reparse point data will not be extracted.");
1671 if (!(args->vol_flags & FILE_NAMED_STREAMS)) {
1672 WARNING("Volume does not support named data streams!\n"
1673 " Named data streams will not be extracted.");
1675 if (!(args->vol_flags & FILE_SUPPORTS_ENCRYPTION)) {
1676 WARNING("Volume does not support encryption!\n"
1677 " Encrypted files will be extracted as raw data.");
1679 if (!(args->vol_flags & FILE_FILE_COMPRESSION)) {
1680 WARNING("Volume does not support transparent compression!\n"
1681 " Compressed files will be extracted as non-compressed.");
1683 if (!(args->vol_flags & FILE_PERSISTENT_ACLS)) {
1684 if (args->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS) {
1685 ERROR("Strict ACLs requested, but the volume does not "
1687 return WIMLIB_ERR_VOLUME_LACKS_FEATURES;
1689 WARNING("Volume does not support persistent ACLS!\n"
1690 " File permissions will not be extracted.");
1695 if (inode->i_nlink > 1 && inode->i_extracted_file != NULL) {
1696 /* Linked file, with another name already extracted. Create a
1699 /* There is a volume flag for this (FILE_SUPPORTS_HARD_LINKS),
1700 * but it's only available on Windows 7 and later. So no use
1701 * even checking it, really. Instead, CreateHardLinkW() will
1702 * apparently return ERROR_INVALID_FUNCTION if the volume does
1703 * not support hard links. */
1704 DEBUG("Creating hard link \"%ls => %ls\"",
1705 output_path, inode->i_extracted_file);
1706 if (CreateHardLinkW(output_path, inode->i_extracted_file, NULL))
1709 err = GetLastError();
1710 if (err != ERROR_INVALID_FUNCTION) {
1711 ERROR("Can't create hard link \"%ls => %ls\"",
1712 output_path, inode->i_extracted_file);
1714 return WIMLIB_ERR_LINK;
1716 WARNING("Can't create hard link \"%ls => %ls\":\n"
1717 " Volume does not support hard links!\n"
1718 " Falling back to extracting a copy of the file.");
1721 /* Create the file, directory, or reparse point, and extract the
1723 ret = win32_extract_streams(inode, output_path,
1724 &args->progress.extract.completed_bytes,
1729 if (inode->i_security_id >= 0 &&
1730 !(args->extract_flags & WIMLIB_EXTRACT_FLAG_NO_ACLS)
1731 && (args->vol_flags & FILE_PERSISTENT_ACLS))
1733 ret = win32_set_security_data(inode, output_path, args);
1737 if (inode->i_nlink > 1) {
1738 /* Save extracted path for a later call to
1739 * CreateHardLinkW() if this inode has multiple links.
1741 inode->i_extracted_file = WSTRDUP(output_path);
1742 if (!inode->i_extracted_file)
1743 ret = WIMLIB_ERR_NOMEM;
1748 /* Set timestamps on an extracted file using the Win32 API */
1750 win32_do_apply_dentry_timestamps(const wchar_t *path,
1751 size_t path_num_chars,
1752 const struct wim_dentry *dentry,
1753 const struct apply_args *args)
1757 const struct wim_inode *inode = dentry->d_inode;
1759 DEBUG("Opening \"%ls\" to set timestamps", path);
1760 h = win32_open_existing_file(path, FILE_WRITE_ATTRIBUTES);
1761 if (h == INVALID_HANDLE_VALUE) {
1762 err = GetLastError();
1766 FILETIME creationTime = {.dwLowDateTime = inode->i_creation_time & 0xffffffff,
1767 .dwHighDateTime = inode->i_creation_time >> 32};
1768 FILETIME lastAccessTime = {.dwLowDateTime = inode->i_last_access_time & 0xffffffff,
1769 .dwHighDateTime = inode->i_last_access_time >> 32};
1770 FILETIME lastWriteTime = {.dwLowDateTime = inode->i_last_write_time & 0xffffffff,
1771 .dwHighDateTime = inode->i_last_write_time >> 32};
1773 DEBUG("Calling SetFileTime() on \"%ls\"", path);
1774 if (!SetFileTime(h, &creationTime, &lastAccessTime, &lastWriteTime)) {
1775 err = GetLastError();
1779 DEBUG("Closing \"%ls\"", path);
1780 if (!CloseHandle(h)) {
1781 err = GetLastError();
1786 /* Only warn if setting timestamps failed; still return 0. */
1787 WARNING("Can't set timestamps on \"%ls\"", path);
1793 /* Replacement for POSIX fsync() */
1800 h = (HANDLE)_get_osfhandle(fd);
1801 if (h == INVALID_HANDLE_VALUE) {
1802 err = GetLastError();
1803 ERROR("Could not get Windows handle for file descriptor");
1808 if (!FlushFileBuffers(h)) {
1809 err = GetLastError();
1810 ERROR("Could not flush file buffers to disk");
1818 /* Use the Win32 API to get the number of processors */
1820 win32_get_number_of_processors()
1822 SYSTEM_INFO sysinfo;
1823 GetSystemInfo(&sysinfo);
1824 return sysinfo.dwNumberOfProcessors;
1827 /* Replacement for POSIX-2008 realpath(). Warning: partial functionality only
1828 * (resolved_path must be NULL). Also I highly doubt that GetFullPathName
1829 * really does the right thing under all circumstances. */
1831 realpath(const wchar_t *path, wchar_t *resolved_path)
1834 wimlib_assert(resolved_path == NULL);
1837 ret = GetFullPathNameW(path, 0, NULL, NULL);
1839 err = GetLastError();
1843 resolved_path = TMALLOC(ret);
1846 ret = GetFullPathNameW(path, ret, resolved_path, NULL);
1848 err = GetLastError();
1849 free(resolved_path);
1850 resolved_path = NULL;
1858 return resolved_path;
1861 /* rename() on Windows fails if the destination file exists. And we need to
1862 * make it work on wide characters. Fix it. */
1864 win32_rename_replacement(const wchar_t *oldpath, const wchar_t *newpath)
1866 if (MoveFileExW(oldpath, newpath, MOVEFILE_REPLACE_EXISTING)) {
1869 /* As usual, the possible error values are not documented */
1870 DWORD err = GetLastError();
1871 ERROR("MoveFileEx(): Can't rename \"%ls\" to \"%ls\"",
1879 /* Replacement for POSIX fnmatch() (partial functionality only) */
1881 fnmatch(const wchar_t *pattern, const wchar_t *string, int flags)
1883 if (PathMatchSpecW(string, pattern))
1889 /* truncate() replacement */
1891 win32_truncate_replacement(const wchar_t *path, off_t size)
1893 DWORD err = NO_ERROR;
1894 LARGE_INTEGER liOffset;
1896 HANDLE h = win32_open_existing_file(path, GENERIC_WRITE);
1897 if (h == INVALID_HANDLE_VALUE)
1900 liOffset.QuadPart = size;
1901 if (!SetFilePointerEx(h, liOffset, NULL, FILE_BEGIN))
1902 goto fail_close_handle;
1904 if (!SetEndOfFile(h))
1905 goto fail_close_handle;
1910 err = GetLastError();
1913 if (err == NO_ERROR)
1914 err = GetLastError();
1915 ERROR("Can't truncate \"%ls\" to %"PRIu64" bytes", path, size);
1922 /* This really could be replaced with _wcserror_s, but this doesn't seem to
1923 * actually be available in MSVCRT.DLL on Windows XP (perhaps it's statically
1924 * linked in by Visual Studio...?). */
1926 win32_strerror_r_replacement(int errnum, wchar_t *buf, size_t buflen)
1928 static pthread_mutex_t strerror_lock = PTHREAD_MUTEX_INITIALIZER;
1930 pthread_mutex_lock(&strerror_lock);
1931 mbstowcs(buf, strerror(errnum), buflen);
1932 buf[buflen - 1] = '\0';
1933 pthread_mutex_unlock(&strerror_lock);
1937 #endif /* __WIN32__ */