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