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