f2e7eeb08988464c43db05f4eb3f9850a381d150
[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
589         u32 stream_id;
590         if (is_named_stream) {
591                 stream_id = ads_entry->stream_id;
592                 ads_entry->lte = lte;
593         } else {
594                 stream_id = 0;
595                 inode->i_lte = lte;
596         }
597
598         lookup_table_insert_unhashed(lookup_table, lte, inode, stream_id);
599 out_free_spath:
600         FREE(spath);
601 out:
602         return ret;
603 out_invalid_stream_name:
604         ERROR("Invalid stream name: \"%ls:%ls\"", path, dat->cStreamName);
605         ret = WIMLIB_ERR_READ;
606         goto out;
607 }
608
609 /* Scans a Win32 file for unnamed and named data streams (not reparse point
610  * streams).
611  *
612  * @path:               Path to the file (UTF-16LE).
613  *
614  * @path_num_chars:     Number of 2-byte characters in @path.
615  *
616  * @inode:              WIM inode to save the stream into.
617  *
618  * @lookup_table:       Stream lookup table for the WIM.
619  *
620  * @file_size:          Size of unnamed data stream.  (Used only if alternate
621  *                      data streams API appears to be unavailable.)
622  *
623  * Returns 0 on success; nonzero on failure.
624  */
625 static int
626 win32_capture_streams(const wchar_t *path,
627                       size_t path_num_chars,
628                       struct wim_inode *inode,
629                       struct wim_lookup_table *lookup_table,
630                       u64 file_size)
631 {
632         WIN32_FIND_STREAM_DATA dat;
633         int ret;
634         HANDLE hFind;
635         DWORD err;
636
637         if (win32func_FindFirstStreamW == NULL)
638                 goto unnamed_only;
639
640         hFind = win32func_FindFirstStreamW(path, FindStreamInfoStandard, &dat, 0);
641         if (hFind == INVALID_HANDLE_VALUE) {
642                 err = GetLastError();
643
644                 if (err == ERROR_CALL_NOT_IMPLEMENTED)
645                         goto unnamed_only;
646
647                 /* Seems legal for this to return ERROR_HANDLE_EOF on reparse
648                  * points and directories */
649                 if ((inode->i_attributes &
650                     (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
651                     && err == ERROR_HANDLE_EOF)
652                 {
653                         return 0;
654                 } else {
655                         if (err == ERROR_ACCESS_DENIED) {
656                                 /* XXX This maybe should be an error. */
657                                 WARNING("Failed to look up data streams "
658                                         "of \"%ls\": Access denied!\n%ls",
659                                         path, capture_access_denied_msg);
660                                 return 0;
661                         } else {
662                                 ERROR("Failed to look up data streams "
663                                       "of \"%ls\"", path);
664                                 win32_error(err);
665                                 return WIMLIB_ERR_READ;
666                         }
667                 }
668         }
669         do {
670                 ret = win32_capture_stream(path,
671                                            path_num_chars,
672                                            inode, lookup_table,
673                                            &dat);
674                 if (ret)
675                         goto out_find_close;
676         } while (win32func_FindNextStreamW(hFind, &dat));
677         err = GetLastError();
678         if (err != ERROR_HANDLE_EOF) {
679                 ERROR("Win32 API: Error reading data streams from \"%ls\"", path);
680                 win32_error(err);
681                 ret = WIMLIB_ERR_READ;
682         }
683 out_find_close:
684         FindClose(hFind);
685         return ret;
686 unnamed_only:
687         /* FindFirstStreamW() API is not available.  Only capture the unnamed
688          * data stream. */
689         if (inode->i_attributes &
690              (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
691         {
692                 ret = 0;
693         } else {
694                 /* Just create our own WIN32_FIND_STREAM_DATA for an unnamed
695                  * stream to reduce the code to a call to the
696                  * already-implemented win32_capture_stream() */
697                 wcscpy(dat.cStreamName, L"::$DATA");
698                 dat.StreamSize.QuadPart = file_size;
699                 ret = win32_capture_stream(path,
700                                            path_num_chars,
701                                            inode, lookup_table,
702                                            &dat);
703         }
704         return ret;
705 }
706
707 static int
708 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
709                                   wchar_t *path,
710                                   size_t path_num_chars,
711                                   struct wim_lookup_table *lookup_table,
712                                   struct wim_inode_table *inode_table,
713                                   struct sd_set *sd_set,
714                                   const struct wimlib_capture_config *config,
715                                   int add_image_flags,
716                                   wimlib_progress_func_t progress_func,
717                                   struct win32_capture_state *state)
718 {
719         struct wim_dentry *root = NULL;
720         struct wim_inode *inode;
721         DWORD err;
722         u64 file_size;
723         int ret = 0;
724
725         if (exclude_path(path, path_num_chars, config, true)) {
726                 if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT) {
727                         ERROR("Cannot exclude the root directory from capture");
728                         ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
729                         goto out;
730                 }
731                 if ((add_image_flags & WIMLIB_ADD_IMAGE_FLAG_EXCLUDE_VERBOSE)
732                     && progress_func)
733                 {
734                         union wimlib_progress_info info;
735                         info.scan.cur_path = path;
736                         info.scan.excluded = true;
737                         progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
738                 }
739                 goto out;
740         }
741
742         if ((add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
743             && progress_func)
744         {
745                 union wimlib_progress_info info;
746                 info.scan.cur_path = path;
747                 info.scan.excluded = false;
748                 progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
749         }
750
751         HANDLE hFile = win32_open_existing_file(path,
752                                                 FILE_READ_DATA | FILE_READ_ATTRIBUTES);
753         if (hFile == INVALID_HANDLE_VALUE) {
754                 err = GetLastError();
755                 ERROR("Win32 API: Failed to open \"%ls\"", path);
756                 win32_error(err);
757                 ret = WIMLIB_ERR_OPEN;
758                 goto out;
759         }
760
761         BY_HANDLE_FILE_INFORMATION file_info;
762         if (!GetFileInformationByHandle(hFile, &file_info)) {
763                 err = GetLastError();
764                 ERROR("Win32 API: Failed to get file information for \"%ls\"",
765                       path);
766                 win32_error(err);
767                 ret = WIMLIB_ERR_STAT;
768                 goto out_close_handle;
769         }
770
771         /* Create a WIM dentry with an associated inode, which may be shared */
772         ret = inode_table_new_dentry(inode_table,
773                                      path_basename_with_len(path, path_num_chars),
774                                      ((u64)file_info.nFileIndexHigh << 32) |
775                                          (u64)file_info.nFileIndexLow,
776                                      file_info.dwVolumeSerialNumber,
777                                      &root);
778         if (ret)
779                 goto out_close_handle;
780
781         ret = win32_get_short_name(root, path);
782         if (ret)
783                 goto out_close_handle;
784
785         inode = root->d_inode;
786
787         if (inode->i_nlink > 1) /* Shared inode; nothing more to do */
788                 goto out_close_handle;
789
790         inode->i_attributes = file_info.dwFileAttributes;
791         inode->i_creation_time = FILETIME_to_u64(&file_info.ftCreationTime);
792         inode->i_last_write_time = FILETIME_to_u64(&file_info.ftLastWriteTime);
793         inode->i_last_access_time = FILETIME_to_u64(&file_info.ftLastAccessTime);
794         inode->i_resolved = 1;
795
796         add_image_flags &= ~(WIMLIB_ADD_IMAGE_FLAG_ROOT | WIMLIB_ADD_IMAGE_FLAG_SOURCE);
797
798         if (!(add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NO_ACLS)) {
799                 ret = win32_get_security_descriptor(root, sd_set, path, state,
800                                                     add_image_flags);
801                 if (ret)
802                         goto out_close_handle;
803         }
804
805         file_size = ((u64)file_info.nFileSizeHigh << 32) |
806                      (u64)file_info.nFileSizeLow;
807
808         if (inode_is_directory(inode)) {
809                 /* Directory (not a reparse point) --- recurse to children */
810
811                 /* But first... directories may have alternate data streams that
812                  * need to be captured. */
813                 ret = win32_capture_streams(path,
814                                             path_num_chars,
815                                             inode,
816                                             lookup_table,
817                                             file_size);
818                 if (ret)
819                         goto out_close_handle;
820                 ret = win32_recurse_directory(root,
821                                               path,
822                                               path_num_chars,
823                                               lookup_table,
824                                               inode_table,
825                                               sd_set,
826                                               config,
827                                               add_image_flags,
828                                               progress_func,
829                                               state);
830         } else if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
831                 /* Reparse point: save the reparse tag and data.  Alternate data
832                  * streams are not captured, if it's even possible for a reparse
833                  * point to have alternate data streams... */
834                 ret = win32_capture_reparse_point(hFile,
835                                                   inode,
836                                                   lookup_table,
837                                                   path);
838         } else {
839                 /* Not a directory, not a reparse point; capture the default
840                  * file contents and any alternate data streams. */
841                 ret = win32_capture_streams(path,
842                                             path_num_chars,
843                                             inode,
844                                             lookup_table,
845                                             file_size);
846         }
847 out_close_handle:
848         CloseHandle(hFile);
849 out:
850         if (ret == 0)
851                 *root_ret = root;
852         else
853                 free_dentry_tree(root, lookup_table);
854         return ret;
855 }
856
857 static void
858 win32_do_capture_warnings(const struct win32_capture_state *state,
859                           int add_image_flags)
860 {
861         if (state->num_get_sacl_priv_notheld == 0 &&
862             state->num_get_sd_access_denied == 0)
863                 return;
864
865         WARNING("");
866         WARNING("Built dentry tree successfully, but with the following problem(s):");
867         if (state->num_get_sacl_priv_notheld != 0) {
868                 WARNING("Could not capture SACL (System Access Control List)\n"
869                         "          on %lu files or directories.",
870                         state->num_get_sacl_priv_notheld);
871         }
872         if (state->num_get_sd_access_denied != 0) {
873                 WARNING("Could not capture security descriptor at all\n"
874                         "          on %lu files or directories.",
875                         state->num_get_sd_access_denied);
876         }
877         WARNING(
878           "Try running the program as the Administrator to make sure all the\n"
879 "          desired metadata has been captured exactly.  However, if you\n"
880 "          do not care about capturing security descriptors correctly, then\n"
881 "          nothing more needs to be done%ls\n",
882         (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NO_ACLS) ? L"." :
883          L", although you might consider\n"
884 "          passing the --no-acls flag to `wimlib-imagex capture' or\n"
885 "          `wimlib-imagex append' to explicitly capture no security\n"
886 "          descriptors.\n");
887 }
888
889 /* Win32 version of capturing a directory tree */
890 int
891 win32_build_dentry_tree(struct wim_dentry **root_ret,
892                         const wchar_t *root_disk_path,
893                         struct wim_lookup_table *lookup_table,
894                         struct wim_inode_table *inode_table,
895                         struct sd_set *sd_set,
896                         const struct wimlib_capture_config *config,
897                         int add_image_flags,
898                         wimlib_progress_func_t progress_func,
899                         void *extra_arg)
900 {
901         size_t path_nchars;
902         wchar_t *path;
903         int ret;
904         struct win32_capture_state state;
905
906         path_nchars = wcslen(root_disk_path);
907         if (path_nchars > 32767)
908                 return WIMLIB_ERR_INVALID_PARAM;
909
910         /* There is no check for overflow later when this buffer is being used!
911          * But the max path length on NTFS is 32767 characters, and paths need
912          * to be written specially to even go past 260 characters, so we should
913          * be okay with 32770 characters. */
914         path = MALLOC(32770 * sizeof(wchar_t));
915         if (!path)
916                 return WIMLIB_ERR_NOMEM;
917
918         wmemcpy(path, root_disk_path, path_nchars + 1);
919
920         memset(&state, 0, sizeof(state));
921         ret = win32_build_dentry_tree_recursive(root_ret,
922                                                 path,
923                                                 path_nchars,
924                                                 lookup_table,
925                                                 inode_table,
926                                                 sd_set,
927                                                 config,
928                                                 add_image_flags,
929                                                 progress_func,
930                                                 &state);
931         FREE(path);
932         if (ret == 0)
933                 win32_do_capture_warnings(&state, add_image_flags);
934         return ret;
935 }
936
937 static int
938 win32_set_reparse_data(HANDLE h,
939                        u32 reparse_tag,
940                        const struct wim_lookup_table_entry *lte,
941                        const wchar_t *path)
942 {
943         int ret;
944         u8 *buf;
945         size_t len;
946
947         if (!lte) {
948                 WARNING("\"%ls\" is marked as a reparse point but had no reparse data",
949                         path);
950                 return 0;
951         }
952         len = wim_resource_size(lte);
953         if (len > 16 * 1024 - 8) {
954                 WARNING("\"%ls\": reparse data too long!", path);
955                 return 0;
956         }
957
958         /* The WIM stream omits the ReparseTag and ReparseDataLength fields, so
959          * leave 8 bytes of space for them at the beginning of the buffer, then
960          * set them manually. */
961         buf = alloca(len + 8);
962         ret = read_full_wim_resource(lte, buf + 8, 0);
963         if (ret)
964                 return ret;
965         *(u32*)(buf + 0) = cpu_to_le32(reparse_tag);
966         *(u16*)(buf + 4) = cpu_to_le16(len);
967         *(u16*)(buf + 6) = 0;
968
969         /* Set the reparse data on the open file using the
970          * FSCTL_SET_REPARSE_POINT ioctl.
971          *
972          * There are contradictions in Microsoft's documentation for this:
973          *
974          * "If hDevice was opened without specifying FILE_FLAG_OVERLAPPED,
975          * lpOverlapped is ignored."
976          *
977          * --- So setting lpOverlapped to NULL is okay since it's ignored.
978          *
979          * "If lpOverlapped is NULL, lpBytesReturned cannot be NULL. Even when an
980          * operation returns no output data and lpOutBuffer is NULL,
981          * DeviceIoControl makes use of lpBytesReturned. After such an
982          * operation, the value of lpBytesReturned is meaningless."
983          *
984          * --- So lpOverlapped not really ignored, as it affects another
985          *  parameter.  This is the actual behavior: lpBytesReturned must be
986          *  specified, even though lpBytesReturned is documented as:
987          *
988          *  "Not used with this operation; set to NULL."
989          */
990         DWORD bytesReturned;
991         if (!DeviceIoControl(h, FSCTL_SET_REPARSE_POINT, buf, len + 8,
992                              NULL, 0,
993                              &bytesReturned /* lpBytesReturned */,
994                              NULL /* lpOverlapped */))
995         {
996                 DWORD err = GetLastError();
997                 ERROR("Failed to set reparse data on \"%ls\"", path);
998                 win32_error(err);
999                 return WIMLIB_ERR_WRITE;
1000         }
1001         return 0;
1002 }
1003
1004 static int
1005 win32_set_compressed(HANDLE hFile, const wchar_t *path)
1006 {
1007         USHORT format = COMPRESSION_FORMAT_DEFAULT;
1008         DWORD bytesReturned = 0;
1009         if (!DeviceIoControl(hFile, FSCTL_SET_COMPRESSION,
1010                              &format, sizeof(USHORT),
1011                              NULL, 0,
1012                              &bytesReturned, NULL))
1013         {
1014                 /* Warning only */
1015                 DWORD err = GetLastError();
1016                 WARNING("Failed to set compression flag on \"%ls\"", path);
1017                 win32_error(err);
1018         }
1019         return 0;
1020 }
1021
1022 static int
1023 win32_set_sparse(HANDLE hFile, const wchar_t *path)
1024 {
1025         DWORD bytesReturned = 0;
1026         if (!DeviceIoControl(hFile, FSCTL_SET_SPARSE,
1027                              NULL, 0,
1028                              NULL, 0,
1029                              &bytesReturned, NULL))
1030         {
1031                 /* Warning only */
1032                 DWORD err = GetLastError();
1033                 WARNING("Failed to set sparse flag on \"%ls\"", path);
1034                 win32_error(err);
1035         }
1036         return 0;
1037 }
1038
1039 /*
1040  * Sets the security descriptor on an extracted file.
1041  */
1042 static int
1043 win32_set_security_data(const struct wim_inode *inode,
1044                         const wchar_t *path,
1045                         struct apply_args *args)
1046 {
1047         PSECURITY_DESCRIPTOR descriptor;
1048         unsigned long n;
1049         DWORD err;
1050
1051         descriptor = wim_const_security_data(args->w)->descriptors[inode->i_security_id];
1052
1053         SECURITY_INFORMATION securityInformation = DACL_SECURITY_INFORMATION |
1054                                                    SACL_SECURITY_INFORMATION |
1055                                                    OWNER_SECURITY_INFORMATION |
1056                                                    GROUP_SECURITY_INFORMATION;
1057 again:
1058         if (SetFileSecurityW(path, securityInformation, descriptor))
1059                 return 0;
1060         err = GetLastError();
1061         if (args->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS)
1062                 goto fail;
1063         switch (err) {
1064         case ERROR_PRIVILEGE_NOT_HELD:
1065                 if (securityInformation & SACL_SECURITY_INFORMATION) {
1066                         n = args->num_set_sacl_priv_notheld++;
1067                         securityInformation &= ~SACL_SECURITY_INFORMATION;
1068                         if (n < MAX_SET_SACL_PRIV_NOTHELD_WARNINGS) {
1069                                 WARNING(
1070 "We don't have enough privileges to set the full security\n"
1071 "          descriptor on \"%ls\"!\n", path);
1072                                 if (args->num_set_sd_access_denied +
1073                                     args->num_set_sacl_priv_notheld == 1)
1074                                 {
1075                                         WARNING("%ls", apply_access_denied_msg);
1076                                 }
1077                                 WARNING("Re-trying with SACL omitted.\n", path);
1078                         } else if (n == MAX_GET_SACL_PRIV_NOTHELD_WARNINGS) {
1079                                 WARNING(
1080 "Suppressing further 'privileges not held' error messages when setting\n"
1081 "          security descriptors.");
1082                         }
1083                         goto again;
1084                 }
1085                 /* Fall through */
1086         case ERROR_INVALID_OWNER:
1087         case ERROR_ACCESS_DENIED:
1088                 n = args->num_set_sd_access_denied++;
1089                 if (n < MAX_SET_SD_ACCESS_DENIED_WARNINGS) {
1090                         WARNING("Failed to set security descriptor on \"%ls\": "
1091                                 "Access denied!\n", path);
1092                         if (args->num_set_sd_access_denied +
1093                             args->num_set_sacl_priv_notheld == 1)
1094                         {
1095                                 WARNING("%ls", apply_access_denied_msg);
1096                         }
1097                 } else if (n == MAX_SET_SD_ACCESS_DENIED_WARNINGS) {
1098                         WARNING(
1099 "Suppressing further access denied error messages when setting\n"
1100 "          security descriptors");
1101                 }
1102                 return 0;
1103         default:
1104 fail:
1105                 ERROR("Failed to set security descriptor on \"%ls\"", path);
1106                 win32_error(err);
1107                 return WIMLIB_ERR_WRITE;
1108         }
1109 }
1110
1111
1112 static int
1113 win32_extract_chunk(const void *buf, size_t len, u64 offset, void *arg)
1114 {
1115         HANDLE hStream = arg;
1116
1117         DWORD nbytes_written;
1118         wimlib_assert(len <= 0xffffffff);
1119
1120         if (!WriteFile(hStream, buf, len, &nbytes_written, NULL) ||
1121             nbytes_written != len)
1122         {
1123                 DWORD err = GetLastError();
1124                 ERROR("WriteFile(): write error");
1125                 win32_error(err);
1126                 return WIMLIB_ERR_WRITE;
1127         }
1128         return 0;
1129 }
1130
1131 static int
1132 do_win32_extract_stream(HANDLE hStream, struct wim_lookup_table_entry *lte)
1133 {
1134         return extract_wim_resource(lte, wim_resource_size(lte),
1135                                     win32_extract_chunk, hStream);
1136 }
1137
1138 static bool
1139 path_is_root_of_drive(const wchar_t *path)
1140 {
1141         if (!*path)
1142                 return false;
1143
1144         if (*path != L'/' && *path != L'\\') {
1145                 if (*(path + 1) == L':')
1146                         path += 2;
1147                 else
1148                         return false;
1149         }
1150         while (*path == L'/' || *path == L'\\')
1151                 path++;
1152         return (*path == L'\0');
1153 }
1154
1155 static DWORD
1156 win32_get_create_flags_and_attributes(DWORD i_attributes)
1157 {
1158         DWORD attributes;
1159
1160         /*
1161          * Some attributes cannot be set by passing them to CreateFile().  In
1162          * particular:
1163          *
1164          * FILE_ATTRIBUTE_DIRECTORY:
1165          *   CreateDirectory() must be called instead of CreateFile().
1166          *
1167          * FILE_ATTRIBUTE_SPARSE_FILE:
1168          *   Needs an ioctl.
1169          *   See: win32_set_sparse().
1170          *
1171          * FILE_ATTRIBUTE_COMPRESSED:
1172          *   Not clear from the documentation, but apparently this needs an
1173          *   ioctl as well.
1174          *   See: win32_set_compressed().
1175          *
1176          * FILE_ATTRIBUTE_REPARSE_POINT:
1177          *   Needs an ioctl, with the reparse data specified.
1178          *   See: win32_set_reparse_data().
1179          *
1180          * In addition, clear any file flags in the attributes that we don't
1181          * want, but also specify FILE_FLAG_OPEN_REPARSE_POINT and
1182          * FILE_FLAG_BACKUP_SEMANTICS as we are a backup application.
1183          */
1184         attributes = i_attributes & ~(FILE_ATTRIBUTE_SPARSE_FILE |
1185                                       FILE_ATTRIBUTE_COMPRESSED |
1186                                       FILE_ATTRIBUTE_REPARSE_POINT |
1187                                       FILE_ATTRIBUTE_DIRECTORY |
1188                                       FILE_FLAG_DELETE_ON_CLOSE |
1189                                       FILE_FLAG_NO_BUFFERING |
1190                                       FILE_FLAG_OPEN_NO_RECALL |
1191                                       FILE_FLAG_OVERLAPPED |
1192                                       FILE_FLAG_RANDOM_ACCESS |
1193                                       /*FILE_FLAG_SESSION_AWARE |*/
1194                                       FILE_FLAG_SEQUENTIAL_SCAN |
1195                                       FILE_FLAG_WRITE_THROUGH);
1196         return attributes |
1197                FILE_FLAG_OPEN_REPARSE_POINT |
1198                FILE_FLAG_BACKUP_SEMANTICS;
1199 }
1200
1201 static bool
1202 inode_has_special_attributes(const struct wim_inode *inode)
1203 {
1204         return (inode->i_attributes & (FILE_ATTRIBUTE_COMPRESSED |
1205                                        FILE_ATTRIBUTE_REPARSE_POINT |
1206                                        FILE_ATTRIBUTE_SPARSE_FILE)) != 0;
1207 }
1208
1209 static int
1210 win32_set_special_attributes(HANDLE hFile, const struct wim_inode *inode,
1211                              struct wim_lookup_table_entry *unnamed_stream_lte,
1212                              const wchar_t *path)
1213 {
1214         int ret;
1215
1216         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1217                 DEBUG("Setting reparse data on \"%ls\"", path);
1218                 ret = win32_set_reparse_data(hFile, inode->i_reparse_tag,
1219                                              unnamed_stream_lte, path);
1220                 if (ret)
1221                         return ret;
1222         }
1223
1224         if (inode->i_attributes & FILE_ATTRIBUTE_COMPRESSED) {
1225                 DEBUG("Setting compression flag on \"%ls\"", path);
1226                 ret = win32_set_compressed(hFile, path);
1227                 if (ret)
1228                         return ret;
1229         }
1230
1231         if (inode->i_attributes & FILE_ATTRIBUTE_SPARSE_FILE) {
1232                 DEBUG("Setting sparse flag on \"%ls\"", path);
1233                 ret = win32_set_sparse(hFile, path);
1234                 if (ret)
1235                         return ret;
1236         }
1237         return 0;
1238 }
1239
1240 static int
1241 win32_extract_stream(const struct wim_inode *inode,
1242                      const wchar_t *path,
1243                      const wchar_t *stream_name_utf16,
1244                      struct wim_lookup_table_entry *lte)
1245 {
1246         wchar_t *stream_path;
1247         HANDLE h;
1248         int ret;
1249         DWORD err;
1250         DWORD creationDisposition = CREATE_ALWAYS;
1251
1252         if (stream_name_utf16) {
1253                 /* Named stream.  Create a buffer that contains the UTF-16LE
1254                  * string [.\]@path:@stream_name_utf16.  This is needed to
1255                  * create and open the stream using CreateFileW().  I'm not
1256                  * aware of any other APIs to do this.  Note: the '$DATA' suffix
1257                  * seems to be unneeded.  Additional note: a "./" prefix needs
1258                  * to be added when the path is not absolute to avoid ambiguity
1259                  * with drive letters. */
1260                 size_t stream_path_nchars;
1261                 size_t path_nchars;
1262                 size_t stream_name_nchars;
1263                 const wchar_t *prefix;
1264
1265                 path_nchars = wcslen(path);
1266                 stream_name_nchars = wcslen(stream_name_utf16);
1267                 stream_path_nchars = path_nchars + 1 + stream_name_nchars;
1268                 if (path[0] != cpu_to_le16(L'\0') &&
1269                     path[0] != cpu_to_le16(L'/') &&
1270                     path[0] != cpu_to_le16(L'\\') &&
1271                     path[1] != cpu_to_le16(L':'))
1272                 {
1273                         prefix = L"./";
1274                         stream_path_nchars += 2;
1275                 } else {
1276                         prefix = L"";
1277                 }
1278                 stream_path = alloca((stream_path_nchars + 1) * sizeof(wchar_t));
1279                 swprintf(stream_path, L"%ls%ls:%ls",
1280                          prefix, path, stream_name_utf16);
1281         } else {
1282                 /* Unnamed stream; its path is just the path to the file itself.
1283                  * */
1284                 stream_path = (wchar_t*)path;
1285
1286                 /* Directories must be created with CreateDirectoryW().  Then
1287                  * the call to CreateFileW() will merely open the directory that
1288                  * was already created rather than creating a new file. */
1289                 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1290                         if (!CreateDirectoryW(stream_path, NULL)) {
1291                                 err = GetLastError();
1292                                 switch (err) {
1293                                 case ERROR_ALREADY_EXISTS:
1294                                         break;
1295                                 case ERROR_ACCESS_DENIED:
1296                                         if (path_is_root_of_drive(path))
1297                                                 break;
1298                                         /* Fall through */
1299                                 default:
1300                                         ERROR("Failed to create directory \"%ls\"",
1301                                               stream_path);
1302                                         win32_error(err);
1303                                         ret = WIMLIB_ERR_MKDIR;
1304                                         goto fail;
1305                                 }
1306                         }
1307                         DEBUG("Created directory \"%ls\"", stream_path);
1308                         if (!inode_has_special_attributes(inode)) {
1309                                 ret = 0;
1310                                 goto out;
1311                         }
1312                         creationDisposition = OPEN_EXISTING;
1313                 }
1314         }
1315
1316         DEBUG("Opening \"%ls\"", stream_path);
1317         h = CreateFileW(stream_path,
1318                         GENERIC_READ | GENERIC_WRITE,
1319                         0,
1320                         NULL,
1321                         creationDisposition,
1322                         win32_get_create_flags_and_attributes(inode->i_attributes),
1323                         NULL);
1324         if (h == INVALID_HANDLE_VALUE) {
1325                 err = GetLastError();
1326                 ERROR("Failed to create \"%ls\"", stream_path);
1327                 win32_error(err);
1328                 ret = WIMLIB_ERR_OPEN;
1329                 goto fail;
1330         }
1331
1332         if (stream_name_utf16 == NULL && inode_has_special_attributes(inode)) {
1333                 ret = win32_set_special_attributes(h, inode, lte, path);
1334                 if (ret)
1335                         goto fail_close_handle;
1336         }
1337
1338         if (!(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
1339                 if (lte) {
1340                         DEBUG("Extracting \"%ls\" (len = %"PRIu64")",
1341                               stream_path, wim_resource_size(lte));
1342                         ret = do_win32_extract_stream(h, lte);
1343                         if (ret)
1344                                 goto fail_close_handle;
1345                 }
1346         }
1347
1348         DEBUG("Closing \"%ls\"", stream_path);
1349         if (!CloseHandle(h)) {
1350                 err = GetLastError();
1351                 ERROR("Failed to close \"%ls\"", stream_path);
1352                 win32_error(err);
1353                 ret = WIMLIB_ERR_WRITE;
1354                 goto fail;
1355         }
1356         ret = 0;
1357         goto out;
1358 fail_close_handle:
1359         CloseHandle(h);
1360 fail:
1361         ERROR("Error extracting %ls", stream_path);
1362 out:
1363         return ret;
1364 }
1365
1366 /*
1367  * Creates a file, directory, or reparse point and extracts all streams to it
1368  * (unnamed data stream and/or reparse point stream, plus any alternate data
1369  * streams).  This in Win32-specific code.
1370  *
1371  * @inode:      WIM inode for this file or directory.
1372  * @path:       UTF-16LE external path to extract the inode to.
1373  *
1374  * Returns 0 on success; nonzero on failure.
1375  */
1376 static int
1377 win32_extract_streams(const struct wim_inode *inode,
1378                       const wchar_t *path, u64 *completed_bytes_p)
1379 {
1380         struct wim_lookup_table_entry *unnamed_lte;
1381         int ret;
1382
1383         unnamed_lte = inode_unnamed_lte_resolved(inode);
1384         ret = win32_extract_stream(inode, path, NULL, unnamed_lte);
1385         if (ret)
1386                 goto out;
1387         if (unnamed_lte)
1388                 *completed_bytes_p += wim_resource_size(unnamed_lte);
1389         for (u16 i = 0; i < inode->i_num_ads; i++) {
1390                 const struct wim_ads_entry *ads_entry = &inode->i_ads_entries[i];
1391                 if (ads_entry->stream_name_nbytes != 0) {
1392                         /* Skip special UNIX data entries (see documentation for
1393                          * WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA) */
1394                         if (ads_entry->stream_name_nbytes == WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES
1395                             && !memcmp(ads_entry->stream_name,
1396                                        WIMLIB_UNIX_DATA_TAG_UTF16LE,
1397                                        WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES))
1398                                 continue;
1399                         ret = win32_extract_stream(inode,
1400                                                    path,
1401                                                    ads_entry->stream_name,
1402                                                    ads_entry->lte);
1403                         if (ret)
1404                                 break;
1405                         if (ads_entry->lte)
1406                                 *completed_bytes_p += wim_resource_size(ads_entry->lte);
1407                 }
1408         }
1409 out:
1410         return ret;
1411 }
1412
1413 /* Extract a file, directory, reparse point, or hard link to an
1414  * already-extracted file using the Win32 API */
1415 int
1416 win32_do_apply_dentry(const wchar_t *output_path,
1417                       size_t output_path_num_chars,
1418                       struct wim_dentry *dentry,
1419                       struct apply_args *args)
1420 {
1421         int ret;
1422         struct wim_inode *inode = dentry->d_inode;
1423         DWORD err;
1424
1425         if (inode->i_nlink > 1 && inode->i_extracted_file != NULL) {
1426                 /* Linked file, with another name already extracted.  Create a
1427                  * hard link. */
1428                 DEBUG("Creating hard link \"%ls => %ls\"",
1429                       output_path, inode->i_extracted_file);
1430                 if (!CreateHardLinkW(output_path, inode->i_extracted_file, NULL)) {
1431                         err = GetLastError();
1432                         ERROR("Can't create hard link \"%ls => %ls\"",
1433                               output_path, inode->i_extracted_file);
1434                         win32_error(err);
1435                         return WIMLIB_ERR_LINK;
1436                 }
1437         } else {
1438                 /* Create the file, directory, or reparse point, and extract the
1439                  * data streams. */
1440                 ret = win32_extract_streams(inode, output_path,
1441                                             &args->progress.extract.completed_bytes);
1442                 if (ret)
1443                         return ret;
1444
1445                 if (inode->i_security_id >= 0 &&
1446                     !(args->extract_flags & WIMLIB_EXTRACT_FLAG_NO_ACLS))
1447                 {
1448                         ret = win32_set_security_data(inode, output_path, args);
1449                         if (ret)
1450                                 return ret;
1451                 }
1452                 if (inode->i_nlink > 1) {
1453                         /* Save extracted path for a later call to
1454                          * CreateHardLinkW() if this inode has multiple links.
1455                          * */
1456                         inode->i_extracted_file = WSTRDUP(output_path);
1457                         if (!inode->i_extracted_file)
1458                                 ret = WIMLIB_ERR_NOMEM;
1459                 }
1460         }
1461         return 0;
1462 }
1463
1464 /* Set timestamps on an extracted file using the Win32 API */
1465 int
1466 win32_do_apply_dentry_timestamps(const wchar_t *path,
1467                                  size_t path_num_chars,
1468                                  const struct wim_dentry *dentry,
1469                                  const struct apply_args *args)
1470 {
1471         DWORD err;
1472         HANDLE h;
1473         const struct wim_inode *inode = dentry->d_inode;
1474
1475         DEBUG("Opening \"%ls\" to set timestamps", path);
1476         h = win32_open_existing_file(path, FILE_WRITE_ATTRIBUTES);
1477         if (h == INVALID_HANDLE_VALUE) {
1478                 err = GetLastError();
1479                 goto fail;
1480         }
1481
1482         FILETIME creationTime = {.dwLowDateTime = inode->i_creation_time & 0xffffffff,
1483                                  .dwHighDateTime = inode->i_creation_time >> 32};
1484         FILETIME lastAccessTime = {.dwLowDateTime = inode->i_last_access_time & 0xffffffff,
1485                                   .dwHighDateTime = inode->i_last_access_time >> 32};
1486         FILETIME lastWriteTime = {.dwLowDateTime = inode->i_last_write_time & 0xffffffff,
1487                                   .dwHighDateTime = inode->i_last_write_time >> 32};
1488
1489         DEBUG("Calling SetFileTime() on \"%ls\"", path);
1490         if (!SetFileTime(h, &creationTime, &lastAccessTime, &lastWriteTime)) {
1491                 err = GetLastError();
1492                 CloseHandle(h);
1493                 goto fail;
1494         }
1495         DEBUG("Closing \"%ls\"", path);
1496         if (!CloseHandle(h)) {
1497                 err = GetLastError();
1498                 goto fail;
1499         }
1500         goto out;
1501 fail:
1502         /* Only warn if setting timestamps failed; still return 0. */
1503         WARNING("Can't set timestamps on \"%ls\"", path);
1504         win32_error(err);
1505 out:
1506         return 0;
1507 }
1508
1509 /* Replacement for POSIX fsync() */
1510 int
1511 fsync(int fd)
1512 {
1513         DWORD err;
1514         HANDLE h;
1515
1516         h = (HANDLE)_get_osfhandle(fd);
1517         if (h == INVALID_HANDLE_VALUE) {
1518                 err = GetLastError();
1519                 ERROR("Could not get Windows handle for file descriptor");
1520                 win32_error(err);
1521                 errno = EBADF;
1522                 return -1;
1523         }
1524         if (!FlushFileBuffers(h)) {
1525                 err = GetLastError();
1526                 ERROR("Could not flush file buffers to disk");
1527                 win32_error(err);
1528                 errno = EIO;
1529                 return -1;
1530         }
1531         return 0;
1532 }
1533
1534 /* Use the Win32 API to get the number of processors */
1535 unsigned
1536 win32_get_number_of_processors()
1537 {
1538         SYSTEM_INFO sysinfo;
1539         GetSystemInfo(&sysinfo);
1540         return sysinfo.dwNumberOfProcessors;
1541 }
1542
1543 /* Replacement for POSIX-2008 realpath().  Warning: partial functionality only
1544  * (resolved_path must be NULL).   Also I highly doubt that GetFullPathName
1545  * really does the right thing under all circumstances. */
1546 wchar_t *
1547 realpath(const wchar_t *path, wchar_t *resolved_path)
1548 {
1549         DWORD ret;
1550         wimlib_assert(resolved_path == NULL);
1551         DWORD err;
1552
1553         ret = GetFullPathNameW(path, 0, NULL, NULL);
1554         if (!ret) {
1555                 err = GetLastError();
1556                 goto fail_win32;
1557         }
1558
1559         resolved_path = TMALLOC(ret);
1560         if (!resolved_path)
1561                 goto out;
1562         ret = GetFullPathNameW(path, ret, resolved_path, NULL);
1563         if (!ret) {
1564                 err = GetLastError();
1565                 free(resolved_path);
1566                 resolved_path = NULL;
1567                 goto fail_win32;
1568         }
1569         goto out;
1570 fail_win32:
1571         win32_error(err);
1572         errno = -1;
1573 out:
1574         return resolved_path;
1575 }
1576
1577 /* rename() on Windows fails if the destination file exists.  And we need to
1578  * make it work on wide characters.  Fix it. */
1579 int
1580 win32_rename_replacement(const wchar_t *oldpath, const wchar_t *newpath)
1581 {
1582         if (MoveFileExW(oldpath, newpath, MOVEFILE_REPLACE_EXISTING)) {
1583                 return 0;
1584         } else {
1585                 /* As usual, the possible error values are not documented */
1586                 DWORD err = GetLastError();
1587                 ERROR("MoveFileEx(): Can't rename \"%ls\" to \"%ls\"",
1588                       oldpath, newpath);
1589                 win32_error(err);
1590                 errno = -1;
1591                 return -1;
1592         }
1593 }
1594
1595 /* Replacement for POSIX fnmatch() (partial functionality only) */
1596 int
1597 fnmatch(const wchar_t *pattern, const wchar_t *string, int flags)
1598 {
1599         if (PathMatchSpecW(string, pattern))
1600                 return 0;
1601         else
1602                 return FNM_NOMATCH;
1603 }
1604
1605 /* truncate() replacement */
1606 int
1607 win32_truncate_replacement(const wchar_t *path, off_t size)
1608 {
1609         DWORD err = NO_ERROR;
1610         LARGE_INTEGER liOffset;
1611
1612         HANDLE h = win32_open_existing_file(path, GENERIC_WRITE);
1613         if (h == INVALID_HANDLE_VALUE)
1614                 goto fail;
1615
1616         liOffset.QuadPart = size;
1617         if (!SetFilePointerEx(h, liOffset, NULL, FILE_BEGIN))
1618                 goto fail_close_handle;
1619
1620         if (!SetEndOfFile(h))
1621                 goto fail_close_handle;
1622         CloseHandle(h);
1623         return 0;
1624
1625 fail_close_handle:
1626         err = GetLastError();
1627         CloseHandle(h);
1628 fail:
1629         if (err == NO_ERROR)
1630                 err = GetLastError();
1631         ERROR("Can't truncate \"%ls\" to %"PRIu64" bytes", path, size);
1632         win32_error(err);
1633         errno = -1;
1634         return -1;
1635 }
1636
1637
1638 /* This really could be replaced with _wcserror_s, but this doesn't seem to
1639  * actually be available in MSVCRT.DLL on Windows XP (perhaps it's statically
1640  * linked in by Visual Studio...?). */
1641 extern int
1642 win32_strerror_r_replacement(int errnum, wchar_t *buf, size_t buflen)
1643 {
1644         static pthread_mutex_t strerror_lock = PTHREAD_MUTEX_INITIALIZER;
1645
1646         pthread_mutex_lock(&strerror_lock);
1647         mbstowcs(buf, strerror(errnum), buflen);
1648         buf[buflen - 1] = '\0';
1649         pthread_mutex_unlock(&strerror_lock);
1650         return 0;
1651 }
1652
1653 #endif /* __WIN32__ */