]> wimlib.net Git - wimlib/blob - src/win32.c
Win32 updates
[wimlib] / src / win32.c
1 /*
2  * win32.c
3  *
4  * All the library code specific to native Windows builds is in here.
5  */
6
7 /*
8  * Copyright (C) 2013 Eric Biggers
9  *
10  * This file is part of wimlib, a library for working with WIM files.
11  *
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)
15  * any later version.
16  *
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
20  * details.
21  *
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/.
24  */
25
26 #ifndef __WIN32__
27 #  error "This file contains Windows code"
28 #endif
29
30 #include "config.h"
31 #include <windows.h>
32 #include <ntdef.h>
33 #include <wchar.h>
34 #include <shlwapi.h> /* shlwapi.h for PathMatchSpecW() */
35 #ifdef ERROR /* windows.h defines this */
36 #  undef ERROR
37 #endif
38
39 #include "win32.h"
40 #include "dentry.h"
41 #include "lookup_table.h"
42 #include "security.h"
43 #include "endianness.h"
44
45 #include <errno.h>
46
47 #define MAX_GET_SD_ACCESS_DENIED_WARNINGS 1
48 #define MAX_GET_SACL_PRIV_NOTHELD_WARNINGS 1
49 struct win32_capture_state {
50         unsigned long num_get_sd_access_denied;
51         unsigned long num_get_sacl_priv_notheld;
52 };
53
54 #define MAX_SET_SD_ACCESS_DENIED_WARNINGS 1
55 #define MAX_SET_SACL_PRIV_NOTHELD_WARNINGS 1
56
57 /* Pointers to functions that are not available on all targetted versions of
58  * Windows (XP and later).  NOTE: The WINAPI annotations seem to be important; I
59  * assume it specifies a certain calling convention. */
60
61 /* Vista and later */
62 static HANDLE (WINAPI *win32func_FindFirstStreamW)(LPCWSTR lpFileName,
63                                             STREAM_INFO_LEVELS InfoLevel,
64                                             LPVOID lpFindStreamData,
65                                             DWORD dwFlags) = NULL;
66
67 /* Vista and later */
68 static BOOL (WINAPI *win32func_FindNextStreamW)(HANDLE hFindStream,
69                                          LPVOID lpFindStreamData) = NULL;
70
71 static HMODULE hKernel32 = NULL;
72
73 /* Try to dynamically load some functions */
74 void
75 win32_global_init()
76 {
77         DWORD err;
78
79         if (hKernel32 == NULL) {
80                 DEBUG("Loading Kernel32.dll");
81                 hKernel32 = LoadLibraryW(L"Kernel32.dll");
82                 if (hKernel32 == NULL) {
83                         err = GetLastError();
84                         WARNING("Can't load Kernel32.dll");
85                         win32_error(err);
86                         return;
87                 }
88         }
89
90         DEBUG("Looking for FindFirstStreamW");
91         win32func_FindFirstStreamW = (void*)GetProcAddress(hKernel32, "FindFirstStreamW");
92         if (!win32func_FindFirstStreamW) {
93                 WARNING("Could not find function FindFirstStreamW() in Kernel32.dll!");
94                 WARNING("Capturing alternate data streams will not be supported.");
95                 return;
96         }
97
98         DEBUG("Looking for FindNextStreamW");
99         win32func_FindNextStreamW = (void*)GetProcAddress(hKernel32, "FindNextStreamW");
100         if (!win32func_FindNextStreamW) {
101                 WARNING("Could not find function FindNextStreamW() in Kernel32.dll!");
102                 WARNING("Capturing alternate data streams will not be supported.");
103                 win32func_FindFirstStreamW = NULL;
104         }
105 }
106
107 void
108 win32_global_cleanup()
109 {
110         if (hKernel32 != NULL) {
111                 DEBUG("Closing Kernel32.dll");
112                 FreeLibrary(hKernel32);
113                 hKernel32 = NULL;
114         }
115 }
116
117 static const wchar_t *capture_access_denied_msg =
118 L"         If you are not running this program as the administrator, you may\n"
119  "         need to do so, so that all data and metadata can be backed up.\n"
120  "         Otherwise, there may be no way to access the desired data or\n"
121  "         metadata without taking ownership of the file or directory.\n"
122  ;
123
124 static const wchar_t *apply_access_denied_msg =
125 L"If you are not running this program as the administrator, you may\n"
126  "          need to do so, so that all data and metadata can be extracted\n"
127  "          exactly as the origignal copy.  However, if you do not care that\n"
128  "          the security descriptors are extracted correctly, you could run\n"
129  "          `wimlib-imagex apply' with the --no-acls flag instead.\n"
130  ;
131
132 #ifdef ENABLE_ERROR_MESSAGES
133 void
134 win32_error(u32 err_code)
135 {
136         wchar_t *buffer;
137         DWORD nchars;
138         nchars = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
139                                     FORMAT_MESSAGE_ALLOCATE_BUFFER,
140                                 NULL, err_code, 0,
141                                 (wchar_t*)&buffer, 0, NULL);
142         if (nchars == 0) {
143                 ERROR("Error printing error message! "
144                       "Computer will self-destruct in 3 seconds.");
145         } else {
146                 ERROR("Win32 error: %ls", buffer);
147                 LocalFree(buffer);
148         }
149 }
150
151 void
152 win32_error_last()
153 {
154         win32_error(GetLastError());
155 }
156 #endif
157
158 static HANDLE
159 win32_open_existing_file(const wchar_t *path, DWORD dwDesiredAccess)
160 {
161         return CreateFileW(path,
162                            dwDesiredAccess,
163                            FILE_SHARE_READ,
164                            NULL, /* lpSecurityAttributes */
165                            OPEN_EXISTING,
166                            FILE_FLAG_BACKUP_SEMANTICS |
167                                FILE_FLAG_OPEN_REPARSE_POINT,
168                            NULL /* hTemplateFile */);
169 }
170
171 HANDLE
172 win32_open_file_data_only(const wchar_t *path)
173 {
174         return win32_open_existing_file(path, FILE_READ_DATA);
175 }
176
177 int
178 win32_read_file(const wchar_t *filename,
179                 void *handle, u64 offset, size_t size, void *buf)
180 {
181         HANDLE h = handle;
182         DWORD err;
183         DWORD bytesRead;
184         LARGE_INTEGER liOffset = {.QuadPart = offset};
185
186         wimlib_assert(size <= 0xffffffff);
187
188         if (SetFilePointerEx(h, liOffset, NULL, FILE_BEGIN))
189                 if (ReadFile(h, buf, size, &bytesRead, NULL) && bytesRead == size)
190                         return 0;
191         err = GetLastError();
192         ERROR("Error reading \"%ls\"", filename);
193         win32_error(err);
194         return WIMLIB_ERR_READ;
195 }
196
197 void
198 win32_close_file(void *handle)
199 {
200         CloseHandle((HANDLE)handle);
201 }
202
203 static u64
204 FILETIME_to_u64(const FILETIME *ft)
205 {
206         return ((u64)ft->dwHighDateTime << 32) | (u64)ft->dwLowDateTime;
207 }
208
209 static int
210 win32_get_short_name(struct wim_dentry *dentry, const wchar_t *path)
211 {
212         WIN32_FIND_DATAW dat;
213         if (FindFirstFileW(path, &dat) && dat.cAlternateFileName[0] != L'\0') {
214                 size_t short_name_nbytes = wcslen(dat.cAlternateFileName) *
215                                            sizeof(wchar_t);
216                 size_t n = short_name_nbytes + sizeof(wchar_t);
217                 dentry->short_name = MALLOC(n);
218                 if (!dentry->short_name)
219                         return WIMLIB_ERR_NOMEM;
220                 memcpy(dentry->short_name, dat.cAlternateFileName, n);
221                 dentry->short_name_nbytes = short_name_nbytes;
222         }
223         return 0;
224 }
225
226 static int
227 win32_get_security_descriptor(struct wim_dentry *dentry,
228                               struct sd_set *sd_set,
229                               const wchar_t *path,
230                               struct win32_capture_state *state,
231                               int add_image_flags)
232 {
233         SECURITY_INFORMATION requestedInformation;
234         DWORD lenNeeded = 0;
235         BOOL status;
236         DWORD err;
237         unsigned long n;
238
239         requestedInformation = DACL_SECURITY_INFORMATION |
240                                SACL_SECURITY_INFORMATION |
241                                OWNER_SECURITY_INFORMATION |
242                                GROUP_SECURITY_INFORMATION;
243 again:
244         /* Request length of security descriptor */
245         status = GetFileSecurityW(path, requestedInformation,
246                                   NULL, 0, &lenNeeded);
247         err = GetLastError();
248         if (!status && err == ERROR_INSUFFICIENT_BUFFER) {
249                 DWORD len = lenNeeded;
250                 char buf[len];
251                 if (GetFileSecurityW(path, requestedInformation,
252                                      (PSECURITY_DESCRIPTOR)buf, len, &lenNeeded))
253                 {
254                         int security_id = sd_set_add_sd(sd_set, buf, len);
255                         if (security_id < 0)
256                                 return WIMLIB_ERR_NOMEM;
257                         else {
258                                 dentry->d_inode->i_security_id = security_id;
259                                 return 0;
260                         }
261                 } else {
262                         err = GetLastError();
263                 }
264         }
265
266         if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_STRICT_ACLS)
267                 goto fail;
268
269         switch (err) {
270         case ERROR_PRIVILEGE_NOT_HELD:
271                 if (requestedInformation & SACL_SECURITY_INFORMATION) {
272                         n = state->num_get_sacl_priv_notheld++;
273                         requestedInformation &= ~SACL_SECURITY_INFORMATION;
274                         if (n < MAX_GET_SACL_PRIV_NOTHELD_WARNINGS) {
275                                 WARNING(
276 "We don't have enough privileges to read the full security\n"
277 "          descriptor of \"%ls\"!\n"
278 "          Re-trying with SACL omitted.\n", path);
279                         } else if (n == MAX_GET_SACL_PRIV_NOTHELD_WARNINGS) {
280                                 WARNING(
281 "Suppressing further privileges not held error messages when reading\n"
282 "          security descriptors.");
283                         }
284                         goto again;
285                 }
286                 /* Fall through */
287         case ERROR_ACCESS_DENIED:
288                 n = state->num_get_sd_access_denied++;
289                 if (n < MAX_GET_SD_ACCESS_DENIED_WARNINGS) {
290                         WARNING("Failed to read security descriptor of \"%ls\": "
291                                 "Access denied!\n%ls", path, capture_access_denied_msg);
292                 } else if (n == MAX_GET_SD_ACCESS_DENIED_WARNINGS) {
293                         WARNING("Suppressing further access denied errors messages i"
294                                 "when reading security descriptors");
295                 }
296                 return 0;
297         default:
298 fail:
299                 ERROR("Failed to read security descriptor of \"%ls\"", path);
300                 win32_error(err);
301                 return WIMLIB_ERR_READ;
302         }
303 }
304
305 static int
306 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
307                                   wchar_t *path,
308                                   size_t path_num_chars,
309                                   struct wim_lookup_table *lookup_table,
310                                   struct sd_set *sd_set,
311                                   const struct capture_config *config,
312                                   int add_image_flags,
313                                   wimlib_progress_func_t progress_func,
314                                   struct win32_capture_state *state);
315
316 /* Reads the directory entries of directory using a Win32 API and recursively
317  * calls win32_build_dentry_tree() on them. */
318 static int
319 win32_recurse_directory(struct wim_dentry *root,
320                         wchar_t *dir_path,
321                         size_t dir_path_num_chars,
322                         struct wim_lookup_table *lookup_table,
323                         struct sd_set *sd_set,
324                         const struct capture_config *config,
325                         int add_image_flags,
326                         wimlib_progress_func_t progress_func,
327                         struct win32_capture_state *state)
328 {
329         WIN32_FIND_DATAW dat;
330         HANDLE hFind;
331         DWORD err;
332         int ret;
333
334         /* Begin reading the directory by calling FindFirstFileW.  Unlike UNIX
335          * opendir(), FindFirstFileW has file globbing built into it.  But this
336          * isn't what we actually want, so just add a dummy glob to get all
337          * entries. */
338         dir_path[dir_path_num_chars] = L'/';
339         dir_path[dir_path_num_chars + 1] = L'*';
340         dir_path[dir_path_num_chars + 2] = L'\0';
341         hFind = FindFirstFileW(dir_path, &dat);
342         dir_path[dir_path_num_chars] = L'\0';
343
344         if (hFind == INVALID_HANDLE_VALUE) {
345                 err = GetLastError();
346                 if (err == ERROR_FILE_NOT_FOUND) {
347                         return 0;
348                 } else {
349                         ERROR("Failed to read directory \"%ls\"", dir_path);
350                         win32_error(err);
351                         return WIMLIB_ERR_READ;
352                 }
353         }
354         ret = 0;
355         do {
356                 /* Skip . and .. entries */
357                 if (dat.cFileName[0] == L'.' &&
358                     (dat.cFileName[1] == L'\0' ||
359                      (dat.cFileName[1] == L'.' &&
360                       dat.cFileName[2] == L'\0')))
361                         continue;
362                 size_t filename_len = wcslen(dat.cFileName);
363
364                 dir_path[dir_path_num_chars] = L'/';
365                 wmemcpy(dir_path + dir_path_num_chars + 1,
366                         dat.cFileName,
367                         filename_len + 1);
368
369                 struct wim_dentry *child;
370                 size_t path_len = dir_path_num_chars + 1 + filename_len;
371                 ret = win32_build_dentry_tree_recursive(&child,
372                                                         dir_path,
373                                                         path_len,
374                                                         lookup_table,
375                                                         sd_set,
376                                                         config,
377                                                         add_image_flags,
378                                                         progress_func,
379                                                         state);
380                 dir_path[dir_path_num_chars] = L'\0';
381                 if (ret)
382                         goto out_find_close;
383                 if (child)
384                         dentry_add_child(root, child);
385         } while (FindNextFileW(hFind, &dat));
386         err = GetLastError();
387         if (err != ERROR_NO_MORE_FILES) {
388                 ERROR("Failed to read directory \"%ls\"", dir_path);
389                 win32_error(err);
390                 if (ret == 0)
391                         ret = WIMLIB_ERR_READ;
392         }
393 out_find_close:
394         FindClose(hFind);
395         return ret;
396 }
397
398 /* Load a reparse point into a WIM inode.  It is just stored in memory.
399  *
400  * @hFile:  Open handle to a reparse point, with permission to read the reparse
401  *          data.
402  *
403  * @inode:  WIM inode for the reparse point.
404  *
405  * @lookup_table:  Stream lookup table for the WIM; an entry will be added to it
406  *                 for the reparse point unless an entry already exists for
407  *                 the exact same data stream.
408  *
409  * @path:  External path to the reparse point.  Used for error messages only.
410  *
411  * Returns 0 on success; nonzero on failure. */
412 static int
413 win32_capture_reparse_point(HANDLE hFile,
414                             struct wim_inode *inode,
415                             struct wim_lookup_table *lookup_table,
416                             const wchar_t *path)
417 {
418         /* "Reparse point data, including the tag and optional GUID,
419          * cannot exceed 16 kilobytes." - MSDN  */
420         char reparse_point_buf[16 * 1024];
421         DWORD bytesReturned;
422
423         if (!DeviceIoControl(hFile, FSCTL_GET_REPARSE_POINT,
424                              NULL, /* "Not used with this operation; set to NULL" */
425                              0, /* "Not used with this operation; set to 0" */
426                              reparse_point_buf, /* "A pointer to a buffer that
427                                                    receives the reparse point data */
428                              sizeof(reparse_point_buf), /* "The size of the output
429                                                            buffer, in bytes */
430                              &bytesReturned,
431                              NULL))
432         {
433                 DWORD err = GetLastError();
434                 ERROR("Failed to get reparse data of \"%ls\"", path);
435                 win32_error(err);
436                 return WIMLIB_ERR_READ;
437         }
438         if (bytesReturned < 8) {
439                 ERROR("Reparse data on \"%ls\" is invalid", path);
440                 return WIMLIB_ERR_READ;
441         }
442         inode->i_reparse_tag = le32_to_cpu(*(u32*)reparse_point_buf);
443         return inode_add_ads_with_data(inode, L"",
444                                        reparse_point_buf + 8,
445                                        bytesReturned - 8, lookup_table);
446 }
447
448 /* Calculate the SHA1 message digest of a Win32 data stream, which may be either
449  * an unnamed or named data stream.
450  *
451  * @path:       Path to the file, with the stream noted at the end for named
452  *              streams.  UTF-16LE encoding.
453  *
454  * @hash:       On success, the SHA1 message digest of the stream is written to
455  *              this location.
456  *
457  * Returns 0 on success; nonzero on failure.
458  */
459 static int
460 win32_sha1sum(const wchar_t *path, u8 hash[SHA1_HASH_SIZE])
461 {
462         HANDLE hFile;
463         SHA_CTX ctx;
464         u8 buf[32768];
465         DWORD bytesRead;
466         int ret;
467
468         hFile = win32_open_file_data_only(path);
469         if (hFile == INVALID_HANDLE_VALUE)
470                 return WIMLIB_ERR_OPEN;
471
472         sha1_init(&ctx);
473         for (;;) {
474                 if (!ReadFile(hFile, buf, sizeof(buf), &bytesRead, NULL)) {
475                         ret = WIMLIB_ERR_READ;
476                         goto out_close_handle;
477                 }
478                 if (bytesRead == 0)
479                         break;
480                 sha1_update(&ctx, buf, bytesRead);
481         }
482         ret = 0;
483         sha1_final(hash, &ctx);
484 out_close_handle:
485         CloseHandle(hFile);
486         return ret;
487 }
488
489 /* Scans an unnamed or named stream of a Win32 file (not a reparse point
490  * stream); calculates its SHA1 message digest and either creates a `struct
491  * wim_lookup_table_entry' in memory for it, or uses an existing 'struct
492  * wim_lookup_table_entry' for an identical stream.
493  *
494  * @path:               Path to the file (UTF-16LE).
495  *
496  * @path_num_chars:     Number of 2-byte characters in @path.
497  *
498  * @inode:              WIM inode to save the stream into.
499  *
500  * @lookup_table:       Stream lookup table for the WIM.
501  *
502  * @dat:                A `WIN32_FIND_STREAM_DATA' structure that specifies the
503  *                      stream name.
504  *
505  * Returns 0 on success; nonzero on failure.
506  */
507 static int
508 win32_capture_stream(const wchar_t *path,
509                      size_t path_num_chars,
510                      struct wim_inode *inode,
511                      struct wim_lookup_table *lookup_table,
512                      WIN32_FIND_STREAM_DATA *dat)
513 {
514         struct wim_ads_entry *ads_entry;
515         u8 hash[SHA1_HASH_SIZE];
516         struct wim_lookup_table_entry *lte;
517         int ret;
518         wchar_t *stream_name, *colon;
519         size_t stream_name_nchars;
520         bool is_named_stream;
521         wchar_t *spath;
522         size_t spath_nchars;
523         DWORD err;
524         size_t spath_buf_nbytes;
525         const wchar_t *relpath_prefix;
526         const wchar_t *colonchar;
527
528         /* The stream name should be returned as :NAME:TYPE */
529         stream_name = dat->cStreamName;
530         if (*stream_name != L':')
531                 goto out_invalid_stream_name;
532         stream_name += 1;
533         colon = wcschr(stream_name, L':');
534         if (colon == NULL)
535                 goto out_invalid_stream_name;
536
537         if (wcscmp(colon + 1, L"$DATA")) {
538                 /* Not a DATA stream */
539                 ret = 0;
540                 goto out;
541         }
542
543         *colon = '\0';
544
545         stream_name_nchars = colon - stream_name;
546         is_named_stream = (stream_name_nchars != 0);
547
548         if (is_named_stream) {
549                 /* Allocate an ADS entry for the named stream. */
550                 ads_entry = inode_add_ads_utf16le(inode, stream_name,
551                                                   stream_name_nchars * sizeof(wchar_t));
552                 if (!ads_entry) {
553                         ret = WIMLIB_ERR_NOMEM;
554                         goto out;
555                 }
556         }
557
558         /* Create a UTF-16LE string @spath that gives the filename, then a
559          * colon, then the stream name.  Or, if it's an unnamed stream, just the
560          * filename.  It is MALLOC()'ed so that it can be saved in the
561          * wim_lookup_table_entry if needed.
562          *
563          * As yet another special case, relative paths need to be changed to
564          * begin with an explicit "./" so that, for example, a file t:ads, where
565          * :ads is the part we added, is not interpreted as a file on the t:
566          * drive. */
567         spath_nchars = path_num_chars;
568         relpath_prefix = L"";
569         colonchar = L"";
570         if (is_named_stream) {
571                 spath_nchars += 1 + stream_name_nchars;
572                 colonchar = L":";
573                 if (path_num_chars == 1 &&
574                     path[0] != L'/' &&
575                     path[0] != L'\\')
576                 {
577                         spath_nchars += 2;
578                         relpath_prefix = L"./";
579                 }
580         }
581
582         spath_buf_nbytes = (spath_nchars + 1) * sizeof(wchar_t);
583         spath = MALLOC(spath_buf_nbytes);
584
585         swprintf(spath, L"%ls%ls%ls%ls",
586                  relpath_prefix, path, colonchar, stream_name);
587
588         ret = win32_sha1sum(spath, hash);
589         if (ret) {
590                 err = GetLastError();
591                 ERROR("Failed to read \"%ls\" to calculate SHA1sum", spath);
592                 win32_error(err);
593                 goto out_free_spath;
594         }
595
596         lte = __lookup_resource(lookup_table, hash);
597         if (lte) {
598                 /* Use existing wim_lookup_table_entry that has the same SHA1
599                  * message digest */
600                 lte->refcnt++;
601         } else {
602                 /* Make a new wim_lookup_table_entry */
603                 lte = new_lookup_table_entry();
604                 if (!lte) {
605                         ret = WIMLIB_ERR_NOMEM;
606                         goto out_free_spath;
607                 }
608                 lte->file_on_disk = spath;
609                 lte->win32_file_on_disk_fp = INVALID_HANDLE_VALUE;
610                 spath = NULL;
611                 lte->resource_location = RESOURCE_WIN32;
612                 lte->resource_entry.original_size = (uint64_t)dat->StreamSize.QuadPart;
613                 lte->resource_entry.size = (uint64_t)dat->StreamSize.QuadPart;
614                 copy_hash(lte->hash, hash);
615                 lookup_table_insert(lookup_table, lte);
616         }
617         if (is_named_stream)
618                 ads_entry->lte = lte;
619         else
620                 inode->i_lte = lte;
621 out_free_spath:
622         FREE(spath);
623 out:
624         return ret;
625 out_invalid_stream_name:
626         ERROR("Invalid stream name: \"%ls:%ls\"", path, dat->cStreamName);
627         ret = WIMLIB_ERR_READ;
628         goto out;
629 }
630
631 /* Scans a Win32 file for unnamed and named data streams (not reparse point
632  * streams).
633  *
634  * @path:               Path to the file (UTF-16LE).
635  *
636  * @path_num_chars:     Number of 2-byte characters in @path.
637  *
638  * @inode:              WIM inode to save the stream into.
639  *
640  * @lookup_table:       Stream lookup table for the WIM.
641  *
642  * @file_size:          Size of unnamed data stream.  (Used only if alternate
643  *                      data streams API appears to be unavailable.)
644  *
645  * Returns 0 on success; nonzero on failure.
646  */
647 static int
648 win32_capture_streams(const wchar_t *path,
649                       size_t path_num_chars,
650                       struct wim_inode *inode,
651                       struct wim_lookup_table *lookup_table,
652                       u64 file_size)
653 {
654         WIN32_FIND_STREAM_DATA dat;
655         int ret;
656         HANDLE hFind;
657         DWORD err;
658
659         if (win32func_FindFirstStreamW == NULL)
660                 goto unnamed_only;
661
662         hFind = win32func_FindFirstStreamW(path, FindStreamInfoStandard, &dat, 0);
663         if (hFind == INVALID_HANDLE_VALUE) {
664                 err = GetLastError();
665
666                 if (err == ERROR_CALL_NOT_IMPLEMENTED)
667                         goto unnamed_only;
668
669                 /* Seems legal for this to return ERROR_HANDLE_EOF on reparse
670                  * points and directories */
671                 if ((inode->i_attributes &
672                     (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
673                     && err == ERROR_HANDLE_EOF)
674                 {
675                         return 0;
676                 } else {
677                         if (err == ERROR_ACCESS_DENIED) {
678                                 WARNING("Failed to look up data streams "
679                                         "of \"%ls\": Access denied!\n%ls",
680                                         path, capture_access_denied_msg);
681                                 return 0;
682                         } else {
683                                 ERROR("Failed to look up data streams "
684                                       "of \"%ls\"", path);
685                                 win32_error(err);
686                                 return WIMLIB_ERR_READ;
687                         }
688                 }
689         }
690         do {
691                 ret = win32_capture_stream(path,
692                                            path_num_chars,
693                                            inode, lookup_table,
694                                            &dat);
695                 if (ret)
696                         goto out_find_close;
697         } while (win32func_FindNextStreamW(hFind, &dat));
698         err = GetLastError();
699         if (err != ERROR_HANDLE_EOF) {
700                 ERROR("Win32 API: Error reading data streams from \"%ls\"", path);
701                 win32_error(err);
702                 ret = WIMLIB_ERR_READ;
703         }
704 out_find_close:
705         FindClose(hFind);
706         return ret;
707 unnamed_only:
708         if (inode->i_attributes &
709              (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
710         {
711                 ret = 0;
712         } else {
713                 wcscpy(dat.cStreamName, L"::$DATA");
714                 dat.StreamSize.QuadPart = file_size;
715                 ret = win32_capture_stream(path,
716                                            path_num_chars,
717                                            inode, lookup_table,
718                                            &dat);
719         }
720         return ret;
721 }
722
723 static int
724 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
725                                   wchar_t *path,
726                                   size_t path_num_chars,
727                                   struct wim_lookup_table *lookup_table,
728                                   struct sd_set *sd_set,
729                                   const struct capture_config *config,
730                                   int add_image_flags,
731                                   wimlib_progress_func_t progress_func,
732                                   struct win32_capture_state *state)
733 {
734         struct wim_dentry *root = NULL;
735         struct wim_inode *inode;
736         DWORD err;
737         u64 file_size;
738         int ret = 0;
739
740         if (exclude_path(path, config, true)) {
741                 if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT) {
742                         ERROR("Cannot exclude the root directory from capture");
743                         ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
744                         goto out;
745                 }
746                 if ((add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
747                     && progress_func)
748                 {
749                         union wimlib_progress_info info;
750                         info.scan.cur_path = path;
751                         info.scan.excluded = true;
752                         progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
753                 }
754                 goto out;
755         }
756
757         if ((add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
758             && progress_func)
759         {
760                 union wimlib_progress_info info;
761                 info.scan.cur_path = path;
762                 info.scan.excluded = false;
763                 progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
764         }
765
766         HANDLE hFile = win32_open_existing_file(path,
767                                                 FILE_READ_DATA | FILE_READ_ATTRIBUTES);
768         if (hFile == INVALID_HANDLE_VALUE) {
769                 err = GetLastError();
770                 ERROR("Win32 API: Failed to open \"%ls\"", path);
771                 win32_error(err);
772                 ret = WIMLIB_ERR_OPEN;
773                 goto out;
774         }
775
776         BY_HANDLE_FILE_INFORMATION file_info;
777         if (!GetFileInformationByHandle(hFile, &file_info)) {
778                 err = GetLastError();
779                 ERROR("Win32 API: Failed to get file information for \"%ls\"",
780                       path);
781                 win32_error(err);
782                 ret = WIMLIB_ERR_STAT;
783                 goto out_close_handle;
784         }
785
786         /* Create a WIM dentry */
787         ret = new_dentry_with_timeless_inode(path_basename_with_len(path, path_num_chars),
788                                              &root);
789         if (ret)
790                 goto out_close_handle;
791
792         /* Start preparing the associated WIM inode */
793         inode = root->d_inode;
794
795         inode->i_attributes = file_info.dwFileAttributes;
796         inode->i_creation_time = FILETIME_to_u64(&file_info.ftCreationTime);
797         inode->i_last_write_time = FILETIME_to_u64(&file_info.ftLastWriteTime);
798         inode->i_last_access_time = FILETIME_to_u64(&file_info.ftLastAccessTime);
799         inode->i_ino = ((u64)file_info.nFileIndexHigh << 32) |
800                         (u64)file_info.nFileIndexLow;
801
802         inode->i_resolved = 1;
803         add_image_flags &= ~(WIMLIB_ADD_IMAGE_FLAG_ROOT | WIMLIB_ADD_IMAGE_FLAG_SOURCE);
804
805         /* Get DOS name and security descriptor (if any). */
806         ret = win32_get_short_name(root, path);
807         if (ret)
808                 goto out_close_handle;
809
810         if (!(add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NO_ACLS)) {
811                 ret = win32_get_security_descriptor(root, sd_set, path, state,
812                                                     add_image_flags);
813                 if (ret)
814                         goto out_close_handle;
815         }
816
817         file_size = ((u64)file_info.nFileSizeHigh << 32) |
818                      (u64)file_info.nFileSizeLow;
819
820         if (inode_is_directory(inode)) {
821                 /* Directory (not a reparse point) --- recurse to children */
822
823                 /* But first... directories may have alternate data streams that
824                  * need to be captured. */
825                 ret = win32_capture_streams(path,
826                                             path_num_chars,
827                                             inode,
828                                             lookup_table,
829                                             file_size);
830                 if (ret)
831                         goto out_close_handle;
832                 ret = win32_recurse_directory(root,
833                                               path,
834                                               path_num_chars,
835                                               lookup_table,
836                                               sd_set,
837                                               config,
838                                               add_image_flags,
839                                               progress_func,
840                                               state);
841         } else if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
842                 /* Reparse point: save the reparse tag and data */
843                 ret = win32_capture_reparse_point(hFile,
844                                                   inode,
845                                                   lookup_table,
846                                                   path);
847         } else {
848                 /* Not a directory, not a reparse point; capture the default
849                  * file contents and any alternate data streams. */
850                 ret = win32_capture_streams(path,
851                                             path_num_chars,
852                                             inode,
853                                             lookup_table,
854                                             file_size);
855         }
856 out_close_handle:
857         CloseHandle(hFile);
858 out:
859         if (ret == 0)
860                 *root_ret = root;
861         else
862                 free_dentry_tree(root, lookup_table);
863         return ret;
864 }
865
866 static void
867 win32_do_capture_warnings(const struct win32_capture_state *state,
868                           int add_image_flags)
869 {
870         if (state->num_get_sacl_priv_notheld == 0 &&
871             state->num_get_sd_access_denied == 0)
872                 return;
873
874         WARNING("");
875         WARNING("Built dentry tree successfully, but with the following problem(s):");
876         if (state->num_get_sacl_priv_notheld != 0) {
877                 WARNING("Could not capture SACL (System Access Control List)\n"
878                         "          on %lu files or directories.",
879                         state->num_get_sacl_priv_notheld);
880         }
881         if (state->num_get_sd_access_denied != 0) {
882                 WARNING("Could not capture security descriptor at all\n"
883                         "          on %lu files or directories.",
884                         state->num_get_sd_access_denied);
885         }
886         WARNING(
887           "Try running the program as the Administrator to make sure all the\n"
888 "          desired metadata has been captured exactly.  However, if you\n"
889 "          do not care about capturing security descriptors correctly, then\n"
890 "          nothing more needs to be done%ls\n",
891         (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NO_ACLS) ? L"." :
892          L", although you might consider\n"
893 "          passing the --no-acls flag to `wimlib-imagex capture' or\n"
894 "          `wimlib-imagex append' to explicitly capture no security\n"
895 "          descriptors.\n");
896 }
897
898 /* Win32 version of capturing a directory tree */
899 int
900 win32_build_dentry_tree(struct wim_dentry **root_ret,
901                         const wchar_t *root_disk_path,
902                         struct wim_lookup_table *lookup_table,
903                         struct sd_set *sd_set,
904                         const struct capture_config *config,
905                         int add_image_flags,
906                         wimlib_progress_func_t progress_func,
907                         void *extra_arg)
908 {
909         size_t path_nchars;
910         wchar_t *path;
911         int ret;
912         struct win32_capture_state state;
913
914         path_nchars = wcslen(root_disk_path);
915         if (path_nchars > 32767)
916                 return WIMLIB_ERR_INVALID_PARAM;
917
918         /* There is no check for overflow later when this buffer is being used!
919          * But the max path length on NTFS is 32767 characters, and paths need
920          * to be written specially to even go past 260 characters, so we should
921          * be okay with 32770 characters. */
922         path = MALLOC(32770 * sizeof(wchar_t));
923         if (!path)
924                 return WIMLIB_ERR_NOMEM;
925
926         wmemcpy(path, root_disk_path, path_nchars + 1);
927
928         memset(&state, 0, sizeof(state));
929         ret = win32_build_dentry_tree_recursive(root_ret,
930                                                 path,
931                                                 path_nchars,
932                                                 lookup_table,
933                                                 sd_set,
934                                                 config,
935                                                 add_image_flags,
936                                                 progress_func,
937                                                 &state);
938         FREE(path);
939         if (ret == 0)
940                 win32_do_capture_warnings(&state, add_image_flags);
941         return ret;
942 }
943
944 static int
945 win32_set_reparse_data(HANDLE h,
946                        u32 reparse_tag,
947                        const struct wim_lookup_table_entry *lte,
948                        const wchar_t *path)
949 {
950         int ret;
951         u8 *buf;
952         size_t len;
953
954         if (!lte) {
955                 WARNING("\"%ls\" is marked as a reparse point but had no reparse data",
956                         path);
957                 return 0;
958         }
959         len = wim_resource_size(lte);
960         if (len > 16 * 1024 - 8) {
961                 WARNING("\"%ls\": reparse data too long!", path);
962                 return 0;
963         }
964
965         /* The WIM stream omits the ReparseTag and ReparseDataLength fields, so
966          * leave 8 bytes of space for them at the beginning of the buffer, then
967          * set them manually. */
968         buf = alloca(len + 8);
969         ret = read_full_wim_resource(lte, buf + 8, 0);
970         if (ret)
971                 return ret;
972         *(u32*)(buf + 0) = cpu_to_le32(reparse_tag);
973         *(u16*)(buf + 4) = cpu_to_le16(len);
974         *(u16*)(buf + 6) = 0;
975
976         /* Set the reparse data on the open file using the
977          * FSCTL_SET_REPARSE_POINT ioctl.
978          *
979          * There are contradictions in Microsoft's documentation for this:
980          *
981          * "If hDevice was opened without specifying FILE_FLAG_OVERLAPPED,
982          * lpOverlapped is ignored."
983          *
984          * --- So setting lpOverlapped to NULL is okay since it's ignored.
985          *
986          * "If lpOverlapped is NULL, lpBytesReturned cannot be NULL. Even when an
987          * operation returns no output data and lpOutBuffer is NULL,
988          * DeviceIoControl makes use of lpBytesReturned. After such an
989          * operation, the value of lpBytesReturned is meaningless."
990          *
991          * --- So lpOverlapped not really ignored, as it affects another
992          *  parameter.  This is the actual behavior: lpBytesReturned must be
993          *  specified, even though lpBytesReturned is documented as:
994          *
995          *  "Not used with this operation; set to NULL."
996          */
997         DWORD bytesReturned;
998         if (!DeviceIoControl(h, FSCTL_SET_REPARSE_POINT, buf, len + 8,
999                              NULL, 0,
1000                              &bytesReturned /* lpBytesReturned */,
1001                              NULL /* lpOverlapped */))
1002         {
1003                 DWORD err = GetLastError();
1004                 ERROR("Failed to set reparse data on \"%ls\"", path);
1005                 win32_error(err);
1006                 return WIMLIB_ERR_WRITE;
1007         }
1008         return 0;
1009 }
1010
1011 /*
1012  * Sets the security descriptor on an extracted file.
1013  */
1014 static int
1015 win32_set_security_data(const struct wim_inode *inode,
1016                         const wchar_t *path,
1017                         struct apply_args *args)
1018 {
1019         PSECURITY_DESCRIPTOR descriptor;
1020         unsigned long n;
1021         DWORD err;
1022
1023         descriptor = wim_const_security_data(args->w)->descriptors[inode->i_security_id];
1024
1025         SECURITY_INFORMATION securityInformation = DACL_SECURITY_INFORMATION |
1026                                                    SACL_SECURITY_INFORMATION |
1027                                                    OWNER_SECURITY_INFORMATION |
1028                                                    GROUP_SECURITY_INFORMATION;
1029 again:
1030         if (SetFileSecurityW(path, securityInformation, descriptor))
1031                 return 0;
1032
1033         err = GetLastError();
1034
1035         if (args->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS)
1036                 goto fail;
1037
1038         switch (err) {
1039         case ERROR_PRIVILEGE_NOT_HELD:
1040                 if (securityInformation & SACL_SECURITY_INFORMATION) {
1041                         n = args->num_set_sacl_priv_notheld++;
1042                         securityInformation &= ~SACL_SECURITY_INFORMATION;
1043                         if (n < MAX_SET_SACL_PRIV_NOTHELD_WARNINGS) {
1044                                 WARNING(
1045 "We don't have enough privileges to set the full security\n"
1046 "          descriptor on \"%ls\"!\n", path);
1047                                 if (args->num_set_sd_access_denied +
1048                                     args->num_set_sacl_priv_notheld == 1)
1049                                 {
1050                                         WARNING("%ls", apply_access_denied_msg);
1051                                 }
1052                                 WARNING("Re-trying with SACL omitted.\n", path);
1053                         } else if (n == MAX_GET_SACL_PRIV_NOTHELD_WARNINGS) {
1054                                 WARNING(
1055 "Suppressing further 'privileges not held' error messages when setting\n"
1056 "          security descriptors.");
1057                         }
1058                         goto again;
1059                 }
1060                 /* Fall through */
1061         case ERROR_INVALID_OWNER:
1062         case ERROR_ACCESS_DENIED:
1063                 n = args->num_set_sd_access_denied++;
1064                 if (n < MAX_SET_SD_ACCESS_DENIED_WARNINGS) {
1065                         WARNING("Failed to set security descriptor on \"%ls\": "
1066                                 "Access denied!\n", path);
1067                         if (args->num_set_sd_access_denied +
1068                             args->num_set_sacl_priv_notheld == 1)
1069                         {
1070                                 WARNING("%ls", apply_access_denied_msg);
1071                         }
1072                 } else if (n == MAX_SET_SD_ACCESS_DENIED_WARNINGS) {
1073                         WARNING(
1074 "Suppressing further access denied error messages when setting\n"
1075 "          security descriptors");
1076                 }
1077                 return 0;
1078         default:
1079 fail:
1080                 ERROR("Failed to set security descriptor on \"%ls\"", path);
1081                 win32_error(err);
1082                 return WIMLIB_ERR_WRITE;
1083         }
1084         return 0;
1085 }
1086
1087
1088 static int
1089 win32_extract_chunk(const void *buf, size_t len, u64 offset, void *arg)
1090 {
1091         HANDLE hStream = arg;
1092
1093         DWORD nbytes_written;
1094         wimlib_assert(len <= 0xffffffff);
1095
1096         if (!WriteFile(hStream, buf, len, &nbytes_written, NULL) ||
1097             nbytes_written != len)
1098         {
1099                 DWORD err = GetLastError();
1100                 ERROR("WriteFile(): write error");
1101                 win32_error(err);
1102                 return WIMLIB_ERR_WRITE;
1103         }
1104         return 0;
1105 }
1106
1107 static int
1108 do_win32_extract_stream(HANDLE hStream, struct wim_lookup_table_entry *lte)
1109 {
1110         return extract_wim_resource(lte, wim_resource_size(lte),
1111                                     win32_extract_chunk, hStream);
1112 }
1113
1114 static bool
1115 path_is_root_of_drive(const wchar_t *path)
1116 {
1117         if (!*path)
1118                 return false;
1119
1120         if (*path != L'/' && *path != L'\\') {
1121                 if (*(path + 1) == L':')
1122                         path += 2;
1123                 else
1124                         return false;
1125         }
1126         while (*path == L'/' || *path == L'\\')
1127                 path++;
1128         return (*path == L'\0');
1129 }
1130
1131 static int
1132 win32_extract_stream(const struct wim_inode *inode,
1133                      const wchar_t *path,
1134                      const wchar_t *stream_name_utf16,
1135                      struct wim_lookup_table_entry *lte)
1136 {
1137         wchar_t *stream_path;
1138         HANDLE h;
1139         int ret;
1140         DWORD err;
1141         DWORD creationDisposition = CREATE_ALWAYS;
1142
1143         if (stream_name_utf16) {
1144                 /* Named stream.  Create a buffer that contains the UTF-16LE
1145                  * string [.\]@path:@stream_name_utf16.  This is needed to
1146                  * create and open the stream using CreateFileW().  I'm not
1147                  * aware of any other APIs to do this.  Note: the '$DATA' suffix
1148                  * seems to be unneeded.  Additional note: a "./" prefix needs
1149                  * to be added when the path is not absolute to avoid ambiguity
1150                  * with drive letters. */
1151                 size_t stream_path_nchars;
1152                 size_t path_nchars;
1153                 size_t stream_name_nchars;
1154                 const wchar_t *prefix;
1155
1156                 path_nchars = wcslen(path);
1157                 stream_name_nchars = wcslen(stream_name_utf16);
1158                 stream_path_nchars = path_nchars + 1 + stream_name_nchars;
1159                 if (path[0] != cpu_to_le16(L'\0') &&
1160                     path[0] != cpu_to_le16(L'/') &&
1161                     path[0] != cpu_to_le16(L'\\') &&
1162                     path[1] != cpu_to_le16(L':'))
1163                 {
1164                         prefix = L"./";
1165                         stream_path_nchars += 2;
1166                 } else {
1167                         prefix = L"";
1168                 }
1169                 stream_path = alloca((stream_path_nchars + 1) * sizeof(wchar_t));
1170                 swprintf(stream_path, L"%ls%ls:%ls",
1171                          prefix, path, stream_name_utf16);
1172         } else {
1173                 /* Unnamed stream; its path is just the path to the file itself.
1174                  * */
1175                 stream_path = (wchar_t*)path;
1176
1177                 /* Directories must be created with CreateDirectoryW().  Then
1178                  * the call to CreateFileW() will merely open the directory that
1179                  * was already created rather than creating a new file. */
1180                 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1181                         if (!CreateDirectoryW(stream_path, NULL)) {
1182                                 err = GetLastError();
1183                                 switch (err) {
1184                                 case ERROR_ALREADY_EXISTS:
1185                                         break;
1186                                 case ERROR_ACCESS_DENIED:
1187                                         if (path_is_root_of_drive(path))
1188                                                 break;
1189                                         /* Fall through */
1190                                 default:
1191                                         ERROR("Failed to create directory \"%ls\"",
1192                                               stream_path);
1193                                         win32_error(err);
1194                                         ret = WIMLIB_ERR_MKDIR;
1195                                         goto fail;
1196                                 }
1197                         }
1198                         DEBUG("Created directory \"%ls\"", stream_path);
1199                         if (!(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
1200                                 ret = 0;
1201                                 goto out;
1202                         }
1203                         creationDisposition = OPEN_EXISTING;
1204                 }
1205         }
1206
1207         DEBUG("Opening \"%ls\"", stream_path);
1208         h = CreateFileW(stream_path,
1209                         GENERIC_WRITE,
1210                         0,
1211                         NULL,
1212                         creationDisposition,
1213                         FILE_FLAG_OPEN_REPARSE_POINT |
1214                             FILE_FLAG_BACKUP_SEMANTICS |
1215                             inode->i_attributes,
1216                         NULL);
1217         if (h == INVALID_HANDLE_VALUE) {
1218                 err = GetLastError();
1219                 ERROR("Failed to create \"%ls\"", stream_path);
1220                 win32_error(err);
1221                 ret = WIMLIB_ERR_OPEN;
1222                 goto fail;
1223         }
1224
1225         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT &&
1226             stream_name_utf16 == NULL)
1227         {
1228                 DEBUG("Setting reparse data on \"%ls\"", path);
1229                 ret = win32_set_reparse_data(h, inode->i_reparse_tag, lte, path);
1230                 if (ret)
1231                         goto fail_close_handle;
1232         } else {
1233                 if (lte) {
1234                         DEBUG("Extracting \"%ls\" (len = %"PRIu64")",
1235                               stream_path, wim_resource_size(lte));
1236                         ret = do_win32_extract_stream(h, lte);
1237                         if (ret)
1238                                 goto fail_close_handle;
1239                 }
1240         }
1241
1242         DEBUG("Closing \"%ls\"", stream_path);
1243         if (!CloseHandle(h)) {
1244                 err = GetLastError();
1245                 ERROR("Failed to close \"%ls\"", stream_path);
1246                 win32_error(err);
1247                 ret = WIMLIB_ERR_WRITE;
1248                 goto fail;
1249         }
1250         ret = 0;
1251         goto out;
1252 fail_close_handle:
1253         CloseHandle(h);
1254 fail:
1255         ERROR("Error extracting %ls", stream_path);
1256 out:
1257         return ret;
1258 }
1259
1260 /*
1261  * Creates a file, directory, or reparse point and extracts all streams to it
1262  * (unnamed data stream and/or reparse point stream, plus any alternate data
1263  * streams).  This in Win32-specific code.
1264  *
1265  * @inode:      WIM inode for this file or directory.
1266  * @path:       UTF-16LE external path to extract the inode to.
1267  *
1268  * Returns 0 on success; nonzero on failure.
1269  */
1270 static int
1271 win32_extract_streams(const struct wim_inode *inode,
1272                       const wchar_t *path, u64 *completed_bytes_p)
1273 {
1274         struct wim_lookup_table_entry *unnamed_lte;
1275         int ret;
1276
1277         unnamed_lte = inode_unnamed_lte_resolved(inode);
1278         ret = win32_extract_stream(inode, path, NULL, unnamed_lte);
1279         if (ret)
1280                 goto out;
1281         if (unnamed_lte)
1282                 *completed_bytes_p += wim_resource_size(unnamed_lte);
1283         for (u16 i = 0; i < inode->i_num_ads; i++) {
1284                 const struct wim_ads_entry *ads_entry = &inode->i_ads_entries[i];
1285                 if (ads_entry->stream_name_nbytes != 0) {
1286                         /* Skip special UNIX data entries (see documentation for
1287                          * WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA) */
1288                         if (ads_entry->stream_name_nbytes == WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES
1289                             && !memcmp(ads_entry->stream_name,
1290                                        WIMLIB_UNIX_DATA_TAG_UTF16LE,
1291                                        WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES))
1292                                 continue;
1293                         ret = win32_extract_stream(inode,
1294                                                    path,
1295                                                    ads_entry->stream_name,
1296                                                    ads_entry->lte);
1297                         if (ret)
1298                                 break;
1299                         if (ads_entry->lte)
1300                                 *completed_bytes_p += wim_resource_size(ads_entry->lte);
1301                 }
1302         }
1303 out:
1304         return ret;
1305 }
1306
1307 /* Extract a file, directory, reparse point, or hard link to an
1308  * already-extracted file using the Win32 API */
1309 int
1310 win32_do_apply_dentry(const wchar_t *output_path,
1311                       size_t output_path_num_chars,
1312                       struct wim_dentry *dentry,
1313                       struct apply_args *args)
1314 {
1315         int ret;
1316         struct wim_inode *inode = dentry->d_inode;
1317         DWORD err;
1318
1319         if (inode->i_nlink > 1 && inode->i_extracted_file != NULL) {
1320                 /* Linked file, with another name already extracted.  Create a
1321                  * hard link. */
1322                 DEBUG("Creating hard link \"%ls => %ls\"",
1323                       output_path, inode->i_extracted_file);
1324                 if (!CreateHardLinkW(output_path, inode->i_extracted_file, NULL)) {
1325                         err = GetLastError();
1326                         ERROR("Can't create hard link \"%ls => %ls\"",
1327                               output_path, inode->i_extracted_file);
1328                         win32_error(err);
1329                         return WIMLIB_ERR_LINK;
1330                 }
1331         } else {
1332                 /* Create the file, directory, or reparse point, and extract the
1333                  * data streams. */
1334                 ret = win32_extract_streams(inode, output_path,
1335                                             &args->progress.extract.completed_bytes);
1336                 if (ret)
1337                         return ret;
1338
1339                 if (inode->i_security_id >= 0 &&
1340                     !(args->extract_flags & WIMLIB_EXTRACT_FLAG_NO_ACLS))
1341                 {
1342                         ret = win32_set_security_data(inode, output_path, args);
1343                         if (ret)
1344                                 return ret;
1345                 }
1346                 if (inode->i_nlink > 1) {
1347                         /* Save extracted path for a later call to
1348                          * CreateHardLinkW() if this inode has multiple links.
1349                          * */
1350                         inode->i_extracted_file = WSTRDUP(output_path);
1351                         if (!inode->i_extracted_file)
1352                                 ret = WIMLIB_ERR_NOMEM;
1353                 }
1354         }
1355         return 0;
1356 }
1357
1358 /* Set timestamps on an extracted file using the Win32 API */
1359 int
1360 win32_do_apply_dentry_timestamps(const wchar_t *path,
1361                                  size_t path_num_chars,
1362                                  const struct wim_dentry *dentry,
1363                                  const struct apply_args *args)
1364 {
1365         DWORD err;
1366         HANDLE h;
1367         const struct wim_inode *inode = dentry->d_inode;
1368
1369         DEBUG("Opening \"%ls\" to set timestamps", path);
1370         h = win32_open_existing_file(path, FILE_WRITE_ATTRIBUTES);
1371         if (h == INVALID_HANDLE_VALUE) {
1372                 err = GetLastError();
1373                 goto fail;
1374         }
1375
1376         FILETIME creationTime = {.dwLowDateTime = inode->i_creation_time & 0xffffffff,
1377                                  .dwHighDateTime = inode->i_creation_time >> 32};
1378         FILETIME lastAccessTime = {.dwLowDateTime = inode->i_last_access_time & 0xffffffff,
1379                                   .dwHighDateTime = inode->i_last_access_time >> 32};
1380         FILETIME lastWriteTime = {.dwLowDateTime = inode->i_last_write_time & 0xffffffff,
1381                                   .dwHighDateTime = inode->i_last_write_time >> 32};
1382
1383         DEBUG("Calling SetFileTime() on \"%ls\"", path);
1384         if (!SetFileTime(h, &creationTime, &lastAccessTime, &lastWriteTime)) {
1385                 err = GetLastError();
1386                 CloseHandle(h);
1387                 goto fail;
1388         }
1389         DEBUG("Closing \"%ls\"", path);
1390         if (!CloseHandle(h)) {
1391                 err = GetLastError();
1392                 goto fail;
1393         }
1394         goto out;
1395 fail:
1396         /* Only warn if setting timestamps failed; still return 0. */
1397         WARNING("Can't set timestamps on \"%ls\"", path);
1398         win32_error(err);
1399 out:
1400         return 0;
1401 }
1402
1403 /* Replacement for POSIX fsync() */
1404 int
1405 fsync(int fd)
1406 {
1407         HANDLE h = (HANDLE)_get_osfhandle(fd);
1408         if (h == INVALID_HANDLE_VALUE) {
1409                 ERROR("Could not get Windows handle for file descriptor");
1410                 win32_error(GetLastError());
1411                 errno = EBADF;
1412                 return -1;
1413         }
1414         if (!FlushFileBuffers(h)) {
1415                 ERROR("Could not flush file buffers to disk");
1416                 win32_error(GetLastError());
1417                 errno = EIO;
1418                 return -1;
1419         }
1420         return 0;
1421 }
1422
1423 /* Use the Win32 API to get the number of processors */
1424 unsigned
1425 win32_get_number_of_processors()
1426 {
1427         SYSTEM_INFO sysinfo;
1428         GetSystemInfo(&sysinfo);
1429         return sysinfo.dwNumberOfProcessors;
1430 }
1431
1432 /* Replacement for POSIX-2008 realpath().  Warning: partial functionality only
1433  * (resolved_path must be NULL).   Also I highly doubt that GetFullPathName
1434  * really does the right thing under all circumstances. */
1435 wchar_t *
1436 realpath(const wchar_t *path, wchar_t *resolved_path)
1437 {
1438         DWORD ret;
1439         wimlib_assert(resolved_path == NULL);
1440
1441         ret = GetFullPathNameW(path, 0, NULL, NULL);
1442         if (!ret)
1443                 goto fail_win32;
1444
1445         resolved_path = TMALLOC(ret);
1446         if (!resolved_path)
1447                 goto fail;
1448         ret = GetFullPathNameW(path, ret, resolved_path, NULL);
1449         if (!ret) {
1450                 free(resolved_path);
1451                 goto fail_win32;
1452         }
1453         return resolved_path;
1454 fail_win32:
1455         win32_error(GetLastError());
1456 fail:
1457         return NULL;
1458 }
1459
1460 char *
1461 nl_langinfo(nl_item item)
1462 {
1463         wimlib_assert(item == CODESET);
1464         static char buf[64];
1465         strcpy(buf, "Unknown");
1466         return buf;
1467 }
1468
1469 /* rename() on Windows fails if the destination file exists.  And we need to
1470  * make it work on wide characters.  Fix it. */
1471 int
1472 win32_rename_replacement(const wchar_t *oldpath, const wchar_t *newpath)
1473 {
1474         if (MoveFileExW(oldpath, newpath, MOVEFILE_REPLACE_EXISTING)) {
1475                 return 0;
1476         } else {
1477                 /* As usual, the possible error values are not documented */
1478                 DWORD err = GetLastError();
1479                 ERROR("MoveFileEx(): Can't rename \"%ls\" to \"%ls\"",
1480                       oldpath, newpath);
1481                 win32_error(err);
1482                 errno = 0;
1483                 return -1;
1484         }
1485 }
1486
1487 /* Replacement for POSIX fnmatch() (partial functionality only) */
1488 int
1489 fnmatch(const wchar_t *pattern, const wchar_t *string, int flags)
1490 {
1491         if (PathMatchSpecW(string, pattern))
1492                 return 0;
1493         else
1494                 return FNM_NOMATCH;
1495 }
1496
1497 /* truncate() replacement */
1498 int
1499 win32_truncate_replacement(const wchar_t *path, off_t size)
1500 {
1501         DWORD err = NO_ERROR;
1502         LARGE_INTEGER liOffset;
1503
1504         HANDLE h = win32_open_existing_file(path, GENERIC_WRITE);
1505         if (h == INVALID_HANDLE_VALUE)
1506                 goto fail;
1507
1508         liOffset.QuadPart = size;
1509         if (!SetFilePointerEx(h, liOffset, NULL, FILE_BEGIN))
1510                 goto fail_close_handle;
1511
1512         if (!SetEndOfFile(h))
1513                 goto fail_close_handle;
1514         CloseHandle(h);
1515         return 0;
1516
1517 fail_close_handle:
1518         err = GetLastError();
1519         CloseHandle(h);
1520 fail:
1521         if (err == NO_ERROR)
1522                 err = GetLastError();
1523         ERROR("Can't truncate %ls to %"PRIu64" bytes", path, size);
1524         win32_error(err);
1525         errno = -1;
1526         return -1;
1527 }