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