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