Win32: Fix cross-drive capture rpfix
[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         if (stripped_chars)
682                 stripped_chars -= 2;
683         target[target_nchars] = L'\0';
684         orig_target = target;
685         target = capture_fixup_absolute_symlink(target + stripped_chars,
686                                                 capture_root_ino, capture_root_dev);
687         if (!target)
688                 return RP_EXCLUDED;
689         target_nchars = wcslen(target);
690         wmemmove(orig_target + stripped_chars, target, target_nchars + 1);
691         *target_nbytes_p = (target_nchars + stripped_chars) * sizeof(wchar_t);
692         DEBUG("Fixed reparse point (new target: \"%ls\")", orig_target);
693         if (stripped_chars)
694                 return RP_FIXED_FULLPATH;
695         else
696                 return RP_FIXED_ABSPATH;
697 }
698
699 /* Returns: `enum rp_status' value on success; negative WIMLIB_ERR_* value on
700  * failure. */
701 static int
702 win32_capture_try_rpfix(u8 *rpbuf, u16 *rpbuflen_p,
703                         u64 capture_root_ino, u64 capture_root_dev)
704 {
705         struct reparse_data rpdata;
706         DWORD rpbuflen;
707         int ret;
708         enum rp_status rp_status;
709
710         rpbuflen = *rpbuflen_p;
711         ret = parse_reparse_data(rpbuf, rpbuflen, &rpdata);
712         if (ret)
713                 return -ret;
714
715         rp_status = win32_capture_maybe_rpfix_target(rpdata.substitute_name,
716                                                      &rpdata.substitute_name_nbytes,
717                                                      capture_root_ino,
718                                                      capture_root_dev,
719                                                      le32_to_cpu(*(u32*)rpbuf));
720         if (rp_status & RP_FIXED) {
721                 wimlib_assert(rpdata.substitute_name_nbytes % 2 == 0);
722                 utf16lechar substitute_name_copy[rpdata.substitute_name_nbytes / 2];
723                 wmemcpy(substitute_name_copy, rpdata.substitute_name,
724                         rpdata.substitute_name_nbytes / 2);
725                 rpdata.substitute_name = substitute_name_copy;
726                 rpdata.print_name = substitute_name_copy;
727                 rpdata.print_name_nbytes = rpdata.substitute_name_nbytes;
728                 if (rp_status == RP_FIXED_FULLPATH) {
729                         /* "full path", meaning \??\ prefixed.  We should not
730                          * include this prefix in the print name, as it is
731                          * apparently meant for the filesystem driver only. */
732                         rpdata.print_name += 4;
733                         rpdata.print_name_nbytes -= 8;
734                 }
735                 ret = make_reparse_buffer(&rpdata, rpbuf);
736                 if (ret == 0)
737                         ret = rp_status;
738                 else
739                         ret = -ret;
740         } else {
741                 ret = rp_status;
742         }
743         return ret;
744 }
745
746 /*
747  * Loads the reparse point data from a reparse point into memory, optionally
748  * fixing the targets of absolute symbolic links and junction points to be
749  * relative to the root of capture.
750  *
751  * @hFile:  Open handle to the reparse point.
752  * @path:   Path to the reparse point.  Used for error messages only.
753  * @params: Additional parameters, including whether to do reparse point fixups
754  *          or not.
755  * @rpbuf:  Buffer of length at least REPARSE_POINT_MAX_SIZE bytes into which
756  *          the reparse point buffer will be loaded.
757  * @rpbuflen_ret:  On success, the length of the reparse point buffer in bytes
758  *                 is written to this location.
759  *
760  * Returns:
761  *      On success, returns an `enum rp_status' value that indicates if and/or
762  *      how the reparse point fixup was done.
763  *
764  *      On failure, returns a negative value that is a negated WIMLIB_ERR_*
765  *      code.
766  */
767 static int
768 win32_get_reparse_data(HANDLE hFile, const wchar_t *path,
769                        struct add_image_params *params,
770                        u8 *rpbuf, u16 *rpbuflen_ret)
771 {
772         DWORD bytesReturned;
773         u32 reparse_tag;
774         int ret;
775         u16 rpbuflen;
776
777         DEBUG("Loading reparse data from \"%ls\"", path);
778         if (!DeviceIoControl(hFile, FSCTL_GET_REPARSE_POINT,
779                              NULL, /* "Not used with this operation; set to NULL" */
780                              0, /* "Not used with this operation; set to 0" */
781                              rpbuf, /* "A pointer to a buffer that
782                                                    receives the reparse point data */
783                              REPARSE_POINT_MAX_SIZE, /* "The size of the output
784                                                         buffer, in bytes */
785                              &bytesReturned,
786                              NULL))
787         {
788                 DWORD err = GetLastError();
789                 ERROR("Failed to get reparse data of \"%ls\"", path);
790                 win32_error(err);
791                 return -WIMLIB_ERR_READ;
792         }
793         if (bytesReturned < 8 || bytesReturned > REPARSE_POINT_MAX_SIZE) {
794                 ERROR("Reparse data on \"%ls\" is invalid", path);
795                 return -WIMLIB_ERR_INVALID_REPARSE_DATA;
796         }
797
798         rpbuflen = bytesReturned;
799         reparse_tag = le32_to_cpu(*(u32*)rpbuf);
800         if (params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_RPFIX &&
801             (reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
802              reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT))
803         {
804                 /* Try doing reparse point fixup */
805                 ret = win32_capture_try_rpfix(rpbuf,
806                                               &rpbuflen,
807                                               params->capture_root_ino,
808                                               params->capture_root_dev);
809         } else {
810                 ret = RP_NOT_FIXED;
811         }
812         *rpbuflen_ret = rpbuflen;
813         return ret;
814 }
815
816 static DWORD WINAPI
817 win32_tally_encrypted_size_cb(unsigned char *_data, void *_ctx,
818                               unsigned long len)
819 {
820         *(u64*)_ctx += len;
821         return ERROR_SUCCESS;
822 }
823
824 static int
825 win32_get_encrypted_file_size(const wchar_t *path, u64 *size_ret)
826 {
827         DWORD err;
828         void *file_ctx;
829         int ret;
830
831         *size_ret = 0;
832         err = OpenEncryptedFileRawW(path, 0, &file_ctx);
833         if (err != ERROR_SUCCESS) {
834                 ERROR("Failed to open encrypted file \"%ls\" for raw read", path);
835                 win32_error(err);
836                 return WIMLIB_ERR_OPEN;
837         }
838         err = ReadEncryptedFileRaw(win32_tally_encrypted_size_cb,
839                                    size_ret, file_ctx);
840         if (err != ERROR_SUCCESS) {
841                 ERROR("Failed to read raw encrypted data from \"%ls\"", path);
842                 win32_error(err);
843                 ret = WIMLIB_ERR_READ;
844         } else {
845                 ret = 0;
846         }
847         CloseEncryptedFileRaw(file_ctx);
848         return ret;
849 }
850
851 /* Scans an unnamed or named stream of a Win32 file (not a reparse point
852  * stream); calculates its SHA1 message digest and either creates a `struct
853  * wim_lookup_table_entry' in memory for it, or uses an existing 'struct
854  * wim_lookup_table_entry' for an identical stream.
855  *
856  * @path:               Path to the file (UTF-16LE).
857  *
858  * @path_num_chars:     Number of 2-byte characters in @path.
859  *
860  * @inode:              WIM inode to save the stream into.
861  *
862  * @lookup_table:       Stream lookup table for the WIM.
863  *
864  * @dat:                A `WIN32_FIND_STREAM_DATA' structure that specifies the
865  *                      stream name.
866  *
867  * Returns 0 on success; nonzero on failure.
868  */
869 static int
870 win32_capture_stream(const wchar_t *path,
871                      size_t path_num_chars,
872                      struct wim_inode *inode,
873                      struct wim_lookup_table *lookup_table,
874                      WIN32_FIND_STREAM_DATA *dat)
875 {
876         struct wim_ads_entry *ads_entry;
877         struct wim_lookup_table_entry *lte;
878         int ret;
879         wchar_t *stream_name, *colon;
880         size_t stream_name_nchars;
881         bool is_named_stream;
882         wchar_t *spath;
883         size_t spath_nchars;
884         size_t spath_buf_nbytes;
885         const wchar_t *relpath_prefix;
886         const wchar_t *colonchar;
887
888         DEBUG("Capture \"%ls\" stream \"%ls\"", path, dat->cStreamName);
889
890         /* The stream name should be returned as :NAME:TYPE */
891         stream_name = dat->cStreamName;
892         if (*stream_name != L':')
893                 goto out_invalid_stream_name;
894         stream_name += 1;
895         colon = wcschr(stream_name, L':');
896         if (colon == NULL)
897                 goto out_invalid_stream_name;
898
899         if (wcscmp(colon + 1, L"$DATA")) {
900                 /* Not a DATA stream */
901                 ret = 0;
902                 goto out;
903         }
904
905         *colon = '\0';
906
907         stream_name_nchars = colon - stream_name;
908         is_named_stream = (stream_name_nchars != 0);
909
910         if (is_named_stream) {
911                 /* Allocate an ADS entry for the named stream. */
912                 ads_entry = inode_add_ads_utf16le(inode, stream_name,
913                                                   stream_name_nchars * sizeof(wchar_t));
914                 if (!ads_entry) {
915                         ret = WIMLIB_ERR_NOMEM;
916                         goto out;
917                 }
918         }
919
920         /* If zero length stream, no lookup table entry needed. */
921         if ((u64)dat->StreamSize.QuadPart == 0) {
922                 ret = 0;
923                 goto out;
924         }
925
926         /* Create a UTF-16LE string @spath that gives the filename, then a
927          * colon, then the stream name.  Or, if it's an unnamed stream, just the
928          * filename.  It is MALLOC()'ed so that it can be saved in the
929          * wim_lookup_table_entry if needed.
930          *
931          * As yet another special case, relative paths need to be changed to
932          * begin with an explicit "./" so that, for example, a file t:ads, where
933          * :ads is the part we added, is not interpreted as a file on the t:
934          * drive. */
935         spath_nchars = path_num_chars;
936         relpath_prefix = L"";
937         colonchar = L"";
938         if (is_named_stream) {
939                 spath_nchars += 1 + stream_name_nchars;
940                 colonchar = L":";
941                 if (path_num_chars == 1 &&
942                     path[0] != L'/' &&
943                     path[0] != L'\\')
944                 {
945                         spath_nchars += 2;
946                         relpath_prefix = L"./";
947                 }
948         }
949
950         spath_buf_nbytes = (spath_nchars + 1) * sizeof(wchar_t);
951         spath = MALLOC(spath_buf_nbytes);
952
953         swprintf(spath, L"%ls%ls%ls%ls",
954                  relpath_prefix, path, colonchar, stream_name);
955
956         /* Make a new wim_lookup_table_entry */
957         lte = new_lookup_table_entry();
958         if (!lte) {
959                 ret = WIMLIB_ERR_NOMEM;
960                 goto out_free_spath;
961         }
962         lte->file_on_disk = spath;
963         spath = NULL;
964         if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED && !is_named_stream) {
965                 u64 encrypted_size;
966                 lte->resource_location = RESOURCE_WIN32_ENCRYPTED;
967                 ret = win32_get_encrypted_file_size(path, &encrypted_size);
968                 if (ret)
969                         goto out_free_spath;
970                 lte->resource_entry.original_size = encrypted_size;
971         } else {
972                 lte->resource_location = RESOURCE_WIN32;
973                 lte->resource_entry.original_size = (u64)dat->StreamSize.QuadPart;
974         }
975
976         u32 stream_id;
977         if (is_named_stream) {
978                 stream_id = ads_entry->stream_id;
979                 ads_entry->lte = lte;
980         } else {
981                 stream_id = 0;
982                 inode->i_lte = lte;
983         }
984         lookup_table_insert_unhashed(lookup_table, lte, inode, stream_id);
985         ret = 0;
986 out_free_spath:
987         FREE(spath);
988 out:
989         return ret;
990 out_invalid_stream_name:
991         ERROR("Invalid stream name: \"%ls:%ls\"", path, dat->cStreamName);
992         ret = WIMLIB_ERR_READ;
993         goto out;
994 }
995
996 /* Scans a Win32 file for unnamed and named data streams (not reparse point
997  * streams).
998  *
999  * @path:               Path to the file (UTF-16LE).
1000  *
1001  * @path_num_chars:     Number of 2-byte characters in @path.
1002  *
1003  * @inode:              WIM inode to save the stream into.
1004  *
1005  * @lookup_table:       Stream lookup table for the WIM.
1006  *
1007  * @file_size:          Size of unnamed data stream.  (Used only if alternate
1008  *                      data streams API appears to be unavailable.)
1009  *
1010  * @vol_flags:          Flags that specify features of the volume being
1011  *                      captured.
1012  *
1013  * Returns 0 on success; nonzero on failure.
1014  */
1015 static int
1016 win32_capture_streams(const wchar_t *path,
1017                       size_t path_num_chars,
1018                       struct wim_inode *inode,
1019                       struct wim_lookup_table *lookup_table,
1020                       u64 file_size,
1021                       unsigned vol_flags)
1022 {
1023         WIN32_FIND_STREAM_DATA dat;
1024         int ret;
1025         HANDLE hFind;
1026         DWORD err;
1027
1028         DEBUG("Capturing streams from \"%ls\"", path);
1029
1030         if (win32func_FindFirstStreamW == NULL ||
1031             !(vol_flags & FILE_NAMED_STREAMS))
1032                 goto unnamed_only;
1033
1034         hFind = win32func_FindFirstStreamW(path, FindStreamInfoStandard, &dat, 0);
1035         if (hFind == INVALID_HANDLE_VALUE) {
1036                 err = GetLastError();
1037                 if (err == ERROR_CALL_NOT_IMPLEMENTED)
1038                         goto unnamed_only;
1039
1040                 /* Seems legal for this to return ERROR_HANDLE_EOF on reparse
1041                  * points and directories */
1042                 if ((inode->i_attributes &
1043                     (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
1044                     && err == ERROR_HANDLE_EOF)
1045                 {
1046                         DEBUG("ERROR_HANDLE_EOF (ok)");
1047                         return 0;
1048                 } else {
1049                         if (err == ERROR_ACCESS_DENIED) {
1050                                 WARNING("Failed to look up data streams "
1051                                         "of \"%ls\": Access denied!\n%ls",
1052                                         path, capture_access_denied_msg);
1053                                 return 0;
1054                         } else {
1055                                 ERROR("Failed to look up data streams "
1056                                       "of \"%ls\"", path);
1057                                 win32_error(err);
1058                                 return WIMLIB_ERR_READ;
1059                         }
1060                 }
1061         }
1062         do {
1063                 ret = win32_capture_stream(path,
1064                                            path_num_chars,
1065                                            inode, lookup_table,
1066                                            &dat);
1067                 if (ret)
1068                         goto out_find_close;
1069         } while (win32func_FindNextStreamW(hFind, &dat));
1070         err = GetLastError();
1071         if (err != ERROR_HANDLE_EOF) {
1072                 ERROR("Win32 API: Error reading data streams from \"%ls\"", path);
1073                 win32_error(err);
1074                 ret = WIMLIB_ERR_READ;
1075         }
1076 out_find_close:
1077         FindClose(hFind);
1078         return ret;
1079 unnamed_only:
1080         /* FindFirstStreamW() API is not available, or the volume does not
1081          * support named streams.  Only capture the unnamed data stream. */
1082         DEBUG("Only capturing unnamed data stream");
1083         if (inode->i_attributes &
1084              (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
1085         {
1086                 ret = 0;
1087         } else {
1088                 /* Just create our own WIN32_FIND_STREAM_DATA for an unnamed
1089                  * stream to reduce the code to a call to the
1090                  * already-implemented win32_capture_stream() */
1091                 wcscpy(dat.cStreamName, L"::$DATA");
1092                 dat.StreamSize.QuadPart = file_size;
1093                 ret = win32_capture_stream(path,
1094                                            path_num_chars,
1095                                            inode, lookup_table,
1096                                            &dat);
1097         }
1098         return ret;
1099 }
1100
1101 static int
1102 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
1103                                   wchar_t *path,
1104                                   size_t path_num_chars,
1105                                   struct add_image_params *params,
1106                                   struct win32_capture_state *state,
1107                                   unsigned vol_flags)
1108 {
1109         struct wim_dentry *root = NULL;
1110         struct wim_inode *inode;
1111         DWORD err;
1112         u64 file_size;
1113         int ret;
1114         u8 *rpbuf;
1115         u16 rpbuflen;
1116         u16 not_rpfixed;
1117
1118         if (exclude_path(path, path_num_chars, params->config, true)) {
1119                 if (params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT) {
1120                         ERROR("Cannot exclude the root directory from capture");
1121                         ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
1122                         goto out;
1123                 }
1124                 if ((params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_EXCLUDE_VERBOSE)
1125                     && params->progress_func)
1126                 {
1127                         union wimlib_progress_info info;
1128                         info.scan.cur_path = path;
1129                         info.scan.excluded = true;
1130                         params->progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
1131                 }
1132                 ret = 0;
1133                 goto out;
1134         }
1135
1136         if ((params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
1137             && params->progress_func)
1138         {
1139                 union wimlib_progress_info info;
1140                 info.scan.cur_path = path;
1141                 info.scan.excluded = false;
1142                 params->progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
1143         }
1144
1145         HANDLE hFile = win32_open_existing_file(path,
1146                                                 FILE_READ_DATA | FILE_READ_ATTRIBUTES);
1147         if (hFile == INVALID_HANDLE_VALUE) {
1148                 err = GetLastError();
1149                 ERROR("Win32 API: Failed to open \"%ls\"", path);
1150                 win32_error(err);
1151                 ret = WIMLIB_ERR_OPEN;
1152                 goto out;
1153         }
1154
1155         BY_HANDLE_FILE_INFORMATION file_info;
1156         if (!GetFileInformationByHandle(hFile, &file_info)) {
1157                 err = GetLastError();
1158                 ERROR("Win32 API: Failed to get file information for \"%ls\"",
1159                       path);
1160                 win32_error(err);
1161                 ret = WIMLIB_ERR_STAT;
1162                 goto out_close_handle;
1163         }
1164
1165         if (file_info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1166                 rpbuf = alloca(REPARSE_POINT_MAX_SIZE);
1167                 ret = win32_get_reparse_data(hFile, path, params,
1168                                              rpbuf, &rpbuflen);
1169                 if (ret < 0) {
1170                         /* WIMLIB_ERR_* (inverted) */
1171                         ret = -ret;
1172                         goto out_close_handle;
1173                 } else if (ret & RP_FIXED) {
1174                         not_rpfixed = 0;
1175                 } else if (ret == RP_EXCLUDED) {
1176                         ret = 0;
1177                         goto out_close_handle;
1178                 } else {
1179                         not_rpfixed = 1;
1180                 }
1181         }
1182
1183         /* Create a WIM dentry with an associated inode, which may be shared.
1184          *
1185          * However, we need to explicitly check for directories and files with
1186          * only 1 link and refuse to hard link them.  This is because Windows
1187          * has a bug where it can return duplicate File IDs for files and
1188          * directories on the FAT filesystem. */
1189         ret = inode_table_new_dentry(params->inode_table,
1190                                      path_basename_with_len(path, path_num_chars),
1191                                      ((u64)file_info.nFileIndexHigh << 32) |
1192                                          (u64)file_info.nFileIndexLow,
1193                                      file_info.dwVolumeSerialNumber,
1194                                      (file_info.nNumberOfLinks <= 1 ||
1195                                         (file_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)),
1196                                      &root);
1197         if (ret)
1198                 goto out_close_handle;
1199
1200         ret = win32_get_short_name(root, path);
1201         if (ret)
1202                 goto out_close_handle;
1203
1204         inode = root->d_inode;
1205
1206         if (inode->i_nlink > 1) /* Shared inode; nothing more to do */
1207                 goto out_close_handle;
1208
1209         inode->i_attributes = file_info.dwFileAttributes;
1210         inode->i_creation_time = FILETIME_to_u64(&file_info.ftCreationTime);
1211         inode->i_last_write_time = FILETIME_to_u64(&file_info.ftLastWriteTime);
1212         inode->i_last_access_time = FILETIME_to_u64(&file_info.ftLastAccessTime);
1213         inode->i_resolved = 1;
1214
1215         params->add_image_flags &= ~(WIMLIB_ADD_IMAGE_FLAG_ROOT | WIMLIB_ADD_IMAGE_FLAG_SOURCE);
1216
1217         if (!(params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NO_ACLS)
1218             && (vol_flags & FILE_PERSISTENT_ACLS))
1219         {
1220                 ret = win32_get_security_descriptor(root, params->sd_set,
1221                                                     path, state,
1222                                                     params->add_image_flags);
1223                 if (ret)
1224                         goto out_close_handle;
1225         }
1226
1227         file_size = ((u64)file_info.nFileSizeHigh << 32) |
1228                      (u64)file_info.nFileSizeLow;
1229
1230         CloseHandle(hFile);
1231
1232         /* Capture the unnamed data stream (only should be present for regular
1233          * files) and any alternate data streams. */
1234         ret = win32_capture_streams(path,
1235                                     path_num_chars,
1236                                     inode,
1237                                     params->lookup_table,
1238                                     file_size,
1239                                     vol_flags);
1240         if (ret)
1241                 goto out;
1242
1243         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1244                 /* Reparse point: set the reparse data (which we read already)
1245                  * */
1246                 inode->i_not_rpfixed = not_rpfixed;
1247                 inode->i_reparse_tag = le32_to_cpu(*(u32*)rpbuf);
1248                 ret = inode_set_unnamed_stream(inode, rpbuf + 8, rpbuflen - 8,
1249                                                params->lookup_table);
1250         } else if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1251                 /* Directory (not a reparse point) --- recurse to children */
1252                 ret = win32_recurse_directory(root,
1253                                               path,
1254                                               path_num_chars,
1255                                               params,
1256                                               state,
1257                                               vol_flags);
1258         }
1259         goto out;
1260 out_close_handle:
1261         CloseHandle(hFile);
1262 out:
1263         if (ret == 0)
1264                 *root_ret = root;
1265         else
1266                 free_dentry_tree(root, params->lookup_table);
1267         return ret;
1268 }
1269
1270 static void
1271 win32_do_capture_warnings(const struct win32_capture_state *state,
1272                           int add_image_flags)
1273 {
1274         if (state->num_get_sacl_priv_notheld == 0 &&
1275             state->num_get_sd_access_denied == 0)
1276                 return;
1277
1278         WARNING("");
1279         WARNING("Built dentry tree successfully, but with the following problem(s):");
1280         if (state->num_get_sacl_priv_notheld != 0) {
1281                 WARNING("Could not capture SACL (System Access Control List)\n"
1282                         "          on %lu files or directories.",
1283                         state->num_get_sacl_priv_notheld);
1284         }
1285         if (state->num_get_sd_access_denied != 0) {
1286                 WARNING("Could not capture security descriptor at all\n"
1287                         "          on %lu files or directories.",
1288                         state->num_get_sd_access_denied);
1289         }
1290         WARNING(
1291           "Try running the program as the Administrator to make sure all the\n"
1292 "          desired metadata has been captured exactly.  However, if you\n"
1293 "          do not care about capturing security descriptors correctly, then\n"
1294 "          nothing more needs to be done%ls\n",
1295         (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NO_ACLS) ? L"." :
1296          L", although you might consider\n"
1297 "          passing the --no-acls flag to `wimlib-imagex capture' or\n"
1298 "          `wimlib-imagex append' to explicitly capture no security\n"
1299 "          descriptors.\n");
1300 }
1301
1302 /* Win32 version of capturing a directory tree */
1303 int
1304 win32_build_dentry_tree(struct wim_dentry **root_ret,
1305                         const wchar_t *root_disk_path,
1306                         struct add_image_params *params)
1307 {
1308         size_t path_nchars;
1309         wchar_t *path;
1310         int ret;
1311         struct win32_capture_state state;
1312         unsigned vol_flags;
1313
1314
1315         path_nchars = wcslen(root_disk_path);
1316         if (path_nchars > 32767)
1317                 return WIMLIB_ERR_INVALID_PARAM;
1318
1319         if (GetFileAttributesW(root_disk_path) == INVALID_FILE_ATTRIBUTES &&
1320             GetLastError() == ERROR_FILE_NOT_FOUND)
1321         {
1322                 ERROR("Capture directory \"%ls\" does not exist!",
1323                       root_disk_path);
1324                 return WIMLIB_ERR_OPENDIR;
1325         }
1326
1327         ret = win32_get_file_and_vol_ids(root_disk_path,
1328                                          &params->capture_root_ino,
1329                                          &params->capture_root_dev);
1330         if (ret)
1331                 return ret;
1332
1333         win32_get_vol_flags(root_disk_path, &vol_flags);
1334
1335         /* There is no check for overflow later when this buffer is being used!
1336          * But the max path length on NTFS is 32767 characters, and paths need
1337          * to be written specially to even go past 260 characters, so we should
1338          * be okay with 32770 characters. */
1339         path = MALLOC(32770 * sizeof(wchar_t));
1340         if (!path)
1341                 return WIMLIB_ERR_NOMEM;
1342
1343         wmemcpy(path, root_disk_path, path_nchars + 1);
1344
1345         memset(&state, 0, sizeof(state));
1346         ret = win32_build_dentry_tree_recursive(root_ret, path,
1347                                                 path_nchars, params,
1348                                                 &state, vol_flags);
1349         FREE(path);
1350         if (ret == 0)
1351                 win32_do_capture_warnings(&state, params->add_image_flags);
1352         return ret;
1353 }
1354
1355 static int
1356 win32_extract_try_rpfix(u8 *rpbuf,
1357                         const wchar_t *extract_root_realpath,
1358                         unsigned extract_root_realpath_nchars)
1359 {
1360         struct reparse_data rpdata;
1361         wchar_t *target;
1362         size_t target_nchars;
1363         size_t stripped_nchars;
1364         wchar_t *stripped_target;
1365         wchar_t stripped_target_nchars;
1366         int ret;
1367
1368         utf16lechar *new_target;
1369         utf16lechar *new_print_name;
1370         size_t new_target_nchars;
1371         size_t new_print_name_nchars;
1372         utf16lechar *p;
1373
1374         ret = parse_reparse_data(rpbuf, 8 + le16_to_cpu(*(u16*)(rpbuf + 4)),
1375                                  &rpdata);
1376         if (ret)
1377                 return ret;
1378
1379         if (extract_root_realpath[0] == L'\0' ||
1380             extract_root_realpath[1] != L':' ||
1381             extract_root_realpath[2] != L'\\')
1382         {
1383                 ERROR("Can't understand full path format \"%ls\".  "
1384                       "Try turning reparse point fixups off...",
1385                       extract_root_realpath);
1386                 return WIMLIB_ERR_REPARSE_POINT_FIXUP_FAILED;
1387         }
1388
1389         ret = parse_substitute_name(rpdata.substitute_name,
1390                                     rpdata.substitute_name_nbytes,
1391                                     rpdata.rptag);
1392         if (ret < 0)
1393                 return 0;
1394         stripped_nchars = ret;
1395         target = rpdata.substitute_name;
1396         target_nchars = rpdata.substitute_name_nbytes / sizeof(utf16lechar);
1397         stripped_target = target + 6;
1398         stripped_target_nchars = target_nchars - stripped_nchars;
1399
1400         new_target = alloca((6 + extract_root_realpath_nchars +
1401                              stripped_target_nchars) * sizeof(utf16lechar));
1402
1403         p = new_target;
1404         if (stripped_nchars == 6) {
1405                 /* Include \??\ prefix if it was present before */
1406                 wmemcpy(p, L"\\??\\", 4);
1407                 p += 4;
1408         }
1409
1410         /* Print name excludes the \??\ if present. */
1411         new_print_name = p;
1412         if (stripped_nchars != 0) {
1413                 /* Get drive letter from real path to extract root, if a drive
1414                  * letter was present before. */
1415                 *p++ = extract_root_realpath[0];
1416                 *p++ = extract_root_realpath[1];
1417         }
1418         /* Copy the rest of the extract root */
1419         wmemcpy(p, extract_root_realpath + 2, extract_root_realpath_nchars - 2);
1420         p += extract_root_realpath_nchars - 2;
1421
1422         /* Append the stripped target */
1423         wmemcpy(p, stripped_target, stripped_target_nchars);
1424         p += stripped_target_nchars;
1425         new_target_nchars = p - new_target;
1426         new_print_name_nchars = p - new_print_name;
1427
1428         if (new_target_nchars * sizeof(utf16lechar) >= REPARSE_POINT_MAX_SIZE ||
1429             new_print_name_nchars * sizeof(utf16lechar) >= REPARSE_POINT_MAX_SIZE)
1430         {
1431                 ERROR("Path names too long to do reparse point fixup!");
1432                 return WIMLIB_ERR_REPARSE_POINT_FIXUP_FAILED;
1433         }
1434         rpdata.substitute_name = new_target;
1435         rpdata.substitute_name_nbytes = new_target_nchars * sizeof(utf16lechar);
1436         rpdata.print_name = new_print_name;
1437         rpdata.print_name_nbytes = new_print_name_nchars * sizeof(utf16lechar);
1438         return make_reparse_buffer(&rpdata, rpbuf);
1439 }
1440
1441 /* Wrapper around the FSCTL_SET_REPARSE_POINT ioctl to set the reparse data on
1442  * an extracted reparse point. */
1443 static int
1444 win32_set_reparse_data(HANDLE h,
1445                        const struct wim_inode *inode,
1446                        const struct wim_lookup_table_entry *lte,
1447                        const wchar_t *path,
1448                        const struct apply_args *args)
1449 {
1450         int ret;
1451         u8 rpbuf[REPARSE_POINT_MAX_SIZE];
1452         DWORD bytesReturned;
1453
1454         DEBUG("Setting reparse data on \"%ls\"", path);
1455
1456         ret = wim_inode_get_reparse_data(inode, rpbuf);
1457         if (ret)
1458                 return ret;
1459
1460         if (args->extract_flags & WIMLIB_EXTRACT_FLAG_RPFIX &&
1461             (inode->i_reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
1462              inode->i_reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT) &&
1463             !inode->i_not_rpfixed)
1464         {
1465                 ret = win32_extract_try_rpfix(rpbuf,
1466                                               args->target_realpath,
1467                                               args->target_realpath_len);
1468                 if (ret)
1469                         return WIMLIB_ERR_REPARSE_POINT_FIXUP_FAILED;
1470         }
1471
1472         /* Set the reparse data on the open file using the
1473          * FSCTL_SET_REPARSE_POINT ioctl.
1474          *
1475          * There are contradictions in Microsoft's documentation for this:
1476          *
1477          * "If hDevice was opened without specifying FILE_FLAG_OVERLAPPED,
1478          * lpOverlapped is ignored."
1479          *
1480          * --- So setting lpOverlapped to NULL is okay since it's ignored.
1481          *
1482          * "If lpOverlapped is NULL, lpBytesReturned cannot be NULL. Even when an
1483          * operation returns no output data and lpOutBuffer is NULL,
1484          * DeviceIoControl makes use of lpBytesReturned. After such an
1485          * operation, the value of lpBytesReturned is meaningless."
1486          *
1487          * --- So lpOverlapped not really ignored, as it affects another
1488          *  parameter.  This is the actual behavior: lpBytesReturned must be
1489          *  specified, even though lpBytesReturned is documented as:
1490          *
1491          *  "Not used with this operation; set to NULL."
1492          */
1493         if (!DeviceIoControl(h, FSCTL_SET_REPARSE_POINT, rpbuf,
1494                              8 + le16_to_cpu(*(u16*)(rpbuf + 4)),
1495                              NULL, 0,
1496                              &bytesReturned /* lpBytesReturned */,
1497                              NULL /* lpOverlapped */))
1498         {
1499                 DWORD err = GetLastError();
1500                 ERROR("Failed to set reparse data on \"%ls\"", path);
1501                 win32_error(err);
1502                 if (err == ERROR_ACCESS_DENIED || err == ERROR_PRIVILEGE_NOT_HELD)
1503                         return WIMLIB_ERR_INSUFFICIENT_PRIVILEGES_TO_EXTRACT;
1504                 else if (inode->i_reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
1505                          inode->i_reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT)
1506                         return WIMLIB_ERR_LINK;
1507                 else
1508                         return WIMLIB_ERR_WRITE;
1509         }
1510         return 0;
1511 }
1512
1513 /* Wrapper around the FSCTL_SET_COMPRESSION ioctl to change the
1514  * FILE_ATTRIBUTE_COMPRESSED flag of a file or directory. */
1515 static int
1516 win32_set_compression_state(HANDLE hFile, USHORT format, const wchar_t *path)
1517 {
1518         DWORD bytesReturned;
1519         if (!DeviceIoControl(hFile, FSCTL_SET_COMPRESSION,
1520                              &format, sizeof(USHORT),
1521                              NULL, 0,
1522                              &bytesReturned, NULL))
1523         {
1524                 /* Could be a warning only, but we only call this if the volume
1525                  * supports compression.  So I'm calling this an error. */
1526                 DWORD err = GetLastError();
1527                 ERROR("Failed to set compression flag on \"%ls\"", path);
1528                 win32_error(err);
1529                 if (err == ERROR_ACCESS_DENIED || err == ERROR_PRIVILEGE_NOT_HELD)
1530                         return WIMLIB_ERR_INSUFFICIENT_PRIVILEGES_TO_EXTRACT;
1531                 else
1532                         return WIMLIB_ERR_WRITE;
1533         }
1534         return 0;
1535 }
1536
1537 /* Wrapper around FSCTL_SET_SPARSE ioctl to set a file as sparse. */
1538 static int
1539 win32_set_sparse(HANDLE hFile, const wchar_t *path)
1540 {
1541         DWORD bytesReturned;
1542         if (!DeviceIoControl(hFile, FSCTL_SET_SPARSE,
1543                              NULL, 0,
1544                              NULL, 0,
1545                              &bytesReturned, NULL))
1546         {
1547                 /* Could be a warning only, but we only call this if the volume
1548                  * supports sparse files.  So I'm calling this an error. */
1549                 DWORD err = GetLastError();
1550                 WARNING("Failed to set sparse flag on \"%ls\"", path);
1551                 win32_error(err);
1552                 if (err == ERROR_ACCESS_DENIED || err == ERROR_PRIVILEGE_NOT_HELD)
1553                         return WIMLIB_ERR_INSUFFICIENT_PRIVILEGES_TO_EXTRACT;
1554                 else
1555                         return WIMLIB_ERR_WRITE;
1556         }
1557         return 0;
1558 }
1559
1560 /*
1561  * Sets the security descriptor on an extracted file.
1562  */
1563 static int
1564 win32_set_security_data(const struct wim_inode *inode,
1565                         HANDLE hFile,
1566                         const wchar_t *path,
1567                         struct apply_args *args)
1568 {
1569         PSECURITY_DESCRIPTOR descriptor;
1570         unsigned long n;
1571         DWORD err;
1572         const struct wim_security_data *sd;
1573
1574         SECURITY_INFORMATION securityInformation = 0;
1575
1576         void *owner = NULL;
1577         void *group = NULL;
1578         ACL *dacl = NULL;
1579         ACL *sacl = NULL;
1580
1581         BOOL owner_defaulted;
1582         BOOL group_defaulted;
1583         BOOL dacl_present;
1584         BOOL dacl_defaulted;
1585         BOOL sacl_present;
1586         BOOL sacl_defaulted;
1587
1588         sd = wim_const_security_data(args->w);
1589         descriptor = sd->descriptors[inode->i_security_id];
1590
1591         GetSecurityDescriptorOwner(descriptor, &owner, &owner_defaulted);
1592         if (owner)
1593                 securityInformation |= OWNER_SECURITY_INFORMATION;
1594
1595         GetSecurityDescriptorGroup(descriptor, &group, &group_defaulted);
1596         if (group)
1597                 securityInformation |= GROUP_SECURITY_INFORMATION;
1598
1599         GetSecurityDescriptorDacl(descriptor, &dacl_present,
1600                                   &dacl, &dacl_defaulted);
1601         if (dacl)
1602                 securityInformation |= DACL_SECURITY_INFORMATION;
1603
1604         GetSecurityDescriptorSacl(descriptor, &sacl_present,
1605                                   &sacl, &sacl_defaulted);
1606         if (sacl)
1607                 securityInformation |= SACL_SECURITY_INFORMATION;
1608
1609 again:
1610         if (securityInformation == 0)
1611                 return 0;
1612         if (SetSecurityInfo(hFile, SE_FILE_OBJECT,
1613                             securityInformation, owner, group, dacl, sacl))
1614                 return 0;
1615         err = GetLastError();
1616         if (args->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS)
1617                 goto fail;
1618         switch (err) {
1619         case ERROR_PRIVILEGE_NOT_HELD:
1620                 if (securityInformation & SACL_SECURITY_INFORMATION) {
1621                         n = args->num_set_sacl_priv_notheld++;
1622                         securityInformation &= ~SACL_SECURITY_INFORMATION;
1623                         sacl = NULL;
1624                         if (n < MAX_SET_SACL_PRIV_NOTHELD_WARNINGS) {
1625                                 WARNING(
1626 "We don't have enough privileges to set the full security\n"
1627 "          descriptor on \"%ls\"!\n", path);
1628                                 if (args->num_set_sd_access_denied +
1629                                     args->num_set_sacl_priv_notheld == 1)
1630                                 {
1631                                         WARNING("%ls", apply_access_denied_msg);
1632                                 }
1633                                 WARNING("Re-trying with SACL omitted.\n", path);
1634                         } else if (n == MAX_GET_SACL_PRIV_NOTHELD_WARNINGS) {
1635                                 WARNING(
1636 "Suppressing further 'privileges not held' error messages when setting\n"
1637 "          security descriptors.");
1638                         }
1639                         goto again;
1640                 }
1641                 /* Fall through */
1642         case ERROR_INVALID_OWNER:
1643         case ERROR_ACCESS_DENIED:
1644                 n = args->num_set_sd_access_denied++;
1645                 if (n < MAX_SET_SD_ACCESS_DENIED_WARNINGS) {
1646                         WARNING("Failed to set security descriptor on \"%ls\": "
1647                                 "Access denied!\n", path);
1648                         if (args->num_set_sd_access_denied +
1649                             args->num_set_sacl_priv_notheld == 1)
1650                         {
1651                                 WARNING("%ls", apply_access_denied_msg);
1652                         }
1653                 } else if (n == MAX_SET_SD_ACCESS_DENIED_WARNINGS) {
1654                         WARNING(
1655 "Suppressing further access denied error messages when setting\n"
1656 "          security descriptors");
1657                 }
1658                 return 0;
1659         default:
1660 fail:
1661                 ERROR("Failed to set security descriptor on \"%ls\"", path);
1662                 win32_error(err);
1663                 if (err == ERROR_ACCESS_DENIED || err == ERROR_PRIVILEGE_NOT_HELD)
1664                         return WIMLIB_ERR_INSUFFICIENT_PRIVILEGES_TO_EXTRACT;
1665                 else
1666                         return WIMLIB_ERR_WRITE;
1667         }
1668 }
1669
1670
1671 static int
1672 win32_extract_chunk(const void *buf, size_t len, void *arg)
1673 {
1674         HANDLE hStream = arg;
1675
1676         DWORD nbytes_written;
1677         wimlib_assert(len <= 0xffffffff);
1678
1679         if (!WriteFile(hStream, buf, len, &nbytes_written, NULL) ||
1680             nbytes_written != len)
1681         {
1682                 DWORD err = GetLastError();
1683                 ERROR("WriteFile(): write error");
1684                 win32_error(err);
1685                 return WIMLIB_ERR_WRITE;
1686         }
1687         return 0;
1688 }
1689
1690 static int
1691 do_win32_extract_stream(HANDLE hStream, const struct wim_lookup_table_entry *lte)
1692 {
1693         return extract_wim_resource(lte, wim_resource_size(lte),
1694                                     win32_extract_chunk, hStream);
1695 }
1696
1697 struct win32_encrypted_extract_ctx {
1698         const struct wim_lookup_table_entry *lte;
1699         u64 offset;
1700 };
1701
1702 static DWORD WINAPI
1703 win32_encrypted_import_cb(unsigned char *data, void *_ctx,
1704                           unsigned long *len_p)
1705 {
1706         struct win32_encrypted_extract_ctx *ctx = _ctx;
1707         unsigned long len = *len_p;
1708         const struct wim_lookup_table_entry *lte = ctx->lte;
1709
1710         len = min(len, wim_resource_size(lte) - ctx->offset);
1711
1712         if (read_partial_wim_resource_into_buf(lte, len, ctx->offset, data, false))
1713                 return ERROR_READ_FAULT;
1714
1715         ctx->offset += len;
1716         *len_p = len;
1717         return ERROR_SUCCESS;
1718 }
1719
1720 /* Create an encrypted file and extract the raw encrypted data to it.
1721  *
1722  * @path:  Path to encrypted file to create.
1723  * @lte:   WIM lookup_table entry for the raw encrypted data.
1724  *
1725  * This is separate from do_win32_extract_stream() because the WIM is supposed
1726  * to contain the *raw* encrypted data, which needs to be extracted ("imported")
1727  * using the special APIs OpenEncryptedFileRawW(), WriteEncryptedFileRaw(), and
1728  * CloseEncryptedFileRaw().
1729  *
1730  * Returns 0 on success; nonzero on failure.
1731  */
1732 static int
1733 do_win32_extract_encrypted_stream(const wchar_t *path,
1734                                   const struct wim_lookup_table_entry *lte)
1735 {
1736         void *file_ctx;
1737         int ret;
1738
1739         DEBUG("Opening file \"%ls\" to extract raw encrypted data", path);
1740
1741         ret = OpenEncryptedFileRawW(path, CREATE_FOR_IMPORT, &file_ctx);
1742         if (ret) {
1743                 ERROR("Failed to open \"%ls\" to write raw encrypted data", path);
1744                 win32_error(ret);
1745                 return WIMLIB_ERR_OPEN;
1746         }
1747
1748         if (lte) {
1749                 struct win32_encrypted_extract_ctx ctx;
1750
1751                 ctx.lte = lte;
1752                 ctx.offset = 0;
1753                 ret = WriteEncryptedFileRaw(win32_encrypted_import_cb, &ctx, file_ctx);
1754                 if (ret == ERROR_SUCCESS) {
1755                         ret = 0;
1756                 } else {
1757                         ret = WIMLIB_ERR_WRITE;
1758                         ERROR("Failed to extract encrypted file \"%ls\"", path);
1759                 }
1760         }
1761         CloseEncryptedFileRaw(file_ctx);
1762         return ret;
1763 }
1764
1765 static bool
1766 path_is_root_of_drive(const wchar_t *path)
1767 {
1768         if (!*path)
1769                 return false;
1770
1771         if (*path != L'/' && *path != L'\\') {
1772                 if (*(path + 1) == L':')
1773                         path += 2;
1774                 else
1775                         return false;
1776         }
1777         while (*path == L'/' || *path == L'\\')
1778                 path++;
1779         return (*path == L'\0');
1780 }
1781
1782 static inline DWORD
1783 win32_mask_attributes(DWORD i_attributes)
1784 {
1785         return i_attributes & ~(FILE_ATTRIBUTE_SPARSE_FILE |
1786                                 FILE_ATTRIBUTE_COMPRESSED |
1787                                 FILE_ATTRIBUTE_REPARSE_POINT |
1788                                 FILE_ATTRIBUTE_DIRECTORY |
1789                                 FILE_ATTRIBUTE_ENCRYPTED |
1790                                 FILE_FLAG_DELETE_ON_CLOSE |
1791                                 FILE_FLAG_NO_BUFFERING |
1792                                 FILE_FLAG_OPEN_NO_RECALL |
1793                                 FILE_FLAG_OVERLAPPED |
1794                                 FILE_FLAG_RANDOM_ACCESS |
1795                                 /*FILE_FLAG_SESSION_AWARE |*/
1796                                 FILE_FLAG_SEQUENTIAL_SCAN |
1797                                 FILE_FLAG_WRITE_THROUGH);
1798 }
1799
1800 static inline DWORD
1801 win32_get_create_flags_and_attributes(DWORD i_attributes)
1802 {
1803         /*
1804          * Some attributes cannot be set by passing them to CreateFile().  In
1805          * particular:
1806          *
1807          * FILE_ATTRIBUTE_DIRECTORY:
1808          *   CreateDirectory() must be called instead of CreateFile().
1809          *
1810          * FILE_ATTRIBUTE_SPARSE_FILE:
1811          *   Needs an ioctl.
1812          *   See: win32_set_sparse().
1813          *
1814          * FILE_ATTRIBUTE_COMPRESSED:
1815          *   Not clear from the documentation, but apparently this needs an
1816          *   ioctl as well.
1817          *   See: win32_set_compressed().
1818          *
1819          * FILE_ATTRIBUTE_REPARSE_POINT:
1820          *   Needs an ioctl, with the reparse data specified.
1821          *   See: win32_set_reparse_data().
1822          *
1823          * In addition, clear any file flags in the attributes that we don't
1824          * want, but also specify FILE_FLAG_OPEN_REPARSE_POINT and
1825          * FILE_FLAG_BACKUP_SEMANTICS as we are a backup application.
1826          */
1827         return win32_mask_attributes(i_attributes) |
1828                 FILE_FLAG_OPEN_REPARSE_POINT |
1829                 FILE_FLAG_BACKUP_SEMANTICS;
1830 }
1831
1832 /* Set compression and/or sparse attributes on a stream, if supported by the
1833  * volume. */
1834 static int
1835 win32_set_special_stream_attributes(HANDLE hFile, const struct wim_inode *inode,
1836                                     struct wim_lookup_table_entry *unnamed_stream_lte,
1837                                     const wchar_t *path, unsigned vol_flags)
1838 {
1839         int ret;
1840
1841         if (inode->i_attributes & FILE_ATTRIBUTE_COMPRESSED) {
1842                 if (vol_flags & FILE_FILE_COMPRESSION) {
1843                         ret = win32_set_compression_state(hFile,
1844                                                           COMPRESSION_FORMAT_DEFAULT,
1845                                                           path);
1846                         if (ret)
1847                                 return ret;
1848                 } else {
1849                         DEBUG("Cannot set compression attribute on \"%ls\": "
1850                               "volume does not support transparent compression",
1851                               path);
1852                 }
1853         }
1854
1855         if (inode->i_attributes & FILE_ATTRIBUTE_SPARSE_FILE) {
1856                 if (vol_flags & FILE_SUPPORTS_SPARSE_FILES) {
1857                         DEBUG("Setting sparse flag on \"%ls\"", path);
1858                         ret = win32_set_sparse(hFile, path);
1859                         if (ret)
1860                                 return ret;
1861                 } else {
1862                         DEBUG("Cannot set sparse attribute on \"%ls\": "
1863                               "volume does not support sparse files",
1864                               path);
1865                 }
1866         }
1867         return 0;
1868 }
1869
1870 /* Pre-create directories; extract encrypted streams */
1871 static int
1872 win32_begin_extract_unnamed_stream(const struct wim_inode *inode,
1873                                    const struct wim_lookup_table_entry *lte,
1874                                    const wchar_t *path,
1875                                    DWORD *creationDisposition_ret,
1876                                    unsigned int vol_flags)
1877 {
1878         DWORD err;
1879         int ret;
1880
1881         /* Directories must be created with CreateDirectoryW().  Then the call
1882          * to CreateFileW() will merely open the directory that was already
1883          * created rather than creating a new file. */
1884         if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY &&
1885             !path_is_root_of_drive(path)) {
1886                 if (!CreateDirectoryW(path, NULL)) {
1887                         err = GetLastError();
1888                         if (err != ERROR_ALREADY_EXISTS) {
1889                                 ERROR("Failed to create directory \"%ls\"",
1890                                       path);
1891                                 win32_error(err);
1892                                 return WIMLIB_ERR_MKDIR;
1893                         }
1894                 }
1895                 DEBUG("Created directory \"%ls\"", path);
1896                 *creationDisposition_ret = OPEN_EXISTING;
1897         }
1898         if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED &&
1899             vol_flags & FILE_SUPPORTS_ENCRYPTION)
1900         {
1901                 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1902                         unsigned remaining_sharing_violations = 100;
1903                         while (!EncryptFile(path)) {
1904                                 if (remaining_sharing_violations &&
1905                                     err == ERROR_SHARING_VIOLATION)
1906                                 {
1907                                         WARNING("Couldn't encrypt directory \"%ls\" "
1908                                                 "due to sharing violation; re-trying "
1909                                                 "after 100 ms", path);
1910                                         Sleep(100);
1911                                         remaining_sharing_violations--;
1912                                 } else {
1913                                         err = GetLastError();
1914                                         ERROR("Failed to encrypt directory \"%ls\"",
1915                                               path);
1916                                         win32_error(err);
1917                                         return WIMLIB_ERR_WRITE;
1918                                 }
1919                         }
1920                 } else {
1921                         ret = do_win32_extract_encrypted_stream(path, lte);
1922                         if (ret)
1923                                 return ret;
1924                         DEBUG("Extracted encrypted file \"%ls\"", path);
1925                 }
1926                 *creationDisposition_ret = OPEN_EXISTING;
1927         }
1928
1929         /* Set file attributes if we created the file.  Otherwise, we haven't
1930          * created the file set and we will set the attributes in the call to
1931          * CreateFileW().
1932          *
1933          * The FAT filesystem does not let you change the attributes of the root
1934          * directory, so treat that as a special case and do not set attributes.
1935          * */
1936         if (*creationDisposition_ret == OPEN_EXISTING &&
1937             !path_is_root_of_drive(path))
1938         {
1939                 if (!SetFileAttributesW(path,
1940                                         win32_mask_attributes(inode->i_attributes)))
1941                 {
1942                         err = GetLastError();
1943                         ERROR("Failed to set attributes on \"%ls\"", path);
1944                         win32_error(err);
1945                         return WIMLIB_ERR_WRITE;
1946                 }
1947         }
1948         return 0;
1949 }
1950
1951 /* Set security descriptor and extract stream data or reparse data (skip the
1952  * unnamed data stream of encrypted files, which was already extracted). */
1953 static int
1954 win32_finish_extract_stream(HANDLE h, const struct wim_inode *inode,
1955                             const struct wim_lookup_table_entry *lte,
1956                             const wchar_t *stream_path,
1957                             const wchar_t *stream_name_utf16,
1958                             struct apply_args *args)
1959 {
1960         int ret = 0;
1961         if (stream_name_utf16 == NULL) {
1962                 /* Unnamed stream. */
1963
1964                 /* Set security descriptor, unless the extract_flags indicate
1965                  * not to or the volume does not supported it.  Note that this
1966                  * is only done when the unnamed stream is being extracted, as
1967                  * security descriptors are per-file and not per-stream. */
1968                 if (inode->i_security_id >= 0 &&
1969                     !(args->extract_flags & WIMLIB_EXTRACT_FLAG_NO_ACLS)
1970                     && (args->vol_flags & FILE_PERSISTENT_ACLS))
1971                 {
1972                         ret = win32_set_security_data(inode, h, stream_path, args);
1973                         if (ret)
1974                                 return ret;
1975                 }
1976
1977                 /* Handle reparse points.  The data for them needs to be set
1978                  * using a special ioctl.  Note that the reparse point may have
1979                  * been created using CreateFileW() in the case of
1980                  * non-directories or CreateDirectoryW() in the case of
1981                  * directories; but the ioctl works either way.  Also, it is
1982                  * only this step that actually sets the
1983                  * FILE_ATTRIBUTE_REPARSE_POINT, as it is not valid to set it
1984                  * using SetFileAttributesW() or CreateFileW().
1985                  *
1986                  * If the volume does not support reparse points we simply
1987                  * ignore the reparse data.  (N.B. the code currently doesn't
1988                  * actually reach this case because reparse points are skipped
1989                  * entirely on such volumes.) */
1990                 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1991                         if (args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS) {
1992                                 ret = win32_set_reparse_data(h, inode,
1993                                                              lte, stream_path,
1994                                                              args);
1995                                 if (ret)
1996                                         return ret;
1997                         } else {
1998                                 DEBUG("Cannot set reparse data on \"%ls\": volume "
1999                                       "does not support reparse points", stream_path);
2000                         }
2001                 } else if (lte != NULL &&
2002                            !(args->vol_flags & FILE_SUPPORTS_ENCRYPTION &&
2003                              inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED))
2004                 {
2005                         /* Extract the data of the unnamed stream, unless the
2006                          * lookup table entry is NULL (indicating an empty
2007                          * stream for which no data needs to be extracted), or
2008                          * the stream is encrypted and therefore was already
2009                          * extracted as a special case. */
2010                         ret = do_win32_extract_stream(h, lte);
2011                 }
2012         } else {
2013                 /* Extract the data for a named data stream. */
2014                 if (lte != NULL) {
2015                         DEBUG("Extracting named data stream \"%ls\" (len = %"PRIu64")",
2016                               stream_path, wim_resource_size(lte));
2017                         ret = do_win32_extract_stream(h, lte);
2018                 }
2019         }
2020         return ret;
2021 }
2022
2023 static int
2024 win32_decrypt_file(HANDLE open_handle, const wchar_t *path)
2025 {
2026         DWORD err;
2027         /* We cannot call DecryptFileW() while there is an open handle to the
2028          * file.  So close it first. */
2029         if (!CloseHandle(open_handle)) {
2030                 err = GetLastError();
2031                 ERROR("Failed to close handle for \"%ls\"", path);
2032                 win32_error(err);
2033                 return WIMLIB_ERR_WRITE;
2034         }
2035         if (!DecryptFileW(path, 0 /* reserved parameter; set to 0 */)) {
2036                 err = GetLastError();
2037                 ERROR("Failed to decrypt file \"%ls\"", path);
2038                 win32_error(err);
2039                 return WIMLIB_ERR_WRITE;
2040         }
2041         return 0;
2042 }
2043
2044 /*
2045  * Create and extract a stream to a file, or create a directory, using the
2046  * Windows API.
2047  *
2048  * This handles reparse points, directories, alternate data streams, encrypted
2049  * files, compressed files, etc.
2050  *
2051  * @inode: WIM inode containing the stream.
2052  *
2053  * @path:  Path to extract the file to.
2054  *
2055  * @stream_name_utf16:
2056  *         Name of the stream, or NULL if the stream is unnamed.  This will
2057  *         be called with a NULL stream_name_utf16 before any non-NULL
2058  *         stream_name_utf16's.
2059  *
2060  * @lte:   WIM lookup table entry for the stream.  May be NULL to indicate
2061  *         a stream of length 0.
2062  *
2063  * @args:  Additional apply context, including flags indicating supported
2064  *         volume features.
2065  *
2066  * Returns 0 on success; nonzero on failure.
2067  */
2068 static int
2069 win32_extract_stream(const struct wim_inode *inode,
2070                      const wchar_t *path,
2071                      const wchar_t *stream_name_utf16,
2072                      struct wim_lookup_table_entry *lte,
2073                      struct apply_args *args)
2074 {
2075         wchar_t *stream_path;
2076         HANDLE h;
2077         int ret;
2078         DWORD err;
2079         DWORD creationDisposition = CREATE_ALWAYS;
2080         DWORD requestedAccess;
2081         BY_HANDLE_FILE_INFORMATION file_info;
2082         unsigned remaining_sharing_violations = 1000;
2083
2084         if (stream_name_utf16) {
2085                 /* Named stream.  Create a buffer that contains the UTF-16LE
2086                  * string [./]path:stream_name_utf16.  This is needed to
2087                  * create and open the stream using CreateFileW().  I'm not
2088                  * aware of any other APIs to do this.  Note: the '$DATA' suffix
2089                  * seems to be unneeded.  Additional note: a "./" prefix needs
2090                  * to be added when the path is not absolute to avoid ambiguity
2091                  * with drive letters. */
2092                 size_t stream_path_nchars;
2093                 size_t path_nchars;
2094                 size_t stream_name_nchars;
2095                 const wchar_t *prefix;
2096
2097                 path_nchars = wcslen(path);
2098                 stream_name_nchars = wcslen(stream_name_utf16);
2099                 stream_path_nchars = path_nchars + 1 + stream_name_nchars;
2100                 if (path[0] != cpu_to_le16(L'\0') &&
2101                     path[0] != cpu_to_le16(L'/') &&
2102                     path[0] != cpu_to_le16(L'\\') &&
2103                     path[1] != cpu_to_le16(L':'))
2104                 {
2105                         prefix = L"./";
2106                         stream_path_nchars += 2;
2107                 } else {
2108                         prefix = L"";
2109                 }
2110                 stream_path = alloca((stream_path_nchars + 1) * sizeof(wchar_t));
2111                 swprintf(stream_path, L"%ls%ls:%ls",
2112                          prefix, path, stream_name_utf16);
2113         } else {
2114                 /* Unnamed stream; its path is just the path to the file itself.
2115                  * */
2116                 stream_path = (wchar_t*)path;
2117
2118                 ret = win32_begin_extract_unnamed_stream(inode, lte, path,
2119                                                          &creationDisposition,
2120                                                          args->vol_flags);
2121                 if (ret)
2122                         goto fail;
2123         }
2124
2125         DEBUG("Opening \"%ls\"", stream_path);
2126         requestedAccess = GENERIC_READ | GENERIC_WRITE |
2127                           ACCESS_SYSTEM_SECURITY;
2128 try_open_again:
2129         /* Open the stream to be extracted.  Depending on what we have set
2130          * creationDisposition to, we may be creating this for the first time,
2131          * or we may be opening on existing stream we already created using
2132          * CreateDirectoryW() or OpenEncryptedFileRawW(). */
2133         h = CreateFileW(stream_path,
2134                         requestedAccess,
2135                         FILE_SHARE_READ,
2136                         NULL,
2137                         creationDisposition,
2138                         win32_get_create_flags_and_attributes(inode->i_attributes),
2139                         NULL);
2140         if (h == INVALID_HANDLE_VALUE) {
2141                 err = GetLastError();
2142                 if (err == ERROR_ACCESS_DENIED &&
2143                     path_is_root_of_drive(stream_path))
2144                 {
2145                         ret = 0;
2146                         goto out;
2147                 }
2148                 if ((err == ERROR_PRIVILEGE_NOT_HELD ||
2149                      err == ERROR_ACCESS_DENIED) &&
2150                     (requestedAccess & ACCESS_SYSTEM_SECURITY))
2151                 {
2152                         /* Try opening the file again without privilege to
2153                          * modify SACL. */
2154                         requestedAccess &= ~ACCESS_SYSTEM_SECURITY;
2155                         goto try_open_again;
2156                 }
2157                 if (err == ERROR_SHARING_VIOLATION) {
2158                         if (remaining_sharing_violations) {
2159                                 --remaining_sharing_violations;
2160                                 /* This can happen when restoring encrypted directories
2161                                  * for some reason.  Probably a bug in EncryptFile(). */
2162                                 WARNING("Couldn't open \"%ls\" due to sharing violation; "
2163                                         "re-trying after 100ms", stream_path);
2164                                 Sleep(100);
2165                                 goto try_open_again;
2166                         } else {
2167                                 ERROR("Too many sharing violations; giving up...");
2168                         }
2169                 } else {
2170                         if (creationDisposition == OPEN_EXISTING)
2171                                 ERROR("Failed to open \"%ls\"", stream_path);
2172                         else
2173                                 ERROR("Failed to create \"%ls\"", stream_path);
2174                         win32_error(err);
2175                 }
2176                 ret = WIMLIB_ERR_OPEN;
2177                 goto fail;
2178         }
2179
2180         /* Check the attributes of the file we just opened, and remove
2181          * encryption or compression if either was set by default but is not
2182          * supposed to be set based on the WIM inode attributes. */
2183         if (!GetFileInformationByHandle(h, &file_info)) {
2184                 err = GetLastError();
2185                 ERROR("Failed to get attributes of \"%ls\"", stream_path);
2186                 win32_error(err);
2187                 ret = WIMLIB_ERR_STAT;
2188                 goto fail_close_handle;
2189         }
2190
2191         /* Remove encryption? */
2192         if (file_info.dwFileAttributes & FILE_ATTRIBUTE_ENCRYPTED &&
2193             !(inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED))
2194         {
2195                 /* File defaulted to encrypted due to being in an encrypted
2196                  * directory, but is not actually supposed to be encrypted.
2197                  *
2198                  * This is a workaround, because I'm not aware of any way to
2199                  * directly (e.g. with CreateFileW()) create an unencrypted file
2200                  * in a directory with FILE_ATTRIBUTE_ENCRYPTED set. */
2201                 ret = win32_decrypt_file(h, stream_path);
2202                 if (ret)
2203                         goto fail; /* win32_decrypt_file() closed the handle. */
2204                 creationDisposition = OPEN_EXISTING;
2205                 goto try_open_again;
2206         }
2207
2208         /* Remove compression? */
2209         if (file_info.dwFileAttributes & FILE_ATTRIBUTE_COMPRESSED &&
2210             !(inode->i_attributes & FILE_ATTRIBUTE_COMPRESSED))
2211         {
2212                 /* Similar to the encrypted case, above, if the file defaulted
2213                  * to compressed due to being in an compressed directory, but is
2214                  * not actually supposed to be compressed, explicitly set the
2215                  * compression format to COMPRESSION_FORMAT_NONE. */
2216                 ret = win32_set_compression_state(h, COMPRESSION_FORMAT_NONE,
2217                                                   stream_path);
2218                 if (ret)
2219                         goto fail_close_handle;
2220         }
2221
2222         /* Set compression and/or sparse attributes if needed */
2223         ret = win32_set_special_stream_attributes(h, inode, lte, path,
2224                                                   args->vol_flags);
2225
2226         if (ret)
2227                 goto fail_close_handle;
2228
2229         /* At this point we have at least created the needed stream with the
2230          * appropriate attributes.  We have yet to set the appropriate security
2231          * descriptor and actually extract the stream data (other than for
2232          * extracted files, which were already extracted).
2233          * win32_finish_extract_stream() handles these additional steps. */
2234         ret = win32_finish_extract_stream(h, inode, lte, stream_path,
2235                                           stream_name_utf16, args);
2236         if (ret)
2237                 goto fail_close_handle;
2238
2239         /* Done extracting the stream.  Close the handle and return. */
2240         DEBUG("Closing \"%ls\"", stream_path);
2241         if (!CloseHandle(h)) {
2242                 err = GetLastError();
2243                 ERROR("Failed to close \"%ls\"", stream_path);
2244                 win32_error(err);
2245                 ret = WIMLIB_ERR_WRITE;
2246                 goto fail;
2247         }
2248         ret = 0;
2249         goto out;
2250 fail_close_handle:
2251         CloseHandle(h);
2252 fail:
2253         ERROR("Error extracting \"%ls\"", stream_path);
2254 out:
2255         return ret;
2256 }
2257
2258 /*
2259  * Creates a file, directory, or reparse point and extracts all streams to it
2260  * (unnamed data stream and/or reparse point stream, plus any alternate data
2261  * streams).  Handles sparse, compressed, and/or encrypted files.
2262  *
2263  * @inode:      WIM inode for this file or directory.
2264  * @path:       UTF-16LE external path to extract the inode to.
2265  * @args:       Additional extraction context.
2266  *
2267  * Returns 0 on success; nonzero on failure.
2268  */
2269 static int
2270 win32_extract_streams(const struct wim_inode *inode,
2271                       const wchar_t *path, struct apply_args *args)
2272 {
2273         struct wim_lookup_table_entry *unnamed_lte;
2274         int ret;
2275
2276         /* First extract the unnamed stream. */
2277
2278         unnamed_lte = inode_unnamed_lte_resolved(inode);
2279         ret = win32_extract_stream(inode, path, NULL, unnamed_lte, args);
2280         if (ret)
2281                 goto out;
2282
2283         /* Extract any named streams, if supported by the volume. */
2284
2285         if (!(args->vol_flags & FILE_NAMED_STREAMS))
2286                 goto out;
2287         for (u16 i = 0; i < inode->i_num_ads; i++) {
2288                 const struct wim_ads_entry *ads_entry = &inode->i_ads_entries[i];
2289
2290                 /* Skip the unnamed stream if it's in the ADS entries (we
2291                  * already extracted it...) */
2292                 if (ads_entry->stream_name_nbytes == 0)
2293                         continue;
2294
2295                 /* Skip special UNIX data entries (see documentation for
2296                  * WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA) */
2297                 if (ads_entry->stream_name_nbytes == WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES
2298                     && !memcmp(ads_entry->stream_name,
2299                                WIMLIB_UNIX_DATA_TAG_UTF16LE,
2300                                WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES))
2301                         continue;
2302
2303                 /* Extract the named stream */
2304                 ret = win32_extract_stream(inode,
2305                                            path,
2306                                            ads_entry->stream_name,
2307                                            ads_entry->lte,
2308                                            args);
2309                 if (ret)
2310                         break;
2311         }
2312 out:
2313         return ret;
2314 }
2315
2316 /* If not done already, load the supported feature flags for the volume onto
2317  * which the image is being extracted, and warn the user about any missing
2318  * features that could be important. */
2319 static int
2320 win32_check_vol_flags(const wchar_t *output_path, struct apply_args *args)
2321 {
2322         if (args->have_vol_flags)
2323                 return 0;
2324
2325         win32_get_vol_flags(output_path, &args->vol_flags);
2326         args->have_vol_flags = true;
2327         /* Warn the user about data that may not be extracted. */
2328         if (!(args->vol_flags & FILE_SUPPORTS_SPARSE_FILES))
2329                 WARNING("Volume does not support sparse files!\n"
2330                         "          Sparse files will be extracted as non-sparse.");
2331         if (!(args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS))
2332                 WARNING("Volume does not support reparse points!\n"
2333                         "          Reparse point data will not be extracted.");
2334         if (!(args->vol_flags & FILE_NAMED_STREAMS)) {
2335                 WARNING("Volume does not support named data streams!\n"
2336                         "          Named data streams will not be extracted.");
2337         }
2338         if (!(args->vol_flags & FILE_SUPPORTS_ENCRYPTION)) {
2339                 WARNING("Volume does not support encryption!\n"
2340                         "          Encrypted files will be extracted as raw data.");
2341         }
2342         if (!(args->vol_flags & FILE_FILE_COMPRESSION)) {
2343                 WARNING("Volume does not support transparent compression!\n"
2344                         "          Compressed files will be extracted as non-compressed.");
2345         }
2346         if (!(args->vol_flags & FILE_PERSISTENT_ACLS)) {
2347                 if (args->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS) {
2348                         ERROR("Strict ACLs requested, but the volume does not "
2349                               "support ACLs!");
2350                         return WIMLIB_ERR_VOLUME_LACKS_FEATURES;
2351                 } else {
2352                         WARNING("Volume does not support persistent ACLS!\n"
2353                                 "          File permissions will not be extracted.");
2354                 }
2355         }
2356         return 0;
2357 }
2358
2359 /*
2360  * Try extracting a hard link.
2361  *
2362  * @output_path:  Path to link to be extracted.
2363  *
2364  * @inode:        WIM inode that the link is to; inode->i_extracted_file
2365  *                the path to a name of the file that has already been
2366  *                extracted (we use this to create the hard link).
2367  *
2368  * @args:         Additional apply context, used here to keep track of
2369  *                the number of times creating a hard link failed due to
2370  *                ERROR_INVALID_FUNCTION.  This error should indicate that hard
2371  *                links are not supported by the volume, and we would like to
2372  *                warn the user a few times, but not too many times.
2373  *
2374  * Returns 0 if the hard link was successfully extracted.  Returns
2375  * WIMLIB_ERR_LINK (> 0) if an error occurred, other than hard links possibly
2376  * being unsupported by the volume.  Returns a negative value if creating the
2377  * hard link failed due to ERROR_INVALID_FUNCTION.
2378  */
2379 static int
2380 win32_try_hard_link(const wchar_t *output_path, const struct wim_inode *inode,
2381                     struct apply_args *args)
2382 {
2383         DWORD err;
2384
2385         /* There is a volume flag for this (FILE_SUPPORTS_HARD_LINKS),
2386          * but it's only available on Windows 7 and later.  So no use
2387          * even checking it, really.  Instead, CreateHardLinkW() will
2388          * apparently return ERROR_INVALID_FUNCTION if the volume does
2389          * not support hard links. */
2390         DEBUG("Creating hard link \"%ls => %ls\"",
2391               output_path, inode->i_extracted_file);
2392         if (CreateHardLinkW(output_path, inode->i_extracted_file, NULL))
2393                 return 0;
2394
2395         err = GetLastError();
2396         if (err != ERROR_INVALID_FUNCTION) {
2397                 ERROR("Can't create hard link \"%ls => %ls\"",
2398                       output_path, inode->i_extracted_file);
2399                 win32_error(err);
2400                 return WIMLIB_ERR_LINK;
2401         } else {
2402                 args->num_hard_links_failed++;
2403                 if (args->num_hard_links_failed < MAX_CREATE_HARD_LINK_WARNINGS) {
2404                         WARNING("Can't create hard link \"%ls => %ls\":\n"
2405                                 "          Volume does not support hard links!\n"
2406                                 "          Falling back to extracting a copy of the file.",
2407                                 output_path, inode->i_extracted_file);
2408                 } else if (args->num_hard_links_failed == MAX_CREATE_HARD_LINK_WARNINGS) {
2409                         WARNING("Suppressing further hard linking warnings...");
2410                 }
2411                 return -1;
2412         }
2413 }
2414
2415 /* Extract a file, directory, reparse point, or hard link to an
2416  * already-extracted file using the Win32 API */
2417 int
2418 win32_do_apply_dentry(const wchar_t *output_path,
2419                       size_t output_path_num_chars,
2420                       struct wim_dentry *dentry,
2421                       struct apply_args *args)
2422 {
2423         int ret;
2424         struct wim_inode *inode = dentry->d_inode;
2425
2426         ret = win32_check_vol_flags(output_path, args);
2427         if (ret)
2428                 return ret;
2429         if (inode->i_nlink > 1 && inode->i_extracted_file != NULL) {
2430                 /* Linked file, with another name already extracted.  Create a
2431                  * hard link. */
2432                 ret = win32_try_hard_link(output_path, inode, args);
2433                 if (ret >= 0)
2434                         return ret;
2435                 /* Negative return value from win32_try_hard_link() indicates
2436                  * that hard links are probably not supported by the volume.
2437                  * Fall back to extracting a copy of the file. */
2438         }
2439
2440         /* If this is a reparse point and the volume does not support reparse
2441          * points, just skip it completely. */
2442         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT &&
2443             !(args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS))
2444         {
2445                 WARNING("Skipping extraction of reparse point \"%ls\":\n"
2446                         "          Not supported by destination filesystem",
2447                         output_path);
2448         } else {
2449                 /* Create the file, directory, or reparse point, and extract the
2450                  * data streams. */
2451                 ret = win32_extract_streams(inode, output_path, args);
2452                 if (ret)
2453                         return ret;
2454         }
2455         if (inode->i_extracted_file == NULL) {
2456                 const struct wim_lookup_table_entry *lte;
2457
2458                 /* Tally bytes extracted, including all alternate data streams,
2459                  * unless we extracted a hard link (or, at least extracted a
2460                  * name that was supposed to be a hard link) */
2461                 for (unsigned i = 0; i <= inode->i_num_ads; i++) {
2462                         lte = inode_stream_lte_resolved(inode, i);
2463                         if (lte)
2464                                 args->progress.extract.completed_bytes +=
2465                                                         wim_resource_size(lte);
2466                 }
2467                 if (inode->i_nlink > 1) {
2468                         /* Save extracted path for a later call to
2469                          * CreateHardLinkW() if this inode has multiple links.
2470                          * */
2471                         inode->i_extracted_file = WSTRDUP(output_path);
2472                         if (!inode->i_extracted_file)
2473                                 return WIMLIB_ERR_NOMEM;
2474                 }
2475         }
2476         return 0;
2477 }
2478
2479 /* Set timestamps on an extracted file using the Win32 API */
2480 int
2481 win32_do_apply_dentry_timestamps(const wchar_t *path,
2482                                  size_t path_num_chars,
2483                                  const struct wim_dentry *dentry,
2484                                  const struct apply_args *args)
2485 {
2486         DWORD err;
2487         HANDLE h;
2488         const struct wim_inode *inode = dentry->d_inode;
2489
2490         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT &&
2491             !(args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS))
2492         {
2493                 /* Skip reparse points not extracted */
2494                 return 0;
2495         }
2496
2497         /* Windows doesn't let you change the timestamps of the root directory
2498          * (at least on FAT, which is dumb but expected since FAT doesn't store
2499          * any metadata about the root directory...) */
2500         if (path_is_root_of_drive(path))
2501                 return 0;
2502
2503         DEBUG("Opening \"%ls\" to set timestamps", path);
2504         h = win32_open_existing_file(path, FILE_WRITE_ATTRIBUTES);
2505         if (h == INVALID_HANDLE_VALUE) {
2506                 err = GetLastError();
2507                 goto fail;
2508         }
2509
2510         FILETIME creationTime = {.dwLowDateTime = inode->i_creation_time & 0xffffffff,
2511                                  .dwHighDateTime = inode->i_creation_time >> 32};
2512         FILETIME lastAccessTime = {.dwLowDateTime = inode->i_last_access_time & 0xffffffff,
2513                                   .dwHighDateTime = inode->i_last_access_time >> 32};
2514         FILETIME lastWriteTime = {.dwLowDateTime = inode->i_last_write_time & 0xffffffff,
2515                                   .dwHighDateTime = inode->i_last_write_time >> 32};
2516
2517         DEBUG("Calling SetFileTime() on \"%ls\"", path);
2518         if (!SetFileTime(h, &creationTime, &lastAccessTime, &lastWriteTime)) {
2519                 err = GetLastError();
2520                 CloseHandle(h);
2521                 goto fail;
2522         }
2523         DEBUG("Closing \"%ls\"", path);
2524         if (!CloseHandle(h)) {
2525                 err = GetLastError();
2526                 goto fail;
2527         }
2528         goto out;
2529 fail:
2530         /* Only warn if setting timestamps failed; still return 0. */
2531         WARNING("Can't set timestamps on \"%ls\"", path);
2532         win32_error(err);
2533 out:
2534         return 0;
2535 }
2536
2537 /* Replacement for POSIX fsync() */
2538 int
2539 fsync(int fd)
2540 {
2541         DWORD err;
2542         HANDLE h;
2543
2544         h = (HANDLE)_get_osfhandle(fd);
2545         if (h == INVALID_HANDLE_VALUE) {
2546                 err = GetLastError();
2547                 ERROR("Could not get Windows handle for file descriptor");
2548                 win32_error(err);
2549                 errno = EBADF;
2550                 return -1;
2551         }
2552         if (!FlushFileBuffers(h)) {
2553                 err = GetLastError();
2554                 ERROR("Could not flush file buffers to disk");
2555                 win32_error(err);
2556                 errno = EIO;
2557                 return -1;
2558         }
2559         return 0;
2560 }
2561
2562 /* Use the Win32 API to get the number of processors */
2563 unsigned
2564 win32_get_number_of_processors()
2565 {
2566         SYSTEM_INFO sysinfo;
2567         GetSystemInfo(&sysinfo);
2568         return sysinfo.dwNumberOfProcessors;
2569 }
2570
2571 /* Replacement for POSIX-2008 realpath().  Warning: partial functionality only
2572  * (resolved_path must be NULL).   Also I highly doubt that GetFullPathName
2573  * really does the right thing under all circumstances. */
2574 wchar_t *
2575 realpath(const wchar_t *path, wchar_t *resolved_path)
2576 {
2577         DWORD ret;
2578         wimlib_assert(resolved_path == NULL);
2579         DWORD err;
2580
2581         ret = GetFullPathNameW(path, 0, NULL, NULL);
2582         if (!ret) {
2583                 err = GetLastError();
2584                 goto fail_win32;
2585         }
2586
2587         resolved_path = TMALLOC(ret);
2588         if (!resolved_path)
2589                 goto out;
2590         ret = GetFullPathNameW(path, ret, resolved_path, NULL);
2591         if (!ret) {
2592                 err = GetLastError();
2593                 free(resolved_path);
2594                 resolved_path = NULL;
2595                 goto fail_win32;
2596         }
2597         goto out;
2598 fail_win32:
2599         win32_error(err);
2600         errno = -1;
2601 out:
2602         return resolved_path;
2603 }
2604
2605 /* rename() on Windows fails if the destination file exists.  And we need to
2606  * make it work on wide characters.  Fix it. */
2607 int
2608 win32_rename_replacement(const wchar_t *oldpath, const wchar_t *newpath)
2609 {
2610         if (MoveFileExW(oldpath, newpath, MOVEFILE_REPLACE_EXISTING)) {
2611                 return 0;
2612         } else {
2613                 /* As usual, the possible error values are not documented */
2614                 DWORD err = GetLastError();
2615                 ERROR("MoveFileEx(): Can't rename \"%ls\" to \"%ls\"",
2616                       oldpath, newpath);
2617                 win32_error(err);
2618                 errno = -1;
2619                 return -1;
2620         }
2621 }
2622
2623 /* Replacement for POSIX fnmatch() (partial functionality only) */
2624 int
2625 fnmatch(const wchar_t *pattern, const wchar_t *string, int flags)
2626 {
2627         if (PathMatchSpecW(string, pattern))
2628                 return 0;
2629         else
2630                 return FNM_NOMATCH;
2631 }
2632
2633 /* truncate() replacement */
2634 int
2635 win32_truncate_replacement(const wchar_t *path, off_t size)
2636 {
2637         DWORD err = NO_ERROR;
2638         LARGE_INTEGER liOffset;
2639
2640         HANDLE h = win32_open_existing_file(path, GENERIC_WRITE);
2641         if (h == INVALID_HANDLE_VALUE)
2642                 goto fail;
2643
2644         liOffset.QuadPart = size;
2645         if (!SetFilePointerEx(h, liOffset, NULL, FILE_BEGIN))
2646                 goto fail_close_handle;
2647
2648         if (!SetEndOfFile(h))
2649                 goto fail_close_handle;
2650         CloseHandle(h);
2651         return 0;
2652
2653 fail_close_handle:
2654         err = GetLastError();
2655         CloseHandle(h);
2656 fail:
2657         if (err == NO_ERROR)
2658                 err = GetLastError();
2659         ERROR("Can't truncate \"%ls\" to %"PRIu64" bytes", path, size);
2660         win32_error(err);
2661         errno = -1;
2662         return -1;
2663 }
2664
2665
2666 /* This really could be replaced with _wcserror_s, but this doesn't seem to
2667  * actually be available in MSVCRT.DLL on Windows XP (perhaps it's statically
2668  * linked in by Visual Studio...?). */
2669 extern int
2670 win32_strerror_r_replacement(int errnum, wchar_t *buf, size_t buflen)
2671 {
2672         static pthread_mutex_t strerror_lock = PTHREAD_MUTEX_INITIALIZER;
2673
2674         pthread_mutex_lock(&strerror_lock);
2675         mbstowcs(buf, strerror(errnum), buflen);
2676         buf[buflen - 1] = '\0';
2677         pthread_mutex_unlock(&strerror_lock);
2678         return 0;
2679 }
2680
2681 #endif /* __WIN32__ */