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