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