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