win32: handle excluded reparse points correctly
[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 "buffer_io.h"
43 #include <pthread.h>
44
45 #include <errno.h>
46
47 #define MAX_GET_SD_ACCESS_DENIED_WARNINGS 1
48 #define MAX_GET_SACL_PRIV_NOTHELD_WARNINGS 1
49 #define MAX_CREATE_HARD_LINK_WARNINGS 5
50 struct win32_capture_state {
51         unsigned long num_get_sd_access_denied;
52         unsigned long num_get_sacl_priv_notheld;
53 };
54
55 #define MAX_SET_SD_ACCESS_DENIED_WARNINGS 1
56 #define MAX_SET_SACL_PRIV_NOTHELD_WARNINGS 1
57
58 #ifdef ENABLE_ERROR_MESSAGES
59 static void
60 win32_error(u32 err_code)
61 {
62         wchar_t *buffer;
63         DWORD nchars;
64         nchars = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
65                                     FORMAT_MESSAGE_ALLOCATE_BUFFER,
66                                 NULL, err_code, 0,
67                                 (wchar_t*)&buffer, 0, NULL);
68         if (nchars == 0) {
69                 ERROR("Error printing error message! "
70                       "Computer will self-destruct in 3 seconds.");
71         } else {
72                 ERROR("Win32 error: %ls", buffer);
73                 LocalFree(buffer);
74         }
75 }
76 #else /* ENABLE_ERROR_MESSAGES */
77 #  define win32_error(err_code)
78 #endif /* !ENABLE_ERROR_MESSAGES */
79
80 /* Pointers to functions that are not available on all targetted versions of
81  * Windows (XP and later).  NOTE: The WINAPI annotations seem to be important; I
82  * assume it specifies a certain calling convention. */
83
84 /* Vista and later */
85 static HANDLE (WINAPI *win32func_FindFirstStreamW)(LPCWSTR lpFileName,
86                                             STREAM_INFO_LEVELS InfoLevel,
87                                             LPVOID lpFindStreamData,
88                                             DWORD dwFlags) = NULL;
89
90 /* Vista and later */
91 static BOOL (WINAPI *win32func_FindNextStreamW)(HANDLE hFindStream,
92                                          LPVOID lpFindStreamData) = NULL;
93
94 static HMODULE hKernel32 = NULL;
95
96 /* Try to dynamically load some functions */
97 void
98 win32_global_init()
99 {
100         DWORD err;
101
102         if (hKernel32 == NULL) {
103                 DEBUG("Loading Kernel32.dll");
104                 hKernel32 = LoadLibraryW(L"Kernel32.dll");
105                 if (hKernel32 == NULL) {
106                         err = GetLastError();
107                         WARNING("Can't load Kernel32.dll");
108                         win32_error(err);
109                         return;
110                 }
111         }
112
113         DEBUG("Looking for FindFirstStreamW");
114         win32func_FindFirstStreamW = (void*)GetProcAddress(hKernel32, "FindFirstStreamW");
115         if (!win32func_FindFirstStreamW) {
116                 WARNING("Could not find function FindFirstStreamW() in Kernel32.dll!");
117                 WARNING("Capturing alternate data streams will not be supported.");
118                 return;
119         }
120
121         DEBUG("Looking for FindNextStreamW");
122         win32func_FindNextStreamW = (void*)GetProcAddress(hKernel32, "FindNextStreamW");
123         if (!win32func_FindNextStreamW) {
124                 WARNING("Could not find function FindNextStreamW() in Kernel32.dll!");
125                 WARNING("Capturing alternate data streams will not be supported.");
126                 win32func_FindFirstStreamW = NULL;
127         }
128 }
129
130 void
131 win32_global_cleanup()
132 {
133         if (hKernel32 != NULL) {
134                 DEBUG("Closing Kernel32.dll");
135                 FreeLibrary(hKernel32);
136                 hKernel32 = NULL;
137         }
138 }
139
140 static const wchar_t *capture_access_denied_msg =
141 L"         If you are not running this program as the administrator, you may\n"
142  "         need to do so, so that all data and metadata can be backed up.\n"
143  "         Otherwise, there may be no way to access the desired data or\n"
144  "         metadata without taking ownership of the file or directory.\n"
145  ;
146
147 static const wchar_t *apply_access_denied_msg =
148 L"If you are not running this program as the administrator, you may\n"
149  "          need to do so, so that all data and metadata can be extracted\n"
150  "          exactly as the origignal copy.  However, if you do not care that\n"
151  "          the security descriptors are extracted correctly, you could run\n"
152  "          `wimlib-imagex apply' with the --no-acls flag instead.\n"
153  ;
154
155 static HANDLE
156 win32_open_existing_file(const wchar_t *path, DWORD dwDesiredAccess)
157 {
158         return CreateFileW(path,
159                            dwDesiredAccess,
160                            FILE_SHARE_READ,
161                            NULL, /* lpSecurityAttributes */
162                            OPEN_EXISTING,
163                            FILE_FLAG_BACKUP_SEMANTICS |
164                                FILE_FLAG_OPEN_REPARSE_POINT,
165                            NULL /* hTemplateFile */);
166 }
167
168 HANDLE
169 win32_open_file_data_only(const wchar_t *path)
170 {
171         return win32_open_existing_file(path, FILE_READ_DATA);
172 }
173
174 int
175 read_win32_file_prefix(const struct wim_lookup_table_entry *lte,
176                        u64 size,
177                        consume_data_callback_t cb,
178                        void *ctx_or_buf,
179                        int _ignored_flags)
180 {
181         int ret = 0;
182         void *out_buf;
183         DWORD err;
184         u64 bytes_remaining;
185
186         HANDLE hFile = win32_open_file_data_only(lte->file_on_disk);
187         if (hFile == INVALID_HANDLE_VALUE) {
188                 err = GetLastError();
189                 ERROR("Failed to open \"%ls\"", lte->file_on_disk);
190                 win32_error(err);
191                 return WIMLIB_ERR_OPEN;
192         }
193
194         if (cb)
195                 out_buf = alloca(WIM_CHUNK_SIZE);
196         else
197                 out_buf = ctx_or_buf;
198
199         bytes_remaining = size;
200         while (bytes_remaining) {
201                 DWORD bytesToRead, bytesRead;
202
203                 bytesToRead = min(WIM_CHUNK_SIZE, bytes_remaining);
204                 if (!ReadFile(hFile, out_buf, bytesToRead, &bytesRead, NULL) ||
205                     bytesRead != bytesToRead)
206                 {
207                         err = GetLastError();
208                         ERROR("Failed to read data from \"%ls\"", lte->file_on_disk);
209                         win32_error(err);
210                         ret = WIMLIB_ERR_READ;
211                         break;
212                 }
213                 bytes_remaining -= bytesRead;
214                 if (cb) {
215                         ret = (*cb)(out_buf, bytesRead, ctx_or_buf);
216                         if (ret)
217                                 break;
218                 } else {
219                         out_buf += bytesRead;
220                 }
221         }
222         CloseHandle(hFile);
223         return ret;
224 }
225
226 struct win32_encrypted_read_ctx {
227         consume_data_callback_t read_prefix_cb;
228         void *read_prefix_ctx_or_buf;
229         int wimlib_err_code;
230         void *buf;
231         size_t buf_filled;
232         u64 bytes_remaining;
233 };
234
235 static DWORD WINAPI
236 win32_encrypted_export_cb(unsigned char *_data, void *_ctx, unsigned long len)
237 {
238         const void *data = _data;
239         struct win32_encrypted_read_ctx *ctx = _ctx;
240         int ret;
241
242         DEBUG("len = %lu", len);
243         if (ctx->read_prefix_cb) {
244                 /* The length of the buffer passed to the ReadEncryptedFileRaw()
245                  * export callback is undocumented, so we assume it may be of
246                  * arbitrary size. */
247                 size_t bytes_to_buffer = min(ctx->bytes_remaining - ctx->buf_filled,
248                                              len);
249                 while (bytes_to_buffer) {
250                         size_t bytes_to_copy_to_buf =
251                                 min(bytes_to_buffer, WIM_CHUNK_SIZE - ctx->buf_filled);
252
253                         memcpy(ctx->buf + ctx->buf_filled, data,
254                                bytes_to_copy_to_buf);
255                         ctx->buf_filled += bytes_to_copy_to_buf;
256                         data += bytes_to_copy_to_buf;
257                         bytes_to_buffer -= bytes_to_copy_to_buf;
258
259                         if (ctx->buf_filled == WIM_CHUNK_SIZE ||
260                             ctx->buf_filled == ctx->bytes_remaining)
261                         {
262                                 ret = (*ctx->read_prefix_cb)(ctx->buf,
263                                                              ctx->buf_filled,
264                                                              ctx->read_prefix_ctx_or_buf);
265                                 if (ret) {
266                                         ctx->wimlib_err_code = ret;
267                                         /* Shouldn't matter what error code is returned
268                                          * here, as long as it isn't ERROR_SUCCESS. */
269                                         return ERROR_READ_FAULT;
270                                 }
271                                 ctx->bytes_remaining -= ctx->buf_filled;
272                                 ctx->buf_filled = 0;
273                         }
274                 }
275         } else {
276                 size_t len_to_copy = min(len, ctx->bytes_remaining);
277                 memcpy(ctx->read_prefix_ctx_or_buf, data, len_to_copy);
278                 ctx->bytes_remaining -= len_to_copy;
279                 ctx->read_prefix_ctx_or_buf += len_to_copy;
280         }
281         return ERROR_SUCCESS;
282 }
283
284 int
285 read_win32_encrypted_file_prefix(const struct wim_lookup_table_entry *lte,
286                                  u64 size,
287                                  consume_data_callback_t cb,
288                                  void *ctx_or_buf,
289                                  int _ignored_flags)
290 {
291         struct win32_encrypted_read_ctx export_ctx;
292         DWORD err;
293         void *file_ctx;
294         int ret;
295
296         DEBUG("Reading %"PRIu64" bytes from encryted file \"%ls\"",
297               size, lte->file_on_disk);
298
299         export_ctx.read_prefix_cb = cb;
300         export_ctx.read_prefix_ctx_or_buf = ctx_or_buf;
301         export_ctx.wimlib_err_code = 0;
302         if (cb) {
303                 export_ctx.buf = MALLOC(WIM_CHUNK_SIZE);
304                 if (!export_ctx.buf)
305                         return WIMLIB_ERR_NOMEM;
306         } else {
307                 export_ctx.buf = NULL;
308         }
309         export_ctx.bytes_remaining = size;
310
311         err = OpenEncryptedFileRawW(lte->file_on_disk, 0, &file_ctx);
312         if (err != ERROR_SUCCESS) {
313                 ERROR("Failed to open encrypted file \"%ls\" for raw read",
314                       lte->file_on_disk);
315                 win32_error(err);
316                 ret = WIMLIB_ERR_OPEN;
317                 goto out_free_buf;
318         }
319         err = ReadEncryptedFileRaw(win32_encrypted_export_cb,
320                                    &export_ctx, file_ctx);
321         if (err != ERROR_SUCCESS) {
322                 ERROR("Failed to read encrypted file \"%ls\"",
323                       lte->file_on_disk);
324                 win32_error(err);
325                 ret = export_ctx.wimlib_err_code;
326                 if (ret == 0)
327                         ret = WIMLIB_ERR_READ;
328         } else if (export_ctx.bytes_remaining != 0) {
329                 ERROR("Only could read %"PRIu64" of %"PRIu64" bytes from "
330                       "encryted file \"%ls\"",
331                       size - export_ctx.bytes_remaining, size,
332                       lte->file_on_disk);
333                 ret = WIMLIB_ERR_READ;
334         } else {
335                 ret = 0;
336         }
337         CloseEncryptedFileRaw(file_ctx);
338 out_free_buf:
339         FREE(export_ctx.buf);
340         return ret;
341 }
342
343 /* Given a path, which may not yet exist, get a set of flags that describe the
344  * features of the volume the path is on. */
345 static int
346 win32_get_vol_flags(const wchar_t *path, unsigned *vol_flags_ret)
347 {
348         wchar_t *volume;
349         BOOL bret;
350         DWORD vol_flags;
351
352         if (path[0] != L'\0' && path[0] != L'\\' &&
353             path[0] != L'/' && path[1] == L':')
354         {
355                 /* Path starts with a drive letter; use it. */
356                 volume = alloca(4 * sizeof(wchar_t));
357                 volume[0] = path[0];
358                 volume[1] = path[1];
359                 volume[2] = L'\\';
360                 volume[3] = L'\0';
361         } else {
362                 /* Path does not start with a drive letter; use the volume of
363                  * the current working directory. */
364                 volume = NULL;
365         }
366         bret = GetVolumeInformationW(volume, /* lpRootPathName */
367                                      NULL,  /* lpVolumeNameBuffer */
368                                      0,     /* nVolumeNameSize */
369                                      NULL,  /* lpVolumeSerialNumber */
370                                      NULL,  /* lpMaximumComponentLength */
371                                      &vol_flags, /* lpFileSystemFlags */
372                                      NULL,  /* lpFileSystemNameBuffer */
373                                      0);    /* nFileSystemNameSize */
374         if (!bret) {
375                 DWORD err = GetLastError();
376                 WARNING("Failed to get volume information for path \"%ls\"", path);
377                 win32_error(err);
378                 vol_flags = 0xffffffff;
379         }
380
381         DEBUG("using vol_flags = %x", vol_flags);
382         *vol_flags_ret = vol_flags;
383         return 0;
384 }
385
386
387 static u64
388 FILETIME_to_u64(const FILETIME *ft)
389 {
390         return ((u64)ft->dwHighDateTime << 32) | (u64)ft->dwLowDateTime;
391 }
392
393 static int
394 win32_get_short_name(struct wim_dentry *dentry, const wchar_t *path)
395 {
396         WIN32_FIND_DATAW dat;
397         HANDLE hFind;
398         int ret = 0;
399
400         /* If we can't read the short filename for some reason, we just ignore
401          * the error and assume the file has no short name.  I don't think this
402          * should be an issue, since the short names are essentially obsolete
403          * anyway. */
404         hFind = FindFirstFileW(path, &dat);
405         if (hFind != INVALID_HANDLE_VALUE) {
406                 if (dat.cAlternateFileName[0] != L'\0') {
407                         DEBUG("\"%ls\": short name \"%ls\"", path, dat.cAlternateFileName);
408                         size_t short_name_nbytes = wcslen(dat.cAlternateFileName) *
409                                                    sizeof(wchar_t);
410                         size_t n = short_name_nbytes + sizeof(wchar_t);
411                         dentry->short_name = MALLOC(n);
412                         if (dentry->short_name) {
413                                 memcpy(dentry->short_name, dat.cAlternateFileName, n);
414                                 dentry->short_name_nbytes = short_name_nbytes;
415                         } else {
416                                 ret = WIMLIB_ERR_NOMEM;
417                         }
418                 }
419                 FindClose(hFind);
420         }
421         return ret;
422 }
423
424 static int
425 win32_get_security_descriptor(struct wim_dentry *dentry,
426                               struct sd_set *sd_set,
427                               const wchar_t *path,
428                               struct win32_capture_state *state,
429                               int add_image_flags)
430 {
431         SECURITY_INFORMATION requestedInformation;
432         DWORD lenNeeded = 0;
433         BOOL status;
434         DWORD err;
435         unsigned long n;
436
437         requestedInformation = DACL_SECURITY_INFORMATION |
438                                SACL_SECURITY_INFORMATION |
439                                OWNER_SECURITY_INFORMATION |
440                                GROUP_SECURITY_INFORMATION;
441 again:
442         /* Request length of security descriptor */
443         status = GetFileSecurityW(path, requestedInformation,
444                                   NULL, 0, &lenNeeded);
445         err = GetLastError();
446         if (!status && err == ERROR_INSUFFICIENT_BUFFER) {
447                 DWORD len = lenNeeded;
448                 char buf[len];
449                 if (GetFileSecurityW(path, requestedInformation,
450                                      (PSECURITY_DESCRIPTOR)buf, len, &lenNeeded))
451                 {
452                         int security_id = sd_set_add_sd(sd_set, buf, len);
453                         if (security_id < 0)
454                                 return WIMLIB_ERR_NOMEM;
455                         else {
456                                 dentry->d_inode->i_security_id = security_id;
457                                 return 0;
458                         }
459                 } else {
460                         err = GetLastError();
461                 }
462         }
463
464         if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_STRICT_ACLS)
465                 goto fail;
466
467         switch (err) {
468         case ERROR_PRIVILEGE_NOT_HELD:
469                 if (requestedInformation & SACL_SECURITY_INFORMATION) {
470                         n = state->num_get_sacl_priv_notheld++;
471                         requestedInformation &= ~SACL_SECURITY_INFORMATION;
472                         if (n < MAX_GET_SACL_PRIV_NOTHELD_WARNINGS) {
473                                 WARNING(
474 "We don't have enough privileges to read the full security\n"
475 "          descriptor of \"%ls\"!\n"
476 "          Re-trying with SACL omitted.\n", path);
477                         } else if (n == MAX_GET_SACL_PRIV_NOTHELD_WARNINGS) {
478                                 WARNING(
479 "Suppressing further privileges not held error messages when reading\n"
480 "          security descriptors.");
481                         }
482                         goto again;
483                 }
484                 /* Fall through */
485         case ERROR_ACCESS_DENIED:
486                 n = state->num_get_sd_access_denied++;
487                 if (n < MAX_GET_SD_ACCESS_DENIED_WARNINGS) {
488                         WARNING("Failed to read security descriptor of \"%ls\": "
489                                 "Access denied!\n%ls", path, capture_access_denied_msg);
490                 } else if (n == MAX_GET_SD_ACCESS_DENIED_WARNINGS) {
491                         WARNING("Suppressing further access denied errors messages i"
492                                 "when reading security descriptors");
493                 }
494                 return 0;
495         default:
496 fail:
497                 ERROR("Failed to read security descriptor of \"%ls\"", path);
498                 win32_error(err);
499                 return WIMLIB_ERR_READ;
500         }
501 }
502
503 static int
504 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
505                                   wchar_t *path,
506                                   size_t path_num_chars,
507                                   struct add_image_params *params,
508                                   struct win32_capture_state *state,
509                                   unsigned vol_flags);
510
511 /* Reads the directory entries of directory using a Win32 API and recursively
512  * calls win32_build_dentry_tree() on them. */
513 static int
514 win32_recurse_directory(struct wim_dentry *root,
515                         wchar_t *dir_path,
516                         size_t dir_path_num_chars,
517                         struct add_image_params *params,
518                         struct win32_capture_state *state,
519                         unsigned vol_flags)
520 {
521         WIN32_FIND_DATAW dat;
522         HANDLE hFind;
523         DWORD err;
524         int ret;
525
526         DEBUG("Recurse to directory \"%ls\"", dir_path);
527
528         /* Begin reading the directory by calling FindFirstFileW.  Unlike UNIX
529          * opendir(), FindFirstFileW has file globbing built into it.  But this
530          * isn't what we actually want, so just add a dummy glob to get all
531          * entries. */
532         dir_path[dir_path_num_chars] = L'/';
533         dir_path[dir_path_num_chars + 1] = L'*';
534         dir_path[dir_path_num_chars + 2] = L'\0';
535         hFind = FindFirstFileW(dir_path, &dat);
536         dir_path[dir_path_num_chars] = L'\0';
537
538         if (hFind == INVALID_HANDLE_VALUE) {
539                 err = GetLastError();
540                 if (err == ERROR_FILE_NOT_FOUND) {
541                         return 0;
542                 } else {
543                         ERROR("Failed to read directory \"%ls\"", dir_path);
544                         win32_error(err);
545                         return WIMLIB_ERR_READ;
546                 }
547         }
548         ret = 0;
549         do {
550                 /* Skip . and .. entries */
551                 if (dat.cFileName[0] == L'.' &&
552                     (dat.cFileName[1] == L'\0' ||
553                      (dat.cFileName[1] == L'.' &&
554                       dat.cFileName[2] == L'\0')))
555                         continue;
556                 size_t filename_len = wcslen(dat.cFileName);
557
558                 dir_path[dir_path_num_chars] = L'/';
559                 wmemcpy(dir_path + dir_path_num_chars + 1,
560                         dat.cFileName,
561                         filename_len + 1);
562
563                 struct wim_dentry *child;
564                 size_t path_len = dir_path_num_chars + 1 + filename_len;
565                 ret = win32_build_dentry_tree_recursive(&child,
566                                                         dir_path,
567                                                         path_len,
568                                                         params,
569                                                         state,
570                                                         vol_flags);
571                 dir_path[dir_path_num_chars] = L'\0';
572                 if (ret)
573                         goto out_find_close;
574                 if (child)
575                         dentry_add_child(root, child);
576         } while (FindNextFileW(hFind, &dat));
577         err = GetLastError();
578         if (err != ERROR_NO_MORE_FILES) {
579                 ERROR("Failed to read directory \"%ls\"", dir_path);
580                 win32_error(err);
581                 if (ret == 0)
582                         ret = WIMLIB_ERR_READ;
583         }
584 out_find_close:
585         FindClose(hFind);
586         return ret;
587 }
588
589 int
590 win32_get_file_and_vol_ids(const wchar_t *path, u64 *ino_ret, u64 *dev_ret)
591 {
592         HANDLE hFile;
593         DWORD err;
594         BY_HANDLE_FILE_INFORMATION file_info;
595         int ret;
596
597         hFile = win32_open_existing_file(path, FILE_READ_ATTRIBUTES);
598         if (hFile == INVALID_HANDLE_VALUE) {
599                 err = GetLastError();
600                 WARNING("Failed to open \"%ls\" to get file and volume IDs",
601                         path);
602                 win32_error(err);
603                 return WIMLIB_ERR_OPEN;
604         }
605
606         if (!GetFileInformationByHandle(hFile, &file_info)) {
607                 err = GetLastError();
608                 ERROR("Failed to get file information for \"%ls\"", path);
609                 win32_error(err);
610                 ret = WIMLIB_ERR_STAT;
611         } else {
612                 *ino_ret = ((u64)file_info.nFileIndexHigh << 32) |
613                             (u64)file_info.nFileIndexLow;
614                 *dev_ret = file_info.dwVolumeSerialNumber;
615                 ret = 0;
616         }
617         CloseHandle(hFile);
618         return ret;
619 }
620
621 /* Reparse point fixup status code */
622 enum rp_status {
623         /* Reparse point corresponded to an absolute symbolic link or junction
624          * point that pointed outside the directory tree being captured, and
625          * therefore was excluded. */
626         RP_EXCLUDED       = 0x0,
627
628         /* Reparse point was not fixed as it was either a relative symbolic
629          * link, a mount point, or something else we could not understand. */
630         RP_NOT_FIXED      = 0x1,
631
632         /* Reparse point corresponded to an absolute symbolic link or junction
633          * point that pointed inside the directory tree being captured, where
634          * the target was specified by a "full" \??\ prefixed path, and
635          * therefore was fixed to be relative to the root of the directory tree
636          * being captured. */
637         RP_FIXED_FULLPATH = 0x2,
638
639         /* Same as RP_FIXED_FULLPATH, except the absolute link target did not
640          * have the \??\ prefix.  It may have begun with a drive letter though.
641          * */
642         RP_FIXED_ABSPATH  = 0x4,
643
644         /* Either RP_FIXED_FULLPATH or RP_FIXED_ABSPATH. */
645         RP_FIXED          = RP_FIXED_FULLPATH | RP_FIXED_ABSPATH,
646 };
647
648 /* Given the "substitute name" target of a Windows reparse point, try doing a
649  * fixup where we change it to be absolute relative to the root of the directory
650  * tree being captured.
651  *
652  * Note that this is only executed when WIMLIB_ADD_IMAGE_FLAG_RPFIX has been
653  * set.
654  *
655  * @capture_root_ino and @capture_root_dev indicate the inode number and device
656  * of the root of the directory tree being captured.  They are meant to identify
657  * this directory (as an alternative to its actual path, which could potentially
658  * be reached via multiple destinations due to other symbolic links).  This may
659  * not work properly on FAT, which doesn't seem to supply proper inode numbers
660  * or file IDs.  However, FAT doesn't support reparse points so this function
661  * wouldn't even be called anyway.  */
662 static enum rp_status
663 win32_maybe_rpfix_target(wchar_t *target, size_t *target_nchars_p,
664                          u64 capture_root_ino, u64 capture_root_dev)
665 {
666         size_t target_nchars= *target_nchars_p;
667         size_t stripped_chars;
668         wchar_t *orig_target;
669
670         if (target_nchars == 0)
671                 /* Invalid reparse point (empty target) */
672                 return RP_NOT_FIXED;
673
674         if (target[0] == L'\\') {
675                 if (target_nchars >= 2 && target[1] == L'\\') {
676                         /* Probably a volume.  Can't do anything with it. */
677                         DEBUG("Not fixing target (probably a volume)");
678                         return RP_NOT_FIXED;
679                 } else if (target_nchars >= 7 &&
680                            target[1] == '?' &&
681                            target[2] == '?' &&
682                            target[3] == '\\' &&
683                            target[4] != '\0' &&
684                            target[5] == ':' &&
685                            target[6] == '\\')
686                 {
687                         DEBUG("Full style path");
688                         /* Full \??\x:\ style path (may be junction or symlink)
689                          * */
690                         stripped_chars = 6;
691                 } else {
692                         DEBUG("Absolute target without drive letter");
693                         /* Absolute target, without drive letter */
694                         stripped_chars = 0;
695                 }
696         } else if (target_nchars >= 3 &&
697                    target[0] != L'\0' &&
698                    target[1] == L':' &&
699                    target[2] == L'\\')
700         {
701                 DEBUG("Absolute target with drive letter");
702                 /* Absolute target, with drive letter */
703                 stripped_chars = 2;
704         } else {
705                 DEBUG("Relative symlink or other link");
706                 /* Relative symlink or other unexpected format */
707                 return RP_NOT_FIXED;
708         }
709         target[target_nchars] = L'\0';
710         orig_target = target;
711         target = fixup_symlink(target + stripped_chars, capture_root_ino, capture_root_dev);
712         if (!target)
713                 return RP_EXCLUDED;
714         target_nchars = wcslen(target);
715         wmemmove(orig_target + stripped_chars, target, target_nchars + 1);
716         *target_nchars_p = target_nchars + stripped_chars;
717         DEBUG("Fixed reparse point (new target: \"%ls\")", orig_target);
718         if (stripped_chars == 6)
719                 return RP_FIXED_FULLPATH;
720         else
721                 return RP_FIXED_ABSPATH;
722 }
723
724 static enum rp_status
725 win32_try_capture_rpfix(char *rpbuf, DWORD *rpbuflen_p,
726                         u64 capture_root_ino, u64 capture_root_dev)
727 {
728         const char *p_get;
729         char *p_put;
730         u16 substitute_name_offset;
731         u16 substitute_name_len;
732         wchar_t *target;
733         size_t target_nchars;
734         enum rp_status status;
735         u32 rptag;
736         DWORD rpbuflen = *rpbuflen_p;
737
738         if (rpbuflen < 16) /* Invalid reparse point (length too small) */
739                 return RP_NOT_FIXED;
740         p_get = get_u32(rpbuf, &rptag);
741         p_get += 4;
742         p_get = get_u16(p_get, &substitute_name_offset);
743         p_get = get_u16(p_get, &substitute_name_len);
744         p_get += 4;
745         if (rptag == WIM_IO_REPARSE_TAG_SYMLINK) {
746                 if (rpbuflen < 20) /* Invalid reparse point (length too small) */
747                         return RP_NOT_FIXED;
748                 p_get += 4;
749         }
750         if ((DWORD)substitute_name_offset +
751             substitute_name_len + (p_get - rpbuf) > rpbuflen)
752                 /* Invalid reparse point (length too small) */
753                 return RP_NOT_FIXED;
754
755         target = (wchar_t*)&p_get[substitute_name_offset];
756         target_nchars = substitute_name_len / 2;
757         /* Note: target is not necessarily null-terminated */
758
759         status = win32_maybe_rpfix_target(target, &target_nchars,
760                                           capture_root_ino, capture_root_dev);
761         if (status & RP_FIXED) {
762                 size_t target_nbytes = target_nchars * 2;
763                 size_t print_nbytes = target_nbytes;
764                 wchar_t target_copy[target_nchars];
765                 wchar_t *print_name = target_copy;
766
767                 if (status == RP_FIXED_FULLPATH) {
768                         /* "full path", meaning \??\ prefixed.  We should not
769                          * include this prefix in the print name, as it is
770                          * apparently meant for the filesystem driver only. */
771                         print_nbytes -= 8;
772                         print_name += 4;
773                 }
774                 wmemcpy(target_copy, target, target_nchars);
775                 p_put = rpbuf + 8;
776                 p_put = put_u16(p_put, 0); /* Substitute name offset */
777                 p_put = put_u16(p_put, target_nbytes); /* Substitute name length */
778                 p_put = put_u16(p_put, target_nbytes + 2); /* Print name offset */
779                 p_put = put_u16(p_put, print_nbytes); /* Print name length */
780                 if (rptag == WIM_IO_REPARSE_TAG_SYMLINK)
781                         p_put = put_u32(p_put, 1);
782                 p_put = put_bytes(p_put, target_nbytes, target_copy);
783                 p_put = put_u16(p_put, 0);
784                 p_put = put_bytes(p_put, print_nbytes, print_name);
785                 p_put = put_u16(p_put, 0);
786
787                 /* Wrote the end of the reparse data.  Recalculate the length,
788                  * set the length field correctly, and return it. */
789                 rpbuflen = p_put - rpbuf;
790                 put_u16(rpbuf + 4, rpbuflen - 8);
791                 *rpbuflen_p = rpbuflen;
792         }
793         return status;
794 }
795
796 static int
797 win32_get_reparse_data(HANDLE hFile, const wchar_t *path,
798                        struct add_image_params *params,
799                        void *reparse_data, size_t *reparse_data_len_ret)
800 {
801         DWORD bytesReturned;
802         u32 reparse_tag;
803         enum rp_status status;
804
805         DEBUG("Loading reparse data from \"%ls\"", path);
806         if (!DeviceIoControl(hFile, FSCTL_GET_REPARSE_POINT,
807                              NULL, /* "Not used with this operation; set to NULL" */
808                              0, /* "Not used with this operation; set to 0" */
809                              reparse_data, /* "A pointer to a buffer that
810                                                    receives the reparse point data */
811                              REPARSE_POINT_MAX_SIZE, /* "The size of the output
812                                                         buffer, in bytes */
813                              &bytesReturned,
814                              NULL))
815         {
816                 DWORD err = GetLastError();
817                 ERROR("Failed to get reparse data of \"%ls\"", path);
818                 win32_error(err);
819                 return -WIMLIB_ERR_READ;
820         }
821         if (bytesReturned < 8) {
822                 ERROR("Reparse data on \"%ls\" is invalid", path);
823                 return -WIMLIB_ERR_READ;
824         }
825
826         reparse_tag = le32_to_cpu(*(u32*)reparse_data);
827         if (params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_RPFIX &&
828             (reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
829              reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT))
830         {
831                 /* Try doing reparse point fixup */
832                 status = win32_try_capture_rpfix(reparse_data,
833                                                  &bytesReturned,
834                                                  params->capture_root_ino,
835                                                  params->capture_root_dev);
836         } else {
837                 status = RP_NOT_FIXED;
838         }
839         *reparse_data_len_ret = bytesReturned;
840         return status;
841 }
842
843 /* Scans an unnamed or named stream of a Win32 file (not a reparse point
844  * stream); calculates its SHA1 message digest and either creates a `struct
845  * wim_lookup_table_entry' in memory for it, or uses an existing 'struct
846  * wim_lookup_table_entry' for an identical stream.
847  *
848  * @path:               Path to the file (UTF-16LE).
849  *
850  * @path_num_chars:     Number of 2-byte characters in @path.
851  *
852  * @inode:              WIM inode to save the stream into.
853  *
854  * @lookup_table:       Stream lookup table for the WIM.
855  *
856  * @dat:                A `WIN32_FIND_STREAM_DATA' structure that specifies the
857  *                      stream name.
858  *
859  * Returns 0 on success; nonzero on failure.
860  */
861 static int
862 win32_capture_stream(const wchar_t *path,
863                      size_t path_num_chars,
864                      struct wim_inode *inode,
865                      struct wim_lookup_table *lookup_table,
866                      WIN32_FIND_STREAM_DATA *dat)
867 {
868         struct wim_ads_entry *ads_entry;
869         struct wim_lookup_table_entry *lte;
870         int ret;
871         wchar_t *stream_name, *colon;
872         size_t stream_name_nchars;
873         bool is_named_stream;
874         wchar_t *spath;
875         size_t spath_nchars;
876         size_t spath_buf_nbytes;
877         const wchar_t *relpath_prefix;
878         const wchar_t *colonchar;
879
880         DEBUG("Capture \"%ls\" stream \"%ls\"", path, dat->cStreamName);
881
882         /* The stream name should be returned as :NAME:TYPE */
883         stream_name = dat->cStreamName;
884         if (*stream_name != L':')
885                 goto out_invalid_stream_name;
886         stream_name += 1;
887         colon = wcschr(stream_name, L':');
888         if (colon == NULL)
889                 goto out_invalid_stream_name;
890
891         if (wcscmp(colon + 1, L"$DATA")) {
892                 /* Not a DATA stream */
893                 ret = 0;
894                 goto out;
895         }
896
897         *colon = '\0';
898
899         stream_name_nchars = colon - stream_name;
900         is_named_stream = (stream_name_nchars != 0);
901
902         if (is_named_stream) {
903                 /* Allocate an ADS entry for the named stream. */
904                 ads_entry = inode_add_ads_utf16le(inode, stream_name,
905                                                   stream_name_nchars * sizeof(wchar_t));
906                 if (!ads_entry) {
907                         ret = WIMLIB_ERR_NOMEM;
908                         goto out;
909                 }
910         }
911
912         /* If zero length stream, no lookup table entry needed. */
913         if ((u64)dat->StreamSize.QuadPart == 0) {
914                 ret = 0;
915                 goto out;
916         }
917
918         /* Create a UTF-16LE string @spath that gives the filename, then a
919          * colon, then the stream name.  Or, if it's an unnamed stream, just the
920          * filename.  It is MALLOC()'ed so that it can be saved in the
921          * wim_lookup_table_entry if needed.
922          *
923          * As yet another special case, relative paths need to be changed to
924          * begin with an explicit "./" so that, for example, a file t:ads, where
925          * :ads is the part we added, is not interpreted as a file on the t:
926          * drive. */
927         spath_nchars = path_num_chars;
928         relpath_prefix = L"";
929         colonchar = L"";
930         if (is_named_stream) {
931                 spath_nchars += 1 + stream_name_nchars;
932                 colonchar = L":";
933                 if (path_num_chars == 1 &&
934                     path[0] != L'/' &&
935                     path[0] != L'\\')
936                 {
937                         spath_nchars += 2;
938                         relpath_prefix = L"./";
939                 }
940         }
941
942         spath_buf_nbytes = (spath_nchars + 1) * sizeof(wchar_t);
943         spath = MALLOC(spath_buf_nbytes);
944
945         swprintf(spath, L"%ls%ls%ls%ls",
946                  relpath_prefix, path, colonchar, stream_name);
947
948         /* Make a new wim_lookup_table_entry */
949         lte = new_lookup_table_entry();
950         if (!lte) {
951                 ret = WIMLIB_ERR_NOMEM;
952                 goto out_free_spath;
953         }
954         lte->file_on_disk = spath;
955         spath = NULL;
956         if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED && !is_named_stream)
957                 lte->resource_location = RESOURCE_WIN32_ENCRYPTED;
958         else
959                 lte->resource_location = RESOURCE_WIN32;
960         lte->resource_entry.original_size = (u64)dat->StreamSize.QuadPart;
961
962         u32 stream_id;
963         if (is_named_stream) {
964                 stream_id = ads_entry->stream_id;
965                 ads_entry->lte = lte;
966         } else {
967                 stream_id = 0;
968                 inode->i_lte = lte;
969         }
970         lookup_table_insert_unhashed(lookup_table, lte, inode, stream_id);
971         ret = 0;
972 out_free_spath:
973         FREE(spath);
974 out:
975         return ret;
976 out_invalid_stream_name:
977         ERROR("Invalid stream name: \"%ls:%ls\"", path, dat->cStreamName);
978         ret = WIMLIB_ERR_READ;
979         goto out;
980 }
981
982 /* Scans a Win32 file for unnamed and named data streams (not reparse point
983  * streams).
984  *
985  * @path:               Path to the file (UTF-16LE).
986  *
987  * @path_num_chars:     Number of 2-byte characters in @path.
988  *
989  * @inode:              WIM inode to save the stream into.
990  *
991  * @lookup_table:       Stream lookup table for the WIM.
992  *
993  * @file_size:          Size of unnamed data stream.  (Used only if alternate
994  *                      data streams API appears to be unavailable.)
995  *
996  * @vol_flags:          Flags that specify features of the volume being
997  *                      captured.
998  *
999  * Returns 0 on success; nonzero on failure.
1000  */
1001 static int
1002 win32_capture_streams(const wchar_t *path,
1003                       size_t path_num_chars,
1004                       struct wim_inode *inode,
1005                       struct wim_lookup_table *lookup_table,
1006                       u64 file_size,
1007                       unsigned vol_flags)
1008 {
1009         WIN32_FIND_STREAM_DATA dat;
1010         int ret;
1011         HANDLE hFind;
1012         DWORD err;
1013
1014         DEBUG("Capturing streams from \"%ls\"", path);
1015
1016         if (win32func_FindFirstStreamW == NULL ||
1017             !(vol_flags & FILE_NAMED_STREAMS))
1018                 goto unnamed_only;
1019
1020         hFind = win32func_FindFirstStreamW(path, FindStreamInfoStandard, &dat, 0);
1021         if (hFind == INVALID_HANDLE_VALUE) {
1022                 err = GetLastError();
1023                 if (err == ERROR_CALL_NOT_IMPLEMENTED)
1024                         goto unnamed_only;
1025
1026                 /* Seems legal for this to return ERROR_HANDLE_EOF on reparse
1027                  * points and directories */
1028                 if ((inode->i_attributes &
1029                     (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
1030                     && err == ERROR_HANDLE_EOF)
1031                 {
1032                         DEBUG("ERROR_HANDLE_EOF (ok)");
1033                         return 0;
1034                 } else {
1035                         if (err == ERROR_ACCESS_DENIED) {
1036                                 ERROR("Failed to look up data streams "
1037                                       "of \"%ls\": Access denied!\n%ls",
1038                                       path, capture_access_denied_msg);
1039                                 return WIMLIB_ERR_READ;
1040                         } else {
1041                                 ERROR("Failed to look up data streams "
1042                                       "of \"%ls\"", path);
1043                                 win32_error(err);
1044                                 return WIMLIB_ERR_READ;
1045                         }
1046                 }
1047         }
1048         do {
1049                 ret = win32_capture_stream(path,
1050                                            path_num_chars,
1051                                            inode, lookup_table,
1052                                            &dat);
1053                 if (ret)
1054                         goto out_find_close;
1055         } while (win32func_FindNextStreamW(hFind, &dat));
1056         err = GetLastError();
1057         if (err != ERROR_HANDLE_EOF) {
1058                 ERROR("Win32 API: Error reading data streams from \"%ls\"", path);
1059                 win32_error(err);
1060                 ret = WIMLIB_ERR_READ;
1061         }
1062 out_find_close:
1063         FindClose(hFind);
1064         return ret;
1065 unnamed_only:
1066         /* FindFirstStreamW() API is not available, or the volume does not
1067          * support named streams.  Only capture the unnamed data stream. */
1068         DEBUG("Only capturing unnamed data stream");
1069         if (inode->i_attributes &
1070              (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
1071         {
1072                 ret = 0;
1073         } else {
1074                 /* Just create our own WIN32_FIND_STREAM_DATA for an unnamed
1075                  * stream to reduce the code to a call to the
1076                  * already-implemented win32_capture_stream() */
1077                 wcscpy(dat.cStreamName, L"::$DATA");
1078                 dat.StreamSize.QuadPart = file_size;
1079                 ret = win32_capture_stream(path,
1080                                            path_num_chars,
1081                                            inode, lookup_table,
1082                                            &dat);
1083         }
1084         return ret;
1085 }
1086
1087 static int
1088 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
1089                                   wchar_t *path,
1090                                   size_t path_num_chars,
1091                                   struct add_image_params *params,
1092                                   struct win32_capture_state *state,
1093                                   unsigned vol_flags)
1094 {
1095         struct wim_dentry *root = NULL;
1096         struct wim_inode *inode;
1097         DWORD err;
1098         u64 file_size;
1099         int ret;
1100         void *reparse_data;
1101         size_t reparse_data_len;
1102         u16 not_rpfixed;
1103
1104         if (exclude_path(path, path_num_chars, params->config, true)) {
1105                 if (params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT) {
1106                         ERROR("Cannot exclude the root directory from capture");
1107                         ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
1108                         goto out;
1109                 }
1110                 if ((params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_EXCLUDE_VERBOSE)
1111                     && params->progress_func)
1112                 {
1113                         union wimlib_progress_info info;
1114                         info.scan.cur_path = path;
1115                         info.scan.excluded = true;
1116                         params->progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
1117                 }
1118                 ret = 0;
1119                 goto out;
1120         }
1121
1122         if ((params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
1123             && params->progress_func)
1124         {
1125                 union wimlib_progress_info info;
1126                 info.scan.cur_path = path;
1127                 info.scan.excluded = false;
1128                 params->progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
1129         }
1130
1131         HANDLE hFile = win32_open_existing_file(path,
1132                                                 FILE_READ_DATA | FILE_READ_ATTRIBUTES);
1133         if (hFile == INVALID_HANDLE_VALUE) {
1134                 err = GetLastError();
1135                 ERROR("Win32 API: Failed to open \"%ls\"", path);
1136                 win32_error(err);
1137                 ret = WIMLIB_ERR_OPEN;
1138                 goto out;
1139         }
1140
1141         BY_HANDLE_FILE_INFORMATION file_info;
1142         if (!GetFileInformationByHandle(hFile, &file_info)) {
1143                 err = GetLastError();
1144                 ERROR("Win32 API: Failed to get file information for \"%ls\"",
1145                       path);
1146                 win32_error(err);
1147                 ret = WIMLIB_ERR_STAT;
1148                 goto out_close_handle;
1149         }
1150
1151         if (file_info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1152                 reparse_data = alloca(REPARSE_POINT_MAX_SIZE);
1153                 ret = win32_get_reparse_data(hFile, path, params,
1154                                              reparse_data, &reparse_data_len);
1155                 if (ret < 0) {
1156                         /* WIMLIB_ERR_* (inverted) */
1157                         ret = -ret;
1158                         goto out_close_handle;
1159                 } else if (ret & RP_FIXED) {
1160                         not_rpfixed = 0;
1161                 } else if (ret == RP_EXCLUDED) {
1162                         ret = 0;
1163                         goto out_close_handle;
1164                 } else {
1165                         not_rpfixed = 1;
1166                 }
1167         }
1168
1169         /* Create a WIM dentry with an associated inode, which may be shared.
1170          *
1171          * However, we need to explicitly check for directories and files with
1172          * only 1 link and refuse to hard link them.  This is because Windows
1173          * has a bug where it can return duplicate File IDs for files and
1174          * directories on the FAT filesystem. */
1175         ret = inode_table_new_dentry(params->inode_table,
1176                                      path_basename_with_len(path, path_num_chars),
1177                                      ((u64)file_info.nFileIndexHigh << 32) |
1178                                          (u64)file_info.nFileIndexLow,
1179                                      file_info.dwVolumeSerialNumber,
1180                                      (file_info.nNumberOfLinks <= 1 ||
1181                                         (file_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)),
1182                                      &root);
1183         if (ret)
1184                 goto out_close_handle;
1185
1186         ret = win32_get_short_name(root, path);
1187         if (ret)
1188                 goto out_close_handle;
1189
1190         inode = root->d_inode;
1191
1192         if (inode->i_nlink > 1) /* Shared inode; nothing more to do */
1193                 goto out_close_handle;
1194
1195         inode->i_attributes = file_info.dwFileAttributes;
1196         inode->i_creation_time = FILETIME_to_u64(&file_info.ftCreationTime);
1197         inode->i_last_write_time = FILETIME_to_u64(&file_info.ftLastWriteTime);
1198         inode->i_last_access_time = FILETIME_to_u64(&file_info.ftLastAccessTime);
1199         inode->i_resolved = 1;
1200
1201         params->add_image_flags &= ~(WIMLIB_ADD_IMAGE_FLAG_ROOT | WIMLIB_ADD_IMAGE_FLAG_SOURCE);
1202
1203         if (!(params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NO_ACLS)
1204             && (vol_flags & FILE_PERSISTENT_ACLS))
1205         {
1206                 ret = win32_get_security_descriptor(root, params->sd_set,
1207                                                     path, state,
1208                                                     params->add_image_flags);
1209                 if (ret)
1210                         goto out_close_handle;
1211         }
1212
1213         file_size = ((u64)file_info.nFileSizeHigh << 32) |
1214                      (u64)file_info.nFileSizeLow;
1215
1216         /* Capture the unnamed data stream (only should be present for regular
1217          * files) and any alternate data streams. */
1218         ret = win32_capture_streams(path,
1219                                     path_num_chars,
1220                                     inode,
1221                                     params->lookup_table,
1222                                     file_size,
1223                                     vol_flags);
1224         if (ret)
1225                 goto out_close_handle;
1226
1227         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1228                 /* Reparse point: set the reparse data (which we read already)
1229                  * */
1230                 inode->i_not_rpfixed = not_rpfixed;
1231                 inode->i_reparse_tag = le32_to_cpu(*(u32*)reparse_data);
1232                 ret = inode_set_unnamed_stream(inode, reparse_data + 8,
1233                                                reparse_data_len - 8,
1234                                                params->lookup_table);
1235         } else if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1236                 /* Directory (not a reparse point) --- recurse to children */
1237                 ret = win32_recurse_directory(root,
1238                                               path,
1239                                               path_num_chars,
1240                                               params,
1241                                               state,
1242                                               vol_flags);
1243         }
1244 out_close_handle:
1245         CloseHandle(hFile);
1246 out:
1247         if (ret == 0)
1248                 *root_ret = root;
1249         else
1250                 free_dentry_tree(root, params->lookup_table);
1251         return ret;
1252 }
1253
1254 static void
1255 win32_do_capture_warnings(const struct win32_capture_state *state,
1256                           int add_image_flags)
1257 {
1258         if (state->num_get_sacl_priv_notheld == 0 &&
1259             state->num_get_sd_access_denied == 0)
1260                 return;
1261
1262         WARNING("");
1263         WARNING("Built dentry tree successfully, but with the following problem(s):");
1264         if (state->num_get_sacl_priv_notheld != 0) {
1265                 WARNING("Could not capture SACL (System Access Control List)\n"
1266                         "          on %lu files or directories.",
1267                         state->num_get_sacl_priv_notheld);
1268         }
1269         if (state->num_get_sd_access_denied != 0) {
1270                 WARNING("Could not capture security descriptor at all\n"
1271                         "          on %lu files or directories.",
1272                         state->num_get_sd_access_denied);
1273         }
1274         WARNING(
1275           "Try running the program as the Administrator to make sure all the\n"
1276 "          desired metadata has been captured exactly.  However, if you\n"
1277 "          do not care about capturing security descriptors correctly, then\n"
1278 "          nothing more needs to be done%ls\n",
1279         (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NO_ACLS) ? L"." :
1280          L", although you might consider\n"
1281 "          passing the --no-acls flag to `wimlib-imagex capture' or\n"
1282 "          `wimlib-imagex append' to explicitly capture no security\n"
1283 "          descriptors.\n");
1284 }
1285
1286 /* Win32 version of capturing a directory tree */
1287 int
1288 win32_build_dentry_tree(struct wim_dentry **root_ret,
1289                         const wchar_t *root_disk_path,
1290                         struct add_image_params *params)
1291 {
1292         size_t path_nchars;
1293         wchar_t *path;
1294         int ret;
1295         struct win32_capture_state state;
1296         unsigned vol_flags;
1297
1298
1299         path_nchars = wcslen(root_disk_path);
1300         if (path_nchars > 32767)
1301                 return WIMLIB_ERR_INVALID_PARAM;
1302
1303         ret = win32_get_file_and_vol_ids(root_disk_path,
1304                                          &params->capture_root_ino,
1305                                          &params->capture_root_dev);
1306         if (ret)
1307                 return ret;
1308
1309         win32_get_vol_flags(root_disk_path, &vol_flags);
1310
1311         /* There is no check for overflow later when this buffer is being used!
1312          * But the max path length on NTFS is 32767 characters, and paths need
1313          * to be written specially to even go past 260 characters, so we should
1314          * be okay with 32770 characters. */
1315         path = MALLOC(32770 * sizeof(wchar_t));
1316         if (!path)
1317                 return WIMLIB_ERR_NOMEM;
1318
1319         wmemcpy(path, root_disk_path, path_nchars + 1);
1320
1321         memset(&state, 0, sizeof(state));
1322         ret = win32_build_dentry_tree_recursive(root_ret, path,
1323                                                 path_nchars, params,
1324                                                 &state, vol_flags);
1325         FREE(path);
1326         if (ret == 0)
1327                 win32_do_capture_warnings(&state, params->add_image_flags);
1328         return ret;
1329 }
1330
1331 static int
1332 win32_set_reparse_data(HANDLE h,
1333                        u32 reparse_tag,
1334                        const struct wim_lookup_table_entry *lte,
1335                        const wchar_t *path)
1336 {
1337         int ret;
1338         u8 *buf;
1339         size_t len;
1340
1341         if (!lte) {
1342                 WARNING("\"%ls\" is marked as a reparse point but had no reparse data",
1343                         path);
1344                 return 0;
1345         }
1346         len = wim_resource_size(lte);
1347         if (len > 16 * 1024 - 8) {
1348                 WARNING("\"%ls\": reparse data too long!", path);
1349                 return 0;
1350         }
1351
1352         /* The WIM stream omits the ReparseTag and ReparseDataLength fields, so
1353          * leave 8 bytes of space for them at the beginning of the buffer, then
1354          * set them manually. */
1355         buf = alloca(len + 8);
1356         ret = read_full_resource_into_buf(lte, buf + 8, false);
1357         if (ret)
1358                 return ret;
1359         *(u32*)(buf + 0) = cpu_to_le32(reparse_tag);
1360         *(u16*)(buf + 4) = cpu_to_le16(len);
1361         *(u16*)(buf + 6) = 0;
1362
1363         /* Set the reparse data on the open file using the
1364          * FSCTL_SET_REPARSE_POINT ioctl.
1365          *
1366          * There are contradictions in Microsoft's documentation for this:
1367          *
1368          * "If hDevice was opened without specifying FILE_FLAG_OVERLAPPED,
1369          * lpOverlapped is ignored."
1370          *
1371          * --- So setting lpOverlapped to NULL is okay since it's ignored.
1372          *
1373          * "If lpOverlapped is NULL, lpBytesReturned cannot be NULL. Even when an
1374          * operation returns no output data and lpOutBuffer is NULL,
1375          * DeviceIoControl makes use of lpBytesReturned. After such an
1376          * operation, the value of lpBytesReturned is meaningless."
1377          *
1378          * --- So lpOverlapped not really ignored, as it affects another
1379          *  parameter.  This is the actual behavior: lpBytesReturned must be
1380          *  specified, even though lpBytesReturned is documented as:
1381          *
1382          *  "Not used with this operation; set to NULL."
1383          */
1384         DWORD bytesReturned;
1385         if (!DeviceIoControl(h, FSCTL_SET_REPARSE_POINT, buf, len + 8,
1386                              NULL, 0,
1387                              &bytesReturned /* lpBytesReturned */,
1388                              NULL /* lpOverlapped */))
1389         {
1390                 DWORD err = GetLastError();
1391                 ERROR("Failed to set reparse data on \"%ls\"", path);
1392                 win32_error(err);
1393                 return WIMLIB_ERR_WRITE;
1394         }
1395         return 0;
1396 }
1397
1398 static int
1399 win32_set_compressed(HANDLE hFile, const wchar_t *path)
1400 {
1401         USHORT format = COMPRESSION_FORMAT_DEFAULT;
1402         DWORD bytesReturned = 0;
1403         if (!DeviceIoControl(hFile, FSCTL_SET_COMPRESSION,
1404                              &format, sizeof(USHORT),
1405                              NULL, 0,
1406                              &bytesReturned, NULL))
1407         {
1408                 /* Could be a warning only, but we only call this if the volume
1409                  * supports compression.  So I'm calling this an error. */
1410                 DWORD err = GetLastError();
1411                 ERROR("Failed to set compression flag on \"%ls\"", path);
1412                 win32_error(err);
1413                 return WIMLIB_ERR_WRITE;
1414         }
1415         return 0;
1416 }
1417
1418 static int
1419 win32_set_sparse(HANDLE hFile, const wchar_t *path)
1420 {
1421         DWORD bytesReturned = 0;
1422         if (!DeviceIoControl(hFile, FSCTL_SET_SPARSE,
1423                              NULL, 0,
1424                              NULL, 0,
1425                              &bytesReturned, NULL))
1426         {
1427                 /* Could be a warning only, but we only call this if the volume
1428                  * supports sparse files.  So I'm calling this an error. */
1429                 DWORD err = GetLastError();
1430                 WARNING("Failed to set sparse flag on \"%ls\"", path);
1431                 win32_error(err);
1432                 return WIMLIB_ERR_WRITE;
1433         }
1434         return 0;
1435 }
1436
1437 /*
1438  * Sets the security descriptor on an extracted file.
1439  */
1440 static int
1441 win32_set_security_data(const struct wim_inode *inode,
1442                         const wchar_t *path,
1443                         struct apply_args *args)
1444 {
1445         PSECURITY_DESCRIPTOR descriptor;
1446         unsigned long n;
1447         DWORD err;
1448
1449         descriptor = wim_const_security_data(args->w)->descriptors[inode->i_security_id];
1450
1451         SECURITY_INFORMATION securityInformation = DACL_SECURITY_INFORMATION |
1452                                                    SACL_SECURITY_INFORMATION |
1453                                                    OWNER_SECURITY_INFORMATION |
1454                                                    GROUP_SECURITY_INFORMATION;
1455 again:
1456         if (SetFileSecurityW(path, securityInformation, descriptor))
1457                 return 0;
1458         err = GetLastError();
1459         if (args->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS)
1460                 goto fail;
1461         switch (err) {
1462         case ERROR_PRIVILEGE_NOT_HELD:
1463                 if (securityInformation & SACL_SECURITY_INFORMATION) {
1464                         n = args->num_set_sacl_priv_notheld++;
1465                         securityInformation &= ~SACL_SECURITY_INFORMATION;
1466                         if (n < MAX_SET_SACL_PRIV_NOTHELD_WARNINGS) {
1467                                 WARNING(
1468 "We don't have enough privileges to set the full security\n"
1469 "          descriptor on \"%ls\"!\n", path);
1470                                 if (args->num_set_sd_access_denied +
1471                                     args->num_set_sacl_priv_notheld == 1)
1472                                 {
1473                                         WARNING("%ls", apply_access_denied_msg);
1474                                 }
1475                                 WARNING("Re-trying with SACL omitted.\n", path);
1476                         } else if (n == MAX_GET_SACL_PRIV_NOTHELD_WARNINGS) {
1477                                 WARNING(
1478 "Suppressing further 'privileges not held' error messages when setting\n"
1479 "          security descriptors.");
1480                         }
1481                         goto again;
1482                 }
1483                 /* Fall through */
1484         case ERROR_INVALID_OWNER:
1485         case ERROR_ACCESS_DENIED:
1486                 n = args->num_set_sd_access_denied++;
1487                 if (n < MAX_SET_SD_ACCESS_DENIED_WARNINGS) {
1488                         WARNING("Failed to set security descriptor on \"%ls\": "
1489                                 "Access denied!\n", path);
1490                         if (args->num_set_sd_access_denied +
1491                             args->num_set_sacl_priv_notheld == 1)
1492                         {
1493                                 WARNING("%ls", apply_access_denied_msg);
1494                         }
1495                 } else if (n == MAX_SET_SD_ACCESS_DENIED_WARNINGS) {
1496                         WARNING(
1497 "Suppressing further access denied error messages when setting\n"
1498 "          security descriptors");
1499                 }
1500                 return 0;
1501         default:
1502 fail:
1503                 ERROR("Failed to set security descriptor on \"%ls\"", path);
1504                 win32_error(err);
1505                 return WIMLIB_ERR_WRITE;
1506         }
1507 }
1508
1509
1510 static int
1511 win32_extract_chunk(const void *buf, size_t len, void *arg)
1512 {
1513         HANDLE hStream = arg;
1514
1515         DWORD nbytes_written;
1516         wimlib_assert(len <= 0xffffffff);
1517
1518         if (!WriteFile(hStream, buf, len, &nbytes_written, NULL) ||
1519             nbytes_written != len)
1520         {
1521                 DWORD err = GetLastError();
1522                 ERROR("WriteFile(): write error");
1523                 win32_error(err);
1524                 return WIMLIB_ERR_WRITE;
1525         }
1526         return 0;
1527 }
1528
1529 static int
1530 do_win32_extract_stream(HANDLE hStream, struct wim_lookup_table_entry *lte)
1531 {
1532         return extract_wim_resource(lte, wim_resource_size(lte),
1533                                     win32_extract_chunk, hStream);
1534 }
1535
1536 static int
1537 do_win32_extract_encrypted_stream(const wchar_t *path,
1538                                   const struct wim_lookup_table_entry *lte)
1539 {
1540         ERROR("Extracting encryted streams not implemented");
1541         return WIMLIB_ERR_INVALID_PARAM;
1542 }
1543
1544 static bool
1545 path_is_root_of_drive(const wchar_t *path)
1546 {
1547         if (!*path)
1548                 return false;
1549
1550         if (*path != L'/' && *path != L'\\') {
1551                 if (*(path + 1) == L':')
1552                         path += 2;
1553                 else
1554                         return false;
1555         }
1556         while (*path == L'/' || *path == L'\\')
1557                 path++;
1558         return (*path == L'\0');
1559 }
1560
1561 static DWORD
1562 win32_get_create_flags_and_attributes(DWORD i_attributes)
1563 {
1564         DWORD attributes;
1565
1566         /*
1567          * Some attributes cannot be set by passing them to CreateFile().  In
1568          * particular:
1569          *
1570          * FILE_ATTRIBUTE_DIRECTORY:
1571          *   CreateDirectory() must be called instead of CreateFile().
1572          *
1573          * FILE_ATTRIBUTE_SPARSE_FILE:
1574          *   Needs an ioctl.
1575          *   See: win32_set_sparse().
1576          *
1577          * FILE_ATTRIBUTE_COMPRESSED:
1578          *   Not clear from the documentation, but apparently this needs an
1579          *   ioctl as well.
1580          *   See: win32_set_compressed().
1581          *
1582          * FILE_ATTRIBUTE_REPARSE_POINT:
1583          *   Needs an ioctl, with the reparse data specified.
1584          *   See: win32_set_reparse_data().
1585          *
1586          * In addition, clear any file flags in the attributes that we don't
1587          * want, but also specify FILE_FLAG_OPEN_REPARSE_POINT and
1588          * FILE_FLAG_BACKUP_SEMANTICS as we are a backup application.
1589          */
1590         attributes = i_attributes & ~(FILE_ATTRIBUTE_SPARSE_FILE |
1591                                       FILE_ATTRIBUTE_COMPRESSED |
1592                                       FILE_ATTRIBUTE_REPARSE_POINT |
1593                                       FILE_ATTRIBUTE_DIRECTORY |
1594                                       FILE_FLAG_DELETE_ON_CLOSE |
1595                                       FILE_FLAG_NO_BUFFERING |
1596                                       FILE_FLAG_OPEN_NO_RECALL |
1597                                       FILE_FLAG_OVERLAPPED |
1598                                       FILE_FLAG_RANDOM_ACCESS |
1599                                       /*FILE_FLAG_SESSION_AWARE |*/
1600                                       FILE_FLAG_SEQUENTIAL_SCAN |
1601                                       FILE_FLAG_WRITE_THROUGH);
1602         return attributes |
1603                FILE_FLAG_OPEN_REPARSE_POINT |
1604                FILE_FLAG_BACKUP_SEMANTICS;
1605 }
1606
1607 static bool
1608 inode_has_special_attributes(const struct wim_inode *inode)
1609 {
1610         return (inode->i_attributes & (FILE_ATTRIBUTE_COMPRESSED |
1611                                        FILE_ATTRIBUTE_REPARSE_POINT |
1612                                        FILE_ATTRIBUTE_SPARSE_FILE)) != 0;
1613 }
1614
1615 /* Set compression or sparse attributes, and reparse data, if supported by the
1616  * volume. */
1617 static int
1618 win32_set_special_attributes(HANDLE hFile, const struct wim_inode *inode,
1619                              struct wim_lookup_table_entry *unnamed_stream_lte,
1620                              const wchar_t *path, unsigned vol_flags)
1621 {
1622         int ret;
1623
1624         if (inode->i_attributes & FILE_ATTRIBUTE_COMPRESSED) {
1625                 if (vol_flags & FILE_FILE_COMPRESSION) {
1626                         DEBUG("Setting compression flag on \"%ls\"", path);
1627                         ret = win32_set_compressed(hFile, path);
1628                         if (ret)
1629                                 return ret;
1630                 } else {
1631                         DEBUG("Cannot set compression attribute on \"%ls\": "
1632                               "volume does not support transparent compression",
1633                               path);
1634                 }
1635         }
1636
1637         if (inode->i_attributes & FILE_ATTRIBUTE_SPARSE_FILE) {
1638                 if (vol_flags & FILE_SUPPORTS_SPARSE_FILES) {
1639                         DEBUG("Setting sparse flag on \"%ls\"", path);
1640                         ret = win32_set_sparse(hFile, path);
1641                         if (ret)
1642                                 return ret;
1643                 } else {
1644                         DEBUG("Cannot set sparse attribute on \"%ls\": "
1645                               "volume does not support sparse files",
1646                               path);
1647                 }
1648         }
1649
1650         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1651                 if (vol_flags & FILE_SUPPORTS_REPARSE_POINTS) {
1652                         DEBUG("Setting reparse data on \"%ls\"", path);
1653                         ret = win32_set_reparse_data(hFile, inode->i_reparse_tag,
1654                                                      unnamed_stream_lte, path);
1655                         if (ret)
1656                                 return ret;
1657                 } else {
1658                         DEBUG("Cannot set reparse data on \"%ls\": volume "
1659                               "does not support reparse points", path);
1660                 }
1661         }
1662
1663         return 0;
1664 }
1665
1666 static int
1667 win32_extract_stream(const struct wim_inode *inode,
1668                      const wchar_t *path,
1669                      const wchar_t *stream_name_utf16,
1670                      struct wim_lookup_table_entry *lte,
1671                      unsigned vol_flags)
1672 {
1673         wchar_t *stream_path;
1674         HANDLE h;
1675         int ret;
1676         DWORD err;
1677         DWORD creationDisposition = CREATE_ALWAYS;
1678
1679         if (stream_name_utf16) {
1680                 /* Named stream.  Create a buffer that contains the UTF-16LE
1681                  * string [.\]@path:@stream_name_utf16.  This is needed to
1682                  * create and open the stream using CreateFileW().  I'm not
1683                  * aware of any other APIs to do this.  Note: the '$DATA' suffix
1684                  * seems to be unneeded.  Additional note: a "./" prefix needs
1685                  * to be added when the path is not absolute to avoid ambiguity
1686                  * with drive letters. */
1687                 size_t stream_path_nchars;
1688                 size_t path_nchars;
1689                 size_t stream_name_nchars;
1690                 const wchar_t *prefix;
1691
1692                 path_nchars = wcslen(path);
1693                 stream_name_nchars = wcslen(stream_name_utf16);
1694                 stream_path_nchars = path_nchars + 1 + stream_name_nchars;
1695                 if (path[0] != cpu_to_le16(L'\0') &&
1696                     path[0] != cpu_to_le16(L'/') &&
1697                     path[0] != cpu_to_le16(L'\\') &&
1698                     path[1] != cpu_to_le16(L':'))
1699                 {
1700                         prefix = L"./";
1701                         stream_path_nchars += 2;
1702                 } else {
1703                         prefix = L"";
1704                 }
1705                 stream_path = alloca((stream_path_nchars + 1) * sizeof(wchar_t));
1706                 swprintf(stream_path, L"%ls%ls:%ls",
1707                          prefix, path, stream_name_utf16);
1708         } else {
1709                 /* Unnamed stream; its path is just the path to the file itself.
1710                  * */
1711                 stream_path = (wchar_t*)path;
1712
1713                 /* Directories must be created with CreateDirectoryW().  Then
1714                  * the call to CreateFileW() will merely open the directory that
1715                  * was already created rather than creating a new file. */
1716                 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1717                         if (!CreateDirectoryW(stream_path, NULL)) {
1718                                 err = GetLastError();
1719                                 switch (err) {
1720                                 case ERROR_ALREADY_EXISTS:
1721                                         break;
1722                                 case ERROR_ACCESS_DENIED:
1723                                         if (path_is_root_of_drive(path))
1724                                                 break;
1725                                         /* Fall through */
1726                                 default:
1727                                         ERROR("Failed to create directory \"%ls\"",
1728                                               stream_path);
1729                                         win32_error(err);
1730                                         ret = WIMLIB_ERR_MKDIR;
1731                                         goto fail;
1732                                 }
1733                         }
1734                         DEBUG("Created directory \"%ls\"", stream_path);
1735                         if (!inode_has_special_attributes(inode)) {
1736                                 ret = 0;
1737                                 goto out;
1738                         }
1739                         DEBUG("Directory \"%ls\" has special attributes!",
1740                               stream_path);
1741                         creationDisposition = OPEN_EXISTING;
1742                 }
1743         }
1744
1745         DEBUG("Opening \"%ls\"", stream_path);
1746         h = CreateFileW(stream_path,
1747                         GENERIC_READ | GENERIC_WRITE,
1748                         0,
1749                         NULL,
1750                         creationDisposition,
1751                         win32_get_create_flags_and_attributes(inode->i_attributes),
1752                         NULL);
1753         if (h == INVALID_HANDLE_VALUE) {
1754                 err = GetLastError();
1755                 ERROR("Failed to create \"%ls\"", stream_path);
1756                 win32_error(err);
1757                 ret = WIMLIB_ERR_OPEN;
1758                 goto fail;
1759         }
1760
1761         if (stream_name_utf16 == NULL && inode_has_special_attributes(inode)) {
1762                 ret = win32_set_special_attributes(h, inode, lte, path,
1763                                                    vol_flags);
1764                 if (ret)
1765                         goto fail_close_handle;
1766         }
1767
1768         if (!(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
1769                 if (lte) {
1770                         DEBUG("Extracting \"%ls\" (len = %"PRIu64")",
1771                               stream_path, wim_resource_size(lte));
1772                         if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED
1773                             && stream_name_utf16 == NULL
1774                             && (vol_flags & FILE_SUPPORTS_ENCRYPTION))
1775                         {
1776                                 ret = do_win32_extract_encrypted_stream(stream_path,
1777                                                                         lte);
1778                         } else {
1779                                 ret = do_win32_extract_stream(h, lte);
1780                         }
1781                         if (ret)
1782                                 goto fail_close_handle;
1783                 }
1784         }
1785
1786         DEBUG("Closing \"%ls\"", stream_path);
1787         if (!CloseHandle(h)) {
1788                 err = GetLastError();
1789                 ERROR("Failed to close \"%ls\"", stream_path);
1790                 win32_error(err);
1791                 ret = WIMLIB_ERR_WRITE;
1792                 goto fail;
1793         }
1794         ret = 0;
1795         goto out;
1796 fail_close_handle:
1797         CloseHandle(h);
1798 fail:
1799         ERROR("Error extracting %ls", stream_path);
1800 out:
1801         return ret;
1802 }
1803
1804 /*
1805  * Creates a file, directory, or reparse point and extracts all streams to it
1806  * (unnamed data stream and/or reparse point stream, plus any alternate data
1807  * streams).  This in Win32-specific code.
1808  *
1809  * @inode:      WIM inode for this file or directory.
1810  * @path:       UTF-16LE external path to extract the inode to.
1811  *
1812  * Returns 0 on success; nonzero on failure.
1813  */
1814 static int
1815 win32_extract_streams(const struct wim_inode *inode,
1816                       const wchar_t *path, u64 *completed_bytes_p,
1817                       unsigned vol_flags)
1818 {
1819         struct wim_lookup_table_entry *unnamed_lte;
1820         int ret;
1821
1822         unnamed_lte = inode_unnamed_lte_resolved(inode);
1823         ret = win32_extract_stream(inode, path, NULL, unnamed_lte,
1824                                    vol_flags);
1825         if (ret)
1826                 goto out;
1827         if (unnamed_lte && inode->i_extracted_file == NULL)
1828                 *completed_bytes_p += wim_resource_size(unnamed_lte);
1829
1830         if (!(vol_flags & FILE_NAMED_STREAMS))
1831                 goto out;
1832         for (u16 i = 0; i < inode->i_num_ads; i++) {
1833                 const struct wim_ads_entry *ads_entry = &inode->i_ads_entries[i];
1834                 if (ads_entry->stream_name_nbytes != 0) {
1835                         /* Skip special UNIX data entries (see documentation for
1836                          * WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA) */
1837                         if (ads_entry->stream_name_nbytes == WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES
1838                             && !memcmp(ads_entry->stream_name,
1839                                        WIMLIB_UNIX_DATA_TAG_UTF16LE,
1840                                        WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES))
1841                                 continue;
1842                         ret = win32_extract_stream(inode,
1843                                                    path,
1844                                                    ads_entry->stream_name,
1845                                                    ads_entry->lte,
1846                                                    vol_flags);
1847                         if (ret)
1848                                 break;
1849                         if (ads_entry->lte && inode->i_extracted_file == NULL)
1850                                 *completed_bytes_p += wim_resource_size(ads_entry->lte);
1851                 }
1852         }
1853 out:
1854         return ret;
1855 }
1856
1857 /* Extract a file, directory, reparse point, or hard link to an
1858  * already-extracted file using the Win32 API */
1859 int
1860 win32_do_apply_dentry(const wchar_t *output_path,
1861                       size_t output_path_num_chars,
1862                       struct wim_dentry *dentry,
1863                       struct apply_args *args)
1864 {
1865         int ret;
1866         struct wim_inode *inode = dentry->d_inode;
1867         DWORD err;
1868
1869         if (!args->have_vol_flags) {
1870                 win32_get_vol_flags(output_path, &args->vol_flags);
1871                 args->have_vol_flags = true;
1872                 /* Warn the user about data that may not be extracted. */
1873                 if (!(args->vol_flags & FILE_SUPPORTS_SPARSE_FILES))
1874                         WARNING("Volume does not support sparse files!\n"
1875                                 "          Sparse files will be extracted as non-sparse.");
1876                 if (!(args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS))
1877                         WARNING("Volume does not support reparse points!\n"
1878                                 "          Reparse point data will not be extracted.");
1879                 if (!(args->vol_flags & FILE_NAMED_STREAMS)) {
1880                         WARNING("Volume does not support named data streams!\n"
1881                                 "          Named data streams will not be extracted.");
1882                 }
1883                 if (!(args->vol_flags & FILE_SUPPORTS_ENCRYPTION)) {
1884                         WARNING("Volume does not support encryption!\n"
1885                                 "          Encrypted files will be extracted as raw data.");
1886                 }
1887                 if (!(args->vol_flags & FILE_FILE_COMPRESSION)) {
1888                         WARNING("Volume does not support transparent compression!\n"
1889                                 "          Compressed files will be extracted as non-compressed.");
1890                 }
1891                 if (!(args->vol_flags & FILE_PERSISTENT_ACLS)) {
1892                         if (args->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS) {
1893                                 ERROR("Strict ACLs requested, but the volume does not "
1894                                       "support ACLs!");
1895                                 return WIMLIB_ERR_VOLUME_LACKS_FEATURES;
1896                         } else {
1897                                 WARNING("Volume does not support persistent ACLS!\n"
1898                                         "          File permissions will not be extracted.");
1899                         }
1900                 }
1901         }
1902
1903         if (inode->i_nlink > 1 && inode->i_extracted_file != NULL) {
1904                 /* Linked file, with another name already extracted.  Create a
1905                  * hard link. */
1906
1907                 /* There is a volume flag for this (FILE_SUPPORTS_HARD_LINKS),
1908                  * but it's only available on Windows 7 and later.  So no use
1909                  * even checking it, really.  Instead, CreateHardLinkW() will
1910                  * apparently return ERROR_INVALID_FUNCTION if the volume does
1911                  * not support hard links. */
1912                 DEBUG("Creating hard link \"%ls => %ls\"",
1913                       output_path, inode->i_extracted_file);
1914                 if (CreateHardLinkW(output_path, inode->i_extracted_file, NULL))
1915                         return 0;
1916
1917                 err = GetLastError();
1918                 if (err != ERROR_INVALID_FUNCTION) {
1919                         ERROR("Can't create hard link \"%ls => %ls\"",
1920                               output_path, inode->i_extracted_file);
1921                         win32_error(err);
1922                         return WIMLIB_ERR_LINK;
1923                 } else {
1924                         args->num_hard_links_failed++;
1925                         if (args->num_hard_links_failed < MAX_CREATE_HARD_LINK_WARNINGS) {
1926                                 WARNING("Can't create hard link \"%ls => %ls\":\n"
1927                                         "          Volume does not support hard links!\n"
1928                                         "          Falling back to extracting a copy of the file.",
1929                                         output_path, inode->i_extracted_file);
1930                         } else if (args->num_hard_links_failed == MAX_CREATE_HARD_LINK_WARNINGS) {
1931                                 WARNING("Suppressing further hard linking warnings...");
1932                         }
1933                 }
1934         }
1935
1936         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT &&
1937             !(args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS))
1938         {
1939                 WARNING("Skipping extraction of reparse point \"%ls\":\n"
1940                         "          Not supported by destination filesystem",
1941                         output_path);
1942                 struct wim_lookup_table_entry *lte;
1943                 lte = inode_unnamed_lte_resolved(inode);
1944                 if (lte)
1945                         args->progress.extract.completed_bytes += wim_resource_size(lte);
1946                 return 0;
1947         }
1948
1949         /* Create the file, directory, or reparse point, and extract the
1950          * data streams. */
1951         ret = win32_extract_streams(inode, output_path,
1952                                     &args->progress.extract.completed_bytes,
1953                                     args->vol_flags);
1954         if (ret)
1955                 return ret;
1956
1957         if (inode->i_security_id >= 0 &&
1958             !(args->extract_flags & WIMLIB_EXTRACT_FLAG_NO_ACLS)
1959             && (args->vol_flags & FILE_PERSISTENT_ACLS))
1960         {
1961                 ret = win32_set_security_data(inode, output_path, args);
1962                 if (ret)
1963                         return ret;
1964         }
1965         if (inode->i_nlink > 1) {
1966                 /* Save extracted path for a later call to
1967                  * CreateHardLinkW() if this inode has multiple links.
1968                  * */
1969                 inode->i_extracted_file = WSTRDUP(output_path);
1970                 if (!inode->i_extracted_file)
1971                         ret = WIMLIB_ERR_NOMEM;
1972         }
1973         return 0;
1974 }
1975
1976 /* Set timestamps on an extracted file using the Win32 API */
1977 int
1978 win32_do_apply_dentry_timestamps(const wchar_t *path,
1979                                  size_t path_num_chars,
1980                                  const struct wim_dentry *dentry,
1981                                  const struct apply_args *args)
1982 {
1983         DWORD err;
1984         HANDLE h;
1985         const struct wim_inode *inode = dentry->d_inode;
1986
1987         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT &&
1988             !(args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS))
1989         {
1990                 /* Skip reparse points not extracted */
1991                 return 0;
1992         }
1993
1994         /* Windows doesn't let you change the timestamps of the root directory
1995          * (at least on FAT, which is dumb but expected since FAT doesn't store
1996          * any metadata about the root directory...) */
1997         if (path_is_root_of_drive(path))
1998                 return 0;
1999
2000         DEBUG("Opening \"%ls\" to set timestamps", path);
2001         h = win32_open_existing_file(path, FILE_WRITE_ATTRIBUTES);
2002         if (h == INVALID_HANDLE_VALUE) {
2003                 err = GetLastError();
2004                 goto fail;
2005         }
2006
2007         FILETIME creationTime = {.dwLowDateTime = inode->i_creation_time & 0xffffffff,
2008                                  .dwHighDateTime = inode->i_creation_time >> 32};
2009         FILETIME lastAccessTime = {.dwLowDateTime = inode->i_last_access_time & 0xffffffff,
2010                                   .dwHighDateTime = inode->i_last_access_time >> 32};
2011         FILETIME lastWriteTime = {.dwLowDateTime = inode->i_last_write_time & 0xffffffff,
2012                                   .dwHighDateTime = inode->i_last_write_time >> 32};
2013
2014         DEBUG("Calling SetFileTime() on \"%ls\"", path);
2015         if (!SetFileTime(h, &creationTime, &lastAccessTime, &lastWriteTime)) {
2016                 err = GetLastError();
2017                 CloseHandle(h);
2018                 goto fail;
2019         }
2020         DEBUG("Closing \"%ls\"", path);
2021         if (!CloseHandle(h)) {
2022                 err = GetLastError();
2023                 goto fail;
2024         }
2025         goto out;
2026 fail:
2027         /* Only warn if setting timestamps failed; still return 0. */
2028         WARNING("Can't set timestamps on \"%ls\"", path);
2029         win32_error(err);
2030 out:
2031         return 0;
2032 }
2033
2034 /* Replacement for POSIX fsync() */
2035 int
2036 fsync(int fd)
2037 {
2038         DWORD err;
2039         HANDLE h;
2040
2041         h = (HANDLE)_get_osfhandle(fd);
2042         if (h == INVALID_HANDLE_VALUE) {
2043                 err = GetLastError();
2044                 ERROR("Could not get Windows handle for file descriptor");
2045                 win32_error(err);
2046                 errno = EBADF;
2047                 return -1;
2048         }
2049         if (!FlushFileBuffers(h)) {
2050                 err = GetLastError();
2051                 ERROR("Could not flush file buffers to disk");
2052                 win32_error(err);
2053                 errno = EIO;
2054                 return -1;
2055         }
2056         return 0;
2057 }
2058
2059 /* Use the Win32 API to get the number of processors */
2060 unsigned
2061 win32_get_number_of_processors()
2062 {
2063         SYSTEM_INFO sysinfo;
2064         GetSystemInfo(&sysinfo);
2065         return sysinfo.dwNumberOfProcessors;
2066 }
2067
2068 /* Replacement for POSIX-2008 realpath().  Warning: partial functionality only
2069  * (resolved_path must be NULL).   Also I highly doubt that GetFullPathName
2070  * really does the right thing under all circumstances. */
2071 wchar_t *
2072 realpath(const wchar_t *path, wchar_t *resolved_path)
2073 {
2074         DWORD ret;
2075         wimlib_assert(resolved_path == NULL);
2076         DWORD err;
2077
2078         ret = GetFullPathNameW(path, 0, NULL, NULL);
2079         if (!ret) {
2080                 err = GetLastError();
2081                 goto fail_win32;
2082         }
2083
2084         resolved_path = TMALLOC(ret);
2085         if (!resolved_path)
2086                 goto out;
2087         ret = GetFullPathNameW(path, ret, resolved_path, NULL);
2088         if (!ret) {
2089                 err = GetLastError();
2090                 free(resolved_path);
2091                 resolved_path = NULL;
2092                 goto fail_win32;
2093         }
2094         goto out;
2095 fail_win32:
2096         win32_error(err);
2097         errno = -1;
2098 out:
2099         return resolved_path;
2100 }
2101
2102 /* rename() on Windows fails if the destination file exists.  And we need to
2103  * make it work on wide characters.  Fix it. */
2104 int
2105 win32_rename_replacement(const wchar_t *oldpath, const wchar_t *newpath)
2106 {
2107         if (MoveFileExW(oldpath, newpath, MOVEFILE_REPLACE_EXISTING)) {
2108                 return 0;
2109         } else {
2110                 /* As usual, the possible error values are not documented */
2111                 DWORD err = GetLastError();
2112                 ERROR("MoveFileEx(): Can't rename \"%ls\" to \"%ls\"",
2113                       oldpath, newpath);
2114                 win32_error(err);
2115                 errno = -1;
2116                 return -1;
2117         }
2118 }
2119
2120 /* Replacement for POSIX fnmatch() (partial functionality only) */
2121 int
2122 fnmatch(const wchar_t *pattern, const wchar_t *string, int flags)
2123 {
2124         if (PathMatchSpecW(string, pattern))
2125                 return 0;
2126         else
2127                 return FNM_NOMATCH;
2128 }
2129
2130 /* truncate() replacement */
2131 int
2132 win32_truncate_replacement(const wchar_t *path, off_t size)
2133 {
2134         DWORD err = NO_ERROR;
2135         LARGE_INTEGER liOffset;
2136
2137         HANDLE h = win32_open_existing_file(path, GENERIC_WRITE);
2138         if (h == INVALID_HANDLE_VALUE)
2139                 goto fail;
2140
2141         liOffset.QuadPart = size;
2142         if (!SetFilePointerEx(h, liOffset, NULL, FILE_BEGIN))
2143                 goto fail_close_handle;
2144
2145         if (!SetEndOfFile(h))
2146                 goto fail_close_handle;
2147         CloseHandle(h);
2148         return 0;
2149
2150 fail_close_handle:
2151         err = GetLastError();
2152         CloseHandle(h);
2153 fail:
2154         if (err == NO_ERROR)
2155                 err = GetLastError();
2156         ERROR("Can't truncate \"%ls\" to %"PRIu64" bytes", path, size);
2157         win32_error(err);
2158         errno = -1;
2159         return -1;
2160 }
2161
2162
2163 /* This really could be replaced with _wcserror_s, but this doesn't seem to
2164  * actually be available in MSVCRT.DLL on Windows XP (perhaps it's statically
2165  * linked in by Visual Studio...?). */
2166 extern int
2167 win32_strerror_r_replacement(int errnum, wchar_t *buf, size_t buflen)
2168 {
2169         static pthread_mutex_t strerror_lock = PTHREAD_MUTEX_INITIALIZER;
2170
2171         pthread_mutex_lock(&strerror_lock);
2172         mbstowcs(buf, strerror(errnum), buflen);
2173         buf[buflen - 1] = '\0';
2174         pthread_mutex_unlock(&strerror_lock);
2175         return 0;
2176 }
2177
2178 #endif /* __WIN32__ */