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"
47 static const char *access_denied_msg =
48 " If you are not running this program as the administrator, you may\n"
49 " need to do so, so that all data and metadata can be backed up.\n"
50 " Otherwise, there may be no way to access the desired data or\n"
51 " metadata without taking ownership of the file or directory.\n";
53 #ifdef ENABLE_ERROR_MESSAGES
55 win32_error(u32 err_code)
59 nchars = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
61 (char*)&buffer, 0, NULL);
63 ERROR("Error printing error message! "
64 "Computer will self-destruct in 3 seconds.");
66 ERROR("Win32 error: %s", buffer);
74 win32_error(GetLastError());
79 win32_open_existing_file(const wchar_t *path, DWORD dwDesiredAccess)
81 return CreateFileW(path,
84 NULL, /* lpSecurityAttributes */
86 FILE_FLAG_BACKUP_SEMANTICS |
87 FILE_FLAG_OPEN_REPARSE_POINT,
88 NULL /* hTemplateFile */);
92 win32_open_file_data_only(const wchar_t *path)
94 return win32_open_existing_file(path, FILE_READ_DATA);
98 win32_read_file(const mbchar *filename,
99 void *handle, u64 offset, size_t size, void *buf)
104 LARGE_INTEGER liOffset = {.QuadPart = offset};
106 wimlib_assert(size <= 0xffffffff);
108 if (SetFilePointerEx(h, liOffset, NULL, FILE_BEGIN))
109 if (ReadFile(h, buf, size, &bytesRead, NULL) && bytesRead == size)
111 err = GetLastError();
112 ERROR("Error reading \"%s\"", filename);
114 return WIMLIB_ERR_READ;
118 win32_close_file(void *handle)
120 CloseHandle((HANDLE)handle);
124 FILETIME_to_u64(const FILETIME *ft)
126 return ((u64)ft->dwHighDateTime << 32) | (u64)ft->dwLowDateTime;
130 win32_get_short_name(struct wim_dentry *dentry,
131 const wchar_t *path_utf16)
133 WIN32_FIND_DATAW dat;
134 if (FindFirstFileW(path_utf16, &dat) &&
135 dat.cAlternateFileName[0] != L'\0')
137 size_t short_name_nbytes = wcslen(dat.cAlternateFileName) * 2;
138 size_t n = short_name_nbytes + sizeof(wchar_t);
139 dentry->short_name = MALLOC(n);
140 if (!dentry->short_name)
141 return WIMLIB_ERR_NOMEM;
142 memcpy(dentry->short_name, dat.cAlternateFileName, n);
143 dentry->short_name_nbytes = short_name_nbytes;
149 win32_get_security_descriptor(struct wim_dentry *dentry,
150 struct sd_set *sd_set,
151 const wchar_t *path_utf16)
153 SECURITY_INFORMATION requestedInformation;
158 requestedInformation = DACL_SECURITY_INFORMATION |
159 SACL_SECURITY_INFORMATION |
160 OWNER_SECURITY_INFORMATION |
161 GROUP_SECURITY_INFORMATION;
162 /* Request length of security descriptor */
163 status = GetFileSecurityW(path_utf16, requestedInformation,
164 NULL, 0, &lenNeeded);
165 err = GetLastError();
166 if (!status && err == ERROR_INSUFFICIENT_BUFFER) {
167 DWORD len = lenNeeded;
169 if (GetFileSecurityW(path_utf16, requestedInformation,
170 (PSECURITY_DESCRIPTOR)buf, len, &lenNeeded))
172 int security_id = sd_set_add_sd(sd_set, buf, len);
174 return WIMLIB_ERR_NOMEM;
176 dentry->d_inode->i_security_id = security_id;
180 err = GetLastError();
184 if (err == ERROR_ACCESS_DENIED) {
185 WARNING("Failed to read security descriptor of \"%ls\": "
186 "Access denied!\n%s", path_utf16, access_denied_msg);
189 ERROR("Win32 API: Failed to read security descriptor of \"%ls\"",
192 return WIMLIB_ERR_READ;
196 /* Reads the directory entries of directory using a Win32 API and recursively
197 * calls win32_build_dentry_tree() on them. */
199 win32_recurse_directory(struct wim_dentry *root,
200 const mbchar *root_disk_path,
201 struct wim_lookup_table *lookup_table,
202 struct wim_security_data *sd,
203 const struct capture_config *config,
205 wimlib_progress_func_t progress_func,
206 struct sd_set *sd_set,
207 const wchar_t *path_utf16,
208 size_t path_utf16_nchars)
210 WIN32_FIND_DATAW dat;
216 /* Begin reading the directory by calling FindFirstFileW.
217 * Unlike UNIX opendir(), FindFirstFileW has file globbing built
218 * into it. But this isn't what we actually want, so just add a
219 * dummy glob to get all entries. */
220 wchar_t pattern_buf[path_utf16_nchars + 3];
221 memcpy(pattern_buf, path_utf16,
222 path_utf16_nchars * sizeof(wchar_t));
223 pattern_buf[path_utf16_nchars] = L'/';
224 pattern_buf[path_utf16_nchars + 1] = L'*';
225 pattern_buf[path_utf16_nchars + 2] = L'\0';
226 hFind = FindFirstFileW(pattern_buf, &dat);
228 if (hFind == INVALID_HANDLE_VALUE) {
229 err = GetLastError();
230 if (err == ERROR_FILE_NOT_FOUND) {
233 ERROR("Win32 API: Failed to read directory \"%s\"",
236 return WIMLIB_ERR_READ;
241 /* Skip . and .. entries */
242 if (!(dat.cFileName[0] == cpu_to_le16(L'.') &&
243 (dat.cFileName[1] == cpu_to_le16(L'\0') ||
244 (dat.cFileName[1] == cpu_to_le16(L'.') &&
245 dat.cFileName[2] == cpu_to_le16(L'\0')))))
247 struct wim_dentry *child;
250 size_t mbs_name_nbytes;
251 ret = utf16le_to_mbs(dat.cFileName,
252 wcslen(dat.cFileName) * sizeof(wchar_t),
258 mbchar name[strlen(root_disk_path) + 1 + mbs_name_nbytes + 1];
259 sprintf(name, "%s/%s", root_disk_path, mbs_name);
261 ret = win32_build_dentry_tree(&child, name, lookup_table,
262 sd, config, add_image_flags,
263 progress_func, sd_set);
267 dentry_add_child(root, child);
269 } while (FindNextFileW(hFind, &dat));
270 err = GetLastError();
271 if (err != ERROR_NO_MORE_FILES) {
272 ERROR("Win32 API: Failed to read directory \"%s\"", root_disk_path);
275 ret = WIMLIB_ERR_READ;
282 /* Load a reparse point into a WIM inode. It is just stored in memory.
284 * @hFile: Open handle to a reparse point, with permission to read the reparse
287 * @inode: WIM inode for the reparse point.
289 * @lookup_table: Stream lookup table for the WIM; an entry will be added to it
290 * for the reparse point unless an entry already exists for
291 * the exact same data stream.
293 * @path: External path to the reparse point. Used for error messages only.
295 * Returns 0 on success; nonzero on failure. */
297 win32_capture_reparse_point(HANDLE hFile,
298 struct wim_inode *inode,
299 struct wim_lookup_table *lookup_table,
302 /* "Reparse point data, including the tag and optional GUID,
303 * cannot exceed 16 kilobytes." - MSDN */
304 char reparse_point_buf[16 * 1024];
307 if (!DeviceIoControl(hFile, FSCTL_GET_REPARSE_POINT,
308 NULL, /* "Not used with this operation; set to NULL" */
309 0, /* "Not used with this operation; set to 0" */
310 reparse_point_buf, /* "A pointer to a buffer that
311 receives the reparse point data */
312 sizeof(reparse_point_buf), /* "The size of the output
317 DWORD err = GetLastError();
318 ERROR("Win32 API: Failed to get reparse data of \"%s\"", path);
320 return WIMLIB_ERR_READ;
322 if (bytesReturned < 8) {
323 ERROR("Reparse data on \"%s\" is invalid", path);
324 return WIMLIB_ERR_READ;
326 inode->i_reparse_tag = le32_to_cpu(*(u32*)reparse_point_buf);
327 return inode_add_ads_with_data(inode, "",
328 reparse_point_buf + 8,
329 bytesReturned - 8, lookup_table);
332 /* Calculate the SHA1 message digest of a Win32 data stream, which may be either
333 * an unnamed or named data stream.
335 * @path: Path to the file, with the stream noted at the end for named
336 * streams. UTF-16LE encoding.
338 * @hash: On success, the SHA1 message digest of the stream is written to
341 * Returns 0 on success; nonzero on failure.
344 win32_sha1sum(const wchar_t *path, u8 hash[SHA1_HASH_SIZE])
352 hFile = win32_open_file_data_only(path);
353 if (hFile == INVALID_HANDLE_VALUE)
354 return WIMLIB_ERR_OPEN;
358 if (!ReadFile(hFile, buf, sizeof(buf), &bytesRead, NULL)) {
359 ret = WIMLIB_ERR_READ;
360 goto out_close_handle;
364 sha1_update(&ctx, buf, bytesRead);
367 sha1_final(hash, &ctx);
373 /* Scans an unnamed or named stream of a Win32 file (not a reparse point
374 * stream); calculates its SHA1 message digest and either creates a `struct
375 * wim_lookup_table_entry' in memory for it, or uses an existing 'struct
376 * wim_lookup_table_entry' for an identical stream.
378 * @path_utf16: Path to the file (UTF-16LE).
380 * @path_utf16_nchars: Number of 2-byte characters in @path_utf16.
382 * @inode: WIM inode to save the stream into.
384 * @lookup_table: Stream lookup table for the WIM.
386 * @dat: A `WIN32_FIND_STREAM_DATA' structure that specifies the
389 * Returns 0 on success; nonzero on failure.
392 win32_capture_stream(const wchar_t *path_utf16,
393 size_t path_utf16_nchars,
394 struct wim_inode *inode,
395 struct wim_lookup_table *lookup_table,
396 WIN32_FIND_STREAM_DATA *dat)
398 struct wim_ads_entry *ads_entry;
399 u8 hash[SHA1_HASH_SIZE];
400 struct wim_lookup_table_entry *lte;
402 wchar_t *stream_name, *colon;
403 size_t stream_name_nchars;
404 bool is_named_stream;
408 size_t spath_buf_nbytes;
409 const wchar_t *relpath_prefix;
410 const wchar_t *colonchar;
412 /* The stream name should be returned as :NAME:TYPE */
413 stream_name = dat->cStreamName;
414 if (*stream_name != L':')
415 goto out_invalid_stream_name;
417 colon = wcschr(stream_name, L':');
419 goto out_invalid_stream_name;
421 if (wcscmp(colon + 1, L"$DATA")) {
422 /* Not a DATA stream */
429 stream_name_nchars = colon - stream_name;
430 is_named_stream = (stream_name_nchars != 0);
432 if (is_named_stream) {
433 /* Allocate an ADS entry for the named stream. */
434 ads_entry = inode_add_ads_utf16le(inode, stream_name,
435 stream_name_nchars * 2);
437 ret = WIMLIB_ERR_NOMEM;
442 /* Create a UTF-16LE string @spath that gives the filename, then a
443 * colon, then the stream name. Or, if it's an unnamed stream, just the
444 * filename. It is MALLOC()'ed so that it can be saved in the
445 * wim_lookup_table_entry if needed.
447 * As yet another special case, relative paths need to be changed to
448 * begin with an explicit "./" so that, for example, a file t:ads, where
449 * :ads is the part we added, is not interpreted as a file on the t:
451 spath_nchars = path_utf16_nchars;
452 relpath_prefix = L"";
454 if (is_named_stream) {
455 spath_nchars += 1 + stream_name_nchars;
457 if (path_utf16_nchars == 1 &&
458 path_utf16[0] != cpu_to_le16('/') &&
459 path_utf16[0] != cpu_to_le16('\\'))
462 relpath_prefix = L"./";
466 spath_buf_nbytes = (spath_nchars + 1) * sizeof(wchar_t);
467 spath = MALLOC(spath_buf_nbytes);
469 swprintf(spath, spath_buf_nbytes, L"%ls%ls%ls%ls",
470 relpath_prefix, path_utf16, colonchar, stream_name);
472 ret = win32_sha1sum(spath, hash);
474 err = GetLastError();
475 ERROR("Win32 API: Failed to read \"%ls\" to calculate SHA1sum",
481 lte = __lookup_resource(lookup_table, hash);
483 /* Use existing wim_lookup_table_entry that has the same SHA1
487 /* Make a new wim_lookup_table_entry */
488 lte = new_lookup_table_entry();
490 ret = WIMLIB_ERR_NOMEM;
493 lte->win32_file_on_disk = spath;
494 lte->file_on_disk_fp = INVALID_HANDLE_VALUE;
496 lte->resource_location = RESOURCE_WIN32;
497 lte->resource_entry.original_size = (uint64_t)dat->StreamSize.QuadPart;
498 lte->resource_entry.size = (uint64_t)dat->StreamSize.QuadPart;
499 copy_hash(lte->hash, hash);
500 lookup_table_insert(lookup_table, lte);
503 ads_entry->lte = lte;
510 out_invalid_stream_name:
511 ERROR("Invalid stream name: \"%ls:%ls\"", path_utf16, dat->cStreamName);
512 ret = WIMLIB_ERR_READ;
516 /* Scans a Win32 file for unnamed and named data streams (not reparse point
519 * @path_utf16: Path to the file (UTF-16LE).
521 * @path_utf16_nchars: Number of 2-byte characters in @path_utf16.
523 * @inode: WIM inode to save the stream into.
525 * @lookup_table: Stream lookup table for the WIM.
527 * Returns 0 on success; nonzero on failure.
530 win32_capture_streams(const wchar_t *path_utf16,
531 size_t path_utf16_nchars,
532 struct wim_inode *inode,
533 struct wim_lookup_table *lookup_table)
535 WIN32_FIND_STREAM_DATA dat;
540 hFind = FindFirstStreamW(path_utf16, FindStreamInfoStandard, &dat, 0);
541 if (hFind == INVALID_HANDLE_VALUE) {
542 err = GetLastError();
544 /* Seems legal for this to return ERROR_HANDLE_EOF on reparse
545 * points and directories */
546 if ((inode->i_attributes &
547 (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
548 && err == ERROR_HANDLE_EOF)
552 if (err == ERROR_ACCESS_DENIED) {
553 WARNING("Failed to look up data streams of \"%ls\": "
554 "Access denied!\n%s", path_utf16,
558 ERROR("Win32 API: Failed to look up data streams of \"%ls\"",
561 return WIMLIB_ERR_READ;
566 ret = win32_capture_stream(path_utf16,
572 } while (FindNextStreamW(hFind, &dat));
573 err = GetLastError();
574 if (err != ERROR_HANDLE_EOF) {
575 ERROR("Win32 API: Error reading data streams from \"%ls\"", path_utf16);
577 ret = WIMLIB_ERR_READ;
584 /* Win32 version of capturing a directory tree */
586 win32_build_dentry_tree(struct wim_dentry **root_ret,
587 const mbchar *root_disk_path,
588 struct wim_lookup_table *lookup_table,
589 struct wim_security_data *sd,
590 const struct capture_config *config,
592 wimlib_progress_func_t progress_func,
595 struct wim_dentry *root = NULL;
597 struct wim_inode *inode;
600 size_t path_utf16_nbytes;
601 size_t path_utf16_nchars;
602 struct sd_set *sd_set;
605 if (exclude_path(root_disk_path, config, true)) {
606 if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT) {
607 ERROR("Cannot exclude the root directory from capture");
608 ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
611 if ((add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
614 union wimlib_progress_info info;
615 info.scan.cur_path = root_disk_path;
616 info.scan.excluded = true;
617 progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
622 if ((add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
625 union wimlib_progress_info info;
626 info.scan.cur_path = root_disk_path;
627 info.scan.excluded = false;
628 progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
631 if (extra_arg == NULL) {
632 sd_set = alloca(sizeof(struct sd_set));
633 sd_set->rb_root.rb_node = NULL,
639 ret = mbs_to_utf16le(root_disk_path, strlen(root_disk_path),
640 &path_utf16, &path_utf16_nbytes);
642 goto out_destroy_sd_set;
643 path_utf16_nchars = path_utf16_nbytes / sizeof(wchar_t);
645 HANDLE hFile = win32_open_existing_file(path_utf16,
646 FILE_READ_DATA | FILE_READ_ATTRIBUTES);
647 if (hFile == INVALID_HANDLE_VALUE) {
648 err = GetLastError();
649 ERROR("Win32 API: Failed to open \"%s\"", root_disk_path);
651 ret = WIMLIB_ERR_OPEN;
652 goto out_free_path_utf16;
655 BY_HANDLE_FILE_INFORMATION file_info;
656 if (!GetFileInformationByHandle(hFile, &file_info)) {
657 err = GetLastError();
658 ERROR("Win32 API: Failed to get file information for \"%s\"",
661 ret = WIMLIB_ERR_STAT;
662 goto out_close_handle;
665 /* Create a WIM dentry */
666 ret = new_dentry_with_timeless_inode(path_basename(root_disk_path), &root);
668 goto out_close_handle;
670 /* Start preparing the associated WIM inode */
671 inode = root->d_inode;
673 inode->i_attributes = file_info.dwFileAttributes;
674 inode->i_creation_time = FILETIME_to_u64(&file_info.ftCreationTime);
675 inode->i_last_write_time = FILETIME_to_u64(&file_info.ftLastWriteTime);
676 inode->i_last_access_time = FILETIME_to_u64(&file_info.ftLastAccessTime);
677 inode->i_ino = ((u64)file_info.nFileIndexHigh << 32) |
678 (u64)file_info.nFileIndexLow;
680 inode->i_resolved = 1;
681 add_image_flags &= ~(WIMLIB_ADD_IMAGE_FLAG_ROOT | WIMLIB_ADD_IMAGE_FLAG_SOURCE);
683 /* Get DOS name and security descriptor (if any). */
684 ret = win32_get_short_name(root, path_utf16);
686 goto out_close_handle;
688 if (!(add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NO_ACLS)) {
689 ret = win32_get_security_descriptor(root, sd_set, path_utf16);
691 goto out_close_handle;
694 if (inode_is_directory(inode)) {
695 /* Directory (not a reparse point) --- recurse to children */
697 /* But first... directories may have alternate data streams that
698 * need to be captured. */
699 ret = win32_capture_streams(path_utf16,
704 goto out_close_handle;
705 ret = win32_recurse_directory(root,
715 } else if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
716 /* Reparse point: save the reparse tag and data */
717 ret = win32_capture_reparse_point(hFile,
722 /* Not a directory, not a reparse point; capture the default
723 * file contents and any alternate data streams. */
724 ret = win32_capture_streams(path_utf16,
734 if (extra_arg == NULL)
735 destroy_sd_set(sd_set);
740 free_dentry_tree(root, lookup_table);
744 /* Replacement for POSIX fnmatch() (partial functionality only) */
746 fnmatch(const char *pattern, const char *string, int flags)
748 if (PathMatchSpecA(string, pattern))
755 win32_set_reparse_data(HANDLE h,
757 const struct wim_lookup_table_entry *lte,
765 WARNING("\"%ls\" is marked as a reparse point but had no reparse data",
769 len = wim_resource_size(lte);
770 if (len > 16 * 1024 - 8) {
771 WARNING("\"%ls\": reparse data too long!", path);
775 /* The WIM stream omits the ReparseTag and ReparseDataLength fields, so
776 * leave 8 bytes of space for them at the beginning of the buffer, then
777 * set them manually. */
778 buf = alloca(len + 8);
779 ret = read_full_wim_resource(lte, buf + 8, 0);
782 *(u32*)(buf + 0) = cpu_to_le32(reparse_tag);
783 *(u16*)(buf + 4) = cpu_to_le16(len);
784 *(u16*)(buf + 6) = 0;
786 /* Set the reparse data on the open file using the
787 * FSCTL_SET_REPARSE_POINT ioctl.
789 * There are contradictions in Microsoft's documentation for this:
791 * "If hDevice was opened without specifying FILE_FLAG_OVERLAPPED,
792 * lpOverlapped is ignored."
794 * --- So setting lpOverlapped to NULL is okay since it's ignored.
796 * "If lpOverlapped is NULL, lpBytesReturned cannot be NULL. Even when an
797 * operation returns no output data and lpOutBuffer is NULL,
798 * DeviceIoControl makes use of lpBytesReturned. After such an
799 * operation, the value of lpBytesReturned is meaningless."
801 * --- So lpOverlapped not really ignored, as it affects another
802 * parameter. This is the actual behavior: lpBytesReturned must be
803 * specified, even though lpBytesReturned is documented as:
805 * "Not used with this operation; set to NULL."
808 if (!DeviceIoControl(h, FSCTL_SET_REPARSE_POINT, buf, len + 8,
810 &bytesReturned /* lpBytesReturned */,
811 NULL /* lpOverlapped */))
813 DWORD err = GetLastError();
814 ERROR("Failed to set reparse data on \"%ls\"", path);
816 return WIMLIB_ERR_WRITE;
823 win32_extract_chunk(const void *buf, size_t len, u64 offset, void *arg)
825 HANDLE hStream = arg;
827 DWORD nbytes_written;
828 wimlib_assert(len <= 0xffffffff);
830 if (!WriteFile(hStream, buf, len, &nbytes_written, NULL) ||
831 nbytes_written != len)
833 DWORD err = GetLastError();
834 ERROR("WriteFile(): write error");
836 return WIMLIB_ERR_WRITE;
842 do_win32_extract_stream(HANDLE hStream, struct wim_lookup_table_entry *lte)
844 return extract_wim_resource(lte, wim_resource_size(lte),
845 win32_extract_chunk, hStream);
849 win32_extract_stream(const struct wim_inode *inode,
851 const wchar_t *stream_name_utf16,
852 struct wim_lookup_table_entry *lte,
853 const struct wim_security_data *security_data)
855 wchar_t *stream_path;
859 DWORD creationDisposition = CREATE_ALWAYS;
861 SECURITY_ATTRIBUTES *secattr;
863 if (security_data && inode->i_security_id != -1) {
864 secattr = alloca(sizeof(*secattr));
865 secattr->nLength = sizeof(*secattr);
866 secattr->lpSecurityDescriptor = security_data->descriptors[inode->i_security_id];
867 secattr->bInheritHandle = FALSE;
872 if (stream_name_utf16) {
873 /* Named stream. Create a buffer that contains the UTF-16LE
874 * string [.\]@path:@stream_name_utf16. This is needed to
875 * create and open the stream using CreateFileW(). I'm not
876 * aware of any other APIs to do this. Note: the '$DATA' suffix
877 * seems to be unneeded. Additional note: a "./" prefix needs
878 * to be added when the path is not absolute to avoid ambiguity
879 * with drive letters. */
880 size_t stream_path_nchars;
882 size_t stream_name_nchars;
883 const wchar_t *prefix;
885 path_nchars = wcslen(path);
886 stream_name_nchars = wcslen(stream_name_utf16);
887 stream_path_nchars = path_nchars + 1 + stream_name_nchars;
888 if (path[0] != cpu_to_le16(L'\0') &&
889 path[0] != cpu_to_le16(L'/') &&
890 path[0] != cpu_to_le16(L'\\') &&
891 path[1] != cpu_to_le16(L':'))
894 stream_path_nchars += 2;
898 stream_path = alloca((stream_path_nchars + 1) * sizeof(wchar_t));
899 swprintf(stream_path, stream_path_nchars + 1, L"%ls%ls:%ls",
900 prefix, path, stream_name_utf16);
902 /* Unnamed stream; its path is just the path to the file itself.
904 stream_path = (wchar_t*)path;
906 /* Directories must be created with CreateDirectoryW(). Then
907 * the call to CreateFileW() will merely open the directory that
908 * was already created rather than creating a new file. */
909 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
910 if (!CreateDirectoryW(stream_path, secattr)) {
911 err = GetLastError();
912 if (err != ERROR_ALREADY_EXISTS) {
913 ERROR("Failed to create directory \"%ls\"",
916 ret = WIMLIB_ERR_MKDIR;
920 DEBUG("Created directory \"%ls\"", stream_path);
921 if (!(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
925 creationDisposition = OPEN_EXISTING;
929 DEBUG("Opening \"%ls\"", stream_path);
930 h = CreateFileW(stream_path,
935 FILE_FLAG_OPEN_REPARSE_POINT |
936 FILE_FLAG_BACKUP_SEMANTICS |
939 if (h == INVALID_HANDLE_VALUE) {
940 err = GetLastError();
941 ERROR("Failed to create \"%ls\"", stream_path);
943 ret = WIMLIB_ERR_OPEN;
947 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT &&
948 stream_name_utf16 == NULL)
950 DEBUG("Setting reparse data on \"%ls\"", path);
951 ret = win32_set_reparse_data(h, inode->i_reparse_tag, lte, path);
953 goto fail_close_handle;
956 DEBUG("Extracting \"%ls\" (len = %"PRIu64")",
957 stream_path, wim_resource_size(lte));
958 ret = do_win32_extract_stream(h, lte);
960 goto fail_close_handle;
964 DEBUG("Closing \"%ls\"", stream_path);
965 if (!CloseHandle(h)) {
966 err = GetLastError();
967 ERROR("Failed to close \"%ls\"", stream_path);
969 ret = WIMLIB_ERR_WRITE;
977 ERROR("Error extracting %ls", stream_path);
983 * Creates a file, directory, or reparse point and extracts all streams to it
984 * (unnamed data stream and/or reparse point stream, plus any alternate data
985 * streams). This in Win32-specific code.
987 * @inode: WIM inode for this file or directory.
988 * @path: UTF-16LE external path to extract the inode to.
990 * Returns 0 on success; nonzero on failure.
993 win32_extract_streams(const struct wim_inode *inode,
994 const wchar_t *path, u64 *completed_bytes_p,
995 const struct wim_security_data *security_data)
997 struct wim_lookup_table_entry *unnamed_lte;
1000 unnamed_lte = inode_unnamed_lte_resolved(inode);
1001 ret = win32_extract_stream(inode, path, NULL, unnamed_lte,
1006 *completed_bytes_p += wim_resource_size(unnamed_lte);
1007 for (u16 i = 0; i < inode->i_num_ads; i++) {
1008 const struct wim_ads_entry *ads_entry = &inode->i_ads_entries[i];
1009 if (ads_entry->stream_name_nbytes != 0) {
1010 /* Skip special UNIX data entries (see documentation for
1011 * WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA) */
1012 if (ads_entry->stream_name_nbytes == WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES
1013 && !memcmp(ads_entry->stream_name,
1014 WIMLIB_UNIX_DATA_TAG_UTF16LE,
1015 WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES))
1017 ret = win32_extract_stream(inode,
1019 ads_entry->stream_name,
1025 *completed_bytes_p += wim_resource_size(ads_entry->lte);
1032 /* Extract a file, directory, reparse point, or hard link to an
1033 * already-extracted file using the Win32 API */
1034 int win32_do_apply_dentry(const mbchar *output_path,
1035 size_t output_path_nbytes,
1036 struct wim_dentry *dentry,
1037 struct apply_args *args)
1039 wchar_t *utf16le_path;
1040 size_t utf16le_path_nbytes;
1043 struct wim_inode *inode = dentry->d_inode;
1045 ret = mbs_to_utf16le(output_path, output_path_nbytes,
1046 &utf16le_path, &utf16le_path_nbytes);
1050 if (inode->i_nlink > 1 && inode->i_extracted_file != NULL) {
1051 /* Linked file, with another name already extracted. Create a
1053 DEBUG("Creating hard link \"%ls => %ls\"",
1054 utf16le_path, inode->i_extracted_file);
1055 if (!CreateHardLinkW(utf16le_path, inode->i_extracted_file, NULL))
1057 err = GetLastError();
1058 ERROR("Can't create hard link \"%ls => %ls\"",
1059 utf16le_path, inode->i_extracted_file);
1060 ret = WIMLIB_ERR_LINK;
1064 /* Create the file, directory, or reparse point, and extract the
1066 const struct wim_security_data *security_data;
1067 if (args->extract_flags & WIMLIB_EXTRACT_FLAG_NOACLS)
1068 security_data = NULL;
1070 security_data = wim_const_security_data(args->w);
1072 ret = win32_extract_streams(inode, utf16le_path,
1073 &args->progress.extract.completed_bytes,
1076 goto out_free_utf16_path;
1078 if (inode->i_nlink > 1) {
1079 /* Save extracted path for a later call to
1080 * CreateHardLinkW() if this inode has multiple links.
1082 inode->i_extracted_file = utf16le_path;
1086 out_free_utf16_path:
1092 /* Set timestamps on an extracted file using the Win32 API */
1094 win32_do_apply_dentry_timestamps(const mbchar *output_path,
1095 size_t output_path_nbytes,
1096 const struct wim_dentry *dentry,
1097 const struct apply_args *args)
1100 wchar_t *utf16le_path;
1101 size_t utf16le_path_nbytes;
1105 const struct wim_inode *inode = dentry->d_inode;
1107 ret = mbs_to_utf16le(output_path, output_path_nbytes,
1108 &utf16le_path, &utf16le_path_nbytes);
1112 DEBUG("Opening \"%s\" to set timestamps", output_path);
1113 h = win32_open_existing_file(utf16le_path, FILE_WRITE_ATTRIBUTES);
1115 if (h == INVALID_HANDLE_VALUE)
1116 err = GetLastError();
1118 if (h == INVALID_HANDLE_VALUE)
1121 FILETIME creationTime = {.dwLowDateTime = inode->i_creation_time & 0xffffffff,
1122 .dwHighDateTime = inode->i_creation_time >> 32};
1123 FILETIME lastAccessTime = {.dwLowDateTime = inode->i_last_access_time & 0xffffffff,
1124 .dwHighDateTime = inode->i_last_access_time >> 32};
1125 FILETIME lastWriteTime = {.dwLowDateTime = inode->i_last_write_time & 0xffffffff,
1126 .dwHighDateTime = inode->i_last_write_time >> 32};
1128 DEBUG("Calling SetFileTime() on \"%s\"", output_path);
1129 if (!SetFileTime(h, &creationTime, &lastAccessTime, &lastWriteTime)) {
1130 err = GetLastError();
1134 DEBUG("Closing \"%s\"", output_path);
1135 if (!CloseHandle(h)) {
1136 err = GetLastError();
1141 /* Only warn if setting timestamps failed. */
1142 WARNING("Can't set timestamps on \"%s\"", output_path);
1148 /* Replacement for POSIX fsync() */
1152 HANDLE h = (HANDLE)_get_osfhandle(fd);
1153 if (h == INVALID_HANDLE_VALUE) {
1154 ERROR("Could not get Windows handle for file descriptor");
1155 win32_error(GetLastError());
1159 if (!FlushFileBuffers(h)) {
1160 ERROR("Could not flush file buffers to disk");
1161 win32_error(GetLastError());
1168 /* Use the Win32 API to get the number of processors */
1170 win32_get_number_of_processors()
1172 SYSTEM_INFO sysinfo;
1173 GetSystemInfo(&sysinfo);
1174 return sysinfo.dwNumberOfProcessors;
1177 /* Replacement for POSIX-2008 realpath(). Warning: partial functionality only
1178 * (resolved_path must be NULL). Also I highly doubt that GetFullPathName
1179 * really does the right thing under all circumstances. */
1181 realpath(const mbchar *path, mbchar *resolved_path)
1184 wimlib_assert(resolved_path == NULL);
1186 ret = GetFullPathNameA(path, 0, NULL, NULL);
1190 resolved_path = MALLOC(ret);
1193 ret = GetFullPathNameA(path, ret, resolved_path, NULL);
1195 free(resolved_path);
1198 return resolved_path;
1200 win32_error(GetLastError());
1206 nl_langinfo(nl_item item)
1208 wimlib_assert(item == CODESET);
1209 static char buf[64];
1210 strcpy(buf, "Unknown");
1214 /* rename() on Windows fails if the destination file exists. Fix it. */
1216 rename_replacement(const char *oldpath, const char *newpath)
1218 if (MoveFileExA(oldpath, newpath, MOVEFILE_REPLACE_EXISTING)) {
1221 /* As usual, the possible error values are not documented */
1222 DWORD err = GetLastError();
1223 ERROR("MoveFileExA(): Can't rename \"%s\" to \"%s\"",