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