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"
49 /* Pointers to functions that are not available on all targetted versions of
50 * Windows (XP and later). NOTE: The WINAPI annotations seem to be important; I
51 * assume it specifies a certain calling convention. */
54 static HANDLE (WINAPI *win32func_FindFirstStreamW)(LPCWSTR lpFileName,
55 STREAM_INFO_LEVELS InfoLevel,
56 LPVOID lpFindStreamData,
57 DWORD dwFlags) = NULL;
60 static BOOL (WINAPI *win32func_FindNextStreamW)(HANDLE hFindStream,
61 LPVOID lpFindStreamData) = NULL;
63 static HMODULE hKernel32 = NULL;
65 /* Try to dynamically load some functions */
71 if (hKernel32 == NULL) {
72 DEBUG("Loading Kernel32.dll");
73 hKernel32 = LoadLibraryW(L"Kernel32.dll");
74 if (hKernel32 == NULL) {
76 WARNING("Can't load Kernel32.dll");
82 DEBUG("Looking for FindFirstStreamW");
83 win32func_FindFirstStreamW = (void*)GetProcAddress(hKernel32, "FindFirstStreamW");
84 if (!win32func_FindFirstStreamW) {
85 WARNING("Could not find function FindFirstStreamW() in Kernel32.dll!");
86 WARNING("Capturing alternate data streams will not be supported.");
90 DEBUG("Looking for FindNextStreamW");
91 win32func_FindNextStreamW = (void*)GetProcAddress(hKernel32, "FindNextStreamW");
92 if (!win32func_FindNextStreamW) {
93 WARNING("Could not find function FindNextStreamW() in Kernel32.dll!");
94 WARNING("Capturing alternate data streams will not be supported.");
95 win32func_FindFirstStreamW = NULL;
100 win32_global_cleanup()
102 if (hKernel32 != NULL) {
103 DEBUG("Closing Kernel32.dll");
104 FreeLibrary(hKernel32);
109 static const wchar_t *access_denied_msg =
110 L" If you are not running this program as the administrator, you may\n"
111 " need to do so, so that all data and metadata can be backed up.\n"
112 " Otherwise, there may be no way to access the desired data or\n"
113 " metadata without taking ownership of the file or directory.\n"
116 #ifdef ENABLE_ERROR_MESSAGES
118 win32_error(u32 err_code)
122 nchars = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
123 FORMAT_MESSAGE_ALLOCATE_BUFFER,
125 (wchar_t*)&buffer, 0, NULL);
127 ERROR("Error printing error message! "
128 "Computer will self-destruct in 3 seconds.");
130 ERROR("Win32 error: %ls", buffer);
138 win32_error(GetLastError());
143 win32_open_existing_file(const wchar_t *path, DWORD dwDesiredAccess)
145 return CreateFileW(path,
148 NULL, /* lpSecurityAttributes */
150 FILE_FLAG_BACKUP_SEMANTICS |
151 FILE_FLAG_OPEN_REPARSE_POINT,
152 NULL /* hTemplateFile */);
156 win32_open_file_data_only(const wchar_t *path)
158 return win32_open_existing_file(path, FILE_READ_DATA);
162 win32_read_file(const wchar_t *filename,
163 void *handle, u64 offset, size_t size, void *buf)
168 LARGE_INTEGER liOffset = {.QuadPart = offset};
170 wimlib_assert(size <= 0xffffffff);
172 if (SetFilePointerEx(h, liOffset, NULL, FILE_BEGIN))
173 if (ReadFile(h, buf, size, &bytesRead, NULL) && bytesRead == size)
175 err = GetLastError();
176 ERROR("Error reading \"%ls\"", filename);
178 return WIMLIB_ERR_READ;
182 win32_close_file(void *handle)
184 CloseHandle((HANDLE)handle);
188 FILETIME_to_u64(const FILETIME *ft)
190 return ((u64)ft->dwHighDateTime << 32) | (u64)ft->dwLowDateTime;
194 win32_get_short_name(struct wim_dentry *dentry, const wchar_t *path)
196 WIN32_FIND_DATAW dat;
197 if (FindFirstFileW(path, &dat) && dat.cAlternateFileName[0] != L'\0') {
198 size_t short_name_nbytes = wcslen(dat.cAlternateFileName) *
200 size_t n = short_name_nbytes + sizeof(wchar_t);
201 dentry->short_name = MALLOC(n);
202 if (!dentry->short_name)
203 return WIMLIB_ERR_NOMEM;
204 memcpy(dentry->short_name, dat.cAlternateFileName, n);
205 dentry->short_name_nbytes = short_name_nbytes;
211 win32_get_security_descriptor(struct wim_dentry *dentry,
212 struct sd_set *sd_set,
215 SECURITY_INFORMATION requestedInformation;
220 requestedInformation = DACL_SECURITY_INFORMATION |
221 SACL_SECURITY_INFORMATION |
222 OWNER_SECURITY_INFORMATION |
223 GROUP_SECURITY_INFORMATION;
224 /* Request length of security descriptor */
225 status = GetFileSecurityW(path, requestedInformation,
226 NULL, 0, &lenNeeded);
227 err = GetLastError();
228 if (!status && err == ERROR_INSUFFICIENT_BUFFER) {
229 DWORD len = lenNeeded;
231 if (GetFileSecurityW(path, requestedInformation,
232 (PSECURITY_DESCRIPTOR)buf, len, &lenNeeded))
234 int security_id = sd_set_add_sd(sd_set, buf, len);
236 return WIMLIB_ERR_NOMEM;
238 dentry->d_inode->i_security_id = security_id;
242 err = GetLastError();
246 if (err == ERROR_ACCESS_DENIED) {
247 WARNING("Failed to read security descriptor of \"%ls\": "
248 "Access denied!\n%ls", path, access_denied_msg);
251 ERROR("Failed to read security descriptor of \"%ls\"", path);
253 return WIMLIB_ERR_READ;
258 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
260 const size_t path_num_chars,
261 struct wim_lookup_table *lookup_table,
262 struct sd_set *sd_set,
263 const struct capture_config *config,
265 wimlib_progress_func_t progress_func);
267 /* Reads the directory entries of directory using a Win32 API and recursively
268 * calls win32_build_dentry_tree() on them. */
270 win32_recurse_directory(struct wim_dentry *root,
271 const wchar_t *dir_path,
272 const size_t dir_path_num_chars,
273 struct wim_lookup_table *lookup_table,
274 struct sd_set *sd_set,
275 const struct capture_config *config,
277 wimlib_progress_func_t progress_func)
279 WIN32_FIND_DATAW dat;
285 /* Begin reading the directory by calling FindFirstFileW.
286 * Unlike UNIX opendir(), FindFirstFileW has file globbing built
287 * into it. But this isn't what we actually want, so just add a
288 * dummy glob to get all entries. */
289 wchar_t pattern_buf[dir_path_num_chars + 3];
290 swprintf(pattern_buf, L"%ls/*", dir_path);
291 hFind = FindFirstFileW(pattern_buf, &dat);
293 if (hFind == INVALID_HANDLE_VALUE) {
294 err = GetLastError();
295 if (err == ERROR_FILE_NOT_FOUND) {
298 ERROR("Failed to read directory \"%ls\"", dir_path);
300 return WIMLIB_ERR_READ;
305 /* Skip . and .. entries */
306 if (wcscmp(dat.cFileName, L".") && wcscmp(dat.cFileName, L".."))
308 size_t filename_num_chars = wcslen(dat.cFileName);
309 size_t new_path_num_chars = dir_path_num_chars + 1 +
311 wchar_t new_path[new_path_num_chars + 1];
313 swprintf(new_path, L"%ls/%ls", dir_path, dat.cFileName);
315 struct wim_dentry *child;
316 ret = win32_build_dentry_tree_recursive(&child,
327 dentry_add_child(root, child);
329 } while (FindNextFileW(hFind, &dat));
330 err = GetLastError();
331 if (err != ERROR_NO_MORE_FILES) {
332 ERROR("Failed to read directory \"%ls\"", dir_path);
335 ret = WIMLIB_ERR_READ;
342 /* Load a reparse point into a WIM inode. It is just stored in memory.
344 * @hFile: Open handle to a reparse point, with permission to read the reparse
347 * @inode: WIM inode for the reparse point.
349 * @lookup_table: Stream lookup table for the WIM; an entry will be added to it
350 * for the reparse point unless an entry already exists for
351 * the exact same data stream.
353 * @path: External path to the reparse point. Used for error messages only.
355 * Returns 0 on success; nonzero on failure. */
357 win32_capture_reparse_point(HANDLE hFile,
358 struct wim_inode *inode,
359 struct wim_lookup_table *lookup_table,
362 /* "Reparse point data, including the tag and optional GUID,
363 * cannot exceed 16 kilobytes." - MSDN */
364 char reparse_point_buf[16 * 1024];
367 if (!DeviceIoControl(hFile, FSCTL_GET_REPARSE_POINT,
368 NULL, /* "Not used with this operation; set to NULL" */
369 0, /* "Not used with this operation; set to 0" */
370 reparse_point_buf, /* "A pointer to a buffer that
371 receives the reparse point data */
372 sizeof(reparse_point_buf), /* "The size of the output
377 DWORD err = GetLastError();
378 ERROR("Failed to get reparse data of \"%ls\"", path);
380 return WIMLIB_ERR_READ;
382 if (bytesReturned < 8) {
383 ERROR("Reparse data on \"%ls\" is invalid", path);
384 return WIMLIB_ERR_READ;
386 inode->i_reparse_tag = le32_to_cpu(*(u32*)reparse_point_buf);
387 return inode_add_ads_with_data(inode, L"",
388 reparse_point_buf + 8,
389 bytesReturned - 8, lookup_table);
392 /* Calculate the SHA1 message digest of a Win32 data stream, which may be either
393 * an unnamed or named data stream.
395 * @path: Path to the file, with the stream noted at the end for named
396 * streams. UTF-16LE encoding.
398 * @hash: On success, the SHA1 message digest of the stream is written to
401 * Returns 0 on success; nonzero on failure.
404 win32_sha1sum(const wchar_t *path, u8 hash[SHA1_HASH_SIZE])
412 hFile = win32_open_file_data_only(path);
413 if (hFile == INVALID_HANDLE_VALUE)
414 return WIMLIB_ERR_OPEN;
418 if (!ReadFile(hFile, buf, sizeof(buf), &bytesRead, NULL)) {
419 ret = WIMLIB_ERR_READ;
420 goto out_close_handle;
424 sha1_update(&ctx, buf, bytesRead);
427 sha1_final(hash, &ctx);
433 /* Scans an unnamed or named stream of a Win32 file (not a reparse point
434 * stream); calculates its SHA1 message digest and either creates a `struct
435 * wim_lookup_table_entry' in memory for it, or uses an existing 'struct
436 * wim_lookup_table_entry' for an identical stream.
438 * @path: Path to the file (UTF-16LE).
440 * @path_num_chars: Number of 2-byte characters in @path.
442 * @inode: WIM inode to save the stream into.
444 * @lookup_table: Stream lookup table for the WIM.
446 * @dat: A `WIN32_FIND_STREAM_DATA' structure that specifies the
449 * Returns 0 on success; nonzero on failure.
452 win32_capture_stream(const wchar_t *path,
453 size_t path_num_chars,
454 struct wim_inode *inode,
455 struct wim_lookup_table *lookup_table,
456 WIN32_FIND_STREAM_DATA *dat)
458 struct wim_ads_entry *ads_entry;
459 u8 hash[SHA1_HASH_SIZE];
460 struct wim_lookup_table_entry *lte;
462 wchar_t *stream_name, *colon;
463 size_t stream_name_nchars;
464 bool is_named_stream;
468 size_t spath_buf_nbytes;
469 const wchar_t *relpath_prefix;
470 const wchar_t *colonchar;
472 /* The stream name should be returned as :NAME:TYPE */
473 stream_name = dat->cStreamName;
474 if (*stream_name != L':')
475 goto out_invalid_stream_name;
477 colon = wcschr(stream_name, L':');
479 goto out_invalid_stream_name;
481 if (wcscmp(colon + 1, L"$DATA")) {
482 /* Not a DATA stream */
489 stream_name_nchars = colon - stream_name;
490 is_named_stream = (stream_name_nchars != 0);
492 if (is_named_stream) {
493 /* Allocate an ADS entry for the named stream. */
494 ads_entry = inode_add_ads_utf16le(inode, stream_name,
495 stream_name_nchars * sizeof(wchar_t));
497 ret = WIMLIB_ERR_NOMEM;
502 /* Create a UTF-16LE string @spath that gives the filename, then a
503 * colon, then the stream name. Or, if it's an unnamed stream, just the
504 * filename. It is MALLOC()'ed so that it can be saved in the
505 * wim_lookup_table_entry if needed.
507 * As yet another special case, relative paths need to be changed to
508 * begin with an explicit "./" so that, for example, a file t:ads, where
509 * :ads is the part we added, is not interpreted as a file on the t:
511 spath_nchars = path_num_chars;
512 relpath_prefix = L"";
514 if (is_named_stream) {
515 spath_nchars += 1 + stream_name_nchars;
517 if (path_num_chars == 1 &&
522 relpath_prefix = L"./";
526 spath_buf_nbytes = (spath_nchars + 1) * sizeof(wchar_t);
527 spath = MALLOC(spath_buf_nbytes);
529 swprintf(spath, L"%ls%ls%ls%ls",
530 relpath_prefix, path, colonchar, stream_name);
532 ret = win32_sha1sum(spath, hash);
534 err = GetLastError();
535 ERROR("Failed to read \"%ls\" to calculate SHA1sum", spath);
540 lte = __lookup_resource(lookup_table, hash);
542 /* Use existing wim_lookup_table_entry that has the same SHA1
546 /* Make a new wim_lookup_table_entry */
547 lte = new_lookup_table_entry();
549 ret = WIMLIB_ERR_NOMEM;
552 lte->file_on_disk = spath;
553 lte->win32_file_on_disk_fp = INVALID_HANDLE_VALUE;
555 lte->resource_location = RESOURCE_WIN32;
556 lte->resource_entry.original_size = (uint64_t)dat->StreamSize.QuadPart;
557 lte->resource_entry.size = (uint64_t)dat->StreamSize.QuadPart;
558 copy_hash(lte->hash, hash);
559 lookup_table_insert(lookup_table, lte);
562 ads_entry->lte = lte;
569 out_invalid_stream_name:
570 ERROR("Invalid stream name: \"%ls:%ls\"", path, dat->cStreamName);
571 ret = WIMLIB_ERR_READ;
575 /* Scans a Win32 file for unnamed and named data streams (not reparse point
578 * @path: Path to the file (UTF-16LE).
580 * @path_num_chars: Number of 2-byte characters in @path.
582 * @inode: WIM inode to save the stream into.
584 * @lookup_table: Stream lookup table for the WIM.
586 * @file_size: Size of unnamed data stream. (Used only if alternate
587 * data streams API appears to be unavailable.)
589 * Returns 0 on success; nonzero on failure.
592 win32_capture_streams(const wchar_t *path,
593 size_t path_num_chars,
594 struct wim_inode *inode,
595 struct wim_lookup_table *lookup_table,
598 WIN32_FIND_STREAM_DATA dat;
603 if (win32func_FindFirstStreamW == NULL)
606 hFind = win32func_FindFirstStreamW(path, FindStreamInfoStandard, &dat, 0);
607 if (hFind == INVALID_HANDLE_VALUE) {
608 err = GetLastError();
610 if (err == ERROR_CALL_NOT_IMPLEMENTED)
613 /* Seems legal for this to return ERROR_HANDLE_EOF on reparse
614 * points and directories */
615 if ((inode->i_attributes &
616 (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
617 && err == ERROR_HANDLE_EOF)
621 if (err == ERROR_ACCESS_DENIED) {
622 WARNING("Failed to look up data streams "
623 "of \"%ls\": Access denied!\n%ls",
624 path, access_denied_msg);
627 ERROR("Failed to look up data streams "
630 return WIMLIB_ERR_READ;
635 ret = win32_capture_stream(path,
641 } while (win32func_FindNextStreamW(hFind, &dat));
642 err = GetLastError();
643 if (err != ERROR_HANDLE_EOF) {
644 ERROR("Win32 API: Error reading data streams from \"%ls\"", path);
646 ret = WIMLIB_ERR_READ;
652 if (inode->i_attributes &
653 (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
657 wcscpy(dat.cStreamName, L"::$DATA");
658 dat.StreamSize.QuadPart = file_size;
659 ret = win32_capture_stream(path,
668 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
670 const size_t path_num_chars,
671 struct wim_lookup_table *lookup_table,
672 struct sd_set *sd_set,
673 const struct capture_config *config,
675 wimlib_progress_func_t progress_func)
677 struct wim_dentry *root = NULL;
678 struct wim_inode *inode;
683 if (exclude_path(path, config, true)) {
684 if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT) {
685 ERROR("Cannot exclude the root directory from capture");
686 ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
689 if ((add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
692 union wimlib_progress_info info;
693 info.scan.cur_path = path;
694 info.scan.excluded = true;
695 progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
700 if ((add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
703 union wimlib_progress_info info;
704 info.scan.cur_path = path;
705 info.scan.excluded = false;
706 progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
709 HANDLE hFile = win32_open_existing_file(path,
710 FILE_READ_DATA | FILE_READ_ATTRIBUTES);
711 if (hFile == INVALID_HANDLE_VALUE) {
712 err = GetLastError();
713 ERROR("Win32 API: Failed to open \"%ls\"", path);
715 ret = WIMLIB_ERR_OPEN;
719 BY_HANDLE_FILE_INFORMATION file_info;
720 if (!GetFileInformationByHandle(hFile, &file_info)) {
721 err = GetLastError();
722 ERROR("Win32 API: Failed to get file information for \"%ls\"",
725 ret = WIMLIB_ERR_STAT;
726 goto out_close_handle;
729 /* Create a WIM dentry */
730 ret = new_dentry_with_timeless_inode(path_basename_with_len(path, path_num_chars),
733 goto out_close_handle;
735 /* Start preparing the associated WIM inode */
736 inode = root->d_inode;
738 inode->i_attributes = file_info.dwFileAttributes;
739 inode->i_creation_time = FILETIME_to_u64(&file_info.ftCreationTime);
740 inode->i_last_write_time = FILETIME_to_u64(&file_info.ftLastWriteTime);
741 inode->i_last_access_time = FILETIME_to_u64(&file_info.ftLastAccessTime);
742 inode->i_ino = ((u64)file_info.nFileIndexHigh << 32) |
743 (u64)file_info.nFileIndexLow;
745 inode->i_resolved = 1;
746 add_image_flags &= ~(WIMLIB_ADD_IMAGE_FLAG_ROOT | WIMLIB_ADD_IMAGE_FLAG_SOURCE);
748 /* Get DOS name and security descriptor (if any). */
749 ret = win32_get_short_name(root, path);
751 goto out_close_handle;
753 if (!(add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NO_ACLS)) {
754 ret = win32_get_security_descriptor(root, sd_set, path);
756 goto out_close_handle;
759 file_size = ((u64)file_info.nFileSizeHigh << 32) |
760 (u64)file_info.nFileSizeLow;
762 if (inode_is_directory(inode)) {
763 /* Directory (not a reparse point) --- recurse to children */
765 /* But first... directories may have alternate data streams that
766 * need to be captured. */
767 ret = win32_capture_streams(path,
773 goto out_close_handle;
774 ret = win32_recurse_directory(root,
782 } else if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
783 /* Reparse point: save the reparse tag and data */
784 ret = win32_capture_reparse_point(hFile,
789 /* Not a directory, not a reparse point; capture the default
790 * file contents and any alternate data streams. */
791 ret = win32_capture_streams(path,
803 free_dentry_tree(root, lookup_table);
807 /* Win32 version of capturing a directory tree */
809 win32_build_dentry_tree(struct wim_dentry **root_ret,
810 const wchar_t *root_disk_path,
811 struct wim_lookup_table *lookup_table,
812 struct sd_set *sd_set,
813 const struct capture_config *config,
815 wimlib_progress_func_t progress_func,
822 path_nchars = wcslen(root_disk_path);
823 if (path_nchars > 32767)
824 return WIMLIB_ERR_INVALID_PARAM;
826 /* There is no check for overflow later when this buffer is being used!
827 * But the max path length on NTFS is 32767 characters, and paths need
828 * to be written specially to even go past 260 characters, so we should
829 * be okay with 32770 characters. */
830 path = MALLOC(32770 * sizeof(wchar_t));
832 return WIMLIB_ERR_NOMEM;
834 wmemcpy(path, root_disk_path, path_nchars + 1);
836 ret = win32_build_dentry_tree_recursive(root_ret,
848 /* Replacement for POSIX fnmatch() (partial functionality only) */
850 fnmatch(const wchar_t *pattern, const wchar_t *string, int flags)
852 if (PathMatchSpecW(string, pattern))
859 win32_set_reparse_data(HANDLE h,
861 const struct wim_lookup_table_entry *lte,
869 WARNING("\"%ls\" is marked as a reparse point but had no reparse data",
873 len = wim_resource_size(lte);
874 if (len > 16 * 1024 - 8) {
875 WARNING("\"%ls\": reparse data too long!", path);
879 /* The WIM stream omits the ReparseTag and ReparseDataLength fields, so
880 * leave 8 bytes of space for them at the beginning of the buffer, then
881 * set them manually. */
882 buf = alloca(len + 8);
883 ret = read_full_wim_resource(lte, buf + 8, 0);
886 *(u32*)(buf + 0) = cpu_to_le32(reparse_tag);
887 *(u16*)(buf + 4) = cpu_to_le16(len);
888 *(u16*)(buf + 6) = 0;
890 /* Set the reparse data on the open file using the
891 * FSCTL_SET_REPARSE_POINT ioctl.
893 * There are contradictions in Microsoft's documentation for this:
895 * "If hDevice was opened without specifying FILE_FLAG_OVERLAPPED,
896 * lpOverlapped is ignored."
898 * --- So setting lpOverlapped to NULL is okay since it's ignored.
900 * "If lpOverlapped is NULL, lpBytesReturned cannot be NULL. Even when an
901 * operation returns no output data and lpOutBuffer is NULL,
902 * DeviceIoControl makes use of lpBytesReturned. After such an
903 * operation, the value of lpBytesReturned is meaningless."
905 * --- So lpOverlapped not really ignored, as it affects another
906 * parameter. This is the actual behavior: lpBytesReturned must be
907 * specified, even though lpBytesReturned is documented as:
909 * "Not used with this operation; set to NULL."
912 if (!DeviceIoControl(h, FSCTL_SET_REPARSE_POINT, buf, len + 8,
914 &bytesReturned /* lpBytesReturned */,
915 NULL /* lpOverlapped */))
917 DWORD err = GetLastError();
918 ERROR("Failed to set reparse data on \"%ls\"", path);
920 return WIMLIB_ERR_WRITE;
927 win32_extract_chunk(const void *buf, size_t len, u64 offset, void *arg)
929 HANDLE hStream = arg;
931 DWORD nbytes_written;
932 wimlib_assert(len <= 0xffffffff);
934 if (!WriteFile(hStream, buf, len, &nbytes_written, NULL) ||
935 nbytes_written != len)
937 DWORD err = GetLastError();
938 ERROR("WriteFile(): write error");
940 return WIMLIB_ERR_WRITE;
946 do_win32_extract_stream(HANDLE hStream, struct wim_lookup_table_entry *lte)
948 return extract_wim_resource(lte, wim_resource_size(lte),
949 win32_extract_chunk, hStream);
953 path_is_root_of_drive(const wchar_t *path)
958 if (*path != L'/' && *path != L'\\') {
959 if (*(path + 1) == L':')
964 while (*path == L'/' || *path == L'\\')
966 return (*path == L'\0');
970 win32_extract_stream(const struct wim_inode *inode,
972 const wchar_t *stream_name_utf16,
973 struct wim_lookup_table_entry *lte,
974 const struct wim_security_data *security_data)
976 wchar_t *stream_path;
980 DWORD creationDisposition = CREATE_ALWAYS;
982 SECURITY_ATTRIBUTES *secattr;
984 if (security_data && inode->i_security_id != -1) {
985 secattr = alloca(sizeof(*secattr));
986 secattr->nLength = sizeof(*secattr);
987 secattr->lpSecurityDescriptor = security_data->descriptors[inode->i_security_id];
988 secattr->bInheritHandle = FALSE;
993 if (stream_name_utf16) {
994 /* Named stream. Create a buffer that contains the UTF-16LE
995 * string [.\]@path:@stream_name_utf16. This is needed to
996 * create and open the stream using CreateFileW(). I'm not
997 * aware of any other APIs to do this. Note: the '$DATA' suffix
998 * seems to be unneeded. Additional note: a "./" prefix needs
999 * to be added when the path is not absolute to avoid ambiguity
1000 * with drive letters. */
1001 size_t stream_path_nchars;
1003 size_t stream_name_nchars;
1004 const wchar_t *prefix;
1006 path_nchars = wcslen(path);
1007 stream_name_nchars = wcslen(stream_name_utf16);
1008 stream_path_nchars = path_nchars + 1 + stream_name_nchars;
1009 if (path[0] != cpu_to_le16(L'\0') &&
1010 path[0] != cpu_to_le16(L'/') &&
1011 path[0] != cpu_to_le16(L'\\') &&
1012 path[1] != cpu_to_le16(L':'))
1015 stream_path_nchars += 2;
1019 stream_path = alloca((stream_path_nchars + 1) * sizeof(wchar_t));
1020 swprintf(stream_path, L"%ls%ls:%ls",
1021 prefix, path, stream_name_utf16);
1023 /* Unnamed stream; its path is just the path to the file itself.
1025 stream_path = (wchar_t*)path;
1027 /* Directories must be created with CreateDirectoryW(). Then
1028 * the call to CreateFileW() will merely open the directory that
1029 * was already created rather than creating a new file. */
1030 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1031 if (!CreateDirectoryW(stream_path, secattr)) {
1032 err = GetLastError();
1034 case ERROR_ALREADY_EXISTS:
1036 case ERROR_ACCESS_DENIED:
1037 if (path_is_root_of_drive(path))
1041 ERROR("Failed to create directory \"%ls\"",
1044 ret = WIMLIB_ERR_MKDIR;
1048 DEBUG("Created directory \"%ls\"", stream_path);
1049 if (!(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
1053 creationDisposition = OPEN_EXISTING;
1057 DEBUG("Opening \"%ls\"", stream_path);
1058 h = CreateFileW(stream_path,
1062 creationDisposition,
1063 FILE_FLAG_OPEN_REPARSE_POINT |
1064 FILE_FLAG_BACKUP_SEMANTICS |
1065 inode->i_attributes,
1067 if (h == INVALID_HANDLE_VALUE) {
1068 err = GetLastError();
1069 ERROR("Failed to create \"%ls\"", stream_path);
1071 ret = WIMLIB_ERR_OPEN;
1075 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT &&
1076 stream_name_utf16 == NULL)
1078 DEBUG("Setting reparse data on \"%ls\"", path);
1079 ret = win32_set_reparse_data(h, inode->i_reparse_tag, lte, path);
1081 goto fail_close_handle;
1084 DEBUG("Extracting \"%ls\" (len = %"PRIu64")",
1085 stream_path, wim_resource_size(lte));
1086 ret = do_win32_extract_stream(h, lte);
1088 goto fail_close_handle;
1092 DEBUG("Closing \"%ls\"", stream_path);
1093 if (!CloseHandle(h)) {
1094 err = GetLastError();
1095 ERROR("Failed to close \"%ls\"", stream_path);
1097 ret = WIMLIB_ERR_WRITE;
1105 ERROR("Error extracting %ls", stream_path);
1111 * Creates a file, directory, or reparse point and extracts all streams to it
1112 * (unnamed data stream and/or reparse point stream, plus any alternate data
1113 * streams). This in Win32-specific code.
1115 * @inode: WIM inode for this file or directory.
1116 * @path: UTF-16LE external path to extract the inode to.
1118 * Returns 0 on success; nonzero on failure.
1121 win32_extract_streams(const struct wim_inode *inode,
1122 const wchar_t *path, u64 *completed_bytes_p,
1123 const struct wim_security_data *security_data)
1125 struct wim_lookup_table_entry *unnamed_lte;
1128 unnamed_lte = inode_unnamed_lte_resolved(inode);
1129 ret = win32_extract_stream(inode, path, NULL, unnamed_lte,
1134 *completed_bytes_p += wim_resource_size(unnamed_lte);
1135 for (u16 i = 0; i < inode->i_num_ads; i++) {
1136 const struct wim_ads_entry *ads_entry = &inode->i_ads_entries[i];
1137 if (ads_entry->stream_name_nbytes != 0) {
1138 /* Skip special UNIX data entries (see documentation for
1139 * WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA) */
1140 if (ads_entry->stream_name_nbytes == WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES
1141 && !memcmp(ads_entry->stream_name,
1142 WIMLIB_UNIX_DATA_TAG_UTF16LE,
1143 WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES))
1145 ret = win32_extract_stream(inode,
1147 ads_entry->stream_name,
1153 *completed_bytes_p += wim_resource_size(ads_entry->lte);
1160 /* Extract a file, directory, reparse point, or hard link to an
1161 * already-extracted file using the Win32 API */
1162 int win32_do_apply_dentry(const wchar_t *output_path,
1163 size_t output_path_num_chars,
1164 struct wim_dentry *dentry,
1165 struct apply_args *args)
1168 struct wim_inode *inode = dentry->d_inode;
1171 if (inode->i_nlink > 1 && inode->i_extracted_file != NULL) {
1172 /* Linked file, with another name already extracted. Create a
1174 DEBUG("Creating hard link \"%ls => %ls\"",
1175 output_path, inode->i_extracted_file);
1176 if (CreateHardLinkW(output_path, inode->i_extracted_file, NULL)) {
1179 err = GetLastError();
1180 ERROR("Can't create hard link \"%ls => %ls\"",
1181 output_path, inode->i_extracted_file);
1182 ret = WIMLIB_ERR_LINK;
1186 /* Create the file, directory, or reparse point, and extract the
1188 const struct wim_security_data *security_data;
1189 if (args->extract_flags & WIMLIB_EXTRACT_FLAG_NOACLS)
1190 security_data = NULL;
1192 security_data = wim_const_security_data(args->w);
1194 ret = win32_extract_streams(inode, output_path,
1195 &args->progress.extract.completed_bytes,
1197 if (ret == 0 && inode->i_nlink > 1) {
1198 /* Save extracted path for a later call to
1199 * CreateHardLinkW() if this inode has multiple links.
1201 inode->i_extracted_file = WSTRDUP(output_path);
1202 if (!inode->i_extracted_file)
1203 ret = WIMLIB_ERR_NOMEM;
1209 /* Set timestamps on an extracted file using the Win32 API */
1211 win32_do_apply_dentry_timestamps(const wchar_t *path,
1212 size_t path_num_chars,
1213 const struct wim_dentry *dentry,
1214 const struct apply_args *args)
1218 const struct wim_inode *inode = dentry->d_inode;
1220 DEBUG("Opening \"%ls\" to set timestamps", path);
1221 h = win32_open_existing_file(path, FILE_WRITE_ATTRIBUTES);
1222 if (h == INVALID_HANDLE_VALUE) {
1223 err = GetLastError();
1227 FILETIME creationTime = {.dwLowDateTime = inode->i_creation_time & 0xffffffff,
1228 .dwHighDateTime = inode->i_creation_time >> 32};
1229 FILETIME lastAccessTime = {.dwLowDateTime = inode->i_last_access_time & 0xffffffff,
1230 .dwHighDateTime = inode->i_last_access_time >> 32};
1231 FILETIME lastWriteTime = {.dwLowDateTime = inode->i_last_write_time & 0xffffffff,
1232 .dwHighDateTime = inode->i_last_write_time >> 32};
1234 DEBUG("Calling SetFileTime() on \"%ls\"", path);
1235 if (!SetFileTime(h, &creationTime, &lastAccessTime, &lastWriteTime)) {
1236 err = GetLastError();
1240 DEBUG("Closing \"%ls\"", path);
1241 if (!CloseHandle(h)) {
1242 err = GetLastError();
1247 /* Only warn if setting timestamps failed; still return 0. */
1248 WARNING("Can't set timestamps on \"%ls\"", path);
1254 /* Replacement for POSIX fsync() */
1258 HANDLE h = (HANDLE)_get_osfhandle(fd);
1259 if (h == INVALID_HANDLE_VALUE) {
1260 ERROR("Could not get Windows handle for file descriptor");
1261 win32_error(GetLastError());
1265 if (!FlushFileBuffers(h)) {
1266 ERROR("Could not flush file buffers to disk");
1267 win32_error(GetLastError());
1274 /* Use the Win32 API to get the number of processors */
1276 win32_get_number_of_processors()
1278 SYSTEM_INFO sysinfo;
1279 GetSystemInfo(&sysinfo);
1280 return sysinfo.dwNumberOfProcessors;
1283 /* Replacement for POSIX-2008 realpath(). Warning: partial functionality only
1284 * (resolved_path must be NULL). Also I highly doubt that GetFullPathName
1285 * really does the right thing under all circumstances. */
1287 realpath(const wchar_t *path, wchar_t *resolved_path)
1290 wimlib_assert(resolved_path == NULL);
1292 ret = GetFullPathNameW(path, 0, NULL, NULL);
1296 resolved_path = TMALLOC(ret);
1299 ret = GetFullPathNameW(path, ret, resolved_path, NULL);
1301 free(resolved_path);
1304 return resolved_path;
1306 win32_error(GetLastError());
1312 nl_langinfo(nl_item item)
1314 wimlib_assert(item == CODESET);
1315 static char buf[64];
1316 strcpy(buf, "Unknown");
1320 /* rename() on Windows fails if the destination file exists. And we need to
1321 * make it work on wide characters. Fix it. */
1323 win32_rename_replacement(const wchar_t *oldpath, const wchar_t *newpath)
1325 if (MoveFileExW(oldpath, newpath, MOVEFILE_REPLACE_EXISTING)) {
1328 /* As usual, the possible error values are not documented */
1329 DWORD err = GetLastError();
1330 ERROR("MoveFileEx(): Can't rename \"%ls\" to \"%ls\"",
1338 /* truncate() replacement */
1340 win32_truncate_replacement(const wchar_t *path, off_t size)
1342 DWORD err = NO_ERROR;
1343 LARGE_INTEGER liOffset;
1345 HANDLE h = win32_open_existing_file(path, GENERIC_WRITE);
1346 if (h == INVALID_HANDLE_VALUE)
1349 liOffset.QuadPart = size;
1350 if (!SetFilePointerEx(h, liOffset, NULL, FILE_BEGIN))
1351 goto fail_close_handle;
1353 if (!SetEndOfFile(h))
1354 goto fail_close_handle;
1359 err = GetLastError();
1362 if (err == NO_ERROR)
1363 err = GetLastError();
1364 ERROR("Can't truncate %ls to %"PRIu64" bytes", path, size);