]> wimlib.net Git - wimlib/blob - src/win32_capture.c
header cleanups
[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 bool
825 get_data_stream_name(const wchar_t *raw_stream_name, size_t raw_stream_name_nchars,
826                      const wchar_t **stream_name_ret, size_t *stream_name_nchars_ret)
827 {
828         const wchar_t *sep, *type, *end;
829
830         /* The stream name should be returned as :NAME:TYPE  */
831         if (raw_stream_name_nchars < 1)
832                 return false;
833         if (raw_stream_name[0] != L':')
834                 return false;
835
836         raw_stream_name++;
837         raw_stream_name_nchars--;
838
839         end = raw_stream_name + raw_stream_name_nchars;
840
841         sep = wmemchr(raw_stream_name, L':', raw_stream_name_nchars);
842         if (!sep)
843                 return false;
844
845         type = sep + 1;
846         if (end - type != 5)
847                 return false;
848
849         if (wmemcmp(type, L"$DATA", 5))
850                 return false;
851
852         *stream_name_ret = raw_stream_name;
853         *stream_name_nchars_ret = sep - raw_stream_name;
854         return true;
855 }
856
857 static wchar_t *
858 build_stream_path(const wchar_t *path, size_t path_nchars,
859                   const wchar_t *stream_name, size_t stream_name_nchars)
860 {
861         size_t stream_path_nchars;
862         wchar_t *stream_path;
863         wchar_t *p;
864
865         stream_path_nchars = path_nchars;
866         if (stream_name_nchars)
867                 stream_path_nchars += 1 + stream_name_nchars;
868
869         stream_path = MALLOC((stream_path_nchars + 1) * sizeof(wchar_t));
870         if (stream_path) {
871                 p = wmempcpy(stream_path, path, path_nchars);
872                 if (stream_name_nchars) {
873                         *p++ = L':';
874                         p = wmempcpy(p, stream_name, stream_name_nchars);
875                 }
876                 *p++ = L'\0';
877         }
878         return stream_path;
879 }
880
881 static int
882 winnt_scan_stream(const wchar_t *path, size_t path_nchars,
883                   const wchar_t *raw_stream_name, size_t raw_stream_name_nchars,
884                   u64 stream_size,
885                   struct wim_inode *inode, struct list_head *unhashed_streams)
886 {
887         const wchar_t *stream_name;
888         size_t stream_name_nchars;
889         struct wim_ads_entry *ads_entry;
890         wchar_t *stream_path;
891         struct wim_lookup_table_entry *lte;
892         u32 stream_id;
893
894         /* Given the raw stream name (which is something like
895          * :streamname:$DATA), extract just the stream name part.
896          * Ignore any non-$DATA streams.  */
897         if (!get_data_stream_name(raw_stream_name, raw_stream_name_nchars,
898                                   &stream_name, &stream_name_nchars))
899                 return 0;
900
901         /* If this is a named stream, allocate an ADS entry for it.  */
902         if (stream_name_nchars) {
903                 ads_entry = inode_add_ads_utf16le(inode, stream_name,
904                                                   stream_name_nchars *
905                                                         sizeof(wchar_t));
906                 if (!ads_entry)
907                         return WIMLIB_ERR_NOMEM;
908         } else if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
909                 /* Ignore unnamed data stream of reparse point  */
910                 return 0;
911         } else {
912                 ads_entry = NULL;
913         }
914
915         /* If the stream is empty, no lookup table entry is needed. */
916         if (stream_size == 0)
917                 return 0;
918
919         /* Build the path to the stream.  For unnamed streams, this is simply
920          * the path to the file.  For named streams, this is the path to the
921          * file, followed by a colon, followed by the stream name.  */
922         stream_path = build_stream_path(path, path_nchars,
923                                         stream_name, stream_name_nchars);
924         if (!stream_path)
925                 return WIMLIB_ERR_NOMEM;
926
927         /* Set up the lookup table entry for the stream.  */
928         lte = new_lookup_table_entry();
929         if (!lte) {
930                 FREE(stream_path);
931                 return WIMLIB_ERR_NOMEM;
932         }
933         lte->file_on_disk = stream_path;
934         lte->resource_location = RESOURCE_IN_WINNT_FILE_ON_DISK;
935         lte->size = stream_size;
936         if ((inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED) && !ads_entry) {
937                 /* Special case for encrypted file.  */
938
939                 /* OpenEncryptedFileRaw() expects Win32 name, not NT name.
940                  * Change \??\ into \\?\  */
941                 lte->file_on_disk[1] = L'\\';
942                 wimlib_assert(!wmemcmp(lte->file_on_disk, L"\\\\?\\", 4));
943
944                 u64 encrypted_size;
945                 int ret;
946
947                 ret = win32_get_encrypted_file_size(lte->file_on_disk,
948                                                     &encrypted_size);
949                 if (ret) {
950                         free_lookup_table_entry(lte);
951                         return ret;
952                 }
953                 lte->size = encrypted_size;
954                 lte->resource_location = RESOURCE_WIN32_ENCRYPTED;
955         }
956
957         if (ads_entry) {
958                 stream_id = ads_entry->stream_id;
959                 ads_entry->lte = lte;
960         } else {
961                 stream_id = 0;
962                 inode->i_lte = lte;
963         }
964         lte->file_inode = inode;
965         add_unhashed_stream(lte, inode, stream_id, unhashed_streams);
966         return 0;
967 }
968
969 /*
970  * Load information about the streams of an open file into a WIM inode.
971  *
972  * We use the NtQueryInformationFile() system call instead of FindFirstStream()
973  * and FindNextStream().  This is done for two reasons:
974  *
975  * - FindFirstStream() opens its own handle to the file or directory and
976  *   apparently does so without specifying FILE_FLAG_BACKUP_SEMANTICS, thereby
977  *   causing access denied errors on certain files (even when running as the
978  *   Administrator).
979  * - FindFirstStream() and FindNextStream() is only available on Windows Vista
980  *   and later, whereas the stream support in NtQueryInformationFile() was
981  *   already present in Windows XP.
982  */
983 static int
984 winnt_scan_streams(HANDLE *hFile_p, const wchar_t *path, size_t path_nchars,
985                    struct wim_inode *inode, struct list_head *unhashed_streams,
986                    u64 file_size, u32 vol_flags)
987 {
988         int ret;
989         u8 _buf[1024] _aligned_attribute(8);
990         u8 *buf;
991         size_t bufsize;
992         IO_STATUS_BLOCK iosb;
993         NTSTATUS status;
994         const FILE_STREAM_INFORMATION *info;
995
996         buf = _buf;
997         bufsize = sizeof(_buf);
998
999         if (!(vol_flags & FILE_NAMED_STREAMS))
1000                 goto unnamed_only;
1001
1002         /* Get a buffer containing the stream information.  */
1003         while (!NT_SUCCESS(status = (*func_NtQueryInformationFile)(*hFile_p,
1004                                                                    &iosb,
1005                                                                    buf,
1006                                                                    bufsize,
1007                                                                    FileStreamInformation)))
1008         {
1009
1010                 switch (status) {
1011                 case STATUS_BUFFER_OVERFLOW:
1012                         {
1013                                 u8 *newbuf;
1014
1015                                 bufsize *= 2;
1016                                 if (buf == _buf)
1017                                         newbuf = MALLOC(bufsize);
1018                                 else
1019                                         newbuf = REALLOC(buf, bufsize);
1020                                 if (!newbuf) {
1021                                         ret = WIMLIB_ERR_NOMEM;
1022                                         goto out_free_buf;
1023                                 }
1024                                 buf = newbuf;
1025                         }
1026                         break;
1027                 case STATUS_NOT_IMPLEMENTED:
1028                 case STATUS_NOT_SUPPORTED:
1029                 case STATUS_INVALID_INFO_CLASS:
1030                         goto unnamed_only;
1031                 default:
1032                         set_errno_from_nt_status(status);
1033                         ERROR_WITH_ERRNO("\"%ls\": Failed to query stream "
1034                                          "information (status=0x%08"PRIx32")",
1035                                          printable_path(path), (u32)status);
1036                         ret = WIMLIB_ERR_READ;
1037                         goto out_free_buf;
1038                 }
1039         }
1040
1041         if (iosb.Information == 0) {
1042                 /* No stream information.  */
1043                 ret = 0;
1044                 goto out_free_buf;
1045         }
1046
1047         if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED)) {
1048                 /* OpenEncryptedFileRaw() seems to fail with
1049                  * ERROR_SHARING_VIOLATION if there are any handles opened to
1050                  * the file.  */
1051                 (*func_NtClose)(*hFile_p);
1052                 *hFile_p = INVALID_HANDLE_VALUE;
1053         }
1054
1055         /* Parse one or more stream information structures.  */
1056         info = (const FILE_STREAM_INFORMATION *)buf;
1057         for (;;) {
1058                 /* Load the stream information.  */
1059                 ret = winnt_scan_stream(path, path_nchars,
1060                                         info->StreamName,
1061                                         info->StreamNameLength / 2,
1062                                         info->StreamSize.QuadPart,
1063                                         inode, unhashed_streams);
1064                 if (ret)
1065                         goto out_free_buf;
1066
1067                 if (info->NextEntryOffset == 0) {
1068                         /* No more stream information.  */
1069                         break;
1070                 }
1071                 /* Advance to next stream information.  */
1072                 info = (const FILE_STREAM_INFORMATION *)
1073                                 ((const u8 *)info + info->NextEntryOffset);
1074         }
1075         ret = 0;
1076         goto out_free_buf;
1077
1078 unnamed_only:
1079         /* The volume does not support named streams.  Only capture the unnamed
1080          * data stream.  */
1081         if (inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
1082                                    FILE_ATTRIBUTE_REPARSE_POINT))
1083         {
1084                 ret = 0;
1085                 goto out_free_buf;
1086         }
1087
1088         ret = winnt_scan_stream(path, path_nchars, L"::$DATA", 7,
1089                                 file_size, inode, unhashed_streams);
1090 out_free_buf:
1091         /* Free buffer if allocated on heap.  */
1092         if (unlikely(buf != _buf))
1093                 FREE(buf);
1094         return ret;
1095 }
1096
1097 static int
1098 winnt_build_dentry_tree_recursive(struct wim_dentry **root_ret,
1099                                   HANDLE cur_dir,
1100                                   wchar_t *full_path,
1101                                   size_t full_path_nchars,
1102                                   const wchar_t *filename,
1103                                   size_t filename_nchars,
1104                                   struct capture_params *params,
1105                                   struct winnt_scan_stats *stats,
1106                                   u32 vol_flags)
1107 {
1108         struct wim_dentry *root = NULL;
1109         struct wim_inode *inode = NULL;
1110         HANDLE h = INVALID_HANDLE_VALUE;
1111         int ret;
1112         NTSTATUS status;
1113         FILE_ALL_INFORMATION file_info;
1114         u8 *rpbuf;
1115         u16 rpbuflen;
1116         u16 not_rpfixed;
1117
1118         ret = try_exclude(full_path, full_path_nchars, params);
1119         if (ret < 0) /* Excluded? */
1120                 goto out_progress;
1121         if (ret > 0) /* Error? */
1122                 goto out;
1123
1124         /* Open the file.  */
1125         status = winnt_openat(cur_dir,
1126                               (cur_dir ? filename : full_path),
1127                               (cur_dir ? filename_nchars : full_path_nchars),
1128                               FILE_READ_DATA |
1129                                         FILE_READ_ATTRIBUTES |
1130                                         READ_CONTROL |
1131                                         ACCESS_SYSTEM_SECURITY |
1132                                         SYNCHRONIZE,
1133                               &h);
1134         if (unlikely(!NT_SUCCESS(status))) {
1135                 if (status == STATUS_DELETE_PENDING) {
1136                         WARNING("\"%ls\": Deletion pending; skipping file",
1137                                 printable_path(full_path));
1138                         ret = 0;
1139                 } else {
1140                         set_errno_from_nt_status(status);
1141                         ERROR_WITH_ERRNO("\"%ls\": Can't open file "
1142                                          "(status=0x%08"PRIx32")",
1143                                          printable_path(full_path), (u32)status);
1144                         if (status == STATUS_FVE_LOCKED_VOLUME)
1145                                 ret = WIMLIB_ERR_FVE_LOCKED_VOLUME;
1146                         else
1147                                 ret = WIMLIB_ERR_OPEN;
1148                 }
1149                 /* XXX: Provide option to exclude files that fail with
1150                  * STATUS_SHARING_VIOLATION?  */
1151                 goto out;
1152         }
1153
1154         /* Get information about the file.  */
1155         {
1156                 IO_STATUS_BLOCK iosb;
1157
1158                 status = (*func_NtQueryInformationFile)(h, &iosb,
1159                                                         &file_info,
1160                                                         sizeof(file_info),
1161                                                         FileAllInformation);
1162
1163                 if (unlikely(!NT_SUCCESS(status) &&
1164                              status != STATUS_BUFFER_OVERFLOW))
1165                 {
1166                         set_errno_from_nt_status(status);
1167                         ERROR_WITH_ERRNO("\"%ls\": Can't get file information "
1168                                          "(status=0x%08"PRIx32")",
1169                                          printable_path(full_path), (u32)status);
1170                         ret = WIMLIB_ERR_STAT;
1171                         goto out;
1172                 }
1173         }
1174
1175         if (unlikely(!cur_dir)) {
1176
1177                 /* Root of tree being captured; get volume information.  */
1178
1179                 FILE_FS_ATTRIBUTE_INFORMATION attr_info;
1180                 FILE_FS_VOLUME_INFORMATION vol_info;
1181                 IO_STATUS_BLOCK iosb;
1182
1183                 /* Get volume flags  */
1184                 status = (*func_NtQueryVolumeInformationFile)(h, &iosb,
1185                                                               &attr_info,
1186                                                               sizeof(attr_info),
1187                                                               FileFsAttributeInformation);
1188                 if (likely((NT_SUCCESS(status) ||
1189                             (status == STATUS_BUFFER_OVERFLOW)) &&
1190                            (iosb.Information >=
1191                                 offsetof(FILE_FS_ATTRIBUTE_INFORMATION,
1192                                          FileSystemAttributes) +
1193                                 sizeof(attr_info.FileSystemAttributes))))
1194                 {
1195                         vol_flags = attr_info.FileSystemAttributes;
1196                 } else {
1197                         set_errno_from_nt_status(status);
1198                         WARNING_WITH_ERRNO("\"%ls\": Can't get volume attributes "
1199                                            "(status=0x%08"PRIx32")",
1200                                            printable_path(full_path),
1201                                            (u32)status);
1202                         vol_flags = 0;
1203                 }
1204
1205                 /* Set inode number of root directory  */
1206                 params->capture_root_ino =
1207                         file_info.InternalInformation.IndexNumber.QuadPart;
1208
1209                 /* Get volume ID.  */
1210                 status = (*func_NtQueryVolumeInformationFile)(h, &iosb,
1211                                                               &vol_info,
1212                                                               sizeof(vol_info),
1213                                                               FileFsVolumeInformation);
1214                 if (likely((NT_SUCCESS(status) ||
1215                             (status == STATUS_BUFFER_OVERFLOW)) &&
1216                            (iosb.Information >=
1217                                 offsetof(FILE_FS_VOLUME_INFORMATION,
1218                                          VolumeSerialNumber) +
1219                                 sizeof(vol_info.VolumeSerialNumber))))
1220                 {
1221                         params->capture_root_dev = vol_info.VolumeSerialNumber;
1222                 } else {
1223                         set_errno_from_nt_status(status);
1224                         WARNING_WITH_ERRNO("\"%ls\": Can't get volume ID "
1225                                            "(status=0x%08"PRIx32")",
1226                                            printable_path(full_path),
1227                                            (u32)status);
1228                         params->capture_root_dev = 0;
1229                 }
1230         }
1231
1232         /* If this is a reparse point, read the reparse data.  */
1233         if (unlikely(file_info.BasicInformation.FileAttributes &
1234                      FILE_ATTRIBUTE_REPARSE_POINT))
1235         {
1236                 rpbuf = alloca(REPARSE_POINT_MAX_SIZE);
1237                 ret = winnt_get_reparse_data(h, full_path, params,
1238                                              rpbuf, &rpbuflen);
1239                 switch (ret) {
1240                 case RP_FIXED:
1241                         not_rpfixed = 0;
1242                         break;
1243                 case RP_NOT_FIXED:
1244                         not_rpfixed = 1;
1245                         break;
1246                 default:
1247                         ERROR_WITH_ERRNO("\"%ls\": Can't get reparse data",
1248                                          printable_path(full_path));
1249                         goto out;
1250                 }
1251         }
1252
1253         /* Create a WIM dentry with an associated inode, which may be shared.
1254          *
1255          * However, we need to explicitly check for directories and files with
1256          * only 1 link and refuse to hard link them.  This is because Windows
1257          * has a bug where it can return duplicate File IDs for files and
1258          * directories on the FAT filesystem.
1259          *
1260          * Since we don't follow mount points on Windows, we don't need to query
1261          * the volume ID per-file.  Just once, for the root, is enough.  But we
1262          * can't simply pass 0, because then there could be inode collisions
1263          * among multiple calls to win32_build_dentry_tree() that are scanning
1264          * files on different volumes.  */
1265         ret = inode_table_new_dentry(params->inode_table,
1266                                      filename,
1267                                      file_info.InternalInformation.IndexNumber.QuadPart,
1268                                      params->capture_root_dev,
1269                                      (file_info.StandardInformation.NumberOfLinks <= 1 ||
1270                                         (file_info.BasicInformation.FileAttributes &
1271                                          FILE_ATTRIBUTE_DIRECTORY)),
1272                                      &root);
1273         if (ret)
1274                 goto out;
1275
1276         /* Get the short (DOS) name of the file.  */
1277         status = winnt_get_short_name(h, root);
1278
1279         /* If we can't read the short filename for any reason other than
1280          * out-of-memory, just ignore the error and assume the file has no short
1281          * name.  This shouldn't be an issue, since the short names are
1282          * essentially obsolete anyway.  */
1283         if (unlikely(status == STATUS_NO_MEMORY)) {
1284                 ret = WIMLIB_ERR_NOMEM;
1285                 goto out;
1286         }
1287
1288         inode = root->d_inode;
1289
1290         if (inode->i_nlink > 1) {
1291                 /* Shared inode (hard link); skip reading per-inode information.
1292                  */
1293                 goto out_progress;
1294         }
1295
1296         inode->i_attributes = file_info.BasicInformation.FileAttributes;
1297         inode->i_creation_time = file_info.BasicInformation.CreationTime.QuadPart;
1298         inode->i_last_write_time = file_info.BasicInformation.LastWriteTime.QuadPart;
1299         inode->i_last_access_time = file_info.BasicInformation.LastAccessTime.QuadPart;
1300         inode->i_resolved = 1;
1301
1302         /* Get the file's security descriptor, unless we are capturing in
1303          * NO_ACLS mode or the volume does not support security descriptors.  */
1304         if (!(params->add_flags & WIMLIB_ADD_FLAG_NO_ACLS)
1305             && (vol_flags & FILE_PERSISTENT_ACLS))
1306         {
1307                 status = winnt_get_security_descriptor(h, inode,
1308                                                        params->sd_set, stats,
1309                                                        params->add_flags);
1310                 if (!NT_SUCCESS(status)) {
1311                         set_errno_from_nt_status(status);
1312                         ERROR_WITH_ERRNO("\"%ls\": Can't read security "
1313                                          "descriptor (status=0x%08"PRIx32")",
1314                                          printable_path(full_path),
1315                                          (u32)status);
1316                         ret = WIMLIB_ERR_STAT;
1317                         goto out;
1318                 }
1319         }
1320
1321         /* Load information about the unnamed data stream and any named data
1322          * streams.  */
1323         ret = winnt_scan_streams(&h,
1324                                  full_path,
1325                                  full_path_nchars,
1326                                  inode,
1327                                  params->unhashed_streams,
1328                                  file_info.StandardInformation.EndOfFile.QuadPart,
1329                                  vol_flags);
1330         if (ret)
1331                 goto out;
1332
1333         if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
1334
1335                 /* Reparse point: set the reparse data (already read).  */
1336
1337                 inode->i_not_rpfixed = not_rpfixed;
1338                 inode->i_reparse_tag = le32_to_cpu(*(le32*)rpbuf);
1339                 ret = inode_set_unnamed_stream(inode, rpbuf + 8, rpbuflen - 8,
1340                                                params->lookup_table);
1341                 if (ret)
1342                         goto out;
1343         } else if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1344
1345                 /* Directory: recurse to children.  */
1346
1347                 if (unlikely(h == INVALID_HANDLE_VALUE)) {
1348                         /* Re-open handle that was closed to read raw encrypted
1349                          * data.  */
1350                         status = winnt_openat(cur_dir,
1351                                               (cur_dir ?
1352                                                filename : full_path),
1353                                               (cur_dir ?
1354                                                filename_nchars : full_path_nchars),
1355                                               FILE_LIST_DIRECTORY | SYNCHRONIZE,
1356                                               &h);
1357                         if (!NT_SUCCESS(status)) {
1358                                 set_errno_from_nt_status(status);
1359                                 ERROR_WITH_ERRNO("\"%ls\": Can't re-open file "
1360                                                  "(status=0x%08"PRIx32")",
1361                                                  printable_path(full_path),
1362                                                  (u32)status);
1363                                 ret = WIMLIB_ERR_OPEN;
1364                                 goto out;
1365                         }
1366                 }
1367                 ret = winnt_recurse_directory(h,
1368                                               full_path,
1369                                               full_path_nchars,
1370                                               root,
1371                                               params,
1372                                               stats,
1373                                               vol_flags);
1374                 if (ret)
1375                         goto out;
1376         }
1377
1378 out_progress:
1379         params->progress.scan.cur_path = printable_path(full_path);
1380         if (likely(root))
1381                 ret = do_capture_progress(params, WIMLIB_SCAN_DENTRY_OK, inode);
1382         else
1383                 ret = do_capture_progress(params, WIMLIB_SCAN_DENTRY_EXCLUDED, NULL);
1384 out:
1385         if (likely(h != INVALID_HANDLE_VALUE))
1386                 (*func_NtClose)(h);
1387         if (unlikely(ret)) {
1388                 free_dentry_tree(root, params->lookup_table);
1389                 root = NULL;
1390                 ret = report_capture_error(params, ret, full_path);
1391         }
1392         *root_ret = root;
1393         return ret;
1394 }
1395
1396 static void
1397 winnt_do_scan_warnings(const wchar_t *path, const struct winnt_scan_stats *stats)
1398 {
1399         if (likely(stats->num_get_sacl_priv_notheld == 0 &&
1400                    stats->num_get_sd_access_denied == 0))
1401                 return;
1402
1403         WARNING("Scan of \"%ls\" complete, but with one or more warnings:", path);
1404         if (stats->num_get_sacl_priv_notheld != 0) {
1405                 WARNING("- Could not capture SACL (System Access Control List)\n"
1406                         "            on %lu files or directories.",
1407                         stats->num_get_sacl_priv_notheld);
1408         }
1409         if (stats->num_get_sd_access_denied != 0) {
1410                 WARNING("- Could not capture security descriptor at all\n"
1411                         "            on %lu files or directories.",
1412                         stats->num_get_sd_access_denied);
1413         }
1414         WARNING("To fully capture all security descriptors, run the program\n"
1415                 "          with Administrator rights.");
1416 }
1417
1418 #define WINDOWS_NT_MAX_PATH 32768
1419
1420 /* Win32 version of capturing a directory tree.  */
1421 int
1422 win32_build_dentry_tree(struct wim_dentry **root_ret,
1423                         const wchar_t *root_disk_path,
1424                         struct capture_params *params)
1425 {
1426         wchar_t *path;
1427         int ret;
1428         UNICODE_STRING ntpath;
1429         struct winnt_scan_stats stats;
1430         size_t ntpath_nchars;
1431
1432         /* WARNING: There is no check for overflow later when this buffer is
1433          * being used!  But it's as long as the maximum path length understood
1434          * by Windows NT (which is NOT the same as MAX_PATH).  */
1435         path = MALLOC((WINDOWS_NT_MAX_PATH + 1) * sizeof(wchar_t));
1436         if (!path)
1437                 return WIMLIB_ERR_NOMEM;
1438
1439         ret = win32_path_to_nt_path(root_disk_path, &ntpath);
1440         if (ret)
1441                 goto out_free_path;
1442
1443         if (ntpath.Length < 4 * sizeof(wchar_t) ||
1444             ntpath.Length > WINDOWS_NT_MAX_PATH * sizeof(wchar_t) ||
1445             wmemcmp(ntpath.Buffer, L"\\??\\", 4))
1446         {
1447                 ERROR("\"%ls\": unrecognized path format", root_disk_path);
1448                 ret = WIMLIB_ERR_INVALID_PARAM;
1449         } else {
1450                 ntpath_nchars = ntpath.Length / sizeof(wchar_t);
1451                 wmemcpy(path, ntpath.Buffer, ntpath_nchars);
1452                 path[ntpath_nchars] = L'\0';
1453
1454                 params->capture_root_nchars = ntpath_nchars;
1455                 if (path[ntpath_nchars - 1] == L'\\')
1456                         params->capture_root_nchars--;
1457                 ret = 0;
1458         }
1459         HeapFree(GetProcessHeap(), 0, ntpath.Buffer);
1460         if (ret)
1461                 goto out_free_path;
1462
1463         memset(&stats, 0, sizeof(stats));
1464
1465         ret = winnt_build_dentry_tree_recursive(root_ret, NULL,
1466                                                 path, ntpath_nchars,
1467                                                 L"", 0, params, &stats, 0);
1468 out_free_path:
1469         FREE(path);
1470         if (ret == 0)
1471                 winnt_do_scan_warnings(root_disk_path, &stats);
1472         return ret;
1473 }
1474
1475 #endif /* __WIN32__ */