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