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;
588 lookup_table_insert_unhashed(lookup_table, lte);
591 ads_entry->lte = lte;
598 out_invalid_stream_name:
599 ERROR("Invalid stream name: \"%ls:%ls\"", path, dat->cStreamName);
600 ret = WIMLIB_ERR_READ;
604 /* Scans a Win32 file for unnamed and named data streams (not reparse point
607 * @path: Path to the file (UTF-16LE).
609 * @path_num_chars: Number of 2-byte characters in @path.
611 * @inode: WIM inode to save the stream into.
613 * @lookup_table: Stream lookup table for the WIM.
615 * @file_size: Size of unnamed data stream. (Used only if alternate
616 * data streams API appears to be unavailable.)
618 * Returns 0 on success; nonzero on failure.
621 win32_capture_streams(const wchar_t *path,
622 size_t path_num_chars,
623 struct wim_inode *inode,
624 struct wim_lookup_table *lookup_table,
627 WIN32_FIND_STREAM_DATA dat;
632 if (win32func_FindFirstStreamW == NULL)
635 hFind = win32func_FindFirstStreamW(path, FindStreamInfoStandard, &dat, 0);
636 if (hFind == INVALID_HANDLE_VALUE) {
637 err = GetLastError();
639 if (err == ERROR_CALL_NOT_IMPLEMENTED)
642 /* Seems legal for this to return ERROR_HANDLE_EOF on reparse
643 * points and directories */
644 if ((inode->i_attributes &
645 (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
646 && err == ERROR_HANDLE_EOF)
650 if (err == ERROR_ACCESS_DENIED) {
651 /* XXX This maybe should be an error. */
652 WARNING("Failed to look up data streams "
653 "of \"%ls\": Access denied!\n%ls",
654 path, capture_access_denied_msg);
657 ERROR("Failed to look up data streams "
660 return WIMLIB_ERR_READ;
665 ret = win32_capture_stream(path,
671 } while (win32func_FindNextStreamW(hFind, &dat));
672 err = GetLastError();
673 if (err != ERROR_HANDLE_EOF) {
674 ERROR("Win32 API: Error reading data streams from \"%ls\"", path);
676 ret = WIMLIB_ERR_READ;
682 /* FindFirstStreamW() API is not available. Only capture the unnamed
684 if (inode->i_attributes &
685 (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
689 /* Just create our own WIN32_FIND_STREAM_DATA for an unnamed
690 * stream to reduce the code to a call to the
691 * already-implemented win32_capture_stream() */
692 wcscpy(dat.cStreamName, L"::$DATA");
693 dat.StreamSize.QuadPart = file_size;
694 ret = win32_capture_stream(path,
703 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
705 size_t path_num_chars,
706 struct wim_lookup_table *lookup_table,
707 struct wim_inode_table *inode_table,
708 struct sd_set *sd_set,
709 const struct wimlib_capture_config *config,
711 wimlib_progress_func_t progress_func,
712 struct win32_capture_state *state)
714 struct wim_dentry *root = NULL;
715 struct wim_inode *inode;
720 if (exclude_path(path, path_num_chars, config, true)) {
721 if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT) {
722 ERROR("Cannot exclude the root directory from capture");
723 ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
726 if ((add_image_flags & WIMLIB_ADD_IMAGE_FLAG_EXCLUDE_VERBOSE)
729 union wimlib_progress_info info;
730 info.scan.cur_path = path;
731 info.scan.excluded = true;
732 progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
737 if ((add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
740 union wimlib_progress_info info;
741 info.scan.cur_path = path;
742 info.scan.excluded = false;
743 progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
746 HANDLE hFile = win32_open_existing_file(path,
747 FILE_READ_DATA | FILE_READ_ATTRIBUTES);
748 if (hFile == INVALID_HANDLE_VALUE) {
749 err = GetLastError();
750 ERROR("Win32 API: Failed to open \"%ls\"", path);
752 ret = WIMLIB_ERR_OPEN;
756 BY_HANDLE_FILE_INFORMATION file_info;
757 if (!GetFileInformationByHandle(hFile, &file_info)) {
758 err = GetLastError();
759 ERROR("Win32 API: Failed to get file information for \"%ls\"",
762 ret = WIMLIB_ERR_STAT;
763 goto out_close_handle;
766 /* Create a WIM dentry with an associated inode, which may be shared */
767 ret = inode_table_new_dentry(inode_table,
768 path_basename_with_len(path, path_num_chars),
769 ((u64)file_info.nFileIndexHigh << 32) |
770 (u64)file_info.nFileIndexLow,
771 file_info.dwVolumeSerialNumber,
774 goto out_close_handle;
776 ret = win32_get_short_name(root, path);
778 goto out_close_handle;
780 inode = root->d_inode;
782 if (inode->i_nlink > 1) /* Shared inode; nothing more to do */
783 goto out_close_handle;
785 inode->i_attributes = file_info.dwFileAttributes;
786 inode->i_creation_time = FILETIME_to_u64(&file_info.ftCreationTime);
787 inode->i_last_write_time = FILETIME_to_u64(&file_info.ftLastWriteTime);
788 inode->i_last_access_time = FILETIME_to_u64(&file_info.ftLastAccessTime);
789 inode->i_resolved = 1;
791 add_image_flags &= ~(WIMLIB_ADD_IMAGE_FLAG_ROOT | WIMLIB_ADD_IMAGE_FLAG_SOURCE);
793 if (!(add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NO_ACLS)) {
794 ret = win32_get_security_descriptor(root, sd_set, path, state,
797 goto out_close_handle;
800 file_size = ((u64)file_info.nFileSizeHigh << 32) |
801 (u64)file_info.nFileSizeLow;
803 if (inode_is_directory(inode)) {
804 /* Directory (not a reparse point) --- recurse to children */
806 /* But first... directories may have alternate data streams that
807 * need to be captured. */
808 ret = win32_capture_streams(path,
814 goto out_close_handle;
815 ret = win32_recurse_directory(root,
825 } else if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
826 /* Reparse point: save the reparse tag and data. Alternate data
827 * streams are not captured, if it's even possible for a reparse
828 * point to have alternate data streams... */
829 ret = win32_capture_reparse_point(hFile,
834 /* Not a directory, not a reparse point; capture the default
835 * file contents and any alternate data streams. */
836 ret = win32_capture_streams(path,
848 free_dentry_tree(root, lookup_table);
853 win32_do_capture_warnings(const struct win32_capture_state *state,
856 if (state->num_get_sacl_priv_notheld == 0 &&
857 state->num_get_sd_access_denied == 0)
861 WARNING("Built dentry tree successfully, but with the following problem(s):");
862 if (state->num_get_sacl_priv_notheld != 0) {
863 WARNING("Could not capture SACL (System Access Control List)\n"
864 " on %lu files or directories.",
865 state->num_get_sacl_priv_notheld);
867 if (state->num_get_sd_access_denied != 0) {
868 WARNING("Could not capture security descriptor at all\n"
869 " on %lu files or directories.",
870 state->num_get_sd_access_denied);
873 "Try running the program as the Administrator to make sure all the\n"
874 " desired metadata has been captured exactly. However, if you\n"
875 " do not care about capturing security descriptors correctly, then\n"
876 " nothing more needs to be done%ls\n",
877 (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NO_ACLS) ? L"." :
878 L", although you might consider\n"
879 " passing the --no-acls flag to `wimlib-imagex capture' or\n"
880 " `wimlib-imagex append' to explicitly capture no security\n"
884 /* Win32 version of capturing a directory tree */
886 win32_build_dentry_tree(struct wim_dentry **root_ret,
887 const wchar_t *root_disk_path,
888 struct wim_lookup_table *lookup_table,
889 struct wim_inode_table *inode_table,
890 struct sd_set *sd_set,
891 const struct wimlib_capture_config *config,
893 wimlib_progress_func_t progress_func,
899 struct win32_capture_state state;
901 path_nchars = wcslen(root_disk_path);
902 if (path_nchars > 32767)
903 return WIMLIB_ERR_INVALID_PARAM;
905 /* There is no check for overflow later when this buffer is being used!
906 * But the max path length on NTFS is 32767 characters, and paths need
907 * to be written specially to even go past 260 characters, so we should
908 * be okay with 32770 characters. */
909 path = MALLOC(32770 * sizeof(wchar_t));
911 return WIMLIB_ERR_NOMEM;
913 wmemcpy(path, root_disk_path, path_nchars + 1);
915 memset(&state, 0, sizeof(state));
916 ret = win32_build_dentry_tree_recursive(root_ret,
928 win32_do_capture_warnings(&state, add_image_flags);
933 win32_set_reparse_data(HANDLE h,
935 const struct wim_lookup_table_entry *lte,
943 WARNING("\"%ls\" is marked as a reparse point but had no reparse data",
947 len = wim_resource_size(lte);
948 if (len > 16 * 1024 - 8) {
949 WARNING("\"%ls\": reparse data too long!", path);
953 /* The WIM stream omits the ReparseTag and ReparseDataLength fields, so
954 * leave 8 bytes of space for them at the beginning of the buffer, then
955 * set them manually. */
956 buf = alloca(len + 8);
957 ret = read_full_wim_resource(lte, buf + 8, 0);
960 *(u32*)(buf + 0) = cpu_to_le32(reparse_tag);
961 *(u16*)(buf + 4) = cpu_to_le16(len);
962 *(u16*)(buf + 6) = 0;
964 /* Set the reparse data on the open file using the
965 * FSCTL_SET_REPARSE_POINT ioctl.
967 * There are contradictions in Microsoft's documentation for this:
969 * "If hDevice was opened without specifying FILE_FLAG_OVERLAPPED,
970 * lpOverlapped is ignored."
972 * --- So setting lpOverlapped to NULL is okay since it's ignored.
974 * "If lpOverlapped is NULL, lpBytesReturned cannot be NULL. Even when an
975 * operation returns no output data and lpOutBuffer is NULL,
976 * DeviceIoControl makes use of lpBytesReturned. After such an
977 * operation, the value of lpBytesReturned is meaningless."
979 * --- So lpOverlapped not really ignored, as it affects another
980 * parameter. This is the actual behavior: lpBytesReturned must be
981 * specified, even though lpBytesReturned is documented as:
983 * "Not used with this operation; set to NULL."
986 if (!DeviceIoControl(h, FSCTL_SET_REPARSE_POINT, buf, len + 8,
988 &bytesReturned /* lpBytesReturned */,
989 NULL /* lpOverlapped */))
991 DWORD err = GetLastError();
992 ERROR("Failed to set reparse data on \"%ls\"", path);
994 return WIMLIB_ERR_WRITE;
1000 win32_set_compressed(HANDLE hFile, const wchar_t *path)
1002 USHORT format = COMPRESSION_FORMAT_DEFAULT;
1003 DWORD bytesReturned = 0;
1004 if (!DeviceIoControl(hFile, FSCTL_SET_COMPRESSION,
1005 &format, sizeof(USHORT),
1007 &bytesReturned, NULL))
1010 DWORD err = GetLastError();
1011 WARNING("Failed to set compression flag on \"%ls\"", path);
1018 win32_set_sparse(HANDLE hFile, const wchar_t *path)
1020 DWORD bytesReturned = 0;
1021 if (!DeviceIoControl(hFile, FSCTL_SET_SPARSE,
1024 &bytesReturned, NULL))
1027 DWORD err = GetLastError();
1028 WARNING("Failed to set sparse flag on \"%ls\"", path);
1035 * Sets the security descriptor on an extracted file.
1038 win32_set_security_data(const struct wim_inode *inode,
1039 const wchar_t *path,
1040 struct apply_args *args)
1042 PSECURITY_DESCRIPTOR descriptor;
1046 descriptor = wim_const_security_data(args->w)->descriptors[inode->i_security_id];
1048 SECURITY_INFORMATION securityInformation = DACL_SECURITY_INFORMATION |
1049 SACL_SECURITY_INFORMATION |
1050 OWNER_SECURITY_INFORMATION |
1051 GROUP_SECURITY_INFORMATION;
1053 if (SetFileSecurityW(path, securityInformation, descriptor))
1055 err = GetLastError();
1056 if (args->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS)
1059 case ERROR_PRIVILEGE_NOT_HELD:
1060 if (securityInformation & SACL_SECURITY_INFORMATION) {
1061 n = args->num_set_sacl_priv_notheld++;
1062 securityInformation &= ~SACL_SECURITY_INFORMATION;
1063 if (n < MAX_SET_SACL_PRIV_NOTHELD_WARNINGS) {
1065 "We don't have enough privileges to set the full security\n"
1066 " descriptor on \"%ls\"!\n", path);
1067 if (args->num_set_sd_access_denied +
1068 args->num_set_sacl_priv_notheld == 1)
1070 WARNING("%ls", apply_access_denied_msg);
1072 WARNING("Re-trying with SACL omitted.\n", path);
1073 } else if (n == MAX_GET_SACL_PRIV_NOTHELD_WARNINGS) {
1075 "Suppressing further 'privileges not held' error messages when setting\n"
1076 " security descriptors.");
1081 case ERROR_INVALID_OWNER:
1082 case ERROR_ACCESS_DENIED:
1083 n = args->num_set_sd_access_denied++;
1084 if (n < MAX_SET_SD_ACCESS_DENIED_WARNINGS) {
1085 WARNING("Failed to set security descriptor on \"%ls\": "
1086 "Access denied!\n", path);
1087 if (args->num_set_sd_access_denied +
1088 args->num_set_sacl_priv_notheld == 1)
1090 WARNING("%ls", apply_access_denied_msg);
1092 } else if (n == MAX_SET_SD_ACCESS_DENIED_WARNINGS) {
1094 "Suppressing further access denied error messages when setting\n"
1095 " security descriptors");
1100 ERROR("Failed to set security descriptor on \"%ls\"", path);
1102 return WIMLIB_ERR_WRITE;
1108 win32_extract_chunk(const void *buf, size_t len, u64 offset, void *arg)
1110 HANDLE hStream = arg;
1112 DWORD nbytes_written;
1113 wimlib_assert(len <= 0xffffffff);
1115 if (!WriteFile(hStream, buf, len, &nbytes_written, NULL) ||
1116 nbytes_written != len)
1118 DWORD err = GetLastError();
1119 ERROR("WriteFile(): write error");
1121 return WIMLIB_ERR_WRITE;
1127 do_win32_extract_stream(HANDLE hStream, struct wim_lookup_table_entry *lte)
1129 return extract_wim_resource(lte, wim_resource_size(lte),
1130 win32_extract_chunk, hStream);
1134 path_is_root_of_drive(const wchar_t *path)
1139 if (*path != L'/' && *path != L'\\') {
1140 if (*(path + 1) == L':')
1145 while (*path == L'/' || *path == L'\\')
1147 return (*path == L'\0');
1151 win32_get_create_flags_and_attributes(DWORD i_attributes)
1156 * Some attributes cannot be set by passing them to CreateFile(). In
1159 * FILE_ATTRIBUTE_DIRECTORY:
1160 * CreateDirectory() must be called instead of CreateFile().
1162 * FILE_ATTRIBUTE_SPARSE_FILE:
1164 * See: win32_set_sparse().
1166 * FILE_ATTRIBUTE_COMPRESSED:
1167 * Not clear from the documentation, but apparently this needs an
1169 * See: win32_set_compressed().
1171 * FILE_ATTRIBUTE_REPARSE_POINT:
1172 * Needs an ioctl, with the reparse data specified.
1173 * See: win32_set_reparse_data().
1175 * In addition, clear any file flags in the attributes that we don't
1176 * want, but also specify FILE_FLAG_OPEN_REPARSE_POINT and
1177 * FILE_FLAG_BACKUP_SEMANTICS as we are a backup application.
1179 attributes = i_attributes & ~(FILE_ATTRIBUTE_SPARSE_FILE |
1180 FILE_ATTRIBUTE_COMPRESSED |
1181 FILE_ATTRIBUTE_REPARSE_POINT |
1182 FILE_ATTRIBUTE_DIRECTORY |
1183 FILE_FLAG_DELETE_ON_CLOSE |
1184 FILE_FLAG_NO_BUFFERING |
1185 FILE_FLAG_OPEN_NO_RECALL |
1186 FILE_FLAG_OVERLAPPED |
1187 FILE_FLAG_RANDOM_ACCESS |
1188 /*FILE_FLAG_SESSION_AWARE |*/
1189 FILE_FLAG_SEQUENTIAL_SCAN |
1190 FILE_FLAG_WRITE_THROUGH);
1192 FILE_FLAG_OPEN_REPARSE_POINT |
1193 FILE_FLAG_BACKUP_SEMANTICS;
1197 inode_has_special_attributes(const struct wim_inode *inode)
1199 return (inode->i_attributes & (FILE_ATTRIBUTE_COMPRESSED |
1200 FILE_ATTRIBUTE_REPARSE_POINT |
1201 FILE_ATTRIBUTE_SPARSE_FILE)) != 0;
1205 win32_set_special_attributes(HANDLE hFile, const struct wim_inode *inode,
1206 struct wim_lookup_table_entry *unnamed_stream_lte,
1207 const wchar_t *path)
1211 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1212 DEBUG("Setting reparse data on \"%ls\"", path);
1213 ret = win32_set_reparse_data(hFile, inode->i_reparse_tag,
1214 unnamed_stream_lte, path);
1219 if (inode->i_attributes & FILE_ATTRIBUTE_COMPRESSED) {
1220 DEBUG("Setting compression flag on \"%ls\"", path);
1221 ret = win32_set_compressed(hFile, path);
1226 if (inode->i_attributes & FILE_ATTRIBUTE_SPARSE_FILE) {
1227 DEBUG("Setting sparse flag on \"%ls\"", path);
1228 ret = win32_set_sparse(hFile, path);
1236 win32_extract_stream(const struct wim_inode *inode,
1237 const wchar_t *path,
1238 const wchar_t *stream_name_utf16,
1239 struct wim_lookup_table_entry *lte)
1241 wchar_t *stream_path;
1245 DWORD creationDisposition = CREATE_ALWAYS;
1247 if (stream_name_utf16) {
1248 /* Named stream. Create a buffer that contains the UTF-16LE
1249 * string [.\]@path:@stream_name_utf16. This is needed to
1250 * create and open the stream using CreateFileW(). I'm not
1251 * aware of any other APIs to do this. Note: the '$DATA' suffix
1252 * seems to be unneeded. Additional note: a "./" prefix needs
1253 * to be added when the path is not absolute to avoid ambiguity
1254 * with drive letters. */
1255 size_t stream_path_nchars;
1257 size_t stream_name_nchars;
1258 const wchar_t *prefix;
1260 path_nchars = wcslen(path);
1261 stream_name_nchars = wcslen(stream_name_utf16);
1262 stream_path_nchars = path_nchars + 1 + stream_name_nchars;
1263 if (path[0] != cpu_to_le16(L'\0') &&
1264 path[0] != cpu_to_le16(L'/') &&
1265 path[0] != cpu_to_le16(L'\\') &&
1266 path[1] != cpu_to_le16(L':'))
1269 stream_path_nchars += 2;
1273 stream_path = alloca((stream_path_nchars + 1) * sizeof(wchar_t));
1274 swprintf(stream_path, L"%ls%ls:%ls",
1275 prefix, path, stream_name_utf16);
1277 /* Unnamed stream; its path is just the path to the file itself.
1279 stream_path = (wchar_t*)path;
1281 /* Directories must be created with CreateDirectoryW(). Then
1282 * the call to CreateFileW() will merely open the directory that
1283 * was already created rather than creating a new file. */
1284 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1285 if (!CreateDirectoryW(stream_path, NULL)) {
1286 err = GetLastError();
1288 case ERROR_ALREADY_EXISTS:
1290 case ERROR_ACCESS_DENIED:
1291 if (path_is_root_of_drive(path))
1295 ERROR("Failed to create directory \"%ls\"",
1298 ret = WIMLIB_ERR_MKDIR;
1302 DEBUG("Created directory \"%ls\"", stream_path);
1303 if (!inode_has_special_attributes(inode)) {
1307 creationDisposition = OPEN_EXISTING;
1311 DEBUG("Opening \"%ls\"", stream_path);
1312 h = CreateFileW(stream_path,
1313 GENERIC_READ | GENERIC_WRITE,
1316 creationDisposition,
1317 win32_get_create_flags_and_attributes(inode->i_attributes),
1319 if (h == INVALID_HANDLE_VALUE) {
1320 err = GetLastError();
1321 ERROR("Failed to create \"%ls\"", stream_path);
1323 ret = WIMLIB_ERR_OPEN;
1327 if (stream_name_utf16 == NULL && inode_has_special_attributes(inode)) {
1328 ret = win32_set_special_attributes(h, inode, lte, path);
1330 goto fail_close_handle;
1333 if (!(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
1335 DEBUG("Extracting \"%ls\" (len = %"PRIu64")",
1336 stream_path, wim_resource_size(lte));
1337 ret = do_win32_extract_stream(h, lte);
1339 goto fail_close_handle;
1343 DEBUG("Closing \"%ls\"", stream_path);
1344 if (!CloseHandle(h)) {
1345 err = GetLastError();
1346 ERROR("Failed to close \"%ls\"", stream_path);
1348 ret = WIMLIB_ERR_WRITE;
1356 ERROR("Error extracting %ls", stream_path);
1362 * Creates a file, directory, or reparse point and extracts all streams to it
1363 * (unnamed data stream and/or reparse point stream, plus any alternate data
1364 * streams). This in Win32-specific code.
1366 * @inode: WIM inode for this file or directory.
1367 * @path: UTF-16LE external path to extract the inode to.
1369 * Returns 0 on success; nonzero on failure.
1372 win32_extract_streams(const struct wim_inode *inode,
1373 const wchar_t *path, u64 *completed_bytes_p)
1375 struct wim_lookup_table_entry *unnamed_lte;
1378 unnamed_lte = inode_unnamed_lte_resolved(inode);
1379 ret = win32_extract_stream(inode, path, NULL, unnamed_lte);
1383 *completed_bytes_p += wim_resource_size(unnamed_lte);
1384 for (u16 i = 0; i < inode->i_num_ads; i++) {
1385 const struct wim_ads_entry *ads_entry = &inode->i_ads_entries[i];
1386 if (ads_entry->stream_name_nbytes != 0) {
1387 /* Skip special UNIX data entries (see documentation for
1388 * WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA) */
1389 if (ads_entry->stream_name_nbytes == WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES
1390 && !memcmp(ads_entry->stream_name,
1391 WIMLIB_UNIX_DATA_TAG_UTF16LE,
1392 WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES))
1394 ret = win32_extract_stream(inode,
1396 ads_entry->stream_name,
1401 *completed_bytes_p += wim_resource_size(ads_entry->lte);
1408 /* Extract a file, directory, reparse point, or hard link to an
1409 * already-extracted file using the Win32 API */
1411 win32_do_apply_dentry(const wchar_t *output_path,
1412 size_t output_path_num_chars,
1413 struct wim_dentry *dentry,
1414 struct apply_args *args)
1417 struct wim_inode *inode = dentry->d_inode;
1420 if (inode->i_nlink > 1 && inode->i_extracted_file != NULL) {
1421 /* Linked file, with another name already extracted. Create a
1423 DEBUG("Creating hard link \"%ls => %ls\"",
1424 output_path, inode->i_extracted_file);
1425 if (!CreateHardLinkW(output_path, inode->i_extracted_file, NULL)) {
1426 err = GetLastError();
1427 ERROR("Can't create hard link \"%ls => %ls\"",
1428 output_path, inode->i_extracted_file);
1430 return WIMLIB_ERR_LINK;
1433 /* Create the file, directory, or reparse point, and extract the
1435 ret = win32_extract_streams(inode, output_path,
1436 &args->progress.extract.completed_bytes);
1440 if (inode->i_security_id >= 0 &&
1441 !(args->extract_flags & WIMLIB_EXTRACT_FLAG_NO_ACLS))
1443 ret = win32_set_security_data(inode, output_path, args);
1447 if (inode->i_nlink > 1) {
1448 /* Save extracted path for a later call to
1449 * CreateHardLinkW() if this inode has multiple links.
1451 inode->i_extracted_file = WSTRDUP(output_path);
1452 if (!inode->i_extracted_file)
1453 ret = WIMLIB_ERR_NOMEM;
1459 /* Set timestamps on an extracted file using the Win32 API */
1461 win32_do_apply_dentry_timestamps(const wchar_t *path,
1462 size_t path_num_chars,
1463 const struct wim_dentry *dentry,
1464 const struct apply_args *args)
1468 const struct wim_inode *inode = dentry->d_inode;
1470 DEBUG("Opening \"%ls\" to set timestamps", path);
1471 h = win32_open_existing_file(path, FILE_WRITE_ATTRIBUTES);
1472 if (h == INVALID_HANDLE_VALUE) {
1473 err = GetLastError();
1477 FILETIME creationTime = {.dwLowDateTime = inode->i_creation_time & 0xffffffff,
1478 .dwHighDateTime = inode->i_creation_time >> 32};
1479 FILETIME lastAccessTime = {.dwLowDateTime = inode->i_last_access_time & 0xffffffff,
1480 .dwHighDateTime = inode->i_last_access_time >> 32};
1481 FILETIME lastWriteTime = {.dwLowDateTime = inode->i_last_write_time & 0xffffffff,
1482 .dwHighDateTime = inode->i_last_write_time >> 32};
1484 DEBUG("Calling SetFileTime() on \"%ls\"", path);
1485 if (!SetFileTime(h, &creationTime, &lastAccessTime, &lastWriteTime)) {
1486 err = GetLastError();
1490 DEBUG("Closing \"%ls\"", path);
1491 if (!CloseHandle(h)) {
1492 err = GetLastError();
1497 /* Only warn if setting timestamps failed; still return 0. */
1498 WARNING("Can't set timestamps on \"%ls\"", path);
1504 /* Replacement for POSIX fsync() */
1511 h = (HANDLE)_get_osfhandle(fd);
1512 if (h == INVALID_HANDLE_VALUE) {
1513 err = GetLastError();
1514 ERROR("Could not get Windows handle for file descriptor");
1519 if (!FlushFileBuffers(h)) {
1520 err = GetLastError();
1521 ERROR("Could not flush file buffers to disk");
1529 /* Use the Win32 API to get the number of processors */
1531 win32_get_number_of_processors()
1533 SYSTEM_INFO sysinfo;
1534 GetSystemInfo(&sysinfo);
1535 return sysinfo.dwNumberOfProcessors;
1538 /* Replacement for POSIX-2008 realpath(). Warning: partial functionality only
1539 * (resolved_path must be NULL). Also I highly doubt that GetFullPathName
1540 * really does the right thing under all circumstances. */
1542 realpath(const wchar_t *path, wchar_t *resolved_path)
1545 wimlib_assert(resolved_path == NULL);
1548 ret = GetFullPathNameW(path, 0, NULL, NULL);
1550 err = GetLastError();
1554 resolved_path = TMALLOC(ret);
1557 ret = GetFullPathNameW(path, ret, resolved_path, NULL);
1559 err = GetLastError();
1560 free(resolved_path);
1561 resolved_path = NULL;
1569 return resolved_path;
1572 /* rename() on Windows fails if the destination file exists. And we need to
1573 * make it work on wide characters. Fix it. */
1575 win32_rename_replacement(const wchar_t *oldpath, const wchar_t *newpath)
1577 if (MoveFileExW(oldpath, newpath, MOVEFILE_REPLACE_EXISTING)) {
1580 /* As usual, the possible error values are not documented */
1581 DWORD err = GetLastError();
1582 ERROR("MoveFileEx(): Can't rename \"%ls\" to \"%ls\"",
1590 /* Replacement for POSIX fnmatch() (partial functionality only) */
1592 fnmatch(const wchar_t *pattern, const wchar_t *string, int flags)
1594 if (PathMatchSpecW(string, pattern))
1600 /* truncate() replacement */
1602 win32_truncate_replacement(const wchar_t *path, off_t size)
1604 DWORD err = NO_ERROR;
1605 LARGE_INTEGER liOffset;
1607 HANDLE h = win32_open_existing_file(path, GENERIC_WRITE);
1608 if (h == INVALID_HANDLE_VALUE)
1611 liOffset.QuadPart = size;
1612 if (!SetFilePointerEx(h, liOffset, NULL, FILE_BEGIN))
1613 goto fail_close_handle;
1615 if (!SetEndOfFile(h))
1616 goto fail_close_handle;
1621 err = GetLastError();
1624 if (err == NO_ERROR)
1625 err = GetLastError();
1626 ERROR("Can't truncate \"%ls\" to %"PRIu64" bytes", path, size);
1633 /* This really could be replaced with _wcserror_s, but this doesn't seem to
1634 * actually be available in MSVCRT.DLL on Windows XP (perhaps it's statically
1635 * linked in by Visual Studio...?). */
1637 win32_strerror_r_replacement(int errnum, wchar_t *buf, size_t buflen)
1639 static pthread_mutex_t strerror_lock = PTHREAD_MUTEX_INITIALIZER;
1641 pthread_mutex_lock(&strerror_lock);
1642 mbstowcs(buf, strerror(errnum), buflen);
1643 buf[buflen - 1] = '\0';
1644 pthread_mutex_unlock(&strerror_lock);
1648 #endif /* __WIN32__ */