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 */
73 if (hKernel32 == NULL) {
74 DEBUG("Loading Kernel32.dll");
75 hKernel32 = LoadLibraryA("Kernel32.dll");
76 if (hKernel32 == NULL) {
78 WARNING("Can't load Kernel32.dll");
84 DEBUG("Looking for FindFirstStreamW");
85 win32func_FindFirstStreamW = (void*)GetProcAddress(hKernel32, "FindFirstStreamW");
86 if (!win32func_FindFirstStreamW) {
87 WARNING("Could not find function FindFirstStreamW() in Kernel32.dll!");
88 WARNING("Capturing alternate data streams will not be supported.");
92 DEBUG("Looking for FindNextStreamW");
93 win32func_FindNextStreamW = (void*)GetProcAddress(hKernel32, "FindNextStreamW");
94 if (!win32func_FindNextStreamW) {
95 WARNING("Could not find function FindNextStreamW() in Kernel32.dll!");
96 WARNING("Capturing alternate data streams will not be supported.");
97 win32func_FindFirstStreamW = NULL;
102 win32_global_cleanup()
104 if (hKernel32 != NULL) {
105 DEBUG("Closing Kernel32.dll");
106 FreeLibrary(hKernel32);
111 static const char *access_denied_msg =
112 " If you are not running this program as the administrator, you may\n"
113 " need to do so, so that all data and metadata can be backed up.\n"
114 " Otherwise, there may be no way to access the desired data or\n"
115 " metadata without taking ownership of the file or directory.\n";
117 #ifdef ENABLE_ERROR_MESSAGES
119 win32_error(u32 err_code)
123 nchars = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
125 (char*)&buffer, 0, NULL);
127 ERROR("Error printing error message! "
128 "Computer will self-destruct in 3 seconds.");
130 ERROR("Win32 error: %s", 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 utf16lechar *win32_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\"", win32_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,
195 const wchar_t *path_utf16)
197 WIN32_FIND_DATAW dat;
198 if (FindFirstFileW(path_utf16, &dat) &&
199 dat.cAlternateFileName[0] != L'\0')
201 size_t short_name_nbytes = wcslen(dat.cAlternateFileName) * 2;
202 size_t n = short_name_nbytes + sizeof(wchar_t);
203 dentry->short_name = MALLOC(n);
204 if (!dentry->short_name)
205 return WIMLIB_ERR_NOMEM;
206 memcpy(dentry->short_name, dat.cAlternateFileName, n);
207 dentry->short_name_nbytes = short_name_nbytes;
213 win32_get_security_descriptor(struct wim_dentry *dentry,
214 struct sd_set *sd_set,
215 const wchar_t *path_utf16)
217 SECURITY_INFORMATION requestedInformation;
222 requestedInformation = DACL_SECURITY_INFORMATION |
223 SACL_SECURITY_INFORMATION |
224 OWNER_SECURITY_INFORMATION |
225 GROUP_SECURITY_INFORMATION;
226 /* Request length of security descriptor */
227 status = GetFileSecurityW(path_utf16, requestedInformation,
228 NULL, 0, &lenNeeded);
229 err = GetLastError();
230 if (!status && err == ERROR_INSUFFICIENT_BUFFER) {
231 DWORD len = lenNeeded;
233 if (GetFileSecurityW(path_utf16, requestedInformation,
234 (PSECURITY_DESCRIPTOR)buf, len, &lenNeeded))
236 int security_id = sd_set_add_sd(sd_set, buf, len);
238 return WIMLIB_ERR_NOMEM;
240 dentry->d_inode->i_security_id = security_id;
244 err = GetLastError();
248 if (err == ERROR_ACCESS_DENIED) {
249 WARNING("Failed to read security descriptor of \"%ls\": "
250 "Access denied!\n%s", path_utf16, access_denied_msg);
253 ERROR("Win32 API: Failed to read security descriptor of \"%ls\"",
256 return WIMLIB_ERR_READ;
260 /* Reads the directory entries of directory using a Win32 API and recursively
261 * calls win32_build_dentry_tree() on them. */
263 win32_recurse_directory(struct wim_dentry *root,
264 const mbchar *root_disk_path,
265 struct wim_lookup_table *lookup_table,
266 struct wim_security_data *sd,
267 const struct capture_config *config,
269 wimlib_progress_func_t progress_func,
270 struct sd_set *sd_set,
271 const wchar_t *path_utf16,
272 size_t path_utf16_nchars)
274 WIN32_FIND_DATAW dat;
280 /* Begin reading the directory by calling FindFirstFileW.
281 * Unlike UNIX opendir(), FindFirstFileW has file globbing built
282 * into it. But this isn't what we actually want, so just add a
283 * dummy glob to get all entries. */
284 wchar_t pattern_buf[path_utf16_nchars + 3];
285 memcpy(pattern_buf, path_utf16,
286 path_utf16_nchars * sizeof(wchar_t));
287 pattern_buf[path_utf16_nchars] = L'/';
288 pattern_buf[path_utf16_nchars + 1] = L'*';
289 pattern_buf[path_utf16_nchars + 2] = L'\0';
290 hFind = FindFirstFileW(pattern_buf, &dat);
292 if (hFind == INVALID_HANDLE_VALUE) {
293 err = GetLastError();
294 if (err == ERROR_FILE_NOT_FOUND) {
297 ERROR("Win32 API: Failed to read directory \"%s\"",
300 return WIMLIB_ERR_READ;
305 /* Skip . and .. entries */
306 if (!(dat.cFileName[0] == cpu_to_le16(L'.') &&
307 (dat.cFileName[1] == cpu_to_le16(L'\0') ||
308 (dat.cFileName[1] == cpu_to_le16(L'.') &&
309 dat.cFileName[2] == cpu_to_le16(L'\0')))))
311 struct wim_dentry *child;
314 size_t mbs_name_nbytes;
315 ret = utf16le_to_mbs(dat.cFileName,
316 wcslen(dat.cFileName) * sizeof(wchar_t),
322 mbchar name[strlen(root_disk_path) + 1 + mbs_name_nbytes + 1];
323 sprintf(name, "%s/%s", root_disk_path, mbs_name);
325 ret = win32_build_dentry_tree(&child, name, lookup_table,
326 sd, config, add_image_flags,
327 progress_func, sd_set);
331 dentry_add_child(root, child);
333 } while (FindNextFileW(hFind, &dat));
334 err = GetLastError();
335 if (err != ERROR_NO_MORE_FILES) {
336 ERROR("Win32 API: Failed to read directory \"%s\"", root_disk_path);
339 ret = WIMLIB_ERR_READ;
346 /* Load a reparse point into a WIM inode. It is just stored in memory.
348 * @hFile: Open handle to a reparse point, with permission to read the reparse
351 * @inode: WIM inode for the reparse point.
353 * @lookup_table: Stream lookup table for the WIM; an entry will be added to it
354 * for the reparse point unless an entry already exists for
355 * the exact same data stream.
357 * @path: External path to the reparse point. Used for error messages only.
359 * Returns 0 on success; nonzero on failure. */
361 win32_capture_reparse_point(HANDLE hFile,
362 struct wim_inode *inode,
363 struct wim_lookup_table *lookup_table,
366 /* "Reparse point data, including the tag and optional GUID,
367 * cannot exceed 16 kilobytes." - MSDN */
368 char reparse_point_buf[16 * 1024];
371 if (!DeviceIoControl(hFile, FSCTL_GET_REPARSE_POINT,
372 NULL, /* "Not used with this operation; set to NULL" */
373 0, /* "Not used with this operation; set to 0" */
374 reparse_point_buf, /* "A pointer to a buffer that
375 receives the reparse point data */
376 sizeof(reparse_point_buf), /* "The size of the output
381 DWORD err = GetLastError();
382 ERROR("Win32 API: Failed to get reparse data of \"%s\"", path);
384 return WIMLIB_ERR_READ;
386 if (bytesReturned < 8) {
387 ERROR("Reparse data on \"%s\" is invalid", path);
388 return WIMLIB_ERR_READ;
390 inode->i_reparse_tag = le32_to_cpu(*(u32*)reparse_point_buf);
391 return inode_add_ads_with_data(inode, "",
392 reparse_point_buf + 8,
393 bytesReturned - 8, lookup_table);
396 /* Calculate the SHA1 message digest of a Win32 data stream, which may be either
397 * an unnamed or named data stream.
399 * @path: Path to the file, with the stream noted at the end for named
400 * streams. UTF-16LE encoding.
402 * @hash: On success, the SHA1 message digest of the stream is written to
405 * Returns 0 on success; nonzero on failure.
408 win32_sha1sum(const wchar_t *path, u8 hash[SHA1_HASH_SIZE])
416 hFile = win32_open_file_data_only(path);
417 if (hFile == INVALID_HANDLE_VALUE)
418 return WIMLIB_ERR_OPEN;
422 if (!ReadFile(hFile, buf, sizeof(buf), &bytesRead, NULL)) {
423 ret = WIMLIB_ERR_READ;
424 goto out_close_handle;
428 sha1_update(&ctx, buf, bytesRead);
431 sha1_final(hash, &ctx);
437 /* Scans an unnamed or named stream of a Win32 file (not a reparse point
438 * stream); calculates its SHA1 message digest and either creates a `struct
439 * wim_lookup_table_entry' in memory for it, or uses an existing 'struct
440 * wim_lookup_table_entry' for an identical stream.
442 * @path_utf16: Path to the file (UTF-16LE).
444 * @path_utf16_nchars: Number of 2-byte characters in @path_utf16.
446 * @inode: WIM inode to save the stream into.
448 * @lookup_table: Stream lookup table for the WIM.
450 * @dat: A `WIN32_FIND_STREAM_DATA' structure that specifies the
453 * Returns 0 on success; nonzero on failure.
456 win32_capture_stream(const wchar_t *path_utf16,
457 size_t path_utf16_nchars,
458 struct wim_inode *inode,
459 struct wim_lookup_table *lookup_table,
460 WIN32_FIND_STREAM_DATA *dat)
462 struct wim_ads_entry *ads_entry;
463 u8 hash[SHA1_HASH_SIZE];
464 struct wim_lookup_table_entry *lte;
466 wchar_t *stream_name, *colon;
467 size_t stream_name_nchars;
468 bool is_named_stream;
472 size_t spath_buf_nbytes;
473 const wchar_t *relpath_prefix;
474 const wchar_t *colonchar;
476 /* The stream name should be returned as :NAME:TYPE */
477 stream_name = dat->cStreamName;
478 if (*stream_name != L':')
479 goto out_invalid_stream_name;
481 colon = wcschr(stream_name, L':');
483 goto out_invalid_stream_name;
485 if (wcscmp(colon + 1, L"$DATA")) {
486 /* Not a DATA stream */
493 stream_name_nchars = colon - stream_name;
494 is_named_stream = (stream_name_nchars != 0);
496 if (is_named_stream) {
497 /* Allocate an ADS entry for the named stream. */
498 ads_entry = inode_add_ads_utf16le(inode, stream_name,
499 stream_name_nchars * 2);
501 ret = WIMLIB_ERR_NOMEM;
506 /* Create a UTF-16LE string @spath that gives the filename, then a
507 * colon, then the stream name. Or, if it's an unnamed stream, just the
508 * filename. It is MALLOC()'ed so that it can be saved in the
509 * wim_lookup_table_entry if needed.
511 * As yet another special case, relative paths need to be changed to
512 * begin with an explicit "./" so that, for example, a file t:ads, where
513 * :ads is the part we added, is not interpreted as a file on the t:
515 spath_nchars = path_utf16_nchars;
516 relpath_prefix = L"";
518 if (is_named_stream) {
519 spath_nchars += 1 + stream_name_nchars;
521 if (path_utf16_nchars == 1 &&
522 path_utf16[0] != cpu_to_le16('/') &&
523 path_utf16[0] != cpu_to_le16('\\'))
526 relpath_prefix = L"./";
530 spath_buf_nbytes = (spath_nchars + 1) * sizeof(wchar_t);
531 spath = MALLOC(spath_buf_nbytes);
533 swprintf(spath, spath_buf_nbytes, L"%ls%ls%ls%ls",
534 relpath_prefix, path_utf16, colonchar, stream_name);
536 ret = win32_sha1sum(spath, hash);
538 err = GetLastError();
539 ERROR("Win32 API: Failed to read \"%ls\" to calculate SHA1sum",
545 lte = __lookup_resource(lookup_table, hash);
547 /* Use existing wim_lookup_table_entry that has the same SHA1
551 /* Make a new wim_lookup_table_entry */
552 lte = new_lookup_table_entry();
554 ret = WIMLIB_ERR_NOMEM;
557 lte->win32_file_on_disk = spath;
558 lte->file_on_disk_fp = INVALID_HANDLE_VALUE;
560 lte->resource_location = RESOURCE_WIN32;
561 lte->resource_entry.original_size = (uint64_t)dat->StreamSize.QuadPart;
562 lte->resource_entry.size = (uint64_t)dat->StreamSize.QuadPart;
563 copy_hash(lte->hash, hash);
564 lookup_table_insert(lookup_table, lte);
567 ads_entry->lte = lte;
574 out_invalid_stream_name:
575 ERROR("Invalid stream name: \"%ls:%ls\"", path_utf16, dat->cStreamName);
576 ret = WIMLIB_ERR_READ;
580 /* Scans a Win32 file for unnamed and named data streams (not reparse point
583 * @path_utf16: Path to the file (UTF-16LE).
585 * @path_utf16_nchars: Number of 2-byte characters in @path_utf16.
587 * @inode: WIM inode to save the stream into.
589 * @lookup_table: Stream lookup table for the WIM.
591 * @file_size: Size of unnamed data stream. (Used only if alternate
592 * data streams API appears to be unavailable.)
594 * Returns 0 on success; nonzero on failure.
597 win32_capture_streams(const wchar_t *path_utf16,
598 size_t path_utf16_nchars,
599 struct wim_inode *inode,
600 struct wim_lookup_table *lookup_table,
603 WIN32_FIND_STREAM_DATA dat;
608 if (win32func_FindFirstStreamW == NULL)
611 hFind = win32func_FindFirstStreamW(path_utf16, FindStreamInfoStandard, &dat, 0);
612 if (hFind == INVALID_HANDLE_VALUE) {
613 err = GetLastError();
615 if (err == ERROR_CALL_NOT_IMPLEMENTED)
618 /* Seems legal for this to return ERROR_HANDLE_EOF on reparse
619 * points and directories */
620 if ((inode->i_attributes &
621 (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
622 && err == ERROR_HANDLE_EOF)
626 if (err == ERROR_ACCESS_DENIED) {
627 WARNING("Failed to look up data streams of \"%ls\": "
628 "Access denied!\n%s", path_utf16,
632 ERROR("Win32 API: Failed to look up data streams of \"%ls\"",
635 return WIMLIB_ERR_READ;
640 ret = win32_capture_stream(path_utf16,
646 } while (win32func_FindNextStreamW(hFind, &dat));
647 err = GetLastError();
648 if (err != ERROR_HANDLE_EOF) {
649 ERROR("Win32 API: Error reading data streams from \"%ls\"", path_utf16);
651 ret = WIMLIB_ERR_READ;
657 if (inode->i_attributes &
658 (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
662 wcscpy(dat.cStreamName, L"::$DATA");
663 dat.StreamSize.QuadPart = file_size;
664 ret = win32_capture_stream(path_utf16,
672 /* Win32 version of capturing a directory tree */
674 win32_build_dentry_tree(struct wim_dentry **root_ret,
675 const mbchar *root_disk_path,
676 struct wim_lookup_table *lookup_table,
677 struct wim_security_data *sd,
678 const struct capture_config *config,
680 wimlib_progress_func_t progress_func,
683 struct wim_dentry *root = NULL;
685 struct wim_inode *inode;
688 size_t path_utf16_nbytes;
689 size_t path_utf16_nchars;
690 struct sd_set *sd_set;
694 if (exclude_path(root_disk_path, config, true)) {
695 if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT) {
696 ERROR("Cannot exclude the root directory from capture");
697 ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
700 if ((add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
703 union wimlib_progress_info info;
704 info.scan.cur_path = root_disk_path;
705 info.scan.excluded = true;
706 progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
711 if ((add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
714 union wimlib_progress_info info;
715 info.scan.cur_path = root_disk_path;
716 info.scan.excluded = false;
717 progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
720 if (extra_arg == NULL) {
721 sd_set = alloca(sizeof(struct sd_set));
722 sd_set->rb_root.rb_node = NULL,
728 ret = mbs_to_utf16le(root_disk_path, strlen(root_disk_path),
729 &path_utf16, &path_utf16_nbytes);
731 goto out_destroy_sd_set;
732 path_utf16_nchars = path_utf16_nbytes / sizeof(wchar_t);
734 HANDLE hFile = win32_open_existing_file(path_utf16,
735 FILE_READ_DATA | FILE_READ_ATTRIBUTES);
736 if (hFile == INVALID_HANDLE_VALUE) {
737 err = GetLastError();
738 ERROR("Win32 API: Failed to open \"%s\"", root_disk_path);
740 ret = WIMLIB_ERR_OPEN;
741 goto out_free_path_utf16;
744 BY_HANDLE_FILE_INFORMATION file_info;
745 if (!GetFileInformationByHandle(hFile, &file_info)) {
746 err = GetLastError();
747 ERROR("Win32 API: Failed to get file information for \"%s\"",
750 ret = WIMLIB_ERR_STAT;
751 goto out_close_handle;
754 /* Create a WIM dentry */
755 ret = new_dentry_with_timeless_inode(path_basename(root_disk_path), &root);
757 goto out_close_handle;
759 /* Start preparing the associated WIM inode */
760 inode = root->d_inode;
762 inode->i_attributes = file_info.dwFileAttributes;
763 inode->i_creation_time = FILETIME_to_u64(&file_info.ftCreationTime);
764 inode->i_last_write_time = FILETIME_to_u64(&file_info.ftLastWriteTime);
765 inode->i_last_access_time = FILETIME_to_u64(&file_info.ftLastAccessTime);
766 inode->i_ino = ((u64)file_info.nFileIndexHigh << 32) |
767 (u64)file_info.nFileIndexLow;
769 inode->i_resolved = 1;
770 add_image_flags &= ~(WIMLIB_ADD_IMAGE_FLAG_ROOT | WIMLIB_ADD_IMAGE_FLAG_SOURCE);
772 /* Get DOS name and security descriptor (if any). */
773 ret = win32_get_short_name(root, path_utf16);
775 goto out_close_handle;
777 if (!(add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NO_ACLS)) {
778 ret = win32_get_security_descriptor(root, sd_set, path_utf16);
780 goto out_close_handle;
783 file_size = ((u64)file_info.nFileSizeHigh << 32) |
784 (u64)file_info.nFileSizeLow;
786 if (inode_is_directory(inode)) {
787 /* Directory (not a reparse point) --- recurse to children */
789 /* But first... directories may have alternate data streams that
790 * need to be captured. */
791 ret = win32_capture_streams(path_utf16,
797 goto out_close_handle;
798 ret = win32_recurse_directory(root,
808 } else if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
809 /* Reparse point: save the reparse tag and data */
810 ret = win32_capture_reparse_point(hFile,
815 /* Not a directory, not a reparse point; capture the default
816 * file contents and any alternate data streams. */
817 ret = win32_capture_streams(path_utf16,
828 if (extra_arg == NULL)
829 destroy_sd_set(sd_set);
834 free_dentry_tree(root, lookup_table);
838 /* Replacement for POSIX fnmatch() (partial functionality only) */
840 fnmatch(const wchar_t *pattern, const wchar_t *string, int flags)
842 if (PathMatchSpecW(string, pattern))
849 win32_set_reparse_data(HANDLE h,
851 const struct wim_lookup_table_entry *lte,
859 WARNING("\"%ls\" is marked as a reparse point but had no reparse data",
863 len = wim_resource_size(lte);
864 if (len > 16 * 1024 - 8) {
865 WARNING("\"%ls\": reparse data too long!", path);
869 /* The WIM stream omits the ReparseTag and ReparseDataLength fields, so
870 * leave 8 bytes of space for them at the beginning of the buffer, then
871 * set them manually. */
872 buf = alloca(len + 8);
873 ret = read_full_wim_resource(lte, buf + 8, 0);
876 *(u32*)(buf + 0) = cpu_to_le32(reparse_tag);
877 *(u16*)(buf + 4) = cpu_to_le16(len);
878 *(u16*)(buf + 6) = 0;
880 /* Set the reparse data on the open file using the
881 * FSCTL_SET_REPARSE_POINT ioctl.
883 * There are contradictions in Microsoft's documentation for this:
885 * "If hDevice was opened without specifying FILE_FLAG_OVERLAPPED,
886 * lpOverlapped is ignored."
888 * --- So setting lpOverlapped to NULL is okay since it's ignored.
890 * "If lpOverlapped is NULL, lpBytesReturned cannot be NULL. Even when an
891 * operation returns no output data and lpOutBuffer is NULL,
892 * DeviceIoControl makes use of lpBytesReturned. After such an
893 * operation, the value of lpBytesReturned is meaningless."
895 * --- So lpOverlapped not really ignored, as it affects another
896 * parameter. This is the actual behavior: lpBytesReturned must be
897 * specified, even though lpBytesReturned is documented as:
899 * "Not used with this operation; set to NULL."
902 if (!DeviceIoControl(h, FSCTL_SET_REPARSE_POINT, buf, len + 8,
904 &bytesReturned /* lpBytesReturned */,
905 NULL /* lpOverlapped */))
907 DWORD err = GetLastError();
908 ERROR("Failed to set reparse data on \"%ls\"", path);
910 return WIMLIB_ERR_WRITE;
917 win32_extract_chunk(const void *buf, size_t len, u64 offset, void *arg)
919 HANDLE hStream = arg;
921 DWORD nbytes_written;
922 wimlib_assert(len <= 0xffffffff);
924 if (!WriteFile(hStream, buf, len, &nbytes_written, NULL) ||
925 nbytes_written != len)
927 DWORD err = GetLastError();
928 ERROR("WriteFile(): write error");
930 return WIMLIB_ERR_WRITE;
936 do_win32_extract_stream(HANDLE hStream, struct wim_lookup_table_entry *lte)
938 return extract_wim_resource(lte, wim_resource_size(lte),
939 win32_extract_chunk, hStream);
943 win32_extract_stream(const struct wim_inode *inode,
945 const wchar_t *stream_name_utf16,
946 struct wim_lookup_table_entry *lte,
947 const struct wim_security_data *security_data)
949 wchar_t *stream_path;
953 DWORD creationDisposition = CREATE_ALWAYS;
955 SECURITY_ATTRIBUTES *secattr;
957 if (security_data && inode->i_security_id != -1) {
958 secattr = alloca(sizeof(*secattr));
959 secattr->nLength = sizeof(*secattr);
960 secattr->lpSecurityDescriptor = security_data->descriptors[inode->i_security_id];
961 secattr->bInheritHandle = FALSE;
966 if (stream_name_utf16) {
967 /* Named stream. Create a buffer that contains the UTF-16LE
968 * string [.\]@path:@stream_name_utf16. This is needed to
969 * create and open the stream using CreateFileW(). I'm not
970 * aware of any other APIs to do this. Note: the '$DATA' suffix
971 * seems to be unneeded. Additional note: a "./" prefix needs
972 * to be added when the path is not absolute to avoid ambiguity
973 * with drive letters. */
974 size_t stream_path_nchars;
976 size_t stream_name_nchars;
977 const wchar_t *prefix;
979 path_nchars = wcslen(path);
980 stream_name_nchars = wcslen(stream_name_utf16);
981 stream_path_nchars = path_nchars + 1 + stream_name_nchars;
982 if (path[0] != cpu_to_le16(L'\0') &&
983 path[0] != cpu_to_le16(L'/') &&
984 path[0] != cpu_to_le16(L'\\') &&
985 path[1] != cpu_to_le16(L':'))
988 stream_path_nchars += 2;
992 stream_path = alloca((stream_path_nchars + 1) * sizeof(wchar_t));
993 swprintf(stream_path, stream_path_nchars + 1, L"%ls%ls:%ls",
994 prefix, path, stream_name_utf16);
996 /* Unnamed stream; its path is just the path to the file itself.
998 stream_path = (wchar_t*)path;
1000 /* Directories must be created with CreateDirectoryW(). Then
1001 * the call to CreateFileW() will merely open the directory that
1002 * was already created rather than creating a new file. */
1003 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1004 if (!CreateDirectoryW(stream_path, secattr)) {
1005 err = GetLastError();
1006 if (err != ERROR_ALREADY_EXISTS) {
1007 ERROR("Failed to create directory \"%ls\"",
1010 ret = WIMLIB_ERR_MKDIR;
1014 DEBUG("Created directory \"%ls\"", stream_path);
1015 if (!(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
1019 creationDisposition = OPEN_EXISTING;
1023 DEBUG("Opening \"%ls\"", stream_path);
1024 h = CreateFileW(stream_path,
1028 creationDisposition,
1029 FILE_FLAG_OPEN_REPARSE_POINT |
1030 FILE_FLAG_BACKUP_SEMANTICS |
1031 inode->i_attributes,
1033 if (h == INVALID_HANDLE_VALUE) {
1034 err = GetLastError();
1035 ERROR("Failed to create \"%ls\"", stream_path);
1037 ret = WIMLIB_ERR_OPEN;
1041 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT &&
1042 stream_name_utf16 == NULL)
1044 DEBUG("Setting reparse data on \"%ls\"", path);
1045 ret = win32_set_reparse_data(h, inode->i_reparse_tag, lte, path);
1047 goto fail_close_handle;
1050 DEBUG("Extracting \"%ls\" (len = %"PRIu64")",
1051 stream_path, wim_resource_size(lte));
1052 ret = do_win32_extract_stream(h, lte);
1054 goto fail_close_handle;
1058 DEBUG("Closing \"%ls\"", stream_path);
1059 if (!CloseHandle(h)) {
1060 err = GetLastError();
1061 ERROR("Failed to close \"%ls\"", stream_path);
1063 ret = WIMLIB_ERR_WRITE;
1071 ERROR("Error extracting %ls", stream_path);
1077 * Creates a file, directory, or reparse point and extracts all streams to it
1078 * (unnamed data stream and/or reparse point stream, plus any alternate data
1079 * streams). This in Win32-specific code.
1081 * @inode: WIM inode for this file or directory.
1082 * @path: UTF-16LE external path to extract the inode to.
1084 * Returns 0 on success; nonzero on failure.
1087 win32_extract_streams(const struct wim_inode *inode,
1088 const wchar_t *path, u64 *completed_bytes_p,
1089 const struct wim_security_data *security_data)
1091 struct wim_lookup_table_entry *unnamed_lte;
1094 unnamed_lte = inode_unnamed_lte_resolved(inode);
1095 ret = win32_extract_stream(inode, path, NULL, unnamed_lte,
1100 *completed_bytes_p += wim_resource_size(unnamed_lte);
1101 for (u16 i = 0; i < inode->i_num_ads; i++) {
1102 const struct wim_ads_entry *ads_entry = &inode->i_ads_entries[i];
1103 if (ads_entry->stream_name_nbytes != 0) {
1104 /* Skip special UNIX data entries (see documentation for
1105 * WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA) */
1106 if (ads_entry->stream_name_nbytes == WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES
1107 && !memcmp(ads_entry->stream_name,
1108 WIMLIB_UNIX_DATA_TAG_UTF16LE,
1109 WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES))
1111 ret = win32_extract_stream(inode,
1113 ads_entry->stream_name,
1119 *completed_bytes_p += wim_resource_size(ads_entry->lte);
1126 /* Extract a file, directory, reparse point, or hard link to an
1127 * already-extracted file using the Win32 API */
1128 int win32_do_apply_dentry(const wchar_t *output_path,
1129 size_t output_path_num_wchars,
1130 struct wim_dentry *dentry,
1131 struct apply_args *args)
1134 if (inode->i_nlink > 1 && inode->i_extracted_file != NULL) {
1135 /* Linked file, with another name already extracted. Create a
1137 DEBUG("Creating hard link \"%ls => %ls\"",
1138 output_path, inode->i_extracted_file);
1139 if (!CreateHardLinkW(utf16le_path, inode->i_extracted_file, NULL))
1141 err = GetLastError();
1142 ERROR("Can't create hard link \"%ls => %ls\"",
1143 output_path, inode->i_extracted_file);
1144 ret = WIMLIB_ERR_LINK;
1148 /* Create the file, directory, or reparse point, and extract the
1150 const struct wim_security_data *security_data;
1151 if (args->extract_flags & WIMLIB_EXTRACT_FLAG_NOACLS)
1152 security_data = NULL;
1154 security_data = wim_const_security_data(args->w);
1156 ret = win32_extract_streams(inode, output_path,
1157 &args->progress.extract.completed_bytes,
1162 if (inode->i_nlink > 1) {
1163 /* Save extracted path for a later call to
1164 * CreateHardLinkW() if this inode has multiple links.
1166 inode->i_extracted_file = WSTRDUP(utf16le_path);
1167 if (!inode->i_extracted_file)
1168 ret = WIMLIB_ERR_NOMEM;
1174 /* Set timestamps on an extracted file using the Win32 API */
1176 win32_do_apply_dentry_timestamps(const mbchar *output_path,
1177 size_t output_path_nbytes,
1178 const struct wim_dentry *dentry,
1179 const struct apply_args *args)
1182 wchar_t *utf16le_path;
1183 size_t utf16le_path_nbytes;
1187 const struct wim_inode *inode = dentry->d_inode;
1189 ret = mbs_to_utf16le(output_path, output_path_nbytes,
1190 &utf16le_path, &utf16le_path_nbytes);
1194 DEBUG("Opening \"%s\" to set timestamps", output_path);
1195 h = win32_open_existing_file(utf16le_path, FILE_WRITE_ATTRIBUTES);
1197 if (h == INVALID_HANDLE_VALUE)
1198 err = GetLastError();
1200 if (h == INVALID_HANDLE_VALUE)
1203 FILETIME creationTime = {.dwLowDateTime = inode->i_creation_time & 0xffffffff,
1204 .dwHighDateTime = inode->i_creation_time >> 32};
1205 FILETIME lastAccessTime = {.dwLowDateTime = inode->i_last_access_time & 0xffffffff,
1206 .dwHighDateTime = inode->i_last_access_time >> 32};
1207 FILETIME lastWriteTime = {.dwLowDateTime = inode->i_last_write_time & 0xffffffff,
1208 .dwHighDateTime = inode->i_last_write_time >> 32};
1210 DEBUG("Calling SetFileTime() on \"%s\"", output_path);
1211 if (!SetFileTime(h, &creationTime, &lastAccessTime, &lastWriteTime)) {
1212 err = GetLastError();
1216 DEBUG("Closing \"%s\"", output_path);
1217 if (!CloseHandle(h)) {
1218 err = GetLastError();
1223 /* Only warn if setting timestamps failed. */
1224 WARNING("Can't set timestamps on \"%s\"", output_path);
1230 /* Replacement for POSIX fsync() */
1234 HANDLE h = (HANDLE)_get_osfhandle(fd);
1235 if (h == INVALID_HANDLE_VALUE) {
1236 ERROR("Could not get Windows handle for file descriptor");
1237 win32_error(GetLastError());
1241 if (!FlushFileBuffers(h)) {
1242 ERROR("Could not flush file buffers to disk");
1243 win32_error(GetLastError());
1250 /* Use the Win32 API to get the number of processors */
1252 win32_get_number_of_processors()
1254 SYSTEM_INFO sysinfo;
1255 GetSystemInfo(&sysinfo);
1256 return sysinfo.dwNumberOfProcessors;
1259 /* Replacement for POSIX-2008 realpath(). Warning: partial functionality only
1260 * (resolved_path must be NULL). Also I highly doubt that GetFullPathName
1261 * really does the right thing under all circumstances. */
1263 realpath(const wchar_t *path, wchar_t *resolved_path)
1266 wimlib_assert(resolved_path == NULL);
1268 ret = GetFullPathNameW(path, 0, NULL, NULL);
1272 resolved_path = TMALLOC(ret);
1275 ret = GetFullPathNameW(path, ret, resolved_path, NULL);
1277 free(resolved_path);
1280 return resolved_path;
1282 win32_error(GetLastError());
1288 nl_langinfo(nl_item item)
1290 wimlib_assert(item == CODESET);
1291 static char buf[64];
1292 strcpy(buf, "Unknown");
1296 /* rename() on Windows fails if the destination file exists. And we need to
1297 * make it work on wide characters. Fix it. */
1299 win32_rename_replacement(const wchar_t *oldpath, const wchar_t *newpath)
1301 if (MoveFileExW(oldpath, newpath, MOVEFILE_REPLACE_EXISTING)) {
1304 /* As usual, the possible error values are not documented */
1305 DWORD err = GetLastError();
1306 ERROR("MoveFileEx(): Can't rename \"%ls\" to \"%ls\"",
1314 /* truncate for wide-character paths */
1316 win32_truncate_replacement(const char *path, off_t size)