]> wimlib.net Git - wimlib/blob - src/win32.c
643832fbdc61dfb151286c1d3d268325afcf44a0
[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> /* shlwapi.h for PathMatchSpecW() */
33 #ifdef ERROR /* windows.h defines this */
34 #  undef ERROR
35 #endif
36
37 #include "win32.h"
38 #include "dentry.h"
39 #include "lookup_table.h"
40 #include "security.h"
41 #include "endianness.h"
42 #include "buffer_io.h"
43 #include <pthread.h>
44
45 #include <errno.h>
46
47 #define MAX_GET_SD_ACCESS_DENIED_WARNINGS 1
48 #define MAX_GET_SACL_PRIV_NOTHELD_WARNINGS 1
49 #define MAX_CREATE_HARD_LINK_WARNINGS 5
50 struct win32_capture_state {
51         unsigned long num_get_sd_access_denied;
52         unsigned long num_get_sacl_priv_notheld;
53 };
54
55 #define MAX_SET_SD_ACCESS_DENIED_WARNINGS 1
56 #define MAX_SET_SACL_PRIV_NOTHELD_WARNINGS 1
57
58 #ifdef ENABLE_ERROR_MESSAGES
59 static void
60 win32_error(u32 err_code)
61 {
62         wchar_t *buffer;
63         DWORD nchars;
64         nchars = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
65                                     FORMAT_MESSAGE_ALLOCATE_BUFFER,
66                                 NULL, err_code, 0,
67                                 (wchar_t*)&buffer, 0, NULL);
68         if (nchars == 0) {
69                 ERROR("Error printing error message! "
70                       "Computer will self-destruct in 3 seconds.");
71         } else {
72                 ERROR("Win32 error: %ls", buffer);
73                 LocalFree(buffer);
74         }
75 }
76 #else /* ENABLE_ERROR_MESSAGES */
77 #  define win32_error(err_code)
78 #endif /* !ENABLE_ERROR_MESSAGES */
79
80 /* Pointers to functions that are not available on all targetted versions of
81  * Windows (XP and later).  NOTE: The WINAPI annotations seem to be important; I
82  * assume it specifies a certain calling convention. */
83
84 /* Vista and later */
85 static HANDLE (WINAPI *win32func_FindFirstStreamW)(LPCWSTR lpFileName,
86                                             STREAM_INFO_LEVELS InfoLevel,
87                                             LPVOID lpFindStreamData,
88                                             DWORD dwFlags) = NULL;
89
90 /* Vista and later */
91 static BOOL (WINAPI *win32func_FindNextStreamW)(HANDLE hFindStream,
92                                          LPVOID lpFindStreamData) = NULL;
93
94 static HMODULE hKernel32 = NULL;
95
96 /* Try to dynamically load some functions */
97 void
98 win32_global_init()
99 {
100         DWORD err;
101
102         if (hKernel32 == NULL) {
103                 DEBUG("Loading Kernel32.dll");
104                 hKernel32 = LoadLibraryW(L"Kernel32.dll");
105                 if (hKernel32 == NULL) {
106                         err = GetLastError();
107                         WARNING("Can't load Kernel32.dll");
108                         win32_error(err);
109                         return;
110                 }
111         }
112
113         DEBUG("Looking for FindFirstStreamW");
114         win32func_FindFirstStreamW = (void*)GetProcAddress(hKernel32, "FindFirstStreamW");
115         if (!win32func_FindFirstStreamW) {
116                 WARNING("Could not find function FindFirstStreamW() in Kernel32.dll!");
117                 WARNING("Capturing alternate data streams will not be supported.");
118                 return;
119         }
120
121         DEBUG("Looking for FindNextStreamW");
122         win32func_FindNextStreamW = (void*)GetProcAddress(hKernel32, "FindNextStreamW");
123         if (!win32func_FindNextStreamW) {
124                 WARNING("Could not find function FindNextStreamW() in Kernel32.dll!");
125                 WARNING("Capturing alternate data streams will not be supported.");
126                 win32func_FindFirstStreamW = NULL;
127         }
128 }
129
130 void
131 win32_global_cleanup()
132 {
133         if (hKernel32 != NULL) {
134                 DEBUG("Closing Kernel32.dll");
135                 FreeLibrary(hKernel32);
136                 hKernel32 = NULL;
137         }
138 }
139
140 static const wchar_t *capture_access_denied_msg =
141 L"         If you are not running this program as the administrator, you may\n"
142  "         need to do so, so that all data and metadata can be backed up.\n"
143  "         Otherwise, there may be no way to access the desired data or\n"
144  "         metadata without taking ownership of the file or directory.\n"
145  ;
146
147 static const wchar_t *apply_access_denied_msg =
148 L"If you are not running this program as the administrator, you may\n"
149  "          need to do so, so that all data and metadata can be extracted\n"
150  "          exactly as the origignal copy.  However, if you do not care that\n"
151  "          the security descriptors are extracted correctly, you could run\n"
152  "          `wimlib-imagex apply' with the --no-acls flag instead.\n"
153  ;
154
155 static HANDLE
156 win32_open_existing_file(const wchar_t *path, DWORD dwDesiredAccess)
157 {
158         return CreateFileW(path,
159                            dwDesiredAccess,
160                            FILE_SHARE_READ,
161                            NULL, /* lpSecurityAttributes */
162                            OPEN_EXISTING,
163                            FILE_FLAG_BACKUP_SEMANTICS |
164                                FILE_FLAG_OPEN_REPARSE_POINT,
165                            NULL /* hTemplateFile */);
166 }
167
168 HANDLE
169 win32_open_file_data_only(const wchar_t *path)
170 {
171         return win32_open_existing_file(path, FILE_READ_DATA);
172 }
173
174 int
175 read_win32_file_prefix(const struct wim_lookup_table_entry *lte,
176                        u64 size,
177                        consume_data_callback_t cb,
178                        void *ctx_or_buf,
179                        int _ignored_flags)
180 {
181         int ret = 0;
182         void *out_buf;
183         DWORD err;
184         u64 bytes_remaining;
185
186         HANDLE hFile = win32_open_file_data_only(lte->file_on_disk);
187         if (hFile == INVALID_HANDLE_VALUE) {
188                 err = GetLastError();
189                 ERROR("Failed to open \"%ls\"", lte->file_on_disk);
190                 win32_error(err);
191                 return WIMLIB_ERR_OPEN;
192         }
193
194         if (cb)
195                 out_buf = alloca(WIM_CHUNK_SIZE);
196         else
197                 out_buf = ctx_or_buf;
198
199         bytes_remaining = size;
200         while (bytes_remaining) {
201                 DWORD bytesToRead, bytesRead;
202
203                 bytesToRead = min(WIM_CHUNK_SIZE, bytes_remaining);
204                 if (!ReadFile(hFile, out_buf, bytesToRead, &bytesRead, NULL) ||
205                     bytesRead != bytesToRead)
206                 {
207                         err = GetLastError();
208                         ERROR("Failed to read data from \"%ls\"", lte->file_on_disk);
209                         win32_error(err);
210                         ret = WIMLIB_ERR_READ;
211                         break;
212                 }
213                 bytes_remaining -= bytesRead;
214                 if (cb) {
215                         ret = (*cb)(out_buf, bytesRead, ctx_or_buf);
216                         if (ret)
217                                 break;
218                 } else {
219                         out_buf += bytesRead;
220                 }
221         }
222         CloseHandle(hFile);
223         return ret;
224 }
225
226 struct win32_encrypted_read_ctx {
227         consume_data_callback_t read_prefix_cb;
228         void *read_prefix_ctx_or_buf;
229         int wimlib_err_code;
230         void *buf;
231         size_t buf_filled;
232         u64 bytes_remaining;
233 };
234
235 static DWORD WINAPI
236 win32_encrypted_export_cb(unsigned char *_data, void *_ctx, unsigned long len)
237 {
238         const void *data = _data;
239         struct win32_encrypted_read_ctx *ctx = _ctx;
240         int ret;
241
242         DEBUG("len = %lu", len);
243         if (ctx->read_prefix_cb) {
244                 /* The length of the buffer passed to the ReadEncryptedFileRaw()
245                  * export callback is undocumented, so we assume it may be of
246                  * arbitrary size. */
247                 size_t bytes_to_buffer = min(ctx->bytes_remaining - ctx->buf_filled,
248                                              len);
249                 while (bytes_to_buffer) {
250                         size_t bytes_to_copy_to_buf =
251                                 min(bytes_to_buffer, WIM_CHUNK_SIZE - ctx->buf_filled);
252
253                         memcpy(ctx->buf + ctx->buf_filled, data,
254                                bytes_to_copy_to_buf);
255                         ctx->buf_filled += bytes_to_copy_to_buf;
256                         data += bytes_to_copy_to_buf;
257                         bytes_to_buffer -= bytes_to_copy_to_buf;
258
259                         if (ctx->buf_filled == WIM_CHUNK_SIZE ||
260                             ctx->buf_filled == ctx->bytes_remaining)
261                         {
262                                 ret = (*ctx->read_prefix_cb)(ctx->buf,
263                                                              ctx->buf_filled,
264                                                              ctx->read_prefix_ctx_or_buf);
265                                 if (ret) {
266                                         ctx->wimlib_err_code = ret;
267                                         /* Shouldn't matter what error code is returned
268                                          * here, as long as it isn't ERROR_SUCCESS. */
269                                         return ERROR_READ_FAULT;
270                                 }
271                                 ctx->bytes_remaining -= ctx->buf_filled;
272                                 ctx->buf_filled = 0;
273                         }
274                 }
275         } else {
276                 size_t len_to_copy = min(len, ctx->bytes_remaining);
277                 memcpy(ctx->read_prefix_ctx_or_buf, data, len_to_copy);
278                 ctx->bytes_remaining -= len_to_copy;
279                 ctx->read_prefix_ctx_or_buf += len_to_copy;
280         }
281         return ERROR_SUCCESS;
282 }
283
284 int
285 read_win32_encrypted_file_prefix(const struct wim_lookup_table_entry *lte,
286                                  u64 size,
287                                  consume_data_callback_t cb,
288                                  void *ctx_or_buf,
289                                  int _ignored_flags)
290 {
291         struct win32_encrypted_read_ctx export_ctx;
292         DWORD err;
293         void *file_ctx;
294         int ret;
295
296         DEBUG("Reading %"PRIu64" bytes from encryted file \"%ls\"",
297               size, lte->file_on_disk);
298
299         export_ctx.read_prefix_cb = cb;
300         export_ctx.read_prefix_ctx_or_buf = ctx_or_buf;
301         export_ctx.wimlib_err_code = 0;
302         if (cb) {
303                 export_ctx.buf = MALLOC(WIM_CHUNK_SIZE);
304                 if (!export_ctx.buf)
305                         return WIMLIB_ERR_NOMEM;
306         } else {
307                 export_ctx.buf = NULL;
308         }
309         export_ctx.bytes_remaining = size;
310
311         err = OpenEncryptedFileRawW(lte->file_on_disk, 0, &file_ctx);
312         if (err != ERROR_SUCCESS) {
313                 ERROR("Failed to open encrypted file \"%ls\" for raw read",
314                       lte->file_on_disk);
315                 win32_error(err);
316                 ret = WIMLIB_ERR_OPEN;
317                 goto out_free_buf;
318         }
319         err = ReadEncryptedFileRaw(win32_encrypted_export_cb,
320                                    &export_ctx, file_ctx);
321         if (err != ERROR_SUCCESS) {
322                 ERROR("Failed to read encrypted file \"%ls\"",
323                       lte->file_on_disk);
324                 win32_error(err);
325                 ret = export_ctx.wimlib_err_code;
326                 if (ret == 0)
327                         ret = WIMLIB_ERR_READ;
328         } else if (export_ctx.bytes_remaining != 0) {
329                 ERROR("Only could read %"PRIu64" of %"PRIu64" bytes from "
330                       "encryted file \"%ls\"",
331                       size - export_ctx.bytes_remaining, size,
332                       lte->file_on_disk);
333                 ret = WIMLIB_ERR_READ;
334         } else {
335                 ret = 0;
336         }
337         CloseEncryptedFileRaw(file_ctx);
338 out_free_buf:
339         FREE(export_ctx.buf);
340         return ret;
341 }
342
343 /* Given a path, which may not yet exist, get a set of flags that describe the
344  * features of the volume the path is on. */
345 static int
346 win32_get_vol_flags(const wchar_t *path, unsigned *vol_flags_ret)
347 {
348         wchar_t *volume;
349         BOOL bret;
350         DWORD vol_flags;
351
352         if (path[0] != L'\0' && path[0] != L'\\' &&
353             path[0] != L'/' && path[1] == L':')
354         {
355                 /* Path starts with a drive letter; use it. */
356                 volume = alloca(4 * sizeof(wchar_t));
357                 volume[0] = path[0];
358                 volume[1] = path[1];
359                 volume[2] = L'\\';
360                 volume[3] = L'\0';
361         } else {
362                 /* Path does not start with a drive letter; use the volume of
363                  * the current working directory. */
364                 volume = NULL;
365         }
366         bret = GetVolumeInformationW(volume, /* lpRootPathName */
367                                      NULL,  /* lpVolumeNameBuffer */
368                                      0,     /* nVolumeNameSize */
369                                      NULL,  /* lpVolumeSerialNumber */
370                                      NULL,  /* lpMaximumComponentLength */
371                                      &vol_flags, /* lpFileSystemFlags */
372                                      NULL,  /* lpFileSystemNameBuffer */
373                                      0);    /* nFileSystemNameSize */
374         if (!bret) {
375                 DWORD err = GetLastError();
376                 WARNING("Failed to get volume information for path \"%ls\"", path);
377                 win32_error(err);
378                 vol_flags = 0xffffffff;
379         }
380
381         DEBUG("using vol_flags = %x", vol_flags);
382         *vol_flags_ret = vol_flags;
383         return 0;
384 }
385
386
387 static u64
388 FILETIME_to_u64(const FILETIME *ft)
389 {
390         return ((u64)ft->dwHighDateTime << 32) | (u64)ft->dwLowDateTime;
391 }
392
393 static int
394 win32_get_short_name(struct wim_dentry *dentry, const wchar_t *path)
395 {
396         WIN32_FIND_DATAW dat;
397         HANDLE hFind;
398         int ret = 0;
399
400         /* If we can't read the short filename for some reason, we just ignore
401          * the error and assume the file has no short name.  I don't think this
402          * should be an issue, since the short names are essentially obsolete
403          * anyway. */
404         hFind = FindFirstFileW(path, &dat);
405         if (hFind != INVALID_HANDLE_VALUE) {
406                 if (dat.cAlternateFileName[0] != L'\0') {
407                         DEBUG("\"%ls\": short name \"%ls\"", path, dat.cAlternateFileName);
408                         size_t short_name_nbytes = wcslen(dat.cAlternateFileName) *
409                                                    sizeof(wchar_t);
410                         size_t n = short_name_nbytes + sizeof(wchar_t);
411                         dentry->short_name = MALLOC(n);
412                         if (dentry->short_name) {
413                                 memcpy(dentry->short_name, dat.cAlternateFileName, n);
414                                 dentry->short_name_nbytes = short_name_nbytes;
415                         } else {
416                                 ret = WIMLIB_ERR_NOMEM;
417                         }
418                 }
419                 FindClose(hFind);
420         }
421         return ret;
422 }
423
424 static int
425 win32_get_security_descriptor(struct wim_dentry *dentry,
426                               struct sd_set *sd_set,
427                               const wchar_t *path,
428                               struct win32_capture_state *state,
429                               int add_image_flags)
430 {
431         SECURITY_INFORMATION requestedInformation;
432         DWORD lenNeeded = 0;
433         BOOL status;
434         DWORD err;
435         unsigned long n;
436
437         requestedInformation = DACL_SECURITY_INFORMATION |
438                                SACL_SECURITY_INFORMATION |
439                                OWNER_SECURITY_INFORMATION |
440                                GROUP_SECURITY_INFORMATION;
441 again:
442         /* Request length of security descriptor */
443         status = GetFileSecurityW(path, requestedInformation,
444                                   NULL, 0, &lenNeeded);
445         err = GetLastError();
446         if (!status && err == ERROR_INSUFFICIENT_BUFFER) {
447                 DWORD len = lenNeeded;
448                 char buf[len];
449                 if (GetFileSecurityW(path, requestedInformation,
450                                      (PSECURITY_DESCRIPTOR)buf, len, &lenNeeded))
451                 {
452                         int security_id = sd_set_add_sd(sd_set, buf, len);
453                         if (security_id < 0)
454                                 return WIMLIB_ERR_NOMEM;
455                         else {
456                                 dentry->d_inode->i_security_id = security_id;
457                                 return 0;
458                         }
459                 } else {
460                         err = GetLastError();
461                 }
462         }
463
464         if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_STRICT_ACLS)
465                 goto fail;
466
467         switch (err) {
468         case ERROR_PRIVILEGE_NOT_HELD:
469                 if (requestedInformation & SACL_SECURITY_INFORMATION) {
470                         n = state->num_get_sacl_priv_notheld++;
471                         requestedInformation &= ~SACL_SECURITY_INFORMATION;
472                         if (n < MAX_GET_SACL_PRIV_NOTHELD_WARNINGS) {
473                                 WARNING(
474 "We don't have enough privileges to read the full security\n"
475 "          descriptor of \"%ls\"!\n"
476 "          Re-trying with SACL omitted.\n", path);
477                         } else if (n == MAX_GET_SACL_PRIV_NOTHELD_WARNINGS) {
478                                 WARNING(
479 "Suppressing further privileges not held error messages when reading\n"
480 "          security descriptors.");
481                         }
482                         goto again;
483                 }
484                 /* Fall through */
485         case ERROR_ACCESS_DENIED:
486                 n = state->num_get_sd_access_denied++;
487                 if (n < MAX_GET_SD_ACCESS_DENIED_WARNINGS) {
488                         WARNING("Failed to read security descriptor of \"%ls\": "
489                                 "Access denied!\n%ls", path, capture_access_denied_msg);
490                 } else if (n == MAX_GET_SD_ACCESS_DENIED_WARNINGS) {
491                         WARNING("Suppressing further access denied errors messages i"
492                                 "when reading security descriptors");
493                 }
494                 return 0;
495         default:
496 fail:
497                 ERROR("Failed to read security descriptor of \"%ls\"", path);
498                 win32_error(err);
499                 return WIMLIB_ERR_READ;
500         }
501 }
502
503 static int
504 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
505                                   wchar_t *path,
506                                   size_t path_num_chars,
507                                   struct add_image_params *params,
508                                   struct win32_capture_state *state,
509                                   unsigned vol_flags);
510
511 /* Reads the directory entries of directory using a Win32 API and recursively
512  * calls win32_build_dentry_tree() on them. */
513 static int
514 win32_recurse_directory(struct wim_dentry *root,
515                         wchar_t *dir_path,
516                         size_t dir_path_num_chars,
517                         struct add_image_params *params,
518                         struct win32_capture_state *state,
519                         unsigned vol_flags)
520 {
521         WIN32_FIND_DATAW dat;
522         HANDLE hFind;
523         DWORD err;
524         int ret;
525
526         DEBUG("Recurse to directory \"%ls\"", dir_path);
527
528         /* Begin reading the directory by calling FindFirstFileW.  Unlike UNIX
529          * opendir(), FindFirstFileW has file globbing built into it.  But this
530          * isn't what we actually want, so just add a dummy glob to get all
531          * entries. */
532         dir_path[dir_path_num_chars] = L'/';
533         dir_path[dir_path_num_chars + 1] = L'*';
534         dir_path[dir_path_num_chars + 2] = L'\0';
535         hFind = FindFirstFileW(dir_path, &dat);
536         dir_path[dir_path_num_chars] = L'\0';
537
538         if (hFind == INVALID_HANDLE_VALUE) {
539                 err = GetLastError();
540                 if (err == ERROR_FILE_NOT_FOUND) {
541                         return 0;
542                 } else {
543                         ERROR("Failed to read directory \"%ls\"", dir_path);
544                         win32_error(err);
545                         return WIMLIB_ERR_READ;
546                 }
547         }
548         ret = 0;
549         do {
550                 /* Skip . and .. entries */
551                 if (dat.cFileName[0] == L'.' &&
552                     (dat.cFileName[1] == L'\0' ||
553                      (dat.cFileName[1] == L'.' &&
554                       dat.cFileName[2] == L'\0')))
555                         continue;
556                 size_t filename_len = wcslen(dat.cFileName);
557
558                 dir_path[dir_path_num_chars] = L'/';
559                 wmemcpy(dir_path + dir_path_num_chars + 1,
560                         dat.cFileName,
561                         filename_len + 1);
562
563                 struct wim_dentry *child;
564                 size_t path_len = dir_path_num_chars + 1 + filename_len;
565                 ret = win32_build_dentry_tree_recursive(&child,
566                                                         dir_path,
567                                                         path_len,
568                                                         params,
569                                                         state,
570                                                         vol_flags);
571                 dir_path[dir_path_num_chars] = L'\0';
572                 if (ret)
573                         goto out_find_close;
574                 if (child)
575                         dentry_add_child(root, child);
576         } while (FindNextFileW(hFind, &dat));
577         err = GetLastError();
578         if (err != ERROR_NO_MORE_FILES) {
579                 ERROR("Failed to read directory \"%ls\"", dir_path);
580                 win32_error(err);
581                 if (ret == 0)
582                         ret = WIMLIB_ERR_READ;
583         }
584 out_find_close:
585         FindClose(hFind);
586         return ret;
587 }
588
589 int
590 win32_get_file_and_vol_ids(const wchar_t *path, u64 *ino_ret, u64 *dev_ret)
591 {
592         HANDLE hFile;
593         DWORD err;
594         BY_HANDLE_FILE_INFORMATION file_info;
595         int ret;
596
597         hFile = win32_open_existing_file(path, FILE_READ_ATTRIBUTES);
598         if (hFile == INVALID_HANDLE_VALUE) {
599                 err = GetLastError();
600                 WARNING("Failed to open \"%ls\" to get file and volume IDs",
601                         path);
602                 win32_error(err);
603                 return WIMLIB_ERR_OPEN;
604         }
605
606         if (!GetFileInformationByHandle(hFile, &file_info)) {
607                 err = GetLastError();
608                 ERROR("Failed to get file information for \"%ls\"", path);
609                 win32_error(err);
610                 ret = WIMLIB_ERR_STAT;
611         } else {
612                 *ino_ret = ((u64)file_info.nFileIndexHigh << 32) |
613                             (u64)file_info.nFileIndexLow;
614                 *dev_ret = file_info.dwVolumeSerialNumber;
615                 ret = 0;
616         }
617         CloseHandle(hFile);
618         return ret;
619 }
620
621 /* Reparse point fixup status code */
622 enum rp_status {
623         /* Reparse point corresponded to an absolute symbolic link or junction
624          * point that pointed outside the directory tree being captured, and
625          * therefore was excluded. */
626         RP_EXCLUDED       = 0x0,
627
628         /* Reparse point was not fixed as it was either a relative symbolic
629          * link, a mount point, or something else we could not understand. */
630         RP_NOT_FIXED      = 0x1,
631
632         /* Reparse point corresponded to an absolute symbolic link or junction
633          * point that pointed inside the directory tree being captured, where
634          * the target was specified by a "full" \??\ prefixed path, and
635          * therefore was fixed to be relative to the root of the directory tree
636          * being captured. */
637         RP_FIXED_FULLPATH = 0x2,
638
639         /* Same as RP_FIXED_FULLPATH, except the absolute link target did not
640          * have the \??\ prefix.  It may have begun with a drive letter though.
641          * */
642         RP_FIXED_ABSPATH  = 0x4,
643
644         /* Either RP_FIXED_FULLPATH or RP_FIXED_ABSPATH. */
645         RP_FIXED          = RP_FIXED_FULLPATH | RP_FIXED_ABSPATH,
646 };
647
648 /* Given the "substitute name" target of a Windows reparse point, try doing a
649  * fixup where we change it to be absolute relative to the root of the directory
650  * tree being captured.
651  *
652  * Note that this is only executed when WIMLIB_ADD_IMAGE_FLAG_RPFIX has been
653  * set.
654  *
655  * @capture_root_ino and @capture_root_dev indicate the inode number and device
656  * of the root of the directory tree being captured.  They are meant to identify
657  * this directory (as an alternative to its actual path, which could potentially
658  * be reached via multiple destinations due to other symbolic links).  This may
659  * not work properly on FAT, which doesn't seem to supply proper inode numbers
660  * or file IDs.  However, FAT doesn't support reparse points so this function
661  * wouldn't even be called anyway.  */
662 static enum rp_status
663 win32_maybe_rpfix_target(wchar_t *target, size_t *target_nchars_p,
664                          u64 capture_root_ino, u64 capture_root_dev)
665 {
666         size_t target_nchars= *target_nchars_p;
667         size_t stripped_chars;
668         wchar_t *orig_target;
669
670         if (target_nchars == 0)
671                 /* Invalid reparse point (empty target) */
672                 return RP_NOT_FIXED;
673
674         if (target[0] == L'\\') {
675                 if (target_nchars >= 2 && target[1] == L'\\') {
676                         /* Probably a volume.  Can't do anything with it. */
677                         DEBUG("Not fixing target (probably a volume)");
678                         return RP_NOT_FIXED;
679                 } else if (target_nchars >= 7 &&
680                            target[1] == '?' &&
681                            target[2] == '?' &&
682                            target[3] == '\\' &&
683                            target[4] != '\0' &&
684                            target[5] == ':' &&
685                            target[6] == '\\')
686                 {
687                         DEBUG("Full style path");
688                         /* Full \??\x:\ style path (may be junction or symlink)
689                          * */
690                         stripped_chars = 6;
691                 } else {
692                         DEBUG("Absolute target without drive letter");
693                         /* Absolute target, without drive letter */
694                         stripped_chars = 0;
695                 }
696         } else if (target_nchars >= 3 &&
697                    target[0] != L'\0' &&
698                    target[1] == L':' &&
699                    target[2] == L'\\')
700         {
701                 DEBUG("Absolute target with drive letter");
702                 /* Absolute target, with drive letter */
703                 stripped_chars = 2;
704         } else {
705                 DEBUG("Relative symlink or other link");
706                 /* Relative symlink or other unexpected format */
707                 return RP_NOT_FIXED;
708         }
709         target[target_nchars] = L'\0';
710         orig_target = target;
711         target = fixup_symlink(target + stripped_chars, capture_root_ino, capture_root_dev);
712         if (!target)
713                 return RP_EXCLUDED;
714
715         target_nchars = wcslen(target);
716         wmemmove(orig_target + stripped_chars, target, target_nchars + 1);
717         *target_nchars_p = target_nchars + stripped_chars;
718         DEBUG("Fixed reparse point (new target: \"%ls\")", orig_target);
719         if (stripped_chars == 6)
720                 return RP_FIXED_FULLPATH;
721         else
722                 return RP_FIXED_ABSPATH;
723 }
724
725 static enum rp_status
726 win32_do_capture_rpfix(char *rpbuf, DWORD *rpbuflen_p,
727                        u64 capture_root_ino, u64 capture_root_dev)
728 {
729         const char *p_get;
730         char *p_put;
731         u16 substitute_name_offset;
732         u16 substitute_name_len;
733         wchar_t *target;
734         size_t target_nchars;
735         enum rp_status status;
736         u32 rptag;
737         DWORD rpbuflen = *rpbuflen_p;
738
739         if (rpbuflen < 16) /* Invalid reparse point (length too small) */
740                 return RP_NOT_FIXED;
741         p_get = get_u32(rpbuf, &rptag);
742         p_get += 4;
743         p_get = get_u16(p_get, &substitute_name_offset);
744         p_get = get_u16(p_get, &substitute_name_len);
745         p_get += 4;
746         if (rptag == WIM_IO_REPARSE_TAG_SYMLINK) {
747                 if (rpbuflen < 20) /* Invalid reparse point (length too small) */
748                         return RP_NOT_FIXED;
749                 p_get += 4;
750         }
751         if ((DWORD)substitute_name_offset +
752             substitute_name_len + (p_get - rpbuf) > rpbuflen)
753                 /* Invalid reparse point (length too small) */
754                 return RP_NOT_FIXED;
755
756         target = (wchar_t*)&p_get[substitute_name_offset];
757         target_nchars = substitute_name_len / 2;
758         /* Note: target is not necessarily null-terminated */
759
760         status = win32_maybe_rpfix_target(target, &target_nchars,
761                                           capture_root_ino, capture_root_dev);
762         if (status & RP_FIXED) {
763                 size_t target_nbytes = target_nchars * 2;
764                 size_t print_nbytes = target_nbytes;
765                 wchar_t target_copy[target_nchars];
766                 wchar_t *print_name = target_copy;
767
768                 if (status == RP_FIXED_FULLPATH) {
769                         /* "full path", meaning \??\ prefixed.  We should not
770                          * include this prefix in the print name, as it is
771                          * apparently meant for the filesystem driver only. */
772                         print_nbytes -= 8;
773                         print_name += 4;
774                 }
775                 wmemcpy(target_copy, target, target_nchars);
776                 p_put = rpbuf + 8;
777                 p_put = put_u16(p_put, 0); /* Substitute name offset */
778                 p_put = put_u16(p_put, target_nbytes); /* Substitute name length */
779                 p_put = put_u16(p_put, target_nbytes + 2); /* Print name offset */
780                 p_put = put_u16(p_put, print_nbytes); /* Print name length */
781                 if (rptag == WIM_IO_REPARSE_TAG_SYMLINK)
782                         p_put = put_u32(p_put, 1);
783                 p_put = put_bytes(p_put, target_nbytes, target_copy);
784                 p_put = put_u16(p_put, 0);
785                 p_put = put_bytes(p_put, print_nbytes, print_name);
786                 p_put = put_u16(p_put, 0);
787
788                 /* Wrote the end of the reparse data.  Recalculate the length,
789                  * set the length field correctly, and return it. */
790                 rpbuflen = p_put - rpbuf;
791                 put_u16(rpbuf + 4, rpbuflen - 8);
792                 *rpbuflen_p = rpbuflen;
793         }
794         return status;
795 }
796
797 /* Load a reparse point into a WIM inode.  It is just stored in memory.
798  *
799  * @hFile is the open handle to a reparse point, with permission to read the
800  * reparse data.
801  *
802  * @inode is the WIM inode for the reparse point.
803  */
804 static int
805 win32_capture_reparse_point(struct wim_dentry **root_p,
806                             HANDLE hFile,
807                             struct wim_inode *inode,
808                             const wchar_t *path,
809                             struct add_image_params *params)
810 {
811         DEBUG("Capturing reparse point \"%ls\"", path);
812
813         /* "Reparse point data, including the tag and optional GUID,
814          * cannot exceed 16 kilobytes." - MSDN  */
815         char reparse_point_buf[REPARSE_POINT_MAX_SIZE];
816         DWORD bytesReturned;
817         char *fixed_buf;
818         DWORD fixed_len;
819
820         if (!DeviceIoControl(hFile, FSCTL_GET_REPARSE_POINT,
821                              NULL, /* "Not used with this operation; set to NULL" */
822                              0, /* "Not used with this operation; set to 0" */
823                              reparse_point_buf, /* "A pointer to a buffer that
824                                                    receives the reparse point data */
825                              sizeof(reparse_point_buf), /* "The size of the output
826                                                            buffer, in bytes */
827                              &bytesReturned,
828                              NULL))
829         {
830                 DWORD err = GetLastError();
831                 ERROR("Failed to get reparse data of \"%ls\"", path);
832                 win32_error(err);
833                 return WIMLIB_ERR_READ;
834         }
835         if (bytesReturned < 8) {
836                 ERROR("Reparse data on \"%ls\" is invalid", path);
837                 return WIMLIB_ERR_READ;
838         }
839         inode->i_reparse_tag = le32_to_cpu(*(u32*)reparse_point_buf);
840
841         if (params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_RPFIX &&
842             (inode->i_reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
843              inode->i_reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT))
844         {
845                 /* Try doing reparse point fixup */
846                 enum rp_status status;
847                 status = win32_do_capture_rpfix(reparse_point_buf,
848                                                 &bytesReturned,
849                                                 params->capture_root_ino,
850                                                 params->capture_root_dev);
851                 if (status == RP_EXCLUDED) {
852                         /* Absolute path points out of capture tree.  Free the
853                          * dentry; we're not including it at all. */
854                         free_dentry(*root_p);
855                         *root_p = NULL;
856                         return 0;
857                 } else if (status & RP_FIXED) {
858                         /* Absolute path fixup was done. */
859                         inode->i_not_rpfixed = 0;
860                 }
861         }
862         return inode_set_unnamed_stream(inode, reparse_point_buf + 8,
863                                         bytesReturned - 8, params->lookup_table);
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                 lte->resource_location = RESOURCE_WIN32_ENCRYPTED;
981         else
982                 lte->resource_location = RESOURCE_WIN32;
983         lte->resource_entry.original_size = (u64)dat->StreamSize.QuadPart;
984
985         u32 stream_id;
986         if (is_named_stream) {
987                 stream_id = ads_entry->stream_id;
988                 ads_entry->lte = lte;
989         } else {
990                 stream_id = 0;
991                 inode->i_lte = lte;
992         }
993         lookup_table_insert_unhashed(lookup_table, lte, inode, stream_id);
994         ret = 0;
995 out_free_spath:
996         FREE(spath);
997 out:
998         return ret;
999 out_invalid_stream_name:
1000         ERROR("Invalid stream name: \"%ls:%ls\"", path, dat->cStreamName);
1001         ret = WIMLIB_ERR_READ;
1002         goto out;
1003 }
1004
1005 /* Scans a Win32 file for unnamed and named data streams (not reparse point
1006  * streams).
1007  *
1008  * @path:               Path to the file (UTF-16LE).
1009  *
1010  * @path_num_chars:     Number of 2-byte characters in @path.
1011  *
1012  * @inode:              WIM inode to save the stream into.
1013  *
1014  * @lookup_table:       Stream lookup table for the WIM.
1015  *
1016  * @file_size:          Size of unnamed data stream.  (Used only if alternate
1017  *                      data streams API appears to be unavailable.)
1018  *
1019  * @vol_flags:          Flags that specify features of the volume being
1020  *                      captured.
1021  *
1022  * Returns 0 on success; nonzero on failure.
1023  */
1024 static int
1025 win32_capture_streams(const wchar_t *path,
1026                       size_t path_num_chars,
1027                       struct wim_inode *inode,
1028                       struct wim_lookup_table *lookup_table,
1029                       u64 file_size,
1030                       unsigned vol_flags)
1031 {
1032         WIN32_FIND_STREAM_DATA dat;
1033         int ret;
1034         HANDLE hFind;
1035         DWORD err;
1036
1037         DEBUG("Capturing streams from \"%ls\"", path);
1038
1039         if (win32func_FindFirstStreamW == NULL ||
1040             !(vol_flags & FILE_NAMED_STREAMS))
1041                 goto unnamed_only;
1042
1043         hFind = win32func_FindFirstStreamW(path, FindStreamInfoStandard, &dat, 0);
1044         if (hFind == INVALID_HANDLE_VALUE) {
1045                 err = GetLastError();
1046                 if (err == ERROR_CALL_NOT_IMPLEMENTED)
1047                         goto unnamed_only;
1048
1049                 /* Seems legal for this to return ERROR_HANDLE_EOF on reparse
1050                  * points and directories */
1051                 if ((inode->i_attributes &
1052                     (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
1053                     && err == ERROR_HANDLE_EOF)
1054                 {
1055                         DEBUG("ERROR_HANDLE_EOF (ok)");
1056                         return 0;
1057                 } else {
1058                         if (err == ERROR_ACCESS_DENIED) {
1059                                 ERROR("Failed to look up data streams "
1060                                       "of \"%ls\": Access denied!\n%ls",
1061                                       path, capture_access_denied_msg);
1062                                 return WIMLIB_ERR_READ;
1063                         } else {
1064                                 ERROR("Failed to look up data streams "
1065                                       "of \"%ls\"", path);
1066                                 win32_error(err);
1067                                 return WIMLIB_ERR_READ;
1068                         }
1069                 }
1070         }
1071         do {
1072                 ret = win32_capture_stream(path,
1073                                            path_num_chars,
1074                                            inode, lookup_table,
1075                                            &dat);
1076                 if (ret)
1077                         goto out_find_close;
1078         } while (win32func_FindNextStreamW(hFind, &dat));
1079         err = GetLastError();
1080         if (err != ERROR_HANDLE_EOF) {
1081                 ERROR("Win32 API: Error reading data streams from \"%ls\"", path);
1082                 win32_error(err);
1083                 ret = WIMLIB_ERR_READ;
1084         }
1085 out_find_close:
1086         FindClose(hFind);
1087         return ret;
1088 unnamed_only:
1089         /* FindFirstStreamW() API is not available, or the volume does not
1090          * support named streams.  Only capture the unnamed data stream. */
1091         DEBUG("Only capturing unnamed data stream");
1092         if (inode->i_attributes &
1093              (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
1094         {
1095                 ret = 0;
1096         } else {
1097                 /* Just create our own WIN32_FIND_STREAM_DATA for an unnamed
1098                  * stream to reduce the code to a call to the
1099                  * already-implemented win32_capture_stream() */
1100                 wcscpy(dat.cStreamName, L"::$DATA");
1101                 dat.StreamSize.QuadPart = file_size;
1102                 ret = win32_capture_stream(path,
1103                                            path_num_chars,
1104                                            inode, lookup_table,
1105                                            &dat);
1106         }
1107         return ret;
1108 }
1109
1110 static int
1111 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
1112                                   wchar_t *path,
1113                                   size_t path_num_chars,
1114                                   struct add_image_params *params,
1115                                   struct win32_capture_state *state,
1116                                   unsigned vol_flags)
1117 {
1118         struct wim_dentry *root = NULL;
1119         struct wim_inode *inode;
1120         DWORD err;
1121         u64 file_size;
1122         int ret = 0;
1123         const wchar_t *basename;
1124
1125         if (exclude_path(path, path_num_chars, params->config, true)) {
1126                 if (params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT) {
1127                         ERROR("Cannot exclude the root directory from capture");
1128                         ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
1129                         goto out;
1130                 }
1131                 if ((params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_EXCLUDE_VERBOSE)
1132                     && params->progress_func)
1133                 {
1134                         union wimlib_progress_info info;
1135                         info.scan.cur_path = path;
1136                         info.scan.excluded = true;
1137                         params->progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
1138                 }
1139                 goto out;
1140         }
1141
1142         if ((params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
1143             && params->progress_func)
1144         {
1145                 union wimlib_progress_info info;
1146                 info.scan.cur_path = path;
1147                 info.scan.excluded = false;
1148                 params->progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
1149         }
1150
1151         HANDLE hFile = win32_open_existing_file(path,
1152                                                 FILE_READ_DATA | FILE_READ_ATTRIBUTES);
1153         if (hFile == INVALID_HANDLE_VALUE) {
1154                 err = GetLastError();
1155                 ERROR("Win32 API: Failed to open \"%ls\"", path);
1156                 win32_error(err);
1157                 ret = WIMLIB_ERR_OPEN;
1158                 goto out;
1159         }
1160
1161         BY_HANDLE_FILE_INFORMATION file_info;
1162         if (!GetFileInformationByHandle(hFile, &file_info)) {
1163                 err = GetLastError();
1164                 ERROR("Win32 API: Failed to get file information for \"%ls\"",
1165                       path);
1166                 win32_error(err);
1167                 ret = WIMLIB_ERR_STAT;
1168                 goto out_close_handle;
1169         }
1170
1171         /* Create a WIM dentry with an associated inode, which may be shared.
1172          *
1173          * However, we need to explicitly check for directories and files with
1174          * only 1 link and refuse to hard link them.  This is because Windows
1175          * has a bug where it can return duplicate File IDs for files and
1176          * directories on the FAT filesystem. */
1177         basename = path_basename_with_len(path, path_num_chars);
1178         if (!(file_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
1179             && file_info.nNumberOfLinks > 1)
1180         {
1181                 ret = inode_table_new_dentry(params->inode_table,
1182                                              basename,
1183                                              ((u64)file_info.nFileIndexHigh << 32) |
1184                                                  (u64)file_info.nFileIndexLow,
1185                                              file_info.dwVolumeSerialNumber,
1186                                              &root);
1187                 if (ret)
1188                         goto out_close_handle;
1189         } else {
1190                 ret = new_dentry_with_inode(basename, &root);
1191                 if (ret)
1192                         goto out_close_handle;
1193                 list_add_tail(&root->d_inode->i_list, &params->inode_table->extra_inodes);
1194         }
1195
1196
1197         ret = win32_get_short_name(root, path);
1198         if (ret)
1199                 goto out_close_handle;
1200
1201         inode = root->d_inode;
1202
1203         if (inode->i_nlink > 1) /* Shared inode; nothing more to do */
1204                 goto out_close_handle;
1205
1206         inode->i_attributes = file_info.dwFileAttributes;
1207         inode->i_creation_time = FILETIME_to_u64(&file_info.ftCreationTime);
1208         inode->i_last_write_time = FILETIME_to_u64(&file_info.ftLastWriteTime);
1209         inode->i_last_access_time = FILETIME_to_u64(&file_info.ftLastAccessTime);
1210         inode->i_resolved = 1;
1211
1212         params->add_image_flags &= ~(WIMLIB_ADD_IMAGE_FLAG_ROOT | WIMLIB_ADD_IMAGE_FLAG_SOURCE);
1213
1214         if (!(params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NO_ACLS)
1215             && (vol_flags & FILE_PERSISTENT_ACLS))
1216         {
1217                 ret = win32_get_security_descriptor(root, params->sd_set,
1218                                                     path, state,
1219                                                     params->add_image_flags);
1220                 if (ret)
1221                         goto out_close_handle;
1222         }
1223
1224         file_size = ((u64)file_info.nFileSizeHigh << 32) |
1225                      (u64)file_info.nFileSizeLow;
1226
1227         if (inode_is_directory(inode)) {
1228                 /* Directory (not a reparse point) --- recurse to children */
1229
1230                 /* But first... directories may have alternate data streams that
1231                  * need to be captured. */
1232                 ret = win32_capture_streams(path,
1233                                             path_num_chars,
1234                                             inode,
1235                                             params->lookup_table,
1236                                             file_size,
1237                                             vol_flags);
1238                 if (ret)
1239                         goto out_close_handle;
1240                 ret = win32_recurse_directory(root,
1241                                               path,
1242                                               path_num_chars,
1243                                               params,
1244                                               state,
1245                                               vol_flags);
1246         } else if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1247                 /* Reparse point: save the reparse tag and data.  Alternate data
1248                  * streams are not captured, if it's even possible for a reparse
1249                  * point to have alternate data streams... */
1250                 ret = win32_capture_reparse_point(&root, hFile, inode, path, params);
1251         } else {
1252                 /* Not a directory, not a reparse point; capture the default
1253                  * file contents and any alternate data streams. */
1254                 ret = win32_capture_streams(path,
1255                                             path_num_chars,
1256                                             inode,
1257                                             params->lookup_table,
1258                                             file_size,
1259                                             vol_flags);
1260         }
1261 out_close_handle:
1262         CloseHandle(hFile);
1263 out:
1264         if (ret == 0)
1265                 *root_ret = root;
1266         else
1267                 free_dentry_tree(root, params->lookup_table);
1268         return ret;
1269 }
1270
1271 static void
1272 win32_do_capture_warnings(const struct win32_capture_state *state,
1273                           int add_image_flags)
1274 {
1275         if (state->num_get_sacl_priv_notheld == 0 &&
1276             state->num_get_sd_access_denied == 0)
1277                 return;
1278
1279         WARNING("");
1280         WARNING("Built dentry tree successfully, but with the following problem(s):");
1281         if (state->num_get_sacl_priv_notheld != 0) {
1282                 WARNING("Could not capture SACL (System Access Control List)\n"
1283                         "          on %lu files or directories.",
1284                         state->num_get_sacl_priv_notheld);
1285         }
1286         if (state->num_get_sd_access_denied != 0) {
1287                 WARNING("Could not capture security descriptor at all\n"
1288                         "          on %lu files or directories.",
1289                         state->num_get_sd_access_denied);
1290         }
1291         WARNING(
1292           "Try running the program as the Administrator to make sure all the\n"
1293 "          desired metadata has been captured exactly.  However, if you\n"
1294 "          do not care about capturing security descriptors correctly, then\n"
1295 "          nothing more needs to be done%ls\n",
1296         (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NO_ACLS) ? L"." :
1297          L", although you might consider\n"
1298 "          passing the --no-acls flag to `wimlib-imagex capture' or\n"
1299 "          `wimlib-imagex append' to explicitly capture no security\n"
1300 "          descriptors.\n");
1301 }
1302
1303 /* Win32 version of capturing a directory tree */
1304 int
1305 win32_build_dentry_tree(struct wim_dentry **root_ret,
1306                         const wchar_t *root_disk_path,
1307                         struct add_image_params *params)
1308 {
1309         size_t path_nchars;
1310         wchar_t *path;
1311         int ret;
1312         struct win32_capture_state state;
1313         unsigned vol_flags;
1314
1315
1316         path_nchars = wcslen(root_disk_path);
1317         if (path_nchars > 32767)
1318                 return WIMLIB_ERR_INVALID_PARAM;
1319
1320         ret = win32_get_file_and_vol_ids(root_disk_path,
1321                                          &params->capture_root_ino,
1322                                          &params->capture_root_dev);
1323         if (ret)
1324                 return ret;
1325
1326         win32_get_vol_flags(root_disk_path, &vol_flags);
1327
1328         /* There is no check for overflow later when this buffer is being used!
1329          * But the max path length on NTFS is 32767 characters, and paths need
1330          * to be written specially to even go past 260 characters, so we should
1331          * be okay with 32770 characters. */
1332         path = MALLOC(32770 * sizeof(wchar_t));
1333         if (!path)
1334                 return WIMLIB_ERR_NOMEM;
1335
1336         wmemcpy(path, root_disk_path, path_nchars + 1);
1337
1338         memset(&state, 0, sizeof(state));
1339         ret = win32_build_dentry_tree_recursive(root_ret, path,
1340                                                 path_nchars, params,
1341                                                 &state, vol_flags);
1342         FREE(path);
1343         if (ret == 0)
1344                 win32_do_capture_warnings(&state, params->add_image_flags);
1345         return ret;
1346 }
1347
1348 static int
1349 win32_set_reparse_data(HANDLE h,
1350                        u32 reparse_tag,
1351                        const struct wim_lookup_table_entry *lte,
1352                        const wchar_t *path)
1353 {
1354         int ret;
1355         u8 *buf;
1356         size_t len;
1357
1358         if (!lte) {
1359                 WARNING("\"%ls\" is marked as a reparse point but had no reparse data",
1360                         path);
1361                 return 0;
1362         }
1363         len = wim_resource_size(lte);
1364         if (len > 16 * 1024 - 8) {
1365                 WARNING("\"%ls\": reparse data too long!", path);
1366                 return 0;
1367         }
1368
1369         /* The WIM stream omits the ReparseTag and ReparseDataLength fields, so
1370          * leave 8 bytes of space for them at the beginning of the buffer, then
1371          * set them manually. */
1372         buf = alloca(len + 8);
1373         ret = read_full_resource_into_buf(lte, buf + 8, false);
1374         if (ret)
1375                 return ret;
1376         *(u32*)(buf + 0) = cpu_to_le32(reparse_tag);
1377         *(u16*)(buf + 4) = cpu_to_le16(len);
1378         *(u16*)(buf + 6) = 0;
1379
1380         /* Set the reparse data on the open file using the
1381          * FSCTL_SET_REPARSE_POINT ioctl.
1382          *
1383          * There are contradictions in Microsoft's documentation for this:
1384          *
1385          * "If hDevice was opened without specifying FILE_FLAG_OVERLAPPED,
1386          * lpOverlapped is ignored."
1387          *
1388          * --- So setting lpOverlapped to NULL is okay since it's ignored.
1389          *
1390          * "If lpOverlapped is NULL, lpBytesReturned cannot be NULL. Even when an
1391          * operation returns no output data and lpOutBuffer is NULL,
1392          * DeviceIoControl makes use of lpBytesReturned. After such an
1393          * operation, the value of lpBytesReturned is meaningless."
1394          *
1395          * --- So lpOverlapped not really ignored, as it affects another
1396          *  parameter.  This is the actual behavior: lpBytesReturned must be
1397          *  specified, even though lpBytesReturned is documented as:
1398          *
1399          *  "Not used with this operation; set to NULL."
1400          */
1401         DWORD bytesReturned;
1402         if (!DeviceIoControl(h, FSCTL_SET_REPARSE_POINT, buf, len + 8,
1403                              NULL, 0,
1404                              &bytesReturned /* lpBytesReturned */,
1405                              NULL /* lpOverlapped */))
1406         {
1407                 DWORD err = GetLastError();
1408                 ERROR("Failed to set reparse data on \"%ls\"", path);
1409                 win32_error(err);
1410                 return WIMLIB_ERR_WRITE;
1411         }
1412         return 0;
1413 }
1414
1415 static int
1416 win32_set_compressed(HANDLE hFile, const wchar_t *path)
1417 {
1418         USHORT format = COMPRESSION_FORMAT_DEFAULT;
1419         DWORD bytesReturned = 0;
1420         if (!DeviceIoControl(hFile, FSCTL_SET_COMPRESSION,
1421                              &format, sizeof(USHORT),
1422                              NULL, 0,
1423                              &bytesReturned, NULL))
1424         {
1425                 /* Could be a warning only, but we only call this if the volume
1426                  * supports compression.  So I'm calling this an error. */
1427                 DWORD err = GetLastError();
1428                 ERROR("Failed to set compression flag on \"%ls\"", path);
1429                 win32_error(err);
1430                 return WIMLIB_ERR_WRITE;
1431         }
1432         return 0;
1433 }
1434
1435 static int
1436 win32_set_sparse(HANDLE hFile, const wchar_t *path)
1437 {
1438         DWORD bytesReturned = 0;
1439         if (!DeviceIoControl(hFile, FSCTL_SET_SPARSE,
1440                              NULL, 0,
1441                              NULL, 0,
1442                              &bytesReturned, NULL))
1443         {
1444                 /* Could be a warning only, but we only call this if the volume
1445                  * supports sparse files.  So I'm calling this an error. */
1446                 DWORD err = GetLastError();
1447                 WARNING("Failed to set sparse flag on \"%ls\"", path);
1448                 win32_error(err);
1449                 return WIMLIB_ERR_WRITE;
1450         }
1451         return 0;
1452 }
1453
1454 /*
1455  * Sets the security descriptor on an extracted file.
1456  */
1457 static int
1458 win32_set_security_data(const struct wim_inode *inode,
1459                         const wchar_t *path,
1460                         struct apply_args *args)
1461 {
1462         PSECURITY_DESCRIPTOR descriptor;
1463         unsigned long n;
1464         DWORD err;
1465
1466         descriptor = wim_const_security_data(args->w)->descriptors[inode->i_security_id];
1467
1468         SECURITY_INFORMATION securityInformation = DACL_SECURITY_INFORMATION |
1469                                                    SACL_SECURITY_INFORMATION |
1470                                                    OWNER_SECURITY_INFORMATION |
1471                                                    GROUP_SECURITY_INFORMATION;
1472 again:
1473         if (SetFileSecurityW(path, securityInformation, descriptor))
1474                 return 0;
1475         err = GetLastError();
1476         if (args->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS)
1477                 goto fail;
1478         switch (err) {
1479         case ERROR_PRIVILEGE_NOT_HELD:
1480                 if (securityInformation & SACL_SECURITY_INFORMATION) {
1481                         n = args->num_set_sacl_priv_notheld++;
1482                         securityInformation &= ~SACL_SECURITY_INFORMATION;
1483                         if (n < MAX_SET_SACL_PRIV_NOTHELD_WARNINGS) {
1484                                 WARNING(
1485 "We don't have enough privileges to set the full security\n"
1486 "          descriptor on \"%ls\"!\n", path);
1487                                 if (args->num_set_sd_access_denied +
1488                                     args->num_set_sacl_priv_notheld == 1)
1489                                 {
1490                                         WARNING("%ls", apply_access_denied_msg);
1491                                 }
1492                                 WARNING("Re-trying with SACL omitted.\n", path);
1493                         } else if (n == MAX_GET_SACL_PRIV_NOTHELD_WARNINGS) {
1494                                 WARNING(
1495 "Suppressing further 'privileges not held' error messages when setting\n"
1496 "          security descriptors.");
1497                         }
1498                         goto again;
1499                 }
1500                 /* Fall through */
1501         case ERROR_INVALID_OWNER:
1502         case ERROR_ACCESS_DENIED:
1503                 n = args->num_set_sd_access_denied++;
1504                 if (n < MAX_SET_SD_ACCESS_DENIED_WARNINGS) {
1505                         WARNING("Failed to set security descriptor on \"%ls\": "
1506                                 "Access denied!\n", path);
1507                         if (args->num_set_sd_access_denied +
1508                             args->num_set_sacl_priv_notheld == 1)
1509                         {
1510                                 WARNING("%ls", apply_access_denied_msg);
1511                         }
1512                 } else if (n == MAX_SET_SD_ACCESS_DENIED_WARNINGS) {
1513                         WARNING(
1514 "Suppressing further access denied error messages when setting\n"
1515 "          security descriptors");
1516                 }
1517                 return 0;
1518         default:
1519 fail:
1520                 ERROR("Failed to set security descriptor on \"%ls\"", path);
1521                 win32_error(err);
1522                 return WIMLIB_ERR_WRITE;
1523         }
1524 }
1525
1526
1527 static int
1528 win32_extract_chunk(const void *buf, size_t len, void *arg)
1529 {
1530         HANDLE hStream = arg;
1531
1532         DWORD nbytes_written;
1533         wimlib_assert(len <= 0xffffffff);
1534
1535         if (!WriteFile(hStream, buf, len, &nbytes_written, NULL) ||
1536             nbytes_written != len)
1537         {
1538                 DWORD err = GetLastError();
1539                 ERROR("WriteFile(): write error");
1540                 win32_error(err);
1541                 return WIMLIB_ERR_WRITE;
1542         }
1543         return 0;
1544 }
1545
1546 static int
1547 do_win32_extract_stream(HANDLE hStream, struct wim_lookup_table_entry *lte)
1548 {
1549         return extract_wim_resource(lte, wim_resource_size(lte),
1550                                     win32_extract_chunk, hStream);
1551 }
1552
1553 static int
1554 do_win32_extract_encrypted_stream(const wchar_t *path,
1555                                   const struct wim_lookup_table_entry *lte)
1556 {
1557         ERROR("Extracting encryted streams not implemented");
1558         return WIMLIB_ERR_INVALID_PARAM;
1559 }
1560
1561 static bool
1562 path_is_root_of_drive(const wchar_t *path)
1563 {
1564         if (!*path)
1565                 return false;
1566
1567         if (*path != L'/' && *path != L'\\') {
1568                 if (*(path + 1) == L':')
1569                         path += 2;
1570                 else
1571                         return false;
1572         }
1573         while (*path == L'/' || *path == L'\\')
1574                 path++;
1575         return (*path == L'\0');
1576 }
1577
1578 static DWORD
1579 win32_get_create_flags_and_attributes(DWORD i_attributes)
1580 {
1581         DWORD attributes;
1582
1583         /*
1584          * Some attributes cannot be set by passing them to CreateFile().  In
1585          * particular:
1586          *
1587          * FILE_ATTRIBUTE_DIRECTORY:
1588          *   CreateDirectory() must be called instead of CreateFile().
1589          *
1590          * FILE_ATTRIBUTE_SPARSE_FILE:
1591          *   Needs an ioctl.
1592          *   See: win32_set_sparse().
1593          *
1594          * FILE_ATTRIBUTE_COMPRESSED:
1595          *   Not clear from the documentation, but apparently this needs an
1596          *   ioctl as well.
1597          *   See: win32_set_compressed().
1598          *
1599          * FILE_ATTRIBUTE_REPARSE_POINT:
1600          *   Needs an ioctl, with the reparse data specified.
1601          *   See: win32_set_reparse_data().
1602          *
1603          * In addition, clear any file flags in the attributes that we don't
1604          * want, but also specify FILE_FLAG_OPEN_REPARSE_POINT and
1605          * FILE_FLAG_BACKUP_SEMANTICS as we are a backup application.
1606          */
1607         attributes = i_attributes & ~(FILE_ATTRIBUTE_SPARSE_FILE |
1608                                       FILE_ATTRIBUTE_COMPRESSED |
1609                                       FILE_ATTRIBUTE_REPARSE_POINT |
1610                                       FILE_ATTRIBUTE_DIRECTORY |
1611                                       FILE_FLAG_DELETE_ON_CLOSE |
1612                                       FILE_FLAG_NO_BUFFERING |
1613                                       FILE_FLAG_OPEN_NO_RECALL |
1614                                       FILE_FLAG_OVERLAPPED |
1615                                       FILE_FLAG_RANDOM_ACCESS |
1616                                       /*FILE_FLAG_SESSION_AWARE |*/
1617                                       FILE_FLAG_SEQUENTIAL_SCAN |
1618                                       FILE_FLAG_WRITE_THROUGH);
1619         return attributes |
1620                FILE_FLAG_OPEN_REPARSE_POINT |
1621                FILE_FLAG_BACKUP_SEMANTICS;
1622 }
1623
1624 static bool
1625 inode_has_special_attributes(const struct wim_inode *inode)
1626 {
1627         return (inode->i_attributes & (FILE_ATTRIBUTE_COMPRESSED |
1628                                        FILE_ATTRIBUTE_REPARSE_POINT |
1629                                        FILE_ATTRIBUTE_SPARSE_FILE)) != 0;
1630 }
1631
1632 /* Set compression or sparse attributes, and reparse data, if supported by the
1633  * volume. */
1634 static int
1635 win32_set_special_attributes(HANDLE hFile, const struct wim_inode *inode,
1636                              struct wim_lookup_table_entry *unnamed_stream_lte,
1637                              const wchar_t *path, unsigned vol_flags)
1638 {
1639         int ret;
1640
1641         if (inode->i_attributes & FILE_ATTRIBUTE_COMPRESSED) {
1642                 if (vol_flags & FILE_FILE_COMPRESSION) {
1643                         DEBUG("Setting compression flag on \"%ls\"", path);
1644                         ret = win32_set_compressed(hFile, path);
1645                         if (ret)
1646                                 return ret;
1647                 } else {
1648                         DEBUG("Cannot set compression attribute on \"%ls\": "
1649                               "volume does not support transparent compression",
1650                               path);
1651                 }
1652         }
1653
1654         if (inode->i_attributes & FILE_ATTRIBUTE_SPARSE_FILE) {
1655                 if (vol_flags & FILE_SUPPORTS_SPARSE_FILES) {
1656                         DEBUG("Setting sparse flag on \"%ls\"", path);
1657                         ret = win32_set_sparse(hFile, path);
1658                         if (ret)
1659                                 return ret;
1660                 } else {
1661                         DEBUG("Cannot set sparse attribute on \"%ls\": "
1662                               "volume does not support sparse files",
1663                               path);
1664                 }
1665         }
1666
1667         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1668                 if (vol_flags & FILE_SUPPORTS_REPARSE_POINTS) {
1669                         DEBUG("Setting reparse data on \"%ls\"", path);
1670                         ret = win32_set_reparse_data(hFile, inode->i_reparse_tag,
1671                                                      unnamed_stream_lte, path);
1672                         if (ret)
1673                                 return ret;
1674                 } else {
1675                         DEBUG("Cannot set reparse data on \"%ls\": volume "
1676                               "does not support reparse points", path);
1677                 }
1678         }
1679
1680         return 0;
1681 }
1682
1683 static int
1684 win32_extract_stream(const struct wim_inode *inode,
1685                      const wchar_t *path,
1686                      const wchar_t *stream_name_utf16,
1687                      struct wim_lookup_table_entry *lte,
1688                      unsigned vol_flags)
1689 {
1690         wchar_t *stream_path;
1691         HANDLE h;
1692         int ret;
1693         DWORD err;
1694         DWORD creationDisposition = CREATE_ALWAYS;
1695
1696         if (stream_name_utf16) {
1697                 /* Named stream.  Create a buffer that contains the UTF-16LE
1698                  * string [.\]@path:@stream_name_utf16.  This is needed to
1699                  * create and open the stream using CreateFileW().  I'm not
1700                  * aware of any other APIs to do this.  Note: the '$DATA' suffix
1701                  * seems to be unneeded.  Additional note: a "./" prefix needs
1702                  * to be added when the path is not absolute to avoid ambiguity
1703                  * with drive letters. */
1704                 size_t stream_path_nchars;
1705                 size_t path_nchars;
1706                 size_t stream_name_nchars;
1707                 const wchar_t *prefix;
1708
1709                 path_nchars = wcslen(path);
1710                 stream_name_nchars = wcslen(stream_name_utf16);
1711                 stream_path_nchars = path_nchars + 1 + stream_name_nchars;
1712                 if (path[0] != cpu_to_le16(L'\0') &&
1713                     path[0] != cpu_to_le16(L'/') &&
1714                     path[0] != cpu_to_le16(L'\\') &&
1715                     path[1] != cpu_to_le16(L':'))
1716                 {
1717                         prefix = L"./";
1718                         stream_path_nchars += 2;
1719                 } else {
1720                         prefix = L"";
1721                 }
1722                 stream_path = alloca((stream_path_nchars + 1) * sizeof(wchar_t));
1723                 swprintf(stream_path, L"%ls%ls:%ls",
1724                          prefix, path, stream_name_utf16);
1725         } else {
1726                 /* Unnamed stream; its path is just the path to the file itself.
1727                  * */
1728                 stream_path = (wchar_t*)path;
1729
1730                 /* Directories must be created with CreateDirectoryW().  Then
1731                  * the call to CreateFileW() will merely open the directory that
1732                  * was already created rather than creating a new file. */
1733                 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1734                         if (!CreateDirectoryW(stream_path, NULL)) {
1735                                 err = GetLastError();
1736                                 switch (err) {
1737                                 case ERROR_ALREADY_EXISTS:
1738                                         break;
1739                                 case ERROR_ACCESS_DENIED:
1740                                         if (path_is_root_of_drive(path))
1741                                                 break;
1742                                         /* Fall through */
1743                                 default:
1744                                         ERROR("Failed to create directory \"%ls\"",
1745                                               stream_path);
1746                                         win32_error(err);
1747                                         ret = WIMLIB_ERR_MKDIR;
1748                                         goto fail;
1749                                 }
1750                         }
1751                         DEBUG("Created directory \"%ls\"", stream_path);
1752                         if (!inode_has_special_attributes(inode)) {
1753                                 ret = 0;
1754                                 goto out;
1755                         }
1756                         DEBUG("Directory \"%ls\" has special attributes!",
1757                               stream_path);
1758                         creationDisposition = OPEN_EXISTING;
1759                 }
1760         }
1761
1762         DEBUG("Opening \"%ls\"", stream_path);
1763         h = CreateFileW(stream_path,
1764                         GENERIC_READ | GENERIC_WRITE,
1765                         0,
1766                         NULL,
1767                         creationDisposition,
1768                         win32_get_create_flags_and_attributes(inode->i_attributes),
1769                         NULL);
1770         if (h == INVALID_HANDLE_VALUE) {
1771                 err = GetLastError();
1772                 ERROR("Failed to create \"%ls\"", stream_path);
1773                 win32_error(err);
1774                 ret = WIMLIB_ERR_OPEN;
1775                 goto fail;
1776         }
1777
1778         if (stream_name_utf16 == NULL && inode_has_special_attributes(inode)) {
1779                 ret = win32_set_special_attributes(h, inode, lte, path,
1780                                                    vol_flags);
1781                 if (ret)
1782                         goto fail_close_handle;
1783         }
1784
1785         if (!(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
1786                 if (lte) {
1787                         DEBUG("Extracting \"%ls\" (len = %"PRIu64")",
1788                               stream_path, wim_resource_size(lte));
1789                         if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED
1790                             && stream_name_utf16 == NULL
1791                             && (vol_flags & FILE_SUPPORTS_ENCRYPTION))
1792                         {
1793                                 ret = do_win32_extract_encrypted_stream(stream_path,
1794                                                                         lte);
1795                         } else {
1796                                 ret = do_win32_extract_stream(h, lte);
1797                         }
1798                         if (ret)
1799                                 goto fail_close_handle;
1800                 }
1801         }
1802
1803         DEBUG("Closing \"%ls\"", stream_path);
1804         if (!CloseHandle(h)) {
1805                 err = GetLastError();
1806                 ERROR("Failed to close \"%ls\"", stream_path);
1807                 win32_error(err);
1808                 ret = WIMLIB_ERR_WRITE;
1809                 goto fail;
1810         }
1811         ret = 0;
1812         goto out;
1813 fail_close_handle:
1814         CloseHandle(h);
1815 fail:
1816         ERROR("Error extracting %ls", stream_path);
1817 out:
1818         return ret;
1819 }
1820
1821 /*
1822  * Creates a file, directory, or reparse point and extracts all streams to it
1823  * (unnamed data stream and/or reparse point stream, plus any alternate data
1824  * streams).  This in Win32-specific code.
1825  *
1826  * @inode:      WIM inode for this file or directory.
1827  * @path:       UTF-16LE external path to extract the inode to.
1828  *
1829  * Returns 0 on success; nonzero on failure.
1830  */
1831 static int
1832 win32_extract_streams(const struct wim_inode *inode,
1833                       const wchar_t *path, u64 *completed_bytes_p,
1834                       unsigned vol_flags)
1835 {
1836         struct wim_lookup_table_entry *unnamed_lte;
1837         int ret;
1838
1839         unnamed_lte = inode_unnamed_lte_resolved(inode);
1840         ret = win32_extract_stream(inode, path, NULL, unnamed_lte,
1841                                    vol_flags);
1842         if (ret)
1843                 goto out;
1844         if (unnamed_lte && inode->i_extracted_file == NULL)
1845                 *completed_bytes_p += wim_resource_size(unnamed_lte);
1846
1847         if (!(vol_flags & FILE_NAMED_STREAMS))
1848                 goto out;
1849         for (u16 i = 0; i < inode->i_num_ads; i++) {
1850                 const struct wim_ads_entry *ads_entry = &inode->i_ads_entries[i];
1851                 if (ads_entry->stream_name_nbytes != 0) {
1852                         /* Skip special UNIX data entries (see documentation for
1853                          * WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA) */
1854                         if (ads_entry->stream_name_nbytes == WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES
1855                             && !memcmp(ads_entry->stream_name,
1856                                        WIMLIB_UNIX_DATA_TAG_UTF16LE,
1857                                        WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES))
1858                                 continue;
1859                         ret = win32_extract_stream(inode,
1860                                                    path,
1861                                                    ads_entry->stream_name,
1862                                                    ads_entry->lte,
1863                                                    vol_flags);
1864                         if (ret)
1865                                 break;
1866                         if (ads_entry->lte && inode->i_extracted_file == NULL)
1867                                 *completed_bytes_p += wim_resource_size(ads_entry->lte);
1868                 }
1869         }
1870 out:
1871         return ret;
1872 }
1873
1874 /* Extract a file, directory, reparse point, or hard link to an
1875  * already-extracted file using the Win32 API */
1876 int
1877 win32_do_apply_dentry(const wchar_t *output_path,
1878                       size_t output_path_num_chars,
1879                       struct wim_dentry *dentry,
1880                       struct apply_args *args)
1881 {
1882         int ret;
1883         struct wim_inode *inode = dentry->d_inode;
1884         DWORD err;
1885
1886         if (!args->have_vol_flags) {
1887                 win32_get_vol_flags(output_path, &args->vol_flags);
1888                 args->have_vol_flags = true;
1889                 /* Warn the user about data that may not be extracted. */
1890                 if (!(args->vol_flags & FILE_SUPPORTS_SPARSE_FILES))
1891                         WARNING("Volume does not support sparse files!\n"
1892                                 "          Sparse files will be extracted as non-sparse.");
1893                 if (!(args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS))
1894                         WARNING("Volume does not support reparse points!\n"
1895                                 "          Reparse point data will not be extracted.");
1896                 if (!(args->vol_flags & FILE_NAMED_STREAMS)) {
1897                         WARNING("Volume does not support named data streams!\n"
1898                                 "          Named data streams will not be extracted.");
1899                 }
1900                 if (!(args->vol_flags & FILE_SUPPORTS_ENCRYPTION)) {
1901                         WARNING("Volume does not support encryption!\n"
1902                                 "          Encrypted files will be extracted as raw data.");
1903                 }
1904                 if (!(args->vol_flags & FILE_FILE_COMPRESSION)) {
1905                         WARNING("Volume does not support transparent compression!\n"
1906                                 "          Compressed files will be extracted as non-compressed.");
1907                 }
1908                 if (!(args->vol_flags & FILE_PERSISTENT_ACLS)) {
1909                         if (args->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS) {
1910                                 ERROR("Strict ACLs requested, but the volume does not "
1911                                       "support ACLs!");
1912                                 return WIMLIB_ERR_VOLUME_LACKS_FEATURES;
1913                         } else {
1914                                 WARNING("Volume does not support persistent ACLS!\n"
1915                                         "          File permissions will not be extracted.");
1916                         }
1917                 }
1918         }
1919
1920         if (inode->i_nlink > 1 && inode->i_extracted_file != NULL) {
1921                 /* Linked file, with another name already extracted.  Create a
1922                  * hard link. */
1923
1924                 /* There is a volume flag for this (FILE_SUPPORTS_HARD_LINKS),
1925                  * but it's only available on Windows 7 and later.  So no use
1926                  * even checking it, really.  Instead, CreateHardLinkW() will
1927                  * apparently return ERROR_INVALID_FUNCTION if the volume does
1928                  * not support hard links. */
1929                 DEBUG("Creating hard link \"%ls => %ls\"",
1930                       output_path, inode->i_extracted_file);
1931                 if (CreateHardLinkW(output_path, inode->i_extracted_file, NULL))
1932                         return 0;
1933
1934                 err = GetLastError();
1935                 if (err != ERROR_INVALID_FUNCTION) {
1936                         ERROR("Can't create hard link \"%ls => %ls\"",
1937                               output_path, inode->i_extracted_file);
1938                         win32_error(err);
1939                         return WIMLIB_ERR_LINK;
1940                 } else {
1941                         args->num_hard_links_failed++;
1942                         if (args->num_hard_links_failed < MAX_CREATE_HARD_LINK_WARNINGS) {
1943                                 WARNING("Can't create hard link \"%ls => %ls\":\n"
1944                                         "          Volume does not support hard links!\n"
1945                                         "          Falling back to extracting a copy of the file.",
1946                                         output_path, inode->i_extracted_file);
1947                         } else if (args->num_hard_links_failed == MAX_CREATE_HARD_LINK_WARNINGS) {
1948                                 WARNING("Suppressing further hard linking warnings...");
1949                         }
1950                 }
1951         }
1952
1953         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT &&
1954             !(args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS))
1955         {
1956                 WARNING("Skipping extraction of reparse point \"%ls\":\n"
1957                         "          Not supported by destination filesystem",
1958                         output_path);
1959                 struct wim_lookup_table_entry *lte;
1960                 lte = inode_unnamed_lte_resolved(inode);
1961                 if (lte)
1962                         args->progress.extract.completed_bytes += wim_resource_size(lte);
1963                 return 0;
1964         }
1965
1966         /* Create the file, directory, or reparse point, and extract the
1967          * data streams. */
1968         ret = win32_extract_streams(inode, output_path,
1969                                     &args->progress.extract.completed_bytes,
1970                                     args->vol_flags);
1971         if (ret)
1972                 return ret;
1973
1974         if (inode->i_security_id >= 0 &&
1975             !(args->extract_flags & WIMLIB_EXTRACT_FLAG_NO_ACLS)
1976             && (args->vol_flags & FILE_PERSISTENT_ACLS))
1977         {
1978                 ret = win32_set_security_data(inode, output_path, args);
1979                 if (ret)
1980                         return ret;
1981         }
1982         if (inode->i_nlink > 1) {
1983                 /* Save extracted path for a later call to
1984                  * CreateHardLinkW() if this inode has multiple links.
1985                  * */
1986                 inode->i_extracted_file = WSTRDUP(output_path);
1987                 if (!inode->i_extracted_file)
1988                         ret = WIMLIB_ERR_NOMEM;
1989         }
1990         return 0;
1991 }
1992
1993 /* Set timestamps on an extracted file using the Win32 API */
1994 int
1995 win32_do_apply_dentry_timestamps(const wchar_t *path,
1996                                  size_t path_num_chars,
1997                                  const struct wim_dentry *dentry,
1998                                  const struct apply_args *args)
1999 {
2000         DWORD err;
2001         HANDLE h;
2002         const struct wim_inode *inode = dentry->d_inode;
2003
2004         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT &&
2005             !(args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS))
2006         {
2007                 /* Skip reparse points not extracted */
2008                 return 0;
2009         }
2010
2011         /* Windows doesn't let you change the timestamps of the root directory
2012          * (at least on FAT, which is dumb but expected since FAT doesn't store
2013          * any metadata about the root directory...) */
2014         if (path_is_root_of_drive(path))
2015                 return 0;
2016
2017         DEBUG("Opening \"%ls\" to set timestamps", path);
2018         h = win32_open_existing_file(path, FILE_WRITE_ATTRIBUTES);
2019         if (h == INVALID_HANDLE_VALUE) {
2020                 err = GetLastError();
2021                 goto fail;
2022         }
2023
2024         FILETIME creationTime = {.dwLowDateTime = inode->i_creation_time & 0xffffffff,
2025                                  .dwHighDateTime = inode->i_creation_time >> 32};
2026         FILETIME lastAccessTime = {.dwLowDateTime = inode->i_last_access_time & 0xffffffff,
2027                                   .dwHighDateTime = inode->i_last_access_time >> 32};
2028         FILETIME lastWriteTime = {.dwLowDateTime = inode->i_last_write_time & 0xffffffff,
2029                                   .dwHighDateTime = inode->i_last_write_time >> 32};
2030
2031         DEBUG("Calling SetFileTime() on \"%ls\"", path);
2032         if (!SetFileTime(h, &creationTime, &lastAccessTime, &lastWriteTime)) {
2033                 err = GetLastError();
2034                 CloseHandle(h);
2035                 goto fail;
2036         }
2037         DEBUG("Closing \"%ls\"", path);
2038         if (!CloseHandle(h)) {
2039                 err = GetLastError();
2040                 goto fail;
2041         }
2042         goto out;
2043 fail:
2044         /* Only warn if setting timestamps failed; still return 0. */
2045         WARNING("Can't set timestamps on \"%ls\"", path);
2046         win32_error(err);
2047 out:
2048         return 0;
2049 }
2050
2051 /* Replacement for POSIX fsync() */
2052 int
2053 fsync(int fd)
2054 {
2055         DWORD err;
2056         HANDLE h;
2057
2058         h = (HANDLE)_get_osfhandle(fd);
2059         if (h == INVALID_HANDLE_VALUE) {
2060                 err = GetLastError();
2061                 ERROR("Could not get Windows handle for file descriptor");
2062                 win32_error(err);
2063                 errno = EBADF;
2064                 return -1;
2065         }
2066         if (!FlushFileBuffers(h)) {
2067                 err = GetLastError();
2068                 ERROR("Could not flush file buffers to disk");
2069                 win32_error(err);
2070                 errno = EIO;
2071                 return -1;
2072         }
2073         return 0;
2074 }
2075
2076 /* Use the Win32 API to get the number of processors */
2077 unsigned
2078 win32_get_number_of_processors()
2079 {
2080         SYSTEM_INFO sysinfo;
2081         GetSystemInfo(&sysinfo);
2082         return sysinfo.dwNumberOfProcessors;
2083 }
2084
2085 /* Replacement for POSIX-2008 realpath().  Warning: partial functionality only
2086  * (resolved_path must be NULL).   Also I highly doubt that GetFullPathName
2087  * really does the right thing under all circumstances. */
2088 wchar_t *
2089 realpath(const wchar_t *path, wchar_t *resolved_path)
2090 {
2091         DWORD ret;
2092         wimlib_assert(resolved_path == NULL);
2093         DWORD err;
2094
2095         ret = GetFullPathNameW(path, 0, NULL, NULL);
2096         if (!ret) {
2097                 err = GetLastError();
2098                 goto fail_win32;
2099         }
2100
2101         resolved_path = TMALLOC(ret);
2102         if (!resolved_path)
2103                 goto out;
2104         ret = GetFullPathNameW(path, ret, resolved_path, NULL);
2105         if (!ret) {
2106                 err = GetLastError();
2107                 free(resolved_path);
2108                 resolved_path = NULL;
2109                 goto fail_win32;
2110         }
2111         goto out;
2112 fail_win32:
2113         win32_error(err);
2114         errno = -1;
2115 out:
2116         return resolved_path;
2117 }
2118
2119 /* rename() on Windows fails if the destination file exists.  And we need to
2120  * make it work on wide characters.  Fix it. */
2121 int
2122 win32_rename_replacement(const wchar_t *oldpath, const wchar_t *newpath)
2123 {
2124         if (MoveFileExW(oldpath, newpath, MOVEFILE_REPLACE_EXISTING)) {
2125                 return 0;
2126         } else {
2127                 /* As usual, the possible error values are not documented */
2128                 DWORD err = GetLastError();
2129                 ERROR("MoveFileEx(): Can't rename \"%ls\" to \"%ls\"",
2130                       oldpath, newpath);
2131                 win32_error(err);
2132                 errno = -1;
2133                 return -1;
2134         }
2135 }
2136
2137 /* Replacement for POSIX fnmatch() (partial functionality only) */
2138 int
2139 fnmatch(const wchar_t *pattern, const wchar_t *string, int flags)
2140 {
2141         if (PathMatchSpecW(string, pattern))
2142                 return 0;
2143         else
2144                 return FNM_NOMATCH;
2145 }
2146
2147 /* truncate() replacement */
2148 int
2149 win32_truncate_replacement(const wchar_t *path, off_t size)
2150 {
2151         DWORD err = NO_ERROR;
2152         LARGE_INTEGER liOffset;
2153
2154         HANDLE h = win32_open_existing_file(path, GENERIC_WRITE);
2155         if (h == INVALID_HANDLE_VALUE)
2156                 goto fail;
2157
2158         liOffset.QuadPart = size;
2159         if (!SetFilePointerEx(h, liOffset, NULL, FILE_BEGIN))
2160                 goto fail_close_handle;
2161
2162         if (!SetEndOfFile(h))
2163                 goto fail_close_handle;
2164         CloseHandle(h);
2165         return 0;
2166
2167 fail_close_handle:
2168         err = GetLastError();
2169         CloseHandle(h);
2170 fail:
2171         if (err == NO_ERROR)
2172                 err = GetLastError();
2173         ERROR("Can't truncate \"%ls\" to %"PRIu64" bytes", path, size);
2174         win32_error(err);
2175         errno = -1;
2176         return -1;
2177 }
2178
2179
2180 /* This really could be replaced with _wcserror_s, but this doesn't seem to
2181  * actually be available in MSVCRT.DLL on Windows XP (perhaps it's statically
2182  * linked in by Visual Studio...?). */
2183 extern int
2184 win32_strerror_r_replacement(int errnum, wchar_t *buf, size_t buflen)
2185 {
2186         static pthread_mutex_t strerror_lock = PTHREAD_MUTEX_INITIALIZER;
2187
2188         pthread_mutex_lock(&strerror_lock);
2189         mbstowcs(buf, strerror(errnum), buflen);
2190         buf[buflen - 1] = '\0';
2191         pthread_mutex_unlock(&strerror_lock);
2192         return 0;
2193 }
2194
2195 #endif /* __WIN32__ */