]> wimlib.net Git - wimlib/blob - src/win32_capture.c
system compression: force XPRESS4K on files accessed by Windows bootloader
[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 noinline_for_stack 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->d_short_name = utf16le_dupz(info->FileName,
252                                                     info->FileNameLength);
253                 if (!dentry->d_short_name)
254                         return STATUS_NO_MEMORY;
255                 dentry->d_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 noinline_for_stack 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 (!should_ignore_filename(info->FileName,
419                                                     info->FileNameLength / 2))
420                         {
421                                 wchar_t *p;
422                                 wchar_t *filename;
423                                 struct wim_dentry *child;
424
425                                 p = full_path + full_path_nchars;
426                                 /* Only add a backslash if we don't already have
427                                  * one.  This prevents a duplicate backslash
428                                  * from being added when the path to the capture
429                                  * dir had a trailing backslash.  */
430                                 if (*(p - 1) != L'\\')
431                                         *p++ = L'\\';
432                                 filename = p;
433                                 p = wmempcpy(filename, info->FileName,
434                                              info->FileNameLength / 2);
435                                 *p = '\0';
436
437                                 ret = winnt_build_dentry_tree_recursive(
438                                                         &child,
439                                                         h,
440                                                         full_path,
441                                                         p - full_path,
442                                                         filename,
443                                                         info->FileNameLength / 2,
444                                                         params,
445                                                         stats,
446                                                         vol_flags);
447
448                                 full_path[full_path_nchars] = L'\0';
449
450                                 if (ret)
451                                         goto out_free_buf;
452                                 attach_scanned_tree(parent, child, params->blob_table);
453                         }
454                         if (info->NextEntryOffset == 0)
455                                 break;
456                         info = (const FILE_NAMES_INFORMATION *)
457                                         ((const u8 *)info + info->NextEntryOffset);
458                 }
459         }
460
461         if (unlikely(status != STATUS_NO_MORE_FILES)) {
462                 winnt_error(status, L"\"%ls\": Can't read directory",
463                             printable_path(full_path));
464                 ret = WIMLIB_ERR_READ;
465         }
466 out_free_buf:
467         FREE(buf);
468         return ret;
469 }
470
471 /* Reparse point fixup status code  */
472 #define RP_FIXED        (-1)
473
474 static bool
475 file_has_ino_and_dev(HANDLE h, u64 ino, u64 dev)
476 {
477         NTSTATUS status;
478         IO_STATUS_BLOCK iosb;
479         FILE_INTERNAL_INFORMATION int_info;
480         FILE_FS_VOLUME_INFORMATION vol_info;
481
482         status = (*func_NtQueryInformationFile)(h, &iosb,
483                                                 &int_info, sizeof(int_info),
484                                                 FileInternalInformation);
485         if (!NT_SUCCESS(status))
486                 return false;
487
488         if (int_info.IndexNumber.QuadPart != ino)
489                 return false;
490
491         status = (*func_NtQueryVolumeInformationFile)(h, &iosb,
492                                                       &vol_info, sizeof(vol_info),
493                                                       FileFsVolumeInformation);
494         if (!(NT_SUCCESS(status) || status == STATUS_BUFFER_OVERFLOW))
495                 return false;
496
497         if (iosb.Information <
498              offsetof(FILE_FS_VOLUME_INFORMATION, VolumeSerialNumber) +
499              sizeof(vol_info.VolumeSerialNumber))
500                 return false;
501
502         return (vol_info.VolumeSerialNumber == dev);
503 }
504
505 /*
506  * This is the Windows equivalent of unix_relativize_link_target(); see there
507  * for general details.  This version works with an "absolute" Windows link
508  * target, specified from the root of the Windows kernel object namespace.  Note
509  * that we have to open directories with a trailing slash when present because
510  * \??\E: opens the E: device itself and not the filesystem root directory.
511  */
512 static const wchar_t *
513 winnt_relativize_link_target(const wchar_t *target, size_t target_nbytes,
514                              u64 ino, u64 dev)
515 {
516         UNICODE_STRING name;
517         OBJECT_ATTRIBUTES attr;
518         IO_STATUS_BLOCK iosb;
519         NTSTATUS status;
520         const wchar_t *target_end;
521         const wchar_t *p;
522
523         target_end = target + (target_nbytes / sizeof(wchar_t));
524
525         /* Empty path??? */
526         if (target_end == target)
527                 return target;
528
529         /* No leading slash???  */
530         if (target[0] != L'\\')
531                 return target;
532
533         /* UNC path???  */
534         if ((target_end - target) >= 2 &&
535             target[0] == L'\\' && target[1] == L'\\')
536                 return target;
537
538         attr.Length = sizeof(attr);
539         attr.RootDirectory = NULL;
540         attr.ObjectName = &name;
541         attr.Attributes = 0;
542         attr.SecurityDescriptor = NULL;
543         attr.SecurityQualityOfService = NULL;
544
545         name.Buffer = (wchar_t *)target;
546         name.Length = 0;
547         p = target;
548         do {
549                 HANDLE h;
550                 const wchar_t *orig_p = p;
551
552                 /* Skip non-backslashes  */
553                 while (p != target_end && *p != L'\\')
554                         p++;
555
556                 /* Skip backslashes  */
557                 while (p != target_end && *p == L'\\')
558                         p++;
559
560                 /* Append path component  */
561                 name.Length += (p - orig_p) * sizeof(wchar_t);
562                 name.MaximumLength = name.Length;
563
564                 /* Try opening the file  */
565                 status = (*func_NtOpenFile) (&h,
566                                              FILE_READ_ATTRIBUTES | FILE_TRAVERSE,
567                                              &attr,
568                                              &iosb,
569                                              FILE_SHARE_VALID_FLAGS,
570                                              FILE_OPEN_FOR_BACKUP_INTENT);
571
572                 if (NT_SUCCESS(status)) {
573                         /* Reset root directory  */
574                         if (attr.RootDirectory)
575                                 (*func_NtClose)(attr.RootDirectory);
576                         attr.RootDirectory = h;
577                         name.Buffer = (wchar_t *)p;
578                         name.Length = 0;
579
580                         if (file_has_ino_and_dev(h, ino, dev))
581                                 goto out_close_root_dir;
582                 }
583         } while (p != target_end);
584
585         p = target;
586
587 out_close_root_dir:
588         if (attr.RootDirectory)
589                 (*func_NtClose)(attr.RootDirectory);
590         while (p > target && *(p - 1) == L'\\')
591                 p--;
592         return p;
593 }
594
595 static int
596 winnt_rpfix_progress(struct capture_params *params, const wchar_t *path,
597                      const struct link_reparse_point *link, int scan_status)
598 {
599         size_t print_name_nchars = link->print_name_nbytes / sizeof(wchar_t);
600         wchar_t print_name0[print_name_nchars + 1];
601
602         wmemcpy(print_name0, link->print_name, print_name_nchars);
603         print_name0[print_name_nchars] = L'\0';
604
605         params->progress.scan.cur_path = printable_path(path);
606         params->progress.scan.symlink_target = print_name0;
607         return do_capture_progress(params, scan_status, NULL);
608 }
609
610 static int
611 winnt_try_rpfix(struct reparse_buffer_disk *rpbuf, u16 *rpbuflen_p,
612                 const wchar_t *path, struct capture_params *params)
613 {
614         struct link_reparse_point link;
615         const wchar_t *rel_target;
616         int ret;
617
618         if (parse_link_reparse_point(rpbuf, *rpbuflen_p, &link)) {
619                 /* Couldn't understand the reparse data; don't do the fixup.  */
620                 return 0;
621         }
622
623         /*
624          * Don't do reparse point fixups on relative symbolic links.
625          *
626          * On Windows, a relative symbolic link is supposed to be identifiable
627          * by having reparse tag WIM_IO_REPARSE_TAG_SYMLINK and flags
628          * SYMBOLIC_LINK_RELATIVE.  We will use this information, although this
629          * may not always do what the user expects, since drive-relative
630          * symbolic links such as "\Users\Public" have SYMBOLIC_LINK_RELATIVE
631          * set, in addition to truely relative symbolic links such as "Users" or
632          * "Users\Public".  However, WIMGAPI (as of Windows 8.1) has this same
633          * behavior.
634          *
635          * Otherwise, as far as I can tell, the targets of symbolic links that
636          * are NOT relative, as well as junctions (note: a mountpoint is the
637          * sames thing as a junction), must be NT namespace paths, for example:
638          *
639          *     - \??\e:\Users\Public
640          *     - \DosDevices\e:\Users\Public
641          *     - \Device\HardDiskVolume4\Users\Public
642          *     - \??\Volume{c47cb07c-946e-4155-b8f7-052e9cec7628}\Users\Public
643          *     - \DosDevices\Volume{c47cb07c-946e-4155-b8f7-052e9cec7628}\Users\Public
644          */
645         if (link_is_relative_symlink(&link))
646                 return 0;
647
648         rel_target = winnt_relativize_link_target(link.substitute_name,
649                                                   link.substitute_name_nbytes,
650                                                   params->capture_root_ino,
651                                                   params->capture_root_dev);
652
653         if (rel_target == link.substitute_name) {
654                 /* Target points outside of the tree being captured or had an
655                  * unrecognized path format.  Don't adjust it.  */
656                 return winnt_rpfix_progress(params, path, &link,
657                                             WIMLIB_SCAN_DENTRY_NOT_FIXED_SYMLINK);
658         }
659
660         /* We have an absolute target pointing within the directory being
661          * captured. @rel_target is the suffix of the link target that is the
662          * part relative to the directory being captured.
663          *
664          * We will cut off the prefix before this part (which is the path to the
665          * directory being captured) and add a dummy prefix.  Since the process
666          * will need to be reversed when applying the image, it doesn't matter
667          * what exactly the prefix is, as long as it looks like an absolute
668          * path.  */
669
670         static const wchar_t prefix[6] = L"\\??\\X:";
671         static const size_t num_unprintable_chars = 4;
672
673         size_t rel_target_nbytes =
674                 link.substitute_name_nbytes - ((const u8 *)rel_target -
675                                                (const u8 *)link.substitute_name);
676
677         wchar_t tmp[(sizeof(prefix) + rel_target_nbytes) / sizeof(wchar_t)];
678
679         memcpy(tmp, prefix, sizeof(prefix));
680         memcpy(tmp + ARRAY_LEN(prefix), rel_target, rel_target_nbytes);
681
682         link.substitute_name = tmp;
683         link.substitute_name_nbytes = sizeof(tmp);
684
685         link.print_name = link.substitute_name + num_unprintable_chars;
686         link.print_name_nbytes = link.substitute_name_nbytes -
687                                  (num_unprintable_chars * sizeof(wchar_t));
688
689         if (make_link_reparse_point(&link, rpbuf, rpbuflen_p))
690                 return 0;
691
692         ret = winnt_rpfix_progress(params, path, &link,
693                                    WIMLIB_SCAN_DENTRY_FIXED_SYMLINK);
694         if (ret)
695                 return ret;
696         return RP_FIXED;
697 }
698
699 /* Load the reparse data of a file into the corresponding WIM inode.  If the
700  * reparse point is a symbolic link or junction with an absolute target and
701  * RPFIX mode is enabled, then also rewrite its target to be relative to the
702  * capture root.  */
703 static noinline_for_stack int
704 winnt_load_reparse_data(HANDLE h, struct wim_inode *inode,
705                         const wchar_t *full_path, struct capture_params *params)
706 {
707         struct reparse_buffer_disk rpbuf;
708         DWORD bytes_returned;
709         u16 rpbuflen;
710         int ret;
711
712         if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED) {
713                 /* See comment above assign_stream_types_encrypted()  */
714                 WARNING("Ignoring reparse data of encrypted file \"%ls\"",
715                         printable_path(full_path));
716                 return 0;
717         }
718
719         if (!DeviceIoControl(h, FSCTL_GET_REPARSE_POINT,
720                              NULL, 0, &rpbuf, REPARSE_POINT_MAX_SIZE,
721                              &bytes_returned, NULL))
722         {
723                 win32_error(GetLastError(), L"\"%ls\": Can't get reparse point",
724                             printable_path(full_path));
725                 return WIMLIB_ERR_READLINK;
726         }
727
728         rpbuflen = bytes_returned;
729
730         if (unlikely(rpbuflen < REPARSE_DATA_OFFSET)) {
731                 ERROR("\"%ls\": reparse point buffer is too short",
732                       printable_path(full_path));
733                 return WIMLIB_ERR_INVALID_REPARSE_DATA;
734         }
735
736         if (params->add_flags & WIMLIB_ADD_FLAG_RPFIX) {
737                 ret = winnt_try_rpfix(&rpbuf, &rpbuflen, full_path, params);
738                 if (ret == RP_FIXED)
739                         inode->i_rp_flags &= ~WIM_RP_FLAG_NOT_FIXED;
740                 else if (ret)
741                         return ret;
742         }
743
744         inode->i_reparse_tag = le32_to_cpu(rpbuf.rptag);
745         inode->i_rp_reserved = le16_to_cpu(rpbuf.rpreserved);
746
747         if (!inode_add_stream_with_data(inode,
748                                         STREAM_TYPE_REPARSE_POINT,
749                                         NO_STREAM_NAME,
750                                         rpbuf.rpdata,
751                                         rpbuflen - REPARSE_DATA_OFFSET,
752                                         params->blob_table))
753                 return WIMLIB_ERR_NOMEM;
754
755         return 0;
756 }
757
758 static DWORD WINAPI
759 win32_tally_encrypted_size_cb(unsigned char *_data, void *_size_ret,
760                               unsigned long len)
761 {
762         *(u64*)_size_ret += len;
763         return ERROR_SUCCESS;
764 }
765
766 static int
767 win32_get_encrypted_file_size(const wchar_t *path, bool is_dir, u64 *size_ret)
768 {
769         DWORD err;
770         void *file_ctx;
771         int ret;
772         DWORD flags = 0;
773
774         if (is_dir)
775                 flags |= CREATE_FOR_DIR;
776
777         err = OpenEncryptedFileRaw(path, flags, &file_ctx);
778         if (err != ERROR_SUCCESS) {
779                 win32_error(err,
780                             L"Failed to open encrypted file \"%ls\" for raw read",
781                             printable_path(path));
782                 return WIMLIB_ERR_OPEN;
783         }
784         *size_ret = 0;
785         err = ReadEncryptedFileRaw(win32_tally_encrypted_size_cb,
786                                    size_ret, file_ctx);
787         if (err != ERROR_SUCCESS) {
788                 win32_error(err,
789                             L"Failed to read raw encrypted data from \"%ls\"",
790                             printable_path(path));
791                 ret = WIMLIB_ERR_READ;
792         } else {
793                 ret = 0;
794         }
795         CloseEncryptedFileRaw(file_ctx);
796         return ret;
797 }
798
799 static int
800 winnt_scan_efsrpc_raw_data(struct wim_inode *inode, const wchar_t *nt_path,
801                            struct list_head *unhashed_blobs)
802 {
803         struct blob_descriptor *blob;
804         struct wim_inode_stream *strm;
805         int ret;
806
807         blob = new_blob_descriptor();
808         if (!blob)
809                 goto err_nomem;
810
811         blob->file_on_disk = WCSDUP(nt_path);
812         if (!blob->file_on_disk)
813                 goto err_nomem;
814         blob->blob_location = BLOB_WIN32_ENCRYPTED;
815
816         /* OpenEncryptedFileRaw() expects a Win32 name.  */
817         wimlib_assert(!wmemcmp(blob->file_on_disk, L"\\??\\", 4));
818         blob->file_on_disk[1] = L'\\';
819
820         blob->file_inode = inode;
821
822         ret = win32_get_encrypted_file_size(blob->file_on_disk,
823                                             (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY),
824                                             &blob->size);
825         if (ret)
826                 goto err;
827
828         /* Empty EFSRPC data does not make sense  */
829         wimlib_assert(blob->size != 0);
830
831         strm = inode_add_stream(inode, STREAM_TYPE_EFSRPC_RAW_DATA,
832                                 NO_STREAM_NAME, blob);
833         if (!strm)
834                 goto err_nomem;
835
836         prepare_unhashed_blob(blob, inode, strm->stream_id, unhashed_blobs);
837         return 0;
838
839 err_nomem:
840         ret = WIMLIB_ERR_NOMEM;
841 err:
842         free_blob_descriptor(blob);
843         return ret;
844 }
845
846 static bool
847 get_data_stream_name(wchar_t *raw_stream_name, size_t raw_stream_name_nchars,
848                      wchar_t **stream_name_ret, size_t *stream_name_nchars_ret)
849 {
850         const wchar_t *sep, *type, *end;
851
852         /* The stream name should be returned as :NAME:TYPE  */
853         if (raw_stream_name_nchars < 1)
854                 return false;
855         if (raw_stream_name[0] != L':')
856                 return false;
857
858         raw_stream_name++;
859         raw_stream_name_nchars--;
860
861         end = raw_stream_name + raw_stream_name_nchars;
862
863         sep = wmemchr(raw_stream_name, L':', raw_stream_name_nchars);
864         if (!sep)
865                 return false;
866
867         type = sep + 1;
868         if (end - type != 5)
869                 return false;
870
871         if (wmemcmp(type, L"$DATA", 5))
872                 return false;
873
874         *stream_name_ret = raw_stream_name;
875         *stream_name_nchars_ret = sep - raw_stream_name;
876         return true;
877 }
878
879 /* Build the path to the data stream.  For unnamed streams, this is simply the
880  * path to the file.  For named streams, this is the path to the file, followed
881  * by a colon, followed by the stream name.  */
882 static wchar_t *
883 build_data_stream_path(const wchar_t *path, size_t path_nchars,
884                        const wchar_t *stream_name, size_t stream_name_nchars)
885 {
886         size_t stream_path_nchars;
887         wchar_t *stream_path;
888         wchar_t *p;
889
890         stream_path_nchars = path_nchars;
891         if (stream_name_nchars)
892                 stream_path_nchars += 1 + stream_name_nchars;
893
894         stream_path = MALLOC((stream_path_nchars + 1) * sizeof(wchar_t));
895         if (stream_path) {
896                 p = wmempcpy(stream_path, path, path_nchars);
897                 if (stream_name_nchars) {
898                         *p++ = L':';
899                         p = wmempcpy(p, stream_name, stream_name_nchars);
900                 }
901                 *p++ = L'\0';
902         }
903         return stream_path;
904 }
905
906 static int
907 winnt_scan_data_stream(const wchar_t *path, size_t path_nchars,
908                        wchar_t *raw_stream_name, size_t raw_stream_name_nchars,
909                        u64 stream_size,
910                        struct wim_inode *inode, struct list_head *unhashed_blobs)
911 {
912         wchar_t *stream_name;
913         size_t stream_name_nchars;
914         struct blob_descriptor *blob;
915         struct wim_inode_stream *strm;
916
917         /* Given the raw stream name (which is something like
918          * :streamname:$DATA), extract just the stream name part (streamname).
919          * Ignore any non-$DATA streams.  */
920         if (!get_data_stream_name(raw_stream_name, raw_stream_name_nchars,
921                                   &stream_name, &stream_name_nchars))
922                 return 0;
923
924         stream_name[stream_name_nchars] = L'\0';
925
926         /* If the stream is non-empty, set up a blob descriptor for it.  */
927         if (stream_size != 0) {
928                 blob = new_blob_descriptor();
929                 if (!blob)
930                         goto err_nomem;
931                 blob->file_on_disk = build_data_stream_path(path,
932                                                             path_nchars,
933                                                             stream_name,
934                                                             stream_name_nchars);
935                 if (!blob->file_on_disk)
936                         goto err_nomem;
937                 blob->blob_location = BLOB_IN_WINNT_FILE_ON_DISK;
938                 blob->size = stream_size;
939                 blob->file_inode = inode;
940         } else {
941                 blob = NULL;
942         }
943
944         strm = inode_add_stream(inode, STREAM_TYPE_DATA, stream_name, blob);
945         if (!strm)
946                 goto err_nomem;
947
948         prepare_unhashed_blob(blob, inode, strm->stream_id, unhashed_blobs);
949         return 0;
950
951 err_nomem:
952         free_blob_descriptor(blob);
953         return WIMLIB_ERR_NOMEM;
954 }
955
956 /*
957  * Load information about the data streams of an open file into a WIM inode.
958  *
959  * We use the NtQueryInformationFile() system call instead of FindFirstStream()
960  * and FindNextStream().  This is done for two reasons:
961  *
962  * - FindFirstStream() opens its own handle to the file or directory and
963  *   apparently does so without specifying FILE_FLAG_BACKUP_SEMANTICS, thereby
964  *   causing access denied errors on certain files (even when running as the
965  *   Administrator).
966  * - FindFirstStream() and FindNextStream() is only available on Windows Vista
967  *   and later, whereas the stream support in NtQueryInformationFile() was
968  *   already present in Windows XP.
969  */
970 static noinline_for_stack int
971 winnt_scan_data_streams(HANDLE h, const wchar_t *path, size_t path_nchars,
972                         struct wim_inode *inode, struct list_head *unhashed_blobs,
973                         u64 file_size, u32 vol_flags)
974 {
975         int ret;
976         u8 _buf[4096] _aligned_attribute(8);
977         u8 *buf;
978         size_t bufsize;
979         IO_STATUS_BLOCK iosb;
980         NTSTATUS status;
981         FILE_STREAM_INFORMATION *info;
982
983         buf = _buf;
984         bufsize = sizeof(_buf);
985
986         if (!(vol_flags & FILE_NAMED_STREAMS))
987                 goto unnamed_only;
988
989         /* Get a buffer containing the stream information.  */
990         while (!NT_SUCCESS(status = (*func_NtQueryInformationFile)(h,
991                                                                    &iosb,
992                                                                    buf,
993                                                                    bufsize,
994                                                                    FileStreamInformation)))
995         {
996
997                 switch (status) {
998                 case STATUS_BUFFER_OVERFLOW:
999                         {
1000                                 u8 *newbuf;
1001
1002                                 bufsize *= 2;
1003                                 if (buf == _buf)
1004                                         newbuf = MALLOC(bufsize);
1005                                 else
1006                                         newbuf = REALLOC(buf, bufsize);
1007                                 if (!newbuf) {
1008                                         ret = WIMLIB_ERR_NOMEM;
1009                                         goto out_free_buf;
1010                                 }
1011                                 buf = newbuf;
1012                         }
1013                         break;
1014                 case STATUS_NOT_IMPLEMENTED:
1015                 case STATUS_NOT_SUPPORTED:
1016                 case STATUS_INVALID_INFO_CLASS:
1017                         goto unnamed_only;
1018                 default:
1019                         winnt_error(status,
1020                                     L"\"%ls\": Failed to query stream information",
1021                                     printable_path(path));
1022                         ret = WIMLIB_ERR_READ;
1023                         goto out_free_buf;
1024                 }
1025         }
1026
1027         if (iosb.Information == 0) {
1028                 /* No stream information.  */
1029                 ret = 0;
1030                 goto out_free_buf;
1031         }
1032
1033         /* Parse one or more stream information structures.  */
1034         info = (FILE_STREAM_INFORMATION *)buf;
1035         for (;;) {
1036                 /* Load the stream information.  */
1037                 ret = winnt_scan_data_stream(path, path_nchars,
1038                                              info->StreamName,
1039                                              info->StreamNameLength / 2,
1040                                              info->StreamSize.QuadPart,
1041                                              inode, unhashed_blobs);
1042                 if (ret)
1043                         goto out_free_buf;
1044
1045                 if (info->NextEntryOffset == 0) {
1046                         /* No more stream information.  */
1047                         break;
1048                 }
1049                 /* Advance to next stream information.  */
1050                 info = (FILE_STREAM_INFORMATION *)
1051                                 ((u8 *)info + info->NextEntryOffset);
1052         }
1053         ret = 0;
1054         goto out_free_buf;
1055
1056 unnamed_only:
1057         /* The volume does not support named streams.  Only capture the unnamed
1058          * data stream.  */
1059         if (inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
1060                                    FILE_ATTRIBUTE_REPARSE_POINT))
1061         {
1062                 ret = 0;
1063                 goto out_free_buf;
1064         }
1065
1066         {
1067                 wchar_t stream_name[] = L"::$DATA";
1068                 ret = winnt_scan_data_stream(path, path_nchars, stream_name, 7,
1069                                              file_size, inode, unhashed_blobs);
1070         }
1071 out_free_buf:
1072         /* Free buffer if allocated on heap.  */
1073         if (unlikely(buf != _buf))
1074                 FREE(buf);
1075         return ret;
1076 }
1077
1078 static noinline_for_stack u64
1079 get_sort_key(HANDLE h)
1080 {
1081         STARTING_VCN_INPUT_BUFFER in = { .StartingVcn.QuadPart = 0 };
1082         RETRIEVAL_POINTERS_BUFFER out;
1083         DWORD bytesReturned;
1084
1085         if (!DeviceIoControl(h, FSCTL_GET_RETRIEVAL_POINTERS,
1086                              &in, sizeof(in),
1087                              &out, sizeof(out),
1088                              &bytesReturned, NULL))
1089                 return 0;
1090
1091         if (out.ExtentCount < 1)
1092                 return 0;
1093
1094         return out.Extents[0].Lcn.QuadPart;
1095 }
1096
1097 static void
1098 set_sort_key(struct wim_inode *inode, u64 sort_key)
1099 {
1100         for (unsigned i = 0; i < inode->i_num_streams; i++) {
1101                 struct wim_inode_stream *strm = &inode->i_streams[i];
1102                 struct blob_descriptor *blob = stream_blob_resolved(strm);
1103                 if (blob && (blob->blob_location == BLOB_IN_WINNT_FILE_ON_DISK ||
1104                              blob->blob_location == BLOB_WIN32_ENCRYPTED))
1105                         blob->sort_key = sort_key;
1106         }
1107 }
1108
1109 static noinline_for_stack u32
1110 get_volume_information(HANDLE h, const wchar_t *full_path,
1111                        struct capture_params *params)
1112 {
1113         FILE_FS_ATTRIBUTE_INFORMATION attr_info;
1114         FILE_FS_VOLUME_INFORMATION vol_info;
1115         IO_STATUS_BLOCK iosb;
1116         NTSTATUS status;
1117         u32 vol_flags;
1118
1119         /* Get volume flags  */
1120         status = (*func_NtQueryVolumeInformationFile)(h, &iosb,
1121                                                       &attr_info,
1122                                                       sizeof(attr_info),
1123                                                       FileFsAttributeInformation);
1124         if (likely((NT_SUCCESS(status) || status == STATUS_BUFFER_OVERFLOW) &&
1125                    (iosb.Information >=
1126                         offsetof(FILE_FS_ATTRIBUTE_INFORMATION,
1127                                  FileSystemAttributes) +
1128                         sizeof(attr_info.FileSystemAttributes))))
1129         {
1130                 vol_flags = attr_info.FileSystemAttributes;
1131         } else {
1132                 winnt_warning(status, L"\"%ls\": Can't get volume attributes",
1133                               printable_path(full_path));
1134                 vol_flags = 0;
1135         }
1136
1137         /* Get volume ID.  */
1138         status = (*func_NtQueryVolumeInformationFile)(h, &iosb,
1139                                                       &vol_info,
1140                                                       sizeof(vol_info),
1141                                                       FileFsVolumeInformation);
1142         if (likely((NT_SUCCESS(status) || status == STATUS_BUFFER_OVERFLOW) &&
1143                    (iosb.Information >=
1144                         offsetof(FILE_FS_VOLUME_INFORMATION,
1145                                  VolumeSerialNumber) +
1146                         sizeof(vol_info.VolumeSerialNumber))))
1147         {
1148                 params->capture_root_dev = vol_info.VolumeSerialNumber;
1149         } else {
1150                 winnt_warning(status, L"\"%ls\": Can't get volume ID",
1151                               printable_path(full_path));
1152                 params->capture_root_dev = 0;
1153         }
1154         return vol_flags;
1155 }
1156
1157 struct file_info {
1158         u32 attributes;
1159         u32 num_links;
1160         u64 creation_time;
1161         u64 last_write_time;
1162         u64 last_access_time;
1163         u64 ino;
1164         u64 end_of_file;
1165 };
1166
1167 static noinline_for_stack NTSTATUS
1168 get_file_info(HANDLE h, struct file_info *info)
1169 {
1170         IO_STATUS_BLOCK iosb;
1171         NTSTATUS status;
1172         FILE_ALL_INFORMATION all_info;
1173
1174         status = (*func_NtQueryInformationFile)(h, &iosb, &all_info,
1175                                                 sizeof(all_info),
1176                                                 FileAllInformation);
1177
1178         if (unlikely(!NT_SUCCESS(status) && status != STATUS_BUFFER_OVERFLOW))
1179                 return status;
1180
1181         info->attributes = all_info.BasicInformation.FileAttributes;
1182         info->num_links = all_info.StandardInformation.NumberOfLinks;
1183         info->creation_time = all_info.BasicInformation.CreationTime.QuadPart;
1184         info->last_write_time = all_info.BasicInformation.LastWriteTime.QuadPart;
1185         info->last_access_time = all_info.BasicInformation.LastAccessTime.QuadPart;
1186         info->ino = all_info.InternalInformation.IndexNumber.QuadPart;
1187         info->end_of_file = all_info.StandardInformation.EndOfFile.QuadPart;
1188         return STATUS_SUCCESS;
1189 }
1190
1191 static int
1192 winnt_build_dentry_tree_recursive(struct wim_dentry **root_ret,
1193                                   HANDLE cur_dir,
1194                                   wchar_t *full_path,
1195                                   size_t full_path_nchars,
1196                                   const wchar_t *filename,
1197                                   size_t filename_nchars,
1198                                   struct capture_params *params,
1199                                   struct winnt_scan_stats *stats,
1200                                   u32 vol_flags)
1201 {
1202         struct wim_dentry *root = NULL;
1203         struct wim_inode *inode = NULL;
1204         HANDLE h = NULL;
1205         int ret;
1206         NTSTATUS status;
1207         struct file_info file_info;
1208         ACCESS_MASK requestedPerms;
1209         u64 sort_key;
1210
1211         ret = try_exclude(full_path, params);
1212         if (unlikely(ret < 0)) /* Excluded? */
1213                 goto out_progress;
1214         if (unlikely(ret > 0)) /* Error? */
1215                 goto out;
1216
1217         /* Open the file.  */
1218         requestedPerms = FILE_READ_DATA |
1219                          FILE_READ_ATTRIBUTES |
1220                          READ_CONTROL |
1221                          ACCESS_SYSTEM_SECURITY |
1222                          SYNCHRONIZE;
1223 retry_open:
1224         status = winnt_openat(cur_dir,
1225                               (cur_dir ? filename : full_path),
1226                               (cur_dir ? filename_nchars : full_path_nchars),
1227                               requestedPerms,
1228                               &h);
1229         if (unlikely(!NT_SUCCESS(status))) {
1230                 if (status == STATUS_DELETE_PENDING) {
1231                         WARNING("\"%ls\": Deletion pending; skipping file",
1232                                 printable_path(full_path));
1233                         ret = 0;
1234                         goto out;
1235                 }
1236                 if (status == STATUS_ACCESS_DENIED &&
1237                     (requestedPerms & FILE_READ_DATA)) {
1238                         /* This happens on encrypted files.  */
1239                         requestedPerms &= ~FILE_READ_DATA;
1240                         goto retry_open;
1241                 }
1242
1243                 winnt_error(status, L"\"%ls\": Can't open file",
1244                             printable_path(full_path));
1245                 if (status == STATUS_FVE_LOCKED_VOLUME)
1246                         ret = WIMLIB_ERR_FVE_LOCKED_VOLUME;
1247                 else
1248                         ret = WIMLIB_ERR_OPEN;
1249                 goto out;
1250         }
1251
1252         /* Get information about the file.  */
1253         status = get_file_info(h, &file_info);
1254         if (!NT_SUCCESS(status)) {
1255                 winnt_error(status, L"\"%ls\": Can't get file information",
1256                             printable_path(full_path));
1257                 ret = WIMLIB_ERR_STAT;
1258                 goto out;
1259         }
1260
1261         if (unlikely(!(requestedPerms & FILE_READ_DATA)) &&
1262             !(file_info.attributes & FILE_ATTRIBUTE_ENCRYPTED))
1263         {
1264                 ERROR("\"%ls\": Permission to read data was denied",
1265                       printable_path(full_path));
1266                 ret = WIMLIB_ERR_OPEN;
1267                 goto out;
1268         }
1269
1270         if (unlikely(!cur_dir)) {
1271                 /* Root of tree being captured; get volume information.  */
1272                 vol_flags = get_volume_information(h, full_path, params);
1273                 params->capture_root_ino = file_info.ino;
1274         }
1275
1276
1277         /* Create a WIM dentry with an associated inode, which may be shared.
1278          *
1279          * However, we need to explicitly check for directories and files with
1280          * only 1 link and refuse to hard link them.  This is because Windows
1281          * has a bug where it can return duplicate File IDs for files and
1282          * directories on the FAT filesystem.
1283          *
1284          * Since we don't follow mount points on Windows, we don't need to query
1285          * the volume ID per-file.  Just once, for the root, is enough.  But we
1286          * can't simply pass 0, because then there could be inode collisions
1287          * among multiple calls to win32_build_dentry_tree() that are scanning
1288          * files on different volumes.  */
1289         ret = inode_table_new_dentry(params->inode_table,
1290                                      filename,
1291                                      file_info.ino,
1292                                      params->capture_root_dev,
1293                                      (file_info.num_links <= 1),
1294                                      &root);
1295         if (ret)
1296                 goto out;
1297
1298         /* Get the short (DOS) name of the file.  */
1299         status = winnt_get_short_name(h, root);
1300
1301         /* If we can't read the short filename for any reason other than
1302          * out-of-memory, just ignore the error and assume the file has no short
1303          * name.  This shouldn't be an issue, since the short names are
1304          * essentially obsolete anyway.  */
1305         if (unlikely(status == STATUS_NO_MEMORY)) {
1306                 ret = WIMLIB_ERR_NOMEM;
1307                 goto out;
1308         }
1309
1310         inode = root->d_inode;
1311
1312         if (inode->i_nlink > 1) {
1313                 /* Shared inode (hard link); skip reading per-inode information.
1314                  */
1315                 goto out_progress;
1316         }
1317
1318         inode->i_attributes = file_info.attributes;
1319         inode->i_creation_time = file_info.creation_time;
1320         inode->i_last_write_time = file_info.last_write_time;
1321         inode->i_last_access_time = file_info.last_access_time;
1322
1323         /* Get the file's security descriptor, unless we are capturing in
1324          * NO_ACLS mode or the volume does not support security descriptors.  */
1325         if (!(params->add_flags & WIMLIB_ADD_FLAG_NO_ACLS)
1326             && (vol_flags & FILE_PERSISTENT_ACLS))
1327         {
1328                 status = winnt_get_security_descriptor(h, inode,
1329                                                        params->sd_set, stats,
1330                                                        params->add_flags);
1331                 if (!NT_SUCCESS(status)) {
1332                         winnt_error(status,
1333                                     L"\"%ls\": Can't read security descriptor",
1334                                     printable_path(full_path));
1335                         ret = WIMLIB_ERR_STAT;
1336                         goto out;
1337                 }
1338         }
1339
1340         /* If this is a reparse point, load the reparse data.  */
1341         if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
1342                 ret = winnt_load_reparse_data(h, inode, full_path, params);
1343                 if (ret)
1344                         goto out;
1345         }
1346
1347         sort_key = get_sort_key(h);
1348
1349         if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED)) {
1350                 /* Load information about the raw encrypted data.  This is
1351                  * needed for any directory or non-directory that has
1352                  * FILE_ATTRIBUTE_ENCRYPTED set.
1353                  *
1354                  * Note: since OpenEncryptedFileRaw() fails with
1355                  * ERROR_SHARING_VIOLATION if there are any open handles to the
1356                  * file, we have to close the file and re-open it later if
1357                  * needed.  */
1358                 (*func_NtClose)(h);
1359                 h = NULL;
1360                 ret = winnt_scan_efsrpc_raw_data(inode, full_path,
1361                                                  params->unhashed_blobs);
1362                 if (ret)
1363                         goto out;
1364         } else {
1365                 /*
1366                  * Load information about data streams (unnamed and named).
1367                  *
1368                  * Skip this step for encrypted files, since the data from
1369                  * ReadEncryptedFileRaw() already contains all data streams (and
1370                  * they do in fact all get restored by WriteEncryptedFileRaw().)
1371                  *
1372                  * Note: WIMGAPI (as of Windows 8.1) gets wrong and stores both
1373                  * the EFSRPC data and the named data stream(s)...!
1374                  */
1375                 ret = winnt_scan_data_streams(h,
1376                                               full_path,
1377                                               full_path_nchars,
1378                                               inode,
1379                                               params->unhashed_blobs,
1380                                               file_info.end_of_file,
1381                                               vol_flags);
1382                 if (ret)
1383                         goto out;
1384         }
1385
1386         set_sort_key(inode, sort_key);
1387
1388         if (inode_is_directory(inode)) {
1389
1390                 /* Directory: recurse to children.  */
1391
1392                 if (unlikely(!h)) {
1393                         /* Re-open handle that was closed to read raw encrypted
1394                          * data.  */
1395                         status = winnt_openat(cur_dir,
1396                                               (cur_dir ?
1397                                                filename : full_path),
1398                                               (cur_dir ?
1399                                                filename_nchars : full_path_nchars),
1400                                               FILE_LIST_DIRECTORY | SYNCHRONIZE,
1401                                               &h);
1402                         if (!NT_SUCCESS(status)) {
1403                                 winnt_error(status,
1404                                             L"\"%ls\": Can't re-open file",
1405                                             printable_path(full_path));
1406                                 ret = WIMLIB_ERR_OPEN;
1407                                 goto out;
1408                         }
1409                 }
1410                 ret = winnt_recurse_directory(h,
1411                                               full_path,
1412                                               full_path_nchars,
1413                                               root,
1414                                               params,
1415                                               stats,
1416                                               vol_flags);
1417                 if (ret)
1418                         goto out;
1419         }
1420
1421 out_progress:
1422         params->progress.scan.cur_path = printable_path(full_path);
1423         if (likely(root))
1424                 ret = do_capture_progress(params, WIMLIB_SCAN_DENTRY_OK, inode);
1425         else
1426                 ret = do_capture_progress(params, WIMLIB_SCAN_DENTRY_EXCLUDED, NULL);
1427 out:
1428         if (likely(h))
1429                 (*func_NtClose)(h);
1430         if (unlikely(ret)) {
1431                 free_dentry_tree(root, params->blob_table);
1432                 root = NULL;
1433                 ret = report_capture_error(params, ret, full_path);
1434         }
1435         *root_ret = root;
1436         return ret;
1437 }
1438
1439 static void
1440 winnt_do_scan_warnings(const wchar_t *path, const struct winnt_scan_stats *stats)
1441 {
1442         if (likely(stats->num_get_sacl_priv_notheld == 0 &&
1443                    stats->num_get_sd_access_denied == 0))
1444                 return;
1445
1446         WARNING("Scan of \"%ls\" complete, but with one or more warnings:", path);
1447         if (stats->num_get_sacl_priv_notheld != 0) {
1448                 WARNING("- Could not capture SACL (System Access Control List)\n"
1449                         "            on %lu files or directories.",
1450                         stats->num_get_sacl_priv_notheld);
1451         }
1452         if (stats->num_get_sd_access_denied != 0) {
1453                 WARNING("- Could not capture security descriptor at all\n"
1454                         "            on %lu files or directories.",
1455                         stats->num_get_sd_access_denied);
1456         }
1457         WARNING("To fully capture all security descriptors, run the program\n"
1458                 "          with Administrator rights.");
1459 }
1460
1461 #define WINDOWS_NT_MAX_PATH 32768
1462
1463 /* Win32 version of capturing a directory tree.  */
1464 int
1465 win32_build_dentry_tree(struct wim_dentry **root_ret,
1466                         const wchar_t *root_disk_path,
1467                         struct capture_params *params)
1468 {
1469         wchar_t *path;
1470         int ret;
1471         UNICODE_STRING ntpath;
1472         struct winnt_scan_stats stats;
1473         size_t ntpath_nchars;
1474
1475         /* WARNING: There is no check for overflow later when this buffer is
1476          * being used!  But it's as long as the maximum path length understood
1477          * by Windows NT (which is NOT the same as MAX_PATH).  */
1478         path = MALLOC((WINDOWS_NT_MAX_PATH + 1) * sizeof(wchar_t));
1479         if (!path)
1480                 return WIMLIB_ERR_NOMEM;
1481
1482         ret = win32_path_to_nt_path(root_disk_path, &ntpath);
1483         if (ret)
1484                 goto out_free_path;
1485
1486         if (ntpath.Length < 4 * sizeof(wchar_t) ||
1487             ntpath.Length > WINDOWS_NT_MAX_PATH * sizeof(wchar_t) ||
1488             wmemcmp(ntpath.Buffer, L"\\??\\", 4))
1489         {
1490                 ERROR("\"%ls\": unrecognized path format", root_disk_path);
1491                 ret = WIMLIB_ERR_INVALID_PARAM;
1492         } else {
1493                 ntpath_nchars = ntpath.Length / sizeof(wchar_t);
1494                 wmemcpy(path, ntpath.Buffer, ntpath_nchars);
1495                 path[ntpath_nchars] = L'\0';
1496
1497                 params->capture_root_nchars = ntpath_nchars;
1498                 if (path[ntpath_nchars - 1] == L'\\')
1499                         params->capture_root_nchars--;
1500                 ret = 0;
1501         }
1502         HeapFree(GetProcessHeap(), 0, ntpath.Buffer);
1503         if (ret)
1504                 goto out_free_path;
1505
1506         memset(&stats, 0, sizeof(stats));
1507
1508         ret = winnt_build_dentry_tree_recursive(root_ret, NULL,
1509                                                 path, ntpath_nchars,
1510                                                 L"", 0, params, &stats, 0);
1511 out_free_path:
1512         FREE(path);
1513         if (ret == 0)
1514                 winnt_do_scan_warnings(root_disk_path, &stats);
1515         return ret;
1516 }
1517
1518 #endif /* __WIN32__ */