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