]> wimlib.net Git - wimlib/blob - src/win32.c
Win32 apply: Accept ERROR_ACCESS_DENIED for SACL access denied
[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 /* Wrapper around the FSCTL_SET_REPARSE_POINT ioctl to set the reparse data on
1378  * an extracted reparse point. */
1379 static int
1380 win32_set_reparse_data(HANDLE h,
1381                        u32 reparse_tag,
1382                        const struct wim_lookup_table_entry *lte,
1383                        const wchar_t *path)
1384 {
1385         int ret;
1386         u8 *buf;
1387         size_t len;
1388
1389         if (!lte) {
1390                 WARNING("\"%ls\" is marked as a reparse point but had no reparse data",
1391                         path);
1392                 return 0;
1393         }
1394         len = wim_resource_size(lte);
1395         if (len > 16 * 1024 - 8) {
1396                 WARNING("\"%ls\": reparse data too long!", path);
1397                 return 0;
1398         }
1399
1400         /* The WIM stream omits the ReparseTag and ReparseDataLength fields, so
1401          * leave 8 bytes of space for them at the beginning of the buffer, then
1402          * set them manually. */
1403         buf = alloca(len + 8);
1404         ret = read_full_resource_into_buf(lte, buf + 8, false);
1405         if (ret)
1406                 return ret;
1407         *(u32*)(buf + 0) = cpu_to_le32(reparse_tag);
1408         *(u16*)(buf + 4) = cpu_to_le16(len);
1409         *(u16*)(buf + 6) = 0;
1410
1411         /* Set the reparse data on the open file using the
1412          * FSCTL_SET_REPARSE_POINT ioctl.
1413          *
1414          * There are contradictions in Microsoft's documentation for this:
1415          *
1416          * "If hDevice was opened without specifying FILE_FLAG_OVERLAPPED,
1417          * lpOverlapped is ignored."
1418          *
1419          * --- So setting lpOverlapped to NULL is okay since it's ignored.
1420          *
1421          * "If lpOverlapped is NULL, lpBytesReturned cannot be NULL. Even when an
1422          * operation returns no output data and lpOutBuffer is NULL,
1423          * DeviceIoControl makes use of lpBytesReturned. After such an
1424          * operation, the value of lpBytesReturned is meaningless."
1425          *
1426          * --- So lpOverlapped not really ignored, as it affects another
1427          *  parameter.  This is the actual behavior: lpBytesReturned must be
1428          *  specified, even though lpBytesReturned is documented as:
1429          *
1430          *  "Not used with this operation; set to NULL."
1431          */
1432         DWORD bytesReturned;
1433         if (!DeviceIoControl(h, FSCTL_SET_REPARSE_POINT, buf, len + 8,
1434                              NULL, 0,
1435                              &bytesReturned /* lpBytesReturned */,
1436                              NULL /* lpOverlapped */))
1437         {
1438                 DWORD err = GetLastError();
1439                 ERROR("Failed to set reparse data on \"%ls\"", path);
1440                 win32_error(err);
1441                 if (err == ERROR_ACCESS_DENIED || err == ERROR_PRIVILEGE_NOT_HELD)
1442                         return WIMLIB_ERR_INSUFFICIENT_PRIVILEGES_TO_EXTRACT;
1443                 else if (reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
1444                          reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT)
1445                         return WIMLIB_ERR_LINK;
1446                 else
1447                         return WIMLIB_ERR_WRITE;
1448         }
1449         return 0;
1450 }
1451
1452 /* Wrapper around the FSCTL_SET_COMPRESSION ioctl to change the
1453  * FILE_ATTRIBUTE_COMPRESSED flag of a file or directory. */
1454 static int
1455 win32_set_compression_state(HANDLE hFile, USHORT format, const wchar_t *path)
1456 {
1457         DWORD bytesReturned;
1458         if (!DeviceIoControl(hFile, FSCTL_SET_COMPRESSION,
1459                              &format, sizeof(USHORT),
1460                              NULL, 0,
1461                              &bytesReturned, NULL))
1462         {
1463                 /* Could be a warning only, but we only call this if the volume
1464                  * supports compression.  So I'm calling this an error. */
1465                 DWORD err = GetLastError();
1466                 ERROR("Failed to set compression flag on \"%ls\"", path);
1467                 win32_error(err);
1468                 if (err == ERROR_ACCESS_DENIED || err == ERROR_PRIVILEGE_NOT_HELD)
1469                         return WIMLIB_ERR_INSUFFICIENT_PRIVILEGES_TO_EXTRACT;
1470                 else
1471                         return WIMLIB_ERR_WRITE;
1472         }
1473         return 0;
1474 }
1475
1476 /* Wrapper around FSCTL_SET_SPARSE ioctl to set a file as sparse. */
1477 static int
1478 win32_set_sparse(HANDLE hFile, const wchar_t *path)
1479 {
1480         DWORD bytesReturned;
1481         if (!DeviceIoControl(hFile, FSCTL_SET_SPARSE,
1482                              NULL, 0,
1483                              NULL, 0,
1484                              &bytesReturned, NULL))
1485         {
1486                 /* Could be a warning only, but we only call this if the volume
1487                  * supports sparse files.  So I'm calling this an error. */
1488                 DWORD err = GetLastError();
1489                 WARNING("Failed to set sparse flag on \"%ls\"", path);
1490                 win32_error(err);
1491                 if (err == ERROR_ACCESS_DENIED || err == ERROR_PRIVILEGE_NOT_HELD)
1492                         return WIMLIB_ERR_INSUFFICIENT_PRIVILEGES_TO_EXTRACT;
1493                 else
1494                         return WIMLIB_ERR_WRITE;
1495         }
1496         return 0;
1497 }
1498
1499 /*
1500  * Sets the security descriptor on an extracted file.
1501  */
1502 static int
1503 win32_set_security_data(const struct wim_inode *inode,
1504                         HANDLE hFile,
1505                         const wchar_t *path,
1506                         struct apply_args *args)
1507 {
1508         PSECURITY_DESCRIPTOR descriptor;
1509         unsigned long n;
1510         DWORD err;
1511         const struct wim_security_data *sd;
1512
1513         SECURITY_INFORMATION securityInformation = 0;
1514
1515         void *owner = NULL;
1516         void *group = NULL;
1517         ACL *dacl = NULL;
1518         ACL *sacl = NULL;
1519
1520         BOOL owner_defaulted;
1521         BOOL group_defaulted;
1522         BOOL dacl_present;
1523         BOOL dacl_defaulted;
1524         BOOL sacl_present;
1525         BOOL sacl_defaulted;
1526
1527         sd = wim_const_security_data(args->w);
1528         descriptor = sd->descriptors[inode->i_security_id];
1529
1530         GetSecurityDescriptorOwner(descriptor, &owner, &owner_defaulted);
1531         if (owner)
1532                 securityInformation |= OWNER_SECURITY_INFORMATION;
1533
1534         GetSecurityDescriptorGroup(descriptor, &group, &group_defaulted);
1535         if (group)
1536                 securityInformation |= GROUP_SECURITY_INFORMATION;
1537
1538         GetSecurityDescriptorDacl(descriptor, &dacl_present,
1539                                   &dacl, &dacl_defaulted);
1540         if (dacl)
1541                 securityInformation |= DACL_SECURITY_INFORMATION;
1542
1543         GetSecurityDescriptorSacl(descriptor, &sacl_present,
1544                                   &sacl, &sacl_defaulted);
1545         if (sacl)
1546                 securityInformation |= SACL_SECURITY_INFORMATION;
1547
1548 again:
1549         if (securityInformation == 0)
1550                 return 0;
1551         if (SetSecurityInfo(hFile, SE_FILE_OBJECT,
1552                             securityInformation, owner, group, dacl, sacl))
1553                 return 0;
1554         err = GetLastError();
1555         if (args->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS)
1556                 goto fail;
1557         switch (err) {
1558         case ERROR_PRIVILEGE_NOT_HELD:
1559                 if (securityInformation & SACL_SECURITY_INFORMATION) {
1560                         n = args->num_set_sacl_priv_notheld++;
1561                         securityInformation &= ~SACL_SECURITY_INFORMATION;
1562                         sacl = NULL;
1563                         if (n < MAX_SET_SACL_PRIV_NOTHELD_WARNINGS) {
1564                                 WARNING(
1565 "We don't have enough privileges to set the full security\n"
1566 "          descriptor on \"%ls\"!\n", path);
1567                                 if (args->num_set_sd_access_denied +
1568                                     args->num_set_sacl_priv_notheld == 1)
1569                                 {
1570                                         WARNING("%ls", apply_access_denied_msg);
1571                                 }
1572                                 WARNING("Re-trying with SACL omitted.\n", path);
1573                         } else if (n == MAX_GET_SACL_PRIV_NOTHELD_WARNINGS) {
1574                                 WARNING(
1575 "Suppressing further 'privileges not held' error messages when setting\n"
1576 "          security descriptors.");
1577                         }
1578                         goto again;
1579                 }
1580                 /* Fall through */
1581         case ERROR_INVALID_OWNER:
1582         case ERROR_ACCESS_DENIED:
1583                 n = args->num_set_sd_access_denied++;
1584                 if (n < MAX_SET_SD_ACCESS_DENIED_WARNINGS) {
1585                         WARNING("Failed to set security descriptor on \"%ls\": "
1586                                 "Access denied!\n", path);
1587                         if (args->num_set_sd_access_denied +
1588                             args->num_set_sacl_priv_notheld == 1)
1589                         {
1590                                 WARNING("%ls", apply_access_denied_msg);
1591                         }
1592                 } else if (n == MAX_SET_SD_ACCESS_DENIED_WARNINGS) {
1593                         WARNING(
1594 "Suppressing further access denied error messages when setting\n"
1595 "          security descriptors");
1596                 }
1597                 return 0;
1598         default:
1599 fail:
1600                 ERROR("Failed to set security descriptor on \"%ls\"", path);
1601                 win32_error(err);
1602                 if (err == ERROR_ACCESS_DENIED || err == ERROR_PRIVILEGE_NOT_HELD)
1603                         return WIMLIB_ERR_INSUFFICIENT_PRIVILEGES_TO_EXTRACT;
1604                 else
1605                         return WIMLIB_ERR_WRITE;
1606         }
1607 }
1608
1609
1610 static int
1611 win32_extract_chunk(const void *buf, size_t len, void *arg)
1612 {
1613         HANDLE hStream = arg;
1614
1615         DWORD nbytes_written;
1616         wimlib_assert(len <= 0xffffffff);
1617
1618         if (!WriteFile(hStream, buf, len, &nbytes_written, NULL) ||
1619             nbytes_written != len)
1620         {
1621                 DWORD err = GetLastError();
1622                 ERROR("WriteFile(): write error");
1623                 win32_error(err);
1624                 return WIMLIB_ERR_WRITE;
1625         }
1626         return 0;
1627 }
1628
1629 static int
1630 do_win32_extract_stream(HANDLE hStream, const struct wim_lookup_table_entry *lte)
1631 {
1632         return extract_wim_resource(lte, wim_resource_size(lte),
1633                                     win32_extract_chunk, hStream);
1634 }
1635
1636 struct win32_encrypted_extract_ctx {
1637         void *file_ctx;
1638         int wimlib_err_code;
1639         bool done;
1640         pthread_cond_t cond;
1641         pthread_mutex_t mutex;
1642         u8 buf[WIM_CHUNK_SIZE];
1643         size_t buf_filled;
1644 };
1645
1646 static DWORD WINAPI
1647 win32_encrypted_import_cb(unsigned char *data, void *_ctx,
1648                           unsigned long *len_p)
1649 {
1650         struct win32_encrypted_extract_ctx *ctx = _ctx;
1651         unsigned long len = *len_p;
1652
1653         pthread_mutex_lock(&ctx->mutex);
1654         while (len) {
1655                 size_t bytes_to_copy;
1656
1657                 DEBUG("Importing up to %lu more bytes of raw encrypted data", len);
1658                 while (ctx->buf_filled == 0) {
1659                         if (ctx->done)
1660                                 goto out;
1661                         pthread_cond_wait(&ctx->cond, &ctx->mutex);
1662                 }
1663                 bytes_to_copy = min(len, ctx->buf_filled);
1664                 memcpy(data, ctx->buf, bytes_to_copy);
1665                 len -= bytes_to_copy;
1666                 data += bytes_to_copy;
1667                 ctx->buf_filled -= bytes_to_copy;
1668                 memmove(ctx->buf, ctx->buf + bytes_to_copy, ctx->buf_filled);
1669                 pthread_cond_signal(&ctx->cond);
1670         }
1671 out:
1672         *len_p -= len;
1673         pthread_mutex_unlock(&ctx->mutex);
1674         return ERROR_SUCCESS;
1675 }
1676
1677 /* Extract ("Import") an encrypted file in a different thread. */
1678 static void *
1679 win32_encrypted_import_proc(void *arg)
1680 {
1681         struct win32_encrypted_extract_ctx *ctx = arg;
1682         DWORD ret;
1683         ret = WriteEncryptedFileRaw(win32_encrypted_import_cb, ctx,
1684                                     ctx->file_ctx);
1685         pthread_mutex_lock(&ctx->mutex);
1686         if (ret == ERROR_SUCCESS) {
1687                 ctx->wimlib_err_code = 0;
1688         } else {
1689                 win32_error(ret);
1690                 ctx->wimlib_err_code = WIMLIB_ERR_WRITE;
1691         }
1692         ctx->done = true;
1693         pthread_cond_signal(&ctx->cond);
1694         pthread_mutex_unlock(&ctx->mutex);
1695         return NULL;
1696 }
1697
1698
1699 static int
1700 win32_extract_raw_encrypted_chunk(const void *buf, size_t len, void *arg)
1701 {
1702         struct win32_encrypted_extract_ctx *ctx = arg;
1703         size_t bytes_to_copy;
1704
1705         while (len) {
1706                 DEBUG("Extracting up to %zu more bytes of encrypted data", len);
1707                 pthread_mutex_lock(&ctx->mutex);
1708                 while (ctx->buf_filled == WIM_CHUNK_SIZE) {
1709                         if (ctx->done) {
1710                                 pthread_mutex_unlock(&ctx->mutex);
1711                                 return ctx->wimlib_err_code;
1712                         }
1713                         pthread_cond_wait(&ctx->cond, &ctx->mutex);
1714                 }
1715                 bytes_to_copy = min(len, WIM_CHUNK_SIZE - ctx->buf_filled);
1716                 memcpy(&ctx->buf[ctx->buf_filled], buf, bytes_to_copy);
1717                 len -= bytes_to_copy;
1718                 buf += bytes_to_copy;
1719                 ctx->buf_filled += bytes_to_copy;
1720                 pthread_cond_signal(&ctx->cond);
1721                 pthread_mutex_unlock(&ctx->mutex);
1722         }
1723         return 0;
1724 }
1725
1726 /* Create an encrypted file and extract the raw encrypted data to it.
1727  *
1728  * @path:  Path to encrypted file to create.
1729  * @lte:   WIM lookup_table entry for the raw encrypted data.
1730  *
1731  * This is separate from do_win32_extract_stream() because the WIM is supposed
1732  * to contain the *raw* encrypted data, which needs to be extracted ("imported")
1733  * using the special APIs OpenEncryptedFileRawW(), WriteEncryptedFileRaw(), and
1734  * CloseEncryptedFileRaw().
1735  *
1736  * Returns 0 on success; nonzero on failure.
1737  */
1738 static int
1739 do_win32_extract_encrypted_stream(const wchar_t *path,
1740                                   const struct wim_lookup_table_entry *lte)
1741 {
1742         struct win32_encrypted_extract_ctx ctx;
1743         void *file_ctx;
1744         pthread_t import_thread;
1745         int ret;
1746         int ret2;
1747
1748         DEBUG("Opening file \"%ls\" to extract raw encrypted data", path);
1749
1750         ret = OpenEncryptedFileRawW(path, CREATE_FOR_IMPORT, &file_ctx);
1751         if (ret) {
1752                 ERROR("Failed to open \"%ls\" to write raw encrypted data", path);
1753                 win32_error(ret);
1754                 return WIMLIB_ERR_OPEN;
1755         }
1756
1757         if (!lte)
1758                 goto out_close;
1759
1760         /* Hack alert:  WriteEncryptedFileRaw() requires the callback function
1761          * to work with a buffer whose size we cannot control.  This doesn't
1762          * play well with our read_resource_prefix() function, which itself uses
1763          * a callback function to extract WIM_CHUNK_SIZE chunks of data.  We
1764          * work around this problem by calling WriteEncryptedFileRaw() in a
1765          * different thread and feeding it the data as needed.  */
1766         ctx.file_ctx = file_ctx;
1767         ctx.buf_filled = 0;
1768         ctx.done = false;
1769         ctx.wimlib_err_code = 0;
1770         if (pthread_mutex_init(&ctx.mutex, NULL)) {
1771                 ERROR_WITH_ERRNO("Can't create mutex");
1772                 ret = WIMLIB_ERR_NOMEM;
1773                 goto out_close;
1774         }
1775         if (pthread_cond_init(&ctx.cond, NULL)) {
1776                 ERROR_WITH_ERRNO("Can't create condition variable");
1777                 ret = WIMLIB_ERR_NOMEM;
1778                 goto out_pthread_mutex_destroy;
1779         }
1780         ret = pthread_create(&import_thread, NULL,
1781                              win32_encrypted_import_proc, &ctx);
1782         if (ret) {
1783                 errno = ret;
1784                 ERROR_WITH_ERRNO("Failed to create thread");
1785                 ret = WIMLIB_ERR_FORK;
1786                 goto out_pthread_cond_destroy;
1787         }
1788
1789         ret = extract_wim_resource(lte, wim_resource_size(lte),
1790                                    win32_extract_raw_encrypted_chunk, &ctx);
1791         pthread_mutex_lock(&ctx.mutex);
1792         ctx.done = true;
1793         pthread_cond_signal(&ctx.cond);
1794         pthread_mutex_unlock(&ctx.mutex);
1795         ret2 = pthread_join(import_thread, NULL);
1796         if (ret2) {
1797                 errno = ret2;
1798                 ERROR_WITH_ERRNO("Failed to join encrypted import thread");
1799                 if (ret == 0)
1800                         ret = WIMLIB_ERR_WRITE;
1801         }
1802         if (ret == 0)
1803                 ret = ctx.wimlib_err_code;
1804 out_pthread_cond_destroy:
1805         pthread_cond_destroy(&ctx.cond);
1806 out_pthread_mutex_destroy:
1807         pthread_mutex_destroy(&ctx.mutex);
1808 out_close:
1809         CloseEncryptedFileRaw(file_ctx);
1810         if (ret)
1811                 ERROR("Failed to extract encrypted file \"%ls\"", path);
1812         return ret;
1813 }
1814
1815 static bool
1816 path_is_root_of_drive(const wchar_t *path)
1817 {
1818         if (!*path)
1819                 return false;
1820
1821         if (*path != L'/' && *path != L'\\') {
1822                 if (*(path + 1) == L':')
1823                         path += 2;
1824                 else
1825                         return false;
1826         }
1827         while (*path == L'/' || *path == L'\\')
1828                 path++;
1829         return (*path == L'\0');
1830 }
1831
1832 static inline DWORD
1833 win32_mask_attributes(DWORD i_attributes)
1834 {
1835         return i_attributes & ~(FILE_ATTRIBUTE_SPARSE_FILE |
1836                                 FILE_ATTRIBUTE_COMPRESSED |
1837                                 FILE_ATTRIBUTE_REPARSE_POINT |
1838                                 FILE_ATTRIBUTE_DIRECTORY |
1839                                 FILE_ATTRIBUTE_ENCRYPTED |
1840                                 FILE_FLAG_DELETE_ON_CLOSE |
1841                                 FILE_FLAG_NO_BUFFERING |
1842                                 FILE_FLAG_OPEN_NO_RECALL |
1843                                 FILE_FLAG_OVERLAPPED |
1844                                 FILE_FLAG_RANDOM_ACCESS |
1845                                 /*FILE_FLAG_SESSION_AWARE |*/
1846                                 FILE_FLAG_SEQUENTIAL_SCAN |
1847                                 FILE_FLAG_WRITE_THROUGH);
1848 }
1849
1850 static inline DWORD
1851 win32_get_create_flags_and_attributes(DWORD i_attributes)
1852 {
1853         /*
1854          * Some attributes cannot be set by passing them to CreateFile().  In
1855          * particular:
1856          *
1857          * FILE_ATTRIBUTE_DIRECTORY:
1858          *   CreateDirectory() must be called instead of CreateFile().
1859          *
1860          * FILE_ATTRIBUTE_SPARSE_FILE:
1861          *   Needs an ioctl.
1862          *   See: win32_set_sparse().
1863          *
1864          * FILE_ATTRIBUTE_COMPRESSED:
1865          *   Not clear from the documentation, but apparently this needs an
1866          *   ioctl as well.
1867          *   See: win32_set_compressed().
1868          *
1869          * FILE_ATTRIBUTE_REPARSE_POINT:
1870          *   Needs an ioctl, with the reparse data specified.
1871          *   See: win32_set_reparse_data().
1872          *
1873          * In addition, clear any file flags in the attributes that we don't
1874          * want, but also specify FILE_FLAG_OPEN_REPARSE_POINT and
1875          * FILE_FLAG_BACKUP_SEMANTICS as we are a backup application.
1876          */
1877         return win32_mask_attributes(i_attributes) |
1878                 FILE_FLAG_OPEN_REPARSE_POINT |
1879                 FILE_FLAG_BACKUP_SEMANTICS;
1880 }
1881
1882 /* Set compression and/or sparse attributes on a stream, if supported by the
1883  * volume. */
1884 static int
1885 win32_set_special_stream_attributes(HANDLE hFile, const struct wim_inode *inode,
1886                                     struct wim_lookup_table_entry *unnamed_stream_lte,
1887                                     const wchar_t *path, unsigned vol_flags)
1888 {
1889         int ret;
1890
1891         if (inode->i_attributes & FILE_ATTRIBUTE_COMPRESSED) {
1892                 if (vol_flags & FILE_FILE_COMPRESSION) {
1893                         ret = win32_set_compression_state(hFile,
1894                                                           COMPRESSION_FORMAT_DEFAULT,
1895                                                           path);
1896                         if (ret)
1897                                 return ret;
1898                 } else {
1899                         DEBUG("Cannot set compression attribute on \"%ls\": "
1900                               "volume does not support transparent compression",
1901                               path);
1902                 }
1903         }
1904
1905         if (inode->i_attributes & FILE_ATTRIBUTE_SPARSE_FILE) {
1906                 if (vol_flags & FILE_SUPPORTS_SPARSE_FILES) {
1907                         DEBUG("Setting sparse flag on \"%ls\"", path);
1908                         ret = win32_set_sparse(hFile, path);
1909                         if (ret)
1910                                 return ret;
1911                 } else {
1912                         DEBUG("Cannot set sparse attribute on \"%ls\": "
1913                               "volume does not support sparse files",
1914                               path);
1915                 }
1916         }
1917         return 0;
1918 }
1919
1920 /* Pre-create directories; extract encrypted streams */
1921 static int
1922 win32_begin_extract_unnamed_stream(const struct wim_inode *inode,
1923                                    const struct wim_lookup_table_entry *lte,
1924                                    const wchar_t *path,
1925                                    DWORD *creationDisposition_ret,
1926                                    unsigned int vol_flags)
1927 {
1928         DWORD err;
1929         int ret;
1930
1931         /* Directories must be created with CreateDirectoryW().  Then the call
1932          * to CreateFileW() will merely open the directory that was already
1933          * created rather than creating a new file. */
1934         if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY &&
1935             !path_is_root_of_drive(path)) {
1936                 if (!CreateDirectoryW(path, NULL)) {
1937                         err = GetLastError();
1938                         if (err != ERROR_ALREADY_EXISTS) {
1939                                 ERROR("Failed to create directory \"%ls\"",
1940                                       path);
1941                                 win32_error(err);
1942                                 return WIMLIB_ERR_MKDIR;
1943                         }
1944                 }
1945                 DEBUG("Created directory \"%ls\"", path);
1946                 *creationDisposition_ret = OPEN_EXISTING;
1947         }
1948         if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED &&
1949             vol_flags & FILE_SUPPORTS_ENCRYPTION)
1950         {
1951                 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1952                         if (!EncryptFile(path)) {
1953                                 err = GetLastError();
1954                                 ERROR("Failed to encrypt directory \"%ls\"",
1955                                       path);
1956                                 win32_error(err);
1957                                 return WIMLIB_ERR_WRITE;
1958                         }
1959                 } else {
1960                         ret = do_win32_extract_encrypted_stream(path, lte);
1961                         if (ret)
1962                                 return ret;
1963                         DEBUG("Extracted encrypted file \"%ls\"", path);
1964                 }
1965                 *creationDisposition_ret = OPEN_EXISTING;
1966         }
1967
1968         /* Set file attributes if we created the file.  Otherwise, we haven't
1969          * created the file set and we will set the attributes in the call to
1970          * CreateFileW().
1971          *
1972          * The FAT filesystem does not let you change the attributes of the root
1973          * directory, so treat that as a special case and do not set attributes.
1974          * */
1975         if (*creationDisposition_ret == OPEN_EXISTING &&
1976             !path_is_root_of_drive(path))
1977         {
1978                 if (!SetFileAttributesW(path,
1979                                         win32_mask_attributes(inode->i_attributes)))
1980                 {
1981                         err = GetLastError();
1982                         ERROR("Failed to set attributes on \"%ls\"", path);
1983                         win32_error(err);
1984                         return WIMLIB_ERR_WRITE;
1985                 }
1986         }
1987         return 0;
1988 }
1989
1990 /* Set security descriptor and extract stream data or reparse data (skip the
1991  * unnamed data stream of encrypted files, which was already extracted). */
1992 static int
1993 win32_finish_extract_stream(HANDLE h, const struct wim_inode *inode,
1994                             const struct wim_lookup_table_entry *lte,
1995                             const wchar_t *stream_path,
1996                             const wchar_t *stream_name_utf16,
1997                             struct apply_args *args)
1998 {
1999         int ret = 0;
2000         if (stream_name_utf16 == NULL) {
2001                 /* Unnamed stream. */
2002
2003                 /* Set security descriptor, unless the extract_flags indicate
2004                  * not to or the volume does not supported it.  Note that this
2005                  * is only done when the unnamed stream is being extracted, as
2006                  * security descriptors are per-file and not per-stream. */
2007                 if (inode->i_security_id >= 0 &&
2008                     !(args->extract_flags & WIMLIB_EXTRACT_FLAG_NO_ACLS)
2009                     && (args->vol_flags & FILE_PERSISTENT_ACLS))
2010                 {
2011                         ret = win32_set_security_data(inode, h, stream_path, args);
2012                         if (ret)
2013                                 return ret;
2014                 }
2015
2016                 /* Handle reparse points.  The data for them needs to be set
2017                  * using a special ioctl.  Note that the reparse point may have
2018                  * been created using CreateFileW() in the case of
2019                  * non-directories or CreateDirectoryW() in the case of
2020                  * directories; but the ioctl works either way.  Also, it is
2021                  * only this step that actually sets the
2022                  * FILE_ATTRIBUTE_REPARSE_POINT, as it is not valid to set it
2023                  * using SetFileAttributesW() or CreateFileW().
2024                  *
2025                  * If the volume does not support reparse points we simply
2026                  * ignore the reparse data.  (N.B. the code currently doesn't
2027                  * actually reach this case because reparse points are skipped
2028                  * entirely on such volumes.) */
2029                 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
2030                         if (args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS) {
2031                                 DEBUG("Setting reparse data on \"%ls\"",
2032                                       stream_path);
2033                                 ret = win32_set_reparse_data(h,
2034                                                              inode->i_reparse_tag,
2035                                                              lte, stream_path);
2036                                 if (ret)
2037                                         return ret;
2038                         } else {
2039                                 DEBUG("Cannot set reparse data on \"%ls\": volume "
2040                                       "does not support reparse points", stream_path);
2041                         }
2042                 } else if (lte != NULL &&
2043                            !(args->vol_flags & FILE_SUPPORTS_ENCRYPTION &&
2044                              inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED))
2045                 {
2046                         /* Extract the data of the unnamed stream, unless the
2047                          * lookup table entry is NULL (indicating an empty
2048                          * stream for which no data needs to be extracted), or
2049                          * the stream is encrypted and therefore was already
2050                          * extracted as a special case. */
2051                         ret = do_win32_extract_stream(h, lte);
2052                 }
2053         } else {
2054                 /* Extract the data for a named data stream. */
2055                 if (lte != NULL) {
2056                         DEBUG("Extracting named data stream \"%ls\" (len = %"PRIu64")",
2057                               stream_path, wim_resource_size(lte));
2058                         ret = do_win32_extract_stream(h, lte);
2059                 }
2060         }
2061         return ret;
2062 }
2063
2064 static int
2065 win32_decrypt_file(HANDLE open_handle, const wchar_t *path)
2066 {
2067         DWORD err;
2068         /* We cannot call DecryptFileW() while there is an open handle to the
2069          * file.  So close it first. */
2070         if (!CloseHandle(open_handle)) {
2071                 err = GetLastError();
2072                 ERROR("Failed to close handle for \"%ls\"", path);
2073                 win32_error(err);
2074                 return WIMLIB_ERR_WRITE;
2075         }
2076         if (!DecryptFileW(path, 0 /* reserved parameter; set to 0 */)) {
2077                 err = GetLastError();
2078                 ERROR("Failed to decrypt file \"%ls\"", path);
2079                 win32_error(err);
2080                 return WIMLIB_ERR_WRITE;
2081         }
2082         return 0;
2083 }
2084
2085 /*
2086  * Create and extract a stream to a file, or create a directory, using the
2087  * Windows API.
2088  *
2089  * This handles reparse points, directories, alternate data streams, encrypted
2090  * files, compressed files, etc.
2091  *
2092  * @inode: WIM inode containing the stream.
2093  *
2094  * @path:  Path to extract the file to.
2095  *
2096  * @stream_name_utf16:
2097  *         Name of the stream, or NULL if the stream is unnamed.  This will
2098  *         be called with a NULL stream_name_utf16 before any non-NULL
2099  *         stream_name_utf16's.
2100  *
2101  * @lte:   WIM lookup table entry for the stream.  May be NULL to indicate
2102  *         a stream of length 0.
2103  *
2104  * @args:  Additional apply context, including flags indicating supported
2105  *         volume features.
2106  *
2107  * Returns 0 on success; nonzero on failure.
2108  */
2109 static int
2110 win32_extract_stream(const struct wim_inode *inode,
2111                      const wchar_t *path,
2112                      const wchar_t *stream_name_utf16,
2113                      struct wim_lookup_table_entry *lte,
2114                      struct apply_args *args)
2115 {
2116         wchar_t *stream_path;
2117         HANDLE h;
2118         int ret;
2119         DWORD err;
2120         DWORD creationDisposition = CREATE_ALWAYS;
2121         DWORD requestedAccess;
2122         BY_HANDLE_FILE_INFORMATION file_info;
2123
2124         if (stream_name_utf16) {
2125                 /* Named stream.  Create a buffer that contains the UTF-16LE
2126                  * string [./]path:stream_name_utf16.  This is needed to
2127                  * create and open the stream using CreateFileW().  I'm not
2128                  * aware of any other APIs to do this.  Note: the '$DATA' suffix
2129                  * seems to be unneeded.  Additional note: a "./" prefix needs
2130                  * to be added when the path is not absolute to avoid ambiguity
2131                  * with drive letters. */
2132                 size_t stream_path_nchars;
2133                 size_t path_nchars;
2134                 size_t stream_name_nchars;
2135                 const wchar_t *prefix;
2136
2137                 path_nchars = wcslen(path);
2138                 stream_name_nchars = wcslen(stream_name_utf16);
2139                 stream_path_nchars = path_nchars + 1 + stream_name_nchars;
2140                 if (path[0] != cpu_to_le16(L'\0') &&
2141                     path[0] != cpu_to_le16(L'/') &&
2142                     path[0] != cpu_to_le16(L'\\') &&
2143                     path[1] != cpu_to_le16(L':'))
2144                 {
2145                         prefix = L"./";
2146                         stream_path_nchars += 2;
2147                 } else {
2148                         prefix = L"";
2149                 }
2150                 stream_path = alloca((stream_path_nchars + 1) * sizeof(wchar_t));
2151                 swprintf(stream_path, L"%ls%ls:%ls",
2152                          prefix, path, stream_name_utf16);
2153         } else {
2154                 /* Unnamed stream; its path is just the path to the file itself.
2155                  * */
2156                 stream_path = (wchar_t*)path;
2157
2158                 ret = win32_begin_extract_unnamed_stream(inode, lte, path,
2159                                                          &creationDisposition,
2160                                                          args->vol_flags);
2161                 if (ret)
2162                         goto fail;
2163         }
2164
2165         DEBUG("Opening \"%ls\"", stream_path);
2166         requestedAccess = GENERIC_READ | GENERIC_WRITE |
2167                           ACCESS_SYSTEM_SECURITY;
2168 try_open_again:
2169         /* Open the stream to be extracted.  Depending on what we have set
2170          * creationDisposition to, we may be creating this for the first time,
2171          * or we may be opening on existing stream we already created using
2172          * CreateDirectoryW() or OpenEncryptedFileRawW(). */
2173         h = CreateFileW(stream_path,
2174                         requestedAccess,
2175                         0,
2176                         NULL,
2177                         creationDisposition,
2178                         win32_get_create_flags_and_attributes(inode->i_attributes),
2179                         NULL);
2180         if (h == INVALID_HANDLE_VALUE) {
2181                 err = GetLastError();
2182                 if (err == ERROR_ACCESS_DENIED &&
2183                     path_is_root_of_drive(stream_path))
2184                 {
2185                         ret = 0;
2186                         goto out;
2187                 }
2188                 if ((err == ERROR_PRIVILEGE_NOT_HELD ||
2189                      err == ERROR_ACCESS_DENIED) &&
2190                     (requestedAccess & ACCESS_SYSTEM_SECURITY))
2191                 {
2192                         /* Try opening the file again without privilege to
2193                          * modify SACL. */
2194                         requestedAccess &= ~ACCESS_SYSTEM_SECURITY;
2195                         goto try_open_again;
2196                 }
2197                 ERROR("Failed to create \"%ls\"", stream_path);
2198                 win32_error(err);
2199                 ret = WIMLIB_ERR_OPEN;
2200                 goto fail;
2201         }
2202
2203         /* Check the attributes of the file we just opened, and remove
2204          * encryption or compression if either was set by default but is not
2205          * supposed to be set based on the WIM inode attributes. */
2206         if (!GetFileInformationByHandle(h, &file_info)) {
2207                 err = GetLastError();
2208                 ERROR("Failed to get attributes of \"%ls\"", stream_path);
2209                 win32_error(err);
2210                 ret = WIMLIB_ERR_STAT;
2211                 goto fail_close_handle;
2212         }
2213
2214         /* Remove encryption? */
2215         if (file_info.dwFileAttributes & FILE_ATTRIBUTE_ENCRYPTED &&
2216             !(inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED))
2217         {
2218                 /* File defaulted to encrypted due to being in an encrypted
2219                  * directory, but is not actually supposed to be encrypted.
2220                  *
2221                  * This is a workaround, because I'm not aware of any way to
2222                  * directly (e.g. with CreateFileW()) create an unencrypted file
2223                  * in a directory with FILE_ATTRIBUTE_ENCRYPTED set. */
2224                 ret = win32_decrypt_file(h, stream_path);
2225                 if (ret)
2226                         goto fail; /* win32_decrypt_file() closed the handle. */
2227                 creationDisposition = OPEN_EXISTING;
2228                 goto try_open_again;
2229         }
2230
2231         /* Remove compression? */
2232         if (file_info.dwFileAttributes & FILE_ATTRIBUTE_COMPRESSED &&
2233             !(inode->i_attributes & FILE_ATTRIBUTE_COMPRESSED))
2234         {
2235                 /* Similar to the encrypted case, above, if the file defaulted
2236                  * to compressed due to being in an compressed directory, but is
2237                  * not actually supposed to be compressed, explicitly set the
2238                  * compression format to COMPRESSION_FORMAT_NONE. */
2239                 ret = win32_set_compression_state(h, COMPRESSION_FORMAT_NONE,
2240                                                   stream_path);
2241                 if (ret)
2242                         goto fail_close_handle;
2243         }
2244
2245         /* Set compression and/or sparse attributes if needed */
2246         ret = win32_set_special_stream_attributes(h, inode, lte, path,
2247                                                   args->vol_flags);
2248
2249         if (ret)
2250                 goto fail_close_handle;
2251
2252         /* At this point we have at least created the needed stream with the
2253          * appropriate attributes.  We have yet to set the appropriate security
2254          * descriptor and actually extract the stream data (other than for
2255          * extracted files, which were already extracted).
2256          * win32_finish_extract_stream() handles these additional steps. */
2257         ret = win32_finish_extract_stream(h, inode, lte, stream_path,
2258                                           stream_name_utf16, args);
2259         if (ret)
2260                 goto fail_close_handle;
2261
2262         /* Done extracting the stream.  Close the handle and return. */
2263         DEBUG("Closing \"%ls\"", stream_path);
2264         if (!CloseHandle(h)) {
2265                 err = GetLastError();
2266                 ERROR("Failed to close \"%ls\"", stream_path);
2267                 win32_error(err);
2268                 ret = WIMLIB_ERR_WRITE;
2269                 goto fail;
2270         }
2271         ret = 0;
2272         goto out;
2273 fail_close_handle:
2274         CloseHandle(h);
2275 fail:
2276         ERROR("Error extracting \"%ls\"", stream_path);
2277 out:
2278         return ret;
2279 }
2280
2281 /*
2282  * Creates a file, directory, or reparse point and extracts all streams to it
2283  * (unnamed data stream and/or reparse point stream, plus any alternate data
2284  * streams).  Handles sparse, compressed, and/or encrypted files.
2285  *
2286  * @inode:      WIM inode for this file or directory.
2287  * @path:       UTF-16LE external path to extract the inode to.
2288  * @args:       Additional extraction context.
2289  *
2290  * Returns 0 on success; nonzero on failure.
2291  */
2292 static int
2293 win32_extract_streams(const struct wim_inode *inode,
2294                       const wchar_t *path, struct apply_args *args)
2295 {
2296         struct wim_lookup_table_entry *unnamed_lte;
2297         int ret;
2298
2299         /* First extract the unnamed stream. */
2300
2301         unnamed_lte = inode_unnamed_lte_resolved(inode);
2302         ret = win32_extract_stream(inode, path, NULL, unnamed_lte, args);
2303         if (ret)
2304                 goto out;
2305
2306         /* Extract any named streams, if supported by the volume. */
2307
2308         if (!(args->vol_flags & FILE_NAMED_STREAMS))
2309                 goto out;
2310         for (u16 i = 0; i < inode->i_num_ads; i++) {
2311                 const struct wim_ads_entry *ads_entry = &inode->i_ads_entries[i];
2312
2313                 /* Skip the unnamed stream if it's in the ADS entries (we
2314                  * already extracted it...) */
2315                 if (ads_entry->stream_name_nbytes == 0)
2316                         continue;
2317
2318                 /* Skip special UNIX data entries (see documentation for
2319                  * WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA) */
2320                 if (ads_entry->stream_name_nbytes == WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES
2321                     && !memcmp(ads_entry->stream_name,
2322                                WIMLIB_UNIX_DATA_TAG_UTF16LE,
2323                                WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES))
2324                         continue;
2325
2326                 /* Extract the named stream */
2327                 ret = win32_extract_stream(inode,
2328                                            path,
2329                                            ads_entry->stream_name,
2330                                            ads_entry->lte,
2331                                            args);
2332                 if (ret)
2333                         break;
2334         }
2335 out:
2336         return ret;
2337 }
2338
2339 /* If not done already, load the supported feature flags for the volume onto
2340  * which the image is being extracted, and warn the user about any missing
2341  * features that could be important. */
2342 static int
2343 win32_check_vol_flags(const wchar_t *output_path, struct apply_args *args)
2344 {
2345         if (args->have_vol_flags)
2346                 return 0;
2347
2348         win32_get_vol_flags(output_path, &args->vol_flags);
2349         args->have_vol_flags = true;
2350         /* Warn the user about data that may not be extracted. */
2351         if (!(args->vol_flags & FILE_SUPPORTS_SPARSE_FILES))
2352                 WARNING("Volume does not support sparse files!\n"
2353                         "          Sparse files will be extracted as non-sparse.");
2354         if (!(args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS))
2355                 WARNING("Volume does not support reparse points!\n"
2356                         "          Reparse point data will not be extracted.");
2357         if (!(args->vol_flags & FILE_NAMED_STREAMS)) {
2358                 WARNING("Volume does not support named data streams!\n"
2359                         "          Named data streams will not be extracted.");
2360         }
2361         if (!(args->vol_flags & FILE_SUPPORTS_ENCRYPTION)) {
2362                 WARNING("Volume does not support encryption!\n"
2363                         "          Encrypted files will be extracted as raw data.");
2364         }
2365         if (!(args->vol_flags & FILE_FILE_COMPRESSION)) {
2366                 WARNING("Volume does not support transparent compression!\n"
2367                         "          Compressed files will be extracted as non-compressed.");
2368         }
2369         if (!(args->vol_flags & FILE_PERSISTENT_ACLS)) {
2370                 if (args->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS) {
2371                         ERROR("Strict ACLs requested, but the volume does not "
2372                               "support ACLs!");
2373                         return WIMLIB_ERR_VOLUME_LACKS_FEATURES;
2374                 } else {
2375                         WARNING("Volume does not support persistent ACLS!\n"
2376                                 "          File permissions will not be extracted.");
2377                 }
2378         }
2379         return 0;
2380 }
2381
2382 /*
2383  * Try extracting a hard link.
2384  *
2385  * @output_path:  Path to link to be extracted.
2386  *
2387  * @inode:        WIM inode that the link is to; inode->i_extracted_file
2388  *                the path to a name of the file that has already been
2389  *                extracted (we use this to create the hard link).
2390  *
2391  * @args:         Additional apply context, used here to keep track of
2392  *                the number of times creating a hard link failed due to
2393  *                ERROR_INVALID_FUNCTION.  This error should indicate that hard
2394  *                links are not supported by the volume, and we would like to
2395  *                warn the user a few times, but not too many times.
2396  *
2397  * Returns 0 if the hard link was successfully extracted.  Returns
2398  * WIMLIB_ERR_LINK (> 0) if an error occurred, other than hard links possibly
2399  * being unsupported by the volume.  Returns a negative value if creating the
2400  * hard link failed due to ERROR_INVALID_FUNCTION.
2401  */
2402 static int
2403 win32_try_hard_link(const wchar_t *output_path, const struct wim_inode *inode,
2404                     struct apply_args *args)
2405 {
2406         DWORD err;
2407
2408         /* There is a volume flag for this (FILE_SUPPORTS_HARD_LINKS),
2409          * but it's only available on Windows 7 and later.  So no use
2410          * even checking it, really.  Instead, CreateHardLinkW() will
2411          * apparently return ERROR_INVALID_FUNCTION if the volume does
2412          * not support hard links. */
2413         DEBUG("Creating hard link \"%ls => %ls\"",
2414               output_path, inode->i_extracted_file);
2415         if (CreateHardLinkW(output_path, inode->i_extracted_file, NULL))
2416                 return 0;
2417
2418         err = GetLastError();
2419         if (err != ERROR_INVALID_FUNCTION) {
2420                 ERROR("Can't create hard link \"%ls => %ls\"",
2421                       output_path, inode->i_extracted_file);
2422                 win32_error(err);
2423                 return WIMLIB_ERR_LINK;
2424         } else {
2425                 args->num_hard_links_failed++;
2426                 if (args->num_hard_links_failed < MAX_CREATE_HARD_LINK_WARNINGS) {
2427                         WARNING("Can't create hard link \"%ls => %ls\":\n"
2428                                 "          Volume does not support hard links!\n"
2429                                 "          Falling back to extracting a copy of the file.",
2430                                 output_path, inode->i_extracted_file);
2431                 } else if (args->num_hard_links_failed == MAX_CREATE_HARD_LINK_WARNINGS) {
2432                         WARNING("Suppressing further hard linking warnings...");
2433                 }
2434                 return -1;
2435         }
2436 }
2437
2438 /* Extract a file, directory, reparse point, or hard link to an
2439  * already-extracted file using the Win32 API */
2440 int
2441 win32_do_apply_dentry(const wchar_t *output_path,
2442                       size_t output_path_num_chars,
2443                       struct wim_dentry *dentry,
2444                       struct apply_args *args)
2445 {
2446         int ret;
2447         struct wim_inode *inode = dentry->d_inode;
2448
2449         ret = win32_check_vol_flags(output_path, args);
2450         if (ret)
2451                 return ret;
2452         if (inode->i_nlink > 1 && inode->i_extracted_file != NULL) {
2453                 /* Linked file, with another name already extracted.  Create a
2454                  * hard link. */
2455                 ret = win32_try_hard_link(output_path, inode, args);
2456                 if (ret >= 0)
2457                         return ret;
2458                 /* Negative return value from win32_try_hard_link() indicates
2459                  * that hard links are probably not supported by the volume.
2460                  * Fall back to extracting a copy of the file. */
2461         }
2462
2463         /* If this is a reparse point and the volume does not support reparse
2464          * points, just skip it completely. */
2465         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT &&
2466             !(args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS))
2467         {
2468                 WARNING("Skipping extraction of reparse point \"%ls\":\n"
2469                         "          Not supported by destination filesystem",
2470                         output_path);
2471         } else {
2472                 /* Create the file, directory, or reparse point, and extract the
2473                  * data streams. */
2474                 ret = win32_extract_streams(inode, output_path, args);
2475                 if (ret)
2476                         return ret;
2477         }
2478         if (inode->i_extracted_file == NULL) {
2479                 const struct wim_lookup_table_entry *lte;
2480
2481                 /* Tally bytes extracted, including all alternate data streams,
2482                  * unless we extracted a hard link (or, at least extracted a
2483                  * name that was supposed to be a hard link) */
2484                 for (unsigned i = 0; i <= inode->i_num_ads; i++) {
2485                         lte = inode_stream_lte_resolved(inode, i);
2486                         if (lte)
2487                                 args->progress.extract.completed_bytes +=
2488                                                         wim_resource_size(lte);
2489                 }
2490                 if (inode->i_nlink > 1) {
2491                         /* Save extracted path for a later call to
2492                          * CreateHardLinkW() if this inode has multiple links.
2493                          * */
2494                         inode->i_extracted_file = WSTRDUP(output_path);
2495                         if (!inode->i_extracted_file)
2496                                 return WIMLIB_ERR_NOMEM;
2497                 }
2498         }
2499         return 0;
2500 }
2501
2502 /* Set timestamps on an extracted file using the Win32 API */
2503 int
2504 win32_do_apply_dentry_timestamps(const wchar_t *path,
2505                                  size_t path_num_chars,
2506                                  const struct wim_dentry *dentry,
2507                                  const struct apply_args *args)
2508 {
2509         DWORD err;
2510         HANDLE h;
2511         const struct wim_inode *inode = dentry->d_inode;
2512
2513         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT &&
2514             !(args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS))
2515         {
2516                 /* Skip reparse points not extracted */
2517                 return 0;
2518         }
2519
2520         /* Windows doesn't let you change the timestamps of the root directory
2521          * (at least on FAT, which is dumb but expected since FAT doesn't store
2522          * any metadata about the root directory...) */
2523         if (path_is_root_of_drive(path))
2524                 return 0;
2525
2526         DEBUG("Opening \"%ls\" to set timestamps", path);
2527         h = win32_open_existing_file(path, FILE_WRITE_ATTRIBUTES);
2528         if (h == INVALID_HANDLE_VALUE) {
2529                 err = GetLastError();
2530                 goto fail;
2531         }
2532
2533         FILETIME creationTime = {.dwLowDateTime = inode->i_creation_time & 0xffffffff,
2534                                  .dwHighDateTime = inode->i_creation_time >> 32};
2535         FILETIME lastAccessTime = {.dwLowDateTime = inode->i_last_access_time & 0xffffffff,
2536                                   .dwHighDateTime = inode->i_last_access_time >> 32};
2537         FILETIME lastWriteTime = {.dwLowDateTime = inode->i_last_write_time & 0xffffffff,
2538                                   .dwHighDateTime = inode->i_last_write_time >> 32};
2539
2540         DEBUG("Calling SetFileTime() on \"%ls\"", path);
2541         if (!SetFileTime(h, &creationTime, &lastAccessTime, &lastWriteTime)) {
2542                 err = GetLastError();
2543                 CloseHandle(h);
2544                 goto fail;
2545         }
2546         DEBUG("Closing \"%ls\"", path);
2547         if (!CloseHandle(h)) {
2548                 err = GetLastError();
2549                 goto fail;
2550         }
2551         goto out;
2552 fail:
2553         /* Only warn if setting timestamps failed; still return 0. */
2554         WARNING("Can't set timestamps on \"%ls\"", path);
2555         win32_error(err);
2556 out:
2557         return 0;
2558 }
2559
2560 /* Replacement for POSIX fsync() */
2561 int
2562 fsync(int fd)
2563 {
2564         DWORD err;
2565         HANDLE h;
2566
2567         h = (HANDLE)_get_osfhandle(fd);
2568         if (h == INVALID_HANDLE_VALUE) {
2569                 err = GetLastError();
2570                 ERROR("Could not get Windows handle for file descriptor");
2571                 win32_error(err);
2572                 errno = EBADF;
2573                 return -1;
2574         }
2575         if (!FlushFileBuffers(h)) {
2576                 err = GetLastError();
2577                 ERROR("Could not flush file buffers to disk");
2578                 win32_error(err);
2579                 errno = EIO;
2580                 return -1;
2581         }
2582         return 0;
2583 }
2584
2585 /* Use the Win32 API to get the number of processors */
2586 unsigned
2587 win32_get_number_of_processors()
2588 {
2589         SYSTEM_INFO sysinfo;
2590         GetSystemInfo(&sysinfo);
2591         return sysinfo.dwNumberOfProcessors;
2592 }
2593
2594 /* Replacement for POSIX-2008 realpath().  Warning: partial functionality only
2595  * (resolved_path must be NULL).   Also I highly doubt that GetFullPathName
2596  * really does the right thing under all circumstances. */
2597 wchar_t *
2598 realpath(const wchar_t *path, wchar_t *resolved_path)
2599 {
2600         DWORD ret;
2601         wimlib_assert(resolved_path == NULL);
2602         DWORD err;
2603
2604         ret = GetFullPathNameW(path, 0, NULL, NULL);
2605         if (!ret) {
2606                 err = GetLastError();
2607                 goto fail_win32;
2608         }
2609
2610         resolved_path = TMALLOC(ret);
2611         if (!resolved_path)
2612                 goto out;
2613         ret = GetFullPathNameW(path, ret, resolved_path, NULL);
2614         if (!ret) {
2615                 err = GetLastError();
2616                 free(resolved_path);
2617                 resolved_path = NULL;
2618                 goto fail_win32;
2619         }
2620         goto out;
2621 fail_win32:
2622         win32_error(err);
2623         errno = -1;
2624 out:
2625         return resolved_path;
2626 }
2627
2628 /* rename() on Windows fails if the destination file exists.  And we need to
2629  * make it work on wide characters.  Fix it. */
2630 int
2631 win32_rename_replacement(const wchar_t *oldpath, const wchar_t *newpath)
2632 {
2633         if (MoveFileExW(oldpath, newpath, MOVEFILE_REPLACE_EXISTING)) {
2634                 return 0;
2635         } else {
2636                 /* As usual, the possible error values are not documented */
2637                 DWORD err = GetLastError();
2638                 ERROR("MoveFileEx(): Can't rename \"%ls\" to \"%ls\"",
2639                       oldpath, newpath);
2640                 win32_error(err);
2641                 errno = -1;
2642                 return -1;
2643         }
2644 }
2645
2646 /* Replacement for POSIX fnmatch() (partial functionality only) */
2647 int
2648 fnmatch(const wchar_t *pattern, const wchar_t *string, int flags)
2649 {
2650         if (PathMatchSpecW(string, pattern))
2651                 return 0;
2652         else
2653                 return FNM_NOMATCH;
2654 }
2655
2656 /* truncate() replacement */
2657 int
2658 win32_truncate_replacement(const wchar_t *path, off_t size)
2659 {
2660         DWORD err = NO_ERROR;
2661         LARGE_INTEGER liOffset;
2662
2663         HANDLE h = win32_open_existing_file(path, GENERIC_WRITE);
2664         if (h == INVALID_HANDLE_VALUE)
2665                 goto fail;
2666
2667         liOffset.QuadPart = size;
2668         if (!SetFilePointerEx(h, liOffset, NULL, FILE_BEGIN))
2669                 goto fail_close_handle;
2670
2671         if (!SetEndOfFile(h))
2672                 goto fail_close_handle;
2673         CloseHandle(h);
2674         return 0;
2675
2676 fail_close_handle:
2677         err = GetLastError();
2678         CloseHandle(h);
2679 fail:
2680         if (err == NO_ERROR)
2681                 err = GetLastError();
2682         ERROR("Can't truncate \"%ls\" to %"PRIu64" bytes", path, size);
2683         win32_error(err);
2684         errno = -1;
2685         return -1;
2686 }
2687
2688
2689 /* This really could be replaced with _wcserror_s, but this doesn't seem to
2690  * actually be available in MSVCRT.DLL on Windows XP (perhaps it's statically
2691  * linked in by Visual Studio...?). */
2692 extern int
2693 win32_strerror_r_replacement(int errnum, wchar_t *buf, size_t buflen)
2694 {
2695         static pthread_mutex_t strerror_lock = PTHREAD_MUTEX_INITIALIZER;
2696
2697         pthread_mutex_lock(&strerror_lock);
2698         mbstowcs(buf, strerror(errnum), buflen);
2699         buf[buflen - 1] = '\0';
2700         pthread_mutex_unlock(&strerror_lock);
2701         return 0;
2702 }
2703
2704 #endif /* __WIN32__ */