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