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