]> wimlib.net Git - wimlib/blob - src/win32_capture.c
Rewrite code for capture rpfix
[wimlib] / src / win32_capture.c
1 /*
2  * win32_capture.c - Windows-specific code for capturing files into a WIM image.
3  *
4  * This now uses the native Windows NT API a lot and not just Win32.
5  */
6
7 /*
8  * Copyright (C) 2013, 2014 Eric Biggers
9  *
10  * This file is part of wimlib, a library for working with WIM files.
11  *
12  * wimlib is free software; you can redistribute it and/or modify it under the
13  * terms of the GNU General Public License as published by the Free
14  * Software Foundation; either version 3 of the License, or (at your option)
15  * any later version.
16  *
17  * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
18  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
19  * A PARTICULAR PURPOSE. See the GNU General Public License for more
20  * details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with wimlib; if not, see http://www.gnu.org/licenses/.
24  */
25
26 #ifdef __WIN32__
27
28 #ifdef HAVE_CONFIG_H
29 #  include "config.h"
30 #endif
31
32 #include "wimlib/win32_common.h"
33
34 #include "wimlib/capture.h"
35 #include "wimlib/dentry.h"
36 #include "wimlib/encoding.h"
37 #include "wimlib/endianness.h"
38 #include "wimlib/error.h"
39 #include "wimlib/lookup_table.h"
40 #include "wimlib/paths.h"
41 #include "wimlib/reparse.h"
42
43 #include <errno.h>
44
45 struct winnt_scan_stats {
46         unsigned long num_get_sd_access_denied;
47         unsigned long num_get_sacl_priv_notheld;
48         unsigned long num_long_path_warnings;
49 };
50
51 static inline const wchar_t *
52 printable_path(const wchar_t *full_path)
53 {
54         /* Skip over \\?\ or \??\  */
55         return full_path + 4;
56 }
57
58 /*
59  * If cur_dir is not NULL, open an existing file relative to the already-open
60  * directory cur_dir.
61  *
62  * Otherwise, open the file specified by @path, which must be a Windows NT
63  * namespace path.
64  */
65 static NTSTATUS
66 winnt_openat(HANDLE cur_dir, const wchar_t *path, size_t path_nchars,
67              ACCESS_MASK perms, HANDLE *h_ret)
68 {
69         UNICODE_STRING name;
70         OBJECT_ATTRIBUTES attr;
71         IO_STATUS_BLOCK iosb;
72         NTSTATUS status;
73
74         name.Length = path_nchars * sizeof(wchar_t);
75         name.MaximumLength = name.Length + sizeof(wchar_t);
76         name.Buffer = (wchar_t *)path;
77
78         attr.Length = sizeof(attr);
79         attr.RootDirectory = cur_dir;
80         attr.ObjectName = &name;
81         attr.Attributes = 0;
82         attr.SecurityDescriptor = NULL;
83         attr.SecurityQualityOfService = NULL;
84
85 retry:
86         status = (*func_NtOpenFile)(h_ret, perms, &attr, &iosb,
87                                     FILE_SHARE_READ |
88                                             FILE_SHARE_WRITE |
89                                             FILE_SHARE_DELETE,
90                                     FILE_OPEN_REPARSE_POINT |
91                                             FILE_OPEN_FOR_BACKUP_INTENT |
92                                             FILE_SYNCHRONOUS_IO_NONALERT |
93                                             FILE_SEQUENTIAL_ONLY);
94         if (!NT_SUCCESS(status)) {
95                 /* Try requesting fewer permissions  */
96                 if (status == STATUS_ACCESS_DENIED ||
97                     status == STATUS_PRIVILEGE_NOT_HELD) {
98                         if (perms & ACCESS_SYSTEM_SECURITY) {
99                                 perms &= ~ACCESS_SYSTEM_SECURITY;
100                                 goto retry;
101                         }
102                         if (perms & READ_CONTROL) {
103                                 perms &= ~READ_CONTROL;
104                                 goto retry;
105                         }
106                 }
107         }
108         return status;
109 }
110
111 /* Read the first @size bytes from the file, or named data stream of a file,
112  * from which the stream entry @lte was created.  */
113 int
114 read_winnt_file_prefix(const struct wim_lookup_table_entry *lte, u64 size,
115                        consume_data_callback_t cb, void *cb_ctx)
116 {
117         const wchar_t *path;
118         HANDLE h;
119         NTSTATUS status;
120         u8 buf[BUFFER_SIZE];
121         u64 bytes_remaining;
122         int ret;
123
124         /* This is an NT namespace path.  */
125         path = lte->file_on_disk;
126
127         status = winnt_openat(NULL, path, wcslen(path),
128                               FILE_READ_DATA | SYNCHRONIZE, &h);
129         if (!NT_SUCCESS(status)) {
130                 set_errno_from_nt_status(status);
131                 ERROR_WITH_ERRNO("\"%ls\": Can't open for reading "
132                                  "(status=0x%08"PRIx32")",
133                                  printable_path(path), (u32)status);
134                 return WIMLIB_ERR_OPEN;
135         }
136
137         ret = 0;
138         bytes_remaining = size;
139         while (bytes_remaining) {
140                 IO_STATUS_BLOCK iosb;
141                 ULONG count;
142                 ULONG bytes_read;
143
144                 count = min(sizeof(buf), bytes_remaining);
145
146                 status = (*func_NtReadFile)(h, NULL, NULL, NULL,
147                                             &iosb, buf, count, NULL, NULL);
148                 if (!NT_SUCCESS(status)) {
149                         set_errno_from_nt_status(status);
150                         ERROR_WITH_ERRNO("\"%ls\": Error reading data "
151                                          "(status=0x%08"PRIx32")",
152                                          printable_path(path), (u32)status);
153                         ret = WIMLIB_ERR_READ;
154                         break;
155                 }
156
157                 bytes_read = iosb.Information;
158
159                 bytes_remaining -= bytes_read;
160                 ret = (*cb)(buf, bytes_read, cb_ctx);
161                 if (ret)
162                         break;
163         }
164         (*func_NtClose)(h);
165         return ret;
166 }
167
168 struct win32_encrypted_read_ctx {
169         consume_data_callback_t read_prefix_cb;
170         void *read_prefix_ctx;
171         int wimlib_err_code;
172         u64 bytes_remaining;
173 };
174
175 static DWORD WINAPI
176 win32_encrypted_export_cb(unsigned char *data, void *_ctx, unsigned long len)
177 {
178         struct win32_encrypted_read_ctx *ctx = _ctx;
179         int ret;
180         size_t bytes_to_consume = min(len, ctx->bytes_remaining);
181
182         if (bytes_to_consume == 0)
183                 return ERROR_SUCCESS;
184
185         ret = (*ctx->read_prefix_cb)(data, bytes_to_consume, ctx->read_prefix_ctx);
186         if (ret) {
187                 ctx->wimlib_err_code = ret;
188                 /* Shouldn't matter what error code is returned here, as long as
189                  * it isn't ERROR_SUCCESS.  */
190                 return ERROR_READ_FAULT;
191         }
192         ctx->bytes_remaining -= bytes_to_consume;
193         return ERROR_SUCCESS;
194 }
195
196 int
197 read_win32_encrypted_file_prefix(const struct wim_lookup_table_entry *lte,
198                                  u64 size,
199                                  consume_data_callback_t cb, void *cb_ctx)
200 {
201         struct win32_encrypted_read_ctx export_ctx;
202         DWORD err;
203         void *file_ctx;
204         int ret;
205
206         export_ctx.read_prefix_cb = cb;
207         export_ctx.read_prefix_ctx = cb_ctx;
208         export_ctx.wimlib_err_code = 0;
209         export_ctx.bytes_remaining = size;
210
211         err = OpenEncryptedFileRaw(lte->file_on_disk, 0, &file_ctx);
212         if (err != ERROR_SUCCESS) {
213                 set_errno_from_win32_error(err);
214                 ERROR_WITH_ERRNO("Failed to open encrypted file \"%ls\" "
215                                  "for raw read",
216                                  printable_path(lte->file_on_disk));
217                 return WIMLIB_ERR_OPEN;
218         }
219         err = ReadEncryptedFileRaw(win32_encrypted_export_cb,
220                                    &export_ctx, file_ctx);
221         if (err != ERROR_SUCCESS) {
222                 set_errno_from_win32_error(err);
223                 ERROR_WITH_ERRNO("Failed to read encrypted file \"%ls\"",
224                                  printable_path(lte->file_on_disk));
225                 ret = export_ctx.wimlib_err_code;
226                 if (ret == 0)
227                         ret = WIMLIB_ERR_READ;
228         } else if (export_ctx.bytes_remaining != 0) {
229                 ERROR("Only could read %"PRIu64" of %"PRIu64" bytes from "
230                       "encryted file \"%ls\"",
231                       size - export_ctx.bytes_remaining, size,
232                       printable_path(lte->file_on_disk));
233                 ret = WIMLIB_ERR_READ;
234         } else {
235                 ret = 0;
236         }
237         CloseEncryptedFileRaw(file_ctx);
238         return ret;
239 }
240
241 /*
242  * Load the short name of a file into a WIM dentry.
243  */
244 static NTSTATUS
245 winnt_get_short_name(HANDLE h, struct wim_dentry *dentry)
246 {
247         /* It's not any harder to just make the NtQueryInformationFile() system
248          * call ourselves, and it saves a dumb call to FindFirstFile() which of
249          * course has to create its own handle.  */
250         NTSTATUS status;
251         IO_STATUS_BLOCK iosb;
252         u8 buf[128] _aligned_attribute(8);
253         const FILE_NAME_INFORMATION *info;
254
255         status = (*func_NtQueryInformationFile)(h, &iosb, buf, sizeof(buf),
256                                                 FileAlternateNameInformation);
257         info = (const FILE_NAME_INFORMATION *)buf;
258         if (NT_SUCCESS(status) && info->FileNameLength != 0) {
259                 dentry->short_name = utf16le_dupz(info->FileName,
260                                                   info->FileNameLength);
261                 if (!dentry->short_name)
262                         return STATUS_NO_MEMORY;
263                 dentry->short_name_nbytes = info->FileNameLength;
264         }
265         return status;
266 }
267
268 /*
269  * Load the security descriptor of a file into the corresponding inode, and the
270  * WIM image's security descriptor set.
271  */
272 static NTSTATUS
273 winnt_get_security_descriptor(HANDLE h, struct wim_inode *inode,
274                               struct wim_sd_set *sd_set,
275                               struct winnt_scan_stats *stats, int add_flags)
276 {
277         SECURITY_INFORMATION requestedInformation;
278         u8 _buf[4096] _aligned_attribute(8);
279         u8 *buf;
280         ULONG bufsize;
281         ULONG len_needed;
282         NTSTATUS status;
283
284         requestedInformation = DACL_SECURITY_INFORMATION |
285                                SACL_SECURITY_INFORMATION |
286                                OWNER_SECURITY_INFORMATION |
287                                GROUP_SECURITY_INFORMATION;
288         buf = _buf;
289         bufsize = sizeof(_buf);
290
291         /*
292          * We need the file's security descriptor in
293          * SECURITY_DESCRIPTOR_RELATIVE format, and we currently have a handle
294          * opened with as many relevant permissions as possible.  At this point,
295          * on Windows there are a number of options for reading a file's
296          * security descriptor:
297          *
298          * GetFileSecurity():  This takes in a path and returns the
299          * SECURITY_DESCRIPTOR_RELATIVE.  Problem: this uses an internal handle,
300          * not ours, and the handle created internally doesn't specify
301          * FILE_FLAG_BACKUP_SEMANTICS.  Therefore there can be access denied
302          * errors on some files and directories, even when running as the
303          * Administrator.
304          *
305          * GetSecurityInfo():  This takes in a handle and returns the security
306          * descriptor split into a bunch of different parts.  This should work,
307          * but it's dumb because we have to put the security descriptor back
308          * together again.
309          *
310          * BackupRead():  This can read the security descriptor, but this is a
311          * difficult-to-use API, probably only works as the Administrator, and
312          * the format of the returned data is not well documented.
313          *
314          * NtQuerySecurityObject():  This is exactly what we need, as it takes
315          * in a handle and returns the security descriptor in
316          * SECURITY_DESCRIPTOR_RELATIVE format.  Only problem is that it's a
317          * ntdll function and therefore not officially part of the Win32 API.
318          * Oh well.
319          */
320         while (!(NT_SUCCESS(status = (*func_NtQuerySecurityObject)(h,
321                                                                    requestedInformation,
322                                                                    (PSECURITY_DESCRIPTOR)buf,
323                                                                    bufsize,
324                                                                    &len_needed))))
325         {
326                 switch (status) {
327                 case STATUS_BUFFER_TOO_SMALL:
328                         wimlib_assert(buf == _buf);
329                         buf = MALLOC(len_needed);
330                         if (!buf)
331                                 return STATUS_NO_MEMORY;
332                         bufsize = len_needed;
333                         break;
334                 case STATUS_PRIVILEGE_NOT_HELD:
335                 case STATUS_ACCESS_DENIED:
336                         if (add_flags & WIMLIB_ADD_FLAG_STRICT_ACLS) {
337                 default:
338                                 /* Permission denied in STRICT_ACLS mode, or
339                                  * unknown error.  */
340                                 goto out_free_buf;
341                         }
342                         if (requestedInformation & SACL_SECURITY_INFORMATION) {
343                                 /* Try again without the SACL.  */
344                                 stats->num_get_sacl_priv_notheld++;
345                                 requestedInformation &= ~SACL_SECURITY_INFORMATION;
346                                 break;
347                         }
348                         /* Fake success (useful when capturing as
349                          * non-Administrator).  */
350                         stats->num_get_sd_access_denied++;
351                         status = STATUS_SUCCESS;
352                         goto out_free_buf;
353                 }
354         }
355
356         /* Add the security descriptor to the WIM image, and save its ID in
357          * file's inode.  */
358         inode->i_security_id = sd_set_add_sd(sd_set, buf, len_needed);
359         if (unlikely(inode->i_security_id < 0))
360                 status = STATUS_NO_MEMORY;
361 out_free_buf:
362         if (unlikely(buf != _buf))
363                 FREE(buf);
364         return status;
365 }
366
367 static int
368 winnt_build_dentry_tree_recursive(struct wim_dentry **root_ret,
369                                   HANDLE cur_dir,
370                                   wchar_t *full_path,
371                                   size_t full_path_nchars,
372                                   const wchar_t *filename,
373                                   size_t filename_nchars,
374                                   struct add_image_params *params,
375                                   struct winnt_scan_stats *stats,
376                                   u32 vol_flags);
377
378 static int
379 winnt_recurse_directory(HANDLE h,
380                         wchar_t *full_path,
381                         size_t full_path_nchars,
382                         struct wim_dentry *parent,
383                         struct add_image_params *params,
384                         struct winnt_scan_stats *stats,
385                         u32 vol_flags)
386 {
387         void *buf;
388         const size_t bufsize = 8192;
389         IO_STATUS_BLOCK iosb;
390         NTSTATUS status;
391         int ret;
392
393         buf = MALLOC(bufsize);
394         if (!buf)
395                 return WIMLIB_ERR_NOMEM;
396
397         /* Using NtQueryDirectoryFile() we can re-use the same open handle,
398          * which we opened with FILE_FLAG_BACKUP_SEMANTICS.  */
399
400         while (NT_SUCCESS(status = (*func_NtQueryDirectoryFile)(h, NULL, NULL, NULL,
401                                                                 &iosb, buf, bufsize,
402                                                                 FileNamesInformation,
403                                                                 FALSE, NULL, FALSE)))
404         {
405                 const FILE_NAMES_INFORMATION *info = buf;
406                 for (;;) {
407                         if (!(info->FileNameLength == 2 && info->FileName[0] == L'.') &&
408                             !(info->FileNameLength == 4 && info->FileName[0] == L'.' &&
409                                                            info->FileName[1] == L'.'))
410                         {
411                                 wchar_t *p;
412                                 struct wim_dentry *child;
413
414                                 p = full_path + full_path_nchars;
415                                 *p++ = L'\\';
416                                 p = wmempcpy(p, info->FileName,
417                                              info->FileNameLength / 2);
418                                 *p = '\0';
419
420                                 ret = winnt_build_dentry_tree_recursive(
421                                                         &child,
422                                                         h,
423                                                         full_path,
424                                                         p - full_path,
425                                                         full_path + full_path_nchars + 1,
426                                                         info->FileNameLength / 2,
427                                                         params,
428                                                         stats,
429                                                         vol_flags);
430
431                                 full_path[full_path_nchars] = L'\0';
432
433                                 if (ret)
434                                         goto out_free_buf;
435                                 if (child)
436                                         dentry_add_child(parent, child);
437                         }
438                         if (info->NextEntryOffset == 0)
439                                 break;
440                         info = (const FILE_NAMES_INFORMATION *)
441                                         ((const u8 *)info + info->NextEntryOffset);
442                 }
443         }
444
445         if (unlikely(status != STATUS_NO_MORE_FILES)) {
446                 set_errno_from_nt_status(status);
447                 ERROR_WITH_ERRNO("\"%ls\": Can't read directory "
448                                  "(status=0x%08"PRIx32")",
449                                  printable_path(full_path), (u32)status);
450                 ret = WIMLIB_ERR_READ;
451         }
452 out_free_buf:
453         FREE(buf);
454         return ret;
455 }
456
457 /* Reparse point fixup status code  */
458 enum rp_status {
459         /* Reparse point should be excluded from capture  */
460         RP_EXCLUDED     = -0,
461
462         /* Reparse point will be captured literally (no fixup)  */
463         RP_NOT_FIXED    = -1,
464
465         /* Reparse point will be captured with fixup  */
466         RP_FIXED        = -2,
467 };
468
469 static bool
470 file_has_ino_and_dev(HANDLE h, u64 ino, u64 dev)
471 {
472         NTSTATUS status;
473         IO_STATUS_BLOCK iosb;
474         FILE_INTERNAL_INFORMATION int_info;
475         FILE_FS_VOLUME_INFORMATION vol_info;
476
477         status = (*func_NtQueryInformationFile)(h, &iosb,
478                                                 &int_info, sizeof(int_info),
479                                                 FileInternalInformation);
480         if (!NT_SUCCESS(status))
481                 return false;
482
483         if (int_info.IndexNumber.QuadPart != ino)
484                 return false;
485
486         status = (*func_NtQueryVolumeInformationFile)(h, &iosb,
487                                                       &vol_info, sizeof(vol_info),
488                                                       FileFsVolumeInformation);
489         if (!(NT_SUCCESS(status) || status == STATUS_BUFFER_OVERFLOW))
490                 return false;
491
492         if (iosb.Information <
493              offsetof(FILE_FS_VOLUME_INFORMATION, VolumeSerialNumber) +
494              sizeof(vol_info.VolumeSerialNumber))
495                 return false;
496
497         return (vol_info.VolumeSerialNumber == dev);
498 }
499
500 /*
501  * Given an (expected) NT namespace symbolic link or junction target @target of
502  * length @target_nbytes, determine if a prefix of the target points to a file
503  * identified by @capture_root_ino and @capture_root_dev.
504  *
505  * If yes, return a pointer to the portion of the link following this prefix.
506  *
507  * If no, return NULL.
508  *
509  * If the link target does not appear to be a valid NT namespace path, return
510  * @target itself.
511  */
512 static const wchar_t *
513 winnt_get_root_relative_target(const wchar_t *target, size_t target_nbytes,
514                                u64 capture_root_ino, u64 capture_root_dev)
515 {
516         UNICODE_STRING name;
517         OBJECT_ATTRIBUTES attr;
518         IO_STATUS_BLOCK iosb;
519         NTSTATUS status;
520         const wchar_t *target_end;
521         const wchar_t *p;
522
523         target_end = target + (target_nbytes / sizeof(wchar_t));
524
525         /* Empty path??? */
526         if (target_end == target)
527                 return target;
528
529         /* No leading slash???  */
530         if (target[0] != L'\\')
531                 return target;
532
533         /* UNC path???  */
534         if ((target_end - target) >= 2 &&
535             target[0] == L'\\' && target[1] == L'\\')
536                 return target;
537
538         attr.Length = sizeof(attr);
539         attr.RootDirectory = NULL;
540         attr.ObjectName = &name;
541         attr.Attributes = 0;
542         attr.SecurityDescriptor = NULL;
543         attr.SecurityQualityOfService = NULL;
544
545         name.Buffer = (wchar_t *)target;
546         name.Length = 0;
547         p = target;
548         do {
549                 HANDLE h;
550                 const wchar_t *orig_p = p;
551
552                 /* Skip non-backslashes  */
553                 while (p != target_end && *p != L'\\')
554                         p++;
555
556                 /* Skip backslashes  */
557                 while (p != target_end && *p == L'\\')
558                         p++;
559
560                 /* Append path component  */
561                 name.Length += (p - orig_p) * sizeof(wchar_t);
562                 name.MaximumLength = name.Length;
563
564                 /* Try opening the file  */
565                 status = (*func_NtOpenFile) (&h,
566                                              FILE_READ_ATTRIBUTES | FILE_TRAVERSE,
567                                              &attr,
568                                              &iosb,
569                                              FILE_SHARE_VALID_FLAGS,
570                                              FILE_OPEN_FOR_BACKUP_INTENT);
571
572                 if (NT_SUCCESS(status)) {
573                         /* Reset root directory  */
574                         if (attr.RootDirectory)
575                                 (*func_NtClose)(attr.RootDirectory);
576                         attr.RootDirectory = h;
577                         name.Buffer = (wchar_t *)p;
578                         name.Length = 0;
579
580                         if (file_has_ino_and_dev(h, capture_root_ino,
581                                                  capture_root_dev))
582                                 goto out_close_root_dir;
583                 }
584         } while (p != target_end);
585
586         p = NULL;
587
588 out_close_root_dir:
589         if (attr.RootDirectory)
590                 (*func_NtClose)(attr.RootDirectory);
591         return p;
592 }
593
594 static enum rp_status
595 winnt_try_rpfix(u8 *rpbuf, u16 *rpbuflen_p,
596                 u64 capture_root_ino, u64 capture_root_dev,
597                 const wchar_t *path, struct add_image_params *params)
598 {
599         struct reparse_data rpdata;
600         const wchar_t *rel_target;
601
602         if (parse_reparse_data(rpbuf, *rpbuflen_p, &rpdata)) {
603                 /* Couldn't even understand the reparse data.  Don't try the
604                  * fixup.  */
605                 return RP_NOT_FIXED;
606         }
607
608         /*
609          * Don't do reparse point fixups on relative symbolic links.
610          *
611          * On Windows, a relative symbolic link is supposed to be identifiable
612          * by having reparse tag WIM_IO_REPARSE_TAG_SYMLINK and flags
613          * SYMBOLIC_LINK_RELATIVE.  We will use this information, although this
614          * may not always do what the user expects, since drive-relative
615          * symbolic links such as "\Users\Public" have SYMBOLIC_LINK_RELATIVE
616          * set, in addition to truely relative symbolic links such as "Users" or
617          * "Users\Public".  However, WIMGAPI (as of Windows 8.1) has this same
618          * behavior.
619          *
620          * Otherwise, as far as I can tell, the targets of symbolic links that
621          * are NOT relative, as well as junctions (note: a mountpoint is the
622          * sames thing as a junction), must be NT namespace paths, for example:
623          *
624          *     - \??\e:\Users\Public
625          *     - \DosDevices\e:\Users\Public
626          *     - \Device\HardDiskVolume4\Users\Public
627          *     - \??\Volume{c47cb07c-946e-4155-b8f7-052e9cec7628}\Users\Public
628          *     - \DosDevices\Volume{c47cb07c-946e-4155-b8f7-052e9cec7628}\Users\Public
629          */
630         if (rpdata.rptag == WIM_IO_REPARSE_TAG_SYMLINK &&
631             (rpdata.rpflags & SYMBOLIC_LINK_RELATIVE))
632                 return RP_NOT_FIXED;
633
634         rel_target = winnt_get_root_relative_target(rpdata.substitute_name,
635                                                     rpdata.substitute_name_nbytes,
636                                                     capture_root_ino,
637                                                     capture_root_dev);
638         if (!rel_target) {
639                 /* Target points outside of the tree being captured.  Exclude
640                  * this reparse point from the capture (but inform the library
641                  * user).  */
642                 size_t print_name_nchars = rpdata.print_name_nbytes / sizeof(wchar_t);
643                 wchar_t print_name0[print_name_nchars + 1];
644                 print_name0[print_name_nchars] = L'\0';
645                 wmemcpy(print_name0, rpdata.print_name, print_name_nchars);
646
647                 params->progress.scan.cur_path = printable_path(path);
648                 params->progress.scan.symlink_target = print_name0;
649                 do_capture_progress(params, WIMLIB_SCAN_DENTRY_EXCLUDED_SYMLINK, NULL);
650                 return RP_EXCLUDED;
651         }
652
653         if (rel_target == rpdata.substitute_name) {
654                 /* Weird target --- keep the reparse point and don't mess with
655                  * it.  */
656                 return RP_NOT_FIXED;
657         }
658
659         /* We have an absolute target pointing within the directory being
660          * captured, @rel_target is the suffix of the link target that is the
661          * part relative to the directory being captured.
662          *
663          * We will cut off the prefix before this part (which is the path to the
664          * directory being captured) and add a dummy prefix.  Since the process
665          * will need to be reversed when applying the image, it shouldn't matter
666          * what exactly the prefix is, as long as it looks like an absolute
667          * path.
668          */
669
670         {
671                 size_t rel_target_nbytes =
672                         rpdata.substitute_name_nbytes - ((const u8 *)rel_target -
673                                                          (const u8 *)rpdata.substitute_name);
674                 size_t rel_target_nchars = rel_target_nbytes / sizeof(wchar_t);
675
676                 wchar_t tmp[rel_target_nchars + 7];
677
678                 wmemcpy(tmp, L"\\??\\X:\\", 7);
679                 wmemcpy(tmp + 7, rel_target, rel_target_nchars);
680
681                 rpdata.substitute_name = tmp;
682                 rpdata.substitute_name_nbytes = rel_target_nbytes + (7 * sizeof(wchar_t));
683                 rpdata.print_name = tmp + 4;
684                 rpdata.print_name_nbytes = rel_target_nbytes + (3 * sizeof(wchar_t));
685
686                 if (make_reparse_buffer(&rpdata, rpbuf, rpbuflen_p))
687                         return RP_NOT_FIXED;
688         }
689         return RP_FIXED;
690 }
691
692 /*
693  * Loads the reparse point data from a reparse point into memory, optionally
694  * fixing the targets of absolute symbolic links and junction points to be
695  * relative to the root of capture.
696  *
697  * @h:
698  *      Open handle to the reparse point file.
699  * @path:
700  *      Path to the reparse point file.
701  * @params:
702  *      Capture parameters.  add_flags, capture_root_ino, capture_root_dev,
703  *      progress_func, and progress are used.
704  * @rpbuf:
705  *      Buffer of length at least REPARSE_POINT_MAX_SIZE bytes into which the
706  *      reparse point buffer will be loaded.
707  * @rpbuflen_ret:
708  *      On success, the length of the reparse point buffer in bytes is written
709  *      to this location.
710  *
711  * On success, returns a nonpositive `enum rp_status' value.
712  * On failure, returns a positive error code.
713  */
714 static int
715 winnt_get_reparse_data(HANDLE h, const wchar_t *path,
716                        struct add_image_params *params,
717                        u8 *rpbuf, u16 *rpbuflen_ret)
718 {
719         DWORD bytes_returned;
720         u32 reparse_tag;
721         int ret;
722         u16 rpbuflen;
723
724         if (!DeviceIoControl(h, FSCTL_GET_REPARSE_POINT,
725                              NULL, 0, rpbuf, REPARSE_POINT_MAX_SIZE,
726                              &bytes_returned, NULL))
727         {
728                 set_errno_from_GetLastError();
729                 return WIMLIB_ERR_READ;
730         }
731
732         if (unlikely(bytes_returned < 8)) {
733                 errno = EINVAL;
734                 return WIMLIB_ERR_INVALID_REPARSE_DATA;
735         }
736
737         rpbuflen = bytes_returned;
738         reparse_tag = le32_to_cpu(*(le32*)rpbuf);
739         ret = RP_NOT_FIXED;
740         if (params->add_flags & WIMLIB_ADD_FLAG_RPFIX &&
741             (reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
742              reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT))
743         {
744                 ret = winnt_try_rpfix(rpbuf, &rpbuflen,
745                                       params->capture_root_ino,
746                                       params->capture_root_dev,
747                                       path, params);
748         }
749         *rpbuflen_ret = rpbuflen;
750         return ret;
751 }
752
753 static DWORD WINAPI
754 win32_tally_encrypted_size_cb(unsigned char *_data, void *_size_ret,
755                               unsigned long len)
756 {
757         *(u64*)_size_ret += len;
758         return ERROR_SUCCESS;
759 }
760
761 static int
762 win32_get_encrypted_file_size(const wchar_t *path, u64 *size_ret)
763 {
764         DWORD err;
765         void *file_ctx;
766         int ret;
767
768         err = OpenEncryptedFileRaw(path, 0, &file_ctx);
769         if (err != ERROR_SUCCESS) {
770                 set_errno_from_win32_error(err);
771                 ERROR_WITH_ERRNO("Failed to open encrypted file \"%ls\" "
772                                  "for raw read", printable_path(path));
773                 return WIMLIB_ERR_OPEN;
774         }
775         *size_ret = 0;
776         err = ReadEncryptedFileRaw(win32_tally_encrypted_size_cb,
777                                    size_ret, file_ctx);
778         if (err != ERROR_SUCCESS) {
779                 set_errno_from_win32_error(err);
780                 ERROR_WITH_ERRNO("Failed to read raw encrypted data from "
781                                  "\"%ls\"", printable_path(path));
782                 ret = WIMLIB_ERR_READ;
783         } else {
784                 ret = 0;
785         }
786         CloseEncryptedFileRaw(file_ctx);
787         return ret;
788 }
789
790 static bool
791 get_data_stream_name(const wchar_t *raw_stream_name, size_t raw_stream_name_nchars,
792                      const wchar_t **stream_name_ret, size_t *stream_name_nchars_ret)
793 {
794         const wchar_t *sep, *type, *end;
795
796         /* The stream name should be returned as :NAME:TYPE  */
797         if (raw_stream_name_nchars < 1)
798                 return false;
799         if (raw_stream_name[0] != L':')
800                 return false;
801
802         raw_stream_name++;
803         raw_stream_name_nchars--;
804
805         end = raw_stream_name + raw_stream_name_nchars;
806
807         sep = wmemchr(raw_stream_name, L':', raw_stream_name_nchars);
808         if (!sep)
809                 return false;
810
811         type = sep + 1;
812         if (end - type != 5)
813                 return false;
814
815         if (wmemcmp(type, L"$DATA", 5))
816                 return false;
817
818         *stream_name_ret = raw_stream_name;
819         *stream_name_nchars_ret = sep - raw_stream_name;
820         return true;
821 }
822
823 static wchar_t *
824 build_stream_path(const wchar_t *path, size_t path_nchars,
825                   const wchar_t *stream_name, size_t stream_name_nchars)
826 {
827         size_t stream_path_nchars;
828         wchar_t *stream_path;
829         wchar_t *p;
830
831         stream_path_nchars = path_nchars;
832         if (stream_name_nchars)
833                 stream_path_nchars += 1 + stream_name_nchars;
834
835         stream_path = MALLOC((stream_path_nchars + 1) * sizeof(wchar_t));
836         if (stream_path) {
837                 p = wmempcpy(stream_path, path, path_nchars);
838                 if (stream_name_nchars) {
839                         *p++ = L':';
840                         p = wmempcpy(p, stream_name, stream_name_nchars);
841                 }
842                 *p++ = L'\0';
843         }
844         return stream_path;
845 }
846
847 static int
848 winnt_scan_stream(const wchar_t *path, size_t path_nchars,
849                   const wchar_t *raw_stream_name, size_t raw_stream_name_nchars,
850                   u64 stream_size,
851                   struct wim_inode *inode, struct list_head *unhashed_streams)
852 {
853         const wchar_t *stream_name;
854         size_t stream_name_nchars;
855         struct wim_ads_entry *ads_entry;
856         wchar_t *stream_path;
857         struct wim_lookup_table_entry *lte;
858         u32 stream_id;
859
860         /* Given the raw stream name (which is something like
861          * :streamname:$DATA), extract just the stream name part.
862          * Ignore any non-$DATA streams.  */
863         if (!get_data_stream_name(raw_stream_name, raw_stream_name_nchars,
864                                   &stream_name, &stream_name_nchars))
865                 return 0;
866
867         /* If this is a named stream, allocate an ADS entry for it.  */
868         if (stream_name_nchars) {
869                 ads_entry = inode_add_ads_utf16le(inode, stream_name,
870                                                   stream_name_nchars *
871                                                         sizeof(wchar_t));
872                 if (!ads_entry)
873                         return WIMLIB_ERR_NOMEM;
874         } else {
875                 ads_entry = NULL;
876         }
877
878         /* If the stream is empty, no lookup table entry is needed. */
879         if (stream_size == 0)
880                 return 0;
881
882         /* Build the path to the stream.  For unnamed streams, this is simply
883          * the path to the file.  For named streams, this is the path to the
884          * file, followed by a colon, followed by the stream name.  */
885         stream_path = build_stream_path(path, path_nchars,
886                                         stream_name, stream_name_nchars);
887         if (!stream_path)
888                 return WIMLIB_ERR_NOMEM;
889
890         /* Set up the lookup table entry for the stream.  */
891         lte = new_lookup_table_entry();
892         if (!lte) {
893                 FREE(stream_path);
894                 return WIMLIB_ERR_NOMEM;
895         }
896         lte->file_on_disk = stream_path;
897         lte->resource_location = RESOURCE_IN_WINNT_FILE_ON_DISK;
898         lte->size = stream_size;
899         if ((inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED) && !ads_entry) {
900                 /* Special case for encrypted file.  */
901
902                 /* OpenEncryptedFileRaw() expects Win32 name, not NT name.
903                  * Change \??\ into \\?\  */
904                 lte->file_on_disk[1] = L'\\';
905                 wimlib_assert(!wmemcmp(lte->file_on_disk, L"\\\\?\\", 4));
906
907                 u64 encrypted_size;
908                 int ret;
909
910                 ret = win32_get_encrypted_file_size(lte->file_on_disk,
911                                                     &encrypted_size);
912                 if (ret) {
913                         free_lookup_table_entry(lte);
914                         return ret;
915                 }
916                 lte->size = encrypted_size;
917                 lte->resource_location = RESOURCE_WIN32_ENCRYPTED;
918         }
919
920         if (ads_entry) {
921                 stream_id = ads_entry->stream_id;
922                 ads_entry->lte = lte;
923         } else {
924                 stream_id = 0;
925                 inode->i_lte = lte;
926         }
927         add_unhashed_stream(lte, inode, stream_id, unhashed_streams);
928         return 0;
929 }
930
931 /*
932  * Load information about the streams of an open file into a WIM inode.
933  *
934  * We use the NtQueryInformationFile() system call instead of FindFirstStream()
935  * and FindNextStream().  This is done for two reasons:
936  *
937  * - FindFirstStream() opens its own handle to the file or directory and
938  *   apparently does so without specifying FILE_FLAG_BACKUP_SEMANTICS, thereby
939  *   causing access denied errors on certain files (even when running as the
940  *   Administrator).
941  * - FindFirstStream() and FindNextStream() is only available on Windows Vista
942  *   and later, whereas the stream support in NtQueryInformationFile() was
943  *   already present in Windows XP.
944  */
945 static int
946 winnt_scan_streams(HANDLE *hFile_p, const wchar_t *path, size_t path_nchars,
947                    struct wim_inode *inode, struct list_head *unhashed_streams,
948                    u64 file_size, u32 vol_flags)
949 {
950         int ret;
951         u8 _buf[1024] _aligned_attribute(8);
952         u8 *buf;
953         size_t bufsize;
954         IO_STATUS_BLOCK iosb;
955         NTSTATUS status;
956         const FILE_STREAM_INFORMATION *info;
957
958         buf = _buf;
959         bufsize = sizeof(_buf);
960
961         if (!(vol_flags & FILE_NAMED_STREAMS))
962                 goto unnamed_only;
963
964         /* Get a buffer containing the stream information.  */
965         while (!NT_SUCCESS(status = (*func_NtQueryInformationFile)(*hFile_p,
966                                                                    &iosb,
967                                                                    buf,
968                                                                    bufsize,
969                                                                    FileStreamInformation)))
970         {
971
972                 switch (status) {
973                 case STATUS_BUFFER_OVERFLOW:
974                         {
975                                 u8 *newbuf;
976
977                                 bufsize *= 2;
978                                 if (buf == _buf)
979                                         newbuf = MALLOC(bufsize);
980                                 else
981                                         newbuf = REALLOC(buf, bufsize);
982                                 if (!newbuf) {
983                                         ret = WIMLIB_ERR_NOMEM;
984                                         goto out_free_buf;
985                                 }
986                                 buf = newbuf;
987                         }
988                         break;
989                 case STATUS_NOT_IMPLEMENTED:
990                 case STATUS_NOT_SUPPORTED:
991                 case STATUS_INVALID_INFO_CLASS:
992                         goto unnamed_only;
993                 default:
994                         set_errno_from_nt_status(status);
995                         ERROR_WITH_ERRNO("\"%ls\": Failed to query stream "
996                                          "information (status=0x%08"PRIx32")",
997                                          printable_path(path), (u32)status);
998                         ret = WIMLIB_ERR_READ;
999                         goto out_free_buf;
1000                 }
1001         }
1002
1003         if (iosb.Information == 0) {
1004                 /* No stream information.  */
1005                 ret = 0;
1006                 goto out_free_buf;
1007         }
1008
1009         if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED)) {
1010                 /* OpenEncryptedFileRaw() seems to fail with
1011                  * ERROR_SHARING_VIOLATION if there are any handles opened to
1012                  * the file.  */
1013                 (*func_NtClose)(*hFile_p);
1014                 *hFile_p = INVALID_HANDLE_VALUE;
1015         }
1016
1017         /* Parse one or more stream information structures.  */
1018         info = (const FILE_STREAM_INFORMATION *)buf;
1019         for (;;) {
1020                 /* Load the stream information.  */
1021                 ret = winnt_scan_stream(path, path_nchars,
1022                                         info->StreamName,
1023                                         info->StreamNameLength / 2,
1024                                         info->StreamSize.QuadPart,
1025                                         inode, unhashed_streams);
1026                 if (ret)
1027                         goto out_free_buf;
1028
1029                 if (info->NextEntryOffset == 0) {
1030                         /* No more stream information.  */
1031                         break;
1032                 }
1033                 /* Advance to next stream information.  */
1034                 info = (const FILE_STREAM_INFORMATION *)
1035                                 ((const u8 *)info + info->NextEntryOffset);
1036         }
1037         ret = 0;
1038         goto out_free_buf;
1039
1040 unnamed_only:
1041         /* The volume does not support named streams.  Only capture the unnamed
1042          * data stream.  */
1043         if (inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
1044                                    FILE_ATTRIBUTE_REPARSE_POINT))
1045         {
1046                 ret = 0;
1047                 goto out_free_buf;
1048         }
1049
1050         ret = winnt_scan_stream(path, path_nchars, L"::$DATA", 7,
1051                                 file_size, inode, unhashed_streams);
1052 out_free_buf:
1053         /* Free buffer if allocated on heap.  */
1054         if (unlikely(buf != _buf))
1055                 FREE(buf);
1056         return ret;
1057 }
1058
1059 static int
1060 winnt_build_dentry_tree_recursive(struct wim_dentry **root_ret,
1061                                   HANDLE cur_dir,
1062                                   wchar_t *full_path,
1063                                   size_t full_path_nchars,
1064                                   const wchar_t *filename,
1065                                   size_t filename_nchars,
1066                                   struct add_image_params *params,
1067                                   struct winnt_scan_stats *stats,
1068                                   u32 vol_flags)
1069 {
1070         struct wim_dentry *root = NULL;
1071         struct wim_inode *inode = NULL;
1072         HANDLE h = INVALID_HANDLE_VALUE;
1073         int ret;
1074         NTSTATUS status;
1075         FILE_ALL_INFORMATION file_info;
1076         u8 *rpbuf;
1077         u16 rpbuflen;
1078         u16 not_rpfixed;
1079
1080         if (should_exclude_path(full_path + params->capture_root_nchars,
1081                                 full_path_nchars - params->capture_root_nchars,
1082                                 params->config))
1083         {
1084                 ret = 0;
1085                 goto out_progress;
1086         }
1087
1088         /* Open the file.  */
1089         status = winnt_openat(cur_dir,
1090                               (cur_dir ? filename : full_path),
1091                               (cur_dir ? filename_nchars : full_path_nchars),
1092                               FILE_READ_DATA |
1093                                         FILE_READ_ATTRIBUTES |
1094                                         READ_CONTROL |
1095                                         ACCESS_SYSTEM_SECURITY |
1096                                         SYNCHRONIZE,
1097                               &h);
1098         if (unlikely(!NT_SUCCESS(status))) {
1099                 set_errno_from_nt_status(status);
1100                 ERROR_WITH_ERRNO("\"%ls\": Can't open file "
1101                                  "(status=0x%08"PRIx32")",
1102                                  printable_path(full_path), (u32)status);
1103                 ret = WIMLIB_ERR_OPEN;
1104                 goto out;
1105         }
1106
1107         /* Get information about the file.  */
1108         {
1109                 IO_STATUS_BLOCK iosb;
1110
1111                 status = (*func_NtQueryInformationFile)(h, &iosb,
1112                                                         &file_info,
1113                                                         sizeof(file_info),
1114                                                         FileAllInformation);
1115
1116                 if (unlikely(!NT_SUCCESS(status) &&
1117                              status != STATUS_BUFFER_OVERFLOW))
1118                 {
1119                         set_errno_from_nt_status(status);
1120                         ERROR_WITH_ERRNO("\"%ls\": Can't get file information "
1121                                          "(status=0x%08"PRIx32")",
1122                                          printable_path(full_path), (u32)status);
1123                         ret = WIMLIB_ERR_STAT;
1124                         goto out;
1125                 }
1126         }
1127
1128         if (unlikely(!cur_dir)) {
1129
1130                 /* Root of tree being captured; get volume information.  */
1131
1132                 FILE_FS_ATTRIBUTE_INFORMATION attr_info;
1133                 FILE_FS_VOLUME_INFORMATION vol_info;
1134                 IO_STATUS_BLOCK iosb;
1135
1136                 /* Get volume flags  */
1137                 status = (*func_NtQueryVolumeInformationFile)(h, &iosb,
1138                                                               &attr_info,
1139                                                               sizeof(attr_info),
1140                                                               FileFsAttributeInformation);
1141                 if (likely((NT_SUCCESS(status) ||
1142                             (status == STATUS_BUFFER_OVERFLOW)) &&
1143                            (iosb.Information >=
1144                                 offsetof(FILE_FS_ATTRIBUTE_INFORMATION,
1145                                          FileSystemAttributes) +
1146                                 sizeof(attr_info.FileSystemAttributes))))
1147                 {
1148                         vol_flags = attr_info.FileSystemAttributes;
1149                 } else {
1150                         set_errno_from_nt_status(status);
1151                         WARNING_WITH_ERRNO("\"%ls\": Can't get volume attributes "
1152                                            "(status=0x%08"PRIx32")",
1153                                            printable_path(full_path),
1154                                            (u32)status);
1155                         vol_flags = 0;
1156                 }
1157
1158                 /* Set inode number of root directory  */
1159                 params->capture_root_ino =
1160                         file_info.InternalInformation.IndexNumber.QuadPart;
1161
1162                 /* Get volume ID.  */
1163                 status = (*func_NtQueryVolumeInformationFile)(h, &iosb,
1164                                                               &vol_info,
1165                                                               sizeof(vol_info),
1166                                                               FileFsVolumeInformation);
1167                 if (likely((NT_SUCCESS(status) ||
1168                             (status == STATUS_BUFFER_OVERFLOW)) &&
1169                            (iosb.Information >=
1170                                 offsetof(FILE_FS_VOLUME_INFORMATION,
1171                                          VolumeSerialNumber) +
1172                                 sizeof(vol_info.VolumeSerialNumber))))
1173                 {
1174                         params->capture_root_dev = vol_info.VolumeSerialNumber;
1175                 } else {
1176                         set_errno_from_nt_status(status);
1177                         WARNING_WITH_ERRNO("\"%ls\": Can't get volume ID "
1178                                            "(status=0x%08"PRIx32")",
1179                                            printable_path(full_path),
1180                                            (u32)status);
1181                         params->capture_root_dev = 0;
1182                 }
1183         }
1184
1185         /* If this is a reparse point, read the reparse data.  */
1186         if (unlikely(file_info.BasicInformation.FileAttributes &
1187                      FILE_ATTRIBUTE_REPARSE_POINT))
1188         {
1189                 rpbuf = alloca(REPARSE_POINT_MAX_SIZE);
1190                 ret = winnt_get_reparse_data(h, full_path, params,
1191                                              rpbuf, &rpbuflen);
1192                 switch (ret) {
1193                 case RP_EXCLUDED:
1194                         ret = 0;
1195                         goto out;
1196                 case RP_FIXED:
1197                         not_rpfixed = 0;
1198                         break;
1199                 case RP_NOT_FIXED:
1200                         not_rpfixed = 1;
1201                         break;
1202                 default:
1203                         ERROR_WITH_ERRNO("\"%ls\": Can't get reparse data",
1204                                          printable_path(full_path));
1205                         goto out;
1206                 }
1207         }
1208
1209         /* Create a WIM dentry with an associated inode, which may be shared.
1210          *
1211          * However, we need to explicitly check for directories and files with
1212          * only 1 link and refuse to hard link them.  This is because Windows
1213          * has a bug where it can return duplicate File IDs for files and
1214          * directories on the FAT filesystem. */
1215         ret = inode_table_new_dentry(params->inode_table,
1216                                      filename,
1217                                      file_info.InternalInformation.IndexNumber.QuadPart,
1218                                      0, /* We don't follow mount points, so we
1219                                            currently don't need to get the
1220                                            volume ID / device number.  */
1221                                      (file_info.StandardInformation.NumberOfLinks <= 1 ||
1222                                         (file_info.BasicInformation.FileAttributes &
1223                                          FILE_ATTRIBUTE_DIRECTORY)),
1224                                      &root);
1225         if (ret)
1226                 goto out;
1227
1228         /* Get the short (DOS) name of the file.  */
1229         status = winnt_get_short_name(h, root);
1230
1231         /* If we can't read the short filename for any reason other than
1232          * out-of-memory, just ignore the error and assume the file has no short
1233          * name.  This shouldn't be an issue, since the short names are
1234          * essentially obsolete anyway.  */
1235         if (unlikely(status == STATUS_NO_MEMORY)) {
1236                 ret = WIMLIB_ERR_NOMEM;
1237                 goto out;
1238         }
1239
1240         inode = root->d_inode;
1241
1242         if (inode->i_nlink > 1) {
1243                 /* Shared inode (hard link); skip reading per-inode information.
1244                  */
1245                 ret = 0;
1246                 goto out_progress;
1247         }
1248
1249         inode->i_attributes = file_info.BasicInformation.FileAttributes;
1250         inode->i_creation_time = file_info.BasicInformation.CreationTime.QuadPart;
1251         inode->i_last_write_time = file_info.BasicInformation.LastWriteTime.QuadPart;
1252         inode->i_last_access_time = file_info.BasicInformation.LastAccessTime.QuadPart;
1253         inode->i_resolved = 1;
1254
1255         /* Get the file's security descriptor, unless we are capturing in
1256          * NO_ACLS mode or the volume does not support security descriptors.  */
1257         if (!(params->add_flags & WIMLIB_ADD_FLAG_NO_ACLS)
1258             && (vol_flags & FILE_PERSISTENT_ACLS))
1259         {
1260                 status = winnt_get_security_descriptor(h, inode,
1261                                                        params->sd_set, stats,
1262                                                        params->add_flags);
1263                 if (!NT_SUCCESS(status)) {
1264                         set_errno_from_nt_status(status);
1265                         ERROR_WITH_ERRNO("\"%ls\": Can't read security "
1266                                          "descriptor (status=0x%08"PRIu32")",
1267                                          printable_path(full_path),
1268                                          (u32)status);
1269                         ret = WIMLIB_ERR_STAT;
1270                         goto out;
1271                 }
1272         }
1273
1274         /* Load information about the unnamed data stream and any named data
1275          * streams.  */
1276         ret = winnt_scan_streams(&h,
1277                                  full_path,
1278                                  full_path_nchars,
1279                                  inode,
1280                                  params->unhashed_streams,
1281                                  file_info.StandardInformation.EndOfFile.QuadPart,
1282                                  vol_flags);
1283         if (ret)
1284                 goto out;
1285
1286         if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
1287
1288                 /* Reparse point: set the reparse data (already read).  */
1289
1290                 inode->i_not_rpfixed = not_rpfixed;
1291                 inode->i_reparse_tag = le32_to_cpu(*(le32*)rpbuf);
1292                 ret = inode_set_unnamed_stream(inode, rpbuf + 8, rpbuflen - 8,
1293                                                params->lookup_table);
1294                 if (ret)
1295                         goto out;
1296         } else if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1297
1298                 /* Directory: recurse to children.  */
1299
1300                 if (unlikely(h == INVALID_HANDLE_VALUE)) {
1301                         /* Re-open handle that was closed to read raw encrypted
1302                          * data.  */
1303                         status = winnt_openat(cur_dir,
1304                                               (cur_dir ?
1305                                                filename : full_path),
1306                                               (cur_dir ?
1307                                                filename_nchars : full_path_nchars),
1308                                               FILE_LIST_DIRECTORY | SYNCHRONIZE,
1309                                               &h);
1310                         if (!NT_SUCCESS(status)) {
1311                                 set_errno_from_nt_status(status);
1312                                 ERROR_WITH_ERRNO("\"%ls\": Can't re-open file "
1313                                                  "(status=0x%08"PRIx32")",
1314                                                  printable_path(full_path),
1315                                                  (u32)status);
1316                                 ret = WIMLIB_ERR_OPEN;
1317                                 goto out;
1318                         }
1319                 }
1320                 ret = winnt_recurse_directory(h,
1321                                               full_path,
1322                                               full_path_nchars,
1323                                               root,
1324                                               params,
1325                                               stats,
1326                                               vol_flags);
1327                 if (ret)
1328                         goto out;
1329         }
1330
1331 out_progress:
1332         params->progress.scan.cur_path = printable_path(full_path);
1333         if (likely(root))
1334                 do_capture_progress(params, WIMLIB_SCAN_DENTRY_OK, inode);
1335         else
1336                 do_capture_progress(params, WIMLIB_SCAN_DENTRY_EXCLUDED, NULL);
1337 out:
1338         if (likely(h != INVALID_HANDLE_VALUE))
1339                 (*func_NtClose)(h);
1340         if (likely(ret == 0))
1341                 *root_ret = root;
1342         else
1343                 free_dentry_tree(root, params->lookup_table);
1344         return ret;
1345 }
1346
1347 static void
1348 winnt_do_scan_warnings(const wchar_t *path, const struct winnt_scan_stats *stats)
1349 {
1350         if (likely(stats->num_get_sacl_priv_notheld == 0 &&
1351                    stats->num_get_sd_access_denied == 0))
1352                 return;
1353
1354         WARNING("Scan of \"%ls\" complete, but with one or more warnings:", path);
1355         if (stats->num_get_sacl_priv_notheld != 0) {
1356                 WARNING("- Could not capture SACL (System Access Control List)\n"
1357                         "            on %lu files or directories.",
1358                         stats->num_get_sacl_priv_notheld);
1359         }
1360         if (stats->num_get_sd_access_denied != 0) {
1361                 WARNING("- Could not capture security descriptor at all\n"
1362                         "            on %lu files or directories.",
1363                         stats->num_get_sd_access_denied);
1364         }
1365         WARNING("To fully capture all security descriptors, run the program\n"
1366                 "          with Administrator rights.");
1367 }
1368
1369 #define WINDOWS_NT_MAX_PATH 32768
1370
1371 /* Win32 version of capturing a directory tree.  */
1372 int
1373 win32_build_dentry_tree(struct wim_dentry **root_ret,
1374                         const wchar_t *root_disk_path,
1375                         struct add_image_params *params)
1376 {
1377         wchar_t *path;
1378         DWORD dret;
1379         size_t path_nchars;
1380         int ret;
1381         struct winnt_scan_stats stats;
1382
1383         /* WARNING: There is no check for overflow later when this buffer is
1384          * being used!  But it's as long as the maximum path length understood
1385          * by Windows NT (which is NOT the same as MAX_PATH).  */
1386         path = MALLOC((WINDOWS_NT_MAX_PATH + 1) * sizeof(wchar_t));
1387         if (!path)
1388                 return WIMLIB_ERR_NOMEM;
1389
1390         /* Translate into full path.  */
1391         dret = GetFullPathName(root_disk_path, WINDOWS_NT_MAX_PATH - 3,
1392                                &path[4], NULL);
1393
1394         if (unlikely(dret == 0 || dret >= WINDOWS_NT_MAX_PATH - 3)) {
1395                 ERROR("Can't get full path name for \"%ls\"", root_disk_path);
1396                 return WIMLIB_ERR_UNSUPPORTED;
1397         }
1398
1399         /* Add \??\ prefix to form the NT namespace path.  */
1400         wmemcpy(path, L"\\??\\", 4);
1401         path_nchars = dret + 4;
1402
1403        /* Strip trailing slashes.  If we don't do this, we may create a path
1404         * with multiple consecutive backslashes, which for some reason causes
1405         * Windows to report that the file cannot be found.  */
1406         while (unlikely(path[path_nchars - 1] == L'\\' &&
1407                         path[path_nchars - 2] != L':'))
1408                 path[--path_nchars] = L'\0';
1409
1410         params->capture_root_nchars = path_nchars;
1411
1412         memset(&stats, 0, sizeof(stats));
1413
1414         ret = winnt_build_dentry_tree_recursive(root_ret, NULL,
1415                                                 path, path_nchars, L"", 0,
1416                                                 params, &stats, 0);
1417         FREE(path);
1418         if (ret == 0)
1419                 winnt_do_scan_warnings(root_disk_path, &stats);
1420         return ret;
1421 }
1422
1423 #endif /* __WIN32__ */