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