Update progress functions
[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 int
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                 int ret = do_capture_progress(params,
648                                               WIMLIB_SCAN_DENTRY_EXCLUDED_SYMLINK,
649                                               NULL);
650                 if (ret)
651                         return ret;
652                 return RP_EXCLUDED;
653         }
654
655         if (rel_target == rpdata.substitute_name) {
656                 /* Weird target --- keep the reparse point and don't mess with
657                  * it.  */
658                 return RP_NOT_FIXED;
659         }
660
661         /* We have an absolute target pointing within the directory being
662          * captured, @rel_target is the suffix of the link target that is the
663          * part relative to the directory being captured.
664          *
665          * We will cut off the prefix before this part (which is the path to the
666          * directory being captured) and add a dummy prefix.  Since the process
667          * will need to be reversed when applying the image, it shouldn't matter
668          * what exactly the prefix is, as long as it looks like an absolute
669          * path.
670          */
671
672         {
673                 size_t rel_target_nbytes =
674                         rpdata.substitute_name_nbytes - ((const u8 *)rel_target -
675                                                          (const u8 *)rpdata.substitute_name);
676                 size_t rel_target_nchars = rel_target_nbytes / sizeof(wchar_t);
677
678                 wchar_t tmp[rel_target_nchars + 7];
679
680                 wmemcpy(tmp, L"\\??\\X:\\", 7);
681                 wmemcpy(tmp + 7, rel_target, rel_target_nchars);
682
683                 rpdata.substitute_name = tmp;
684                 rpdata.substitute_name_nbytes = rel_target_nbytes + (7 * sizeof(wchar_t));
685                 rpdata.print_name = tmp + 4;
686                 rpdata.print_name_nbytes = rel_target_nbytes + (3 * sizeof(wchar_t));
687
688                 if (make_reparse_buffer(&rpdata, rpbuf, rpbuflen_p))
689                         return RP_NOT_FIXED;
690         }
691         return RP_FIXED;
692 }
693
694 /*
695  * Loads the reparse point data from a reparse point into memory, optionally
696  * fixing the targets of absolute symbolic links and junction points to be
697  * relative to the root of capture.
698  *
699  * @h:
700  *      Open handle to the reparse point file.
701  * @path:
702  *      Path to the reparse point file.
703  * @params:
704  *      Capture parameters.  add_flags, capture_root_ino, capture_root_dev,
705  *      progfunc, progctx, and progress are used.
706  * @rpbuf:
707  *      Buffer of length at least REPARSE_POINT_MAX_SIZE bytes into which the
708  *      reparse point buffer will be loaded.
709  * @rpbuflen_ret:
710  *      On success, the length of the reparse point buffer in bytes is written
711  *      to this location.
712  *
713  * On success, returns a nonpositive `enum rp_status' value.
714  * On failure, returns a positive error code.
715  */
716 static int
717 winnt_get_reparse_data(HANDLE h, const wchar_t *path,
718                        struct add_image_params *params,
719                        u8 *rpbuf, u16 *rpbuflen_ret)
720 {
721         DWORD bytes_returned;
722         u32 reparse_tag;
723         int ret;
724         u16 rpbuflen;
725
726         if (!DeviceIoControl(h, FSCTL_GET_REPARSE_POINT,
727                              NULL, 0, rpbuf, REPARSE_POINT_MAX_SIZE,
728                              &bytes_returned, NULL))
729         {
730                 set_errno_from_GetLastError();
731                 return WIMLIB_ERR_READ;
732         }
733
734         if (unlikely(bytes_returned < 8)) {
735                 errno = EINVAL;
736                 return WIMLIB_ERR_INVALID_REPARSE_DATA;
737         }
738
739         rpbuflen = bytes_returned;
740         reparse_tag = le32_to_cpu(*(le32*)rpbuf);
741         ret = RP_NOT_FIXED;
742         if (params->add_flags & WIMLIB_ADD_FLAG_RPFIX &&
743             (reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
744              reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT))
745         {
746                 ret = winnt_try_rpfix(rpbuf, &rpbuflen,
747                                       params->capture_root_ino,
748                                       params->capture_root_dev,
749                                       path, params);
750         }
751         *rpbuflen_ret = rpbuflen;
752         return ret;
753 }
754
755 static DWORD WINAPI
756 win32_tally_encrypted_size_cb(unsigned char *_data, void *_size_ret,
757                               unsigned long len)
758 {
759         *(u64*)_size_ret += len;
760         return ERROR_SUCCESS;
761 }
762
763 static int
764 win32_get_encrypted_file_size(const wchar_t *path, u64 *size_ret)
765 {
766         DWORD err;
767         void *file_ctx;
768         int ret;
769
770         err = OpenEncryptedFileRaw(path, 0, &file_ctx);
771         if (err != ERROR_SUCCESS) {
772                 set_errno_from_win32_error(err);
773                 ERROR_WITH_ERRNO("Failed to open encrypted file \"%ls\" "
774                                  "for raw read", printable_path(path));
775                 return WIMLIB_ERR_OPEN;
776         }
777         *size_ret = 0;
778         err = ReadEncryptedFileRaw(win32_tally_encrypted_size_cb,
779                                    size_ret, file_ctx);
780         if (err != ERROR_SUCCESS) {
781                 set_errno_from_win32_error(err);
782                 ERROR_WITH_ERRNO("Failed to read raw encrypted data from "
783                                  "\"%ls\"", printable_path(path));
784                 ret = WIMLIB_ERR_READ;
785         } else {
786                 ret = 0;
787         }
788         CloseEncryptedFileRaw(file_ctx);
789         return ret;
790 }
791
792 static bool
793 get_data_stream_name(const wchar_t *raw_stream_name, size_t raw_stream_name_nchars,
794                      const wchar_t **stream_name_ret, size_t *stream_name_nchars_ret)
795 {
796         const wchar_t *sep, *type, *end;
797
798         /* The stream name should be returned as :NAME:TYPE  */
799         if (raw_stream_name_nchars < 1)
800                 return false;
801         if (raw_stream_name[0] != L':')
802                 return false;
803
804         raw_stream_name++;
805         raw_stream_name_nchars--;
806
807         end = raw_stream_name + raw_stream_name_nchars;
808
809         sep = wmemchr(raw_stream_name, L':', raw_stream_name_nchars);
810         if (!sep)
811                 return false;
812
813         type = sep + 1;
814         if (end - type != 5)
815                 return false;
816
817         if (wmemcmp(type, L"$DATA", 5))
818                 return false;
819
820         *stream_name_ret = raw_stream_name;
821         *stream_name_nchars_ret = sep - raw_stream_name;
822         return true;
823 }
824
825 static wchar_t *
826 build_stream_path(const wchar_t *path, size_t path_nchars,
827                   const wchar_t *stream_name, size_t stream_name_nchars)
828 {
829         size_t stream_path_nchars;
830         wchar_t *stream_path;
831         wchar_t *p;
832
833         stream_path_nchars = path_nchars;
834         if (stream_name_nchars)
835                 stream_path_nchars += 1 + stream_name_nchars;
836
837         stream_path = MALLOC((stream_path_nchars + 1) * sizeof(wchar_t));
838         if (stream_path) {
839                 p = wmempcpy(stream_path, path, path_nchars);
840                 if (stream_name_nchars) {
841                         *p++ = L':';
842                         p = wmempcpy(p, stream_name, stream_name_nchars);
843                 }
844                 *p++ = L'\0';
845         }
846         return stream_path;
847 }
848
849 static int
850 winnt_scan_stream(const wchar_t *path, size_t path_nchars,
851                   const wchar_t *raw_stream_name, size_t raw_stream_name_nchars,
852                   u64 stream_size,
853                   struct wim_inode *inode, struct list_head *unhashed_streams)
854 {
855         const wchar_t *stream_name;
856         size_t stream_name_nchars;
857         struct wim_ads_entry *ads_entry;
858         wchar_t *stream_path;
859         struct wim_lookup_table_entry *lte;
860         u32 stream_id;
861
862         /* Given the raw stream name (which is something like
863          * :streamname:$DATA), extract just the stream name part.
864          * Ignore any non-$DATA streams.  */
865         if (!get_data_stream_name(raw_stream_name, raw_stream_name_nchars,
866                                   &stream_name, &stream_name_nchars))
867                 return 0;
868
869         /* If this is a named stream, allocate an ADS entry for it.  */
870         if (stream_name_nchars) {
871                 ads_entry = inode_add_ads_utf16le(inode, stream_name,
872                                                   stream_name_nchars *
873                                                         sizeof(wchar_t));
874                 if (!ads_entry)
875                         return WIMLIB_ERR_NOMEM;
876         } else {
877                 ads_entry = NULL;
878         }
879
880         /* If the stream is empty, no lookup table entry is needed. */
881         if (stream_size == 0)
882                 return 0;
883
884         /* Build the path to the stream.  For unnamed streams, this is simply
885          * the path to the file.  For named streams, this is the path to the
886          * file, followed by a colon, followed by the stream name.  */
887         stream_path = build_stream_path(path, path_nchars,
888                                         stream_name, stream_name_nchars);
889         if (!stream_path)
890                 return WIMLIB_ERR_NOMEM;
891
892         /* Set up the lookup table entry for the stream.  */
893         lte = new_lookup_table_entry();
894         if (!lte) {
895                 FREE(stream_path);
896                 return WIMLIB_ERR_NOMEM;
897         }
898         lte->file_on_disk = stream_path;
899         lte->resource_location = RESOURCE_IN_WINNT_FILE_ON_DISK;
900         lte->size = stream_size;
901         if ((inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED) && !ads_entry) {
902                 /* Special case for encrypted file.  */
903
904                 /* OpenEncryptedFileRaw() expects Win32 name, not NT name.
905                  * Change \??\ into \\?\  */
906                 lte->file_on_disk[1] = L'\\';
907                 wimlib_assert(!wmemcmp(lte->file_on_disk, L"\\\\?\\", 4));
908
909                 u64 encrypted_size;
910                 int ret;
911
912                 ret = win32_get_encrypted_file_size(lte->file_on_disk,
913                                                     &encrypted_size);
914                 if (ret) {
915                         free_lookup_table_entry(lte);
916                         return ret;
917                 }
918                 lte->size = encrypted_size;
919                 lte->resource_location = RESOURCE_WIN32_ENCRYPTED;
920         }
921
922         if (ads_entry) {
923                 stream_id = ads_entry->stream_id;
924                 ads_entry->lte = lte;
925         } else {
926                 stream_id = 0;
927                 inode->i_lte = lte;
928         }
929         add_unhashed_stream(lte, inode, stream_id, unhashed_streams);
930         return 0;
931 }
932
933 /*
934  * Load information about the streams of an open file into a WIM inode.
935  *
936  * We use the NtQueryInformationFile() system call instead of FindFirstStream()
937  * and FindNextStream().  This is done for two reasons:
938  *
939  * - FindFirstStream() opens its own handle to the file or directory and
940  *   apparently does so without specifying FILE_FLAG_BACKUP_SEMANTICS, thereby
941  *   causing access denied errors on certain files (even when running as the
942  *   Administrator).
943  * - FindFirstStream() and FindNextStream() is only available on Windows Vista
944  *   and later, whereas the stream support in NtQueryInformationFile() was
945  *   already present in Windows XP.
946  */
947 static int
948 winnt_scan_streams(HANDLE *hFile_p, const wchar_t *path, size_t path_nchars,
949                    struct wim_inode *inode, struct list_head *unhashed_streams,
950                    u64 file_size, u32 vol_flags)
951 {
952         int ret;
953         u8 _buf[1024] _aligned_attribute(8);
954         u8 *buf;
955         size_t bufsize;
956         IO_STATUS_BLOCK iosb;
957         NTSTATUS status;
958         const FILE_STREAM_INFORMATION *info;
959
960         buf = _buf;
961         bufsize = sizeof(_buf);
962
963         if (!(vol_flags & FILE_NAMED_STREAMS))
964                 goto unnamed_only;
965
966         /* Get a buffer containing the stream information.  */
967         while (!NT_SUCCESS(status = (*func_NtQueryInformationFile)(*hFile_p,
968                                                                    &iosb,
969                                                                    buf,
970                                                                    bufsize,
971                                                                    FileStreamInformation)))
972         {
973
974                 switch (status) {
975                 case STATUS_BUFFER_OVERFLOW:
976                         {
977                                 u8 *newbuf;
978
979                                 bufsize *= 2;
980                                 if (buf == _buf)
981                                         newbuf = MALLOC(bufsize);
982                                 else
983                                         newbuf = REALLOC(buf, bufsize);
984                                 if (!newbuf) {
985                                         ret = WIMLIB_ERR_NOMEM;
986                                         goto out_free_buf;
987                                 }
988                                 buf = newbuf;
989                         }
990                         break;
991                 case STATUS_NOT_IMPLEMENTED:
992                 case STATUS_NOT_SUPPORTED:
993                 case STATUS_INVALID_INFO_CLASS:
994                         goto unnamed_only;
995                 default:
996                         set_errno_from_nt_status(status);
997                         ERROR_WITH_ERRNO("\"%ls\": Failed to query stream "
998                                          "information (status=0x%08"PRIx32")",
999                                          printable_path(path), (u32)status);
1000                         ret = WIMLIB_ERR_READ;
1001                         goto out_free_buf;
1002                 }
1003         }
1004
1005         if (iosb.Information == 0) {
1006                 /* No stream information.  */
1007                 ret = 0;
1008                 goto out_free_buf;
1009         }
1010
1011         if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED)) {
1012                 /* OpenEncryptedFileRaw() seems to fail with
1013                  * ERROR_SHARING_VIOLATION if there are any handles opened to
1014                  * the file.  */
1015                 (*func_NtClose)(*hFile_p);
1016                 *hFile_p = INVALID_HANDLE_VALUE;
1017         }
1018
1019         /* Parse one or more stream information structures.  */
1020         info = (const FILE_STREAM_INFORMATION *)buf;
1021         for (;;) {
1022                 /* Load the stream information.  */
1023                 ret = winnt_scan_stream(path, path_nchars,
1024                                         info->StreamName,
1025                                         info->StreamNameLength / 2,
1026                                         info->StreamSize.QuadPart,
1027                                         inode, unhashed_streams);
1028                 if (ret)
1029                         goto out_free_buf;
1030
1031                 if (info->NextEntryOffset == 0) {
1032                         /* No more stream information.  */
1033                         break;
1034                 }
1035                 /* Advance to next stream information.  */
1036                 info = (const FILE_STREAM_INFORMATION *)
1037                                 ((const u8 *)info + info->NextEntryOffset);
1038         }
1039         ret = 0;
1040         goto out_free_buf;
1041
1042 unnamed_only:
1043         /* The volume does not support named streams.  Only capture the unnamed
1044          * data stream.  */
1045         if (inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
1046                                    FILE_ATTRIBUTE_REPARSE_POINT))
1047         {
1048                 ret = 0;
1049                 goto out_free_buf;
1050         }
1051
1052         ret = winnt_scan_stream(path, path_nchars, L"::$DATA", 7,
1053                                 file_size, inode, unhashed_streams);
1054 out_free_buf:
1055         /* Free buffer if allocated on heap.  */
1056         if (unlikely(buf != _buf))
1057                 FREE(buf);
1058         return ret;
1059 }
1060
1061 static int
1062 winnt_build_dentry_tree_recursive(struct wim_dentry **root_ret,
1063                                   HANDLE cur_dir,
1064                                   wchar_t *full_path,
1065                                   size_t full_path_nchars,
1066                                   const wchar_t *filename,
1067                                   size_t filename_nchars,
1068                                   struct add_image_params *params,
1069                                   struct winnt_scan_stats *stats,
1070                                   u32 vol_flags)
1071 {
1072         struct wim_dentry *root = NULL;
1073         struct wim_inode *inode = NULL;
1074         HANDLE h = INVALID_HANDLE_VALUE;
1075         int ret;
1076         NTSTATUS status;
1077         FILE_ALL_INFORMATION file_info;
1078         u8 *rpbuf;
1079         u16 rpbuflen;
1080         u16 not_rpfixed;
1081
1082         if (should_exclude_path(full_path + params->capture_root_nchars,
1083                                 full_path_nchars - params->capture_root_nchars,
1084                                 params->config))
1085         {
1086                 ret = 0;
1087                 goto out_progress;
1088         }
1089
1090         /* Open the file.  */
1091         status = winnt_openat(cur_dir,
1092                               (cur_dir ? filename : full_path),
1093                               (cur_dir ? filename_nchars : full_path_nchars),
1094                               FILE_READ_DATA |
1095                                         FILE_READ_ATTRIBUTES |
1096                                         READ_CONTROL |
1097                                         ACCESS_SYSTEM_SECURITY |
1098                                         SYNCHRONIZE,
1099                               &h);
1100         if (unlikely(!NT_SUCCESS(status))) {
1101                 set_errno_from_nt_status(status);
1102                 ERROR_WITH_ERRNO("\"%ls\": Can't open file "
1103                                  "(status=0x%08"PRIx32")",
1104                                  printable_path(full_path), (u32)status);
1105                 ret = WIMLIB_ERR_OPEN;
1106                 goto out;
1107         }
1108
1109         /* Get information about the file.  */
1110         {
1111                 IO_STATUS_BLOCK iosb;
1112
1113                 status = (*func_NtQueryInformationFile)(h, &iosb,
1114                                                         &file_info,
1115                                                         sizeof(file_info),
1116                                                         FileAllInformation);
1117
1118                 if (unlikely(!NT_SUCCESS(status) &&
1119                              status != STATUS_BUFFER_OVERFLOW))
1120                 {
1121                         set_errno_from_nt_status(status);
1122                         ERROR_WITH_ERRNO("\"%ls\": Can't get file information "
1123                                          "(status=0x%08"PRIx32")",
1124                                          printable_path(full_path), (u32)status);
1125                         ret = WIMLIB_ERR_STAT;
1126                         goto out;
1127                 }
1128         }
1129
1130         if (unlikely(!cur_dir)) {
1131
1132                 /* Root of tree being captured; get volume information.  */
1133
1134                 FILE_FS_ATTRIBUTE_INFORMATION attr_info;
1135                 FILE_FS_VOLUME_INFORMATION vol_info;
1136                 IO_STATUS_BLOCK iosb;
1137
1138                 /* Get volume flags  */
1139                 status = (*func_NtQueryVolumeInformationFile)(h, &iosb,
1140                                                               &attr_info,
1141                                                               sizeof(attr_info),
1142                                                               FileFsAttributeInformation);
1143                 if (likely((NT_SUCCESS(status) ||
1144                             (status == STATUS_BUFFER_OVERFLOW)) &&
1145                            (iosb.Information >=
1146                                 offsetof(FILE_FS_ATTRIBUTE_INFORMATION,
1147                                          FileSystemAttributes) +
1148                                 sizeof(attr_info.FileSystemAttributes))))
1149                 {
1150                         vol_flags = attr_info.FileSystemAttributes;
1151                 } else {
1152                         set_errno_from_nt_status(status);
1153                         WARNING_WITH_ERRNO("\"%ls\": Can't get volume attributes "
1154                                            "(status=0x%08"PRIx32")",
1155                                            printable_path(full_path),
1156                                            (u32)status);
1157                         vol_flags = 0;
1158                 }
1159
1160                 /* Set inode number of root directory  */
1161                 params->capture_root_ino =
1162                         file_info.InternalInformation.IndexNumber.QuadPart;
1163
1164                 /* Get volume ID.  */
1165                 status = (*func_NtQueryVolumeInformationFile)(h, &iosb,
1166                                                               &vol_info,
1167                                                               sizeof(vol_info),
1168                                                               FileFsVolumeInformation);
1169                 if (likely((NT_SUCCESS(status) ||
1170                             (status == STATUS_BUFFER_OVERFLOW)) &&
1171                            (iosb.Information >=
1172                                 offsetof(FILE_FS_VOLUME_INFORMATION,
1173                                          VolumeSerialNumber) +
1174                                 sizeof(vol_info.VolumeSerialNumber))))
1175                 {
1176                         params->capture_root_dev = vol_info.VolumeSerialNumber;
1177                 } else {
1178                         set_errno_from_nt_status(status);
1179                         WARNING_WITH_ERRNO("\"%ls\": Can't get volume ID "
1180                                            "(status=0x%08"PRIx32")",
1181                                            printable_path(full_path),
1182                                            (u32)status);
1183                         params->capture_root_dev = 0;
1184                 }
1185         }
1186
1187         /* If this is a reparse point, read the reparse data.  */
1188         if (unlikely(file_info.BasicInformation.FileAttributes &
1189                      FILE_ATTRIBUTE_REPARSE_POINT))
1190         {
1191                 rpbuf = alloca(REPARSE_POINT_MAX_SIZE);
1192                 ret = winnt_get_reparse_data(h, full_path, params,
1193                                              rpbuf, &rpbuflen);
1194                 switch (ret) {
1195                 case RP_EXCLUDED:
1196                         ret = 0;
1197                         goto out;
1198                 case RP_FIXED:
1199                         not_rpfixed = 0;
1200                         break;
1201                 case RP_NOT_FIXED:
1202                         not_rpfixed = 1;
1203                         break;
1204                 default:
1205                         ERROR_WITH_ERRNO("\"%ls\": Can't get reparse data",
1206                                          printable_path(full_path));
1207                         goto out;
1208                 }
1209         }
1210
1211         /* Create a WIM dentry with an associated inode, which may be shared.
1212          *
1213          * However, we need to explicitly check for directories and files with
1214          * only 1 link and refuse to hard link them.  This is because Windows
1215          * has a bug where it can return duplicate File IDs for files and
1216          * directories on the FAT filesystem. */
1217         ret = inode_table_new_dentry(params->inode_table,
1218                                      filename,
1219                                      file_info.InternalInformation.IndexNumber.QuadPart,
1220                                      0, /* We don't follow mount points, so we
1221                                            currently don't need to get the
1222                                            volume ID / device number.  */
1223                                      (file_info.StandardInformation.NumberOfLinks <= 1 ||
1224                                         (file_info.BasicInformation.FileAttributes &
1225                                          FILE_ATTRIBUTE_DIRECTORY)),
1226                                      &root);
1227         if (ret)
1228                 goto out;
1229
1230         /* Get the short (DOS) name of the file.  */
1231         status = winnt_get_short_name(h, root);
1232
1233         /* If we can't read the short filename for any reason other than
1234          * out-of-memory, just ignore the error and assume the file has no short
1235          * name.  This shouldn't be an issue, since the short names are
1236          * essentially obsolete anyway.  */
1237         if (unlikely(status == STATUS_NO_MEMORY)) {
1238                 ret = WIMLIB_ERR_NOMEM;
1239                 goto out;
1240         }
1241
1242         inode = root->d_inode;
1243
1244         if (inode->i_nlink > 1) {
1245                 /* Shared inode (hard link); skip reading per-inode information.
1246                  */
1247                 ret = 0;
1248                 goto out_progress;
1249         }
1250
1251         inode->i_attributes = file_info.BasicInformation.FileAttributes;
1252         inode->i_creation_time = file_info.BasicInformation.CreationTime.QuadPart;
1253         inode->i_last_write_time = file_info.BasicInformation.LastWriteTime.QuadPart;
1254         inode->i_last_access_time = file_info.BasicInformation.LastAccessTime.QuadPart;
1255         inode->i_resolved = 1;
1256
1257         /* Get the file's security descriptor, unless we are capturing in
1258          * NO_ACLS mode or the volume does not support security descriptors.  */
1259         if (!(params->add_flags & WIMLIB_ADD_FLAG_NO_ACLS)
1260             && (vol_flags & FILE_PERSISTENT_ACLS))
1261         {
1262                 status = winnt_get_security_descriptor(h, inode,
1263                                                        params->sd_set, stats,
1264                                                        params->add_flags);
1265                 if (!NT_SUCCESS(status)) {
1266                         set_errno_from_nt_status(status);
1267                         ERROR_WITH_ERRNO("\"%ls\": Can't read security "
1268                                          "descriptor (status=0x%08"PRIu32")",
1269                                          printable_path(full_path),
1270                                          (u32)status);
1271                         ret = WIMLIB_ERR_STAT;
1272                         goto out;
1273                 }
1274         }
1275
1276         /* Load information about the unnamed data stream and any named data
1277          * streams.  */
1278         ret = winnt_scan_streams(&h,
1279                                  full_path,
1280                                  full_path_nchars,
1281                                  inode,
1282                                  params->unhashed_streams,
1283                                  file_info.StandardInformation.EndOfFile.QuadPart,
1284                                  vol_flags);
1285         if (ret)
1286                 goto out;
1287
1288         if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
1289
1290                 /* Reparse point: set the reparse data (already read).  */
1291
1292                 inode->i_not_rpfixed = not_rpfixed;
1293                 inode->i_reparse_tag = le32_to_cpu(*(le32*)rpbuf);
1294                 ret = inode_set_unnamed_stream(inode, rpbuf + 8, rpbuflen - 8,
1295                                                params->lookup_table);
1296                 if (ret)
1297                         goto out;
1298         } else if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1299
1300                 /* Directory: recurse to children.  */
1301
1302                 if (unlikely(h == INVALID_HANDLE_VALUE)) {
1303                         /* Re-open handle that was closed to read raw encrypted
1304                          * data.  */
1305                         status = winnt_openat(cur_dir,
1306                                               (cur_dir ?
1307                                                filename : full_path),
1308                                               (cur_dir ?
1309                                                filename_nchars : full_path_nchars),
1310                                               FILE_LIST_DIRECTORY | SYNCHRONIZE,
1311                                               &h);
1312                         if (!NT_SUCCESS(status)) {
1313                                 set_errno_from_nt_status(status);
1314                                 ERROR_WITH_ERRNO("\"%ls\": Can't re-open file "
1315                                                  "(status=0x%08"PRIx32")",
1316                                                  printable_path(full_path),
1317                                                  (u32)status);
1318                                 ret = WIMLIB_ERR_OPEN;
1319                                 goto out;
1320                         }
1321                 }
1322                 ret = winnt_recurse_directory(h,
1323                                               full_path,
1324                                               full_path_nchars,
1325                                               root,
1326                                               params,
1327                                               stats,
1328                                               vol_flags);
1329                 if (ret)
1330                         goto out;
1331         }
1332
1333 out_progress:
1334         params->progress.scan.cur_path = printable_path(full_path);
1335         if (likely(root))
1336                 ret = do_capture_progress(params, WIMLIB_SCAN_DENTRY_OK, inode);
1337         else
1338                 ret = do_capture_progress(params, WIMLIB_SCAN_DENTRY_EXCLUDED, NULL);
1339 out:
1340         if (likely(h != INVALID_HANDLE_VALUE))
1341                 (*func_NtClose)(h);
1342         if (likely(ret == 0))
1343                 *root_ret = root;
1344         else
1345                 free_dentry_tree(root, params->lookup_table);
1346         return ret;
1347 }
1348
1349 static void
1350 winnt_do_scan_warnings(const wchar_t *path, const struct winnt_scan_stats *stats)
1351 {
1352         if (likely(stats->num_get_sacl_priv_notheld == 0 &&
1353                    stats->num_get_sd_access_denied == 0))
1354                 return;
1355
1356         WARNING("Scan of \"%ls\" complete, but with one or more warnings:", path);
1357         if (stats->num_get_sacl_priv_notheld != 0) {
1358                 WARNING("- Could not capture SACL (System Access Control List)\n"
1359                         "            on %lu files or directories.",
1360                         stats->num_get_sacl_priv_notheld);
1361         }
1362         if (stats->num_get_sd_access_denied != 0) {
1363                 WARNING("- Could not capture security descriptor at all\n"
1364                         "            on %lu files or directories.",
1365                         stats->num_get_sd_access_denied);
1366         }
1367         WARNING("To fully capture all security descriptors, run the program\n"
1368                 "          with Administrator rights.");
1369 }
1370
1371 #define WINDOWS_NT_MAX_PATH 32768
1372
1373 /* Win32 version of capturing a directory tree.  */
1374 int
1375 win32_build_dentry_tree(struct wim_dentry **root_ret,
1376                         const wchar_t *root_disk_path,
1377                         struct add_image_params *params)
1378 {
1379         wchar_t *path;
1380         DWORD dret;
1381         size_t path_nchars;
1382         int ret;
1383         struct winnt_scan_stats stats;
1384
1385         /* WARNING: There is no check for overflow later when this buffer is
1386          * being used!  But it's as long as the maximum path length understood
1387          * by Windows NT (which is NOT the same as MAX_PATH).  */
1388         path = MALLOC((WINDOWS_NT_MAX_PATH + 1) * sizeof(wchar_t));
1389         if (!path)
1390                 return WIMLIB_ERR_NOMEM;
1391
1392         /* Translate into full path.  */
1393         dret = GetFullPathName(root_disk_path, WINDOWS_NT_MAX_PATH - 3,
1394                                &path[4], NULL);
1395
1396         if (unlikely(dret == 0 || dret >= WINDOWS_NT_MAX_PATH - 3)) {
1397                 ERROR("Can't get full path name for \"%ls\"", root_disk_path);
1398                 return WIMLIB_ERR_UNSUPPORTED;
1399         }
1400
1401         /* Add \??\ prefix to form the NT namespace path.  */
1402         wmemcpy(path, L"\\??\\", 4);
1403         path_nchars = dret + 4;
1404
1405        /* Strip trailing slashes.  If we don't do this, we may create a path
1406         * with multiple consecutive backslashes, which for some reason causes
1407         * Windows to report that the file cannot be found.  */
1408         while (unlikely(path[path_nchars - 1] == L'\\' &&
1409                         path[path_nchars - 2] != L':'))
1410                 path[--path_nchars] = L'\0';
1411
1412         params->capture_root_nchars = path_nchars;
1413
1414         memset(&stats, 0, sizeof(stats));
1415
1416         ret = winnt_build_dentry_tree_recursive(root_ret, NULL,
1417                                                 path, path_nchars, L"", 0,
1418                                                 params, &stats, 0);
1419         FREE(path);
1420         if (ret == 0)
1421                 winnt_do_scan_warnings(root_disk_path, &stats);
1422         return ret;
1423 }
1424
1425 #endif /* __WIN32__ */