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