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] == L'.' &&
240 (dat.cFileName[1] == L'\0' ||
241 (dat.cFileName[1] == L'.' && dat.cFileName[2] == L'\0'))))
243 struct wim_dentry *child;
246 size_t mbs_name_nbytes;
247 ret = utf16le_to_mbs(dat.cFileName,
248 wcslen(dat.cFileName) * sizeof(wchar_t),
254 char name[strlen(root_disk_path) + 1 + mbs_name_nbytes + 1];
255 sprintf(name, "%s/%s", root_disk_path, mbs_name);
257 ret = win32_build_dentry_tree(&child, name, lookup_table,
258 sd, config, add_image_flags,
259 progress_func, sd_set);
263 dentry_add_child(root, child);
265 } while (FindNextFileW(hFind, &dat));
266 err = GetLastError();
267 if (err != ERROR_NO_MORE_FILES) {
268 ERROR("Win32 API: Failed to read directory \"%s\"", root_disk_path);
271 ret = WIMLIB_ERR_READ;
278 /* Load a reparse point into a WIM inode. It is just stored in memory.
280 * @hFile: Open handle to a reparse point, with permission to read the reparse
283 * @inode: WIM inode for the reparse point.
285 * @lookup_table: Stream lookup table for the WIM; an entry will be added to it
286 * for the reparse point unless an entry already exists for
287 * the exact same data stream.
289 * @path: External path to the parse point (UTF-8). Used for error messages
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, 0, reparse_point_buf,
306 sizeof(reparse_point_buf), &bytesReturned, NULL))
308 DWORD err = GetLastError();
309 ERROR("Win32 API: Failed to get reparse data of \"%s\"", path);
311 return WIMLIB_ERR_READ;
313 if (bytesReturned < 8) {
314 ERROR("Reparse data on \"%s\" is invalid", path);
315 return WIMLIB_ERR_READ;
317 inode->i_reparse_tag = le32_to_cpu(*(u32*)reparse_point_buf);
318 return inode_add_ads_with_data(inode, "",
319 (const u8*)reparse_point_buf + 8,
320 bytesReturned - 8, lookup_table);
323 /* Calculate the SHA1 message digest of a Win32 data stream, which may be either
324 * an unnamed or named data stream.
326 * @path: Path to the file, with the stream noted at the end for named
327 * streams. UTF-16LE encoding.
329 * @hash: On success, the SHA1 message digest of the stream is written to
332 * Returns 0 on success; nonzero on failure.
335 win32_sha1sum(const wchar_t *path, u8 hash[SHA1_HASH_SIZE])
343 hFile = win32_open_file_readonly(path, false);
344 if (hFile == INVALID_HANDLE_VALUE)
345 return WIMLIB_ERR_OPEN;
349 if (!ReadFile(hFile, buf, sizeof(buf), &bytesRead, NULL)) {
350 ret = WIMLIB_ERR_READ;
351 goto out_close_handle;
355 sha1_update(&ctx, buf, bytesRead);
358 sha1_final(hash, &ctx);
364 /* Scans an unnamed or named stream of a Win32 file (not a reparse point
365 * stream); calculates its SHA1 message digest and either creates a `struct
366 * wim_lookup_table_entry' in memory for it, or uses an existing 'struct
367 * wim_lookup_table_entry' for an identical stream.
369 * @path_utf16: Path to the file (UTF-16LE).
371 * @path_utf16_nchars: Number of 2-byte characters in @path_utf16.
373 * @inode: WIM inode to save the stream into.
375 * @lookup_table: Stream lookup table for the WIM.
377 * @dat: A `WIN32_FIND_STREAM_DATA' structure that specifies the
380 * Returns 0 on success; nonzero on failure.
383 win32_capture_stream(const wchar_t *path_utf16,
384 size_t path_utf16_nchars,
385 struct wim_inode *inode,
386 struct wim_lookup_table *lookup_table,
387 WIN32_FIND_STREAM_DATA *dat)
389 struct wim_ads_entry *ads_entry;
390 u8 hash[SHA1_HASH_SIZE];
391 struct wim_lookup_table_entry *lte;
394 bool is_named_stream;
399 /* The stream name should be returned as :NAME:TYPE */
400 p = dat->cStreamName;
402 goto out_invalid_stream_name;
404 colon = wcschr(p, L':');
406 goto out_invalid_stream_name;
408 if (wcscmp(colon + 1, L"$DATA")) {
409 /* Not a DATA stream */
414 is_named_stream = (p != colon);
415 if (is_named_stream) {
416 /* Allocate an ADS entry for the named stream. */
417 char *mbs_stream_name;
418 size_t mbs_stream_name_nbytes;
419 ret = utf16le_to_mbs(p,
420 (colon - p) * sizeof(wchar_t),
422 &mbs_stream_name_nbytes);
425 ads_entry = inode_add_ads(inode, mbs_stream_name);
426 FREE(mbs_stream_name);
428 ret = WIMLIB_ERR_NOMEM;
433 /* Create a UTF-16 string @spath that gives the filename, then a colon,
434 * then the stream name. Or, if it's an unnamed stream, just the
435 * filename. It is MALLOC()'ed so that it can be saved in the
436 * wim_lookup_table_entry if needed. */
438 spath_nchars = path_utf16_nchars;
440 spath_nchars += colon - p + 1;
442 spath = MALLOC((spath_nchars + 1) * sizeof(wchar_t));
443 memcpy(spath, path_utf16, path_utf16_nchars * sizeof(wchar_t));
444 if (is_named_stream) {
445 spath[path_utf16_nchars] = L':';
446 memcpy(&spath[path_utf16_nchars + 1], p, (colon - p) * sizeof(wchar_t));
448 spath[spath_nchars] = L'\0';
450 ret = win32_sha1sum(spath, hash);
452 err = GetLastError();
453 ERROR("Win32 API: Failed to read \"%ls\" to calculate SHA1sum",
459 lte = __lookup_resource(lookup_table, hash);
461 /* Use existing wim_lookup_table_entry that has the same SHA1
465 /* Make a new wim_lookup_table_entry */
466 lte = new_lookup_table_entry();
468 ret = WIMLIB_ERR_NOMEM;
471 lte->win32_file_on_disk = spath;
472 lte->file_on_disk_fp = INVALID_HANDLE_VALUE;
474 lte->resource_location = RESOURCE_WIN32;
475 lte->resource_entry.original_size = (uint64_t)dat->StreamSize.QuadPart;
476 lte->resource_entry.size = (uint64_t)dat->StreamSize.QuadPart;
477 copy_hash(lte->hash, hash);
478 lookup_table_insert(lookup_table, lte);
481 ads_entry->lte = lte;
488 out_invalid_stream_name:
489 ERROR("Invalid stream name: \"%ls:%ls\"", path_utf16, dat->cStreamName);
490 ret = WIMLIB_ERR_READ;
494 /* Scans a Win32 file for unnamed and named data streams (not reparse point
497 * @path_utf16: Path to the file (UTF-16LE).
499 * @path_utf16_nchars: Number of 2-byte characters in @path_utf16.
501 * @inode: WIM inode to save the stream into.
503 * @lookup_table: Stream lookup table for the WIM.
505 * Returns 0 on success; nonzero on failure.
508 win32_capture_streams(const wchar_t *path_utf16,
509 size_t path_utf16_nchars,
510 struct wim_inode *inode,
511 struct wim_lookup_table *lookup_table)
513 WIN32_FIND_STREAM_DATA dat;
518 hFind = FindFirstStreamW(path_utf16, FindStreamInfoStandard, &dat, 0);
519 if (hFind == INVALID_HANDLE_VALUE) {
520 err = GetLastError();
522 /* Seems legal for this to return ERROR_HANDLE_EOF on reparse
523 * points and directories */
524 if ((inode->i_attributes &
525 (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
526 && err == ERROR_HANDLE_EOF)
530 if (err == ERROR_ACCESS_DENIED) {
531 WARNING("Failed to look up data streams of \"%ls\": "
532 "Access denied!\n%s", path_utf16,
536 ERROR("Win32 API: Failed to look up data streams of \"%ls\"",
539 return WIMLIB_ERR_READ;
544 ret = win32_capture_stream(path_utf16,
550 } while (FindNextStreamW(hFind, &dat));
551 err = GetLastError();
552 if (err != ERROR_HANDLE_EOF) {
553 ERROR("Win32 API: Error reading data streams from \"%ls\"", path_utf16);
555 ret = WIMLIB_ERR_READ;
562 /* Win32 version of capturing a directory tree */
564 win32_build_dentry_tree(struct wim_dentry **root_ret,
565 const char *root_disk_path,
566 struct wim_lookup_table *lookup_table,
567 struct wim_security_data *sd,
568 const struct capture_config *config,
570 wimlib_progress_func_t progress_func,
573 struct wim_dentry *root = NULL;
575 struct wim_inode *inode;
578 size_t path_utf16_nbytes;
579 size_t path_utf16_nchars;
580 struct sd_set *sd_set;
583 if (exclude_path(root_disk_path, config, true)) {
584 if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT) {
585 ERROR("Cannot exclude the root directory from capture");
586 ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
589 if ((add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
592 union wimlib_progress_info info;
593 info.scan.cur_path = root_disk_path;
594 info.scan.excluded = true;
595 progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
600 if ((add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
603 union wimlib_progress_info info;
604 info.scan.cur_path = root_disk_path;
605 info.scan.excluded = false;
606 progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
609 if (extra_arg == NULL) {
610 sd_set = alloca(sizeof(struct sd_set));
611 sd_set->rb_root.rb_node = NULL,
617 ret = mbs_to_utf16le(root_disk_path, strlen(root_disk_path),
618 &path_utf16, &path_utf16_nbytes);
620 goto out_destroy_sd_set;
621 path_utf16_nchars = path_utf16_nbytes / sizeof(wchar_t);
623 HANDLE hFile = win32_open_file_readonly(path_utf16, false);
624 if (hFile == INVALID_HANDLE_VALUE) {
625 err = GetLastError();
626 ERROR("Win32 API: Failed to open \"%s\"", root_disk_path);
628 ret = WIMLIB_ERR_OPEN;
629 goto out_free_path_utf16;
632 BY_HANDLE_FILE_INFORMATION file_info;
633 if (!GetFileInformationByHandle(hFile, &file_info)) {
634 err = GetLastError();
635 ERROR("Win32 API: Failed to get file information for \"%s\"",
638 ret = WIMLIB_ERR_STAT;
639 goto out_close_handle;
642 /* Create a WIM dentry */
643 ret = new_dentry_with_timeless_inode(path_basename(root_disk_path), &root);
645 goto out_close_handle;
647 /* Start preparing the associated WIM inode */
648 inode = root->d_inode;
650 inode->i_attributes = file_info.dwFileAttributes;
651 inode->i_creation_time = FILETIME_to_u64(&file_info.ftCreationTime);
652 inode->i_last_write_time = FILETIME_to_u64(&file_info.ftLastWriteTime);
653 inode->i_last_access_time = FILETIME_to_u64(&file_info.ftLastAccessTime);
654 inode->i_ino = ((u64)file_info.nFileIndexHigh << 32) |
655 (u64)file_info.nFileIndexLow;
657 inode->i_resolved = 1;
658 add_image_flags &= ~(WIMLIB_ADD_IMAGE_FLAG_ROOT | WIMLIB_ADD_IMAGE_FLAG_SOURCE);
660 /* Get DOS name and security descriptor (if any). */
661 ret = win32_get_short_name(root, path_utf16);
663 goto out_close_handle;
664 ret = win32_get_security_descriptor(root, sd_set, path_utf16);
666 goto out_close_handle;
668 if (inode_is_directory(inode)) {
669 /* Directory (not a reparse point) --- recurse to children */
671 /* But first... directories may have alternate data streams that
672 * need to be captured. */
673 ret = win32_capture_streams(path_utf16,
678 goto out_close_handle;
679 ret = win32_recurse_directory(root,
689 } else if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
690 /* Reparse point: save the reparse tag and data */
691 ret = win32_capture_reparse_point(hFile,
696 /* Not a directory, not a reparse point; capture the default
697 * file contents and any alternate data streams. */
698 ret = win32_capture_streams(path_utf16,
708 if (extra_arg == NULL)
709 destroy_sd_set(sd_set);
714 free_dentry_tree(root, lookup_table);
718 /* Replacement for POSIX fnmatch() (partial functionality only) */
720 fnmatch(const char *pattern, const char *string, int flags)
722 if (PathMatchSpecA(string, pattern))
729 win32_set_reparse_data(HANDLE h,
731 const struct wim_lookup_table_entry *lte,
739 WARNING("\"%ls\" is marked as a reparse point but had no reparse data",
743 len = wim_resource_size(lte);
744 if (len > 16 * 1024 - 8) {
745 WARNING("\"%ls\": reparse data too long!", path);
749 /* The WIM stream omits the ReparseTag and ReparseDataLength fields, so
750 * leave 8 bytes of space for them at the beginning of the buffer, then
751 * set them manually. */
752 buf = alloca(len + 8);
753 ret = read_full_wim_resource(lte, buf + 8, 0);
756 *(u32*)(buf + 0) = cpu_to_le32(reparse_tag);
757 *(u16*)(buf + 4) = cpu_to_le16(len);
758 *(u16*)(buf + 6) = 0;
760 /* Set the reparse data on the open file using the
761 * FSCTL_SET_REPARSE_POINT ioctl.
763 * There are contradictions in Microsoft's documentation for this:
765 * "If hDevice was opened without specifying FILE_FLAG_OVERLAPPED,
766 * lpOverlapped is ignored."
768 * --- So setting lpOverlapped to NULL is okay since it's ignored.
770 * "If lpOverlapped is NULL, lpBytesReturned cannot be NULL. Even when an
771 * operation returns no output data and lpOutBuffer is NULL,
772 * DeviceIoControl makes use of lpBytesReturned. After such an
773 * operation, the value of lpBytesReturned is meaningless."
775 * --- So lpOverlapped not really ignored, as it affects another
776 * parameter. This is the actual behavior: lpBytesReturned must be
777 * specified, even though lpBytesReturned is documented as:
779 * "Not used with this operation; set to NULL."
782 if (!DeviceIoControl(h, FSCTL_SET_REPARSE_POINT, buf, len + 8,
784 &bytesReturned /* lpBytesReturned */,
785 NULL /* lpOverlapped */))
787 DWORD err = GetLastError();
788 ERROR("Failed to set reparse data on \"%ls\"", path);
790 return WIMLIB_ERR_WRITE;
797 win32_extract_chunk(const void *buf, size_t len, u64 offset, void *arg)
799 HANDLE hStream = arg;
801 DWORD nbytes_written;
802 wimlib_assert(len <= 0xffffffff);
804 if (!WriteFile(hStream, buf, len, &nbytes_written, NULL) ||
805 nbytes_written != len)
807 DWORD err = GetLastError();
808 ERROR("WriteFile(): write error");
810 return WIMLIB_ERR_WRITE;
816 do_win32_extract_stream(HANDLE hStream, struct wim_lookup_table_entry *lte)
818 return extract_wim_resource(lte, wim_resource_size(lte),
819 win32_extract_chunk, hStream);
823 win32_extract_stream(const struct wim_inode *inode,
825 const wchar_t *stream_name_utf16,
826 struct wim_lookup_table_entry *lte)
828 wchar_t *stream_path;
832 DWORD creationDisposition = CREATE_ALWAYS;
834 if (stream_name_utf16) {
835 /* Named stream. Create a buffer that contains the UTF-16LE
836 * string [./]@path:@stream_name_utf16. This is needed to
837 * create and open the stream using CreateFileW(). I'm not
838 * aware of any other APIs to do this. Note: the '$DATA' suffix
839 * seems to be unneeded. Additional note: a "./" prefix needs
840 * to be added when the path is not absolute to avoid ambiguity
841 * with drive letters. */
842 size_t stream_path_nchars;
844 size_t stream_name_nchars;
845 const wchar_t *prefix;
847 path_nchars = wcslen(path);
848 stream_name_nchars = wcslen(stream_name_utf16);
849 stream_path_nchars = path_nchars + 1 + stream_name_nchars;
850 if (path[0] != L'/' && path[0] != L'\\') {
852 stream_path_nchars += 2;
856 stream_path = alloca((stream_path_nchars + 1) * sizeof(wchar_t));
857 swprintf(stream_path, stream_path_nchars + 1, L"%ls%ls:%ls",
858 prefix, path, stream_name_utf16);
860 /* Unnamed stream; its path is just the path to the file itself.
862 stream_path = (wchar_t*)path;
864 /* Directories must be created with CreateDirectoryW(). Then
865 * the call to CreateFileW() will merely open the directory that
866 * was already created rather than creating a new file. */
867 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
868 if (!CreateDirectoryW(stream_path, NULL)) {
869 err = GetLastError();
870 if (err != ERROR_ALREADY_EXISTS) {
871 ERROR("Failed to create directory \"%ls\"",
874 ret = WIMLIB_ERR_MKDIR;
878 DEBUG("Created directory \"%ls\"", stream_path);
879 if (!(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
883 creationDisposition = OPEN_EXISTING;
887 DEBUG("Opening \"%ls\"", stream_path);
888 h = CreateFileW(stream_path,
889 GENERIC_WRITE | WRITE_OWNER | WRITE_DAC | ACCESS_SYSTEM_SECURITY,
893 FILE_FLAG_OPEN_REPARSE_POINT |
894 FILE_FLAG_BACKUP_SEMANTICS |
897 if (h == INVALID_HANDLE_VALUE) {
898 err = GetLastError();
899 ERROR("Failed to create \"%ls\"", stream_path);
901 ret = WIMLIB_ERR_OPEN;
905 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT &&
906 stream_name_utf16 == NULL)
908 DEBUG("Setting reparse data on \"%ls\"", path);
909 ret = win32_set_reparse_data(h, inode->i_reparse_tag, lte, path);
911 goto fail_close_handle;
914 DEBUG("Extracting \"%ls\" (len = %"PRIu64")",
915 stream_path, wim_resource_size(lte));
916 ret = do_win32_extract_stream(h, lte);
918 goto fail_close_handle;
922 DEBUG("Closing \"%ls\"", stream_path);
923 if (!CloseHandle(h)) {
924 err = GetLastError();
925 ERROR("Failed to close \"%ls\"", stream_path);
927 ret = WIMLIB_ERR_WRITE;
935 ERROR("Error extracting %ls", stream_path);
941 * Creates a file, directory, or reparse point and extracts all streams to it
942 * (unnamed data stream and/or reparse point stream, plus any alternate data
943 * streams). This in Win32-specific code.
945 * @inode: WIM inode for this file or directory.
946 * @path: UTF-16LE external path to extract the inode to.
948 * Returns 0 on success; nonzero on failure.
951 win32_extract_streams(const struct wim_inode *inode,
952 const wchar_t *path, u64 *completed_bytes_p)
954 struct wim_lookup_table_entry *unnamed_lte;
957 unnamed_lte = inode_unnamed_lte_resolved(inode);
958 ret = win32_extract_stream(inode, path, NULL, unnamed_lte);
962 *completed_bytes_p += wim_resource_size(unnamed_lte);
963 for (u16 i = 0; i < inode->i_num_ads; i++) {
964 const struct wim_ads_entry *ads_entry = &inode->i_ads_entries[i];
965 if (ads_entry->stream_name_nbytes != 0) {
966 /* Skip special UNIX data entries (see documentation for
967 * WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA) */
968 if (ads_entry->stream_name_nbytes == WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES
969 && !memcmp(ads_entry->stream_name,
970 WIMLIB_UNIX_DATA_TAG_UTF16LE,
971 WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES))
973 ret = win32_extract_stream(inode,
975 ads_entry->stream_name,
980 *completed_bytes_p += wim_resource_size(ads_entry->lte);
988 * Sets the security descriptor on an extracted file. This is Win32-specific
991 * @inode: The WIM inode that was extracted and has a security descriptor.
992 * @path: UTF-16LE external path that the inode was extracted to.
993 * @sd: Security data for the WIM image.
995 * Returns 0 on success; nonzero on failure.
997 static int win32_set_security_data(const struct wim_inode *inode,
999 const struct wim_security_data *sd)
1001 SECURITY_INFORMATION securityInformation = DACL_SECURITY_INFORMATION |
1002 SACL_SECURITY_INFORMATION |
1003 OWNER_SECURITY_INFORMATION |
1004 GROUP_SECURITY_INFORMATION;
1005 if (!SetFileSecurityW(path, securityInformation,
1006 (PSECURITY_DESCRIPTOR)sd->descriptors[inode->i_security_id]))
1008 DWORD err = GetLastError();
1009 ERROR("Can't set security descriptor on \"%ls\"", path);
1011 return WIMLIB_ERR_WRITE;
1016 /* Extract a file, directory, reparse point, or hard link to an
1017 * already-extracted file using the Win32 API */
1018 int win32_do_apply_dentry(const mbchar *output_path,
1019 size_t output_path_nbytes,
1020 struct wim_dentry *dentry,
1021 struct apply_args *args)
1023 wchar_t *utf16le_path;
1024 size_t utf16le_path_nbytes;
1027 struct wim_inode *inode = dentry->d_inode;
1029 ret = mbs_to_utf16le(output_path, output_path_nbytes,
1030 &utf16le_path, &utf16le_path_nbytes);
1034 if (inode->i_nlink > 1 && inode->i_extracted_file != NULL) {
1035 /* Linked file, with another name already extracted. Create a
1037 DEBUG("Creating hard link \"%ls => %ls\"",
1038 utf16le_path, inode->i_extracted_file);
1039 if (!CreateHardLinkW(utf16le_path, inode->i_extracted_file, NULL))
1041 err = GetLastError();
1042 ERROR("Can't create hard link \"%ls => %ls\"",
1043 utf16le_path, inode->i_extracted_file);
1044 ret = WIMLIB_ERR_LINK;
1048 /* Create the file, directory, or reparse point, and extract the
1050 ret = win32_extract_streams(inode, utf16le_path,
1051 &args->progress.extract.completed_bytes);
1053 goto out_free_utf16_path;
1055 /* Set security descriptor if present */
1056 if (inode->i_security_id != -1) {
1057 DEBUG("Setting security descriptor %d on %s",
1058 inode->i_security_id, output_path);
1059 ret = win32_set_security_data(inode,
1061 wim_const_security_data(args->w));
1063 goto out_free_utf16_path;
1065 if (inode->i_nlink > 1) {
1066 /* Save extracted path for a later call to
1067 * CreateHardLinkW() if this inode has multiple links.
1069 inode->i_extracted_file = utf16le_path;
1073 out_free_utf16_path:
1079 /* Set timestamps on an extracted file using the Win32 API */
1081 win32_do_apply_dentry_timestamps(const mbchar *output_path,
1082 size_t output_path_nbytes,
1083 const struct wim_dentry *dentry,
1084 const struct apply_args *args)
1087 wchar_t *utf16le_path;
1088 size_t utf16le_path_nbytes;
1092 const struct wim_inode *inode = dentry->d_inode;
1094 ret = mbs_to_utf16le(output_path, output_path_nbytes,
1095 &utf16le_path, &utf16le_path_nbytes);
1099 DEBUG("Opening \"%s\" to set timestamps", output_path);
1100 h = CreateFileW(utf16le_path,
1101 GENERIC_WRITE | WRITE_OWNER | WRITE_DAC | ACCESS_SYSTEM_SECURITY,
1105 FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
1108 if (h == INVALID_HANDLE_VALUE)
1109 err = GetLastError();
1111 if (h == INVALID_HANDLE_VALUE)
1114 FILETIME creationTime = {.dwLowDateTime = inode->i_creation_time & 0xffffffff,
1115 .dwHighDateTime = inode->i_creation_time >> 32};
1116 FILETIME lastAccessTime = {.dwLowDateTime = inode->i_last_access_time & 0xffffffff,
1117 .dwHighDateTime = inode->i_last_access_time >> 32};
1118 FILETIME lastWriteTime = {.dwLowDateTime = inode->i_last_write_time & 0xffffffff,
1119 .dwHighDateTime = inode->i_last_write_time >> 32};
1121 DEBUG("Calling SetFileTime() on \"%s\"", output_path);
1122 if (!SetFileTime(h, &creationTime, &lastAccessTime, &lastWriteTime)) {
1123 err = GetLastError();
1127 DEBUG("Closing \"%s\"", output_path);
1128 if (!CloseHandle(h)) {
1129 err = GetLastError();
1134 /* Only warn if setting timestamps failed. */
1135 WARNING("Can't set timestamps on \"%s\"", output_path);
1141 /* Replacement for POSIX fsync() */
1145 HANDLE h = (HANDLE)_get_osfhandle(fd);
1146 if (h == INVALID_HANDLE_VALUE) {
1147 ERROR("Could not get Windows handle for file descriptor");
1148 win32_error(GetLastError());
1152 if (!FlushFileBuffers(h)) {
1153 ERROR("Could not flush file buffers to disk");
1154 win32_error(GetLastError());
1161 /* Use the Win32 API to get the number of processors */
1163 win32_get_number_of_processors()
1165 SYSTEM_INFO sysinfo;
1166 GetSystemInfo(&sysinfo);
1167 return sysinfo.dwNumberOfProcessors;
1170 /* Replacement for POSIX-2008 realpath(). Warning: partial functionality only
1171 * (resolved_path must be NULL). Also I highly doubt that GetFullPathName
1172 * really does the right thing under all circumstances. */
1174 realpath(const mbchar *path, mbchar *resolved_path)
1177 wimlib_assert(resolved_path == NULL);
1179 ret = GetFullPathNameA(path, 0, NULL, NULL);
1183 resolved_path = MALLOC(ret + 1);
1186 ret = GetFullPathNameA(path, ret, resolved_path, NULL);
1188 free(resolved_path);
1191 return resolved_path;
1193 win32_error(GetLastError());
1199 nl_langinfo(nl_item item)
1201 wimlib_assert(item == CODESET);
1202 static char buf[64];
1203 strcpy(buf, "Unknown");