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 #ifdef ENABLE_ERROR_MESSAGES
49 win32_error(u32 err_code)
53 nchars = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
55 (char*)&buffer, 0, NULL);
57 ERROR("Error printing error message! "
58 "Computer will self-destruct in 3 seconds.");
60 ERROR("Win32 error: %s", buffer);
68 win32_error(GetLastError());
73 win32_open_file_readonly(const wchar_t *path, bool data_only)
75 DWORD dwDesiredAccess = FILE_READ_DATA;
77 dwDesiredAccess |= FILE_READ_ATTRIBUTES | READ_CONTROL | ACCESS_SYSTEM_SECURITY;
78 return CreateFileW(path,
81 NULL, /* lpSecurityAttributes */
83 FILE_FLAG_BACKUP_SEMANTICS |
84 FILE_FLAG_OPEN_REPARSE_POINT,
85 NULL /* hTemplateFile */);
89 win32_read_file(const mbchar *filename,
90 void *handle, u64 offset, size_t size, void *buf)
95 LARGE_INTEGER liOffset = {.QuadPart = offset};
97 wimlib_assert(size <= 0xffffffff);
99 if (SetFilePointerEx(h, liOffset, NULL, FILE_BEGIN))
100 if (ReadFile(h, buf, size, &bytesRead, NULL) && bytesRead == size)
102 err = GetLastError();
103 ERROR("Error reading \"%s\"", filename);
105 return WIMLIB_ERR_READ;
109 win32_close_file(void *handle)
111 CloseHandle((HANDLE)handle);
115 FILETIME_to_u64(const FILETIME *ft)
117 return ((u64)ft->dwHighDateTime << 32) | (u64)ft->dwLowDateTime;
121 win32_get_short_name(struct wim_dentry *dentry,
122 const wchar_t *path_utf16)
124 WIN32_FIND_DATAW dat;
125 if (FindFirstFileW(path_utf16, &dat) &&
126 dat.cAlternateFileName[0] != L'\0')
128 size_t short_name_nbytes = wcslen(dat.cAlternateFileName) * 2;
129 size_t n = short_name_nbytes + sizeof(wchar_t);
130 dentry->short_name = MALLOC(n);
131 if (!dentry->short_name)
132 return WIMLIB_ERR_NOMEM;
133 memcpy(dentry->short_name, dat.cAlternateFileName, n);
134 dentry->short_name_nbytes = short_name_nbytes;
140 win32_get_security_descriptor(struct wim_dentry *dentry,
141 struct sd_set *sd_set,
142 const wchar_t *path_utf16)
144 SECURITY_INFORMATION requestedInformation;
149 requestedInformation = DACL_SECURITY_INFORMATION |
150 SACL_SECURITY_INFORMATION |
151 OWNER_SECURITY_INFORMATION |
152 GROUP_SECURITY_INFORMATION;
153 /* Request length of security descriptor */
154 status = GetFileSecurityW(path_utf16, requestedInformation,
155 NULL, 0, &lenNeeded);
156 err = GetLastError();
157 if (!status && err == ERROR_INSUFFICIENT_BUFFER) {
158 DWORD len = lenNeeded;
160 if (GetFileSecurityW(path_utf16, requestedInformation,
161 (PSECURITY_DESCRIPTOR)buf, len, &lenNeeded))
163 int security_id = sd_set_add_sd(sd_set, buf, len);
165 return WIMLIB_ERR_NOMEM;
167 dentry->d_inode->i_security_id = security_id;
171 err = GetLastError();
174 ERROR("Win32 API: Failed to read security descriptor of \"%ls\"",
177 return WIMLIB_ERR_READ;
180 /* Reads the directory entries of directory using a Win32 API and recursively
181 * calls win32_build_dentry_tree() on them. */
183 win32_recurse_directory(struct wim_dentry *root,
184 const mbchar *root_disk_path,
185 struct wim_lookup_table *lookup_table,
186 struct wim_security_data *sd,
187 const struct capture_config *config,
189 wimlib_progress_func_t progress_func,
190 struct sd_set *sd_set,
191 const wchar_t *path_utf16,
192 size_t path_utf16_nchars)
194 WIN32_FIND_DATAW dat;
200 /* Begin reading the directory by calling FindFirstFileW.
201 * Unlike UNIX opendir(), FindFirstFileW has file globbing built
202 * into it. But this isn't what we actually want, so just add a
203 * dummy glob to get all entries. */
204 wchar_t pattern_buf[path_utf16_nchars + 3];
205 memcpy(pattern_buf, path_utf16,
206 path_utf16_nchars * sizeof(wchar_t));
207 pattern_buf[path_utf16_nchars] = L'/';
208 pattern_buf[path_utf16_nchars + 1] = L'*';
209 pattern_buf[path_utf16_nchars + 2] = L'\0';
210 hFind = FindFirstFileW(pattern_buf, &dat);
212 if (hFind == INVALID_HANDLE_VALUE) {
213 err = GetLastError();
214 if (err == ERROR_FILE_NOT_FOUND) {
217 ERROR("Win32 API: Failed to read directory \"%s\"",
220 return WIMLIB_ERR_READ;
225 /* Skip . and .. entries */
226 if (!(dat.cFileName[0] == L'.' &&
227 (dat.cFileName[1] == L'\0' ||
228 (dat.cFileName[1] == L'.' && dat.cFileName[2] == L'\0'))))
230 struct wim_dentry *child;
233 size_t mbs_name_nbytes;
234 ret = utf16le_to_mbs(dat.cFileName,
235 wcslen(dat.cFileName) * sizeof(wchar_t),
241 char name[strlen(root_disk_path) + 1 + mbs_name_nbytes + 1];
242 sprintf(name, "%s/%s", root_disk_path, mbs_name);
244 ret = win32_build_dentry_tree(&child, name, lookup_table,
245 sd, config, add_image_flags,
246 progress_func, sd_set);
250 dentry_add_child(root, child);
252 } while (FindNextFileW(hFind, &dat));
253 err = GetLastError();
254 if (err != ERROR_NO_MORE_FILES) {
255 ERROR("Win32 API: Failed to read directory \"%s\"", root_disk_path);
258 ret = WIMLIB_ERR_READ;
265 /* Load a reparse point into a WIM inode. It is just stored in memory.
267 * @hFile: Open handle to a reparse point, with permission to read the reparse
270 * @inode: WIM inode for the reparse point.
272 * @lookup_table: Stream lookup table for the WIM; an entry will be added to it
273 * for the reparse point unless an entry already exists for
274 * the exact same data stream.
276 * @path: External path to the parse point (UTF-8). Used for error messages
279 * Returns 0 on success; nonzero on failure. */
281 win32_capture_reparse_point(HANDLE hFile,
282 struct wim_inode *inode,
283 struct wim_lookup_table *lookup_table,
286 /* "Reparse point data, including the tag and optional GUID,
287 * cannot exceed 16 kilobytes." - MSDN */
288 char reparse_point_buf[16 * 1024];
291 if (!DeviceIoControl(hFile, FSCTL_GET_REPARSE_POINT,
292 NULL, 0, reparse_point_buf,
293 sizeof(reparse_point_buf), &bytesReturned, NULL))
295 DWORD err = GetLastError();
296 ERROR("Win32 API: Failed to get reparse data of \"%s\"", path);
298 return WIMLIB_ERR_READ;
300 if (bytesReturned < 8) {
301 ERROR("Reparse data on \"%s\" is invalid", path);
302 return WIMLIB_ERR_READ;
304 inode->i_reparse_tag = le32_to_cpu(*(u32*)reparse_point_buf);
305 return inode_add_ads_with_data(inode, "",
306 (const u8*)reparse_point_buf + 8,
307 bytesReturned - 8, lookup_table);
310 /* Calculate the SHA1 message digest of a Win32 data stream, which may be either
311 * an unnamed or named data stream.
313 * @path: Path to the file, with the stream noted at the end for named
314 * streams. UTF-16LE encoding.
316 * @hash: On success, the SHA1 message digest of the stream is written to
319 * Returns 0 on success; nonzero on failure.
322 win32_sha1sum(const wchar_t *path, u8 hash[SHA1_HASH_SIZE])
330 hFile = win32_open_file_readonly(path, false);
331 if (hFile == INVALID_HANDLE_VALUE)
332 return WIMLIB_ERR_OPEN;
336 if (!ReadFile(hFile, buf, sizeof(buf), &bytesRead, NULL)) {
337 ret = WIMLIB_ERR_READ;
338 goto out_close_handle;
342 sha1_update(&ctx, buf, bytesRead);
345 sha1_final(hash, &ctx);
351 /* Scans an unnamed or named stream of a Win32 file (not a reparse point
352 * stream); calculates its SHA1 message digest and either creates a `struct
353 * wim_lookup_table_entry' in memory for it, or uses an existing 'struct
354 * wim_lookup_table_entry' for an identical stream.
356 * @path_utf16: Path to the file (UTF-16LE).
358 * @path_utf16_nchars: Number of 2-byte characters in @path_utf16.
360 * @inode: WIM inode to save the stream into.
362 * @lookup_table: Stream lookup table for the WIM.
364 * @dat: A `WIN32_FIND_STREAM_DATA' structure that specifies the
367 * Returns 0 on success; nonzero on failure.
370 win32_capture_stream(const wchar_t *path_utf16,
371 size_t path_utf16_nchars,
372 struct wim_inode *inode,
373 struct wim_lookup_table *lookup_table,
374 WIN32_FIND_STREAM_DATA *dat)
376 struct wim_ads_entry *ads_entry;
377 u8 hash[SHA1_HASH_SIZE];
378 struct wim_lookup_table_entry *lte;
381 bool is_named_stream;
386 /* The stream name should be returned as :NAME:TYPE */
387 p = dat->cStreamName;
389 goto out_invalid_stream_name;
391 colon = wcschr(p, L':');
393 goto out_invalid_stream_name;
395 if (wcscmp(colon + 1, L"$DATA")) {
396 /* Not a DATA stream */
401 is_named_stream = (p != colon);
402 if (is_named_stream) {
403 /* Allocate an ADS entry for the named stream. */
404 char *mbs_stream_name;
405 size_t mbs_stream_name_nbytes;
406 ret = utf16le_to_mbs(p,
407 (colon - p) * sizeof(wchar_t),
409 &mbs_stream_name_nbytes);
412 ads_entry = inode_add_ads(inode, mbs_stream_name);
413 FREE(mbs_stream_name);
415 ret = WIMLIB_ERR_NOMEM;
420 /* Create a UTF-16 string @spath that gives the filename, then a colon,
421 * then the stream name. Or, if it's an unnamed stream, just the
422 * filename. It is MALLOC()'ed so that it can be saved in the
423 * wim_lookup_table_entry if needed. */
425 spath_nchars = path_utf16_nchars;
427 spath_nchars += colon - p + 1;
429 spath = MALLOC((spath_nchars + 1) * sizeof(wchar_t));
430 memcpy(spath, path_utf16, path_utf16_nchars * sizeof(wchar_t));
431 if (is_named_stream) {
432 spath[path_utf16_nchars] = L':';
433 memcpy(&spath[path_utf16_nchars + 1], p, (colon - p) * sizeof(wchar_t));
435 spath[spath_nchars] = L'\0';
437 ret = win32_sha1sum(spath, hash);
439 err = GetLastError();
440 ERROR("Win32 API: Failed to read \"%ls\" to calculate SHA1sum",
446 lte = __lookup_resource(lookup_table, hash);
448 /* Use existing wim_lookup_table_entry that has the same SHA1
452 /* Make a new wim_lookup_table_entry */
453 lte = new_lookup_table_entry();
455 ret = WIMLIB_ERR_NOMEM;
458 lte->win32_file_on_disk = spath;
459 lte->file_on_disk_fp = INVALID_HANDLE_VALUE;
461 lte->resource_location = RESOURCE_WIN32;
462 lte->resource_entry.original_size = (uint64_t)dat->StreamSize.QuadPart;
463 lte->resource_entry.size = (uint64_t)dat->StreamSize.QuadPart;
464 copy_hash(lte->hash, hash);
465 lookup_table_insert(lookup_table, lte);
468 ads_entry->lte = lte;
475 out_invalid_stream_name:
476 ERROR("Invalid stream name: \"%ls:%ls\"", path_utf16, dat->cStreamName);
477 ret = WIMLIB_ERR_READ;
481 /* Scans a Win32 file for unnamed and named data streams (not reparse point
484 * @path_utf16: Path to the file (UTF-16LE).
486 * @path_utf16_nchars: Number of 2-byte characters in @path_utf16.
488 * @inode: WIM inode to save the stream into.
490 * @lookup_table: Stream lookup table for the WIM.
492 * Returns 0 on success; nonzero on failure.
495 win32_capture_streams(const wchar_t *path_utf16,
496 size_t path_utf16_nchars,
497 struct wim_inode *inode,
498 struct wim_lookup_table *lookup_table)
500 WIN32_FIND_STREAM_DATA dat;
505 hFind = FindFirstStreamW(path_utf16, FindStreamInfoStandard, &dat, 0);
506 if (hFind == INVALID_HANDLE_VALUE) {
507 err = GetLastError();
509 /* Seems legal for this to return ERROR_HANDLE_EOF on reparse
510 * points and directories */
511 if ((inode->i_attributes &
512 (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
513 && err == ERROR_HANDLE_EOF)
517 ERROR("Win32 API: Failed to look up data streams of \"%ls\"",
520 return WIMLIB_ERR_READ;
524 ret = win32_capture_stream(path_utf16,
530 } while (FindNextStreamW(hFind, &dat));
531 err = GetLastError();
532 if (err != ERROR_HANDLE_EOF) {
533 ERROR("Win32 API: Error reading data streams from \"%ls\"", path_utf16);
535 ret = WIMLIB_ERR_READ;
542 /* Win32 version of capturing a directory tree */
544 win32_build_dentry_tree(struct wim_dentry **root_ret,
545 const char *root_disk_path,
546 struct wim_lookup_table *lookup_table,
547 struct wim_security_data *sd,
548 const struct capture_config *config,
550 wimlib_progress_func_t progress_func,
553 struct wim_dentry *root = NULL;
555 struct wim_inode *inode;
558 size_t path_utf16_nbytes;
559 size_t path_utf16_nchars;
560 struct sd_set *sd_set;
563 if (exclude_path(root_disk_path, config, true)) {
564 if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT) {
565 ERROR("Cannot exclude the root directory from capture");
566 ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
569 if ((add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
572 union wimlib_progress_info info;
573 info.scan.cur_path = root_disk_path;
574 info.scan.excluded = true;
575 progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
580 if ((add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
583 union wimlib_progress_info info;
584 info.scan.cur_path = root_disk_path;
585 info.scan.excluded = false;
586 progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
589 if (extra_arg == NULL) {
590 sd_set = alloca(sizeof(struct sd_set));
591 sd_set->rb_root.rb_node = NULL,
597 ret = mbs_to_utf16le(root_disk_path, strlen(root_disk_path),
598 &path_utf16, &path_utf16_nbytes);
600 goto out_destroy_sd_set;
601 path_utf16_nchars = path_utf16_nbytes / sizeof(wchar_t);
603 HANDLE hFile = win32_open_file_readonly(path_utf16, false);
604 if (hFile == INVALID_HANDLE_VALUE) {
605 err = GetLastError();
606 ERROR("Win32 API: Failed to open \"%s\"", root_disk_path);
608 ret = WIMLIB_ERR_OPEN;
609 goto out_free_path_utf16;
612 BY_HANDLE_FILE_INFORMATION file_info;
613 if (!GetFileInformationByHandle(hFile, &file_info)) {
614 err = GetLastError();
615 ERROR("Win32 API: Failed to get file information for \"%s\"",
618 ret = WIMLIB_ERR_STAT;
619 goto out_close_handle;
622 /* Create a WIM dentry */
623 ret = new_dentry_with_timeless_inode(path_basename(root_disk_path), &root);
625 goto out_close_handle;
627 /* Start preparing the associated WIM inode */
628 inode = root->d_inode;
630 inode->i_attributes = file_info.dwFileAttributes;
631 inode->i_creation_time = FILETIME_to_u64(&file_info.ftCreationTime);
632 inode->i_last_write_time = FILETIME_to_u64(&file_info.ftLastWriteTime);
633 inode->i_last_access_time = FILETIME_to_u64(&file_info.ftLastAccessTime);
634 inode->i_ino = ((u64)file_info.nFileIndexHigh << 32) |
635 (u64)file_info.nFileIndexLow;
637 inode->i_resolved = 1;
638 add_image_flags &= ~(WIMLIB_ADD_IMAGE_FLAG_ROOT | WIMLIB_ADD_IMAGE_FLAG_SOURCE);
640 /* Get DOS name and security descriptor (if any). */
641 ret = win32_get_short_name(root, path_utf16);
643 goto out_close_handle;
644 ret = win32_get_security_descriptor(root, sd_set, path_utf16);
646 goto out_close_handle;
648 if (inode_is_directory(inode)) {
649 /* Directory (not a reparse point) --- recurse to children */
651 /* But first... directories may have alternate data streams that
652 * need to be captured. */
653 ret = win32_capture_streams(path_utf16,
658 goto out_close_handle;
659 ret = win32_recurse_directory(root,
669 } else if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
670 /* Reparse point: save the reparse tag and data */
671 ret = win32_capture_reparse_point(hFile,
676 /* Not a directory, not a reparse point; capture the default
677 * file contents and any alternate data streams. */
678 ret = win32_capture_streams(path_utf16,
688 if (extra_arg == NULL)
689 destroy_sd_set(sd_set);
694 free_dentry_tree(root, lookup_table);
698 /* Replacement for POSIX fnmatch() (partial functionality only) */
700 fnmatch(const char *pattern, const char *string, int flags)
702 if (PathMatchSpecA(string, pattern))
709 win32_set_reparse_data(HANDLE h,
711 const struct wim_lookup_table_entry *lte,
719 WARNING("\"%ls\" is marked as a reparse point but had no reparse data",
723 len = wim_resource_size(lte);
724 if (len > 16 * 1024 - 8) {
725 WARNING("\"%ls\": reparse data too long!", path);
729 /* The WIM stream omits the ReparseTag and ReparseDataLength fields, so
730 * leave 8 bytes of space for them at the beginning of the buffer, then
731 * set them manually. */
732 buf = alloca(len + 8);
733 ret = read_full_wim_resource(lte, buf + 8, 0);
736 *(u32*)(buf + 0) = cpu_to_le32(reparse_tag);
737 *(u16*)(buf + 4) = cpu_to_le16(len);
738 *(u16*)(buf + 6) = 0;
740 /* Set the reparse data on the open file using the
741 * FSCTL_SET_REPARSE_POINT ioctl.
743 * There are contradictions in Microsoft's documentation for this:
745 * "If hDevice was opened without specifying FILE_FLAG_OVERLAPPED,
746 * lpOverlapped is ignored."
748 * --- So setting lpOverlapped to NULL is okay since it's ignored.
750 * "If lpOverlapped is NULL, lpBytesReturned cannot be NULL. Even when an
751 * operation returns no output data and lpOutBuffer is NULL,
752 * DeviceIoControl makes use of lpBytesReturned. After such an
753 * operation, the value of lpBytesReturned is meaningless."
755 * --- So lpOverlapped not really ignored, as it affects another
756 * parameter. This is the actual behavior: lpBytesReturned must be
757 * specified, even though lpBytesReturned is documented as:
759 * "Not used with this operation; set to NULL."
762 if (!DeviceIoControl(h, FSCTL_SET_REPARSE_POINT, buf, len + 8,
764 &bytesReturned /* lpBytesReturned */,
765 NULL /* lpOverlapped */))
767 DWORD err = GetLastError();
768 ERROR("Failed to set reparse data on \"%ls\"", path);
770 return WIMLIB_ERR_WRITE;
777 win32_extract_chunk(const void *buf, size_t len, u64 offset, void *arg)
779 HANDLE hStream = arg;
781 DWORD nbytes_written;
782 wimlib_assert(len <= 0xffffffff);
784 if (!WriteFile(hStream, buf, len, &nbytes_written, NULL) ||
785 nbytes_written != len)
787 DWORD err = GetLastError();
788 ERROR("WriteFile(): write error");
790 return WIMLIB_ERR_WRITE;
796 do_win32_extract_stream(HANDLE hStream, struct wim_lookup_table_entry *lte)
798 return extract_wim_resource(lte, wim_resource_size(lte),
799 win32_extract_chunk, hStream);
803 win32_extract_stream(const struct wim_inode *inode,
805 const wchar_t *stream_name_utf16,
806 struct wim_lookup_table_entry *lte)
808 wchar_t *stream_path;
812 DWORD creationDisposition = CREATE_ALWAYS;
814 if (stream_name_utf16) {
815 /* Named stream. Create a buffer that contains the UTF-16LE
816 * string [./]@path:@stream_name_utf16. This is needed to
817 * create and open the stream using CreateFileW(). I'm not
818 * aware of any other APIs to do this. Note: the '$DATA' suffix
819 * seems to be unneeded. Additional note: a "./" prefix needs
820 * to be added when the path is not absolute to avoid ambiguity
821 * with drive letters. */
822 size_t stream_path_nchars;
824 size_t stream_name_nchars;
825 const wchar_t *prefix;
827 path_nchars = wcslen(path);
828 stream_name_nchars = wcslen(stream_name_utf16);
829 stream_path_nchars = path_nchars + 1 + stream_name_nchars;
830 if (path[0] != L'/' && path[0] != L'\\') {
832 stream_path_nchars += 2;
836 stream_path = alloca((stream_path_nchars + 1) * sizeof(wchar_t));
837 swprintf(stream_path, stream_path_nchars + 1, L"%ls%ls:%ls",
838 prefix, path, stream_name_utf16);
840 /* Unnamed stream; its path is just the path to the file itself.
842 stream_path = (wchar_t*)path;
844 /* Directories must be created with CreateDirectoryW(). Then
845 * the call to CreateFileW() will merely open the directory that
846 * was already created rather than creating a new file. */
847 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
848 if (!CreateDirectoryW(stream_path, NULL)) {
849 err = GetLastError();
850 if (err != ERROR_ALREADY_EXISTS) {
851 ERROR("Failed to create directory \"%ls\"",
854 ret = WIMLIB_ERR_MKDIR;
858 DEBUG("Created directory \"%ls\"", stream_path);
859 if (!(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
863 creationDisposition = OPEN_EXISTING;
867 DEBUG("Opening \"%ls\"", stream_path);
868 h = CreateFileW(stream_path,
869 GENERIC_WRITE | WRITE_OWNER | WRITE_DAC | ACCESS_SYSTEM_SECURITY,
873 FILE_FLAG_OPEN_REPARSE_POINT |
874 FILE_FLAG_BACKUP_SEMANTICS |
877 if (h == INVALID_HANDLE_VALUE) {
878 err = GetLastError();
879 ERROR("Failed to create \"%ls\"", stream_path);
881 ret = WIMLIB_ERR_OPEN;
885 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT &&
886 stream_name_utf16 == NULL)
888 DEBUG("Setting reparse data on \"%ls\"", path);
889 ret = win32_set_reparse_data(h, inode->i_reparse_tag, lte, path);
891 goto fail_close_handle;
894 DEBUG("Extracting \"%ls\" (len = %"PRIu64")",
895 stream_path, wim_resource_size(lte));
896 ret = do_win32_extract_stream(h, lte);
898 goto fail_close_handle;
902 DEBUG("Closing \"%ls\"", stream_path);
903 if (!CloseHandle(h)) {
904 err = GetLastError();
905 ERROR("Failed to close \"%ls\"", stream_path);
907 ret = WIMLIB_ERR_WRITE;
915 ERROR("Error extracting %ls", stream_path);
921 * Creates a file, directory, or reparse point and extracts all streams to it
922 * (unnamed data stream and/or reparse point stream, plus any alternate data
923 * streams). This in Win32-specific code.
925 * @inode: WIM inode for this file or directory.
926 * @path: UTF-16LE external path to extract the inode to.
928 * Returns 0 on success; nonzero on failure.
931 win32_extract_streams(const struct wim_inode *inode,
932 const wchar_t *path, u64 *completed_bytes_p)
934 struct wim_lookup_table_entry *unnamed_lte;
937 unnamed_lte = inode_unnamed_lte_resolved(inode);
938 ret = win32_extract_stream(inode, path, NULL, unnamed_lte);
942 *completed_bytes_p += wim_resource_size(unnamed_lte);
943 for (u16 i = 0; i < inode->i_num_ads; i++) {
944 const struct wim_ads_entry *ads_entry = &inode->i_ads_entries[i];
945 if (ads_entry->stream_name_nbytes != 0) {
946 /* Skip special UNIX data entries (see documentation for
947 * WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA) */
948 if (ads_entry->stream_name_nbytes == WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES
949 && !memcmp(ads_entry->stream_name,
950 WIMLIB_UNIX_DATA_TAG_UTF16LE,
951 WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES))
953 ret = win32_extract_stream(inode,
955 ads_entry->stream_name,
960 *completed_bytes_p += wim_resource_size(ads_entry->lte);
968 * Sets the security descriptor on an extracted file. This is Win32-specific
971 * @inode: The WIM inode that was extracted and has a security descriptor.
972 * @path: UTF-16LE external path that the inode was extracted to.
973 * @sd: Security data for the WIM image.
975 * Returns 0 on success; nonzero on failure.
977 static int win32_set_security_data(const struct wim_inode *inode,
979 const struct wim_security_data *sd)
981 SECURITY_INFORMATION securityInformation = DACL_SECURITY_INFORMATION |
982 SACL_SECURITY_INFORMATION |
983 OWNER_SECURITY_INFORMATION |
984 GROUP_SECURITY_INFORMATION;
985 if (!SetFileSecurityW(path, securityInformation,
986 (PSECURITY_DESCRIPTOR)sd->descriptors[inode->i_security_id]))
988 DWORD err = GetLastError();
989 ERROR("Can't set security descriptor on \"%ls\"", path);
991 return WIMLIB_ERR_WRITE;
996 /* Extract a file, directory, reparse point, or hard link to an
997 * already-extracted file using the Win32 API */
998 int win32_do_apply_dentry(const mbchar *output_path,
999 size_t output_path_nbytes,
1000 struct wim_dentry *dentry,
1001 struct apply_args *args)
1003 wchar_t *utf16le_path;
1004 size_t utf16le_path_nbytes;
1007 struct wim_inode *inode = dentry->d_inode;
1009 ret = mbs_to_utf16le(output_path, output_path_nbytes,
1010 &utf16le_path, &utf16le_path_nbytes);
1014 if (inode->i_nlink > 1 && inode->i_extracted_file != NULL) {
1015 /* Linked file, with another name already extracted. Create a
1017 DEBUG("Creating hard link \"%ls => %ls\"",
1018 utf16le_path, inode->i_extracted_file);
1019 if (!CreateHardLinkW(utf16le_path, inode->i_extracted_file, NULL))
1021 err = GetLastError();
1022 ERROR("Can't create hard link \"%ls => %ls\"",
1023 utf16le_path, inode->i_extracted_file);
1024 ret = WIMLIB_ERR_LINK;
1028 /* Create the file, directory, or reparse point, and extract the
1030 ret = win32_extract_streams(inode, utf16le_path,
1031 &args->progress.extract.completed_bytes);
1033 goto out_free_utf16_path;
1035 /* Set security descriptor if present */
1036 if (inode->i_security_id != -1) {
1037 DEBUG("Setting security descriptor %d on %s",
1038 inode->i_security_id, output_path);
1039 ret = win32_set_security_data(inode,
1041 wim_const_security_data(args->w));
1043 goto out_free_utf16_path;
1045 if (inode->i_nlink > 1) {
1046 /* Save extracted path for a later call to
1047 * CreateHardLinkW() if this inode has multiple links.
1049 inode->i_extracted_file = utf16le_path;
1053 out_free_utf16_path:
1059 /* Set timestamps on an extracted file using the Win32 API */
1061 win32_do_apply_dentry_timestamps(const mbchar *output_path,
1062 size_t output_path_nbytes,
1063 const struct wim_dentry *dentry,
1064 const struct apply_args *args)
1067 wchar_t *utf16le_path;
1068 size_t utf16le_path_nbytes;
1072 const struct wim_inode *inode = dentry->d_inode;
1074 ret = mbs_to_utf16le(output_path, output_path_nbytes,
1075 &utf16le_path, &utf16le_path_nbytes);
1079 DEBUG("Opening \"%s\" to set timestamps", output_path);
1080 h = CreateFileW(utf16le_path,
1081 GENERIC_WRITE | WRITE_OWNER | WRITE_DAC | ACCESS_SYSTEM_SECURITY,
1085 FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
1088 if (h == INVALID_HANDLE_VALUE)
1089 err = GetLastError();
1091 if (h == INVALID_HANDLE_VALUE)
1094 FILETIME creationTime = {.dwLowDateTime = inode->i_creation_time & 0xffffffff,
1095 .dwHighDateTime = inode->i_creation_time >> 32};
1096 FILETIME lastAccessTime = {.dwLowDateTime = inode->i_last_access_time & 0xffffffff,
1097 .dwHighDateTime = inode->i_last_access_time >> 32};
1098 FILETIME lastWriteTime = {.dwLowDateTime = inode->i_last_write_time & 0xffffffff,
1099 .dwHighDateTime = inode->i_last_write_time >> 32};
1101 DEBUG("Calling SetFileTime() on \"%s\"", output_path);
1102 if (!SetFileTime(h, &creationTime, &lastAccessTime, &lastWriteTime)) {
1103 err = GetLastError();
1107 DEBUG("Closing \"%s\"", output_path);
1108 if (!CloseHandle(h)) {
1109 err = GetLastError();
1114 /* Only warn if setting timestamps failed. */
1115 WARNING("Can't set timestamps on \"%s\"", output_path);
1121 /* Replacement for POSIX fsync() */
1125 HANDLE h = (HANDLE)_get_osfhandle(fd);
1126 if (h == INVALID_HANDLE_VALUE) {
1127 ERROR("Could not get Windows handle for file descriptor");
1128 win32_error(GetLastError());
1132 if (!FlushFileBuffers(h)) {
1133 ERROR("Could not flush file buffers to disk");
1134 win32_error(GetLastError());
1141 /* Use the Win32 API to get the number of processors */
1143 win32_get_number_of_processors()
1145 SYSTEM_INFO sysinfo;
1146 GetSystemInfo(&sysinfo);
1147 return sysinfo.dwNumberOfProcessors;
1150 /* Replacement for POSIX-2008 realpath(). Warning: partial functionality only
1151 * (resolved_path must be NULL). Also I highly doubt that GetFullPathName
1152 * really does the right thing under all circumstances. */
1154 realpath(const mbchar *path, mbchar *resolved_path)
1157 wimlib_assert(resolved_path == NULL);
1159 ret = GetFullPathNameA(path, 0, NULL, NULL);
1163 resolved_path = MALLOC(ret + 1);
1166 ret = GetFullPathNameA(path, ret, resolved_path, NULL);
1168 free(resolved_path);
1171 return resolved_path;
1173 win32_error(GetLastError());
1179 nl_langinfo(nl_item item)
1181 wimlib_assert(item == CODESET);
1182 static char buf[64];
1183 strcpy(buf, "Unknown");