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 /* Pointers to functions that are not available on all targetted versions of
57 * Windows (XP and later). NOTE: The WINAPI annotations seem to be important; I
58 * assume it specifies a certain calling convention. */
61 static HANDLE (WINAPI *win32func_FindFirstStreamW)(LPCWSTR lpFileName,
62 STREAM_INFO_LEVELS InfoLevel,
63 LPVOID lpFindStreamData,
64 DWORD dwFlags) = NULL;
67 static BOOL (WINAPI *win32func_FindNextStreamW)(HANDLE hFindStream,
68 LPVOID lpFindStreamData) = NULL;
70 static HMODULE hKernel32 = NULL;
72 /* Try to dynamically load some functions */
78 if (hKernel32 == NULL) {
79 DEBUG("Loading Kernel32.dll");
80 hKernel32 = LoadLibraryW(L"Kernel32.dll");
81 if (hKernel32 == NULL) {
83 WARNING("Can't load Kernel32.dll");
89 DEBUG("Looking for FindFirstStreamW");
90 win32func_FindFirstStreamW = (void*)GetProcAddress(hKernel32, "FindFirstStreamW");
91 if (!win32func_FindFirstStreamW) {
92 WARNING("Could not find function FindFirstStreamW() in Kernel32.dll!");
93 WARNING("Capturing alternate data streams will not be supported.");
97 DEBUG("Looking for FindNextStreamW");
98 win32func_FindNextStreamW = (void*)GetProcAddress(hKernel32, "FindNextStreamW");
99 if (!win32func_FindNextStreamW) {
100 WARNING("Could not find function FindNextStreamW() in Kernel32.dll!");
101 WARNING("Capturing alternate data streams will not be supported.");
102 win32func_FindFirstStreamW = NULL;
107 win32_global_cleanup()
109 if (hKernel32 != NULL) {
110 DEBUG("Closing Kernel32.dll");
111 FreeLibrary(hKernel32);
116 static const wchar_t *capture_access_denied_msg =
117 L" If you are not running this program as the administrator, you may\n"
118 " need to do so, so that all data and metadata can be backed up.\n"
119 " Otherwise, there may be no way to access the desired data or\n"
120 " metadata without taking ownership of the file or directory.\n"
123 static const wchar_t *apply_access_denied_msg =
124 L"If you are not running this program as the administrator, you may\n"
125 " need to do so, so that all data and metadata can be extracted\n"
126 " exactly as the origignal copy. However, if you do not care that\n"
127 " the security descriptors are extracted correctly, you could run\n"
128 " `wimlib-imagex apply' with the --no-acls flag instead.\n"
131 #ifdef ENABLE_ERROR_MESSAGES
133 win32_error(u32 err_code)
137 nchars = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
138 FORMAT_MESSAGE_ALLOCATE_BUFFER,
140 (wchar_t*)&buffer, 0, NULL);
142 ERROR("Error printing error message! "
143 "Computer will self-destruct in 3 seconds.");
145 ERROR("Win32 error: %ls", buffer);
153 win32_error(GetLastError());
158 win32_open_existing_file(const wchar_t *path, DWORD dwDesiredAccess)
160 return CreateFileW(path,
163 NULL, /* lpSecurityAttributes */
165 FILE_FLAG_BACKUP_SEMANTICS |
166 FILE_FLAG_OPEN_REPARSE_POINT,
167 NULL /* hTemplateFile */);
171 win32_open_file_data_only(const wchar_t *path)
173 return win32_open_existing_file(path, FILE_READ_DATA);
177 win32_read_file(const wchar_t *filename,
178 void *handle, u64 offset, size_t size, void *buf)
183 LARGE_INTEGER liOffset = {.QuadPart = offset};
185 wimlib_assert(size <= 0xffffffff);
187 if (SetFilePointerEx(h, liOffset, NULL, FILE_BEGIN))
188 if (ReadFile(h, buf, size, &bytesRead, NULL) && bytesRead == size)
190 err = GetLastError();
191 ERROR("Error reading \"%ls\"", filename);
193 return WIMLIB_ERR_READ;
197 win32_close_file(void *handle)
199 CloseHandle((HANDLE)handle);
203 FILETIME_to_u64(const FILETIME *ft)
205 return ((u64)ft->dwHighDateTime << 32) | (u64)ft->dwLowDateTime;
209 win32_get_short_name(struct wim_dentry *dentry, const wchar_t *path)
211 WIN32_FIND_DATAW dat;
212 if (FindFirstFileW(path, &dat) && dat.cAlternateFileName[0] != L'\0') {
213 size_t short_name_nbytes = wcslen(dat.cAlternateFileName) *
215 size_t n = short_name_nbytes + sizeof(wchar_t);
216 dentry->short_name = MALLOC(n);
217 if (!dentry->short_name)
218 return WIMLIB_ERR_NOMEM;
219 memcpy(dentry->short_name, dat.cAlternateFileName, n);
220 dentry->short_name_nbytes = short_name_nbytes;
222 /* If we can't read the short filename for some reason, we just ignore
223 * the error and assume the file has no short name. I don't think this
224 * should be an issue, since the short names are essentially obsolete
230 win32_get_security_descriptor(struct wim_dentry *dentry,
231 struct sd_set *sd_set,
233 struct win32_capture_state *state,
236 SECURITY_INFORMATION requestedInformation;
242 requestedInformation = DACL_SECURITY_INFORMATION |
243 SACL_SECURITY_INFORMATION |
244 OWNER_SECURITY_INFORMATION |
245 GROUP_SECURITY_INFORMATION;
247 /* Request length of security descriptor */
248 status = GetFileSecurityW(path, requestedInformation,
249 NULL, 0, &lenNeeded);
250 err = GetLastError();
251 if (!status && err == ERROR_INSUFFICIENT_BUFFER) {
252 DWORD len = lenNeeded;
254 if (GetFileSecurityW(path, requestedInformation,
255 (PSECURITY_DESCRIPTOR)buf, len, &lenNeeded))
257 int security_id = sd_set_add_sd(sd_set, buf, len);
259 return WIMLIB_ERR_NOMEM;
261 dentry->d_inode->i_security_id = security_id;
265 err = GetLastError();
269 if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_STRICT_ACLS)
273 case ERROR_PRIVILEGE_NOT_HELD:
274 if (requestedInformation & SACL_SECURITY_INFORMATION) {
275 n = state->num_get_sacl_priv_notheld++;
276 requestedInformation &= ~SACL_SECURITY_INFORMATION;
277 if (n < MAX_GET_SACL_PRIV_NOTHELD_WARNINGS) {
279 "We don't have enough privileges to read the full security\n"
280 " descriptor of \"%ls\"!\n"
281 " Re-trying with SACL omitted.\n", path);
282 } else if (n == MAX_GET_SACL_PRIV_NOTHELD_WARNINGS) {
284 "Suppressing further privileges not held error messages when reading\n"
285 " security descriptors.");
290 case ERROR_ACCESS_DENIED:
291 n = state->num_get_sd_access_denied++;
292 if (n < MAX_GET_SD_ACCESS_DENIED_WARNINGS) {
293 WARNING("Failed to read security descriptor of \"%ls\": "
294 "Access denied!\n%ls", path, capture_access_denied_msg);
295 } else if (n == MAX_GET_SD_ACCESS_DENIED_WARNINGS) {
296 WARNING("Suppressing further access denied errors messages i"
297 "when reading security descriptors");
302 ERROR("Failed to read security descriptor of \"%ls\"", path);
304 return WIMLIB_ERR_READ;
309 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
311 size_t path_num_chars,
312 struct wim_lookup_table *lookup_table,
313 struct wim_inode_table *inode_table,
314 struct sd_set *sd_set,
315 const struct wimlib_capture_config *config,
317 wimlib_progress_func_t progress_func,
318 struct win32_capture_state *state);
320 /* Reads the directory entries of directory using a Win32 API and recursively
321 * calls win32_build_dentry_tree() on them. */
323 win32_recurse_directory(struct wim_dentry *root,
325 size_t dir_path_num_chars,
326 struct wim_lookup_table *lookup_table,
327 struct wim_inode_table *inode_table,
328 struct sd_set *sd_set,
329 const struct wimlib_capture_config *config,
331 wimlib_progress_func_t progress_func,
332 struct win32_capture_state *state)
334 WIN32_FIND_DATAW dat;
339 /* Begin reading the directory by calling FindFirstFileW. Unlike UNIX
340 * opendir(), FindFirstFileW has file globbing built into it. But this
341 * isn't what we actually want, so just add a dummy glob to get all
343 dir_path[dir_path_num_chars] = L'/';
344 dir_path[dir_path_num_chars + 1] = L'*';
345 dir_path[dir_path_num_chars + 2] = L'\0';
346 hFind = FindFirstFileW(dir_path, &dat);
347 dir_path[dir_path_num_chars] = L'\0';
349 if (hFind == INVALID_HANDLE_VALUE) {
350 err = GetLastError();
351 if (err == ERROR_FILE_NOT_FOUND) {
354 ERROR("Failed to read directory \"%ls\"", dir_path);
356 return WIMLIB_ERR_READ;
361 /* Skip . and .. entries */
362 if (dat.cFileName[0] == L'.' &&
363 (dat.cFileName[1] == L'\0' ||
364 (dat.cFileName[1] == L'.' &&
365 dat.cFileName[2] == L'\0')))
367 size_t filename_len = wcslen(dat.cFileName);
369 dir_path[dir_path_num_chars] = L'/';
370 wmemcpy(dir_path + dir_path_num_chars + 1,
374 struct wim_dentry *child;
375 size_t path_len = dir_path_num_chars + 1 + filename_len;
376 ret = win32_build_dentry_tree_recursive(&child,
386 dir_path[dir_path_num_chars] = L'\0';
390 dentry_add_child(root, child);
391 } while (FindNextFileW(hFind, &dat));
392 err = GetLastError();
393 if (err != ERROR_NO_MORE_FILES) {
394 ERROR("Failed to read directory \"%ls\"", dir_path);
397 ret = WIMLIB_ERR_READ;
404 /* Load a reparse point into a WIM inode. It is just stored in memory.
406 * @hFile: Open handle to a reparse point, with permission to read the reparse
409 * @inode: WIM inode for the reparse point.
411 * @lookup_table: Stream lookup table for the WIM; an entry will be added to it
412 * for the reparse point unless an entry already exists for
413 * the exact same data stream.
415 * @path: External path to the reparse point. Used for error messages only.
417 * Returns 0 on success; nonzero on failure. */
419 win32_capture_reparse_point(HANDLE hFile,
420 struct wim_inode *inode,
421 struct wim_lookup_table *lookup_table,
424 /* "Reparse point data, including the tag and optional GUID,
425 * cannot exceed 16 kilobytes." - MSDN */
426 char reparse_point_buf[16 * 1024];
429 if (!DeviceIoControl(hFile, FSCTL_GET_REPARSE_POINT,
430 NULL, /* "Not used with this operation; set to NULL" */
431 0, /* "Not used with this operation; set to 0" */
432 reparse_point_buf, /* "A pointer to a buffer that
433 receives the reparse point data */
434 sizeof(reparse_point_buf), /* "The size of the output
439 DWORD err = GetLastError();
440 ERROR("Failed to get reparse data of \"%ls\"", path);
442 return WIMLIB_ERR_READ;
444 if (bytesReturned < 8) {
445 ERROR("Reparse data on \"%ls\" is invalid", path);
446 return WIMLIB_ERR_READ;
448 inode->i_reparse_tag = le32_to_cpu(*(u32*)reparse_point_buf);
449 return inode_add_ads_with_data(inode, L"",
450 reparse_point_buf + 8,
451 bytesReturned - 8, lookup_table);
454 /* Calculate the SHA1 message digest of a Win32 data stream, which may be either
455 * an unnamed or named data stream.
457 * @path: Path to the file, with the stream noted at the end for named
458 * streams. UTF-16LE encoding.
460 * @hash: On success, the SHA1 message digest of the stream is written to
463 * Returns 0 on success; nonzero on failure.
466 win32_sha1sum(const wchar_t *path, u8 hash[SHA1_HASH_SIZE])
474 hFile = win32_open_file_data_only(path);
475 if (hFile == INVALID_HANDLE_VALUE)
476 return WIMLIB_ERR_OPEN;
480 if (!ReadFile(hFile, buf, sizeof(buf), &bytesRead, NULL)) {
481 ret = WIMLIB_ERR_READ;
482 goto out_close_handle;
486 sha1_update(&ctx, buf, bytesRead);
489 sha1_final(hash, &ctx);
495 /* Scans an unnamed or named stream of a Win32 file (not a reparse point
496 * stream); calculates its SHA1 message digest and either creates a `struct
497 * wim_lookup_table_entry' in memory for it, or uses an existing 'struct
498 * wim_lookup_table_entry' for an identical stream.
500 * @path: Path to the file (UTF-16LE).
502 * @path_num_chars: Number of 2-byte characters in @path.
504 * @inode: WIM inode to save the stream into.
506 * @lookup_table: Stream lookup table for the WIM.
508 * @dat: A `WIN32_FIND_STREAM_DATA' structure that specifies the
511 * Returns 0 on success; nonzero on failure.
514 win32_capture_stream(const wchar_t *path,
515 size_t path_num_chars,
516 struct wim_inode *inode,
517 struct wim_lookup_table *lookup_table,
518 WIN32_FIND_STREAM_DATA *dat)
520 struct wim_ads_entry *ads_entry;
521 u8 hash[SHA1_HASH_SIZE];
522 struct wim_lookup_table_entry *lte;
524 wchar_t *stream_name, *colon;
525 size_t stream_name_nchars;
526 bool is_named_stream;
530 size_t spath_buf_nbytes;
531 const wchar_t *relpath_prefix;
532 const wchar_t *colonchar;
534 /* The stream name should be returned as :NAME:TYPE */
535 stream_name = dat->cStreamName;
536 if (*stream_name != L':')
537 goto out_invalid_stream_name;
539 colon = wcschr(stream_name, L':');
541 goto out_invalid_stream_name;
543 if (wcscmp(colon + 1, L"$DATA")) {
544 /* Not a DATA stream */
551 stream_name_nchars = colon - stream_name;
552 is_named_stream = (stream_name_nchars != 0);
554 if (is_named_stream) {
555 /* Allocate an ADS entry for the named stream. */
556 ads_entry = inode_add_ads_utf16le(inode, stream_name,
557 stream_name_nchars * sizeof(wchar_t));
559 ret = WIMLIB_ERR_NOMEM;
564 /* Create a UTF-16LE string @spath that gives the filename, then a
565 * colon, then the stream name. Or, if it's an unnamed stream, just the
566 * filename. It is MALLOC()'ed so that it can be saved in the
567 * wim_lookup_table_entry if needed.
569 * As yet another special case, relative paths need to be changed to
570 * begin with an explicit "./" so that, for example, a file t:ads, where
571 * :ads is the part we added, is not interpreted as a file on the t:
573 spath_nchars = path_num_chars;
574 relpath_prefix = L"";
576 if (is_named_stream) {
577 spath_nchars += 1 + stream_name_nchars;
579 if (path_num_chars == 1 &&
584 relpath_prefix = L"./";
588 spath_buf_nbytes = (spath_nchars + 1) * sizeof(wchar_t);
589 spath = MALLOC(spath_buf_nbytes);
591 swprintf(spath, L"%ls%ls%ls%ls",
592 relpath_prefix, path, colonchar, stream_name);
594 ret = win32_sha1sum(spath, hash);
596 err = GetLastError();
597 ERROR("Failed to read \"%ls\" to calculate SHA1sum", spath);
602 lte = __lookup_resource(lookup_table, hash);
604 /* Use existing wim_lookup_table_entry that has the same SHA1
608 /* Make a new wim_lookup_table_entry */
609 lte = new_lookup_table_entry();
611 ret = WIMLIB_ERR_NOMEM;
614 lte->file_on_disk = spath;
615 lte->win32_file_on_disk_fp = INVALID_HANDLE_VALUE;
617 lte->resource_location = RESOURCE_WIN32;
618 lte->resource_entry.original_size = (uint64_t)dat->StreamSize.QuadPart;
619 lte->resource_entry.size = (uint64_t)dat->StreamSize.QuadPart;
620 copy_hash(lte->hash, hash);
621 lookup_table_insert(lookup_table, lte);
624 ads_entry->lte = lte;
631 out_invalid_stream_name:
632 ERROR("Invalid stream name: \"%ls:%ls\"", path, dat->cStreamName);
633 ret = WIMLIB_ERR_READ;
637 /* Scans a Win32 file for unnamed and named data streams (not reparse point
640 * @path: Path to the file (UTF-16LE).
642 * @path_num_chars: Number of 2-byte characters in @path.
644 * @inode: WIM inode to save the stream into.
646 * @lookup_table: Stream lookup table for the WIM.
648 * @file_size: Size of unnamed data stream. (Used only if alternate
649 * data streams API appears to be unavailable.)
651 * Returns 0 on success; nonzero on failure.
654 win32_capture_streams(const wchar_t *path,
655 size_t path_num_chars,
656 struct wim_inode *inode,
657 struct wim_lookup_table *lookup_table,
660 WIN32_FIND_STREAM_DATA dat;
665 if (win32func_FindFirstStreamW == NULL)
668 hFind = win32func_FindFirstStreamW(path, FindStreamInfoStandard, &dat, 0);
669 if (hFind == INVALID_HANDLE_VALUE) {
670 err = GetLastError();
672 if (err == ERROR_CALL_NOT_IMPLEMENTED)
675 /* Seems legal for this to return ERROR_HANDLE_EOF on reparse
676 * points and directories */
677 if ((inode->i_attributes &
678 (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
679 && err == ERROR_HANDLE_EOF)
683 if (err == ERROR_ACCESS_DENIED) {
684 /* XXX This maybe should be an error. */
685 WARNING("Failed to look up data streams "
686 "of \"%ls\": Access denied!\n%ls",
687 path, capture_access_denied_msg);
690 ERROR("Failed to look up data streams "
693 return WIMLIB_ERR_READ;
698 ret = win32_capture_stream(path,
704 } while (win32func_FindNextStreamW(hFind, &dat));
705 err = GetLastError();
706 if (err != ERROR_HANDLE_EOF) {
707 ERROR("Win32 API: Error reading data streams from \"%ls\"", path);
709 ret = WIMLIB_ERR_READ;
715 /* FindFirstStreamW() API is not available. Only capture the unnamed
717 if (inode->i_attributes &
718 (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
722 /* Just create our own WIN32_FIND_STREAM_DATA for an unnamed
723 * stream to reduce the code to a call to the
724 * already-implemented win32_capture_stream() */
725 wcscpy(dat.cStreamName, L"::$DATA");
726 dat.StreamSize.QuadPart = file_size;
727 ret = win32_capture_stream(path,
736 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
738 size_t path_num_chars,
739 struct wim_lookup_table *lookup_table,
740 struct wim_inode_table *inode_table,
741 struct sd_set *sd_set,
742 const struct wimlib_capture_config *config,
744 wimlib_progress_func_t progress_func,
745 struct win32_capture_state *state)
747 struct wim_dentry *root = NULL;
748 struct wim_inode *inode;
753 if (exclude_path(path, path_num_chars, config, true)) {
754 if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT) {
755 ERROR("Cannot exclude the root directory from capture");
756 ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
759 if ((add_image_flags & WIMLIB_ADD_IMAGE_FLAG_EXCLUDE_VERBOSE)
762 union wimlib_progress_info info;
763 info.scan.cur_path = path;
764 info.scan.excluded = true;
765 progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
770 if ((add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
773 union wimlib_progress_info info;
774 info.scan.cur_path = path;
775 info.scan.excluded = false;
776 progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
779 HANDLE hFile = win32_open_existing_file(path,
780 FILE_READ_DATA | FILE_READ_ATTRIBUTES);
781 if (hFile == INVALID_HANDLE_VALUE) {
782 err = GetLastError();
783 ERROR("Win32 API: Failed to open \"%ls\"", path);
785 ret = WIMLIB_ERR_OPEN;
789 BY_HANDLE_FILE_INFORMATION file_info;
790 if (!GetFileInformationByHandle(hFile, &file_info)) {
791 err = GetLastError();
792 ERROR("Win32 API: Failed to get file information for \"%ls\"",
795 ret = WIMLIB_ERR_STAT;
796 goto out_close_handle;
799 /* Create a WIM dentry with an associated inode, which may be shared */
800 ret = inode_table_new_dentry(inode_table,
801 path_basename_with_len(path, path_num_chars),
802 ((u64)file_info.nFileIndexHigh << 32) |
803 (u64)file_info.nFileIndexLow,
804 file_info.dwVolumeSerialNumber,
807 goto out_close_handle;
809 ret = win32_get_short_name(root, path);
811 goto out_close_handle;
813 inode = root->d_inode;
815 if (inode->i_nlink > 1) /* Shared inode; nothing more to do */
816 goto out_close_handle;
818 inode->i_attributes = file_info.dwFileAttributes;
819 inode->i_creation_time = FILETIME_to_u64(&file_info.ftCreationTime);
820 inode->i_last_write_time = FILETIME_to_u64(&file_info.ftLastWriteTime);
821 inode->i_last_access_time = FILETIME_to_u64(&file_info.ftLastAccessTime);
822 inode->i_resolved = 1;
824 add_image_flags &= ~(WIMLIB_ADD_IMAGE_FLAG_ROOT | WIMLIB_ADD_IMAGE_FLAG_SOURCE);
826 if (!(add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NO_ACLS)) {
827 ret = win32_get_security_descriptor(root, sd_set, path, state,
830 goto out_close_handle;
833 file_size = ((u64)file_info.nFileSizeHigh << 32) |
834 (u64)file_info.nFileSizeLow;
836 if (inode_is_directory(inode)) {
837 /* Directory (not a reparse point) --- recurse to children */
839 /* But first... directories may have alternate data streams that
840 * need to be captured. */
841 ret = win32_capture_streams(path,
847 goto out_close_handle;
848 ret = win32_recurse_directory(root,
858 } else if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
859 /* Reparse point: save the reparse tag and data. Alternate data
860 * streams are not captured, if it's even possible for a reparse
861 * point to have alternate data streams... */
862 ret = win32_capture_reparse_point(hFile,
867 /* Not a directory, not a reparse point; capture the default
868 * file contents and any alternate data streams. */
869 ret = win32_capture_streams(path,
881 free_dentry_tree(root, lookup_table);
886 win32_do_capture_warnings(const struct win32_capture_state *state,
889 if (state->num_get_sacl_priv_notheld == 0 &&
890 state->num_get_sd_access_denied == 0)
894 WARNING("Built dentry tree successfully, but with the following problem(s):");
895 if (state->num_get_sacl_priv_notheld != 0) {
896 WARNING("Could not capture SACL (System Access Control List)\n"
897 " on %lu files or directories.",
898 state->num_get_sacl_priv_notheld);
900 if (state->num_get_sd_access_denied != 0) {
901 WARNING("Could not capture security descriptor at all\n"
902 " on %lu files or directories.",
903 state->num_get_sd_access_denied);
906 "Try running the program as the Administrator to make sure all the\n"
907 " desired metadata has been captured exactly. However, if you\n"
908 " do not care about capturing security descriptors correctly, then\n"
909 " nothing more needs to be done%ls\n",
910 (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NO_ACLS) ? L"." :
911 L", although you might consider\n"
912 " passing the --no-acls flag to `wimlib-imagex capture' or\n"
913 " `wimlib-imagex append' to explicitly capture no security\n"
917 /* Win32 version of capturing a directory tree */
919 win32_build_dentry_tree(struct wim_dentry **root_ret,
920 const wchar_t *root_disk_path,
921 struct wim_lookup_table *lookup_table,
922 struct wim_inode_table *inode_table,
923 struct sd_set *sd_set,
924 const struct wimlib_capture_config *config,
926 wimlib_progress_func_t progress_func,
932 struct win32_capture_state state;
934 path_nchars = wcslen(root_disk_path);
935 if (path_nchars > 32767)
936 return WIMLIB_ERR_INVALID_PARAM;
938 /* There is no check for overflow later when this buffer is being used!
939 * But the max path length on NTFS is 32767 characters, and paths need
940 * to be written specially to even go past 260 characters, so we should
941 * be okay with 32770 characters. */
942 path = MALLOC(32770 * sizeof(wchar_t));
944 return WIMLIB_ERR_NOMEM;
946 wmemcpy(path, root_disk_path, path_nchars + 1);
948 memset(&state, 0, sizeof(state));
949 ret = win32_build_dentry_tree_recursive(root_ret,
961 win32_do_capture_warnings(&state, add_image_flags);
966 win32_set_reparse_data(HANDLE h,
968 const struct wim_lookup_table_entry *lte,
976 WARNING("\"%ls\" is marked as a reparse point but had no reparse data",
980 len = wim_resource_size(lte);
981 if (len > 16 * 1024 - 8) {
982 WARNING("\"%ls\": reparse data too long!", path);
986 /* The WIM stream omits the ReparseTag and ReparseDataLength fields, so
987 * leave 8 bytes of space for them at the beginning of the buffer, then
988 * set them manually. */
989 buf = alloca(len + 8);
990 ret = read_full_wim_resource(lte, buf + 8, 0);
993 *(u32*)(buf + 0) = cpu_to_le32(reparse_tag);
994 *(u16*)(buf + 4) = cpu_to_le16(len);
995 *(u16*)(buf + 6) = 0;
997 /* Set the reparse data on the open file using the
998 * FSCTL_SET_REPARSE_POINT ioctl.
1000 * There are contradictions in Microsoft's documentation for this:
1002 * "If hDevice was opened without specifying FILE_FLAG_OVERLAPPED,
1003 * lpOverlapped is ignored."
1005 * --- So setting lpOverlapped to NULL is okay since it's ignored.
1007 * "If lpOverlapped is NULL, lpBytesReturned cannot be NULL. Even when an
1008 * operation returns no output data and lpOutBuffer is NULL,
1009 * DeviceIoControl makes use of lpBytesReturned. After such an
1010 * operation, the value of lpBytesReturned is meaningless."
1012 * --- So lpOverlapped not really ignored, as it affects another
1013 * parameter. This is the actual behavior: lpBytesReturned must be
1014 * specified, even though lpBytesReturned is documented as:
1016 * "Not used with this operation; set to NULL."
1018 DWORD bytesReturned;
1019 if (!DeviceIoControl(h, FSCTL_SET_REPARSE_POINT, buf, len + 8,
1021 &bytesReturned /* lpBytesReturned */,
1022 NULL /* lpOverlapped */))
1024 DWORD err = GetLastError();
1025 ERROR("Failed to set reparse data on \"%ls\"", path);
1027 return WIMLIB_ERR_WRITE;
1033 * Sets the security descriptor on an extracted file.
1036 win32_set_security_data(const struct wim_inode *inode,
1037 const wchar_t *path,
1038 struct apply_args *args)
1040 PSECURITY_DESCRIPTOR descriptor;
1044 descriptor = wim_const_security_data(args->w)->descriptors[inode->i_security_id];
1046 SECURITY_INFORMATION securityInformation = DACL_SECURITY_INFORMATION |
1047 SACL_SECURITY_INFORMATION |
1048 OWNER_SECURITY_INFORMATION |
1049 GROUP_SECURITY_INFORMATION;
1051 if (SetFileSecurityW(path, securityInformation, descriptor))
1053 err = GetLastError();
1054 if (args->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS)
1057 case ERROR_PRIVILEGE_NOT_HELD:
1058 if (securityInformation & SACL_SECURITY_INFORMATION) {
1059 n = args->num_set_sacl_priv_notheld++;
1060 securityInformation &= ~SACL_SECURITY_INFORMATION;
1061 if (n < MAX_SET_SACL_PRIV_NOTHELD_WARNINGS) {
1063 "We don't have enough privileges to set the full security\n"
1064 " descriptor on \"%ls\"!\n", path);
1065 if (args->num_set_sd_access_denied +
1066 args->num_set_sacl_priv_notheld == 1)
1068 WARNING("%ls", apply_access_denied_msg);
1070 WARNING("Re-trying with SACL omitted.\n", path);
1071 } else if (n == MAX_GET_SACL_PRIV_NOTHELD_WARNINGS) {
1073 "Suppressing further 'privileges not held' error messages when setting\n"
1074 " security descriptors.");
1079 case ERROR_INVALID_OWNER:
1080 case ERROR_ACCESS_DENIED:
1081 n = args->num_set_sd_access_denied++;
1082 if (n < MAX_SET_SD_ACCESS_DENIED_WARNINGS) {
1083 WARNING("Failed to set security descriptor on \"%ls\": "
1084 "Access denied!\n", path);
1085 if (args->num_set_sd_access_denied +
1086 args->num_set_sacl_priv_notheld == 1)
1088 WARNING("%ls", apply_access_denied_msg);
1090 } else if (n == MAX_SET_SD_ACCESS_DENIED_WARNINGS) {
1092 "Suppressing further access denied error messages when setting\n"
1093 " security descriptors");
1098 ERROR("Failed to set security descriptor on \"%ls\"", path);
1100 return WIMLIB_ERR_WRITE;
1106 win32_extract_chunk(const void *buf, size_t len, u64 offset, void *arg)
1108 HANDLE hStream = arg;
1110 DWORD nbytes_written;
1111 wimlib_assert(len <= 0xffffffff);
1113 if (!WriteFile(hStream, buf, len, &nbytes_written, NULL) ||
1114 nbytes_written != len)
1116 DWORD err = GetLastError();
1117 ERROR("WriteFile(): write error");
1119 return WIMLIB_ERR_WRITE;
1125 do_win32_extract_stream(HANDLE hStream, struct wim_lookup_table_entry *lte)
1127 return extract_wim_resource(lte, wim_resource_size(lte),
1128 win32_extract_chunk, hStream);
1132 path_is_root_of_drive(const wchar_t *path)
1137 if (*path != L'/' && *path != L'\\') {
1138 if (*(path + 1) == L':')
1143 while (*path == L'/' || *path == L'\\')
1145 return (*path == L'\0');
1149 win32_extract_stream(const struct wim_inode *inode,
1150 const wchar_t *path,
1151 const wchar_t *stream_name_utf16,
1152 struct wim_lookup_table_entry *lte)
1154 wchar_t *stream_path;
1158 DWORD creationDisposition = CREATE_ALWAYS;
1160 if (stream_name_utf16) {
1161 /* Named stream. Create a buffer that contains the UTF-16LE
1162 * string [.\]@path:@stream_name_utf16. This is needed to
1163 * create and open the stream using CreateFileW(). I'm not
1164 * aware of any other APIs to do this. Note: the '$DATA' suffix
1165 * seems to be unneeded. Additional note: a "./" prefix needs
1166 * to be added when the path is not absolute to avoid ambiguity
1167 * with drive letters. */
1168 size_t stream_path_nchars;
1170 size_t stream_name_nchars;
1171 const wchar_t *prefix;
1173 path_nchars = wcslen(path);
1174 stream_name_nchars = wcslen(stream_name_utf16);
1175 stream_path_nchars = path_nchars + 1 + stream_name_nchars;
1176 if (path[0] != cpu_to_le16(L'\0') &&
1177 path[0] != cpu_to_le16(L'/') &&
1178 path[0] != cpu_to_le16(L'\\') &&
1179 path[1] != cpu_to_le16(L':'))
1182 stream_path_nchars += 2;
1186 stream_path = alloca((stream_path_nchars + 1) * sizeof(wchar_t));
1187 swprintf(stream_path, L"%ls%ls:%ls",
1188 prefix, path, stream_name_utf16);
1190 /* Unnamed stream; its path is just the path to the file itself.
1192 stream_path = (wchar_t*)path;
1194 /* Directories must be created with CreateDirectoryW(). Then
1195 * the call to CreateFileW() will merely open the directory that
1196 * was already created rather than creating a new file. */
1197 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1198 if (!CreateDirectoryW(stream_path, NULL)) {
1199 err = GetLastError();
1201 case ERROR_ALREADY_EXISTS:
1203 case ERROR_ACCESS_DENIED:
1204 if (path_is_root_of_drive(path))
1208 ERROR("Failed to create directory \"%ls\"",
1211 ret = WIMLIB_ERR_MKDIR;
1215 DEBUG("Created directory \"%ls\"", stream_path);
1216 if (!(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
1220 creationDisposition = OPEN_EXISTING;
1224 DEBUG("Opening \"%ls\"", stream_path);
1225 h = CreateFileW(stream_path,
1229 creationDisposition,
1230 FILE_FLAG_OPEN_REPARSE_POINT |
1231 FILE_FLAG_BACKUP_SEMANTICS |
1232 inode->i_attributes,
1234 if (h == INVALID_HANDLE_VALUE) {
1235 err = GetLastError();
1236 ERROR("Failed to create \"%ls\"", stream_path);
1238 ret = WIMLIB_ERR_OPEN;
1242 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT &&
1243 stream_name_utf16 == NULL)
1245 DEBUG("Setting reparse data on \"%ls\"", path);
1246 ret = win32_set_reparse_data(h, inode->i_reparse_tag, lte, path);
1248 goto fail_close_handle;
1251 DEBUG("Extracting \"%ls\" (len = %"PRIu64")",
1252 stream_path, wim_resource_size(lte));
1253 ret = do_win32_extract_stream(h, lte);
1255 goto fail_close_handle;
1259 DEBUG("Closing \"%ls\"", stream_path);
1260 if (!CloseHandle(h)) {
1261 err = GetLastError();
1262 ERROR("Failed to close \"%ls\"", stream_path);
1264 ret = WIMLIB_ERR_WRITE;
1272 ERROR("Error extracting %ls", stream_path);
1278 * Creates a file, directory, or reparse point and extracts all streams to it
1279 * (unnamed data stream and/or reparse point stream, plus any alternate data
1280 * streams). This in Win32-specific code.
1282 * @inode: WIM inode for this file or directory.
1283 * @path: UTF-16LE external path to extract the inode to.
1285 * Returns 0 on success; nonzero on failure.
1288 win32_extract_streams(const struct wim_inode *inode,
1289 const wchar_t *path, u64 *completed_bytes_p)
1291 struct wim_lookup_table_entry *unnamed_lte;
1294 unnamed_lte = inode_unnamed_lte_resolved(inode);
1295 ret = win32_extract_stream(inode, path, NULL, unnamed_lte);
1299 *completed_bytes_p += wim_resource_size(unnamed_lte);
1300 for (u16 i = 0; i < inode->i_num_ads; i++) {
1301 const struct wim_ads_entry *ads_entry = &inode->i_ads_entries[i];
1302 if (ads_entry->stream_name_nbytes != 0) {
1303 /* Skip special UNIX data entries (see documentation for
1304 * WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA) */
1305 if (ads_entry->stream_name_nbytes == WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES
1306 && !memcmp(ads_entry->stream_name,
1307 WIMLIB_UNIX_DATA_TAG_UTF16LE,
1308 WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES))
1310 ret = win32_extract_stream(inode,
1312 ads_entry->stream_name,
1317 *completed_bytes_p += wim_resource_size(ads_entry->lte);
1324 /* Extract a file, directory, reparse point, or hard link to an
1325 * already-extracted file using the Win32 API */
1327 win32_do_apply_dentry(const wchar_t *output_path,
1328 size_t output_path_num_chars,
1329 struct wim_dentry *dentry,
1330 struct apply_args *args)
1333 struct wim_inode *inode = dentry->d_inode;
1336 if (inode->i_nlink > 1 && inode->i_extracted_file != NULL) {
1337 /* Linked file, with another name already extracted. Create a
1339 DEBUG("Creating hard link \"%ls => %ls\"",
1340 output_path, inode->i_extracted_file);
1341 if (!CreateHardLinkW(output_path, inode->i_extracted_file, NULL)) {
1342 err = GetLastError();
1343 ERROR("Can't create hard link \"%ls => %ls\"",
1344 output_path, inode->i_extracted_file);
1346 return WIMLIB_ERR_LINK;
1349 /* Create the file, directory, or reparse point, and extract the
1351 ret = win32_extract_streams(inode, output_path,
1352 &args->progress.extract.completed_bytes);
1356 if (inode->i_security_id >= 0 &&
1357 !(args->extract_flags & WIMLIB_EXTRACT_FLAG_NO_ACLS))
1359 ret = win32_set_security_data(inode, output_path, args);
1363 if (inode->i_nlink > 1) {
1364 /* Save extracted path for a later call to
1365 * CreateHardLinkW() if this inode has multiple links.
1367 inode->i_extracted_file = WSTRDUP(output_path);
1368 if (!inode->i_extracted_file)
1369 ret = WIMLIB_ERR_NOMEM;
1375 /* Set timestamps on an extracted file using the Win32 API */
1377 win32_do_apply_dentry_timestamps(const wchar_t *path,
1378 size_t path_num_chars,
1379 const struct wim_dentry *dentry,
1380 const struct apply_args *args)
1384 const struct wim_inode *inode = dentry->d_inode;
1386 DEBUG("Opening \"%ls\" to set timestamps", path);
1387 h = win32_open_existing_file(path, FILE_WRITE_ATTRIBUTES);
1388 if (h == INVALID_HANDLE_VALUE) {
1389 err = GetLastError();
1393 FILETIME creationTime = {.dwLowDateTime = inode->i_creation_time & 0xffffffff,
1394 .dwHighDateTime = inode->i_creation_time >> 32};
1395 FILETIME lastAccessTime = {.dwLowDateTime = inode->i_last_access_time & 0xffffffff,
1396 .dwHighDateTime = inode->i_last_access_time >> 32};
1397 FILETIME lastWriteTime = {.dwLowDateTime = inode->i_last_write_time & 0xffffffff,
1398 .dwHighDateTime = inode->i_last_write_time >> 32};
1400 DEBUG("Calling SetFileTime() on \"%ls\"", path);
1401 if (!SetFileTime(h, &creationTime, &lastAccessTime, &lastWriteTime)) {
1402 err = GetLastError();
1406 DEBUG("Closing \"%ls\"", path);
1407 if (!CloseHandle(h)) {
1408 err = GetLastError();
1413 /* Only warn if setting timestamps failed; still return 0. */
1414 WARNING("Can't set timestamps on \"%ls\"", path);
1420 /* Replacement for POSIX fsync() */
1427 h = (HANDLE)_get_osfhandle(fd);
1428 if (h == INVALID_HANDLE_VALUE) {
1429 err = GetLastError();
1430 ERROR("Could not get Windows handle for file descriptor");
1435 if (!FlushFileBuffers(h)) {
1436 err = GetLastError();
1437 ERROR("Could not flush file buffers to disk");
1445 /* Use the Win32 API to get the number of processors */
1447 win32_get_number_of_processors()
1449 SYSTEM_INFO sysinfo;
1450 GetSystemInfo(&sysinfo);
1451 return sysinfo.dwNumberOfProcessors;
1454 /* Replacement for POSIX-2008 realpath(). Warning: partial functionality only
1455 * (resolved_path must be NULL). Also I highly doubt that GetFullPathName
1456 * really does the right thing under all circumstances. */
1458 realpath(const wchar_t *path, wchar_t *resolved_path)
1461 wimlib_assert(resolved_path == NULL);
1464 ret = GetFullPathNameW(path, 0, NULL, NULL);
1466 err = GetLastError();
1470 resolved_path = TMALLOC(ret);
1473 ret = GetFullPathNameW(path, ret, resolved_path, NULL);
1475 err = GetLastError();
1476 free(resolved_path);
1477 resolved_path = NULL;
1485 return resolved_path;
1488 /* rename() on Windows fails if the destination file exists. And we need to
1489 * make it work on wide characters. Fix it. */
1491 win32_rename_replacement(const wchar_t *oldpath, const wchar_t *newpath)
1493 if (MoveFileExW(oldpath, newpath, MOVEFILE_REPLACE_EXISTING)) {
1496 /* As usual, the possible error values are not documented */
1497 DWORD err = GetLastError();
1498 ERROR("MoveFileEx(): Can't rename \"%ls\" to \"%ls\"",
1506 /* Replacement for POSIX fnmatch() (partial functionality only) */
1508 fnmatch(const wchar_t *pattern, const wchar_t *string, int flags)
1510 if (PathMatchSpecW(string, pattern))
1516 /* truncate() replacement */
1518 win32_truncate_replacement(const wchar_t *path, off_t size)
1520 DWORD err = NO_ERROR;
1521 LARGE_INTEGER liOffset;
1523 HANDLE h = win32_open_existing_file(path, GENERIC_WRITE);
1524 if (h == INVALID_HANDLE_VALUE)
1527 liOffset.QuadPart = size;
1528 if (!SetFilePointerEx(h, liOffset, NULL, FILE_BEGIN))
1529 goto fail_close_handle;
1531 if (!SetEndOfFile(h))
1532 goto fail_close_handle;
1537 err = GetLastError();
1540 if (err == NO_ERROR)
1541 err = GetLastError();
1542 ERROR("Can't truncate \"%ls\" to %"PRIu64" bytes", path, size);
1549 /* This really could be replaced with _wcserror_s, but this doesn't seem to
1550 * actually be available in MSVCRT.DLL on Windows XP (perhaps it's statically
1551 * linked in by Visual Studio...?). */
1553 win32_strerror_r_replacement(int errnum, wchar_t *buf, size_t buflen)
1555 static pthread_mutex_t strerror_lock = PTHREAD_MUTEX_INITIALIZER;
1557 pthread_mutex_lock(&strerror_lock);
1558 mbstowcs(buf, strerror(errnum), buflen);
1559 buf[buflen - 1] = '\0';
1560 pthread_mutex_unlock(&strerror_lock);
1564 #endif /* __WIN32__ */