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 PathMatchSpecA() */
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 = LoadLibraryA("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 \"%s\"", 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 ret = win32_build_dentry_tree_recursive(root_ret,
846 /* Replacement for POSIX fnmatch() (partial functionality only) */
848 fnmatch(const wchar_t *pattern, const wchar_t *string, int flags)
850 if (PathMatchSpecW(string, pattern))
857 win32_set_reparse_data(HANDLE h,
859 const struct wim_lookup_table_entry *lte,
867 WARNING("\"%ls\" is marked as a reparse point but had no reparse data",
871 len = wim_resource_size(lte);
872 if (len > 16 * 1024 - 8) {
873 WARNING("\"%ls\": reparse data too long!", path);
877 /* The WIM stream omits the ReparseTag and ReparseDataLength fields, so
878 * leave 8 bytes of space for them at the beginning of the buffer, then
879 * set them manually. */
880 buf = alloca(len + 8);
881 ret = read_full_wim_resource(lte, buf + 8, 0);
884 *(u32*)(buf + 0) = cpu_to_le32(reparse_tag);
885 *(u16*)(buf + 4) = cpu_to_le16(len);
886 *(u16*)(buf + 6) = 0;
888 /* Set the reparse data on the open file using the
889 * FSCTL_SET_REPARSE_POINT ioctl.
891 * There are contradictions in Microsoft's documentation for this:
893 * "If hDevice was opened without specifying FILE_FLAG_OVERLAPPED,
894 * lpOverlapped is ignored."
896 * --- So setting lpOverlapped to NULL is okay since it's ignored.
898 * "If lpOverlapped is NULL, lpBytesReturned cannot be NULL. Even when an
899 * operation returns no output data and lpOutBuffer is NULL,
900 * DeviceIoControl makes use of lpBytesReturned. After such an
901 * operation, the value of lpBytesReturned is meaningless."
903 * --- So lpOverlapped not really ignored, as it affects another
904 * parameter. This is the actual behavior: lpBytesReturned must be
905 * specified, even though lpBytesReturned is documented as:
907 * "Not used with this operation; set to NULL."
910 if (!DeviceIoControl(h, FSCTL_SET_REPARSE_POINT, buf, len + 8,
912 &bytesReturned /* lpBytesReturned */,
913 NULL /* lpOverlapped */))
915 DWORD err = GetLastError();
916 ERROR("Failed to set reparse data on \"%ls\"", path);
918 return WIMLIB_ERR_WRITE;
925 win32_extract_chunk(const void *buf, size_t len, u64 offset, void *arg)
927 HANDLE hStream = arg;
929 DWORD nbytes_written;
930 wimlib_assert(len <= 0xffffffff);
932 if (!WriteFile(hStream, buf, len, &nbytes_written, NULL) ||
933 nbytes_written != len)
935 DWORD err = GetLastError();
936 ERROR("WriteFile(): write error");
938 return WIMLIB_ERR_WRITE;
944 do_win32_extract_stream(HANDLE hStream, struct wim_lookup_table_entry *lte)
946 return extract_wim_resource(lte, wim_resource_size(lte),
947 win32_extract_chunk, hStream);
951 win32_extract_stream(const struct wim_inode *inode,
953 const wchar_t *stream_name_utf16,
954 struct wim_lookup_table_entry *lte,
955 const struct wim_security_data *security_data)
957 wchar_t *stream_path;
961 DWORD creationDisposition = CREATE_ALWAYS;
963 SECURITY_ATTRIBUTES *secattr;
965 if (security_data && inode->i_security_id != -1) {
966 secattr = alloca(sizeof(*secattr));
967 secattr->nLength = sizeof(*secattr);
968 secattr->lpSecurityDescriptor = security_data->descriptors[inode->i_security_id];
969 secattr->bInheritHandle = FALSE;
974 if (stream_name_utf16) {
975 /* Named stream. Create a buffer that contains the UTF-16LE
976 * string [.\]@path:@stream_name_utf16. This is needed to
977 * create and open the stream using CreateFileW(). I'm not
978 * aware of any other APIs to do this. Note: the '$DATA' suffix
979 * seems to be unneeded. Additional note: a "./" prefix needs
980 * to be added when the path is not absolute to avoid ambiguity
981 * with drive letters. */
982 size_t stream_path_nchars;
984 size_t stream_name_nchars;
985 const wchar_t *prefix;
987 path_nchars = wcslen(path);
988 stream_name_nchars = wcslen(stream_name_utf16);
989 stream_path_nchars = path_nchars + 1 + stream_name_nchars;
990 if (path[0] != cpu_to_le16(L'\0') &&
991 path[0] != cpu_to_le16(L'/') &&
992 path[0] != cpu_to_le16(L'\\') &&
993 path[1] != cpu_to_le16(L':'))
996 stream_path_nchars += 2;
1000 stream_path = alloca((stream_path_nchars + 1) * sizeof(wchar_t));
1001 swprintf(stream_path, L"%ls%ls:%ls",
1002 prefix, path, stream_name_utf16);
1004 /* Unnamed stream; its path is just the path to the file itself.
1006 stream_path = (wchar_t*)path;
1008 /* Directories must be created with CreateDirectoryW(). Then
1009 * the call to CreateFileW() will merely open the directory that
1010 * was already created rather than creating a new file. */
1011 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1012 if (!CreateDirectoryW(stream_path, secattr)) {
1013 err = GetLastError();
1014 if (err != ERROR_ALREADY_EXISTS) {
1015 ERROR("Failed to create directory \"%ls\"",
1018 ret = WIMLIB_ERR_MKDIR;
1022 DEBUG("Created directory \"%ls\"", stream_path);
1023 if (!(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
1027 creationDisposition = OPEN_EXISTING;
1031 DEBUG("Opening \"%ls\"", stream_path);
1032 h = CreateFileW(stream_path,
1036 creationDisposition,
1037 FILE_FLAG_OPEN_REPARSE_POINT |
1038 FILE_FLAG_BACKUP_SEMANTICS |
1039 inode->i_attributes,
1041 if (h == INVALID_HANDLE_VALUE) {
1042 err = GetLastError();
1043 ERROR("Failed to create \"%ls\"", stream_path);
1045 ret = WIMLIB_ERR_OPEN;
1049 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT &&
1050 stream_name_utf16 == NULL)
1052 DEBUG("Setting reparse data on \"%ls\"", path);
1053 ret = win32_set_reparse_data(h, inode->i_reparse_tag, lte, path);
1055 goto fail_close_handle;
1058 DEBUG("Extracting \"%ls\" (len = %"PRIu64")",
1059 stream_path, wim_resource_size(lte));
1060 ret = do_win32_extract_stream(h, lte);
1062 goto fail_close_handle;
1066 DEBUG("Closing \"%ls\"", stream_path);
1067 if (!CloseHandle(h)) {
1068 err = GetLastError();
1069 ERROR("Failed to close \"%ls\"", stream_path);
1071 ret = WIMLIB_ERR_WRITE;
1079 ERROR("Error extracting %ls", stream_path);
1085 * Creates a file, directory, or reparse point and extracts all streams to it
1086 * (unnamed data stream and/or reparse point stream, plus any alternate data
1087 * streams). This in Win32-specific code.
1089 * @inode: WIM inode for this file or directory.
1090 * @path: UTF-16LE external path to extract the inode to.
1092 * Returns 0 on success; nonzero on failure.
1095 win32_extract_streams(const struct wim_inode *inode,
1096 const wchar_t *path, u64 *completed_bytes_p,
1097 const struct wim_security_data *security_data)
1099 struct wim_lookup_table_entry *unnamed_lte;
1102 unnamed_lte = inode_unnamed_lte_resolved(inode);
1103 ret = win32_extract_stream(inode, path, NULL, unnamed_lte,
1108 *completed_bytes_p += wim_resource_size(unnamed_lte);
1109 for (u16 i = 0; i < inode->i_num_ads; i++) {
1110 const struct wim_ads_entry *ads_entry = &inode->i_ads_entries[i];
1111 if (ads_entry->stream_name_nbytes != 0) {
1112 /* Skip special UNIX data entries (see documentation for
1113 * WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA) */
1114 if (ads_entry->stream_name_nbytes == WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES
1115 && !memcmp(ads_entry->stream_name,
1116 WIMLIB_UNIX_DATA_TAG_UTF16LE,
1117 WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES))
1119 ret = win32_extract_stream(inode,
1121 ads_entry->stream_name,
1127 *completed_bytes_p += wim_resource_size(ads_entry->lte);
1134 /* Extract a file, directory, reparse point, or hard link to an
1135 * already-extracted file using the Win32 API */
1136 int win32_do_apply_dentry(const wchar_t *output_path,
1137 size_t output_path_num_chars,
1138 struct wim_dentry *dentry,
1139 struct apply_args *args)
1142 struct wim_inode *inode = dentry->d_inode;
1145 if (inode->i_nlink > 1 && inode->i_extracted_file != NULL) {
1146 /* Linked file, with another name already extracted. Create a
1148 DEBUG("Creating hard link \"%ls => %ls\"",
1149 output_path, inode->i_extracted_file);
1150 if (CreateHardLinkW(output_path, inode->i_extracted_file, NULL)) {
1153 err = GetLastError();
1154 ERROR("Can't create hard link \"%ls => %ls\"",
1155 output_path, inode->i_extracted_file);
1156 ret = WIMLIB_ERR_LINK;
1160 /* Create the file, directory, or reparse point, and extract the
1162 const struct wim_security_data *security_data;
1163 if (args->extract_flags & WIMLIB_EXTRACT_FLAG_NOACLS)
1164 security_data = NULL;
1166 security_data = wim_const_security_data(args->w);
1168 ret = win32_extract_streams(inode, output_path,
1169 &args->progress.extract.completed_bytes,
1171 if (ret == 0 && inode->i_nlink > 1) {
1172 /* Save extracted path for a later call to
1173 * CreateHardLinkW() if this inode has multiple links.
1175 inode->i_extracted_file = WSTRDUP(output_path);
1176 if (!inode->i_extracted_file)
1177 ret = WIMLIB_ERR_NOMEM;
1183 /* Set timestamps on an extracted file using the Win32 API */
1185 win32_do_apply_dentry_timestamps(const wchar_t *path,
1186 size_t path_num_chars,
1187 const struct wim_dentry *dentry,
1188 const struct apply_args *args)
1193 const struct wim_inode *inode = dentry->d_inode;
1195 DEBUG("Opening \"%ls\" to set timestamps", path);
1196 h = win32_open_existing_file(path, FILE_WRITE_ATTRIBUTES);
1197 if (h == INVALID_HANDLE_VALUE) {
1198 err = GetLastError();
1202 FILETIME creationTime = {.dwLowDateTime = inode->i_creation_time & 0xffffffff,
1203 .dwHighDateTime = inode->i_creation_time >> 32};
1204 FILETIME lastAccessTime = {.dwLowDateTime = inode->i_last_access_time & 0xffffffff,
1205 .dwHighDateTime = inode->i_last_access_time >> 32};
1206 FILETIME lastWriteTime = {.dwLowDateTime = inode->i_last_write_time & 0xffffffff,
1207 .dwHighDateTime = inode->i_last_write_time >> 32};
1209 DEBUG("Calling SetFileTime() on \"%ls\"", path);
1210 if (!SetFileTime(h, &creationTime, &lastAccessTime, &lastWriteTime)) {
1211 err = GetLastError();
1215 DEBUG("Closing \"%ls\"", path);
1216 if (!CloseHandle(h)) {
1217 err = GetLastError();
1222 /* Only warn if setting timestamps failed; still return 0. */
1223 WARNING("Can't set timestamps on \"%ls\"", path);
1229 /* Replacement for POSIX fsync() */
1233 HANDLE h = (HANDLE)_get_osfhandle(fd);
1234 if (h == INVALID_HANDLE_VALUE) {
1235 ERROR("Could not get Windows handle for file descriptor");
1236 win32_error(GetLastError());
1240 if (!FlushFileBuffers(h)) {
1241 ERROR("Could not flush file buffers to disk");
1242 win32_error(GetLastError());
1249 /* Use the Win32 API to get the number of processors */
1251 win32_get_number_of_processors()
1253 SYSTEM_INFO sysinfo;
1254 GetSystemInfo(&sysinfo);
1255 return sysinfo.dwNumberOfProcessors;
1258 /* Replacement for POSIX-2008 realpath(). Warning: partial functionality only
1259 * (resolved_path must be NULL). Also I highly doubt that GetFullPathName
1260 * really does the right thing under all circumstances. */
1262 realpath(const wchar_t *path, wchar_t *resolved_path)
1265 wimlib_assert(resolved_path == NULL);
1267 ret = GetFullPathNameW(path, 0, NULL, NULL);
1271 resolved_path = TMALLOC(ret);
1274 ret = GetFullPathNameW(path, ret, resolved_path, NULL);
1276 free(resolved_path);
1279 return resolved_path;
1281 win32_error(GetLastError());
1287 nl_langinfo(nl_item item)
1289 wimlib_assert(item == CODESET);
1290 static char buf[64];
1291 strcpy(buf, "Unknown");
1295 /* rename() on Windows fails if the destination file exists. And we need to
1296 * make it work on wide characters. Fix it. */
1298 win32_rename_replacement(const wchar_t *oldpath, const wchar_t *newpath)
1300 if (MoveFileExW(oldpath, newpath, MOVEFILE_REPLACE_EXISTING)) {
1303 /* As usual, the possible error values are not documented */
1304 DWORD err = GetLastError();
1305 ERROR("MoveFileEx(): Can't rename \"%ls\" to \"%ls\"",
1313 /* truncate() replacement */
1315 win32_truncate_replacement(const wchar_t *path, off_t size)
1317 DWORD err = NO_ERROR;
1318 LARGE_INTEGER liOffset;
1320 HANDLE h = win32_open_existing_file(path, GENERIC_WRITE);
1321 if (h == INVALID_HANDLE_VALUE)
1324 liOffset.QuadPart = size;
1325 if (!SetFilePointerEx(h, liOffset, NULL, FILE_BEGIN))
1326 goto fail_close_handle;
1328 if (!SetEndOfFile(h))
1329 goto fail_close_handle;
1334 err = GetLastError();
1337 if (err == NO_ERROR)
1338 err = GetLastError();
1339 ERROR("Can't truncate %ls to %"PRIu64" bytes", path, size);