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 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 ret = WIMLIB_ERR_OPEN;
194 out_buf = alloca(WIM_CHUNK_SIZE);
196 out_buf = ctx_or_buf;
198 bytes_remaining = size;
199 while (bytes_remaining) {
200 DWORD bytesToRead, bytesRead;
202 bytesToRead = min(WIM_CHUNK_SIZE, bytes_remaining);
203 if (!ReadFile(h, out_buf, bytesToRead, &bytesRead, NULL) ||
204 bytesRead != bytesToRead)
206 err = GetLastError();
207 ERROR("Failed to read data from \"%ls\"", lte->file_on_disk);
209 ret = WIMLIB_ERR_READ;
210 goto out_close_handle;
212 bytes_remaining -= bytesRead;
214 ret = cb(out_buf, bytesRead, ctx_or_buf);
216 goto out_close_handle;
218 out_buf += bytesRead;
228 FILETIME_to_u64(const FILETIME *ft)
230 return ((u64)ft->dwHighDateTime << 32) | (u64)ft->dwLowDateTime;
234 win32_get_short_name(struct wim_dentry *dentry, const wchar_t *path)
236 WIN32_FIND_DATAW dat;
237 if (FindFirstFileW(path, &dat) && dat.cAlternateFileName[0] != L'\0') {
238 size_t short_name_nbytes = wcslen(dat.cAlternateFileName) *
240 size_t n = short_name_nbytes + sizeof(wchar_t);
241 dentry->short_name = MALLOC(n);
242 if (!dentry->short_name)
243 return WIMLIB_ERR_NOMEM;
244 memcpy(dentry->short_name, dat.cAlternateFileName, n);
245 dentry->short_name_nbytes = short_name_nbytes;
247 /* If we can't read the short filename for some reason, we just ignore
248 * the error and assume the file has no short name. I don't think this
249 * should be an issue, since the short names are essentially obsolete
255 win32_get_security_descriptor(struct wim_dentry *dentry,
256 struct sd_set *sd_set,
258 struct win32_capture_state *state,
261 SECURITY_INFORMATION requestedInformation;
267 requestedInformation = DACL_SECURITY_INFORMATION |
268 SACL_SECURITY_INFORMATION |
269 OWNER_SECURITY_INFORMATION |
270 GROUP_SECURITY_INFORMATION;
272 /* Request length of security descriptor */
273 status = GetFileSecurityW(path, requestedInformation,
274 NULL, 0, &lenNeeded);
275 err = GetLastError();
276 if (!status && err == ERROR_INSUFFICIENT_BUFFER) {
277 DWORD len = lenNeeded;
279 if (GetFileSecurityW(path, requestedInformation,
280 (PSECURITY_DESCRIPTOR)buf, len, &lenNeeded))
282 int security_id = sd_set_add_sd(sd_set, buf, len);
284 return WIMLIB_ERR_NOMEM;
286 dentry->d_inode->i_security_id = security_id;
290 err = GetLastError();
294 if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_STRICT_ACLS)
298 case ERROR_PRIVILEGE_NOT_HELD:
299 if (requestedInformation & SACL_SECURITY_INFORMATION) {
300 n = state->num_get_sacl_priv_notheld++;
301 requestedInformation &= ~SACL_SECURITY_INFORMATION;
302 if (n < MAX_GET_SACL_PRIV_NOTHELD_WARNINGS) {
304 "We don't have enough privileges to read the full security\n"
305 " descriptor of \"%ls\"!\n"
306 " Re-trying with SACL omitted.\n", path);
307 } else if (n == MAX_GET_SACL_PRIV_NOTHELD_WARNINGS) {
309 "Suppressing further privileges not held error messages when reading\n"
310 " security descriptors.");
315 case ERROR_ACCESS_DENIED:
316 n = state->num_get_sd_access_denied++;
317 if (n < MAX_GET_SD_ACCESS_DENIED_WARNINGS) {
318 WARNING("Failed to read security descriptor of \"%ls\": "
319 "Access denied!\n%ls", path, capture_access_denied_msg);
320 } else if (n == MAX_GET_SD_ACCESS_DENIED_WARNINGS) {
321 WARNING("Suppressing further access denied errors messages i"
322 "when reading security descriptors");
327 ERROR("Failed to read security descriptor of \"%ls\"", path);
329 return WIMLIB_ERR_READ;
334 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
336 size_t path_num_chars,
337 struct wim_lookup_table *lookup_table,
338 struct wim_inode_table *inode_table,
339 struct sd_set *sd_set,
340 const struct wimlib_capture_config *config,
342 wimlib_progress_func_t progress_func,
343 struct win32_capture_state *state);
345 /* Reads the directory entries of directory using a Win32 API and recursively
346 * calls win32_build_dentry_tree() on them. */
348 win32_recurse_directory(struct wim_dentry *root,
350 size_t dir_path_num_chars,
351 struct wim_lookup_table *lookup_table,
352 struct wim_inode_table *inode_table,
353 struct sd_set *sd_set,
354 const struct wimlib_capture_config *config,
356 wimlib_progress_func_t progress_func,
357 struct win32_capture_state *state)
359 WIN32_FIND_DATAW dat;
364 /* Begin reading the directory by calling FindFirstFileW. Unlike UNIX
365 * opendir(), FindFirstFileW has file globbing built into it. But this
366 * isn't what we actually want, so just add a dummy glob to get all
368 dir_path[dir_path_num_chars] = L'/';
369 dir_path[dir_path_num_chars + 1] = L'*';
370 dir_path[dir_path_num_chars + 2] = L'\0';
371 hFind = FindFirstFileW(dir_path, &dat);
372 dir_path[dir_path_num_chars] = L'\0';
374 if (hFind == INVALID_HANDLE_VALUE) {
375 err = GetLastError();
376 if (err == ERROR_FILE_NOT_FOUND) {
379 ERROR("Failed to read directory \"%ls\"", dir_path);
381 return WIMLIB_ERR_READ;
386 /* Skip . and .. entries */
387 if (dat.cFileName[0] == L'.' &&
388 (dat.cFileName[1] == L'\0' ||
389 (dat.cFileName[1] == L'.' &&
390 dat.cFileName[2] == L'\0')))
392 size_t filename_len = wcslen(dat.cFileName);
394 dir_path[dir_path_num_chars] = L'/';
395 wmemcpy(dir_path + dir_path_num_chars + 1,
399 struct wim_dentry *child;
400 size_t path_len = dir_path_num_chars + 1 + filename_len;
401 ret = win32_build_dentry_tree_recursive(&child,
411 dir_path[dir_path_num_chars] = L'\0';
415 dentry_add_child(root, child);
416 } while (FindNextFileW(hFind, &dat));
417 err = GetLastError();
418 if (err != ERROR_NO_MORE_FILES) {
419 ERROR("Failed to read directory \"%ls\"", dir_path);
422 ret = WIMLIB_ERR_READ;
429 /* Load a reparse point into a WIM inode. It is just stored in memory.
431 * @hFile: Open handle to a reparse point, with permission to read the reparse
434 * @inode: WIM inode for the reparse point.
436 * @lookup_table: Stream lookup table for the WIM; an entry will be added to it
437 * for the reparse point unless an entry already exists for
438 * the exact same data stream.
440 * @path: External path to the reparse point. Used for error messages only.
442 * Returns 0 on success; nonzero on failure. */
444 win32_capture_reparse_point(HANDLE hFile,
445 struct wim_inode *inode,
446 struct wim_lookup_table *lookup_table,
449 /* "Reparse point data, including the tag and optional GUID,
450 * cannot exceed 16 kilobytes." - MSDN */
451 char reparse_point_buf[16 * 1024];
454 if (!DeviceIoControl(hFile, FSCTL_GET_REPARSE_POINT,
455 NULL, /* "Not used with this operation; set to NULL" */
456 0, /* "Not used with this operation; set to 0" */
457 reparse_point_buf, /* "A pointer to a buffer that
458 receives the reparse point data */
459 sizeof(reparse_point_buf), /* "The size of the output
464 DWORD err = GetLastError();
465 ERROR("Failed to get reparse data of \"%ls\"", path);
467 return WIMLIB_ERR_READ;
469 if (bytesReturned < 8) {
470 ERROR("Reparse data on \"%ls\" is invalid", path);
471 return WIMLIB_ERR_READ;
473 inode->i_reparse_tag = le32_to_cpu(*(u32*)reparse_point_buf);
474 return inode_add_ads_with_data(inode, L"",
475 reparse_point_buf + 8,
476 bytesReturned - 8, lookup_table);
479 /* Scans an unnamed or named stream of a Win32 file (not a reparse point
480 * stream); calculates its SHA1 message digest and either creates a `struct
481 * wim_lookup_table_entry' in memory for it, or uses an existing 'struct
482 * wim_lookup_table_entry' for an identical stream.
484 * @path: Path to the file (UTF-16LE).
486 * @path_num_chars: Number of 2-byte characters in @path.
488 * @inode: WIM inode to save the stream into.
490 * @lookup_table: Stream lookup table for the WIM.
492 * @dat: A `WIN32_FIND_STREAM_DATA' structure that specifies the
495 * Returns 0 on success; nonzero on failure.
498 win32_capture_stream(const wchar_t *path,
499 size_t path_num_chars,
500 struct wim_inode *inode,
501 struct wim_lookup_table *lookup_table,
502 WIN32_FIND_STREAM_DATA *dat)
504 struct wim_ads_entry *ads_entry;
505 u8 hash[SHA1_HASH_SIZE];
506 struct wim_lookup_table_entry *lte;
508 wchar_t *stream_name, *colon;
509 size_t stream_name_nchars;
510 bool is_named_stream;
514 size_t spath_buf_nbytes;
515 const wchar_t *relpath_prefix;
516 const wchar_t *colonchar;
518 /* The stream name should be returned as :NAME:TYPE */
519 stream_name = dat->cStreamName;
520 if (*stream_name != L':')
521 goto out_invalid_stream_name;
523 colon = wcschr(stream_name, L':');
525 goto out_invalid_stream_name;
527 if (wcscmp(colon + 1, L"$DATA")) {
528 /* Not a DATA stream */
535 stream_name_nchars = colon - stream_name;
536 is_named_stream = (stream_name_nchars != 0);
538 if (is_named_stream) {
539 /* Allocate an ADS entry for the named stream. */
540 ads_entry = inode_add_ads_utf16le(inode, stream_name,
541 stream_name_nchars * sizeof(wchar_t));
543 ret = WIMLIB_ERR_NOMEM;
548 /* Create a UTF-16LE string @spath that gives the filename, then a
549 * colon, then the stream name. Or, if it's an unnamed stream, just the
550 * filename. It is MALLOC()'ed so that it can be saved in the
551 * wim_lookup_table_entry if needed.
553 * As yet another special case, relative paths need to be changed to
554 * begin with an explicit "./" so that, for example, a file t:ads, where
555 * :ads is the part we added, is not interpreted as a file on the t:
557 spath_nchars = path_num_chars;
558 relpath_prefix = L"";
560 if (is_named_stream) {
561 spath_nchars += 1 + stream_name_nchars;
563 if (path_num_chars == 1 &&
568 relpath_prefix = L"./";
572 spath_buf_nbytes = (spath_nchars + 1) * sizeof(wchar_t);
573 spath = MALLOC(spath_buf_nbytes);
575 swprintf(spath, L"%ls%ls%ls%ls",
576 relpath_prefix, path, colonchar, stream_name);
578 /* Make a new wim_lookup_table_entry */
579 lte = new_lookup_table_entry();
581 ret = WIMLIB_ERR_NOMEM;
584 lte->file_on_disk = spath;
586 lte->resource_location = RESOURCE_WIN32;
587 lte->resource_entry.original_size = (u64)dat->StreamSize.QuadPart;
590 if (is_named_stream) {
591 stream_id = ads_entry->stream_id;
592 ads_entry->lte = lte;
598 lookup_table_insert_unhashed(lookup_table, lte, inode, stream_id);
603 out_invalid_stream_name:
604 ERROR("Invalid stream name: \"%ls:%ls\"", path, dat->cStreamName);
605 ret = WIMLIB_ERR_READ;
609 /* Scans a Win32 file for unnamed and named data streams (not reparse point
612 * @path: Path to the file (UTF-16LE).
614 * @path_num_chars: Number of 2-byte characters in @path.
616 * @inode: WIM inode to save the stream into.
618 * @lookup_table: Stream lookup table for the WIM.
620 * @file_size: Size of unnamed data stream. (Used only if alternate
621 * data streams API appears to be unavailable.)
623 * Returns 0 on success; nonzero on failure.
626 win32_capture_streams(const wchar_t *path,
627 size_t path_num_chars,
628 struct wim_inode *inode,
629 struct wim_lookup_table *lookup_table,
632 WIN32_FIND_STREAM_DATA dat;
637 if (win32func_FindFirstStreamW == NULL)
640 hFind = win32func_FindFirstStreamW(path, FindStreamInfoStandard, &dat, 0);
641 if (hFind == INVALID_HANDLE_VALUE) {
642 err = GetLastError();
644 if (err == ERROR_CALL_NOT_IMPLEMENTED)
647 /* Seems legal for this to return ERROR_HANDLE_EOF on reparse
648 * points and directories */
649 if ((inode->i_attributes &
650 (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
651 && err == ERROR_HANDLE_EOF)
655 if (err == ERROR_ACCESS_DENIED) {
656 /* XXX This maybe should be an error. */
657 WARNING("Failed to look up data streams "
658 "of \"%ls\": Access denied!\n%ls",
659 path, capture_access_denied_msg);
662 ERROR("Failed to look up data streams "
665 return WIMLIB_ERR_READ;
670 ret = win32_capture_stream(path,
676 } while (win32func_FindNextStreamW(hFind, &dat));
677 err = GetLastError();
678 if (err != ERROR_HANDLE_EOF) {
679 ERROR("Win32 API: Error reading data streams from \"%ls\"", path);
681 ret = WIMLIB_ERR_READ;
687 /* FindFirstStreamW() API is not available. Only capture the unnamed
689 if (inode->i_attributes &
690 (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
694 /* Just create our own WIN32_FIND_STREAM_DATA for an unnamed
695 * stream to reduce the code to a call to the
696 * already-implemented win32_capture_stream() */
697 wcscpy(dat.cStreamName, L"::$DATA");
698 dat.StreamSize.QuadPart = file_size;
699 ret = win32_capture_stream(path,
708 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
710 size_t path_num_chars,
711 struct wim_lookup_table *lookup_table,
712 struct wim_inode_table *inode_table,
713 struct sd_set *sd_set,
714 const struct wimlib_capture_config *config,
716 wimlib_progress_func_t progress_func,
717 struct win32_capture_state *state)
719 struct wim_dentry *root = NULL;
720 struct wim_inode *inode;
725 if (exclude_path(path, path_num_chars, config, true)) {
726 if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT) {
727 ERROR("Cannot exclude the root directory from capture");
728 ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
731 if ((add_image_flags & WIMLIB_ADD_IMAGE_FLAG_EXCLUDE_VERBOSE)
734 union wimlib_progress_info info;
735 info.scan.cur_path = path;
736 info.scan.excluded = true;
737 progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
742 if ((add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
745 union wimlib_progress_info info;
746 info.scan.cur_path = path;
747 info.scan.excluded = false;
748 progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
751 HANDLE hFile = win32_open_existing_file(path,
752 FILE_READ_DATA | FILE_READ_ATTRIBUTES);
753 if (hFile == INVALID_HANDLE_VALUE) {
754 err = GetLastError();
755 ERROR("Win32 API: Failed to open \"%ls\"", path);
757 ret = WIMLIB_ERR_OPEN;
761 BY_HANDLE_FILE_INFORMATION file_info;
762 if (!GetFileInformationByHandle(hFile, &file_info)) {
763 err = GetLastError();
764 ERROR("Win32 API: Failed to get file information for \"%ls\"",
767 ret = WIMLIB_ERR_STAT;
768 goto out_close_handle;
771 /* Create a WIM dentry with an associated inode, which may be shared */
772 ret = inode_table_new_dentry(inode_table,
773 path_basename_with_len(path, path_num_chars),
774 ((u64)file_info.nFileIndexHigh << 32) |
775 (u64)file_info.nFileIndexLow,
776 file_info.dwVolumeSerialNumber,
779 goto out_close_handle;
781 ret = win32_get_short_name(root, path);
783 goto out_close_handle;
785 inode = root->d_inode;
787 if (inode->i_nlink > 1) /* Shared inode; nothing more to do */
788 goto out_close_handle;
790 inode->i_attributes = file_info.dwFileAttributes;
791 inode->i_creation_time = FILETIME_to_u64(&file_info.ftCreationTime);
792 inode->i_last_write_time = FILETIME_to_u64(&file_info.ftLastWriteTime);
793 inode->i_last_access_time = FILETIME_to_u64(&file_info.ftLastAccessTime);
794 inode->i_resolved = 1;
796 add_image_flags &= ~(WIMLIB_ADD_IMAGE_FLAG_ROOT | WIMLIB_ADD_IMAGE_FLAG_SOURCE);
798 if (!(add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NO_ACLS)) {
799 ret = win32_get_security_descriptor(root, sd_set, path, state,
802 goto out_close_handle;
805 file_size = ((u64)file_info.nFileSizeHigh << 32) |
806 (u64)file_info.nFileSizeLow;
808 if (inode_is_directory(inode)) {
809 /* Directory (not a reparse point) --- recurse to children */
811 /* But first... directories may have alternate data streams that
812 * need to be captured. */
813 ret = win32_capture_streams(path,
819 goto out_close_handle;
820 ret = win32_recurse_directory(root,
830 } else if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
831 /* Reparse point: save the reparse tag and data. Alternate data
832 * streams are not captured, if it's even possible for a reparse
833 * point to have alternate data streams... */
834 ret = win32_capture_reparse_point(hFile,
839 /* Not a directory, not a reparse point; capture the default
840 * file contents and any alternate data streams. */
841 ret = win32_capture_streams(path,
853 free_dentry_tree(root, lookup_table);
858 win32_do_capture_warnings(const struct win32_capture_state *state,
861 if (state->num_get_sacl_priv_notheld == 0 &&
862 state->num_get_sd_access_denied == 0)
866 WARNING("Built dentry tree successfully, but with the following problem(s):");
867 if (state->num_get_sacl_priv_notheld != 0) {
868 WARNING("Could not capture SACL (System Access Control List)\n"
869 " on %lu files or directories.",
870 state->num_get_sacl_priv_notheld);
872 if (state->num_get_sd_access_denied != 0) {
873 WARNING("Could not capture security descriptor at all\n"
874 " on %lu files or directories.",
875 state->num_get_sd_access_denied);
878 "Try running the program as the Administrator to make sure all the\n"
879 " desired metadata has been captured exactly. However, if you\n"
880 " do not care about capturing security descriptors correctly, then\n"
881 " nothing more needs to be done%ls\n",
882 (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NO_ACLS) ? L"." :
883 L", although you might consider\n"
884 " passing the --no-acls flag to `wimlib-imagex capture' or\n"
885 " `wimlib-imagex append' to explicitly capture no security\n"
889 /* Win32 version of capturing a directory tree */
891 win32_build_dentry_tree(struct wim_dentry **root_ret,
892 const wchar_t *root_disk_path,
893 struct wim_lookup_table *lookup_table,
894 struct wim_inode_table *inode_table,
895 struct sd_set *sd_set,
896 const struct wimlib_capture_config *config,
898 wimlib_progress_func_t progress_func,
904 struct win32_capture_state state;
906 path_nchars = wcslen(root_disk_path);
907 if (path_nchars > 32767)
908 return WIMLIB_ERR_INVALID_PARAM;
910 /* There is no check for overflow later when this buffer is being used!
911 * But the max path length on NTFS is 32767 characters, and paths need
912 * to be written specially to even go past 260 characters, so we should
913 * be okay with 32770 characters. */
914 path = MALLOC(32770 * sizeof(wchar_t));
916 return WIMLIB_ERR_NOMEM;
918 wmemcpy(path, root_disk_path, path_nchars + 1);
920 memset(&state, 0, sizeof(state));
921 ret = win32_build_dentry_tree_recursive(root_ret,
933 win32_do_capture_warnings(&state, add_image_flags);
938 win32_set_reparse_data(HANDLE h,
940 const struct wim_lookup_table_entry *lte,
948 WARNING("\"%ls\" is marked as a reparse point but had no reparse data",
952 len = wim_resource_size(lte);
953 if (len > 16 * 1024 - 8) {
954 WARNING("\"%ls\": reparse data too long!", path);
958 /* The WIM stream omits the ReparseTag and ReparseDataLength fields, so
959 * leave 8 bytes of space for them at the beginning of the buffer, then
960 * set them manually. */
961 buf = alloca(len + 8);
962 ret = read_full_wim_resource(lte, buf + 8, 0);
965 *(u32*)(buf + 0) = cpu_to_le32(reparse_tag);
966 *(u16*)(buf + 4) = cpu_to_le16(len);
967 *(u16*)(buf + 6) = 0;
969 /* Set the reparse data on the open file using the
970 * FSCTL_SET_REPARSE_POINT ioctl.
972 * There are contradictions in Microsoft's documentation for this:
974 * "If hDevice was opened without specifying FILE_FLAG_OVERLAPPED,
975 * lpOverlapped is ignored."
977 * --- So setting lpOverlapped to NULL is okay since it's ignored.
979 * "If lpOverlapped is NULL, lpBytesReturned cannot be NULL. Even when an
980 * operation returns no output data and lpOutBuffer is NULL,
981 * DeviceIoControl makes use of lpBytesReturned. After such an
982 * operation, the value of lpBytesReturned is meaningless."
984 * --- So lpOverlapped not really ignored, as it affects another
985 * parameter. This is the actual behavior: lpBytesReturned must be
986 * specified, even though lpBytesReturned is documented as:
988 * "Not used with this operation; set to NULL."
991 if (!DeviceIoControl(h, FSCTL_SET_REPARSE_POINT, buf, len + 8,
993 &bytesReturned /* lpBytesReturned */,
994 NULL /* lpOverlapped */))
996 DWORD err = GetLastError();
997 ERROR("Failed to set reparse data on \"%ls\"", path);
999 return WIMLIB_ERR_WRITE;
1005 win32_set_compressed(HANDLE hFile, const wchar_t *path)
1007 USHORT format = COMPRESSION_FORMAT_DEFAULT;
1008 DWORD bytesReturned = 0;
1009 if (!DeviceIoControl(hFile, FSCTL_SET_COMPRESSION,
1010 &format, sizeof(USHORT),
1012 &bytesReturned, NULL))
1015 DWORD err = GetLastError();
1016 WARNING("Failed to set compression flag on \"%ls\"", path);
1023 win32_set_sparse(HANDLE hFile, const wchar_t *path)
1025 DWORD bytesReturned = 0;
1026 if (!DeviceIoControl(hFile, FSCTL_SET_SPARSE,
1029 &bytesReturned, NULL))
1032 DWORD err = GetLastError();
1033 WARNING("Failed to set sparse flag on \"%ls\"", path);
1040 * Sets the security descriptor on an extracted file.
1043 win32_set_security_data(const struct wim_inode *inode,
1044 const wchar_t *path,
1045 struct apply_args *args)
1047 PSECURITY_DESCRIPTOR descriptor;
1051 descriptor = wim_const_security_data(args->w)->descriptors[inode->i_security_id];
1053 SECURITY_INFORMATION securityInformation = DACL_SECURITY_INFORMATION |
1054 SACL_SECURITY_INFORMATION |
1055 OWNER_SECURITY_INFORMATION |
1056 GROUP_SECURITY_INFORMATION;
1058 if (SetFileSecurityW(path, securityInformation, descriptor))
1060 err = GetLastError();
1061 if (args->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS)
1064 case ERROR_PRIVILEGE_NOT_HELD:
1065 if (securityInformation & SACL_SECURITY_INFORMATION) {
1066 n = args->num_set_sacl_priv_notheld++;
1067 securityInformation &= ~SACL_SECURITY_INFORMATION;
1068 if (n < MAX_SET_SACL_PRIV_NOTHELD_WARNINGS) {
1070 "We don't have enough privileges to set the full security\n"
1071 " descriptor on \"%ls\"!\n", path);
1072 if (args->num_set_sd_access_denied +
1073 args->num_set_sacl_priv_notheld == 1)
1075 WARNING("%ls", apply_access_denied_msg);
1077 WARNING("Re-trying with SACL omitted.\n", path);
1078 } else if (n == MAX_GET_SACL_PRIV_NOTHELD_WARNINGS) {
1080 "Suppressing further 'privileges not held' error messages when setting\n"
1081 " security descriptors.");
1086 case ERROR_INVALID_OWNER:
1087 case ERROR_ACCESS_DENIED:
1088 n = args->num_set_sd_access_denied++;
1089 if (n < MAX_SET_SD_ACCESS_DENIED_WARNINGS) {
1090 WARNING("Failed to set security descriptor on \"%ls\": "
1091 "Access denied!\n", path);
1092 if (args->num_set_sd_access_denied +
1093 args->num_set_sacl_priv_notheld == 1)
1095 WARNING("%ls", apply_access_denied_msg);
1097 } else if (n == MAX_SET_SD_ACCESS_DENIED_WARNINGS) {
1099 "Suppressing further access denied error messages when setting\n"
1100 " security descriptors");
1105 ERROR("Failed to set security descriptor on \"%ls\"", path);
1107 return WIMLIB_ERR_WRITE;
1113 win32_extract_chunk(const void *buf, size_t len, u64 offset, void *arg)
1115 HANDLE hStream = arg;
1117 DWORD nbytes_written;
1118 wimlib_assert(len <= 0xffffffff);
1120 if (!WriteFile(hStream, buf, len, &nbytes_written, NULL) ||
1121 nbytes_written != len)
1123 DWORD err = GetLastError();
1124 ERROR("WriteFile(): write error");
1126 return WIMLIB_ERR_WRITE;
1132 do_win32_extract_stream(HANDLE hStream, struct wim_lookup_table_entry *lte)
1134 return extract_wim_resource(lte, wim_resource_size(lte),
1135 win32_extract_chunk, hStream);
1139 path_is_root_of_drive(const wchar_t *path)
1144 if (*path != L'/' && *path != L'\\') {
1145 if (*(path + 1) == L':')
1150 while (*path == L'/' || *path == L'\\')
1152 return (*path == L'\0');
1156 win32_get_create_flags_and_attributes(DWORD i_attributes)
1161 * Some attributes cannot be set by passing them to CreateFile(). In
1164 * FILE_ATTRIBUTE_DIRECTORY:
1165 * CreateDirectory() must be called instead of CreateFile().
1167 * FILE_ATTRIBUTE_SPARSE_FILE:
1169 * See: win32_set_sparse().
1171 * FILE_ATTRIBUTE_COMPRESSED:
1172 * Not clear from the documentation, but apparently this needs an
1174 * See: win32_set_compressed().
1176 * FILE_ATTRIBUTE_REPARSE_POINT:
1177 * Needs an ioctl, with the reparse data specified.
1178 * See: win32_set_reparse_data().
1180 * In addition, clear any file flags in the attributes that we don't
1181 * want, but also specify FILE_FLAG_OPEN_REPARSE_POINT and
1182 * FILE_FLAG_BACKUP_SEMANTICS as we are a backup application.
1184 attributes = i_attributes & ~(FILE_ATTRIBUTE_SPARSE_FILE |
1185 FILE_ATTRIBUTE_COMPRESSED |
1186 FILE_ATTRIBUTE_REPARSE_POINT |
1187 FILE_ATTRIBUTE_DIRECTORY |
1188 FILE_FLAG_DELETE_ON_CLOSE |
1189 FILE_FLAG_NO_BUFFERING |
1190 FILE_FLAG_OPEN_NO_RECALL |
1191 FILE_FLAG_OVERLAPPED |
1192 FILE_FLAG_RANDOM_ACCESS |
1193 /*FILE_FLAG_SESSION_AWARE |*/
1194 FILE_FLAG_SEQUENTIAL_SCAN |
1195 FILE_FLAG_WRITE_THROUGH);
1197 FILE_FLAG_OPEN_REPARSE_POINT |
1198 FILE_FLAG_BACKUP_SEMANTICS;
1202 inode_has_special_attributes(const struct wim_inode *inode)
1204 return (inode->i_attributes & (FILE_ATTRIBUTE_COMPRESSED |
1205 FILE_ATTRIBUTE_REPARSE_POINT |
1206 FILE_ATTRIBUTE_SPARSE_FILE)) != 0;
1210 win32_set_special_attributes(HANDLE hFile, const struct wim_inode *inode,
1211 struct wim_lookup_table_entry *unnamed_stream_lte,
1212 const wchar_t *path)
1216 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1217 DEBUG("Setting reparse data on \"%ls\"", path);
1218 ret = win32_set_reparse_data(hFile, inode->i_reparse_tag,
1219 unnamed_stream_lte, path);
1224 if (inode->i_attributes & FILE_ATTRIBUTE_COMPRESSED) {
1225 DEBUG("Setting compression flag on \"%ls\"", path);
1226 ret = win32_set_compressed(hFile, path);
1231 if (inode->i_attributes & FILE_ATTRIBUTE_SPARSE_FILE) {
1232 DEBUG("Setting sparse flag on \"%ls\"", path);
1233 ret = win32_set_sparse(hFile, path);
1241 win32_extract_stream(const struct wim_inode *inode,
1242 const wchar_t *path,
1243 const wchar_t *stream_name_utf16,
1244 struct wim_lookup_table_entry *lte)
1246 wchar_t *stream_path;
1250 DWORD creationDisposition = CREATE_ALWAYS;
1252 if (stream_name_utf16) {
1253 /* Named stream. Create a buffer that contains the UTF-16LE
1254 * string [.\]@path:@stream_name_utf16. This is needed to
1255 * create and open the stream using CreateFileW(). I'm not
1256 * aware of any other APIs to do this. Note: the '$DATA' suffix
1257 * seems to be unneeded. Additional note: a "./" prefix needs
1258 * to be added when the path is not absolute to avoid ambiguity
1259 * with drive letters. */
1260 size_t stream_path_nchars;
1262 size_t stream_name_nchars;
1263 const wchar_t *prefix;
1265 path_nchars = wcslen(path);
1266 stream_name_nchars = wcslen(stream_name_utf16);
1267 stream_path_nchars = path_nchars + 1 + stream_name_nchars;
1268 if (path[0] != cpu_to_le16(L'\0') &&
1269 path[0] != cpu_to_le16(L'/') &&
1270 path[0] != cpu_to_le16(L'\\') &&
1271 path[1] != cpu_to_le16(L':'))
1274 stream_path_nchars += 2;
1278 stream_path = alloca((stream_path_nchars + 1) * sizeof(wchar_t));
1279 swprintf(stream_path, L"%ls%ls:%ls",
1280 prefix, path, stream_name_utf16);
1282 /* Unnamed stream; its path is just the path to the file itself.
1284 stream_path = (wchar_t*)path;
1286 /* Directories must be created with CreateDirectoryW(). Then
1287 * the call to CreateFileW() will merely open the directory that
1288 * was already created rather than creating a new file. */
1289 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1290 if (!CreateDirectoryW(stream_path, NULL)) {
1291 err = GetLastError();
1293 case ERROR_ALREADY_EXISTS:
1295 case ERROR_ACCESS_DENIED:
1296 if (path_is_root_of_drive(path))
1300 ERROR("Failed to create directory \"%ls\"",
1303 ret = WIMLIB_ERR_MKDIR;
1307 DEBUG("Created directory \"%ls\"", stream_path);
1308 if (!inode_has_special_attributes(inode)) {
1312 creationDisposition = OPEN_EXISTING;
1316 DEBUG("Opening \"%ls\"", stream_path);
1317 h = CreateFileW(stream_path,
1318 GENERIC_READ | GENERIC_WRITE,
1321 creationDisposition,
1322 win32_get_create_flags_and_attributes(inode->i_attributes),
1324 if (h == INVALID_HANDLE_VALUE) {
1325 err = GetLastError();
1326 ERROR("Failed to create \"%ls\"", stream_path);
1328 ret = WIMLIB_ERR_OPEN;
1332 if (stream_name_utf16 == NULL && inode_has_special_attributes(inode)) {
1333 ret = win32_set_special_attributes(h, inode, lte, path);
1335 goto fail_close_handle;
1338 if (!(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
1340 DEBUG("Extracting \"%ls\" (len = %"PRIu64")",
1341 stream_path, wim_resource_size(lte));
1342 ret = do_win32_extract_stream(h, lte);
1344 goto fail_close_handle;
1348 DEBUG("Closing \"%ls\"", stream_path);
1349 if (!CloseHandle(h)) {
1350 err = GetLastError();
1351 ERROR("Failed to close \"%ls\"", stream_path);
1353 ret = WIMLIB_ERR_WRITE;
1361 ERROR("Error extracting %ls", stream_path);
1367 * Creates a file, directory, or reparse point and extracts all streams to it
1368 * (unnamed data stream and/or reparse point stream, plus any alternate data
1369 * streams). This in Win32-specific code.
1371 * @inode: WIM inode for this file or directory.
1372 * @path: UTF-16LE external path to extract the inode to.
1374 * Returns 0 on success; nonzero on failure.
1377 win32_extract_streams(const struct wim_inode *inode,
1378 const wchar_t *path, u64 *completed_bytes_p)
1380 struct wim_lookup_table_entry *unnamed_lte;
1383 unnamed_lte = inode_unnamed_lte_resolved(inode);
1384 ret = win32_extract_stream(inode, path, NULL, unnamed_lte);
1388 *completed_bytes_p += wim_resource_size(unnamed_lte);
1389 for (u16 i = 0; i < inode->i_num_ads; i++) {
1390 const struct wim_ads_entry *ads_entry = &inode->i_ads_entries[i];
1391 if (ads_entry->stream_name_nbytes != 0) {
1392 /* Skip special UNIX data entries (see documentation for
1393 * WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA) */
1394 if (ads_entry->stream_name_nbytes == WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES
1395 && !memcmp(ads_entry->stream_name,
1396 WIMLIB_UNIX_DATA_TAG_UTF16LE,
1397 WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES))
1399 ret = win32_extract_stream(inode,
1401 ads_entry->stream_name,
1406 *completed_bytes_p += wim_resource_size(ads_entry->lte);
1413 /* Extract a file, directory, reparse point, or hard link to an
1414 * already-extracted file using the Win32 API */
1416 win32_do_apply_dentry(const wchar_t *output_path,
1417 size_t output_path_num_chars,
1418 struct wim_dentry *dentry,
1419 struct apply_args *args)
1422 struct wim_inode *inode = dentry->d_inode;
1425 if (inode->i_nlink > 1 && inode->i_extracted_file != NULL) {
1426 /* Linked file, with another name already extracted. Create a
1428 DEBUG("Creating hard link \"%ls => %ls\"",
1429 output_path, inode->i_extracted_file);
1430 if (!CreateHardLinkW(output_path, inode->i_extracted_file, NULL)) {
1431 err = GetLastError();
1432 ERROR("Can't create hard link \"%ls => %ls\"",
1433 output_path, inode->i_extracted_file);
1435 return WIMLIB_ERR_LINK;
1438 /* Create the file, directory, or reparse point, and extract the
1440 ret = win32_extract_streams(inode, output_path,
1441 &args->progress.extract.completed_bytes);
1445 if (inode->i_security_id >= 0 &&
1446 !(args->extract_flags & WIMLIB_EXTRACT_FLAG_NO_ACLS))
1448 ret = win32_set_security_data(inode, output_path, args);
1452 if (inode->i_nlink > 1) {
1453 /* Save extracted path for a later call to
1454 * CreateHardLinkW() if this inode has multiple links.
1456 inode->i_extracted_file = WSTRDUP(output_path);
1457 if (!inode->i_extracted_file)
1458 ret = WIMLIB_ERR_NOMEM;
1464 /* Set timestamps on an extracted file using the Win32 API */
1466 win32_do_apply_dentry_timestamps(const wchar_t *path,
1467 size_t path_num_chars,
1468 const struct wim_dentry *dentry,
1469 const struct apply_args *args)
1473 const struct wim_inode *inode = dentry->d_inode;
1475 DEBUG("Opening \"%ls\" to set timestamps", path);
1476 h = win32_open_existing_file(path, FILE_WRITE_ATTRIBUTES);
1477 if (h == INVALID_HANDLE_VALUE) {
1478 err = GetLastError();
1482 FILETIME creationTime = {.dwLowDateTime = inode->i_creation_time & 0xffffffff,
1483 .dwHighDateTime = inode->i_creation_time >> 32};
1484 FILETIME lastAccessTime = {.dwLowDateTime = inode->i_last_access_time & 0xffffffff,
1485 .dwHighDateTime = inode->i_last_access_time >> 32};
1486 FILETIME lastWriteTime = {.dwLowDateTime = inode->i_last_write_time & 0xffffffff,
1487 .dwHighDateTime = inode->i_last_write_time >> 32};
1489 DEBUG("Calling SetFileTime() on \"%ls\"", path);
1490 if (!SetFileTime(h, &creationTime, &lastAccessTime, &lastWriteTime)) {
1491 err = GetLastError();
1495 DEBUG("Closing \"%ls\"", path);
1496 if (!CloseHandle(h)) {
1497 err = GetLastError();
1502 /* Only warn if setting timestamps failed; still return 0. */
1503 WARNING("Can't set timestamps on \"%ls\"", path);
1509 /* Replacement for POSIX fsync() */
1516 h = (HANDLE)_get_osfhandle(fd);
1517 if (h == INVALID_HANDLE_VALUE) {
1518 err = GetLastError();
1519 ERROR("Could not get Windows handle for file descriptor");
1524 if (!FlushFileBuffers(h)) {
1525 err = GetLastError();
1526 ERROR("Could not flush file buffers to disk");
1534 /* Use the Win32 API to get the number of processors */
1536 win32_get_number_of_processors()
1538 SYSTEM_INFO sysinfo;
1539 GetSystemInfo(&sysinfo);
1540 return sysinfo.dwNumberOfProcessors;
1543 /* Replacement for POSIX-2008 realpath(). Warning: partial functionality only
1544 * (resolved_path must be NULL). Also I highly doubt that GetFullPathName
1545 * really does the right thing under all circumstances. */
1547 realpath(const wchar_t *path, wchar_t *resolved_path)
1550 wimlib_assert(resolved_path == NULL);
1553 ret = GetFullPathNameW(path, 0, NULL, NULL);
1555 err = GetLastError();
1559 resolved_path = TMALLOC(ret);
1562 ret = GetFullPathNameW(path, ret, resolved_path, NULL);
1564 err = GetLastError();
1565 free(resolved_path);
1566 resolved_path = NULL;
1574 return resolved_path;
1577 /* rename() on Windows fails if the destination file exists. And we need to
1578 * make it work on wide characters. Fix it. */
1580 win32_rename_replacement(const wchar_t *oldpath, const wchar_t *newpath)
1582 if (MoveFileExW(oldpath, newpath, MOVEFILE_REPLACE_EXISTING)) {
1585 /* As usual, the possible error values are not documented */
1586 DWORD err = GetLastError();
1587 ERROR("MoveFileEx(): Can't rename \"%ls\" to \"%ls\"",
1595 /* Replacement for POSIX fnmatch() (partial functionality only) */
1597 fnmatch(const wchar_t *pattern, const wchar_t *string, int flags)
1599 if (PathMatchSpecW(string, pattern))
1605 /* truncate() replacement */
1607 win32_truncate_replacement(const wchar_t *path, off_t size)
1609 DWORD err = NO_ERROR;
1610 LARGE_INTEGER liOffset;
1612 HANDLE h = win32_open_existing_file(path, GENERIC_WRITE);
1613 if (h == INVALID_HANDLE_VALUE)
1616 liOffset.QuadPart = size;
1617 if (!SetFilePointerEx(h, liOffset, NULL, FILE_BEGIN))
1618 goto fail_close_handle;
1620 if (!SetEndOfFile(h))
1621 goto fail_close_handle;
1626 err = GetLastError();
1629 if (err == NO_ERROR)
1630 err = GetLastError();
1631 ERROR("Can't truncate \"%ls\" to %"PRIu64" bytes", path, size);
1638 /* This really could be replaced with _wcserror_s, but this doesn't seem to
1639 * actually be available in MSVCRT.DLL on Windows XP (perhaps it's statically
1640 * linked in by Visual Studio...?). */
1642 win32_strerror_r_replacement(int errnum, wchar_t *buf, size_t buflen)
1644 static pthread_mutex_t strerror_lock = PTHREAD_MUTEX_INITIALIZER;
1646 pthread_mutex_lock(&strerror_lock);
1647 mbstowcs(buf, strerror(errnum), buflen);
1648 buf[buflen - 1] = '\0';
1649 pthread_mutex_unlock(&strerror_lock);
1653 #endif /* __WIN32__ */