]> wimlib.net Git - wimlib/blob - src/win32_capture.c
Win32 capture: Query stream information with native API
[wimlib] / src / win32_capture.c
1 /*
2  * win32_capture.c - Windows-specific code for capturing files into a WIM image.
3  */
4
5 /*
6  * Copyright (C) 2013 Eric Biggers
7  *
8  * This file is part of wimlib, a library for working with WIM files.
9  *
10  * wimlib is free software; you can redistribute it and/or modify it under the
11  * terms of the GNU General Public License as published by the Free
12  * Software Foundation; either version 3 of the License, or (at your option)
13  * any later version.
14  *
15  * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
16  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
17  * A PARTICULAR PURPOSE. See the GNU General Public License for more
18  * details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with wimlib; if not, see http://www.gnu.org/licenses/.
22  */
23
24 #ifdef __WIN32__
25
26 #ifdef HAVE_CONFIG_H
27 #  include "config.h"
28 #endif
29
30 #include "wimlib/win32_common.h"
31
32 #include "wimlib/capture.h"
33 #include "wimlib/endianness.h"
34 #include "wimlib/error.h"
35 #include "wimlib/lookup_table.h"
36 #include "wimlib/paths.h"
37 #include "wimlib/reparse.h"
38
39 #ifdef WITH_NTDLL
40 #  include <winternl.h>
41 #  include <ntstatus.h>
42 #endif
43
44 #define MAX_GET_SD_ACCESS_DENIED_WARNINGS 1
45 #define MAX_GET_SACL_PRIV_NOTHELD_WARNINGS 1
46 #define MAX_CAPTURE_LONG_PATH_WARNINGS 5
47
48 struct win32_capture_state {
49         unsigned long num_get_sd_access_denied;
50         unsigned long num_get_sacl_priv_notheld;
51         unsigned long num_long_path_warnings;
52 };
53
54
55 static const wchar_t *capture_access_denied_msg =
56 L"         If you are not running this program as the administrator, you may\n"
57  "         need to do so, so that all data and metadata can be backed up.\n"
58  "         Otherwise, there may be no way to access the desired data or\n"
59  "         metadata without taking ownership of the file or directory.\n"
60  ;
61
62 int
63 read_win32_file_prefix(const struct wim_lookup_table_entry *lte,
64                        u64 size,
65                        consume_data_callback_t cb,
66                        void *ctx_or_buf,
67                        int _ignored_flags)
68 {
69         int ret = 0;
70         void *out_buf;
71         DWORD err;
72         u64 bytes_remaining;
73
74         HANDLE hFile = win32_open_file_data_only(lte->file_on_disk);
75         if (hFile == INVALID_HANDLE_VALUE) {
76                 err = GetLastError();
77                 ERROR("Failed to open \"%ls\"", lte->file_on_disk);
78                 win32_error(err);
79                 return WIMLIB_ERR_OPEN;
80         }
81
82         if (cb)
83                 out_buf = alloca(WIM_CHUNK_SIZE);
84         else
85                 out_buf = ctx_or_buf;
86
87         bytes_remaining = size;
88         while (bytes_remaining) {
89                 DWORD bytesToRead, bytesRead;
90
91                 bytesToRead = min(WIM_CHUNK_SIZE, bytes_remaining);
92                 if (!ReadFile(hFile, out_buf, bytesToRead, &bytesRead, NULL) ||
93                     bytesRead != bytesToRead)
94                 {
95                         err = GetLastError();
96                         ERROR("Failed to read data from \"%ls\"", lte->file_on_disk);
97                         win32_error(err);
98                         ret = WIMLIB_ERR_READ;
99                         break;
100                 }
101                 bytes_remaining -= bytesRead;
102                 if (cb) {
103                         ret = (*cb)(out_buf, bytesRead, ctx_or_buf);
104                         if (ret)
105                                 break;
106                 } else {
107                         out_buf += bytesRead;
108                 }
109         }
110         CloseHandle(hFile);
111         return ret;
112 }
113
114 struct win32_encrypted_read_ctx {
115         consume_data_callback_t read_prefix_cb;
116         void *read_prefix_ctx_or_buf;
117         int wimlib_err_code;
118         void *buf;
119         size_t buf_filled;
120         u64 bytes_remaining;
121 };
122
123 static DWORD WINAPI
124 win32_encrypted_export_cb(unsigned char *_data, void *_ctx, unsigned long len)
125 {
126         const void *data = _data;
127         struct win32_encrypted_read_ctx *ctx = _ctx;
128         int ret;
129
130         DEBUG("len = %lu", len);
131         if (ctx->read_prefix_cb) {
132                 /* The length of the buffer passed to the ReadEncryptedFileRaw()
133                  * export callback is undocumented, so we assume it may be of
134                  * arbitrary size. */
135                 size_t bytes_to_buffer = min(ctx->bytes_remaining - ctx->buf_filled,
136                                              len);
137                 while (bytes_to_buffer) {
138                         size_t bytes_to_copy_to_buf =
139                                 min(bytes_to_buffer, WIM_CHUNK_SIZE - ctx->buf_filled);
140
141                         memcpy(ctx->buf + ctx->buf_filled, data,
142                                bytes_to_copy_to_buf);
143                         ctx->buf_filled += bytes_to_copy_to_buf;
144                         data += bytes_to_copy_to_buf;
145                         bytes_to_buffer -= bytes_to_copy_to_buf;
146
147                         if (ctx->buf_filled == WIM_CHUNK_SIZE ||
148                             ctx->buf_filled == ctx->bytes_remaining)
149                         {
150                                 ret = (*ctx->read_prefix_cb)(ctx->buf,
151                                                              ctx->buf_filled,
152                                                              ctx->read_prefix_ctx_or_buf);
153                                 if (ret) {
154                                         ctx->wimlib_err_code = ret;
155                                         /* Shouldn't matter what error code is returned
156                                          * here, as long as it isn't ERROR_SUCCESS. */
157                                         return ERROR_READ_FAULT;
158                                 }
159                                 ctx->bytes_remaining -= ctx->buf_filled;
160                                 ctx->buf_filled = 0;
161                         }
162                 }
163         } else {
164                 size_t len_to_copy = min(len, ctx->bytes_remaining);
165                 ctx->read_prefix_ctx_or_buf = mempcpy(ctx->read_prefix_ctx_or_buf,
166                                                       data,
167                                                       len_to_copy);
168                 ctx->bytes_remaining -= len_to_copy;
169         }
170         return ERROR_SUCCESS;
171 }
172
173 int
174 read_win32_encrypted_file_prefix(const struct wim_lookup_table_entry *lte,
175                                  u64 size,
176                                  consume_data_callback_t cb,
177                                  void *ctx_or_buf,
178                                  int _ignored_flags)
179 {
180         struct win32_encrypted_read_ctx export_ctx;
181         DWORD err;
182         void *file_ctx;
183         int ret;
184
185         DEBUG("Reading %"PRIu64" bytes from encryted file \"%ls\"",
186               size, lte->file_on_disk);
187
188         export_ctx.read_prefix_cb = cb;
189         export_ctx.read_prefix_ctx_or_buf = ctx_or_buf;
190         export_ctx.wimlib_err_code = 0;
191         if (cb) {
192                 export_ctx.buf = MALLOC(WIM_CHUNK_SIZE);
193                 if (!export_ctx.buf)
194                         return WIMLIB_ERR_NOMEM;
195         } else {
196                 export_ctx.buf = NULL;
197         }
198         export_ctx.buf_filled = 0;
199         export_ctx.bytes_remaining = size;
200
201         err = OpenEncryptedFileRawW(lte->file_on_disk, 0, &file_ctx);
202         if (err != ERROR_SUCCESS) {
203                 ERROR("Failed to open encrypted file \"%ls\" for raw read",
204                       lte->file_on_disk);
205                 win32_error(err);
206                 ret = WIMLIB_ERR_OPEN;
207                 goto out_free_buf;
208         }
209         err = ReadEncryptedFileRaw(win32_encrypted_export_cb,
210                                    &export_ctx, file_ctx);
211         if (err != ERROR_SUCCESS) {
212                 ERROR("Failed to read encrypted file \"%ls\"",
213                       lte->file_on_disk);
214                 win32_error(err);
215                 ret = export_ctx.wimlib_err_code;
216                 if (ret == 0)
217                         ret = WIMLIB_ERR_READ;
218         } else if (export_ctx.bytes_remaining != 0) {
219                 ERROR("Only could read %"PRIu64" of %"PRIu64" bytes from "
220                       "encryted file \"%ls\"",
221                       size - export_ctx.bytes_remaining, size,
222                       lte->file_on_disk);
223                 ret = WIMLIB_ERR_READ;
224         } else {
225                 ret = 0;
226         }
227         CloseEncryptedFileRaw(file_ctx);
228 out_free_buf:
229         FREE(export_ctx.buf);
230         return ret;
231 }
232
233
234 static u64
235 FILETIME_to_u64(const FILETIME *ft)
236 {
237         return ((u64)ft->dwHighDateTime << 32) | (u64)ft->dwLowDateTime;
238 }
239
240 static int
241 win32_get_short_name(struct wim_dentry *dentry, const wchar_t *path)
242 {
243         WIN32_FIND_DATAW dat;
244         HANDLE hFind;
245         int ret = 0;
246
247         /* If we can't read the short filename for some reason, we just ignore
248          * the error and assume the file has no short name.  I don't think this
249          * should be an issue, since the short names are essentially obsolete
250          * anyway. */
251         hFind = FindFirstFileW(path, &dat);
252         if (hFind != INVALID_HANDLE_VALUE) {
253                 if (dat.cAlternateFileName[0] != L'\0') {
254                         DEBUG("\"%ls\": short name \"%ls\"", path, dat.cAlternateFileName);
255                         size_t short_name_nbytes = wcslen(dat.cAlternateFileName) *
256                                                    sizeof(wchar_t);
257                         size_t n = short_name_nbytes + sizeof(wchar_t);
258                         dentry->short_name = MALLOC(n);
259                         if (dentry->short_name) {
260                                 memcpy(dentry->short_name, dat.cAlternateFileName, n);
261                                 dentry->short_name_nbytes = short_name_nbytes;
262                         } else {
263                                 ret = WIMLIB_ERR_NOMEM;
264                         }
265                 }
266                 FindClose(hFind);
267         }
268         return ret;
269 }
270
271 static int
272 win32_get_security_descriptor(struct wim_dentry *dentry,
273                               struct wim_sd_set *sd_set,
274                               const wchar_t *path,
275                               struct win32_capture_state *state,
276                               int add_flags)
277 {
278         SECURITY_INFORMATION requestedInformation;
279         DWORD lenNeeded = 0;
280         BOOL status;
281         DWORD err;
282         unsigned long n;
283
284         requestedInformation = DACL_SECURITY_INFORMATION |
285                                SACL_SECURITY_INFORMATION |
286                                OWNER_SECURITY_INFORMATION |
287                                GROUP_SECURITY_INFORMATION;
288 again:
289         /* Request length of security descriptor */
290         status = GetFileSecurityW(path, requestedInformation,
291                                   NULL, 0, &lenNeeded);
292         err = GetLastError();
293         if (!status && err == ERROR_INSUFFICIENT_BUFFER) {
294                 DWORD len = lenNeeded;
295                 char buf[len];
296                 if (GetFileSecurityW(path, requestedInformation,
297                                      (PSECURITY_DESCRIPTOR)buf, len, &lenNeeded))
298                 {
299                         int security_id = sd_set_add_sd(sd_set, buf, len);
300                         if (security_id < 0)
301                                 return WIMLIB_ERR_NOMEM;
302                         else {
303                                 dentry->d_inode->i_security_id = security_id;
304                                 return 0;
305                         }
306                 } else {
307                         err = GetLastError();
308                 }
309         }
310
311         if (add_flags & WIMLIB_ADD_FLAG_STRICT_ACLS)
312                 goto fail;
313
314         switch (err) {
315         case ERROR_PRIVILEGE_NOT_HELD:
316                 if (requestedInformation & SACL_SECURITY_INFORMATION) {
317                         n = state->num_get_sacl_priv_notheld++;
318                         requestedInformation &= ~SACL_SECURITY_INFORMATION;
319                         if (n < MAX_GET_SACL_PRIV_NOTHELD_WARNINGS) {
320                                 WARNING(
321 "We don't have enough privileges to read the full security\n"
322 "          descriptor of \"%ls\"!\n"
323 "          Re-trying with SACL omitted.\n", path);
324                         } else if (n == MAX_GET_SACL_PRIV_NOTHELD_WARNINGS) {
325                                 WARNING(
326 "Suppressing further privileges not held error messages when reading\n"
327 "          security descriptors.");
328                         }
329                         goto again;
330                 }
331                 /* Fall through */
332         case ERROR_ACCESS_DENIED:
333                 n = state->num_get_sd_access_denied++;
334                 if (n < MAX_GET_SD_ACCESS_DENIED_WARNINGS) {
335                         WARNING("Failed to read security descriptor of \"%ls\": "
336                                 "Access denied!\n%ls", path, capture_access_denied_msg);
337                 } else if (n == MAX_GET_SD_ACCESS_DENIED_WARNINGS) {
338                         WARNING("Suppressing further access denied errors messages i"
339                                 "when reading security descriptors");
340                 }
341                 return 0;
342         default:
343 fail:
344                 ERROR("Failed to read security descriptor of \"%ls\"", path);
345                 win32_error(err);
346                 return WIMLIB_ERR_READ;
347         }
348 }
349
350 static int
351 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
352                                   wchar_t *path,
353                                   size_t path_num_chars,
354                                   struct add_image_params *params,
355                                   struct win32_capture_state *state,
356                                   unsigned vol_flags);
357
358 /* Reads the directory entries of directory using a Win32 API and recursively
359  * calls win32_build_dentry_tree() on them. */
360 static int
361 win32_recurse_directory(struct wim_dentry *root,
362                         wchar_t *dir_path,
363                         size_t dir_path_num_chars,
364                         struct add_image_params *params,
365                         struct win32_capture_state *state,
366                         unsigned vol_flags)
367 {
368         WIN32_FIND_DATAW dat;
369         HANDLE hFind;
370         DWORD err;
371         int ret;
372
373         DEBUG("Recurse to directory \"%ls\"", dir_path);
374
375         /* Begin reading the directory by calling FindFirstFileW.  Unlike UNIX
376          * opendir(), FindFirstFileW has file globbing built into it.  But this
377          * isn't what we actually want, so just add a dummy glob to get all
378          * entries. */
379         dir_path[dir_path_num_chars] = OS_PREFERRED_PATH_SEPARATOR;
380         dir_path[dir_path_num_chars + 1] = L'*';
381         dir_path[dir_path_num_chars + 2] = L'\0';
382         hFind = FindFirstFileW(dir_path, &dat);
383         dir_path[dir_path_num_chars] = L'\0';
384
385         if (hFind == INVALID_HANDLE_VALUE) {
386                 err = GetLastError();
387                 if (err == ERROR_FILE_NOT_FOUND) {
388                         return 0;
389                 } else {
390                         ERROR("Failed to read directory \"%ls\"", dir_path);
391                         win32_error(err);
392                         return WIMLIB_ERR_READ;
393                 }
394         }
395         ret = 0;
396         do {
397                 /* Skip . and .. entries */
398                 if (dat.cFileName[0] == L'.' &&
399                     (dat.cFileName[1] == L'\0' ||
400                      (dat.cFileName[1] == L'.' &&
401                       dat.cFileName[2] == L'\0')))
402                         continue;
403                 size_t filename_len = wcslen(dat.cFileName);
404
405                 dir_path[dir_path_num_chars] = OS_PREFERRED_PATH_SEPARATOR;
406                 wmemcpy(dir_path + dir_path_num_chars + 1,
407                         dat.cFileName,
408                         filename_len + 1);
409
410                 struct wim_dentry *child;
411                 size_t path_len = dir_path_num_chars + 1 + filename_len;
412                 ret = win32_build_dentry_tree_recursive(&child,
413                                                         dir_path,
414                                                         path_len,
415                                                         params,
416                                                         state,
417                                                         vol_flags);
418                 dir_path[dir_path_num_chars] = L'\0';
419                 if (ret)
420                         goto out_find_close;
421                 if (child)
422                         dentry_add_child(root, child);
423         } while (FindNextFileW(hFind, &dat));
424         err = GetLastError();
425         if (err != ERROR_NO_MORE_FILES) {
426                 ERROR("Failed to read directory \"%ls\"", dir_path);
427                 win32_error(err);
428                 if (ret == 0)
429                         ret = WIMLIB_ERR_READ;
430         }
431 out_find_close:
432         FindClose(hFind);
433         return ret;
434 }
435
436 /* Reparse point fixup status code */
437 enum rp_status {
438         /* Reparse point corresponded to an absolute symbolic link or junction
439          * point that pointed outside the directory tree being captured, and
440          * therefore was excluded. */
441         RP_EXCLUDED       = 0x0,
442
443         /* Reparse point was not fixed as it was either a relative symbolic
444          * link, a mount point, or something else we could not understand. */
445         RP_NOT_FIXED      = 0x1,
446
447         /* Reparse point corresponded to an absolute symbolic link or junction
448          * point that pointed inside the directory tree being captured, where
449          * the target was specified by a "full" \??\ prefixed path, and
450          * therefore was fixed to be relative to the root of the directory tree
451          * being captured. */
452         RP_FIXED_FULLPATH = 0x2,
453
454         /* Same as RP_FIXED_FULLPATH, except the absolute link target did not
455          * have the \??\ prefix.  It may have begun with a drive letter though.
456          * */
457         RP_FIXED_ABSPATH  = 0x4,
458
459         /* Either RP_FIXED_FULLPATH or RP_FIXED_ABSPATH. */
460         RP_FIXED          = RP_FIXED_FULLPATH | RP_FIXED_ABSPATH,
461 };
462
463 /* Given the "substitute name" target of a Windows reparse point, try doing a
464  * fixup where we change it to be absolute relative to the root of the directory
465  * tree being captured.
466  *
467  * Note that this is only executed when WIMLIB_ADD_FLAG_RPFIX has been
468  * set.
469  *
470  * @capture_root_ino and @capture_root_dev indicate the inode number and device
471  * of the root of the directory tree being captured.  They are meant to identify
472  * this directory (as an alternative to its actual path, which could potentially
473  * be reached via multiple destinations due to other symbolic links).  This may
474  * not work properly on FAT, which doesn't seem to supply proper inode numbers
475  * or file IDs.  However, FAT doesn't support reparse points so this function
476  * wouldn't even be called anyway.
477  */
478 static enum rp_status
479 win32_capture_maybe_rpfix_target(wchar_t *target, u16 *target_nbytes_p,
480                                  u64 capture_root_ino, u64 capture_root_dev,
481                                  u32 rptag)
482 {
483         u16 target_nchars = *target_nbytes_p / 2;
484         size_t stripped_chars;
485         wchar_t *orig_target;
486         int ret;
487
488         ret = parse_substitute_name(target, *target_nbytes_p, rptag);
489         if (ret < 0)
490                 return RP_NOT_FIXED;
491         stripped_chars = ret;
492         if (stripped_chars)
493                 stripped_chars -= 2;
494         target[target_nchars] = L'\0';
495         orig_target = target;
496         target = capture_fixup_absolute_symlink(target + stripped_chars,
497                                                 capture_root_ino, capture_root_dev);
498         if (!target)
499                 return RP_EXCLUDED;
500         target_nchars = wcslen(target);
501         wmemmove(orig_target + stripped_chars, target, target_nchars + 1);
502         *target_nbytes_p = (target_nchars + stripped_chars) * sizeof(wchar_t);
503         DEBUG("Fixed reparse point (new target: \"%ls\")", orig_target);
504         if (stripped_chars)
505                 return RP_FIXED_FULLPATH;
506         else
507                 return RP_FIXED_ABSPATH;
508 }
509
510 /* Returns: `enum rp_status' value on success; negative WIMLIB_ERR_* value on
511  * failure. */
512 static int
513 win32_capture_try_rpfix(u8 *rpbuf, u16 *rpbuflen_p,
514                         u64 capture_root_ino, u64 capture_root_dev,
515                         const wchar_t *path)
516 {
517         struct reparse_data rpdata;
518         int ret;
519         enum rp_status rp_status;
520
521         ret = parse_reparse_data(rpbuf, *rpbuflen_p, &rpdata);
522         if (ret)
523                 return -ret;
524
525         rp_status = win32_capture_maybe_rpfix_target(rpdata.substitute_name,
526                                                      &rpdata.substitute_name_nbytes,
527                                                      capture_root_ino,
528                                                      capture_root_dev,
529                                                      le32_to_cpu(*(le32*)rpbuf));
530         if (rp_status & RP_FIXED) {
531                 wimlib_assert(rpdata.substitute_name_nbytes % 2 == 0);
532                 utf16lechar substitute_name_copy[rpdata.substitute_name_nbytes / 2];
533                 wmemcpy(substitute_name_copy, rpdata.substitute_name,
534                         rpdata.substitute_name_nbytes / 2);
535                 rpdata.substitute_name = substitute_name_copy;
536                 rpdata.print_name = substitute_name_copy;
537                 rpdata.print_name_nbytes = rpdata.substitute_name_nbytes;
538                 if (rp_status == RP_FIXED_FULLPATH) {
539                         /* "full path", meaning \??\ prefixed.  We should not
540                          * include this prefix in the print name, as it is
541                          * apparently meant for the filesystem driver only. */
542                         rpdata.print_name += 4;
543                         rpdata.print_name_nbytes -= 8;
544                 }
545                 ret = make_reparse_buffer(&rpdata, rpbuf, rpbuflen_p);
546                 if (ret == 0)
547                         ret = rp_status;
548                 else
549                         ret = -ret;
550         } else {
551                 if (rp_status == RP_EXCLUDED) {
552                         size_t print_name_nchars = rpdata.print_name_nbytes / 2;
553                         wchar_t print_name0[print_name_nchars + 1];
554                         print_name0[print_name_nchars] = L'\0';
555                         wmemcpy(print_name0, rpdata.print_name, print_name_nchars);
556                         WARNING("Ignoring %ls pointing out of capture directory:\n"
557                                 "          \"%ls\" -> \"%ls\"\n"
558                                 "          (Use --norpfix to capture all symbolic links "
559                                 "and junction points as-is)",
560                                 (rpdata.rptag == WIM_IO_REPARSE_TAG_SYMLINK) ?
561                                         L"absolute symbolic link" : L"junction point",
562                                 path, print_name0);
563                 }
564                 ret = rp_status;
565         }
566         return ret;
567 }
568
569 /*
570  * Loads the reparse point data from a reparse point into memory, optionally
571  * fixing the targets of absolute symbolic links and junction points to be
572  * relative to the root of capture.
573  *
574  * @hFile:  Open handle to the reparse point.
575  * @path:   Path to the reparse point.  Used for error messages only.
576  * @params: Additional parameters, including whether to do reparse point fixups
577  *          or not.
578  * @rpbuf:  Buffer of length at least REPARSE_POINT_MAX_SIZE bytes into which
579  *          the reparse point buffer will be loaded.
580  * @rpbuflen_ret:  On success, the length of the reparse point buffer in bytes
581  *                 is written to this location.
582  *
583  * Returns:
584  *      On success, returns an `enum rp_status' value that indicates if and/or
585  *      how the reparse point fixup was done.
586  *
587  *      On failure, returns a negative value that is a negated WIMLIB_ERR_*
588  *      code.
589  */
590 static int
591 win32_get_reparse_data(HANDLE hFile, const wchar_t *path,
592                        struct add_image_params *params,
593                        u8 *rpbuf, u16 *rpbuflen_ret)
594 {
595         DWORD bytesReturned;
596         u32 reparse_tag;
597         int ret;
598         u16 rpbuflen;
599
600         DEBUG("Loading reparse data from \"%ls\"", path);
601         if (!DeviceIoControl(hFile, FSCTL_GET_REPARSE_POINT,
602                              NULL, /* "Not used with this operation; set to NULL" */
603                              0, /* "Not used with this operation; set to 0" */
604                              rpbuf, /* "A pointer to a buffer that
605                                                    receives the reparse point data */
606                              REPARSE_POINT_MAX_SIZE, /* "The size of the output
607                                                         buffer, in bytes */
608                              &bytesReturned,
609                              NULL))
610         {
611                 DWORD err = GetLastError();
612                 ERROR("Failed to get reparse data of \"%ls\"", path);
613                 win32_error(err);
614                 return -WIMLIB_ERR_READ;
615         }
616         if (bytesReturned < 8 || bytesReturned > REPARSE_POINT_MAX_SIZE) {
617                 ERROR("Reparse data on \"%ls\" is invalid", path);
618                 return -WIMLIB_ERR_INVALID_REPARSE_DATA;
619         }
620
621         rpbuflen = bytesReturned;
622         reparse_tag = le32_to_cpu(*(le32*)rpbuf);
623         if (params->add_flags & WIMLIB_ADD_FLAG_RPFIX &&
624             (reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
625              reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT))
626         {
627                 /* Try doing reparse point fixup */
628                 ret = win32_capture_try_rpfix(rpbuf,
629                                               &rpbuflen,
630                                               params->capture_root_ino,
631                                               params->capture_root_dev,
632                                               path);
633         } else {
634                 ret = RP_NOT_FIXED;
635         }
636         *rpbuflen_ret = rpbuflen;
637         return ret;
638 }
639
640 static DWORD WINAPI
641 win32_tally_encrypted_size_cb(unsigned char *_data, void *_ctx,
642                               unsigned long len)
643 {
644         *(u64*)_ctx += len;
645         return ERROR_SUCCESS;
646 }
647
648 static int
649 win32_get_encrypted_file_size(const wchar_t *path, u64 *size_ret)
650 {
651         DWORD err;
652         void *file_ctx;
653         int ret;
654
655         *size_ret = 0;
656         err = OpenEncryptedFileRawW(path, 0, &file_ctx);
657         if (err != ERROR_SUCCESS) {
658                 ERROR("Failed to open encrypted file \"%ls\" for raw read", path);
659                 win32_error(err);
660                 return WIMLIB_ERR_OPEN;
661         }
662         err = ReadEncryptedFileRaw(win32_tally_encrypted_size_cb,
663                                    size_ret, file_ctx);
664         if (err != ERROR_SUCCESS) {
665                 ERROR("Failed to read raw encrypted data from \"%ls\"", path);
666                 win32_error(err);
667                 ret = WIMLIB_ERR_READ;
668         } else {
669                 ret = 0;
670         }
671         CloseEncryptedFileRaw(file_ctx);
672         return ret;
673 }
674
675 /* Scans an unnamed or named stream of a Win32 file (not a reparse point
676  * stream); calculates its SHA1 message digest and either creates a `struct
677  * wim_lookup_table_entry' in memory for it, or uses an existing 'struct
678  * wim_lookup_table_entry' for an identical stream.
679  *
680  * @path:               Path to the file (UTF-16LE).
681  *
682  * @path_num_chars:     Number of 2-byte characters in @path.
683  *
684  * @inode:              WIM inode to save the stream into.
685  *
686  * @lookup_table:       Stream lookup table for the WIM.
687  *
688  * @dat:                A `WIN32_FIND_STREAM_DATA' structure that specifies the
689  *                      stream name.
690  *
691  * Returns 0 on success; nonzero on failure.
692  */
693 static int
694 win32_capture_stream(const wchar_t *path,
695                      size_t path_num_chars,
696                      struct wim_inode *inode,
697                      struct wim_lookup_table *lookup_table,
698                      WIN32_FIND_STREAM_DATA *dat)
699 {
700         struct wim_ads_entry *ads_entry;
701         struct wim_lookup_table_entry *lte;
702         int ret;
703         wchar_t *stream_name, *colon;
704         size_t stream_name_nchars;
705         bool is_named_stream;
706         wchar_t *spath;
707         size_t spath_nchars;
708         size_t spath_buf_nbytes;
709         const wchar_t *relpath_prefix;
710         const wchar_t *colonchar;
711
712         DEBUG("Capture \"%ls\" stream \"%ls\"", path, dat->cStreamName);
713
714         /* The stream name should be returned as :NAME:TYPE */
715         stream_name = dat->cStreamName;
716         if (*stream_name != L':')
717                 goto out_invalid_stream_name;
718         stream_name += 1;
719         colon = wcschr(stream_name, L':');
720         if (colon == NULL)
721                 goto out_invalid_stream_name;
722
723         if (wcscmp(colon + 1, L"$DATA")) {
724                 /* Not a DATA stream */
725                 ret = 0;
726                 goto out;
727         }
728
729         *colon = '\0';
730
731         stream_name_nchars = colon - stream_name;
732         is_named_stream = (stream_name_nchars != 0);
733
734         if (is_named_stream) {
735                 /* Allocate an ADS entry for the named stream. */
736                 ads_entry = inode_add_ads_utf16le(inode, stream_name,
737                                                   stream_name_nchars * sizeof(wchar_t));
738                 if (!ads_entry) {
739                         ret = WIMLIB_ERR_NOMEM;
740                         goto out;
741                 }
742         }
743
744         /* If zero length stream, no lookup table entry needed. */
745         if ((u64)dat->StreamSize.QuadPart == 0) {
746                 ret = 0;
747                 goto out;
748         }
749
750         /* Create a UTF-16LE string @spath that gives the filename, then a
751          * colon, then the stream name.  Or, if it's an unnamed stream, just the
752          * filename.  It is MALLOC()'ed so that it can be saved in the
753          * wim_lookup_table_entry if needed.
754          *
755          * As yet another special case, relative paths need to be changed to
756          * begin with an explicit "./" so that, for example, a file t:ads, where
757          * :ads is the part we added, is not interpreted as a file on the t:
758          * drive. */
759         spath_nchars = path_num_chars;
760         relpath_prefix = L"";
761         colonchar = L"";
762         if (is_named_stream) {
763                 spath_nchars += 1 + stream_name_nchars;
764                 colonchar = L":";
765                 if (path_num_chars == 1 && !is_any_path_separator(path[0])) {
766                         spath_nchars += 2;
767                         static const wchar_t _relpath_prefix[] =
768                                 {L'.', OS_PREFERRED_PATH_SEPARATOR, L'\0'};
769                         relpath_prefix = _relpath_prefix;
770                 }
771         }
772
773         spath_buf_nbytes = (spath_nchars + 1) * sizeof(wchar_t);
774         spath = MALLOC(spath_buf_nbytes);
775
776         swprintf(spath, L"%ls%ls%ls%ls",
777                  relpath_prefix, path, colonchar, stream_name);
778
779         /* Make a new wim_lookup_table_entry */
780         lte = new_lookup_table_entry();
781         if (!lte) {
782                 ret = WIMLIB_ERR_NOMEM;
783                 goto out_free_spath;
784         }
785         lte->file_on_disk = spath;
786         spath = NULL;
787         if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED && !is_named_stream) {
788                 u64 encrypted_size;
789                 lte->resource_location = RESOURCE_WIN32_ENCRYPTED;
790                 ret = win32_get_encrypted_file_size(path, &encrypted_size);
791                 if (ret)
792                         goto out_free_spath;
793                 lte->resource_entry.original_size = encrypted_size;
794         } else {
795                 lte->resource_location = RESOURCE_IN_FILE_ON_DISK;
796                 lte->resource_entry.original_size = (u64)dat->StreamSize.QuadPart;
797         }
798
799         u32 stream_id;
800         if (is_named_stream) {
801                 stream_id = ads_entry->stream_id;
802                 ads_entry->lte = lte;
803         } else {
804                 stream_id = 0;
805                 inode->i_lte = lte;
806         }
807         lookup_table_insert_unhashed(lookup_table, lte, inode, stream_id);
808         ret = 0;
809 out_free_spath:
810         FREE(spath);
811 out:
812         return ret;
813 out_invalid_stream_name:
814         ERROR("Invalid stream name: \"%ls:%ls\"", path, dat->cStreamName);
815         ret = WIMLIB_ERR_READ;
816         goto out;
817 }
818
819 /* Load information about the streams of an open file into a WIM inode.
820  *
821  * By default, we use the NtQueryInformationFile() system call instead of
822  * FindFirstStream() and FindNextStream().  This is done for two reasons:
823  *
824  * - FindFirstStream() opens its own handle to the file or directory and
825  *   apparently does so without specifying FILE_FLAG_BACKUP_SEMANTICS, thereby
826  *   causing access denied errors on certain files (even when running as the
827  *   Administrator).
828  * - FindFirstStream() and FindNextStream() is only available on Windows Vista
829  *   and later, whereas the stream support in NtQueryInformationFile() was
830  *   already present in Windows XP.
831  */
832 static int
833 win32_capture_streams(HANDLE hFile,
834                       const wchar_t *path,
835                       size_t path_num_chars,
836                       struct wim_inode *inode,
837                       struct wim_lookup_table *lookup_table,
838                       u64 file_size,
839                       unsigned vol_flags)
840 {
841         WIN32_FIND_STREAM_DATA dat;
842         int ret;
843 #ifdef WITH_NTDLL
844         u8 _buf[8192] _aligned_attribute(8);
845         u8 *buf;
846         size_t bufsize;
847         IO_STATUS_BLOCK io_status;
848         NTSTATUS status;
849         const FILE_STREAM_INFORMATION *info;
850 #else
851         HANDLE hFind;
852         DWORD err;
853 #endif
854
855         DEBUG("Capturing streams from \"%ls\"", path);
856
857         if (!(vol_flags & FILE_NAMED_STREAMS))
858                 goto unnamed_only;
859 #ifndef WITH_NTDLL
860         if (win32func_FindFirstStreamW == NULL)
861                 goto unnamed_only;
862 #endif
863
864 #ifdef WITH_NTDLL
865         buf = _buf;
866         bufsize = sizeof(_buf);
867
868         /* Get a buffer containing the stream information.  */
869         for (;;) {
870                 status = NtQueryInformationFile(hFile, &io_status, buf, bufsize,
871                                                 FileStreamInformation);
872                 if (status == STATUS_SUCCESS) {
873                         break;
874                 } else if (status == STATUS_BUFFER_OVERFLOW) {
875                         u8 *newbuf;
876
877                         bufsize *= 2;
878                         if (buf == _buf)
879                                 newbuf = MALLOC(bufsize);
880                         else
881                                 newbuf = REALLOC(buf, bufsize);
882
883                         if (!newbuf) {
884                                 ret = WIMLIB_ERR_NOMEM;
885                                 goto out_free_buf;
886                         }
887                         buf = newbuf;
888                 } else {
889                         errno = win32_error_to_errno(RtlNtStatusToDosError(status));
890                         ERROR_WITH_ERRNO("Failed to read streams of %ls", path);
891                         ret = WIMLIB_ERR_READ;
892                         goto out_free_buf;
893                 }
894         }
895
896         if (io_status.Information == 0) {
897                 /* No stream information.  */
898                 ret = 0;
899                 goto out_free_buf;
900         }
901
902         /* Parse one or more stream information structures.  */
903         info = (const FILE_STREAM_INFORMATION*)buf;
904         for (;;) {
905                 if (info->StreamNameLength <= sizeof(dat.cStreamName) - 2) {
906                         dat.StreamSize = info->StreamSize;
907                         memcpy(dat.cStreamName, info->StreamName, info->StreamNameLength);
908                         dat.cStreamName[info->StreamNameLength / 2] = L'\0';
909
910                         /* Capture the stream.  */
911                         ret = win32_capture_stream(path, path_num_chars, inode,
912                                                    lookup_table, &dat);
913                         if (ret)
914                                 goto out_free_buf;
915                 }
916                 if (info->NextEntryOffset == 0) {
917                         /* No more stream information.  */
918                         ret = 0;
919                         break;
920                 }
921                 /* Advance to next stream information.  */
922                 info = (const FILE_STREAM_INFORMATION*)
923                                 ((const u8*)info + info->NextEntryOffset);
924         }
925 out_free_buf:
926         /* Free buffer if allocated on heap.  */
927         if (buf != _buf)
928                 FREE(buf);
929         return ret;
930
931 #else /* WITH_NTDLL */
932         hFind = win32func_FindFirstStreamW(path, FindStreamInfoStandard, &dat, 0);
933         if (hFind == INVALID_HANDLE_VALUE) {
934                 err = GetLastError();
935                 if (err == ERROR_CALL_NOT_IMPLEMENTED)
936                         goto unnamed_only;
937
938                 /* Seems legal for this to return ERROR_HANDLE_EOF on reparse
939                  * points and directories */
940                 if ((inode->i_attributes &
941                     (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
942                     && err == ERROR_HANDLE_EOF)
943                 {
944                         DEBUG("ERROR_HANDLE_EOF (ok)");
945                         return 0;
946                 } else {
947                         if (err == ERROR_ACCESS_DENIED) {
948                                 WARNING("Failed to look up data streams "
949                                         "of \"%ls\": Access denied!\n%ls",
950                                         path, capture_access_denied_msg);
951                                 return 0;
952                         } else {
953                                 ERROR("Failed to look up data streams "
954                                       "of \"%ls\"", path);
955                                 win32_error(err);
956                                 return WIMLIB_ERR_READ;
957                         }
958                 }
959         }
960         do {
961                 ret = win32_capture_stream(path,
962                                            path_num_chars,
963                                            inode, lookup_table,
964                                            &dat);
965                 if (ret)
966                         goto out_find_close;
967         } while (win32func_FindNextStreamW(hFind, &dat));
968         err = GetLastError();
969         if (err != ERROR_HANDLE_EOF) {
970                 ERROR("Win32 API: Error reading data streams from \"%ls\"", path);
971                 win32_error(err);
972                 ret = WIMLIB_ERR_READ;
973         }
974 out_find_close:
975         FindClose(hFind);
976         return ret;
977 #endif /* !WITH_NTDLL */
978
979 unnamed_only:
980         /* FindFirstStreamW() API is not available, or the volume does not
981          * support named streams.  Only capture the unnamed data stream. */
982         DEBUG("Only capturing unnamed data stream");
983         if (!(inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
984                                      FILE_ATTRIBUTE_REPARSE_POINT)))
985         {
986                 wcscpy(dat.cStreamName, L"::$DATA");
987                 dat.StreamSize.QuadPart = file_size;
988                 ret = win32_capture_stream(path,
989                                            path_num_chars,
990                                            inode, lookup_table,
991                                            &dat);
992                 if (ret)
993                         return ret;
994         }
995         return ret;
996 }
997
998 static int
999 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
1000                                   wchar_t *path,
1001                                   size_t path_num_chars,
1002                                   struct add_image_params *params,
1003                                   struct win32_capture_state *state,
1004                                   unsigned vol_flags)
1005 {
1006         struct wim_dentry *root = NULL;
1007         struct wim_inode *inode;
1008         DWORD err;
1009         u64 file_size;
1010         int ret;
1011         u8 *rpbuf;
1012         u16 rpbuflen;
1013         u16 not_rpfixed;
1014
1015         params->progress.scan.cur_path = path;
1016
1017         if (exclude_path(path, path_num_chars, params->config, true)) {
1018                 if (params->add_flags & WIMLIB_ADD_FLAG_ROOT) {
1019                         ERROR("Cannot exclude the root directory from capture");
1020                         ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
1021                         goto out;
1022                 }
1023                 do_capture_progress(params, WIMLIB_SCAN_DENTRY_EXCLUDED);
1024                 ret = 0;
1025                 goto out;
1026         }
1027
1028 #if 0
1029         if (path_num_chars >= 4 &&
1030             !wmemcmp(path, L"\\\\?\\", 4) &&
1031             path_num_chars + 1 - 4 > MAX_PATH &&
1032             state->num_long_path_warnings < MAX_CAPTURE_LONG_PATH_WARNINGS)
1033         {
1034                 WARNING("Path \"%ls\" exceeds MAX_PATH", path);
1035                 if (++state->num_long_path_warnings == MAX_CAPTURE_LONG_PATH_WARNINGS)
1036                         WARNING("Suppressing further warnings about long paths.");
1037         }
1038 #endif
1039
1040         do_capture_progress(params, WIMLIB_SCAN_DENTRY_OK);
1041
1042         HANDLE hFile = win32_open_existing_file(path,
1043                                                 FILE_READ_DATA | FILE_READ_ATTRIBUTES);
1044         if (hFile == INVALID_HANDLE_VALUE) {
1045                 err = GetLastError();
1046                 ERROR("Win32 API: Failed to open \"%ls\"", path);
1047                 win32_error(err);
1048                 ret = WIMLIB_ERR_OPEN;
1049                 goto out;
1050         }
1051
1052         BY_HANDLE_FILE_INFORMATION file_info;
1053         if (!GetFileInformationByHandle(hFile, &file_info)) {
1054                 err = GetLastError();
1055                 ERROR("Win32 API: Failed to get file information for \"%ls\"",
1056                       path);
1057                 win32_error(err);
1058                 ret = WIMLIB_ERR_STAT;
1059                 goto out_close_handle;
1060         }
1061
1062         if (file_info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1063                 rpbuf = alloca(REPARSE_POINT_MAX_SIZE);
1064                 ret = win32_get_reparse_data(hFile, path, params,
1065                                              rpbuf, &rpbuflen);
1066                 if (ret < 0) {
1067                         /* WIMLIB_ERR_* (inverted) */
1068                         ret = -ret;
1069                         goto out_close_handle;
1070                 } else if (ret & RP_FIXED) {
1071                         not_rpfixed = 0;
1072                 } else if (ret == RP_EXCLUDED) {
1073                         ret = 0;
1074                         goto out_close_handle;
1075                 } else {
1076                         not_rpfixed = 1;
1077                 }
1078         }
1079
1080         /* Create a WIM dentry with an associated inode, which may be shared.
1081          *
1082          * However, we need to explicitly check for directories and files with
1083          * only 1 link and refuse to hard link them.  This is because Windows
1084          * has a bug where it can return duplicate File IDs for files and
1085          * directories on the FAT filesystem. */
1086         ret = inode_table_new_dentry(&params->inode_table,
1087                                      path_basename_with_len(path, path_num_chars),
1088                                      ((u64)file_info.nFileIndexHigh << 32) |
1089                                          (u64)file_info.nFileIndexLow,
1090                                      file_info.dwVolumeSerialNumber,
1091                                      (file_info.nNumberOfLinks <= 1 ||
1092                                         (file_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)),
1093                                      &root);
1094         if (ret)
1095                 goto out_close_handle;
1096
1097         ret = win32_get_short_name(root, path);
1098         if (ret)
1099                 goto out_close_handle;
1100
1101         inode = root->d_inode;
1102
1103         if (inode->i_nlink > 1) /* Shared inode; nothing more to do */
1104                 goto out_close_handle;
1105
1106         inode->i_attributes = file_info.dwFileAttributes;
1107         inode->i_creation_time = FILETIME_to_u64(&file_info.ftCreationTime);
1108         inode->i_last_write_time = FILETIME_to_u64(&file_info.ftLastWriteTime);
1109         inode->i_last_access_time = FILETIME_to_u64(&file_info.ftLastAccessTime);
1110         inode->i_resolved = 1;
1111
1112         params->add_flags &= ~WIMLIB_ADD_FLAG_ROOT;
1113
1114         if (!(params->add_flags & WIMLIB_ADD_FLAG_NO_ACLS)
1115             && (vol_flags & FILE_PERSISTENT_ACLS))
1116         {
1117                 ret = win32_get_security_descriptor(root, &params->sd_set,
1118                                                     path, state,
1119                                                     params->add_flags);
1120                 if (ret)
1121                         goto out_close_handle;
1122         }
1123
1124         file_size = ((u64)file_info.nFileSizeHigh << 32) |
1125                      (u64)file_info.nFileSizeLow;
1126
1127
1128         /* Capture the unnamed data stream (only should be present for regular
1129          * files) and any alternate data streams. */
1130         ret = win32_capture_streams(hFile,
1131                                     path,
1132                                     path_num_chars,
1133                                     inode,
1134                                     params->lookup_table,
1135                                     file_size,
1136                                     vol_flags);
1137         if (ret)
1138                 goto out_close_handle;
1139
1140         CloseHandle(hFile);
1141
1142         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1143                 /* Reparse point: set the reparse data (which we read already)
1144                  * */
1145                 inode->i_not_rpfixed = not_rpfixed;
1146                 inode->i_reparse_tag = le32_to_cpu(*(le32*)rpbuf);
1147                 ret = inode_set_unnamed_stream(inode, rpbuf + 8, rpbuflen - 8,
1148                                                params->lookup_table);
1149         } else if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1150                 /* Directory (not a reparse point) --- recurse to children */
1151                 ret = win32_recurse_directory(root,
1152                                               path,
1153                                               path_num_chars,
1154                                               params,
1155                                               state,
1156                                               vol_flags);
1157         }
1158         goto out;
1159 out_close_handle:
1160         CloseHandle(hFile);
1161 out:
1162         if (ret == 0)
1163                 *root_ret = root;
1164         else
1165                 free_dentry_tree(root, params->lookup_table);
1166         return ret;
1167 }
1168
1169 static void
1170 win32_do_capture_warnings(const struct win32_capture_state *state,
1171                           int add_flags)
1172 {
1173         if (state->num_get_sacl_priv_notheld == 0 &&
1174             state->num_get_sd_access_denied == 0)
1175                 return;
1176
1177         WARNING("");
1178         WARNING("Built dentry tree successfully, but with the following problem(s):");
1179         if (state->num_get_sacl_priv_notheld != 0) {
1180                 WARNING("Could not capture SACL (System Access Control List)\n"
1181                         "          on %lu files or directories.",
1182                         state->num_get_sacl_priv_notheld);
1183         }
1184         if (state->num_get_sd_access_denied != 0) {
1185                 WARNING("Could not capture security descriptor at all\n"
1186                         "          on %lu files or directories.",
1187                         state->num_get_sd_access_denied);
1188         }
1189         WARNING(
1190           "Try running the program as the Administrator to make sure all the\n"
1191 "          desired metadata has been captured exactly.  However, if you\n"
1192 "          do not care about capturing security descriptors correctly, then\n"
1193 "          nothing more needs to be done%ls\n",
1194         (add_flags & WIMLIB_ADD_FLAG_NO_ACLS) ? L"." :
1195          L", although you might consider\n"
1196 "          using the --no-acls option to explicitly capture no security\n"
1197 "          descriptors.\n");
1198 }
1199
1200 #define WINDOWS_NT_MAX_PATH 32768
1201
1202 /* Win32 version of capturing a directory tree */
1203 int
1204 win32_build_dentry_tree(struct wim_dentry **root_ret,
1205                         const wchar_t *root_disk_path,
1206                         struct add_image_params *params)
1207 {
1208         size_t path_nchars;
1209         wchar_t *path;
1210         int ret;
1211         struct win32_capture_state state;
1212         unsigned vol_flags;
1213         DWORD dret;
1214         bool need_prefix_free = false;
1215
1216 #ifndef WITH_NTDLL
1217         if (!win32func_FindFirstStreamW) {
1218                 WARNING("Running on Windows XP or earlier; "
1219                         "alternate data streams will not be captured.");
1220         }
1221 #endif
1222
1223         path_nchars = wcslen(root_disk_path);
1224         if (path_nchars > WINDOWS_NT_MAX_PATH)
1225                 return WIMLIB_ERR_INVALID_PARAM;
1226
1227         if (GetFileAttributesW(root_disk_path) == INVALID_FILE_ATTRIBUTES &&
1228             GetLastError() == ERROR_FILE_NOT_FOUND)
1229         {
1230                 ERROR("Capture directory \"%ls\" does not exist!",
1231                       root_disk_path);
1232                 return WIMLIB_ERR_OPENDIR;
1233         }
1234
1235         ret = win32_get_file_and_vol_ids(root_disk_path,
1236                                          &params->capture_root_ino,
1237                                          &params->capture_root_dev);
1238         if (ret)
1239                 return ret;
1240
1241         win32_get_vol_flags(root_disk_path, &vol_flags, NULL);
1242
1243         /* WARNING: There is no check for overflow later when this buffer is
1244          * being used!  But it's as long as the maximum path length understood
1245          * by Windows NT (which is NOT the same as MAX_PATH). */
1246         path = MALLOC(WINDOWS_NT_MAX_PATH * sizeof(wchar_t));
1247         if (!path)
1248                 return WIMLIB_ERR_NOMEM;
1249
1250         /* Work around defective behavior in Windows where paths longer than 260
1251          * characters are not supported by default; instead they need to be
1252          * turned into absolute paths and prefixed with "\\?\".  */
1253
1254         if (wcsncmp(root_disk_path, L"\\\\?\\", 4)) {
1255                 dret = GetFullPathName(root_disk_path, WINDOWS_NT_MAX_PATH - 4,
1256                                        &path[4], NULL);
1257
1258                 if (dret == 0 || dret >= WINDOWS_NT_MAX_PATH - 4) {
1259                         WARNING("Can't get full path name for \"%ls\"", root_disk_path);
1260                         wmemcpy(path, root_disk_path, path_nchars + 1);
1261                 } else {
1262                         wmemcpy(path, L"\\\\?\\", 4);
1263                         path_nchars = 4 + dret;
1264                         /* Update pattern prefix */
1265                         if (params->config != NULL)
1266                         {
1267                                 params->config->_prefix = TSTRDUP(path);
1268                                 params->config->_prefix_num_tchars = path_nchars;
1269                                 if (params->config->_prefix == NULL)
1270                                 {
1271                                         ret = WIMLIB_ERR_NOMEM;
1272                                         goto out_free_path;
1273                                 }
1274                                 need_prefix_free = true;
1275                         }
1276                 }
1277         } else {
1278                 wmemcpy(path, root_disk_path, path_nchars + 1);
1279         }
1280
1281         memset(&state, 0, sizeof(state));
1282         ret = win32_build_dentry_tree_recursive(root_ret, path,
1283                                                 path_nchars, params,
1284                                                 &state, vol_flags);
1285         if (need_prefix_free)
1286                 FREE(params->config->_prefix);
1287 out_free_path:
1288         FREE(path);
1289         if (ret == 0)
1290                 win32_do_capture_warnings(&state, params->add_flags);
1291         return ret;
1292 }
1293
1294 #endif /* __WIN32__ */