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