b6e28e75ad4211d1a7030ef6060aa46b479a8035
[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_dentry *dentry,
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         const struct wim_inode *inode = dentry->d_inode;
1962         const wchar_t *short_name;
1963         if (stream_name_utf16 == NULL) {
1964                 /* Unnamed stream. */
1965
1966                 /* Set security descriptor, unless the extract_flags indicate
1967                  * not to or the volume does not supported it.  Note that this
1968                  * is only done when the unnamed stream is being extracted, as
1969                  * security descriptors are per-file and not per-stream. */
1970                 if (inode->i_security_id >= 0 &&
1971                     !(args->extract_flags & WIMLIB_EXTRACT_FLAG_NO_ACLS)
1972                     && (args->vol_flags & FILE_PERSISTENT_ACLS))
1973                 {
1974                         ret = win32_set_security_data(inode, h, stream_path, args);
1975                         if (ret)
1976                                 return ret;
1977                 }
1978
1979                 /* Handle reparse points.  The data for them needs to be set
1980                  * using a special ioctl.  Note that the reparse point may have
1981                  * been created using CreateFileW() in the case of
1982                  * non-directories or CreateDirectoryW() in the case of
1983                  * directories; but the ioctl works either way.  Also, it is
1984                  * only this step that actually sets the
1985                  * FILE_ATTRIBUTE_REPARSE_POINT, as it is not valid to set it
1986                  * using SetFileAttributesW() or CreateFileW().
1987                  *
1988                  * If the volume does not support reparse points we simply
1989                  * ignore the reparse data.  (N.B. the code currently doesn't
1990                  * actually reach this case because reparse points are skipped
1991                  * entirely on such volumes.) */
1992                 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1993                         if (args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS) {
1994                                 ret = win32_set_reparse_data(h, inode,
1995                                                              lte, stream_path,
1996                                                              args);
1997                                 if (ret)
1998                                         return ret;
1999                         } else {
2000                                 DEBUG("Cannot set reparse data on \"%ls\": volume "
2001                                       "does not support reparse points", stream_path);
2002                         }
2003                 } else if (lte != NULL &&
2004                            !(args->vol_flags & FILE_SUPPORTS_ENCRYPTION &&
2005                              inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED))
2006                 {
2007                         /* Extract the data of the unnamed stream, unless the
2008                          * lookup table entry is NULL (indicating an empty
2009                          * stream for which no data needs to be extracted), or
2010                          * the stream is encrypted and therefore was already
2011                          * extracted as a special case. */
2012                         ret = do_win32_extract_stream(h, lte);
2013                         if (ret)
2014                                 return ret;
2015                 }
2016
2017                 if (dentry_has_short_name(dentry))
2018                         short_name = dentry->short_name;
2019                 else
2020                         short_name = L"";
2021                 /* Set short name */
2022                 if (!SetFileShortNameW(h, short_name)) {
2023                 #if 0
2024                         DWORD err = GetLastError();
2025                         ERROR("Could not set short name on \"%ls\"", stream_path);
2026                         win32_error(err);
2027                 #endif
2028                 }
2029         } else {
2030                 /* Extract the data for a named data stream. */
2031                 if (lte != NULL) {
2032                         DEBUG("Extracting named data stream \"%ls\" (len = %"PRIu64")",
2033                               stream_path, wim_resource_size(lte));
2034                         ret = do_win32_extract_stream(h, lte);
2035                 }
2036         }
2037         return ret;
2038 }
2039
2040 static int
2041 win32_decrypt_file(HANDLE open_handle, const wchar_t *path)
2042 {
2043         DWORD err;
2044         /* We cannot call DecryptFileW() while there is an open handle to the
2045          * file.  So close it first. */
2046         if (!CloseHandle(open_handle)) {
2047                 err = GetLastError();
2048                 ERROR("Failed to close handle for \"%ls\"", path);
2049                 win32_error(err);
2050                 return WIMLIB_ERR_WRITE;
2051         }
2052         if (!DecryptFileW(path, 0 /* reserved parameter; set to 0 */)) {
2053                 err = GetLastError();
2054                 ERROR("Failed to decrypt file \"%ls\"", path);
2055                 win32_error(err);
2056                 return WIMLIB_ERR_WRITE;
2057         }
2058         return 0;
2059 }
2060
2061 /*
2062  * Create and extract a stream to a file, or create a directory, using the
2063  * Windows API.
2064  *
2065  * This handles reparse points, directories, alternate data streams, encrypted
2066  * files, compressed files, etc.
2067  *
2068  * @dentry: WIM dentry for the file or directory being extracted.
2069  *
2070  * @path:  Path to extract the file to.
2071  *
2072  * @stream_name_utf16:
2073  *         Name of the stream, or NULL if the stream is unnamed.  This will
2074  *         be called with a NULL stream_name_utf16 before any non-NULL
2075  *         stream_name_utf16's.
2076  *
2077  * @lte:   WIM lookup table entry for the stream.  May be NULL to indicate
2078  *         a stream of length 0.
2079  *
2080  * @args:  Additional apply context, including flags indicating supported
2081  *         volume features.
2082  *
2083  * Returns 0 on success; nonzero on failure.
2084  */
2085 static int
2086 win32_extract_stream(const struct wim_dentry *dentry,
2087                      const wchar_t *path,
2088                      const wchar_t *stream_name_utf16,
2089                      struct wim_lookup_table_entry *lte,
2090                      struct apply_args *args)
2091 {
2092         wchar_t *stream_path;
2093         HANDLE h;
2094         int ret;
2095         DWORD err;
2096         DWORD creationDisposition = CREATE_ALWAYS;
2097         DWORD requestedAccess;
2098         BY_HANDLE_FILE_INFORMATION file_info;
2099         unsigned remaining_sharing_violations = 1000;
2100         const struct wim_inode *inode = dentry->d_inode;
2101
2102         if (stream_name_utf16) {
2103                 /* Named stream.  Create a buffer that contains the UTF-16LE
2104                  * string [./]path:stream_name_utf16.  This is needed to
2105                  * create and open the stream using CreateFileW().  I'm not
2106                  * aware of any other APIs to do this.  Note: the '$DATA' suffix
2107                  * seems to be unneeded.  Additional note: a "./" prefix needs
2108                  * to be added when the path is not absolute to avoid ambiguity
2109                  * with drive letters. */
2110                 size_t stream_path_nchars;
2111                 size_t path_nchars;
2112                 size_t stream_name_nchars;
2113                 const wchar_t *prefix;
2114
2115                 path_nchars = wcslen(path);
2116                 stream_name_nchars = wcslen(stream_name_utf16);
2117                 stream_path_nchars = path_nchars + 1 + stream_name_nchars;
2118                 if (path[0] != cpu_to_le16(L'\0') &&
2119                     path[0] != cpu_to_le16(L'/') &&
2120                     path[0] != cpu_to_le16(L'\\') &&
2121                     path[1] != cpu_to_le16(L':'))
2122                 {
2123                         prefix = L"./";
2124                         stream_path_nchars += 2;
2125                 } else {
2126                         prefix = L"";
2127                 }
2128                 stream_path = alloca((stream_path_nchars + 1) * sizeof(wchar_t));
2129                 swprintf(stream_path, L"%ls%ls:%ls",
2130                          prefix, path, stream_name_utf16);
2131         } else {
2132                 /* Unnamed stream; its path is just the path to the file itself.
2133                  * */
2134                 stream_path = (wchar_t*)path;
2135
2136                 ret = win32_begin_extract_unnamed_stream(inode, lte, path,
2137                                                          &creationDisposition,
2138                                                          args->vol_flags);
2139                 if (ret)
2140                         goto fail;
2141         }
2142
2143         DEBUG("Opening \"%ls\"", stream_path);
2144         /* DELETE access is needed for SetFileShortNameW(), for some reason. */
2145         requestedAccess = GENERIC_READ | GENERIC_WRITE | DELETE |
2146                           ACCESS_SYSTEM_SECURITY;
2147 try_open_again:
2148         /* Open the stream to be extracted.  Depending on what we have set
2149          * creationDisposition to, we may be creating this for the first time,
2150          * or we may be opening on existing stream we already created using
2151          * CreateDirectoryW() or OpenEncryptedFileRawW(). */
2152         h = CreateFileW(stream_path,
2153                         requestedAccess,
2154                         FILE_SHARE_READ,
2155                         NULL,
2156                         creationDisposition,
2157                         win32_get_create_flags_and_attributes(inode->i_attributes),
2158                         NULL);
2159         if (h == INVALID_HANDLE_VALUE) {
2160                 err = GetLastError();
2161                 if (err == ERROR_ACCESS_DENIED &&
2162                     path_is_root_of_drive(stream_path))
2163                 {
2164                         ret = 0;
2165                         goto out;
2166                 }
2167                 if ((err == ERROR_PRIVILEGE_NOT_HELD ||
2168                      err == ERROR_ACCESS_DENIED) &&
2169                     (requestedAccess & ACCESS_SYSTEM_SECURITY))
2170                 {
2171                         /* Try opening the file again without privilege to
2172                          * modify SACL. */
2173                         requestedAccess &= ~ACCESS_SYSTEM_SECURITY;
2174                         goto try_open_again;
2175                 }
2176                 if (err == ERROR_SHARING_VIOLATION) {
2177                         if (remaining_sharing_violations) {
2178                                 --remaining_sharing_violations;
2179                                 /* This can happen when restoring encrypted directories
2180                                  * for some reason.  Probably a bug in EncryptFile(). */
2181                                 WARNING("Couldn't open \"%ls\" due to sharing violation; "
2182                                         "re-trying after 100ms", stream_path);
2183                                 Sleep(100);
2184                                 goto try_open_again;
2185                         } else {
2186                                 ERROR("Too many sharing violations; giving up...");
2187                         }
2188                 } else {
2189                         if (creationDisposition == OPEN_EXISTING)
2190                                 ERROR("Failed to open \"%ls\"", stream_path);
2191                         else
2192                                 ERROR("Failed to create \"%ls\"", stream_path);
2193                         win32_error(err);
2194                 }
2195                 ret = WIMLIB_ERR_OPEN;
2196                 goto fail;
2197         }
2198
2199         /* Check the attributes of the file we just opened, and remove
2200          * encryption or compression if either was set by default but is not
2201          * supposed to be set based on the WIM inode attributes. */
2202         if (!GetFileInformationByHandle(h, &file_info)) {
2203                 err = GetLastError();
2204                 ERROR("Failed to get attributes of \"%ls\"", stream_path);
2205                 win32_error(err);
2206                 ret = WIMLIB_ERR_STAT;
2207                 goto fail_close_handle;
2208         }
2209
2210         /* Remove encryption? */
2211         if (file_info.dwFileAttributes & FILE_ATTRIBUTE_ENCRYPTED &&
2212             !(inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED))
2213         {
2214                 /* File defaulted to encrypted due to being in an encrypted
2215                  * directory, but is not actually supposed to be encrypted.
2216                  *
2217                  * This is a workaround, because I'm not aware of any way to
2218                  * directly (e.g. with CreateFileW()) create an unencrypted file
2219                  * in a directory with FILE_ATTRIBUTE_ENCRYPTED set. */
2220                 ret = win32_decrypt_file(h, stream_path);
2221                 if (ret)
2222                         goto fail; /* win32_decrypt_file() closed the handle. */
2223                 creationDisposition = OPEN_EXISTING;
2224                 goto try_open_again;
2225         }
2226
2227         /* Remove compression? */
2228         if (file_info.dwFileAttributes & FILE_ATTRIBUTE_COMPRESSED &&
2229             !(inode->i_attributes & FILE_ATTRIBUTE_COMPRESSED))
2230         {
2231                 /* Similar to the encrypted case, above, if the file defaulted
2232                  * to compressed due to being in an compressed directory, but is
2233                  * not actually supposed to be compressed, explicitly set the
2234                  * compression format to COMPRESSION_FORMAT_NONE. */
2235                 ret = win32_set_compression_state(h, COMPRESSION_FORMAT_NONE,
2236                                                   stream_path);
2237                 if (ret)
2238                         goto fail_close_handle;
2239         }
2240
2241         /* Set compression and/or sparse attributes if needed */
2242         ret = win32_set_special_stream_attributes(h, inode, lte, path,
2243                                                   args->vol_flags);
2244
2245         if (ret)
2246                 goto fail_close_handle;
2247
2248         /* At this point we have at least created the needed stream with the
2249          * appropriate attributes.  We have yet to set the appropriate security
2250          * descriptor and actually extract the stream data (other than for
2251          * extracted files, which were already extracted).
2252          * win32_finish_extract_stream() handles these additional steps. */
2253         ret = win32_finish_extract_stream(h, dentry, lte, stream_path,
2254                                           stream_name_utf16, args);
2255         if (ret)
2256                 goto fail_close_handle;
2257
2258         /* Done extracting the stream.  Close the handle and return. */
2259         DEBUG("Closing \"%ls\"", stream_path);
2260         if (!CloseHandle(h)) {
2261                 err = GetLastError();
2262                 ERROR("Failed to close \"%ls\"", stream_path);
2263                 win32_error(err);
2264                 ret = WIMLIB_ERR_WRITE;
2265                 goto fail;
2266         }
2267         ret = 0;
2268         goto out;
2269 fail_close_handle:
2270         CloseHandle(h);
2271 fail:
2272         ERROR("Error extracting \"%ls\"", stream_path);
2273 out:
2274         return ret;
2275 }
2276
2277 /*
2278  * Creates a file, directory, or reparse point and extracts all streams to it
2279  * (unnamed data stream and/or reparse point stream, plus any alternate data
2280  * streams).  Handles sparse, compressed, and/or encrypted files.
2281  *
2282  * @dentry:     WIM dentry for this file or directory.
2283  * @path:       UTF-16LE external path to extract the inode to.
2284  * @args:       Additional extraction context.
2285  *
2286  * Returns 0 on success; nonzero on failure.
2287  */
2288 static int
2289 win32_extract_streams(const struct wim_dentry *dentry,
2290                       const wchar_t *path, struct apply_args *args)
2291 {
2292         struct wim_lookup_table_entry *unnamed_lte;
2293         int ret;
2294         const struct wim_inode *inode = dentry->d_inode;
2295
2296         /* First extract the unnamed stream. */
2297
2298         unnamed_lte = inode_unnamed_lte_resolved(inode);
2299         ret = win32_extract_stream(dentry, path, NULL, unnamed_lte, args);
2300         if (ret)
2301                 goto out;
2302
2303         /* Extract any named streams, if supported by the volume. */
2304
2305         if (!(args->vol_flags & FILE_NAMED_STREAMS))
2306                 goto out;
2307         for (u16 i = 0; i < inode->i_num_ads; i++) {
2308                 const struct wim_ads_entry *ads_entry = &inode->i_ads_entries[i];
2309
2310                 /* Skip the unnamed stream if it's in the ADS entries (we
2311                  * already extracted it...) */
2312                 if (ads_entry->stream_name_nbytes == 0)
2313                         continue;
2314
2315                 /* Skip special UNIX data entries (see documentation for
2316                  * WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA) */
2317                 if (ads_entry->stream_name_nbytes == WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES
2318                     && !memcmp(ads_entry->stream_name,
2319                                WIMLIB_UNIX_DATA_TAG_UTF16LE,
2320                                WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES))
2321                         continue;
2322
2323                 /* Extract the named stream */
2324                 ret = win32_extract_stream(dentry,
2325                                            path,
2326                                            ads_entry->stream_name,
2327                                            ads_entry->lte,
2328                                            args);
2329                 if (ret)
2330                         break;
2331         }
2332 out:
2333         return ret;
2334 }
2335
2336 /* If not done already, load the supported feature flags for the volume onto
2337  * which the image is being extracted, and warn the user about any missing
2338  * features that could be important. */
2339 static int
2340 win32_check_vol_flags(const wchar_t *output_path, struct apply_args *args)
2341 {
2342         if (args->have_vol_flags)
2343                 return 0;
2344
2345         win32_get_vol_flags(output_path, &args->vol_flags);
2346         args->have_vol_flags = true;
2347         /* Warn the user about data that may not be extracted. */
2348         if (!(args->vol_flags & FILE_SUPPORTS_SPARSE_FILES))
2349                 WARNING("Volume does not support sparse files!\n"
2350                         "          Sparse files will be extracted as non-sparse.");
2351         if (!(args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS))
2352                 WARNING("Volume does not support reparse points!\n"
2353                         "          Reparse point data will not be extracted.");
2354         if (!(args->vol_flags & FILE_NAMED_STREAMS)) {
2355                 WARNING("Volume does not support named data streams!\n"
2356                         "          Named data streams will not be extracted.");
2357         }
2358         if (!(args->vol_flags & FILE_SUPPORTS_ENCRYPTION)) {
2359                 WARNING("Volume does not support encryption!\n"
2360                         "          Encrypted files will be extracted as raw data.");
2361         }
2362         if (!(args->vol_flags & FILE_FILE_COMPRESSION)) {
2363                 WARNING("Volume does not support transparent compression!\n"
2364                         "          Compressed files will be extracted as non-compressed.");
2365         }
2366         if (!(args->vol_flags & FILE_PERSISTENT_ACLS)) {
2367                 if (args->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS) {
2368                         ERROR("Strict ACLs requested, but the volume does not "
2369                               "support ACLs!");
2370                         return WIMLIB_ERR_VOLUME_LACKS_FEATURES;
2371                 } else {
2372                         WARNING("Volume does not support persistent ACLS!\n"
2373                                 "          File permissions will not be extracted.");
2374                 }
2375         }
2376         return 0;
2377 }
2378
2379 /*
2380  * Try extracting a hard link.
2381  *
2382  * @output_path:  Path to link to be extracted.
2383  *
2384  * @inode:        WIM inode that the link is to; inode->i_extracted_file
2385  *                the path to a name of the file that has already been
2386  *                extracted (we use this to create the hard link).
2387  *
2388  * @args:         Additional apply context, used here to keep track of
2389  *                the number of times creating a hard link failed due to
2390  *                ERROR_INVALID_FUNCTION.  This error should indicate that hard
2391  *                links are not supported by the volume, and we would like to
2392  *                warn the user a few times, but not too many times.
2393  *
2394  * Returns 0 if the hard link was successfully extracted.  Returns
2395  * WIMLIB_ERR_LINK (> 0) if an error occurred, other than hard links possibly
2396  * being unsupported by the volume.  Returns a negative value if creating the
2397  * hard link failed due to ERROR_INVALID_FUNCTION.
2398  */
2399 static int
2400 win32_try_hard_link(const wchar_t *output_path, const struct wim_inode *inode,
2401                     struct apply_args *args)
2402 {
2403         DWORD err;
2404
2405         /* There is a volume flag for this (FILE_SUPPORTS_HARD_LINKS),
2406          * but it's only available on Windows 7 and later.  So no use
2407          * even checking it, really.  Instead, CreateHardLinkW() will
2408          * apparently return ERROR_INVALID_FUNCTION if the volume does
2409          * not support hard links. */
2410         DEBUG("Creating hard link \"%ls => %ls\"",
2411               output_path, inode->i_extracted_file);
2412         if (CreateHardLinkW(output_path, inode->i_extracted_file, NULL))
2413                 return 0;
2414
2415         err = GetLastError();
2416         if (err != ERROR_INVALID_FUNCTION) {
2417                 ERROR("Can't create hard link \"%ls => %ls\"",
2418                       output_path, inode->i_extracted_file);
2419                 win32_error(err);
2420                 return WIMLIB_ERR_LINK;
2421         } else {
2422                 args->num_hard_links_failed++;
2423                 if (args->num_hard_links_failed < MAX_CREATE_HARD_LINK_WARNINGS) {
2424                         WARNING("Can't create hard link \"%ls => %ls\":\n"
2425                                 "          Volume does not support hard links!\n"
2426                                 "          Falling back to extracting a copy of the file.",
2427                                 output_path, inode->i_extracted_file);
2428                 } else if (args->num_hard_links_failed == MAX_CREATE_HARD_LINK_WARNINGS) {
2429                         WARNING("Suppressing further hard linking warnings...");
2430                 }
2431                 return -1;
2432         }
2433 }
2434
2435 /* Extract a file, directory, reparse point, or hard link to an
2436  * already-extracted file using the Win32 API */
2437 int
2438 win32_do_apply_dentry(const wchar_t *output_path,
2439                       size_t output_path_num_chars,
2440                       struct wim_dentry *dentry,
2441                       struct apply_args *args)
2442 {
2443         int ret;
2444         struct wim_inode *inode = dentry->d_inode;
2445
2446         ret = win32_check_vol_flags(output_path, args);
2447         if (ret)
2448                 return ret;
2449         if (inode->i_nlink > 1 && inode->i_extracted_file != NULL) {
2450                 /* Linked file, with another name already extracted.  Create a
2451                  * hard link. */
2452                 ret = win32_try_hard_link(output_path, inode, args);
2453                 if (ret >= 0)
2454                         return ret;
2455                 /* Negative return value from win32_try_hard_link() indicates
2456                  * that hard links are probably not supported by the volume.
2457                  * Fall back to extracting a copy of the file. */
2458         }
2459
2460         /* If this is a reparse point and the volume does not support reparse
2461          * points, just skip it completely. */
2462         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT &&
2463             !(args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS))
2464         {
2465                 WARNING("Skipping extraction of reparse point \"%ls\":\n"
2466                         "          Not supported by destination filesystem",
2467                         output_path);
2468         } else {
2469                 /* Create the file, directory, or reparse point, and extract the
2470                  * data streams. */
2471                 ret = win32_extract_streams(dentry, output_path, args);
2472                 if (ret)
2473                         return ret;
2474         }
2475         if (inode->i_extracted_file == NULL) {
2476                 const struct wim_lookup_table_entry *lte;
2477
2478                 /* Tally bytes extracted, including all alternate data streams,
2479                  * unless we extracted a hard link (or, at least extracted a
2480                  * name that was supposed to be a hard link) */
2481                 for (unsigned i = 0; i <= inode->i_num_ads; i++) {
2482                         lte = inode_stream_lte_resolved(inode, i);
2483                         if (lte)
2484                                 args->progress.extract.completed_bytes +=
2485                                                         wim_resource_size(lte);
2486                 }
2487                 if (inode->i_nlink > 1) {
2488                         /* Save extracted path for a later call to
2489                          * CreateHardLinkW() if this inode has multiple links.
2490                          * */
2491                         inode->i_extracted_file = WSTRDUP(output_path);
2492                         if (!inode->i_extracted_file)
2493                                 return WIMLIB_ERR_NOMEM;
2494                 }
2495         }
2496         return 0;
2497 }
2498
2499 /* Set timestamps on an extracted file using the Win32 API */
2500 int
2501 win32_do_apply_dentry_timestamps(const wchar_t *path,
2502                                  size_t path_num_chars,
2503                                  const struct wim_dentry *dentry,
2504                                  const struct apply_args *args)
2505 {
2506         DWORD err;
2507         HANDLE h;
2508         const struct wim_inode *inode = dentry->d_inode;
2509
2510         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT &&
2511             !(args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS))
2512         {
2513                 /* Skip reparse points not extracted */
2514                 return 0;
2515         }
2516
2517         /* Windows doesn't let you change the timestamps of the root directory
2518          * (at least on FAT, which is dumb but expected since FAT doesn't store
2519          * any metadata about the root directory...) */
2520         if (path_is_root_of_drive(path))
2521                 return 0;
2522
2523         DEBUG("Opening \"%ls\" to set timestamps", path);
2524         h = win32_open_existing_file(path, FILE_WRITE_ATTRIBUTES);
2525         if (h == INVALID_HANDLE_VALUE) {
2526                 err = GetLastError();
2527                 goto fail;
2528         }
2529
2530         FILETIME creationTime = {.dwLowDateTime = inode->i_creation_time & 0xffffffff,
2531                                  .dwHighDateTime = inode->i_creation_time >> 32};
2532         FILETIME lastAccessTime = {.dwLowDateTime = inode->i_last_access_time & 0xffffffff,
2533                                   .dwHighDateTime = inode->i_last_access_time >> 32};
2534         FILETIME lastWriteTime = {.dwLowDateTime = inode->i_last_write_time & 0xffffffff,
2535                                   .dwHighDateTime = inode->i_last_write_time >> 32};
2536
2537         DEBUG("Calling SetFileTime() on \"%ls\"", path);
2538         if (!SetFileTime(h, &creationTime, &lastAccessTime, &lastWriteTime)) {
2539                 err = GetLastError();
2540                 CloseHandle(h);
2541                 goto fail;
2542         }
2543         DEBUG("Closing \"%ls\"", path);
2544         if (!CloseHandle(h)) {
2545                 err = GetLastError();
2546                 goto fail;
2547         }
2548         goto out;
2549 fail:
2550         /* Only warn if setting timestamps failed; still return 0. */
2551         WARNING("Can't set timestamps on \"%ls\"", path);
2552         win32_error(err);
2553 out:
2554         return 0;
2555 }
2556
2557 /* Replacement for POSIX fsync() */
2558 int
2559 fsync(int fd)
2560 {
2561         DWORD err;
2562         HANDLE h;
2563
2564         h = (HANDLE)_get_osfhandle(fd);
2565         if (h == INVALID_HANDLE_VALUE) {
2566                 err = GetLastError();
2567                 ERROR("Could not get Windows handle for file descriptor");
2568                 win32_error(err);
2569                 errno = EBADF;
2570                 return -1;
2571         }
2572         if (!FlushFileBuffers(h)) {
2573                 err = GetLastError();
2574                 ERROR("Could not flush file buffers to disk");
2575                 win32_error(err);
2576                 errno = EIO;
2577                 return -1;
2578         }
2579         return 0;
2580 }
2581
2582 /* Use the Win32 API to get the number of processors */
2583 unsigned
2584 win32_get_number_of_processors()
2585 {
2586         SYSTEM_INFO sysinfo;
2587         GetSystemInfo(&sysinfo);
2588         return sysinfo.dwNumberOfProcessors;
2589 }
2590
2591 /* Replacement for POSIX-2008 realpath().  Warning: partial functionality only
2592  * (resolved_path must be NULL).   Also I highly doubt that GetFullPathName
2593  * really does the right thing under all circumstances. */
2594 wchar_t *
2595 realpath(const wchar_t *path, wchar_t *resolved_path)
2596 {
2597         DWORD ret;
2598         wimlib_assert(resolved_path == NULL);
2599         DWORD err;
2600
2601         ret = GetFullPathNameW(path, 0, NULL, NULL);
2602         if (!ret) {
2603                 err = GetLastError();
2604                 goto fail_win32;
2605         }
2606
2607         resolved_path = TMALLOC(ret);
2608         if (!resolved_path)
2609                 goto out;
2610         ret = GetFullPathNameW(path, ret, resolved_path, NULL);
2611         if (!ret) {
2612                 err = GetLastError();
2613                 free(resolved_path);
2614                 resolved_path = NULL;
2615                 goto fail_win32;
2616         }
2617         goto out;
2618 fail_win32:
2619         win32_error(err);
2620         errno = -1;
2621 out:
2622         return resolved_path;
2623 }
2624
2625 /* rename() on Windows fails if the destination file exists.  And we need to
2626  * make it work on wide characters.  Fix it. */
2627 int
2628 win32_rename_replacement(const wchar_t *oldpath, const wchar_t *newpath)
2629 {
2630         if (MoveFileExW(oldpath, newpath, MOVEFILE_REPLACE_EXISTING)) {
2631                 return 0;
2632         } else {
2633                 /* As usual, the possible error values are not documented */
2634                 DWORD err = GetLastError();
2635                 ERROR("MoveFileEx(): Can't rename \"%ls\" to \"%ls\"",
2636                       oldpath, newpath);
2637                 win32_error(err);
2638                 errno = -1;
2639                 return -1;
2640         }
2641 }
2642
2643 /* Replacement for POSIX fnmatch() (partial functionality only) */
2644 int
2645 fnmatch(const wchar_t *pattern, const wchar_t *string, int flags)
2646 {
2647         if (PathMatchSpecW(string, pattern))
2648                 return 0;
2649         else
2650                 return FNM_NOMATCH;
2651 }
2652
2653 /* truncate() replacement */
2654 int
2655 win32_truncate_replacement(const wchar_t *path, off_t size)
2656 {
2657         DWORD err = NO_ERROR;
2658         LARGE_INTEGER liOffset;
2659
2660         HANDLE h = win32_open_existing_file(path, GENERIC_WRITE);
2661         if (h == INVALID_HANDLE_VALUE)
2662                 goto fail;
2663
2664         liOffset.QuadPart = size;
2665         if (!SetFilePointerEx(h, liOffset, NULL, FILE_BEGIN))
2666                 goto fail_close_handle;
2667
2668         if (!SetEndOfFile(h))
2669                 goto fail_close_handle;
2670         CloseHandle(h);
2671         return 0;
2672
2673 fail_close_handle:
2674         err = GetLastError();
2675         CloseHandle(h);
2676 fail:
2677         if (err == NO_ERROR)
2678                 err = GetLastError();
2679         ERROR("Can't truncate \"%ls\" to %"PRIu64" bytes", path, size);
2680         win32_error(err);
2681         errno = -1;
2682         return -1;
2683 }
2684
2685
2686 /* This really could be replaced with _wcserror_s, but this doesn't seem to
2687  * actually be available in MSVCRT.DLL on Windows XP (perhaps it's statically
2688  * linked in by Visual Studio...?). */
2689 extern int
2690 win32_strerror_r_replacement(int errnum, wchar_t *buf, size_t buflen)
2691 {
2692         static pthread_mutex_t strerror_lock = PTHREAD_MUTEX_INITIALIZER;
2693
2694         pthread_mutex_lock(&strerror_lock);
2695         mbstowcs(buf, strerror(errnum), buflen);
2696         buf[buflen - 1] = '\0';
2697         pthread_mutex_unlock(&strerror_lock);
2698         return 0;
2699 }
2700
2701 #endif /* __WIN32__ */