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"
45 #define MAX_GET_SD_ACCESS_DENIED_WARNINGS 1
46 #define MAX_GET_SACL_PRIV_NOTHELD_WARNINGS 1
47 struct win32_capture_state {
48 unsigned long num_get_sd_access_denied;
49 unsigned long num_get_sacl_priv_notheld;
52 #define MAX_SET_SD_ACCESS_DENIED_WARNINGS 1
53 #define MAX_SET_SACL_PRIV_NOTHELD_WARNINGS 1
55 /* Pointers to functions that are not available on all targetted versions of
56 * Windows (XP and later). NOTE: The WINAPI annotations seem to be important; I
57 * assume it specifies a certain calling convention. */
60 static HANDLE (WINAPI *win32func_FindFirstStreamW)(LPCWSTR lpFileName,
61 STREAM_INFO_LEVELS InfoLevel,
62 LPVOID lpFindStreamData,
63 DWORD dwFlags) = NULL;
66 static BOOL (WINAPI *win32func_FindNextStreamW)(HANDLE hFindStream,
67 LPVOID lpFindStreamData) = NULL;
69 static HMODULE hKernel32 = NULL;
71 /* Try to dynamically load some functions */
77 if (hKernel32 == NULL) {
78 DEBUG("Loading Kernel32.dll");
79 hKernel32 = LoadLibraryW(L"Kernel32.dll");
80 if (hKernel32 == NULL) {
82 WARNING("Can't load Kernel32.dll");
88 DEBUG("Looking for FindFirstStreamW");
89 win32func_FindFirstStreamW = (void*)GetProcAddress(hKernel32, "FindFirstStreamW");
90 if (!win32func_FindFirstStreamW) {
91 WARNING("Could not find function FindFirstStreamW() in Kernel32.dll!");
92 WARNING("Capturing alternate data streams will not be supported.");
96 DEBUG("Looking for FindNextStreamW");
97 win32func_FindNextStreamW = (void*)GetProcAddress(hKernel32, "FindNextStreamW");
98 if (!win32func_FindNextStreamW) {
99 WARNING("Could not find function FindNextStreamW() in Kernel32.dll!");
100 WARNING("Capturing alternate data streams will not be supported.");
101 win32func_FindFirstStreamW = NULL;
106 win32_global_cleanup()
108 if (hKernel32 != NULL) {
109 DEBUG("Closing Kernel32.dll");
110 FreeLibrary(hKernel32);
115 static const wchar_t *capture_access_denied_msg =
116 L" If you are not running this program as the administrator, you may\n"
117 " need to do so, so that all data and metadata can be backed up.\n"
118 " Otherwise, there may be no way to access the desired data or\n"
119 " metadata without taking ownership of the file or directory.\n"
122 static const wchar_t *apply_access_denied_msg =
123 L"If you are not running this program as the administrator, you may\n"
124 " need to do so, so that all data and metadata can be extracted\n"
125 " exactly as the origignal copy. However, if you do not care that\n"
126 " the security descriptors are extracted correctly, you could run\n"
127 " `wimlib-imagex apply' with the --no-acls flag instead.\n"
130 #ifdef ENABLE_ERROR_MESSAGES
132 win32_error(u32 err_code)
136 nchars = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
137 FORMAT_MESSAGE_ALLOCATE_BUFFER,
139 (wchar_t*)&buffer, 0, NULL);
141 ERROR("Error printing error message! "
142 "Computer will self-destruct in 3 seconds.");
144 ERROR("Win32 error: %ls", buffer);
152 win32_error(GetLastError());
157 win32_open_existing_file(const wchar_t *path, DWORD dwDesiredAccess)
159 return CreateFileW(path,
162 NULL, /* lpSecurityAttributes */
164 FILE_FLAG_BACKUP_SEMANTICS |
165 FILE_FLAG_OPEN_REPARSE_POINT,
166 NULL /* hTemplateFile */);
170 win32_open_file_data_only(const wchar_t *path)
172 return win32_open_existing_file(path, FILE_READ_DATA);
176 win32_read_file(const wchar_t *filename,
177 void *handle, u64 offset, size_t size, void *buf)
182 LARGE_INTEGER liOffset = {.QuadPart = offset};
184 wimlib_assert(size <= 0xffffffff);
186 if (SetFilePointerEx(h, liOffset, NULL, FILE_BEGIN))
187 if (ReadFile(h, buf, size, &bytesRead, NULL) && bytesRead == size)
189 err = GetLastError();
190 ERROR("Error reading \"%ls\"", filename);
192 return WIMLIB_ERR_READ;
196 win32_close_file(void *handle)
198 CloseHandle((HANDLE)handle);
202 FILETIME_to_u64(const FILETIME *ft)
204 return ((u64)ft->dwHighDateTime << 32) | (u64)ft->dwLowDateTime;
208 win32_get_short_name(struct wim_dentry *dentry, const wchar_t *path)
210 WIN32_FIND_DATAW dat;
211 if (FindFirstFileW(path, &dat) && dat.cAlternateFileName[0] != L'\0') {
212 size_t short_name_nbytes = wcslen(dat.cAlternateFileName) *
214 size_t n = short_name_nbytes + sizeof(wchar_t);
215 dentry->short_name = MALLOC(n);
216 if (!dentry->short_name)
217 return WIMLIB_ERR_NOMEM;
218 memcpy(dentry->short_name, dat.cAlternateFileName, n);
219 dentry->short_name_nbytes = short_name_nbytes;
221 /* If we can't read the short filename for some reason, we just ignore
222 * the error and assume the file has no short name. I don't think this
223 * should be an issue, since the short names are essentially obsolete
229 win32_get_security_descriptor(struct wim_dentry *dentry,
230 struct sd_set *sd_set,
232 struct win32_capture_state *state,
235 SECURITY_INFORMATION requestedInformation;
241 requestedInformation = DACL_SECURITY_INFORMATION |
242 SACL_SECURITY_INFORMATION |
243 OWNER_SECURITY_INFORMATION |
244 GROUP_SECURITY_INFORMATION;
246 /* Request length of security descriptor */
247 status = GetFileSecurityW(path, requestedInformation,
248 NULL, 0, &lenNeeded);
249 err = GetLastError();
250 if (!status && err == ERROR_INSUFFICIENT_BUFFER) {
251 DWORD len = lenNeeded;
253 if (GetFileSecurityW(path, requestedInformation,
254 (PSECURITY_DESCRIPTOR)buf, len, &lenNeeded))
256 int security_id = sd_set_add_sd(sd_set, buf, len);
258 return WIMLIB_ERR_NOMEM;
260 dentry->d_inode->i_security_id = security_id;
264 err = GetLastError();
268 if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_STRICT_ACLS)
272 case ERROR_PRIVILEGE_NOT_HELD:
273 if (requestedInformation & SACL_SECURITY_INFORMATION) {
274 n = state->num_get_sacl_priv_notheld++;
275 requestedInformation &= ~SACL_SECURITY_INFORMATION;
276 if (n < MAX_GET_SACL_PRIV_NOTHELD_WARNINGS) {
278 "We don't have enough privileges to read the full security\n"
279 " descriptor of \"%ls\"!\n"
280 " Re-trying with SACL omitted.\n", path);
281 } else if (n == MAX_GET_SACL_PRIV_NOTHELD_WARNINGS) {
283 "Suppressing further privileges not held error messages when reading\n"
284 " security descriptors.");
289 case ERROR_ACCESS_DENIED:
290 n = state->num_get_sd_access_denied++;
291 if (n < MAX_GET_SD_ACCESS_DENIED_WARNINGS) {
292 WARNING("Failed to read security descriptor of \"%ls\": "
293 "Access denied!\n%ls", path, capture_access_denied_msg);
294 } else if (n == MAX_GET_SD_ACCESS_DENIED_WARNINGS) {
295 WARNING("Suppressing further access denied errors messages i"
296 "when reading security descriptors");
301 ERROR("Failed to read security descriptor of \"%ls\"", path);
303 return WIMLIB_ERR_READ;
308 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
310 size_t path_num_chars,
311 struct wim_lookup_table *lookup_table,
312 struct sd_set *sd_set,
313 const struct wimlib_capture_config *config,
315 wimlib_progress_func_t progress_func,
316 struct win32_capture_state *state);
318 /* Reads the directory entries of directory using a Win32 API and recursively
319 * calls win32_build_dentry_tree() on them. */
321 win32_recurse_directory(struct wim_dentry *root,
323 size_t dir_path_num_chars,
324 struct wim_lookup_table *lookup_table,
325 struct sd_set *sd_set,
326 const struct wimlib_capture_config *config,
328 wimlib_progress_func_t progress_func,
329 struct win32_capture_state *state)
331 WIN32_FIND_DATAW dat;
336 /* Begin reading the directory by calling FindFirstFileW. Unlike UNIX
337 * opendir(), FindFirstFileW has file globbing built into it. But this
338 * isn't what we actually want, so just add a dummy glob to get all
340 dir_path[dir_path_num_chars] = L'/';
341 dir_path[dir_path_num_chars + 1] = L'*';
342 dir_path[dir_path_num_chars + 2] = L'\0';
343 hFind = FindFirstFileW(dir_path, &dat);
344 dir_path[dir_path_num_chars] = L'\0';
346 if (hFind == INVALID_HANDLE_VALUE) {
347 err = GetLastError();
348 if (err == ERROR_FILE_NOT_FOUND) {
351 ERROR("Failed to read directory \"%ls\"", dir_path);
353 return WIMLIB_ERR_READ;
358 /* Skip . and .. entries */
359 if (dat.cFileName[0] == L'.' &&
360 (dat.cFileName[1] == L'\0' ||
361 (dat.cFileName[1] == L'.' &&
362 dat.cFileName[2] == L'\0')))
364 size_t filename_len = wcslen(dat.cFileName);
366 dir_path[dir_path_num_chars] = L'/';
367 wmemcpy(dir_path + dir_path_num_chars + 1,
371 struct wim_dentry *child;
372 size_t path_len = dir_path_num_chars + 1 + filename_len;
373 ret = win32_build_dentry_tree_recursive(&child,
382 dir_path[dir_path_num_chars] = L'\0';
386 dentry_add_child(root, child);
387 } while (FindNextFileW(hFind, &dat));
388 err = GetLastError();
389 if (err != ERROR_NO_MORE_FILES) {
390 ERROR("Failed to read directory \"%ls\"", dir_path);
393 ret = WIMLIB_ERR_READ;
400 /* Load a reparse point into a WIM inode. It is just stored in memory.
402 * @hFile: Open handle to a reparse point, with permission to read the reparse
405 * @inode: WIM inode for the reparse point.
407 * @lookup_table: Stream lookup table for the WIM; an entry will be added to it
408 * for the reparse point unless an entry already exists for
409 * the exact same data stream.
411 * @path: External path to the reparse point. Used for error messages only.
413 * Returns 0 on success; nonzero on failure. */
415 win32_capture_reparse_point(HANDLE hFile,
416 struct wim_inode *inode,
417 struct wim_lookup_table *lookup_table,
420 /* "Reparse point data, including the tag and optional GUID,
421 * cannot exceed 16 kilobytes." - MSDN */
422 char reparse_point_buf[16 * 1024];
425 if (!DeviceIoControl(hFile, FSCTL_GET_REPARSE_POINT,
426 NULL, /* "Not used with this operation; set to NULL" */
427 0, /* "Not used with this operation; set to 0" */
428 reparse_point_buf, /* "A pointer to a buffer that
429 receives the reparse point data */
430 sizeof(reparse_point_buf), /* "The size of the output
435 DWORD err = GetLastError();
436 ERROR("Failed to get reparse data of \"%ls\"", path);
438 return WIMLIB_ERR_READ;
440 if (bytesReturned < 8) {
441 ERROR("Reparse data on \"%ls\" is invalid", path);
442 return WIMLIB_ERR_READ;
444 inode->i_reparse_tag = le32_to_cpu(*(u32*)reparse_point_buf);
445 return inode_add_ads_with_data(inode, L"",
446 reparse_point_buf + 8,
447 bytesReturned - 8, lookup_table);
450 /* Calculate the SHA1 message digest of a Win32 data stream, which may be either
451 * an unnamed or named data stream.
453 * @path: Path to the file, with the stream noted at the end for named
454 * streams. UTF-16LE encoding.
456 * @hash: On success, the SHA1 message digest of the stream is written to
459 * Returns 0 on success; nonzero on failure.
462 win32_sha1sum(const wchar_t *path, u8 hash[SHA1_HASH_SIZE])
470 hFile = win32_open_file_data_only(path);
471 if (hFile == INVALID_HANDLE_VALUE)
472 return WIMLIB_ERR_OPEN;
476 if (!ReadFile(hFile, buf, sizeof(buf), &bytesRead, NULL)) {
477 ret = WIMLIB_ERR_READ;
478 goto out_close_handle;
482 sha1_update(&ctx, buf, bytesRead);
485 sha1_final(hash, &ctx);
491 /* Scans an unnamed or named stream of a Win32 file (not a reparse point
492 * stream); calculates its SHA1 message digest and either creates a `struct
493 * wim_lookup_table_entry' in memory for it, or uses an existing 'struct
494 * wim_lookup_table_entry' for an identical stream.
496 * @path: Path to the file (UTF-16LE).
498 * @path_num_chars: Number of 2-byte characters in @path.
500 * @inode: WIM inode to save the stream into.
502 * @lookup_table: Stream lookup table for the WIM.
504 * @dat: A `WIN32_FIND_STREAM_DATA' structure that specifies the
507 * Returns 0 on success; nonzero on failure.
510 win32_capture_stream(const wchar_t *path,
511 size_t path_num_chars,
512 struct wim_inode *inode,
513 struct wim_lookup_table *lookup_table,
514 WIN32_FIND_STREAM_DATA *dat)
516 struct wim_ads_entry *ads_entry;
517 u8 hash[SHA1_HASH_SIZE];
518 struct wim_lookup_table_entry *lte;
520 wchar_t *stream_name, *colon;
521 size_t stream_name_nchars;
522 bool is_named_stream;
526 size_t spath_buf_nbytes;
527 const wchar_t *relpath_prefix;
528 const wchar_t *colonchar;
530 /* The stream name should be returned as :NAME:TYPE */
531 stream_name = dat->cStreamName;
532 if (*stream_name != L':')
533 goto out_invalid_stream_name;
535 colon = wcschr(stream_name, L':');
537 goto out_invalid_stream_name;
539 if (wcscmp(colon + 1, L"$DATA")) {
540 /* Not a DATA stream */
547 stream_name_nchars = colon - stream_name;
548 is_named_stream = (stream_name_nchars != 0);
550 if (is_named_stream) {
551 /* Allocate an ADS entry for the named stream. */
552 ads_entry = inode_add_ads_utf16le(inode, stream_name,
553 stream_name_nchars * sizeof(wchar_t));
555 ret = WIMLIB_ERR_NOMEM;
560 /* Create a UTF-16LE string @spath that gives the filename, then a
561 * colon, then the stream name. Or, if it's an unnamed stream, just the
562 * filename. It is MALLOC()'ed so that it can be saved in the
563 * wim_lookup_table_entry if needed.
565 * As yet another special case, relative paths need to be changed to
566 * begin with an explicit "./" so that, for example, a file t:ads, where
567 * :ads is the part we added, is not interpreted as a file on the t:
569 spath_nchars = path_num_chars;
570 relpath_prefix = L"";
572 if (is_named_stream) {
573 spath_nchars += 1 + stream_name_nchars;
575 if (path_num_chars == 1 &&
580 relpath_prefix = L"./";
584 spath_buf_nbytes = (spath_nchars + 1) * sizeof(wchar_t);
585 spath = MALLOC(spath_buf_nbytes);
587 swprintf(spath, L"%ls%ls%ls%ls",
588 relpath_prefix, path, colonchar, stream_name);
590 ret = win32_sha1sum(spath, hash);
592 err = GetLastError();
593 ERROR("Failed to read \"%ls\" to calculate SHA1sum", spath);
598 lte = __lookup_resource(lookup_table, hash);
600 /* Use existing wim_lookup_table_entry that has the same SHA1
604 /* Make a new wim_lookup_table_entry */
605 lte = new_lookup_table_entry();
607 ret = WIMLIB_ERR_NOMEM;
610 lte->file_on_disk = spath;
611 lte->win32_file_on_disk_fp = INVALID_HANDLE_VALUE;
613 lte->resource_location = RESOURCE_WIN32;
614 lte->resource_entry.original_size = (uint64_t)dat->StreamSize.QuadPart;
615 lte->resource_entry.size = (uint64_t)dat->StreamSize.QuadPart;
616 copy_hash(lte->hash, hash);
617 lookup_table_insert(lookup_table, lte);
620 ads_entry->lte = lte;
627 out_invalid_stream_name:
628 ERROR("Invalid stream name: \"%ls:%ls\"", path, dat->cStreamName);
629 ret = WIMLIB_ERR_READ;
633 /* Scans a Win32 file for unnamed and named data streams (not reparse point
636 * @path: Path to the file (UTF-16LE).
638 * @path_num_chars: Number of 2-byte characters in @path.
640 * @inode: WIM inode to save the stream into.
642 * @lookup_table: Stream lookup table for the WIM.
644 * @file_size: Size of unnamed data stream. (Used only if alternate
645 * data streams API appears to be unavailable.)
647 * Returns 0 on success; nonzero on failure.
650 win32_capture_streams(const wchar_t *path,
651 size_t path_num_chars,
652 struct wim_inode *inode,
653 struct wim_lookup_table *lookup_table,
656 WIN32_FIND_STREAM_DATA dat;
661 if (win32func_FindFirstStreamW == NULL)
664 hFind = win32func_FindFirstStreamW(path, FindStreamInfoStandard, &dat, 0);
665 if (hFind == INVALID_HANDLE_VALUE) {
666 err = GetLastError();
668 if (err == ERROR_CALL_NOT_IMPLEMENTED)
671 /* Seems legal for this to return ERROR_HANDLE_EOF on reparse
672 * points and directories */
673 if ((inode->i_attributes &
674 (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
675 && err == ERROR_HANDLE_EOF)
679 if (err == ERROR_ACCESS_DENIED) {
680 /* XXX This maybe should be an error. */
681 WARNING("Failed to look up data streams "
682 "of \"%ls\": Access denied!\n%ls",
683 path, capture_access_denied_msg);
686 ERROR("Failed to look up data streams "
689 return WIMLIB_ERR_READ;
694 ret = win32_capture_stream(path,
700 } while (win32func_FindNextStreamW(hFind, &dat));
701 err = GetLastError();
702 if (err != ERROR_HANDLE_EOF) {
703 ERROR("Win32 API: Error reading data streams from \"%ls\"", path);
705 ret = WIMLIB_ERR_READ;
711 /* FindFirstStreamW() API is not available. Only capture the unnamed
713 if (inode->i_attributes &
714 (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
718 /* Just create our own WIN32_FIND_STREAM_DATA for an unnamed
719 * stream to reduce the code to a call to the
720 * already-implemented win32_capture_stream() */
721 wcscpy(dat.cStreamName, L"::$DATA");
722 dat.StreamSize.QuadPart = file_size;
723 ret = win32_capture_stream(path,
732 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
734 size_t path_num_chars,
735 struct wim_lookup_table *lookup_table,
736 struct sd_set *sd_set,
737 const struct wimlib_capture_config *config,
739 wimlib_progress_func_t progress_func,
740 struct win32_capture_state *state)
742 struct wim_dentry *root = NULL;
743 struct wim_inode *inode;
748 if (exclude_path(path, path_num_chars, config, true)) {
749 if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT) {
750 ERROR("Cannot exclude the root directory from capture");
751 ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
754 if ((add_image_flags & WIMLIB_ADD_IMAGE_FLAG_EXCLUDE_VERBOSE)
757 union wimlib_progress_info info;
758 info.scan.cur_path = path;
759 info.scan.excluded = true;
760 progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
765 if ((add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
768 union wimlib_progress_info info;
769 info.scan.cur_path = path;
770 info.scan.excluded = false;
771 progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
774 HANDLE hFile = win32_open_existing_file(path,
775 FILE_READ_DATA | FILE_READ_ATTRIBUTES);
776 if (hFile == INVALID_HANDLE_VALUE) {
777 err = GetLastError();
778 ERROR("Win32 API: Failed to open \"%ls\"", path);
780 ret = WIMLIB_ERR_OPEN;
784 BY_HANDLE_FILE_INFORMATION file_info;
785 if (!GetFileInformationByHandle(hFile, &file_info)) {
786 err = GetLastError();
787 ERROR("Win32 API: Failed to get file information for \"%ls\"",
790 ret = WIMLIB_ERR_STAT;
791 goto out_close_handle;
794 /* Create a WIM dentry */
795 ret = new_dentry_with_timeless_inode(path_basename_with_len(path, path_num_chars),
798 goto out_close_handle;
800 /* Start preparing the associated WIM inode */
801 inode = root->d_inode;
803 inode->i_attributes = file_info.dwFileAttributes;
804 inode->i_creation_time = FILETIME_to_u64(&file_info.ftCreationTime);
805 inode->i_last_write_time = FILETIME_to_u64(&file_info.ftLastWriteTime);
806 inode->i_last_access_time = FILETIME_to_u64(&file_info.ftLastAccessTime);
807 inode->i_ino = ((u64)file_info.nFileIndexHigh << 32) |
808 (u64)file_info.nFileIndexLow;
810 inode->i_resolved = 1;
811 add_image_flags &= ~(WIMLIB_ADD_IMAGE_FLAG_ROOT | WIMLIB_ADD_IMAGE_FLAG_SOURCE);
813 /* Get DOS name and security descriptor (if any). */
814 ret = win32_get_short_name(root, path);
816 goto out_close_handle;
818 if (!(add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NO_ACLS)) {
819 ret = win32_get_security_descriptor(root, sd_set, path, state,
822 goto out_close_handle;
825 file_size = ((u64)file_info.nFileSizeHigh << 32) |
826 (u64)file_info.nFileSizeLow;
828 if (inode_is_directory(inode)) {
829 /* Directory (not a reparse point) --- recurse to children */
831 /* But first... directories may have alternate data streams that
832 * need to be captured. */
833 ret = win32_capture_streams(path,
839 goto out_close_handle;
840 ret = win32_recurse_directory(root,
849 } else if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
850 /* Reparse point: save the reparse tag and data. Alternate data
851 * streams are not captured, if it's even possible for a reparse
852 * point to have alternate data streams... */
853 ret = win32_capture_reparse_point(hFile,
858 /* Not a directory, not a reparse point; capture the default
859 * file contents and any alternate data streams. */
860 ret = win32_capture_streams(path,
872 free_dentry_tree(root, lookup_table);
877 win32_do_capture_warnings(const struct win32_capture_state *state,
880 if (state->num_get_sacl_priv_notheld == 0 &&
881 state->num_get_sd_access_denied == 0)
885 WARNING("Built dentry tree successfully, but with the following problem(s):");
886 if (state->num_get_sacl_priv_notheld != 0) {
887 WARNING("Could not capture SACL (System Access Control List)\n"
888 " on %lu files or directories.",
889 state->num_get_sacl_priv_notheld);
891 if (state->num_get_sd_access_denied != 0) {
892 WARNING("Could not capture security descriptor at all\n"
893 " on %lu files or directories.",
894 state->num_get_sd_access_denied);
897 "Try running the program as the Administrator to make sure all the\n"
898 " desired metadata has been captured exactly. However, if you\n"
899 " do not care about capturing security descriptors correctly, then\n"
900 " nothing more needs to be done%ls\n",
901 (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NO_ACLS) ? L"." :
902 L", although you might consider\n"
903 " passing the --no-acls flag to `wimlib-imagex capture' or\n"
904 " `wimlib-imagex append' to explicitly capture no security\n"
908 /* Win32 version of capturing a directory tree */
910 win32_build_dentry_tree(struct wim_dentry **root_ret,
911 const wchar_t *root_disk_path,
912 struct wim_lookup_table *lookup_table,
913 struct sd_set *sd_set,
914 const struct wimlib_capture_config *config,
916 wimlib_progress_func_t progress_func,
922 struct win32_capture_state state;
924 path_nchars = wcslen(root_disk_path);
925 if (path_nchars > 32767)
926 return WIMLIB_ERR_INVALID_PARAM;
928 /* There is no check for overflow later when this buffer is being used!
929 * But the max path length on NTFS is 32767 characters, and paths need
930 * to be written specially to even go past 260 characters, so we should
931 * be okay with 32770 characters. */
932 path = MALLOC(32770 * sizeof(wchar_t));
934 return WIMLIB_ERR_NOMEM;
936 wmemcpy(path, root_disk_path, path_nchars + 1);
938 memset(&state, 0, sizeof(state));
939 ret = win32_build_dentry_tree_recursive(root_ret,
950 win32_do_capture_warnings(&state, add_image_flags);
955 win32_set_reparse_data(HANDLE h,
957 const struct wim_lookup_table_entry *lte,
965 WARNING("\"%ls\" is marked as a reparse point but had no reparse data",
969 len = wim_resource_size(lte);
970 if (len > 16 * 1024 - 8) {
971 WARNING("\"%ls\": reparse data too long!", path);
975 /* The WIM stream omits the ReparseTag and ReparseDataLength fields, so
976 * leave 8 bytes of space for them at the beginning of the buffer, then
977 * set them manually. */
978 buf = alloca(len + 8);
979 ret = read_full_wim_resource(lte, buf + 8, 0);
982 *(u32*)(buf + 0) = cpu_to_le32(reparse_tag);
983 *(u16*)(buf + 4) = cpu_to_le16(len);
984 *(u16*)(buf + 6) = 0;
986 /* Set the reparse data on the open file using the
987 * FSCTL_SET_REPARSE_POINT ioctl.
989 * There are contradictions in Microsoft's documentation for this:
991 * "If hDevice was opened without specifying FILE_FLAG_OVERLAPPED,
992 * lpOverlapped is ignored."
994 * --- So setting lpOverlapped to NULL is okay since it's ignored.
996 * "If lpOverlapped is NULL, lpBytesReturned cannot be NULL. Even when an
997 * operation returns no output data and lpOutBuffer is NULL,
998 * DeviceIoControl makes use of lpBytesReturned. After such an
999 * operation, the value of lpBytesReturned is meaningless."
1001 * --- So lpOverlapped not really ignored, as it affects another
1002 * parameter. This is the actual behavior: lpBytesReturned must be
1003 * specified, even though lpBytesReturned is documented as:
1005 * "Not used with this operation; set to NULL."
1007 DWORD bytesReturned;
1008 if (!DeviceIoControl(h, FSCTL_SET_REPARSE_POINT, buf, len + 8,
1010 &bytesReturned /* lpBytesReturned */,
1011 NULL /* lpOverlapped */))
1013 DWORD err = GetLastError();
1014 ERROR("Failed to set reparse data on \"%ls\"", path);
1016 return WIMLIB_ERR_WRITE;
1022 * Sets the security descriptor on an extracted file.
1025 win32_set_security_data(const struct wim_inode *inode,
1026 const wchar_t *path,
1027 struct apply_args *args)
1029 PSECURITY_DESCRIPTOR descriptor;
1033 descriptor = wim_const_security_data(args->w)->descriptors[inode->i_security_id];
1035 SECURITY_INFORMATION securityInformation = DACL_SECURITY_INFORMATION |
1036 SACL_SECURITY_INFORMATION |
1037 OWNER_SECURITY_INFORMATION |
1038 GROUP_SECURITY_INFORMATION;
1040 if (SetFileSecurityW(path, securityInformation, descriptor))
1042 err = GetLastError();
1043 if (args->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS)
1046 case ERROR_PRIVILEGE_NOT_HELD:
1047 if (securityInformation & SACL_SECURITY_INFORMATION) {
1048 n = args->num_set_sacl_priv_notheld++;
1049 securityInformation &= ~SACL_SECURITY_INFORMATION;
1050 if (n < MAX_SET_SACL_PRIV_NOTHELD_WARNINGS) {
1052 "We don't have enough privileges to set the full security\n"
1053 " descriptor on \"%ls\"!\n", path);
1054 if (args->num_set_sd_access_denied +
1055 args->num_set_sacl_priv_notheld == 1)
1057 WARNING("%ls", apply_access_denied_msg);
1059 WARNING("Re-trying with SACL omitted.\n", path);
1060 } else if (n == MAX_GET_SACL_PRIV_NOTHELD_WARNINGS) {
1062 "Suppressing further 'privileges not held' error messages when setting\n"
1063 " security descriptors.");
1068 case ERROR_INVALID_OWNER:
1069 case ERROR_ACCESS_DENIED:
1070 n = args->num_set_sd_access_denied++;
1071 if (n < MAX_SET_SD_ACCESS_DENIED_WARNINGS) {
1072 WARNING("Failed to set security descriptor on \"%ls\": "
1073 "Access denied!\n", path);
1074 if (args->num_set_sd_access_denied +
1075 args->num_set_sacl_priv_notheld == 1)
1077 WARNING("%ls", apply_access_denied_msg);
1079 } else if (n == MAX_SET_SD_ACCESS_DENIED_WARNINGS) {
1081 "Suppressing further access denied error messages when setting\n"
1082 " security descriptors");
1087 ERROR("Failed to set security descriptor on \"%ls\"", path);
1089 return WIMLIB_ERR_WRITE;
1095 win32_extract_chunk(const void *buf, size_t len, u64 offset, void *arg)
1097 HANDLE hStream = arg;
1099 DWORD nbytes_written;
1100 wimlib_assert(len <= 0xffffffff);
1102 if (!WriteFile(hStream, buf, len, &nbytes_written, NULL) ||
1103 nbytes_written != len)
1105 DWORD err = GetLastError();
1106 ERROR("WriteFile(): write error");
1108 return WIMLIB_ERR_WRITE;
1114 do_win32_extract_stream(HANDLE hStream, struct wim_lookup_table_entry *lte)
1116 return extract_wim_resource(lte, wim_resource_size(lte),
1117 win32_extract_chunk, hStream);
1121 path_is_root_of_drive(const wchar_t *path)
1126 if (*path != L'/' && *path != L'\\') {
1127 if (*(path + 1) == L':')
1132 while (*path == L'/' || *path == L'\\')
1134 return (*path == L'\0');
1138 win32_extract_stream(const struct wim_inode *inode,
1139 const wchar_t *path,
1140 const wchar_t *stream_name_utf16,
1141 struct wim_lookup_table_entry *lte)
1143 wchar_t *stream_path;
1147 DWORD creationDisposition = CREATE_ALWAYS;
1149 if (stream_name_utf16) {
1150 /* Named stream. Create a buffer that contains the UTF-16LE
1151 * string [.\]@path:@stream_name_utf16. This is needed to
1152 * create and open the stream using CreateFileW(). I'm not
1153 * aware of any other APIs to do this. Note: the '$DATA' suffix
1154 * seems to be unneeded. Additional note: a "./" prefix needs
1155 * to be added when the path is not absolute to avoid ambiguity
1156 * with drive letters. */
1157 size_t stream_path_nchars;
1159 size_t stream_name_nchars;
1160 const wchar_t *prefix;
1162 path_nchars = wcslen(path);
1163 stream_name_nchars = wcslen(stream_name_utf16);
1164 stream_path_nchars = path_nchars + 1 + stream_name_nchars;
1165 if (path[0] != cpu_to_le16(L'\0') &&
1166 path[0] != cpu_to_le16(L'/') &&
1167 path[0] != cpu_to_le16(L'\\') &&
1168 path[1] != cpu_to_le16(L':'))
1171 stream_path_nchars += 2;
1175 stream_path = alloca((stream_path_nchars + 1) * sizeof(wchar_t));
1176 swprintf(stream_path, L"%ls%ls:%ls",
1177 prefix, path, stream_name_utf16);
1179 /* Unnamed stream; its path is just the path to the file itself.
1181 stream_path = (wchar_t*)path;
1183 /* Directories must be created with CreateDirectoryW(). Then
1184 * the call to CreateFileW() will merely open the directory that
1185 * was already created rather than creating a new file. */
1186 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1187 if (!CreateDirectoryW(stream_path, NULL)) {
1188 err = GetLastError();
1190 case ERROR_ALREADY_EXISTS:
1192 case ERROR_ACCESS_DENIED:
1193 if (path_is_root_of_drive(path))
1197 ERROR("Failed to create directory \"%ls\"",
1200 ret = WIMLIB_ERR_MKDIR;
1204 DEBUG("Created directory \"%ls\"", stream_path);
1205 if (!(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
1209 creationDisposition = OPEN_EXISTING;
1213 DEBUG("Opening \"%ls\"", stream_path);
1214 h = CreateFileW(stream_path,
1218 creationDisposition,
1219 FILE_FLAG_OPEN_REPARSE_POINT |
1220 FILE_FLAG_BACKUP_SEMANTICS |
1221 inode->i_attributes,
1223 if (h == INVALID_HANDLE_VALUE) {
1224 err = GetLastError();
1225 ERROR("Failed to create \"%ls\"", stream_path);
1227 ret = WIMLIB_ERR_OPEN;
1231 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT &&
1232 stream_name_utf16 == NULL)
1234 DEBUG("Setting reparse data on \"%ls\"", path);
1235 ret = win32_set_reparse_data(h, inode->i_reparse_tag, lte, path);
1237 goto fail_close_handle;
1240 DEBUG("Extracting \"%ls\" (len = %"PRIu64")",
1241 stream_path, wim_resource_size(lte));
1242 ret = do_win32_extract_stream(h, lte);
1244 goto fail_close_handle;
1248 DEBUG("Closing \"%ls\"", stream_path);
1249 if (!CloseHandle(h)) {
1250 err = GetLastError();
1251 ERROR("Failed to close \"%ls\"", stream_path);
1253 ret = WIMLIB_ERR_WRITE;
1261 ERROR("Error extracting %ls", stream_path);
1267 * Creates a file, directory, or reparse point and extracts all streams to it
1268 * (unnamed data stream and/or reparse point stream, plus any alternate data
1269 * streams). This in Win32-specific code.
1271 * @inode: WIM inode for this file or directory.
1272 * @path: UTF-16LE external path to extract the inode to.
1274 * Returns 0 on success; nonzero on failure.
1277 win32_extract_streams(const struct wim_inode *inode,
1278 const wchar_t *path, u64 *completed_bytes_p)
1280 struct wim_lookup_table_entry *unnamed_lte;
1283 unnamed_lte = inode_unnamed_lte_resolved(inode);
1284 ret = win32_extract_stream(inode, path, NULL, unnamed_lte);
1288 *completed_bytes_p += wim_resource_size(unnamed_lte);
1289 for (u16 i = 0; i < inode->i_num_ads; i++) {
1290 const struct wim_ads_entry *ads_entry = &inode->i_ads_entries[i];
1291 if (ads_entry->stream_name_nbytes != 0) {
1292 /* Skip special UNIX data entries (see documentation for
1293 * WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA) */
1294 if (ads_entry->stream_name_nbytes == WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES
1295 && !memcmp(ads_entry->stream_name,
1296 WIMLIB_UNIX_DATA_TAG_UTF16LE,
1297 WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES))
1299 ret = win32_extract_stream(inode,
1301 ads_entry->stream_name,
1306 *completed_bytes_p += wim_resource_size(ads_entry->lte);
1313 /* Extract a file, directory, reparse point, or hard link to an
1314 * already-extracted file using the Win32 API */
1316 win32_do_apply_dentry(const wchar_t *output_path,
1317 size_t output_path_num_chars,
1318 struct wim_dentry *dentry,
1319 struct apply_args *args)
1322 struct wim_inode *inode = dentry->d_inode;
1325 if (inode->i_nlink > 1 && inode->i_extracted_file != NULL) {
1326 /* Linked file, with another name already extracted. Create a
1328 DEBUG("Creating hard link \"%ls => %ls\"",
1329 output_path, inode->i_extracted_file);
1330 if (!CreateHardLinkW(output_path, inode->i_extracted_file, NULL)) {
1331 err = GetLastError();
1332 ERROR("Can't create hard link \"%ls => %ls\"",
1333 output_path, inode->i_extracted_file);
1335 return WIMLIB_ERR_LINK;
1338 /* Create the file, directory, or reparse point, and extract the
1340 ret = win32_extract_streams(inode, output_path,
1341 &args->progress.extract.completed_bytes);
1345 if (inode->i_security_id >= 0 &&
1346 !(args->extract_flags & WIMLIB_EXTRACT_FLAG_NO_ACLS))
1348 ret = win32_set_security_data(inode, output_path, args);
1352 if (inode->i_nlink > 1) {
1353 /* Save extracted path for a later call to
1354 * CreateHardLinkW() if this inode has multiple links.
1356 inode->i_extracted_file = WSTRDUP(output_path);
1357 if (!inode->i_extracted_file)
1358 ret = WIMLIB_ERR_NOMEM;
1364 /* Set timestamps on an extracted file using the Win32 API */
1366 win32_do_apply_dentry_timestamps(const wchar_t *path,
1367 size_t path_num_chars,
1368 const struct wim_dentry *dentry,
1369 const struct apply_args *args)
1373 const struct wim_inode *inode = dentry->d_inode;
1375 DEBUG("Opening \"%ls\" to set timestamps", path);
1376 h = win32_open_existing_file(path, FILE_WRITE_ATTRIBUTES);
1377 if (h == INVALID_HANDLE_VALUE) {
1378 err = GetLastError();
1382 FILETIME creationTime = {.dwLowDateTime = inode->i_creation_time & 0xffffffff,
1383 .dwHighDateTime = inode->i_creation_time >> 32};
1384 FILETIME lastAccessTime = {.dwLowDateTime = inode->i_last_access_time & 0xffffffff,
1385 .dwHighDateTime = inode->i_last_access_time >> 32};
1386 FILETIME lastWriteTime = {.dwLowDateTime = inode->i_last_write_time & 0xffffffff,
1387 .dwHighDateTime = inode->i_last_write_time >> 32};
1389 DEBUG("Calling SetFileTime() on \"%ls\"", path);
1390 if (!SetFileTime(h, &creationTime, &lastAccessTime, &lastWriteTime)) {
1391 err = GetLastError();
1395 DEBUG("Closing \"%ls\"", path);
1396 if (!CloseHandle(h)) {
1397 err = GetLastError();
1402 /* Only warn if setting timestamps failed; still return 0. */
1403 WARNING("Can't set timestamps on \"%ls\"", path);
1409 /* Replacement for POSIX fsync() */
1416 h = (HANDLE)_get_osfhandle(fd);
1417 if (h == INVALID_HANDLE_VALUE) {
1418 err = GetLastError();
1419 ERROR("Could not get Windows handle for file descriptor");
1424 if (!FlushFileBuffers(h)) {
1425 err = GetLastError();
1426 ERROR("Could not flush file buffers to disk");
1434 /* Use the Win32 API to get the number of processors */
1436 win32_get_number_of_processors()
1438 SYSTEM_INFO sysinfo;
1439 GetSystemInfo(&sysinfo);
1440 return sysinfo.dwNumberOfProcessors;
1443 /* Replacement for POSIX-2008 realpath(). Warning: partial functionality only
1444 * (resolved_path must be NULL). Also I highly doubt that GetFullPathName
1445 * really does the right thing under all circumstances. */
1447 realpath(const wchar_t *path, wchar_t *resolved_path)
1450 wimlib_assert(resolved_path == NULL);
1453 ret = GetFullPathNameW(path, 0, NULL, NULL);
1455 err = GetLastError();
1459 resolved_path = TMALLOC(ret);
1462 ret = GetFullPathNameW(path, ret, resolved_path, NULL);
1464 err = GetLastError();
1465 free(resolved_path);
1466 resolved_path = NULL;
1474 return resolved_path;
1477 /* rename() on Windows fails if the destination file exists. And we need to
1478 * make it work on wide characters. Fix it. */
1480 win32_rename_replacement(const wchar_t *oldpath, const wchar_t *newpath)
1482 if (MoveFileExW(oldpath, newpath, MOVEFILE_REPLACE_EXISTING)) {
1485 /* As usual, the possible error values are not documented */
1486 DWORD err = GetLastError();
1487 ERROR("MoveFileEx(): Can't rename \"%ls\" to \"%ls\"",
1495 /* Replacement for POSIX fnmatch() (partial functionality only) */
1497 fnmatch(const wchar_t *pattern, const wchar_t *string, int flags)
1499 if (PathMatchSpecW(string, pattern))
1505 /* truncate() replacement */
1507 win32_truncate_replacement(const wchar_t *path, off_t size)
1509 DWORD err = NO_ERROR;
1510 LARGE_INTEGER liOffset;
1512 HANDLE h = win32_open_existing_file(path, GENERIC_WRITE);
1513 if (h == INVALID_HANDLE_VALUE)
1516 liOffset.QuadPart = size;
1517 if (!SetFilePointerEx(h, liOffset, NULL, FILE_BEGIN))
1518 goto fail_close_handle;
1520 if (!SetEndOfFile(h))
1521 goto fail_close_handle;
1526 err = GetLastError();
1529 if (err == NO_ERROR)
1530 err = GetLastError();
1531 ERROR("Can't truncate \"%ls\" to %"PRIu64" bytes", path, size);
1537 #endif /* __WIN32__ */