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/.
27 # error "This file contains Windows code"
34 #include <shlwapi.h> /* shlwapi.h for PathMatchSpecW() */
35 #ifdef ERROR /* windows.h defines this */
41 #include "lookup_table.h"
43 #include "endianness.h"
47 #define MAX_GET_SD_ACCESS_DENIED_WARNINGS 1
48 #define MAX_GET_SACL_PRIV_NOTHELD_WARNINGS 1
49 struct win32_capture_state {
50 unsigned long num_get_sd_access_denied;
51 unsigned long num_get_sacl_priv_notheld;
54 #define MAX_SET_SD_ACCESS_DENIED_WARNINGS 1
55 #define MAX_SET_SACL_PRIV_NOTHELD_WARNINGS 1
57 /* Pointers to functions that are not available on all targetted versions of
58 * Windows (XP and later). NOTE: The WINAPI annotations seem to be important; I
59 * assume it specifies a certain calling convention. */
62 static HANDLE (WINAPI *win32func_FindFirstStreamW)(LPCWSTR lpFileName,
63 STREAM_INFO_LEVELS InfoLevel,
64 LPVOID lpFindStreamData,
65 DWORD dwFlags) = NULL;
68 static BOOL (WINAPI *win32func_FindNextStreamW)(HANDLE hFindStream,
69 LPVOID lpFindStreamData) = NULL;
71 static HMODULE hKernel32 = NULL;
73 /* Try to dynamically load some functions */
79 if (hKernel32 == NULL) {
80 DEBUG("Loading Kernel32.dll");
81 hKernel32 = LoadLibraryW(L"Kernel32.dll");
82 if (hKernel32 == NULL) {
84 WARNING("Can't load Kernel32.dll");
90 DEBUG("Looking for FindFirstStreamW");
91 win32func_FindFirstStreamW = (void*)GetProcAddress(hKernel32, "FindFirstStreamW");
92 if (!win32func_FindFirstStreamW) {
93 WARNING("Could not find function FindFirstStreamW() in Kernel32.dll!");
94 WARNING("Capturing alternate data streams will not be supported.");
98 DEBUG("Looking for FindNextStreamW");
99 win32func_FindNextStreamW = (void*)GetProcAddress(hKernel32, "FindNextStreamW");
100 if (!win32func_FindNextStreamW) {
101 WARNING("Could not find function FindNextStreamW() in Kernel32.dll!");
102 WARNING("Capturing alternate data streams will not be supported.");
103 win32func_FindFirstStreamW = NULL;
108 win32_global_cleanup()
110 if (hKernel32 != NULL) {
111 DEBUG("Closing Kernel32.dll");
112 FreeLibrary(hKernel32);
117 static const wchar_t *capture_access_denied_msg =
118 L" If you are not running this program as the administrator, you may\n"
119 " need to do so, so that all data and metadata can be backed up.\n"
120 " Otherwise, there may be no way to access the desired data or\n"
121 " metadata without taking ownership of the file or directory.\n"
124 static const wchar_t *apply_access_denied_msg =
125 L"If you are not running this program as the administrator, you may\n"
126 " need to do so, so that all data and metadata can be extracted\n"
127 " exactly as the origignal copy. However, if you do not care that\n"
128 " the security descriptors are extracted correctly, you could run\n"
129 " `wimlib-imagex apply' with the --no-acls flag instead.\n"
132 #ifdef ENABLE_ERROR_MESSAGES
134 win32_error(u32 err_code)
138 nchars = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
139 FORMAT_MESSAGE_ALLOCATE_BUFFER,
141 (wchar_t*)&buffer, 0, NULL);
143 ERROR("Error printing error message! "
144 "Computer will self-destruct in 3 seconds.");
146 ERROR("Win32 error: %ls", buffer);
154 win32_error(GetLastError());
159 win32_open_existing_file(const wchar_t *path, DWORD dwDesiredAccess)
161 return CreateFileW(path,
164 NULL, /* lpSecurityAttributes */
166 FILE_FLAG_BACKUP_SEMANTICS |
167 FILE_FLAG_OPEN_REPARSE_POINT,
168 NULL /* hTemplateFile */);
172 win32_open_file_data_only(const wchar_t *path)
174 return win32_open_existing_file(path, FILE_READ_DATA);
178 win32_read_file(const wchar_t *filename,
179 void *handle, u64 offset, size_t size, void *buf)
184 LARGE_INTEGER liOffset = {.QuadPart = offset};
186 wimlib_assert(size <= 0xffffffff);
188 if (SetFilePointerEx(h, liOffset, NULL, FILE_BEGIN))
189 if (ReadFile(h, buf, size, &bytesRead, NULL) && bytesRead == size)
191 err = GetLastError();
192 ERROR("Error reading \"%ls\"", filename);
194 return WIMLIB_ERR_READ;
198 win32_close_file(void *handle)
200 CloseHandle((HANDLE)handle);
204 FILETIME_to_u64(const FILETIME *ft)
206 return ((u64)ft->dwHighDateTime << 32) | (u64)ft->dwLowDateTime;
210 win32_get_short_name(struct wim_dentry *dentry, const wchar_t *path)
212 WIN32_FIND_DATAW dat;
213 if (FindFirstFileW(path, &dat) && dat.cAlternateFileName[0] != L'\0') {
214 size_t short_name_nbytes = wcslen(dat.cAlternateFileName) *
216 size_t n = short_name_nbytes + sizeof(wchar_t);
217 dentry->short_name = MALLOC(n);
218 if (!dentry->short_name)
219 return WIMLIB_ERR_NOMEM;
220 memcpy(dentry->short_name, dat.cAlternateFileName, n);
221 dentry->short_name_nbytes = short_name_nbytes;
227 win32_get_security_descriptor(struct wim_dentry *dentry,
228 struct sd_set *sd_set,
230 struct win32_capture_state *state,
233 SECURITY_INFORMATION requestedInformation;
239 requestedInformation = DACL_SECURITY_INFORMATION |
240 SACL_SECURITY_INFORMATION |
241 OWNER_SECURITY_INFORMATION |
242 GROUP_SECURITY_INFORMATION;
244 /* Request length of security descriptor */
245 status = GetFileSecurityW(path, requestedInformation,
246 NULL, 0, &lenNeeded);
247 err = GetLastError();
248 if (!status && err == ERROR_INSUFFICIENT_BUFFER) {
249 DWORD len = lenNeeded;
251 if (GetFileSecurityW(path, requestedInformation,
252 (PSECURITY_DESCRIPTOR)buf, len, &lenNeeded))
254 int security_id = sd_set_add_sd(sd_set, buf, len);
256 return WIMLIB_ERR_NOMEM;
258 dentry->d_inode->i_security_id = security_id;
262 err = GetLastError();
266 if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_STRICT_ACLS)
270 case ERROR_PRIVILEGE_NOT_HELD:
271 if (requestedInformation & SACL_SECURITY_INFORMATION) {
272 n = state->num_get_sacl_priv_notheld++;
273 requestedInformation &= ~SACL_SECURITY_INFORMATION;
274 if (n < MAX_GET_SACL_PRIV_NOTHELD_WARNINGS) {
276 "We don't have enough privileges to read the full security\n"
277 " descriptor of \"%ls\"!\n"
278 " Re-trying with SACL omitted.\n", path);
279 } else if (n == MAX_GET_SACL_PRIV_NOTHELD_WARNINGS) {
281 "Suppressing further privileges not held error messages when reading\n"
282 " security descriptors.");
287 case ERROR_ACCESS_DENIED:
288 n = state->num_get_sd_access_denied++;
289 if (n < MAX_GET_SD_ACCESS_DENIED_WARNINGS) {
290 WARNING("Failed to read security descriptor of \"%ls\": "
291 "Access denied!\n%ls", path, capture_access_denied_msg);
292 } else if (n == MAX_GET_SD_ACCESS_DENIED_WARNINGS) {
293 WARNING("Suppressing further access denied errors messages i"
294 "when reading security descriptors");
299 ERROR("Failed to read security descriptor of \"%ls\"", path);
301 return WIMLIB_ERR_READ;
306 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
308 size_t path_num_chars,
309 struct wim_lookup_table *lookup_table,
310 struct sd_set *sd_set,
311 const struct capture_config *config,
313 wimlib_progress_func_t progress_func,
314 struct win32_capture_state *state);
316 /* Reads the directory entries of directory using a Win32 API and recursively
317 * calls win32_build_dentry_tree() on them. */
319 win32_recurse_directory(struct wim_dentry *root,
321 size_t dir_path_num_chars,
322 struct wim_lookup_table *lookup_table,
323 struct sd_set *sd_set,
324 const struct capture_config *config,
326 wimlib_progress_func_t progress_func,
327 struct win32_capture_state *state)
329 WIN32_FIND_DATAW dat;
334 /* Begin reading the directory by calling FindFirstFileW. Unlike UNIX
335 * opendir(), FindFirstFileW has file globbing built into it. But this
336 * isn't what we actually want, so just add a dummy glob to get all
338 dir_path[dir_path_num_chars] = L'/';
339 dir_path[dir_path_num_chars + 1] = L'*';
340 dir_path[dir_path_num_chars + 2] = L'\0';
341 hFind = FindFirstFileW(dir_path, &dat);
342 dir_path[dir_path_num_chars] = L'\0';
344 if (hFind == INVALID_HANDLE_VALUE) {
345 err = GetLastError();
346 if (err == ERROR_FILE_NOT_FOUND) {
349 ERROR("Failed to read directory \"%ls\"", dir_path);
351 return WIMLIB_ERR_READ;
356 /* Skip . and .. entries */
357 if (dat.cFileName[0] == L'.' &&
358 (dat.cFileName[1] == L'\0' ||
359 (dat.cFileName[1] == L'.' &&
360 dat.cFileName[2] == L'\0')))
362 size_t filename_len = wcslen(dat.cFileName);
364 dir_path[dir_path_num_chars] = L'/';
365 wmemcpy(dir_path + dir_path_num_chars + 1,
369 struct wim_dentry *child;
370 size_t path_len = dir_path_num_chars + 1 + filename_len;
371 ret = win32_build_dentry_tree_recursive(&child,
380 dir_path[dir_path_num_chars] = L'\0';
384 dentry_add_child(root, child);
385 } while (FindNextFileW(hFind, &dat));
386 err = GetLastError();
387 if (err != ERROR_NO_MORE_FILES) {
388 ERROR("Failed to read directory \"%ls\"", dir_path);
391 ret = WIMLIB_ERR_READ;
398 /* Load a reparse point into a WIM inode. It is just stored in memory.
400 * @hFile: Open handle to a reparse point, with permission to read the reparse
403 * @inode: WIM inode for the reparse point.
405 * @lookup_table: Stream lookup table for the WIM; an entry will be added to it
406 * for the reparse point unless an entry already exists for
407 * the exact same data stream.
409 * @path: External path to the reparse point. Used for error messages only.
411 * Returns 0 on success; nonzero on failure. */
413 win32_capture_reparse_point(HANDLE hFile,
414 struct wim_inode *inode,
415 struct wim_lookup_table *lookup_table,
418 /* "Reparse point data, including the tag and optional GUID,
419 * cannot exceed 16 kilobytes." - MSDN */
420 char reparse_point_buf[16 * 1024];
423 if (!DeviceIoControl(hFile, FSCTL_GET_REPARSE_POINT,
424 NULL, /* "Not used with this operation; set to NULL" */
425 0, /* "Not used with this operation; set to 0" */
426 reparse_point_buf, /* "A pointer to a buffer that
427 receives the reparse point data */
428 sizeof(reparse_point_buf), /* "The size of the output
433 DWORD err = GetLastError();
434 ERROR("Failed to get reparse data of \"%ls\"", path);
436 return WIMLIB_ERR_READ;
438 if (bytesReturned < 8) {
439 ERROR("Reparse data on \"%ls\" is invalid", path);
440 return WIMLIB_ERR_READ;
442 inode->i_reparse_tag = le32_to_cpu(*(u32*)reparse_point_buf);
443 return inode_add_ads_with_data(inode, L"",
444 reparse_point_buf + 8,
445 bytesReturned - 8, lookup_table);
448 /* Calculate the SHA1 message digest of a Win32 data stream, which may be either
449 * an unnamed or named data stream.
451 * @path: Path to the file, with the stream noted at the end for named
452 * streams. UTF-16LE encoding.
454 * @hash: On success, the SHA1 message digest of the stream is written to
457 * Returns 0 on success; nonzero on failure.
460 win32_sha1sum(const wchar_t *path, u8 hash[SHA1_HASH_SIZE])
468 hFile = win32_open_file_data_only(path);
469 if (hFile == INVALID_HANDLE_VALUE)
470 return WIMLIB_ERR_OPEN;
474 if (!ReadFile(hFile, buf, sizeof(buf), &bytesRead, NULL)) {
475 ret = WIMLIB_ERR_READ;
476 goto out_close_handle;
480 sha1_update(&ctx, buf, bytesRead);
483 sha1_final(hash, &ctx);
489 /* Scans an unnamed or named stream of a Win32 file (not a reparse point
490 * stream); calculates its SHA1 message digest and either creates a `struct
491 * wim_lookup_table_entry' in memory for it, or uses an existing 'struct
492 * wim_lookup_table_entry' for an identical stream.
494 * @path: Path to the file (UTF-16LE).
496 * @path_num_chars: Number of 2-byte characters in @path.
498 * @inode: WIM inode to save the stream into.
500 * @lookup_table: Stream lookup table for the WIM.
502 * @dat: A `WIN32_FIND_STREAM_DATA' structure that specifies the
505 * Returns 0 on success; nonzero on failure.
508 win32_capture_stream(const wchar_t *path,
509 size_t path_num_chars,
510 struct wim_inode *inode,
511 struct wim_lookup_table *lookup_table,
512 WIN32_FIND_STREAM_DATA *dat)
514 struct wim_ads_entry *ads_entry;
515 u8 hash[SHA1_HASH_SIZE];
516 struct wim_lookup_table_entry *lte;
518 wchar_t *stream_name, *colon;
519 size_t stream_name_nchars;
520 bool is_named_stream;
524 size_t spath_buf_nbytes;
525 const wchar_t *relpath_prefix;
526 const wchar_t *colonchar;
528 /* The stream name should be returned as :NAME:TYPE */
529 stream_name = dat->cStreamName;
530 if (*stream_name != L':')
531 goto out_invalid_stream_name;
533 colon = wcschr(stream_name, L':');
535 goto out_invalid_stream_name;
537 if (wcscmp(colon + 1, L"$DATA")) {
538 /* Not a DATA stream */
545 stream_name_nchars = colon - stream_name;
546 is_named_stream = (stream_name_nchars != 0);
548 if (is_named_stream) {
549 /* Allocate an ADS entry for the named stream. */
550 ads_entry = inode_add_ads_utf16le(inode, stream_name,
551 stream_name_nchars * sizeof(wchar_t));
553 ret = WIMLIB_ERR_NOMEM;
558 /* Create a UTF-16LE string @spath that gives the filename, then a
559 * colon, then the stream name. Or, if it's an unnamed stream, just the
560 * filename. It is MALLOC()'ed so that it can be saved in the
561 * wim_lookup_table_entry if needed.
563 * As yet another special case, relative paths need to be changed to
564 * begin with an explicit "./" so that, for example, a file t:ads, where
565 * :ads is the part we added, is not interpreted as a file on the t:
567 spath_nchars = path_num_chars;
568 relpath_prefix = L"";
570 if (is_named_stream) {
571 spath_nchars += 1 + stream_name_nchars;
573 if (path_num_chars == 1 &&
578 relpath_prefix = L"./";
582 spath_buf_nbytes = (spath_nchars + 1) * sizeof(wchar_t);
583 spath = MALLOC(spath_buf_nbytes);
585 swprintf(spath, L"%ls%ls%ls%ls",
586 relpath_prefix, path, colonchar, stream_name);
588 ret = win32_sha1sum(spath, hash);
590 err = GetLastError();
591 ERROR("Failed to read \"%ls\" to calculate SHA1sum", spath);
596 lte = __lookup_resource(lookup_table, hash);
598 /* Use existing wim_lookup_table_entry that has the same SHA1
602 /* Make a new wim_lookup_table_entry */
603 lte = new_lookup_table_entry();
605 ret = WIMLIB_ERR_NOMEM;
608 lte->file_on_disk = spath;
609 lte->win32_file_on_disk_fp = INVALID_HANDLE_VALUE;
611 lte->resource_location = RESOURCE_WIN32;
612 lte->resource_entry.original_size = (uint64_t)dat->StreamSize.QuadPart;
613 lte->resource_entry.size = (uint64_t)dat->StreamSize.QuadPart;
614 copy_hash(lte->hash, hash);
615 lookup_table_insert(lookup_table, lte);
618 ads_entry->lte = lte;
625 out_invalid_stream_name:
626 ERROR("Invalid stream name: \"%ls:%ls\"", path, dat->cStreamName);
627 ret = WIMLIB_ERR_READ;
631 /* Scans a Win32 file for unnamed and named data streams (not reparse point
634 * @path: Path to the file (UTF-16LE).
636 * @path_num_chars: Number of 2-byte characters in @path.
638 * @inode: WIM inode to save the stream into.
640 * @lookup_table: Stream lookup table for the WIM.
642 * @file_size: Size of unnamed data stream. (Used only if alternate
643 * data streams API appears to be unavailable.)
645 * Returns 0 on success; nonzero on failure.
648 win32_capture_streams(const wchar_t *path,
649 size_t path_num_chars,
650 struct wim_inode *inode,
651 struct wim_lookup_table *lookup_table,
654 WIN32_FIND_STREAM_DATA dat;
659 if (win32func_FindFirstStreamW == NULL)
662 hFind = win32func_FindFirstStreamW(path, FindStreamInfoStandard, &dat, 0);
663 if (hFind == INVALID_HANDLE_VALUE) {
664 err = GetLastError();
666 if (err == ERROR_CALL_NOT_IMPLEMENTED)
669 /* Seems legal for this to return ERROR_HANDLE_EOF on reparse
670 * points and directories */
671 if ((inode->i_attributes &
672 (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
673 && err == ERROR_HANDLE_EOF)
677 if (err == ERROR_ACCESS_DENIED) {
678 WARNING("Failed to look up data streams "
679 "of \"%ls\": Access denied!\n%ls",
680 path, capture_access_denied_msg);
683 ERROR("Failed to look up data streams "
686 return WIMLIB_ERR_READ;
691 ret = win32_capture_stream(path,
697 } while (win32func_FindNextStreamW(hFind, &dat));
698 err = GetLastError();
699 if (err != ERROR_HANDLE_EOF) {
700 ERROR("Win32 API: Error reading data streams from \"%ls\"", path);
702 ret = WIMLIB_ERR_READ;
708 if (inode->i_attributes &
709 (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
713 wcscpy(dat.cStreamName, L"::$DATA");
714 dat.StreamSize.QuadPart = file_size;
715 ret = win32_capture_stream(path,
724 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
726 size_t path_num_chars,
727 struct wim_lookup_table *lookup_table,
728 struct sd_set *sd_set,
729 const struct capture_config *config,
731 wimlib_progress_func_t progress_func,
732 struct win32_capture_state *state)
734 struct wim_dentry *root = NULL;
735 struct wim_inode *inode;
740 if (exclude_path(path, config, true)) {
741 if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT) {
742 ERROR("Cannot exclude the root directory from capture");
743 ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
746 if ((add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
749 union wimlib_progress_info info;
750 info.scan.cur_path = path;
751 info.scan.excluded = true;
752 progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
757 if ((add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
760 union wimlib_progress_info info;
761 info.scan.cur_path = path;
762 info.scan.excluded = false;
763 progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
766 HANDLE hFile = win32_open_existing_file(path,
767 FILE_READ_DATA | FILE_READ_ATTRIBUTES);
768 if (hFile == INVALID_HANDLE_VALUE) {
769 err = GetLastError();
770 ERROR("Win32 API: Failed to open \"%ls\"", path);
772 ret = WIMLIB_ERR_OPEN;
776 BY_HANDLE_FILE_INFORMATION file_info;
777 if (!GetFileInformationByHandle(hFile, &file_info)) {
778 err = GetLastError();
779 ERROR("Win32 API: Failed to get file information for \"%ls\"",
782 ret = WIMLIB_ERR_STAT;
783 goto out_close_handle;
786 /* Create a WIM dentry */
787 ret = new_dentry_with_timeless_inode(path_basename_with_len(path, path_num_chars),
790 goto out_close_handle;
792 /* Start preparing the associated WIM inode */
793 inode = root->d_inode;
795 inode->i_attributes = file_info.dwFileAttributes;
796 inode->i_creation_time = FILETIME_to_u64(&file_info.ftCreationTime);
797 inode->i_last_write_time = FILETIME_to_u64(&file_info.ftLastWriteTime);
798 inode->i_last_access_time = FILETIME_to_u64(&file_info.ftLastAccessTime);
799 inode->i_ino = ((u64)file_info.nFileIndexHigh << 32) |
800 (u64)file_info.nFileIndexLow;
802 inode->i_resolved = 1;
803 add_image_flags &= ~(WIMLIB_ADD_IMAGE_FLAG_ROOT | WIMLIB_ADD_IMAGE_FLAG_SOURCE);
805 /* Get DOS name and security descriptor (if any). */
806 ret = win32_get_short_name(root, path);
808 goto out_close_handle;
810 if (!(add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NO_ACLS)) {
811 ret = win32_get_security_descriptor(root, sd_set, path, state,
814 goto out_close_handle;
817 file_size = ((u64)file_info.nFileSizeHigh << 32) |
818 (u64)file_info.nFileSizeLow;
820 if (inode_is_directory(inode)) {
821 /* Directory (not a reparse point) --- recurse to children */
823 /* But first... directories may have alternate data streams that
824 * need to be captured. */
825 ret = win32_capture_streams(path,
831 goto out_close_handle;
832 ret = win32_recurse_directory(root,
841 } else if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
842 /* Reparse point: save the reparse tag and data */
843 ret = win32_capture_reparse_point(hFile,
848 /* Not a directory, not a reparse point; capture the default
849 * file contents and any alternate data streams. */
850 ret = win32_capture_streams(path,
862 free_dentry_tree(root, lookup_table);
867 win32_do_capture_warnings(const struct win32_capture_state *state,
870 if (state->num_get_sacl_priv_notheld == 0 &&
871 state->num_get_sd_access_denied == 0)
875 WARNING("Built dentry tree successfully, but with the following problem(s):");
876 if (state->num_get_sacl_priv_notheld != 0) {
877 WARNING("Could not capture SACL (System Access Control List)\n"
878 " on %lu files or directories.",
879 state->num_get_sacl_priv_notheld);
881 if (state->num_get_sd_access_denied != 0) {
882 WARNING("Could not capture security descriptor at all\n"
883 " on %lu files or directories.",
884 state->num_get_sd_access_denied);
887 "Try running the program as the Administrator to make sure all the\n"
888 " desired metadata has been captured exactly. However, if you\n"
889 " do not care about capturing security descriptors correctly, then\n"
890 " nothing more needs to be done%ls\n",
891 (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NO_ACLS) ? L"." :
892 L", although you might consider\n"
893 " passing the --no-acls flag to `wimlib-imagex capture' or\n"
894 " `wimlib-imagex append' to explicitly capture no security\n"
898 /* Win32 version of capturing a directory tree */
900 win32_build_dentry_tree(struct wim_dentry **root_ret,
901 const wchar_t *root_disk_path,
902 struct wim_lookup_table *lookup_table,
903 struct sd_set *sd_set,
904 const struct capture_config *config,
906 wimlib_progress_func_t progress_func,
912 struct win32_capture_state state;
914 path_nchars = wcslen(root_disk_path);
915 if (path_nchars > 32767)
916 return WIMLIB_ERR_INVALID_PARAM;
918 /* There is no check for overflow later when this buffer is being used!
919 * But the max path length on NTFS is 32767 characters, and paths need
920 * to be written specially to even go past 260 characters, so we should
921 * be okay with 32770 characters. */
922 path = MALLOC(32770 * sizeof(wchar_t));
924 return WIMLIB_ERR_NOMEM;
926 wmemcpy(path, root_disk_path, path_nchars + 1);
928 memset(&state, 0, sizeof(state));
929 ret = win32_build_dentry_tree_recursive(root_ret,
940 win32_do_capture_warnings(&state, add_image_flags);
945 win32_set_reparse_data(HANDLE h,
947 const struct wim_lookup_table_entry *lte,
955 WARNING("\"%ls\" is marked as a reparse point but had no reparse data",
959 len = wim_resource_size(lte);
960 if (len > 16 * 1024 - 8) {
961 WARNING("\"%ls\": reparse data too long!", path);
965 /* The WIM stream omits the ReparseTag and ReparseDataLength fields, so
966 * leave 8 bytes of space for them at the beginning of the buffer, then
967 * set them manually. */
968 buf = alloca(len + 8);
969 ret = read_full_wim_resource(lte, buf + 8, 0);
972 *(u32*)(buf + 0) = cpu_to_le32(reparse_tag);
973 *(u16*)(buf + 4) = cpu_to_le16(len);
974 *(u16*)(buf + 6) = 0;
976 /* Set the reparse data on the open file using the
977 * FSCTL_SET_REPARSE_POINT ioctl.
979 * There are contradictions in Microsoft's documentation for this:
981 * "If hDevice was opened without specifying FILE_FLAG_OVERLAPPED,
982 * lpOverlapped is ignored."
984 * --- So setting lpOverlapped to NULL is okay since it's ignored.
986 * "If lpOverlapped is NULL, lpBytesReturned cannot be NULL. Even when an
987 * operation returns no output data and lpOutBuffer is NULL,
988 * DeviceIoControl makes use of lpBytesReturned. After such an
989 * operation, the value of lpBytesReturned is meaningless."
991 * --- So lpOverlapped not really ignored, as it affects another
992 * parameter. This is the actual behavior: lpBytesReturned must be
993 * specified, even though lpBytesReturned is documented as:
995 * "Not used with this operation; set to NULL."
998 if (!DeviceIoControl(h, FSCTL_SET_REPARSE_POINT, buf, len + 8,
1000 &bytesReturned /* lpBytesReturned */,
1001 NULL /* lpOverlapped */))
1003 DWORD err = GetLastError();
1004 ERROR("Failed to set reparse data on \"%ls\"", path);
1006 return WIMLIB_ERR_WRITE;
1012 * Sets the security descriptor on an extracted file.
1015 win32_set_security_data(const struct wim_inode *inode,
1016 const wchar_t *path,
1017 struct apply_args *args)
1019 PSECURITY_DESCRIPTOR descriptor;
1023 descriptor = wim_const_security_data(args->w)->descriptors[inode->i_security_id];
1025 SECURITY_INFORMATION securityInformation = DACL_SECURITY_INFORMATION |
1026 SACL_SECURITY_INFORMATION |
1027 OWNER_SECURITY_INFORMATION |
1028 GROUP_SECURITY_INFORMATION;
1030 if (SetFileSecurityW(path, securityInformation, descriptor))
1033 err = GetLastError();
1035 if (args->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS)
1039 case ERROR_PRIVILEGE_NOT_HELD:
1040 if (securityInformation & SACL_SECURITY_INFORMATION) {
1041 n = args->num_set_sacl_priv_notheld++;
1042 securityInformation &= ~SACL_SECURITY_INFORMATION;
1043 if (n < MAX_SET_SACL_PRIV_NOTHELD_WARNINGS) {
1045 "We don't have enough privileges to set the full security\n"
1046 " descriptor on \"%ls\"!\n", path);
1047 if (args->num_set_sd_access_denied +
1048 args->num_set_sacl_priv_notheld == 1)
1050 WARNING("%ls", apply_access_denied_msg);
1052 WARNING("Re-trying with SACL omitted.\n", path);
1053 } else if (n == MAX_GET_SACL_PRIV_NOTHELD_WARNINGS) {
1055 "Suppressing further 'privileges not held' error messages when setting\n"
1056 " security descriptors.");
1061 case ERROR_INVALID_OWNER:
1062 case ERROR_ACCESS_DENIED:
1063 n = args->num_set_sd_access_denied++;
1064 if (n < MAX_SET_SD_ACCESS_DENIED_WARNINGS) {
1065 WARNING("Failed to set security descriptor on \"%ls\": "
1066 "Access denied!\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 } else if (n == MAX_SET_SD_ACCESS_DENIED_WARNINGS) {
1074 "Suppressing further access denied error messages when setting\n"
1075 " security descriptors");
1080 ERROR("Failed to set security descriptor on \"%ls\"", path);
1082 return WIMLIB_ERR_WRITE;
1089 win32_extract_chunk(const void *buf, size_t len, u64 offset, void *arg)
1091 HANDLE hStream = arg;
1093 DWORD nbytes_written;
1094 wimlib_assert(len <= 0xffffffff);
1096 if (!WriteFile(hStream, buf, len, &nbytes_written, NULL) ||
1097 nbytes_written != len)
1099 DWORD err = GetLastError();
1100 ERROR("WriteFile(): write error");
1102 return WIMLIB_ERR_WRITE;
1108 do_win32_extract_stream(HANDLE hStream, struct wim_lookup_table_entry *lte)
1110 return extract_wim_resource(lte, wim_resource_size(lte),
1111 win32_extract_chunk, hStream);
1115 path_is_root_of_drive(const wchar_t *path)
1120 if (*path != L'/' && *path != L'\\') {
1121 if (*(path + 1) == L':')
1126 while (*path == L'/' || *path == L'\\')
1128 return (*path == L'\0');
1132 win32_extract_stream(const struct wim_inode *inode,
1133 const wchar_t *path,
1134 const wchar_t *stream_name_utf16,
1135 struct wim_lookup_table_entry *lte)
1137 wchar_t *stream_path;
1141 DWORD creationDisposition = CREATE_ALWAYS;
1143 if (stream_name_utf16) {
1144 /* Named stream. Create a buffer that contains the UTF-16LE
1145 * string [.\]@path:@stream_name_utf16. This is needed to
1146 * create and open the stream using CreateFileW(). I'm not
1147 * aware of any other APIs to do this. Note: the '$DATA' suffix
1148 * seems to be unneeded. Additional note: a "./" prefix needs
1149 * to be added when the path is not absolute to avoid ambiguity
1150 * with drive letters. */
1151 size_t stream_path_nchars;
1153 size_t stream_name_nchars;
1154 const wchar_t *prefix;
1156 path_nchars = wcslen(path);
1157 stream_name_nchars = wcslen(stream_name_utf16);
1158 stream_path_nchars = path_nchars + 1 + stream_name_nchars;
1159 if (path[0] != cpu_to_le16(L'\0') &&
1160 path[0] != cpu_to_le16(L'/') &&
1161 path[0] != cpu_to_le16(L'\\') &&
1162 path[1] != cpu_to_le16(L':'))
1165 stream_path_nchars += 2;
1169 stream_path = alloca((stream_path_nchars + 1) * sizeof(wchar_t));
1170 swprintf(stream_path, L"%ls%ls:%ls",
1171 prefix, path, stream_name_utf16);
1173 /* Unnamed stream; its path is just the path to the file itself.
1175 stream_path = (wchar_t*)path;
1177 /* Directories must be created with CreateDirectoryW(). Then
1178 * the call to CreateFileW() will merely open the directory that
1179 * was already created rather than creating a new file. */
1180 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1181 if (!CreateDirectoryW(stream_path, NULL)) {
1182 err = GetLastError();
1184 case ERROR_ALREADY_EXISTS:
1186 case ERROR_ACCESS_DENIED:
1187 if (path_is_root_of_drive(path))
1191 ERROR("Failed to create directory \"%ls\"",
1194 ret = WIMLIB_ERR_MKDIR;
1198 DEBUG("Created directory \"%ls\"", stream_path);
1199 if (!(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
1203 creationDisposition = OPEN_EXISTING;
1207 DEBUG("Opening \"%ls\"", stream_path);
1208 h = CreateFileW(stream_path,
1212 creationDisposition,
1213 FILE_FLAG_OPEN_REPARSE_POINT |
1214 FILE_FLAG_BACKUP_SEMANTICS |
1215 inode->i_attributes,
1217 if (h == INVALID_HANDLE_VALUE) {
1218 err = GetLastError();
1219 ERROR("Failed to create \"%ls\"", stream_path);
1221 ret = WIMLIB_ERR_OPEN;
1225 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT &&
1226 stream_name_utf16 == NULL)
1228 DEBUG("Setting reparse data on \"%ls\"", path);
1229 ret = win32_set_reparse_data(h, inode->i_reparse_tag, lte, path);
1231 goto fail_close_handle;
1234 DEBUG("Extracting \"%ls\" (len = %"PRIu64")",
1235 stream_path, wim_resource_size(lte));
1236 ret = do_win32_extract_stream(h, lte);
1238 goto fail_close_handle;
1242 DEBUG("Closing \"%ls\"", stream_path);
1243 if (!CloseHandle(h)) {
1244 err = GetLastError();
1245 ERROR("Failed to close \"%ls\"", stream_path);
1247 ret = WIMLIB_ERR_WRITE;
1255 ERROR("Error extracting %ls", stream_path);
1261 * Creates a file, directory, or reparse point and extracts all streams to it
1262 * (unnamed data stream and/or reparse point stream, plus any alternate data
1263 * streams). This in Win32-specific code.
1265 * @inode: WIM inode for this file or directory.
1266 * @path: UTF-16LE external path to extract the inode to.
1268 * Returns 0 on success; nonzero on failure.
1271 win32_extract_streams(const struct wim_inode *inode,
1272 const wchar_t *path, u64 *completed_bytes_p)
1274 struct wim_lookup_table_entry *unnamed_lte;
1277 unnamed_lte = inode_unnamed_lte_resolved(inode);
1278 ret = win32_extract_stream(inode, path, NULL, unnamed_lte);
1282 *completed_bytes_p += wim_resource_size(unnamed_lte);
1283 for (u16 i = 0; i < inode->i_num_ads; i++) {
1284 const struct wim_ads_entry *ads_entry = &inode->i_ads_entries[i];
1285 if (ads_entry->stream_name_nbytes != 0) {
1286 /* Skip special UNIX data entries (see documentation for
1287 * WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA) */
1288 if (ads_entry->stream_name_nbytes == WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES
1289 && !memcmp(ads_entry->stream_name,
1290 WIMLIB_UNIX_DATA_TAG_UTF16LE,
1291 WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES))
1293 ret = win32_extract_stream(inode,
1295 ads_entry->stream_name,
1300 *completed_bytes_p += wim_resource_size(ads_entry->lte);
1307 /* Extract a file, directory, reparse point, or hard link to an
1308 * already-extracted file using the Win32 API */
1310 win32_do_apply_dentry(const wchar_t *output_path,
1311 size_t output_path_num_chars,
1312 struct wim_dentry *dentry,
1313 struct apply_args *args)
1316 struct wim_inode *inode = dentry->d_inode;
1319 if (inode->i_nlink > 1 && inode->i_extracted_file != NULL) {
1320 /* Linked file, with another name already extracted. Create a
1322 DEBUG("Creating hard link \"%ls => %ls\"",
1323 output_path, inode->i_extracted_file);
1324 if (!CreateHardLinkW(output_path, inode->i_extracted_file, NULL)) {
1325 err = GetLastError();
1326 ERROR("Can't create hard link \"%ls => %ls\"",
1327 output_path, inode->i_extracted_file);
1329 return WIMLIB_ERR_LINK;
1332 /* Create the file, directory, or reparse point, and extract the
1334 ret = win32_extract_streams(inode, output_path,
1335 &args->progress.extract.completed_bytes);
1339 if (inode->i_security_id >= 0 &&
1340 !(args->extract_flags & WIMLIB_EXTRACT_FLAG_NO_ACLS))
1342 ret = win32_set_security_data(inode, output_path, args);
1346 if (inode->i_nlink > 1) {
1347 /* Save extracted path for a later call to
1348 * CreateHardLinkW() if this inode has multiple links.
1350 inode->i_extracted_file = WSTRDUP(output_path);
1351 if (!inode->i_extracted_file)
1352 ret = WIMLIB_ERR_NOMEM;
1358 /* Set timestamps on an extracted file using the Win32 API */
1360 win32_do_apply_dentry_timestamps(const wchar_t *path,
1361 size_t path_num_chars,
1362 const struct wim_dentry *dentry,
1363 const struct apply_args *args)
1367 const struct wim_inode *inode = dentry->d_inode;
1369 DEBUG("Opening \"%ls\" to set timestamps", path);
1370 h = win32_open_existing_file(path, FILE_WRITE_ATTRIBUTES);
1371 if (h == INVALID_HANDLE_VALUE) {
1372 err = GetLastError();
1376 FILETIME creationTime = {.dwLowDateTime = inode->i_creation_time & 0xffffffff,
1377 .dwHighDateTime = inode->i_creation_time >> 32};
1378 FILETIME lastAccessTime = {.dwLowDateTime = inode->i_last_access_time & 0xffffffff,
1379 .dwHighDateTime = inode->i_last_access_time >> 32};
1380 FILETIME lastWriteTime = {.dwLowDateTime = inode->i_last_write_time & 0xffffffff,
1381 .dwHighDateTime = inode->i_last_write_time >> 32};
1383 DEBUG("Calling SetFileTime() on \"%ls\"", path);
1384 if (!SetFileTime(h, &creationTime, &lastAccessTime, &lastWriteTime)) {
1385 err = GetLastError();
1389 DEBUG("Closing \"%ls\"", path);
1390 if (!CloseHandle(h)) {
1391 err = GetLastError();
1396 /* Only warn if setting timestamps failed; still return 0. */
1397 WARNING("Can't set timestamps on \"%ls\"", path);
1403 /* Replacement for POSIX fsync() */
1407 HANDLE h = (HANDLE)_get_osfhandle(fd);
1408 if (h == INVALID_HANDLE_VALUE) {
1409 ERROR("Could not get Windows handle for file descriptor");
1410 win32_error(GetLastError());
1414 if (!FlushFileBuffers(h)) {
1415 ERROR("Could not flush file buffers to disk");
1416 win32_error(GetLastError());
1423 /* Use the Win32 API to get the number of processors */
1425 win32_get_number_of_processors()
1427 SYSTEM_INFO sysinfo;
1428 GetSystemInfo(&sysinfo);
1429 return sysinfo.dwNumberOfProcessors;
1432 /* Replacement for POSIX-2008 realpath(). Warning: partial functionality only
1433 * (resolved_path must be NULL). Also I highly doubt that GetFullPathName
1434 * really does the right thing under all circumstances. */
1436 realpath(const wchar_t *path, wchar_t *resolved_path)
1439 wimlib_assert(resolved_path == NULL);
1441 ret = GetFullPathNameW(path, 0, NULL, NULL);
1445 resolved_path = TMALLOC(ret);
1448 ret = GetFullPathNameW(path, ret, resolved_path, NULL);
1450 free(resolved_path);
1453 return resolved_path;
1455 win32_error(GetLastError());
1461 nl_langinfo(nl_item item)
1463 wimlib_assert(item == CODESET);
1464 static char buf[64];
1465 strcpy(buf, "Unknown");
1469 /* rename() on Windows fails if the destination file exists. And we need to
1470 * make it work on wide characters. Fix it. */
1472 win32_rename_replacement(const wchar_t *oldpath, const wchar_t *newpath)
1474 if (MoveFileExW(oldpath, newpath, MOVEFILE_REPLACE_EXISTING)) {
1477 /* As usual, the possible error values are not documented */
1478 DWORD err = GetLastError();
1479 ERROR("MoveFileEx(): Can't rename \"%ls\" to \"%ls\"",
1487 /* Replacement for POSIX fnmatch() (partial functionality only) */
1489 fnmatch(const wchar_t *pattern, const wchar_t *string, int flags)
1491 if (PathMatchSpecW(string, pattern))
1497 /* truncate() replacement */
1499 win32_truncate_replacement(const wchar_t *path, off_t size)
1501 DWORD err = NO_ERROR;
1502 LARGE_INTEGER liOffset;
1504 HANDLE h = win32_open_existing_file(path, GENERIC_WRITE);
1505 if (h == INVALID_HANDLE_VALUE)
1508 liOffset.QuadPart = size;
1509 if (!SetFilePointerEx(h, liOffset, NULL, FILE_BEGIN))
1510 goto fail_close_handle;
1512 if (!SetEndOfFile(h))
1513 goto fail_close_handle;
1518 err = GetLastError();
1521 if (err == NO_ERROR)
1522 err = GetLastError();
1523 ERROR("Can't truncate %ls to %"PRIu64" bytes", path, size);