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_file_readonly(const wchar_t *path, bool data_only)
81 DWORD dwDesiredAccess = FILE_READ_DATA;
83 dwDesiredAccess |= FILE_READ_ATTRIBUTES | READ_CONTROL | ACCESS_SYSTEM_SECURITY;
84 return CreateFileW(path,
87 NULL, /* lpSecurityAttributes */
89 FILE_FLAG_BACKUP_SEMANTICS |
90 FILE_FLAG_OPEN_REPARSE_POINT,
91 NULL /* hTemplateFile */);
95 win32_read_file(const mbchar *filename,
96 void *handle, u64 offset, size_t size, void *buf)
101 LARGE_INTEGER liOffset = {.QuadPart = offset};
103 wimlib_assert(size <= 0xffffffff);
105 if (SetFilePointerEx(h, liOffset, NULL, FILE_BEGIN))
106 if (ReadFile(h, buf, size, &bytesRead, NULL) && bytesRead == size)
108 err = GetLastError();
109 ERROR("Error reading \"%s\"", filename);
111 return WIMLIB_ERR_READ;
115 win32_close_file(void *handle)
117 CloseHandle((HANDLE)handle);
121 FILETIME_to_u64(const FILETIME *ft)
123 return ((u64)ft->dwHighDateTime << 32) | (u64)ft->dwLowDateTime;
127 win32_get_short_name(struct wim_dentry *dentry,
128 const wchar_t *path_utf16)
130 WIN32_FIND_DATAW dat;
131 if (FindFirstFileW(path_utf16, &dat) &&
132 dat.cAlternateFileName[0] != L'\0')
134 size_t short_name_nbytes = wcslen(dat.cAlternateFileName) * 2;
135 size_t n = short_name_nbytes + sizeof(wchar_t);
136 dentry->short_name = MALLOC(n);
137 if (!dentry->short_name)
138 return WIMLIB_ERR_NOMEM;
139 memcpy(dentry->short_name, dat.cAlternateFileName, n);
140 dentry->short_name_nbytes = short_name_nbytes;
146 win32_get_security_descriptor(struct wim_dentry *dentry,
147 struct sd_set *sd_set,
148 const wchar_t *path_utf16)
150 SECURITY_INFORMATION requestedInformation;
155 requestedInformation = DACL_SECURITY_INFORMATION |
156 SACL_SECURITY_INFORMATION |
157 OWNER_SECURITY_INFORMATION |
158 GROUP_SECURITY_INFORMATION;
159 /* Request length of security descriptor */
160 status = GetFileSecurityW(path_utf16, requestedInformation,
161 NULL, 0, &lenNeeded);
162 err = GetLastError();
163 if (!status && err == ERROR_INSUFFICIENT_BUFFER) {
164 DWORD len = lenNeeded;
166 if (GetFileSecurityW(path_utf16, requestedInformation,
167 (PSECURITY_DESCRIPTOR)buf, len, &lenNeeded))
169 int security_id = sd_set_add_sd(sd_set, buf, len);
171 return WIMLIB_ERR_NOMEM;
173 dentry->d_inode->i_security_id = security_id;
177 err = GetLastError();
181 if (err == ERROR_ACCESS_DENIED) {
182 WARNING("Failed to read security descriptor of \"%ls\": "
183 "Access denied!\n%s", path_utf16, access_denied_msg);
186 ERROR("Win32 API: Failed to read security descriptor of \"%ls\"",
189 return WIMLIB_ERR_READ;
193 /* Reads the directory entries of directory using a Win32 API and recursively
194 * calls win32_build_dentry_tree() on them. */
196 win32_recurse_directory(struct wim_dentry *root,
197 const mbchar *root_disk_path,
198 struct wim_lookup_table *lookup_table,
199 struct wim_security_data *sd,
200 const struct capture_config *config,
202 wimlib_progress_func_t progress_func,
203 struct sd_set *sd_set,
204 const wchar_t *path_utf16,
205 size_t path_utf16_nchars)
207 WIN32_FIND_DATAW dat;
213 /* Begin reading the directory by calling FindFirstFileW.
214 * Unlike UNIX opendir(), FindFirstFileW has file globbing built
215 * into it. But this isn't what we actually want, so just add a
216 * dummy glob to get all entries. */
217 wchar_t pattern_buf[path_utf16_nchars + 3];
218 memcpy(pattern_buf, path_utf16,
219 path_utf16_nchars * sizeof(wchar_t));
220 pattern_buf[path_utf16_nchars] = L'/';
221 pattern_buf[path_utf16_nchars + 1] = L'*';
222 pattern_buf[path_utf16_nchars + 2] = L'\0';
223 hFind = FindFirstFileW(pattern_buf, &dat);
225 if (hFind == INVALID_HANDLE_VALUE) {
226 err = GetLastError();
227 if (err == ERROR_FILE_NOT_FOUND) {
230 ERROR("Win32 API: Failed to read directory \"%s\"",
233 return WIMLIB_ERR_READ;
238 /* Skip . and .. entries */
239 if (!(dat.cFileName[0] == cpu_to_le16(L'.') &&
240 (dat.cFileName[1] == cpu_to_le16(L'\0') ||
241 (dat.cFileName[1] == cpu_to_le16(L'.') &&
242 dat.cFileName[2] == cpu_to_le16(L'\0')))))
244 struct wim_dentry *child;
247 size_t mbs_name_nbytes;
248 ret = utf16le_to_mbs(dat.cFileName,
249 wcslen(dat.cFileName) * sizeof(wchar_t),
255 mbchar name[strlen(root_disk_path) + 1 + mbs_name_nbytes + 1];
256 sprintf(name, "%s/%s", root_disk_path, mbs_name);
258 ret = win32_build_dentry_tree(&child, name, lookup_table,
259 sd, config, add_image_flags,
260 progress_func, sd_set);
264 dentry_add_child(root, child);
266 } while (FindNextFileW(hFind, &dat));
267 err = GetLastError();
268 if (err != ERROR_NO_MORE_FILES) {
269 ERROR("Win32 API: Failed to read directory \"%s\"", root_disk_path);
272 ret = WIMLIB_ERR_READ;
279 /* Load a reparse point into a WIM inode. It is just stored in memory.
281 * @hFile: Open handle to a reparse point, with permission to read the reparse
284 * @inode: WIM inode for the reparse point.
286 * @lookup_table: Stream lookup table for the WIM; an entry will be added to it
287 * for the reparse point unless an entry already exists for
288 * the exact same data stream.
290 * @path: External path to the reparse point. Used for error messages only.
292 * Returns 0 on success; nonzero on failure. */
294 win32_capture_reparse_point(HANDLE hFile,
295 struct wim_inode *inode,
296 struct wim_lookup_table *lookup_table,
299 /* "Reparse point data, including the tag and optional GUID,
300 * cannot exceed 16 kilobytes." - MSDN */
301 char reparse_point_buf[16 * 1024];
304 if (!DeviceIoControl(hFile, FSCTL_GET_REPARSE_POINT,
305 NULL, /* "Not used with this operation; set to NULL" */
306 0, /* "Not used with this operation; set to 0" */
307 reparse_point_buf, /* "A pointer to a buffer that
308 receives the reparse point data */
309 sizeof(reparse_point_buf), /* "The size of the output
314 DWORD err = GetLastError();
315 ERROR("Win32 API: Failed to get reparse data of \"%s\"", path);
317 return WIMLIB_ERR_READ;
319 if (bytesReturned < 8) {
320 ERROR("Reparse data on \"%s\" is invalid", path);
321 return WIMLIB_ERR_READ;
323 inode->i_reparse_tag = le32_to_cpu(*(u32*)reparse_point_buf);
324 return inode_add_ads_with_data(inode, "",
325 reparse_point_buf + 8,
326 bytesReturned - 8, lookup_table);
329 /* Calculate the SHA1 message digest of a Win32 data stream, which may be either
330 * an unnamed or named data stream.
332 * @path: Path to the file, with the stream noted at the end for named
333 * streams. UTF-16LE encoding.
335 * @hash: On success, the SHA1 message digest of the stream is written to
338 * Returns 0 on success; nonzero on failure.
341 win32_sha1sum(const wchar_t *path, u8 hash[SHA1_HASH_SIZE])
349 hFile = win32_open_file_readonly(path, false);
350 if (hFile == INVALID_HANDLE_VALUE)
351 return WIMLIB_ERR_OPEN;
355 if (!ReadFile(hFile, buf, sizeof(buf), &bytesRead, NULL)) {
356 ret = WIMLIB_ERR_READ;
357 goto out_close_handle;
361 sha1_update(&ctx, buf, bytesRead);
364 sha1_final(hash, &ctx);
370 /* Scans an unnamed or named stream of a Win32 file (not a reparse point
371 * stream); calculates its SHA1 message digest and either creates a `struct
372 * wim_lookup_table_entry' in memory for it, or uses an existing 'struct
373 * wim_lookup_table_entry' for an identical stream.
375 * @path_utf16: Path to the file (UTF-16LE).
377 * @path_utf16_nchars: Number of 2-byte characters in @path_utf16.
379 * @inode: WIM inode to save the stream into.
381 * @lookup_table: Stream lookup table for the WIM.
383 * @dat: A `WIN32_FIND_STREAM_DATA' structure that specifies the
386 * Returns 0 on success; nonzero on failure.
389 win32_capture_stream(const wchar_t *path_utf16,
390 size_t path_utf16_nchars,
391 struct wim_inode *inode,
392 struct wim_lookup_table *lookup_table,
393 WIN32_FIND_STREAM_DATA *dat)
395 struct wim_ads_entry *ads_entry;
396 u8 hash[SHA1_HASH_SIZE];
397 struct wim_lookup_table_entry *lte;
399 wchar_t *stream_name, *colon;
400 size_t stream_name_nchars;
401 bool is_named_stream;
405 size_t spath_buf_nbytes;
406 const wchar_t *relpath_prefix;
407 const wchar_t *colonchar;
409 /* The stream name should be returned as :NAME:TYPE */
410 stream_name = dat->cStreamName;
411 if (*stream_name != L':')
412 goto out_invalid_stream_name;
414 colon = wcschr(stream_name, L':');
416 goto out_invalid_stream_name;
418 if (wcscmp(colon + 1, L"$DATA")) {
419 /* Not a DATA stream */
426 stream_name_nchars = colon - stream_name;
427 is_named_stream = (stream_name_nchars != 0);
429 if (is_named_stream) {
430 /* Allocate an ADS entry for the named stream. */
431 ads_entry = inode_add_ads_utf16le(inode, stream_name,
432 stream_name_nchars * 2);
434 ret = WIMLIB_ERR_NOMEM;
439 /* Create a UTF-16LE string @spath that gives the filename, then a
440 * colon, then the stream name. Or, if it's an unnamed stream, just the
441 * filename. It is MALLOC()'ed so that it can be saved in the
442 * wim_lookup_table_entry if needed.
444 * As yet another special case, relative paths need to be changed to
445 * begin with an explicit "./" so that, for example, a file t:ads, where
446 * :ads is the part we added, is not interpreted as a file on the t:
448 spath_nchars = path_utf16_nchars;
449 relpath_prefix = L"";
451 if (is_named_stream) {
452 spath_nchars += 1 + stream_name_nchars;
454 if (path_utf16_nchars == 1 &&
455 path_utf16[0] != cpu_to_le16('/') &&
456 path_utf16[0] != cpu_to_le16('\\'))
459 relpath_prefix = L"./";
463 spath_buf_nbytes = (spath_nchars + 1) * sizeof(wchar_t);
464 spath = MALLOC(spath_buf_nbytes);
466 swprintf(spath, spath_buf_nbytes, L"%ls%ls%ls%ls",
467 relpath_prefix, path_utf16, colonchar, stream_name);
469 ret = win32_sha1sum(spath, hash);
471 err = GetLastError();
472 ERROR("Win32 API: Failed to read \"%ls\" to calculate SHA1sum",
478 lte = __lookup_resource(lookup_table, hash);
480 /* Use existing wim_lookup_table_entry that has the same SHA1
484 /* Make a new wim_lookup_table_entry */
485 lte = new_lookup_table_entry();
487 ret = WIMLIB_ERR_NOMEM;
490 lte->win32_file_on_disk = spath;
491 lte->file_on_disk_fp = INVALID_HANDLE_VALUE;
493 lte->resource_location = RESOURCE_WIN32;
494 lte->resource_entry.original_size = (uint64_t)dat->StreamSize.QuadPart;
495 lte->resource_entry.size = (uint64_t)dat->StreamSize.QuadPart;
496 copy_hash(lte->hash, hash);
497 lookup_table_insert(lookup_table, lte);
500 ads_entry->lte = lte;
507 out_invalid_stream_name:
508 ERROR("Invalid stream name: \"%ls:%ls\"", path_utf16, dat->cStreamName);
509 ret = WIMLIB_ERR_READ;
513 /* Scans a Win32 file for unnamed and named data streams (not reparse point
516 * @path_utf16: Path to the file (UTF-16LE).
518 * @path_utf16_nchars: Number of 2-byte characters in @path_utf16.
520 * @inode: WIM inode to save the stream into.
522 * @lookup_table: Stream lookup table for the WIM.
524 * Returns 0 on success; nonzero on failure.
527 win32_capture_streams(const wchar_t *path_utf16,
528 size_t path_utf16_nchars,
529 struct wim_inode *inode,
530 struct wim_lookup_table *lookup_table)
532 WIN32_FIND_STREAM_DATA dat;
537 hFind = FindFirstStreamW(path_utf16, FindStreamInfoStandard, &dat, 0);
538 if (hFind == INVALID_HANDLE_VALUE) {
539 err = GetLastError();
541 /* Seems legal for this to return ERROR_HANDLE_EOF on reparse
542 * points and directories */
543 if ((inode->i_attributes &
544 (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
545 && err == ERROR_HANDLE_EOF)
549 if (err == ERROR_ACCESS_DENIED) {
550 WARNING("Failed to look up data streams of \"%ls\": "
551 "Access denied!\n%s", path_utf16,
555 ERROR("Win32 API: Failed to look up data streams of \"%ls\"",
558 return WIMLIB_ERR_READ;
563 ret = win32_capture_stream(path_utf16,
569 } while (FindNextStreamW(hFind, &dat));
570 err = GetLastError();
571 if (err != ERROR_HANDLE_EOF) {
572 ERROR("Win32 API: Error reading data streams from \"%ls\"", path_utf16);
574 ret = WIMLIB_ERR_READ;
581 /* Win32 version of capturing a directory tree */
583 win32_build_dentry_tree(struct wim_dentry **root_ret,
584 const mbchar *root_disk_path,
585 struct wim_lookup_table *lookup_table,
586 struct wim_security_data *sd,
587 const struct capture_config *config,
589 wimlib_progress_func_t progress_func,
592 struct wim_dentry *root = NULL;
594 struct wim_inode *inode;
597 size_t path_utf16_nbytes;
598 size_t path_utf16_nchars;
599 struct sd_set *sd_set;
602 if (exclude_path(root_disk_path, config, true)) {
603 if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT) {
604 ERROR("Cannot exclude the root directory from capture");
605 ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
608 if ((add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
611 union wimlib_progress_info info;
612 info.scan.cur_path = root_disk_path;
613 info.scan.excluded = true;
614 progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
619 if ((add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
622 union wimlib_progress_info info;
623 info.scan.cur_path = root_disk_path;
624 info.scan.excluded = false;
625 progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
628 if (extra_arg == NULL) {
629 sd_set = alloca(sizeof(struct sd_set));
630 sd_set->rb_root.rb_node = NULL,
636 ret = mbs_to_utf16le(root_disk_path, strlen(root_disk_path),
637 &path_utf16, &path_utf16_nbytes);
639 goto out_destroy_sd_set;
640 path_utf16_nchars = path_utf16_nbytes / sizeof(wchar_t);
642 HANDLE hFile = win32_open_file_readonly(path_utf16, false);
643 if (hFile == INVALID_HANDLE_VALUE) {
644 err = GetLastError();
645 ERROR("Win32 API: Failed to open \"%s\"", root_disk_path);
647 ret = WIMLIB_ERR_OPEN;
648 goto out_free_path_utf16;
651 BY_HANDLE_FILE_INFORMATION file_info;
652 if (!GetFileInformationByHandle(hFile, &file_info)) {
653 err = GetLastError();
654 ERROR("Win32 API: Failed to get file information for \"%s\"",
657 ret = WIMLIB_ERR_STAT;
658 goto out_close_handle;
661 /* Create a WIM dentry */
662 ret = new_dentry_with_timeless_inode(path_basename(root_disk_path), &root);
664 goto out_close_handle;
666 /* Start preparing the associated WIM inode */
667 inode = root->d_inode;
669 inode->i_attributes = file_info.dwFileAttributes;
670 inode->i_creation_time = FILETIME_to_u64(&file_info.ftCreationTime);
671 inode->i_last_write_time = FILETIME_to_u64(&file_info.ftLastWriteTime);
672 inode->i_last_access_time = FILETIME_to_u64(&file_info.ftLastAccessTime);
673 inode->i_ino = ((u64)file_info.nFileIndexHigh << 32) |
674 (u64)file_info.nFileIndexLow;
676 inode->i_resolved = 1;
677 add_image_flags &= ~(WIMLIB_ADD_IMAGE_FLAG_ROOT | WIMLIB_ADD_IMAGE_FLAG_SOURCE);
679 /* Get DOS name and security descriptor (if any). */
680 ret = win32_get_short_name(root, path_utf16);
682 goto out_close_handle;
683 ret = win32_get_security_descriptor(root, sd_set, path_utf16);
685 goto out_close_handle;
687 if (inode_is_directory(inode)) {
688 /* Directory (not a reparse point) --- recurse to children */
690 /* But first... directories may have alternate data streams that
691 * need to be captured. */
692 ret = win32_capture_streams(path_utf16,
697 goto out_close_handle;
698 ret = win32_recurse_directory(root,
708 } else if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
709 /* Reparse point: save the reparse tag and data */
710 ret = win32_capture_reparse_point(hFile,
715 /* Not a directory, not a reparse point; capture the default
716 * file contents and any alternate data streams. */
717 ret = win32_capture_streams(path_utf16,
727 if (extra_arg == NULL)
728 destroy_sd_set(sd_set);
733 free_dentry_tree(root, lookup_table);
737 /* Replacement for POSIX fnmatch() (partial functionality only) */
739 fnmatch(const char *pattern, const char *string, int flags)
741 if (PathMatchSpecA(string, pattern))
748 win32_set_reparse_data(HANDLE h,
750 const struct wim_lookup_table_entry *lte,
758 WARNING("\"%ls\" is marked as a reparse point but had no reparse data",
762 len = wim_resource_size(lte);
763 if (len > 16 * 1024 - 8) {
764 WARNING("\"%ls\": reparse data too long!", path);
768 /* The WIM stream omits the ReparseTag and ReparseDataLength fields, so
769 * leave 8 bytes of space for them at the beginning of the buffer, then
770 * set them manually. */
771 buf = alloca(len + 8);
772 ret = read_full_wim_resource(lte, buf + 8, 0);
775 *(u32*)(buf + 0) = cpu_to_le32(reparse_tag);
776 *(u16*)(buf + 4) = cpu_to_le16(len);
777 *(u16*)(buf + 6) = 0;
779 /* Set the reparse data on the open file using the
780 * FSCTL_SET_REPARSE_POINT ioctl.
782 * There are contradictions in Microsoft's documentation for this:
784 * "If hDevice was opened without specifying FILE_FLAG_OVERLAPPED,
785 * lpOverlapped is ignored."
787 * --- So setting lpOverlapped to NULL is okay since it's ignored.
789 * "If lpOverlapped is NULL, lpBytesReturned cannot be NULL. Even when an
790 * operation returns no output data and lpOutBuffer is NULL,
791 * DeviceIoControl makes use of lpBytesReturned. After such an
792 * operation, the value of lpBytesReturned is meaningless."
794 * --- So lpOverlapped not really ignored, as it affects another
795 * parameter. This is the actual behavior: lpBytesReturned must be
796 * specified, even though lpBytesReturned is documented as:
798 * "Not used with this operation; set to NULL."
801 if (!DeviceIoControl(h, FSCTL_SET_REPARSE_POINT, buf, len + 8,
803 &bytesReturned /* lpBytesReturned */,
804 NULL /* lpOverlapped */))
806 DWORD err = GetLastError();
807 ERROR("Failed to set reparse data on \"%ls\"", path);
809 return WIMLIB_ERR_WRITE;
816 win32_extract_chunk(const void *buf, size_t len, u64 offset, void *arg)
818 HANDLE hStream = arg;
820 DWORD nbytes_written;
821 wimlib_assert(len <= 0xffffffff);
823 if (!WriteFile(hStream, buf, len, &nbytes_written, NULL) ||
824 nbytes_written != len)
826 DWORD err = GetLastError();
827 ERROR("WriteFile(): write error");
829 return WIMLIB_ERR_WRITE;
835 do_win32_extract_stream(HANDLE hStream, struct wim_lookup_table_entry *lte)
837 return extract_wim_resource(lte, wim_resource_size(lte),
838 win32_extract_chunk, hStream);
842 win32_extract_stream(const struct wim_inode *inode,
844 const wchar_t *stream_name_utf16,
845 struct wim_lookup_table_entry *lte)
847 wchar_t *stream_path;
851 DWORD creationDisposition = CREATE_ALWAYS;
853 if (stream_name_utf16) {
854 /* Named stream. Create a buffer that contains the UTF-16LE
855 * string [.\]@path:@stream_name_utf16. This is needed to
856 * create and open the stream using CreateFileW(). I'm not
857 * aware of any other APIs to do this. Note: the '$DATA' suffix
858 * seems to be unneeded. Additional note: a "./" prefix needs
859 * to be added when the path is not absolute to avoid ambiguity
860 * with drive letters. */
861 size_t stream_path_nchars;
863 size_t stream_name_nchars;
864 const wchar_t *prefix;
866 path_nchars = wcslen(path);
867 stream_name_nchars = wcslen(stream_name_utf16);
868 stream_path_nchars = path_nchars + 1 + stream_name_nchars;
869 if (path[0] != cpu_to_le16(L'\0') &&
870 path[0] != cpu_to_le16(L'/') &&
871 path[0] != cpu_to_le16(L'\\') &&
872 path[1] != cpu_to_le16(L':'))
875 stream_path_nchars += 2;
879 stream_path = alloca((stream_path_nchars + 1) * sizeof(wchar_t));
880 swprintf(stream_path, stream_path_nchars + 1, L"%ls%ls:%ls",
881 prefix, path, stream_name_utf16);
883 /* Unnamed stream; its path is just the path to the file itself.
885 stream_path = (wchar_t*)path;
887 /* Directories must be created with CreateDirectoryW(). Then
888 * the call to CreateFileW() will merely open the directory that
889 * was already created rather than creating a new file. */
890 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
891 if (!CreateDirectoryW(stream_path, NULL)) {
892 err = GetLastError();
893 if (err != ERROR_ALREADY_EXISTS) {
894 ERROR("Failed to create directory \"%ls\"",
897 ret = WIMLIB_ERR_MKDIR;
901 DEBUG("Created directory \"%ls\"", stream_path);
902 if (!(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
906 creationDisposition = OPEN_EXISTING;
910 DEBUG("Opening \"%ls\"", stream_path);
911 h = CreateFileW(stream_path,
912 GENERIC_WRITE | WRITE_OWNER | WRITE_DAC | ACCESS_SYSTEM_SECURITY,
916 FILE_FLAG_OPEN_REPARSE_POINT |
917 FILE_FLAG_BACKUP_SEMANTICS |
920 if (h == INVALID_HANDLE_VALUE) {
921 err = GetLastError();
922 ERROR("Failed to create \"%ls\"", stream_path);
924 ret = WIMLIB_ERR_OPEN;
928 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT &&
929 stream_name_utf16 == NULL)
931 DEBUG("Setting reparse data on \"%ls\"", path);
932 ret = win32_set_reparse_data(h, inode->i_reparse_tag, lte, path);
934 goto fail_close_handle;
937 DEBUG("Extracting \"%ls\" (len = %"PRIu64")",
938 stream_path, wim_resource_size(lte));
939 ret = do_win32_extract_stream(h, lte);
941 goto fail_close_handle;
945 DEBUG("Closing \"%ls\"", stream_path);
946 if (!CloseHandle(h)) {
947 err = GetLastError();
948 ERROR("Failed to close \"%ls\"", stream_path);
950 ret = WIMLIB_ERR_WRITE;
958 ERROR("Error extracting %ls", stream_path);
964 * Creates a file, directory, or reparse point and extracts all streams to it
965 * (unnamed data stream and/or reparse point stream, plus any alternate data
966 * streams). This in Win32-specific code.
968 * @inode: WIM inode for this file or directory.
969 * @path: UTF-16LE external path to extract the inode to.
971 * Returns 0 on success; nonzero on failure.
974 win32_extract_streams(const struct wim_inode *inode,
975 const wchar_t *path, u64 *completed_bytes_p)
977 struct wim_lookup_table_entry *unnamed_lte;
980 unnamed_lte = inode_unnamed_lte_resolved(inode);
981 ret = win32_extract_stream(inode, path, NULL, unnamed_lte);
985 *completed_bytes_p += wim_resource_size(unnamed_lte);
986 for (u16 i = 0; i < inode->i_num_ads; i++) {
987 const struct wim_ads_entry *ads_entry = &inode->i_ads_entries[i];
988 if (ads_entry->stream_name_nbytes != 0) {
989 /* Skip special UNIX data entries (see documentation for
990 * WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA) */
991 if (ads_entry->stream_name_nbytes == WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES
992 && !memcmp(ads_entry->stream_name,
993 WIMLIB_UNIX_DATA_TAG_UTF16LE,
994 WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES))
996 ret = win32_extract_stream(inode,
998 ads_entry->stream_name,
1003 *completed_bytes_p += wim_resource_size(ads_entry->lte);
1011 * Sets the security descriptor on an extracted file. This is Win32-specific
1014 * @inode: The WIM inode that was extracted and has a security descriptor.
1015 * @path: UTF-16LE external path that the inode was extracted to.
1016 * @sd: Security data for the WIM image.
1018 * Returns 0 on success; nonzero on failure.
1020 static int win32_set_security_data(const struct wim_inode *inode,
1021 const wchar_t *path,
1022 const struct wim_security_data *sd)
1024 SECURITY_INFORMATION securityInformation = DACL_SECURITY_INFORMATION |
1025 SACL_SECURITY_INFORMATION |
1026 OWNER_SECURITY_INFORMATION |
1027 GROUP_SECURITY_INFORMATION;
1028 if (!SetFileSecurityW(path, securityInformation,
1029 (PSECURITY_DESCRIPTOR)sd->descriptors[inode->i_security_id]))
1031 DWORD err = GetLastError();
1032 ERROR("Can't set security descriptor on \"%ls\"", path);
1034 return WIMLIB_ERR_WRITE;
1039 /* Extract a file, directory, reparse point, or hard link to an
1040 * already-extracted file using the Win32 API */
1041 int win32_do_apply_dentry(const mbchar *output_path,
1042 size_t output_path_nbytes,
1043 struct wim_dentry *dentry,
1044 struct apply_args *args)
1046 wchar_t *utf16le_path;
1047 size_t utf16le_path_nbytes;
1050 struct wim_inode *inode = dentry->d_inode;
1052 ret = mbs_to_utf16le(output_path, output_path_nbytes,
1053 &utf16le_path, &utf16le_path_nbytes);
1057 if (inode->i_nlink > 1 && inode->i_extracted_file != NULL) {
1058 /* Linked file, with another name already extracted. Create a
1060 DEBUG("Creating hard link \"%ls => %ls\"",
1061 utf16le_path, inode->i_extracted_file);
1062 if (!CreateHardLinkW(utf16le_path, inode->i_extracted_file, NULL))
1064 err = GetLastError();
1065 ERROR("Can't create hard link \"%ls => %ls\"",
1066 utf16le_path, inode->i_extracted_file);
1067 ret = WIMLIB_ERR_LINK;
1071 /* Create the file, directory, or reparse point, and extract the
1073 ret = win32_extract_streams(inode, utf16le_path,
1074 &args->progress.extract.completed_bytes);
1076 goto out_free_utf16_path;
1078 /* Set security descriptor if present */
1079 if (inode->i_security_id != -1) {
1080 DEBUG("Setting security descriptor %d on %s",
1081 inode->i_security_id, output_path);
1082 ret = win32_set_security_data(inode,
1084 wim_const_security_data(args->w));
1086 goto out_free_utf16_path;
1088 if (inode->i_nlink > 1) {
1089 /* Save extracted path for a later call to
1090 * CreateHardLinkW() if this inode has multiple links.
1092 inode->i_extracted_file = utf16le_path;
1096 out_free_utf16_path:
1102 /* Set timestamps on an extracted file using the Win32 API */
1104 win32_do_apply_dentry_timestamps(const mbchar *output_path,
1105 size_t output_path_nbytes,
1106 const struct wim_dentry *dentry,
1107 const struct apply_args *args)
1110 wchar_t *utf16le_path;
1111 size_t utf16le_path_nbytes;
1115 const struct wim_inode *inode = dentry->d_inode;
1117 ret = mbs_to_utf16le(output_path, output_path_nbytes,
1118 &utf16le_path, &utf16le_path_nbytes);
1122 DEBUG("Opening \"%s\" to set timestamps", output_path);
1123 h = CreateFileW(utf16le_path,
1124 GENERIC_WRITE | WRITE_OWNER | WRITE_DAC | ACCESS_SYSTEM_SECURITY,
1128 FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
1131 if (h == INVALID_HANDLE_VALUE)
1132 err = GetLastError();
1134 if (h == INVALID_HANDLE_VALUE)
1137 FILETIME creationTime = {.dwLowDateTime = inode->i_creation_time & 0xffffffff,
1138 .dwHighDateTime = inode->i_creation_time >> 32};
1139 FILETIME lastAccessTime = {.dwLowDateTime = inode->i_last_access_time & 0xffffffff,
1140 .dwHighDateTime = inode->i_last_access_time >> 32};
1141 FILETIME lastWriteTime = {.dwLowDateTime = inode->i_last_write_time & 0xffffffff,
1142 .dwHighDateTime = inode->i_last_write_time >> 32};
1144 DEBUG("Calling SetFileTime() on \"%s\"", output_path);
1145 if (!SetFileTime(h, &creationTime, &lastAccessTime, &lastWriteTime)) {
1146 err = GetLastError();
1150 DEBUG("Closing \"%s\"", output_path);
1151 if (!CloseHandle(h)) {
1152 err = GetLastError();
1157 /* Only warn if setting timestamps failed. */
1158 WARNING("Can't set timestamps on \"%s\"", output_path);
1164 /* Replacement for POSIX fsync() */
1168 HANDLE h = (HANDLE)_get_osfhandle(fd);
1169 if (h == INVALID_HANDLE_VALUE) {
1170 ERROR("Could not get Windows handle for file descriptor");
1171 win32_error(GetLastError());
1175 if (!FlushFileBuffers(h)) {
1176 ERROR("Could not flush file buffers to disk");
1177 win32_error(GetLastError());
1184 /* Use the Win32 API to get the number of processors */
1186 win32_get_number_of_processors()
1188 SYSTEM_INFO sysinfo;
1189 GetSystemInfo(&sysinfo);
1190 return sysinfo.dwNumberOfProcessors;
1193 /* Replacement for POSIX-2008 realpath(). Warning: partial functionality only
1194 * (resolved_path must be NULL). Also I highly doubt that GetFullPathName
1195 * really does the right thing under all circumstances. */
1197 realpath(const mbchar *path, mbchar *resolved_path)
1200 wimlib_assert(resolved_path == NULL);
1202 ret = GetFullPathNameA(path, 0, NULL, NULL);
1206 resolved_path = MALLOC(ret);
1209 ret = GetFullPathNameA(path, ret, resolved_path, NULL);
1211 free(resolved_path);
1214 return resolved_path;
1216 win32_error(GetLastError());
1222 nl_langinfo(nl_item item)
1224 wimlib_assert(item == CODESET);
1225 static char buf[64];
1226 strcpy(buf, "Unknown");
1230 /* rename() on Windows fails if the destination file exists. Fix it. */
1232 rename_replacement(const char *oldpath, const char *newpath)
1234 if (MoveFileExA(oldpath, newpath, MOVEFILE_REPLACE_EXISTING)) {
1237 /* As usual, the possible error values are not documented */
1238 DWORD err = GetLastError();
1239 ERROR("MoveFileExA(): Can't rename \"%s\" to \"%s\"",