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