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