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