]> wimlib.net Git - wimlib/blob - src/win32_capture.c
71e6c840ab3c6f7f9186768813f2272778fbb25f
[wimlib] / src / win32_capture.c
1 /*
2  * win32_capture.c - Windows-specific code for capturing files into a WIM image.
3  */
4
5 /*
6  * Copyright (C) 2013 Eric Biggers
7  *
8  * This file is part of wimlib, a library for working with WIM files.
9  *
10  * wimlib is free software; you can redistribute it and/or modify it under the
11  * terms of the GNU General Public License as published by the Free
12  * Software Foundation; either version 3 of the License, or (at your option)
13  * any later version.
14  *
15  * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
16  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
17  * A PARTICULAR PURPOSE. See the GNU General Public License for more
18  * details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with wimlib; 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/endianness.h"
34 #include "wimlib/error.h"
35 #include "wimlib/lookup_table.h"
36 #include "wimlib/paths.h"
37 #include "wimlib/reparse.h"
38
39 #define MAX_GET_SD_ACCESS_DENIED_WARNINGS 1
40 #define MAX_GET_SACL_PRIV_NOTHELD_WARNINGS 1
41 #define MAX_CAPTURE_LONG_PATH_WARNINGS 5
42
43 struct win32_capture_state {
44         unsigned long num_get_sd_access_denied;
45         unsigned long num_get_sacl_priv_notheld;
46         unsigned long num_long_path_warnings;
47 };
48
49
50 static const wchar_t *capture_access_denied_msg =
51 L"         If you are not running this program as the administrator, you may\n"
52  "         need to do so, so that all data and metadata can be backed up.\n"
53  "         Otherwise, there may be no way to access the desired data or\n"
54  "         metadata without taking ownership of the file or directory.\n"
55  ;
56
57 int
58 read_win32_file_prefix(const struct wim_lookup_table_entry *lte,
59                        u64 size,
60                        consume_data_callback_t cb,
61                        void *cb_ctx)
62 {
63         int ret = 0;
64         u64 bytes_remaining;
65         u8 buf[BUFFER_SIZE];
66
67         HANDLE hFile = win32_open_existing_file(lte->file_on_disk,
68                                                 FILE_READ_DATA);
69         if (hFile == INVALID_HANDLE_VALUE) {
70                 set_errno_from_GetLastError();
71                 ERROR_WITH_ERRNO("Failed to open \"%ls\"", lte->file_on_disk);
72                 return WIMLIB_ERR_OPEN;
73         }
74
75         bytes_remaining = size;
76         while (bytes_remaining) {
77                 DWORD bytesToRead, bytesRead;
78
79                 bytesToRead = min(sizeof(buf), bytes_remaining);
80                 if (!ReadFile(hFile, buf, bytesToRead, &bytesRead, NULL) ||
81                     bytesRead != bytesToRead)
82                 {
83                         set_errno_from_GetLastError();
84                         ERROR_WITH_ERRNO("Failed to read data from \"%ls\"",
85                                          lte->file_on_disk);
86                         ret = WIMLIB_ERR_READ;
87                         break;
88                 }
89                 bytes_remaining -= bytesRead;
90                 ret = (*cb)(buf, bytesRead, cb_ctx);
91                 if (ret)
92                         break;
93         }
94 out_close_handle:
95         CloseHandle(hFile);
96         return ret;
97 }
98
99 struct win32_encrypted_read_ctx {
100         consume_data_callback_t read_prefix_cb;
101         void *read_prefix_ctx;
102         int wimlib_err_code;
103         u64 bytes_remaining;
104 };
105
106 static DWORD WINAPI
107 win32_encrypted_export_cb(unsigned char *data, void *_ctx, unsigned long len)
108 {
109         struct win32_encrypted_read_ctx *ctx = _ctx;
110         int ret;
111         size_t bytes_to_consume = min(len, ctx->bytes_remaining);
112
113         if (bytes_to_consume == 0)
114                 return ERROR_SUCCESS;
115
116         ret = (*ctx->read_prefix_cb)(data, bytes_to_consume, ctx->read_prefix_ctx);
117         if (ret) {
118                 ctx->wimlib_err_code = ret;
119                 /* Shouldn't matter what error code is returned here, as long as
120                  * it isn't ERROR_SUCCESS.  */
121                 return ERROR_READ_FAULT;
122         }
123         ctx->bytes_remaining -= bytes_to_consume;
124         return ERROR_SUCCESS;
125 }
126
127 int
128 read_win32_encrypted_file_prefix(const struct wim_lookup_table_entry *lte,
129                                  u64 size,
130                                  consume_data_callback_t cb,
131                                  void *cb_ctx)
132 {
133         struct win32_encrypted_read_ctx export_ctx;
134         DWORD err;
135         void *file_ctx;
136         int ret;
137
138         DEBUG("Reading %"PRIu64" bytes from encryted file \"%ls\"",
139               size, lte->file_on_disk);
140
141         export_ctx.read_prefix_cb = cb;
142         export_ctx.read_prefix_ctx = cb_ctx;
143         export_ctx.wimlib_err_code = 0;
144         export_ctx.bytes_remaining = size;
145
146         err = OpenEncryptedFileRaw(lte->file_on_disk, 0, &file_ctx);
147         if (err != ERROR_SUCCESS) {
148                 set_errno_from_win32_error(err);
149                 ERROR_WITH_ERRNO("Failed to open encrypted file \"%ls\" "
150                                  "for raw read", lte->file_on_disk);
151                 return WIMLIB_ERR_OPEN;
152         }
153         err = ReadEncryptedFileRaw(win32_encrypted_export_cb,
154                                    &export_ctx, file_ctx);
155         if (err != ERROR_SUCCESS) {
156                 set_errno_from_win32_error(err);
157                 ERROR_WITH_ERRNO("Failed to read encrypted file \"%ls\"",
158                                  lte->file_on_disk);
159                 ret = export_ctx.wimlib_err_code;
160                 if (ret == 0)
161                         ret = WIMLIB_ERR_READ;
162         } else if (export_ctx.bytes_remaining != 0) {
163                 ERROR("Only could read %"PRIu64" of %"PRIu64" bytes from "
164                       "encryted file \"%ls\"",
165                       size - export_ctx.bytes_remaining, size,
166                       lte->file_on_disk);
167                 ret = WIMLIB_ERR_READ;
168         } else {
169                 ret = 0;
170         }
171         CloseEncryptedFileRaw(file_ctx);
172         return ret;
173 }
174
175
176 static u64
177 FILETIME_to_u64(const FILETIME *ft)
178 {
179         return ((u64)ft->dwHighDateTime << 32) | (u64)ft->dwLowDateTime;
180 }
181
182 /* Load the short name of a file into a WIM dentry.
183  *
184  * If we can't read the short filename for some reason, we just ignore the error
185  * and assume the file has no short name.  This shouldn't be an issue, since the
186  * short names are essentially obsolete anyway.
187  */
188 static int
189 win32_get_short_name(HANDLE hFile, const wchar_t *path, struct wim_dentry *dentry)
190 {
191
192         /* It's not any harder to just make the NtQueryInformationFile() system
193          * call ourselves, and it saves a dumb call to FindFirstFile() which of
194          * course has to create its own handle.  */
195 #ifdef WITH_NTDLL
196         if (func_NtQueryInformationFile) {
197                 NTSTATUS status;
198                 IO_STATUS_BLOCK io_status;
199                 u8 buf[128] _aligned_attribute(8);
200                 const FILE_NAME_INFORMATION *info;
201
202                 status = (*func_NtQueryInformationFile)(hFile, &io_status, buf, sizeof(buf),
203                                                         FileAlternateNameInformation);
204                 info = (const FILE_NAME_INFORMATION*)buf;
205                 if (status == STATUS_SUCCESS && info->FileNameLength != 0) {
206                         dentry->short_name = MALLOC(info->FileNameLength + 2);
207                         if (!dentry->short_name)
208                                 return WIMLIB_ERR_NOMEM;
209                         memcpy(dentry->short_name, info->FileName,
210                                info->FileNameLength);
211                         dentry->short_name[info->FileNameLength / 2] = L'\0';
212                         dentry->short_name_nbytes = info->FileNameLength;
213                 }
214                 return 0;
215         }
216 #endif
217
218         WIN32_FIND_DATAW dat;
219         HANDLE hFind;
220         int ret = 0;
221
222         hFind = FindFirstFile(path, &dat);
223         if (hFind != INVALID_HANDLE_VALUE) {
224                 if (dat.cAlternateFileName[0] != L'\0') {
225                         DEBUG("\"%ls\": short name \"%ls\"", path, dat.cAlternateFileName);
226                         size_t short_name_nbytes = wcslen(dat.cAlternateFileName) *
227                                                    sizeof(wchar_t);
228                         size_t n = short_name_nbytes + sizeof(wchar_t);
229                         dentry->short_name = MALLOC(n);
230                         if (dentry->short_name) {
231                                 memcpy(dentry->short_name, dat.cAlternateFileName, n);
232                                 dentry->short_name_nbytes = short_name_nbytes;
233                         } else {
234                                 ret = WIMLIB_ERR_NOMEM;
235                         }
236                 }
237                 FindClose(hFind);
238         }
239         return ret;
240 }
241
242 /*
243  * win32_query_security_descriptor() - Query a file's security descriptor
244  *
245  * We need the file's security descriptor in SECURITY_DESCRIPTOR_RELATIVE
246  * format, and we currently have a handle opened with as many relevant
247  * permissions as possible.  At this point, on Windows there are a number of
248  * options for reading a file's security descriptor:
249  *
250  * GetFileSecurity():  This takes in a path and returns the
251  * SECURITY_DESCRIPTOR_RELATIVE.  Problem: this uses an internal handle, not
252  * ours, and the handle created internally doesn't specify
253  * FILE_FLAG_BACKUP_SEMANTICS.  Therefore there can be access denied errors on
254  * some files and directories, even when running as the Administrator.
255  *
256  * GetSecurityInfo():  This takes in a handle and returns the security
257  * descriptor split into a bunch of different parts.  This should work, but it's
258  * dumb because we have to put the security descriptor back together again.
259  *
260  * BackupRead():  This can read the security descriptor, but this is a
261  * difficult-to-use API, probably only works as the Administrator, and the
262  * format of the returned data is not well documented.
263  *
264  * NtQuerySecurityObject():  This is exactly what we need, as it takes in a
265  * handle and returns the security descriptor in SECURITY_DESCRIPTOR_RELATIVE
266  * format.  Only problem is that it's a ntdll function and therefore not
267  * officially part of the Win32 API.  Oh well.
268  */
269 static DWORD
270 win32_query_security_descriptor(HANDLE hFile, const wchar_t *path,
271                                 SECURITY_INFORMATION requestedInformation,
272                                 SECURITY_DESCRIPTOR *buf,
273                                 DWORD bufsize, DWORD *lengthNeeded)
274 {
275 #ifdef WITH_NTDLL
276         if (func_NtQuerySecurityObject) {
277                 NTSTATUS status;
278
279                 status = (*func_NtQuerySecurityObject)(hFile,
280                                                        requestedInformation, buf,
281                                                        bufsize, lengthNeeded);
282                 /* Since it queries an already-open handle, NtQuerySecurityObject()
283                  * apparently returns STATUS_ACCESS_DENIED rather than
284                  * STATUS_PRIVILEGE_NOT_HELD.  */
285                 if (status == STATUS_ACCESS_DENIED)
286                         return ERROR_PRIVILEGE_NOT_HELD;
287                 else
288                         return (*func_RtlNtStatusToDosError)(status);
289         }
290 #endif
291         if (GetFileSecurity(path, requestedInformation, buf,
292                             bufsize, lengthNeeded))
293                 return ERROR_SUCCESS;
294         else
295                 return GetLastError();
296 }
297
298 static int
299 win32_get_security_descriptor(HANDLE hFile,
300                               const wchar_t *path,
301                               struct wim_inode *inode,
302                               struct wim_sd_set *sd_set,
303                               struct win32_capture_state *state,
304                               int add_flags)
305 {
306         SECURITY_INFORMATION requestedInformation;
307         u8 _buf[4096];
308         u8 *buf;
309         size_t bufsize;
310         DWORD lenNeeded;
311         DWORD err;
312         int ret;
313
314         requestedInformation = DACL_SECURITY_INFORMATION |
315                                SACL_SECURITY_INFORMATION |
316                                OWNER_SECURITY_INFORMATION |
317                                GROUP_SECURITY_INFORMATION;
318         buf = _buf;
319         bufsize = sizeof(_buf);
320         for (;;) {
321                 err = win32_query_security_descriptor(hFile, path,
322                                                       requestedInformation,
323                                                       (SECURITY_DESCRIPTOR*)buf,
324                                                       bufsize, &lenNeeded);
325                 switch (err) {
326                 case ERROR_SUCCESS:
327                         goto have_descriptor;
328                 case ERROR_INSUFFICIENT_BUFFER:
329                         wimlib_assert(buf == _buf);
330                         buf = MALLOC(lenNeeded);
331                         if (!buf)
332                                 return WIMLIB_ERR_NOMEM;
333                         bufsize = lenNeeded;
334                         break;
335                 case ERROR_PRIVILEGE_NOT_HELD:
336                         if (add_flags & WIMLIB_ADD_FLAG_STRICT_ACLS)
337                                 goto fail;
338                         if (requestedInformation & SACL_SECURITY_INFORMATION) {
339                                 state->num_get_sacl_priv_notheld++;
340                                 requestedInformation &= ~SACL_SECURITY_INFORMATION;
341                                 break;
342                         }
343                         /* Fall through */
344                 case ERROR_ACCESS_DENIED:
345                         if (add_flags & WIMLIB_ADD_FLAG_STRICT_ACLS)
346                                 goto fail;
347                         state->num_get_sd_access_denied++;
348                         ret = 0;
349                         goto out_free_buf;
350                 default:
351                 fail:
352                         set_errno_from_win32_error(err);
353                         ERROR_WITH_ERRNO("Failed to read security descriptor of \"%ls\"", path);
354                         ret = WIMLIB_ERR_READ;
355                         goto out_free_buf;
356                 }
357         }
358
359 have_descriptor:
360         inode->i_security_id = sd_set_add_sd(sd_set, buf, lenNeeded);
361         if (inode->i_security_id < 0)
362                 ret = WIMLIB_ERR_NOMEM;
363         else
364                 ret = 0;
365 out_free_buf:
366         if (buf != _buf)
367                 FREE(buf);
368         return ret;
369 }
370
371 static int
372 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
373                                   wchar_t *path,
374                                   size_t path_num_chars,
375                                   struct add_image_params *params,
376                                   struct win32_capture_state *state,
377                                   unsigned vol_flags);
378
379 /* Reads the directory entries of directory and recursively calls
380  * win32_build_dentry_tree() on them.  */
381 static int
382 win32_recurse_directory(HANDLE hDir,
383                         wchar_t *dir_path,
384                         size_t dir_path_num_chars,
385                         struct wim_dentry *root,
386                         struct add_image_params *params,
387                         struct win32_capture_state *state,
388                         unsigned vol_flags)
389 {
390         int ret;
391
392         DEBUG("Recurse to directory \"%ls\"", dir_path);
393
394         /* Using NtQueryDirectoryFile() we can re-use the same open handle,
395          * which we opened with FILE_FLAG_BACKUP_SEMANTICS (probably not the
396          * case for the FindFirstFile() API; it's not documented).  */
397 #ifdef WITH_NTDLL
398         if (!func_NtQueryDirectoryFile)
399                 goto use_FindFirstFile;
400
401         NTSTATUS status;
402         IO_STATUS_BLOCK io_status;
403         const size_t bufsize = 8192;
404         u8 *buf;
405         BOOL restartScan = TRUE;
406         const FILE_NAMES_INFORMATION *info;
407
408         buf = MALLOC(bufsize);
409         if (!buf)
410                 return WIMLIB_ERR_NOMEM;
411         for (;;) {
412                 status = (*func_NtQueryDirectoryFile)(hDir, NULL, NULL, NULL,
413                                                       &io_status, buf, bufsize,
414                                                       FileNamesInformation,
415                                                       FALSE, NULL, restartScan);
416                 restartScan = FALSE;
417                 if (status != STATUS_SUCCESS) {
418                         if (status == STATUS_NO_MORE_FILES ||
419                             status == STATUS_NO_MORE_ENTRIES ||
420                             status == STATUS_NO_MORE_MATCHES) {
421                                 ret = 0;
422                         } else if (status == STATUS_NOT_IMPLEMENTED ||
423                                    status == STATUS_NOT_SUPPORTED ||
424                                    status == STATUS_INVALID_INFO_CLASS) {
425                                 FREE(buf);
426                                 goto use_FindFirstFile;
427                         } else {
428                                 set_errno_from_nt_status(status);
429                                 ERROR_WITH_ERRNO("Failed to read directory "
430                                                  "\"%ls\"", dir_path);
431                                 ret = WIMLIB_ERR_READ;
432                         }
433                         goto out_free_buf;
434                 }
435                 wimlib_assert(io_status.Information != 0);
436                 info = (const FILE_NAMES_INFORMATION*)buf;
437                 for (;;) {
438                         if (!(info->FileNameLength == 2 && info->FileName[0] == L'.') &&
439                             !(info->FileNameLength == 4 && info->FileName[0] == L'.' &&
440                                                            info->FileName[1] == L'.'))
441                         {
442                                 wchar_t *p;
443                                 struct wim_dentry *child;
444
445                                 p = dir_path + dir_path_num_chars;
446                                 *p++ = L'\\';
447                                 p = wmempcpy(p, info->FileName,
448                                              info->FileNameLength / 2);
449                                 *p = '\0';
450
451                                 ret = win32_build_dentry_tree_recursive(
452                                                                 &child,
453                                                                 dir_path,
454                                                                 p - dir_path,
455                                                                 params,
456                                                                 state,
457                                                                 vol_flags);
458
459                                 dir_path[dir_path_num_chars] = L'\0';
460
461                                 if (ret)
462                                         goto out_free_buf;
463                                 if (child)
464                                         dentry_add_child(root, child);
465                         }
466                         if (info->NextEntryOffset == 0)
467                                 break;
468                         info = (const FILE_NAMES_INFORMATION*)
469                                         ((const u8*)info + info->NextEntryOffset);
470                 }
471         }
472 out_free_buf:
473         FREE(buf);
474         return ret;
475 #endif
476
477 use_FindFirstFile:
478         ;
479         WIN32_FIND_DATAW dat;
480         HANDLE hFind;
481         DWORD err;
482
483         /* Begin reading the directory by calling FindFirstFileW.  Unlike UNIX
484          * opendir(), FindFirstFileW has file globbing built into it.  But this
485          * isn't what we actually want, so just add a dummy glob to get all
486          * entries. */
487         dir_path[dir_path_num_chars] = OS_PREFERRED_PATH_SEPARATOR;
488         dir_path[dir_path_num_chars + 1] = L'*';
489         dir_path[dir_path_num_chars + 2] = L'\0';
490         hFind = FindFirstFile(dir_path, &dat);
491         dir_path[dir_path_num_chars] = L'\0';
492
493         if (hFind == INVALID_HANDLE_VALUE) {
494                 err = GetLastError();
495                 if (err == ERROR_FILE_NOT_FOUND) {
496                         return 0;
497                 } else {
498                         set_errno_from_win32_error(err);
499                         ERROR_WITH_ERRNO("Failed to read directory \"%ls\"",
500                                          dir_path);
501                         return WIMLIB_ERR_READ;
502                 }
503         }
504         ret = 0;
505         do {
506                 /* Skip . and .. entries */
507                 if (dat.cFileName[0] == L'.' &&
508                     (dat.cFileName[1] == L'\0' ||
509                      (dat.cFileName[1] == L'.' &&
510                       dat.cFileName[2] == L'\0')))
511                         continue;
512                 size_t filename_len = wcslen(dat.cFileName);
513
514                 dir_path[dir_path_num_chars] = OS_PREFERRED_PATH_SEPARATOR;
515                 wmemcpy(dir_path + dir_path_num_chars + 1,
516                         dat.cFileName,
517                         filename_len + 1);
518
519                 struct wim_dentry *child;
520                 size_t path_len = dir_path_num_chars + 1 + filename_len;
521                 ret = win32_build_dentry_tree_recursive(&child,
522                                                         dir_path,
523                                                         path_len,
524                                                         params,
525                                                         state,
526                                                         vol_flags);
527                 dir_path[dir_path_num_chars] = L'\0';
528                 if (ret)
529                         goto out_find_close;
530                 if (child)
531                         dentry_add_child(root, child);
532         } while (FindNextFile(hFind, &dat));
533         err = GetLastError();
534         if (err != ERROR_NO_MORE_FILES) {
535                 set_errno_from_win32_error(err);
536                 ERROR_WITH_ERRNO("Failed to read directory \"%ls\"", dir_path);
537                 if (ret == 0)
538                         ret = WIMLIB_ERR_READ;
539         }
540 out_find_close:
541         FindClose(hFind);
542         return ret;
543 }
544
545 /* Reparse point fixup status code */
546 enum rp_status {
547         /* Reparse point corresponded to an absolute symbolic link or junction
548          * point that pointed outside the directory tree being captured, and
549          * therefore was excluded. */
550         RP_EXCLUDED       = 0x0,
551
552         /* Reparse point was not fixed as it was either a relative symbolic
553          * link, a mount point, or something else we could not understand. */
554         RP_NOT_FIXED      = 0x1,
555
556         /* Reparse point corresponded to an absolute symbolic link or junction
557          * point that pointed inside the directory tree being captured, where
558          * the target was specified by a "full" \??\ prefixed path, and
559          * therefore was fixed to be relative to the root of the directory tree
560          * being captured. */
561         RP_FIXED_FULLPATH = 0x2,
562
563         /* Same as RP_FIXED_FULLPATH, except the absolute link target did not
564          * have the \??\ prefix.  It may have begun with a drive letter though.
565          * */
566         RP_FIXED_ABSPATH  = 0x4,
567
568         /* Either RP_FIXED_FULLPATH or RP_FIXED_ABSPATH. */
569         RP_FIXED          = RP_FIXED_FULLPATH | RP_FIXED_ABSPATH,
570 };
571
572 /* Given the "substitute name" target of a Windows reparse point, try doing a
573  * fixup where we change it to be absolute relative to the root of the directory
574  * tree being captured.
575  *
576  * Note that this is only executed when WIMLIB_ADD_FLAG_RPFIX has been
577  * set.
578  *
579  * @capture_root_ino and @capture_root_dev indicate the inode number and device
580  * of the root of the directory tree being captured.  They are meant to identify
581  * this directory (as an alternative to its actual path, which could potentially
582  * be reached via multiple destinations due to other symbolic links).  This may
583  * not work properly on FAT, which doesn't seem to supply proper inode numbers
584  * or file IDs.  However, FAT doesn't support reparse points so this function
585  * wouldn't even be called anyway.
586  */
587 static enum rp_status
588 win32_capture_maybe_rpfix_target(wchar_t *target, u16 *target_nbytes_p,
589                                  u64 capture_root_ino, u64 capture_root_dev,
590                                  u32 rptag)
591 {
592         u16 target_nchars = *target_nbytes_p / 2;
593         size_t stripped_chars;
594         wchar_t *orig_target;
595         int ret;
596
597         ret = parse_substitute_name(target, *target_nbytes_p, rptag);
598         if (ret < 0)
599                 return RP_NOT_FIXED;
600         stripped_chars = ret;
601         if (stripped_chars)
602                 stripped_chars -= 2;
603         target[target_nchars] = L'\0';
604         orig_target = target;
605         target = capture_fixup_absolute_symlink(target + stripped_chars,
606                                                 capture_root_ino, capture_root_dev);
607         if (!target)
608                 return RP_EXCLUDED;
609         target_nchars = wcslen(target);
610         wmemmove(orig_target + stripped_chars, target, target_nchars + 1);
611         *target_nbytes_p = (target_nchars + stripped_chars) * sizeof(wchar_t);
612         DEBUG("Fixed reparse point (new target: \"%ls\")", orig_target);
613         if (stripped_chars)
614                 return RP_FIXED_FULLPATH;
615         else
616                 return RP_FIXED_ABSPATH;
617 }
618
619 /* Returns: `enum rp_status' value on success; negative WIMLIB_ERR_* value on
620  * failure. */
621 static int
622 win32_capture_try_rpfix(u8 *rpbuf, u16 *rpbuflen_p,
623                         u64 capture_root_ino, u64 capture_root_dev,
624                         const wchar_t *path)
625 {
626         struct reparse_data rpdata;
627         int ret;
628         enum rp_status rp_status;
629
630         ret = parse_reparse_data(rpbuf, *rpbuflen_p, &rpdata);
631         if (ret)
632                 return -ret;
633
634         rp_status = win32_capture_maybe_rpfix_target(rpdata.substitute_name,
635                                                      &rpdata.substitute_name_nbytes,
636                                                      capture_root_ino,
637                                                      capture_root_dev,
638                                                      le32_to_cpu(*(le32*)rpbuf));
639         if (rp_status & RP_FIXED) {
640                 wimlib_assert(rpdata.substitute_name_nbytes % 2 == 0);
641                 utf16lechar substitute_name_copy[rpdata.substitute_name_nbytes / 2];
642                 wmemcpy(substitute_name_copy, rpdata.substitute_name,
643                         rpdata.substitute_name_nbytes / 2);
644                 rpdata.substitute_name = substitute_name_copy;
645                 rpdata.print_name = substitute_name_copy;
646                 rpdata.print_name_nbytes = rpdata.substitute_name_nbytes;
647                 if (rp_status == RP_FIXED_FULLPATH) {
648                         /* "full path", meaning \??\ prefixed.  We should not
649                          * include this prefix in the print name, as it is
650                          * apparently meant for the filesystem driver only. */
651                         rpdata.print_name += 4;
652                         rpdata.print_name_nbytes -= 8;
653                 }
654                 ret = make_reparse_buffer(&rpdata, rpbuf, rpbuflen_p);
655                 if (ret == 0)
656                         ret = rp_status;
657                 else
658                         ret = -ret;
659         } else {
660                 if (rp_status == RP_EXCLUDED) {
661                         size_t print_name_nchars = rpdata.print_name_nbytes / 2;
662                         wchar_t print_name0[print_name_nchars + 1];
663                         print_name0[print_name_nchars] = L'\0';
664                         wmemcpy(print_name0, rpdata.print_name, print_name_nchars);
665                         WARNING("Ignoring %ls pointing out of capture directory:\n"
666                                 "          \"%ls\" -> \"%ls\"\n"
667                                 "          (Use --norpfix to capture all symbolic links "
668                                 "and junction points as-is)",
669                                 (rpdata.rptag == WIM_IO_REPARSE_TAG_SYMLINK) ?
670                                         L"absolute symbolic link" : L"junction point",
671                                 path, print_name0);
672                 }
673                 ret = rp_status;
674         }
675         return ret;
676 }
677
678 /*
679  * Loads the reparse point data from a reparse point into memory, optionally
680  * fixing the targets of absolute symbolic links and junction points to be
681  * relative to the root of capture.
682  *
683  * @hFile:  Open handle to the reparse point.
684  * @path:   Path to the reparse point.  Used for error messages only.
685  * @params: Additional parameters, including whether to do reparse point fixups
686  *          or not.
687  * @rpbuf:  Buffer of length at least REPARSE_POINT_MAX_SIZE bytes into which
688  *          the reparse point buffer will be loaded.
689  * @rpbuflen_ret:  On success, the length of the reparse point buffer in bytes
690  *                 is written to this location.
691  *
692  * Returns:
693  *      On success, returns an `enum rp_status' value that indicates if and/or
694  *      how the reparse point fixup was done.
695  *
696  *      On failure, returns a negative value that is a negated WIMLIB_ERR_*
697  *      code.
698  */
699 static int
700 win32_get_reparse_data(HANDLE hFile, const wchar_t *path,
701                        struct add_image_params *params,
702                        u8 *rpbuf, u16 *rpbuflen_ret)
703 {
704         DWORD bytesReturned;
705         u32 reparse_tag;
706         int ret;
707         u16 rpbuflen;
708
709         DEBUG("Loading reparse data from \"%ls\"", path);
710         if (!DeviceIoControl(hFile, FSCTL_GET_REPARSE_POINT,
711                              NULL, /* "Not used with this operation; set to NULL" */
712                              0, /* "Not used with this operation; set to 0" */
713                              rpbuf, /* "A pointer to a buffer that
714                                                    receives the reparse point data */
715                              REPARSE_POINT_MAX_SIZE, /* "The size of the output
716                                                         buffer, in bytes */
717                              &bytesReturned,
718                              NULL))
719         {
720                 set_errno_from_GetLastError();
721                 ERROR_WITH_ERRNO("Failed to get reparse data of \"%ls\"", path);
722                 return -WIMLIB_ERR_READ;
723         }
724         if (bytesReturned < 8 || bytesReturned > REPARSE_POINT_MAX_SIZE) {
725                 ERROR("Reparse data on \"%ls\" is invalid", path);
726                 return -WIMLIB_ERR_INVALID_REPARSE_DATA;
727         }
728
729         rpbuflen = bytesReturned;
730         reparse_tag = le32_to_cpu(*(le32*)rpbuf);
731         if (params->add_flags & WIMLIB_ADD_FLAG_RPFIX &&
732             (reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
733              reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT))
734         {
735                 /* Try doing reparse point fixup */
736                 ret = win32_capture_try_rpfix(rpbuf,
737                                               &rpbuflen,
738                                               params->capture_root_ino,
739                                               params->capture_root_dev,
740                                               path);
741         } else {
742                 ret = RP_NOT_FIXED;
743         }
744         *rpbuflen_ret = rpbuflen;
745         return ret;
746 }
747
748 static DWORD WINAPI
749 win32_tally_encrypted_size_cb(unsigned char *_data, void *_size_ret,
750                               unsigned long len)
751 {
752         *(u64*)_size_ret += len;
753         return ERROR_SUCCESS;
754 }
755
756 static int
757 win32_get_encrypted_file_size(const wchar_t *path, u64 *size_ret)
758 {
759         DWORD err;
760         void *file_ctx;
761         int ret;
762
763         err = OpenEncryptedFileRaw(path, 0, &file_ctx);
764         if (err != ERROR_SUCCESS) {
765                 set_errno_from_win32_error(err);
766                 ERROR_WITH_ERRNO("Failed to open encrypted file \"%ls\" "
767                                  "for raw read", path);
768                 return WIMLIB_ERR_OPEN;
769         }
770         *size_ret = 0;
771         err = ReadEncryptedFileRaw(win32_tally_encrypted_size_cb,
772                                    size_ret, file_ctx);
773         if (err != ERROR_SUCCESS) {
774                 set_errno_from_win32_error(err);
775                 ERROR_WITH_ERRNO("Failed to read raw encrypted data from "
776                                  "\"%ls\"", path);
777                 ret = WIMLIB_ERR_READ;
778         } else {
779                 ret = 0;
780         }
781         CloseEncryptedFileRaw(file_ctx);
782         return ret;
783 }
784
785 /* Scans an unnamed or named stream of a Win32 file (not a reparse point
786  * stream); calculates its SHA1 message digest and either creates a `struct
787  * wim_lookup_table_entry' in memory for it, or uses an existing 'struct
788  * wim_lookup_table_entry' for an identical stream.
789  *
790  * @path:               Path to the file (UTF-16LE).
791  *
792  * @path_num_chars:     Number of 2-byte characters in @path.
793  *
794  * @inode:              WIM inode to save the stream into.
795  *
796  * @lookup_table:       Stream lookup table for the WIM.
797  *
798  * @dat:                A `WIN32_FIND_STREAM_DATA' structure that specifies the
799  *                      stream name.
800  *
801  * Returns 0 on success; nonzero on failure.
802  */
803 static int
804 win32_capture_stream(const wchar_t *path,
805                      size_t path_num_chars,
806                      struct wim_inode *inode,
807                      struct wim_lookup_table *lookup_table,
808                      WIN32_FIND_STREAM_DATA *dat)
809 {
810         struct wim_ads_entry *ads_entry;
811         struct wim_lookup_table_entry *lte;
812         int ret;
813         wchar_t *stream_name, *colon;
814         size_t stream_name_nchars;
815         bool is_named_stream;
816         wchar_t *spath;
817         size_t spath_nchars;
818         size_t spath_buf_nbytes;
819         const wchar_t *relpath_prefix;
820         const wchar_t *colonchar;
821
822         DEBUG("Capture \"%ls\" stream \"%ls\"", path, dat->cStreamName);
823
824         /* The stream name should be returned as :NAME:TYPE */
825         stream_name = dat->cStreamName;
826         if (*stream_name != L':')
827                 goto out_invalid_stream_name;
828         stream_name += 1;
829         colon = wcschr(stream_name, L':');
830         if (colon == NULL)
831                 goto out_invalid_stream_name;
832
833         if (wcscmp(colon + 1, L"$DATA")) {
834                 /* Not a DATA stream */
835                 ret = 0;
836                 goto out;
837         }
838
839         *colon = '\0';
840
841         stream_name_nchars = colon - stream_name;
842         is_named_stream = (stream_name_nchars != 0);
843
844         if (is_named_stream) {
845                 /* Allocate an ADS entry for the named stream. */
846                 ads_entry = inode_add_ads_utf16le(inode, stream_name,
847                                                   stream_name_nchars * sizeof(wchar_t));
848                 if (!ads_entry) {
849                         ret = WIMLIB_ERR_NOMEM;
850                         goto out;
851                 }
852         }
853
854         /* If zero length stream, no lookup table entry needed. */
855         if ((u64)dat->StreamSize.QuadPart == 0) {
856                 ret = 0;
857                 goto out;
858         }
859
860         /* Create a UTF-16LE string @spath that gives the filename, then a
861          * colon, then the stream name.  Or, if it's an unnamed stream, just the
862          * filename.  It is MALLOC()'ed so that it can be saved in the
863          * wim_lookup_table_entry if needed.
864          *
865          * As yet another special case, relative paths need to be changed to
866          * begin with an explicit "./" so that, for example, a file t:ads, where
867          * :ads is the part we added, is not interpreted as a file on the t:
868          * drive. */
869         spath_nchars = path_num_chars;
870         relpath_prefix = L"";
871         colonchar = L"";
872         if (is_named_stream) {
873                 spath_nchars += 1 + stream_name_nchars;
874                 colonchar = L":";
875                 if (path_num_chars == 1 && !is_any_path_separator(path[0])) {
876                         spath_nchars += 2;
877                         static const wchar_t _relpath_prefix[] =
878                                 {L'.', OS_PREFERRED_PATH_SEPARATOR, L'\0'};
879                         relpath_prefix = _relpath_prefix;
880                 }
881         }
882
883         spath_buf_nbytes = (spath_nchars + 1) * sizeof(wchar_t);
884         spath = MALLOC(spath_buf_nbytes);
885
886         tsprintf(spath, L"%ls%ls%ls%ls",
887                  relpath_prefix, path, colonchar, stream_name);
888
889         /* Make a new wim_lookup_table_entry */
890         lte = new_lookup_table_entry();
891         if (!lte) {
892                 ret = WIMLIB_ERR_NOMEM;
893                 goto out_free_spath;
894         }
895         lte->file_on_disk = spath;
896         spath = NULL;
897         if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED && !is_named_stream) {
898                 u64 encrypted_size;
899                 lte->resource_location = RESOURCE_WIN32_ENCRYPTED;
900                 ret = win32_get_encrypted_file_size(path, &encrypted_size);
901                 if (ret)
902                         goto out_free_spath;
903                 lte->size = encrypted_size;
904         } else {
905                 lte->resource_location = RESOURCE_IN_FILE_ON_DISK;
906                 lte->size = (u64)dat->StreamSize.QuadPart;
907         }
908
909         u32 stream_id;
910         if (is_named_stream) {
911                 stream_id = ads_entry->stream_id;
912                 ads_entry->lte = lte;
913         } else {
914                 stream_id = 0;
915                 inode->i_lte = lte;
916         }
917         lookup_table_insert_unhashed(lookup_table, lte, inode, stream_id);
918         ret = 0;
919 out_free_spath:
920         FREE(spath);
921 out:
922         return ret;
923 out_invalid_stream_name:
924         ERROR("Invalid stream name: \"%ls:%ls\"", path, dat->cStreamName);
925         ret = WIMLIB_ERR_READ;
926         goto out;
927 }
928
929 /* Load information about the streams of an open file into a WIM inode.
930  *
931  * By default, we use the NtQueryInformationFile() system call instead of
932  * FindFirstStream() and FindNextStream().  This is done for two reasons:
933  *
934  * - FindFirstStream() opens its own handle to the file or directory and
935  *   apparently does so without specifying FILE_FLAG_BACKUP_SEMANTICS, thereby
936  *   causing access denied errors on certain files (even when running as the
937  *   Administrator).
938  * - FindFirstStream() and FindNextStream() is only available on Windows Vista
939  *   and later, whereas the stream support in NtQueryInformationFile() was
940  *   already present in Windows XP.
941  */
942 static int
943 win32_capture_streams(HANDLE *hFile_p,
944                       const wchar_t *path,
945                       size_t path_num_chars,
946                       struct wim_inode *inode,
947                       struct wim_lookup_table *lookup_table,
948                       u64 file_size,
949                       unsigned vol_flags)
950 {
951         WIN32_FIND_STREAM_DATA dat;
952         int ret;
953 #ifdef WITH_NTDLL
954         u8 _buf[8192] _aligned_attribute(8);
955         u8 *buf;
956         size_t bufsize;
957         IO_STATUS_BLOCK io_status;
958         NTSTATUS status;
959         const FILE_STREAM_INFORMATION *info;
960 #endif
961         HANDLE hFind;
962         DWORD err;
963
964         DEBUG("Capturing streams from \"%ls\"", path);
965
966         if (!(vol_flags & FILE_NAMED_STREAMS))
967                 goto unnamed_only;
968
969 #ifdef WITH_NTDLL
970         if (!func_NtQueryInformationFile)
971                 goto use_FindFirstStream;
972
973         buf = _buf;
974         bufsize = sizeof(_buf);
975
976         /* Get a buffer containing the stream information.  */
977         for (;;) {
978                 status = (*func_NtQueryInformationFile)(*hFile_p, &io_status,
979                                                         buf, bufsize,
980                                                         FileStreamInformation);
981                 if (status == STATUS_SUCCESS) {
982                         break;
983                 } else if (status == STATUS_BUFFER_OVERFLOW) {
984                         u8 *newbuf;
985
986                         bufsize *= 2;
987                         if (buf == _buf)
988                                 newbuf = MALLOC(bufsize);
989                         else
990                                 newbuf = REALLOC(buf, bufsize);
991
992                         if (!newbuf) {
993                                 ret = WIMLIB_ERR_NOMEM;
994                                 goto out_free_buf;
995                         }
996                         buf = newbuf;
997                 } else if (status == STATUS_NOT_IMPLEMENTED ||
998                            status == STATUS_NOT_SUPPORTED ||
999                            status == STATUS_INVALID_INFO_CLASS) {
1000                         goto use_FindFirstStream;
1001                 } else {
1002                         set_errno_from_nt_status(status);
1003                         ERROR_WITH_ERRNO("Failed to read streams of %ls", path);
1004                         ret = WIMLIB_ERR_READ;
1005                         goto out_free_buf;
1006                 }
1007         }
1008
1009         if (io_status.Information == 0) {
1010                 /* No stream information.  */
1011                 ret = 0;
1012                 goto out_free_buf;
1013         }
1014
1015         if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED) {
1016                 /* OpenEncryptedFileRaw() seems to fail with
1017                  * ERROR_SHARING_VIOLATION if there are any handles opened to
1018                  * the file.  */
1019                 CloseHandle(*hFile_p);
1020                 *hFile_p = INVALID_HANDLE_VALUE;
1021         }
1022
1023         /* Parse one or more stream information structures.  */
1024         info = (const FILE_STREAM_INFORMATION*)buf;
1025         for (;;) {
1026                 if (info->StreamNameLength <= sizeof(dat.cStreamName) - 2) {
1027                         dat.StreamSize = info->StreamSize;
1028                         memcpy(dat.cStreamName, info->StreamName, info->StreamNameLength);
1029                         dat.cStreamName[info->StreamNameLength / 2] = L'\0';
1030
1031                         /* Capture the stream.  */
1032                         ret = win32_capture_stream(path, path_num_chars, inode,
1033                                                    lookup_table, &dat);
1034                         if (ret)
1035                                 goto out_free_buf;
1036                 }
1037                 if (info->NextEntryOffset == 0) {
1038                         /* No more stream information.  */
1039                         ret = 0;
1040                         break;
1041                 }
1042                 /* Advance to next stream information.  */
1043                 info = (const FILE_STREAM_INFORMATION*)
1044                                 ((const u8*)info + info->NextEntryOffset);
1045         }
1046 out_free_buf:
1047         /* Free buffer if allocated on heap.  */
1048         if (buf != _buf)
1049                 FREE(buf);
1050         return ret;
1051 #endif /* WITH_NTDLL */
1052
1053 use_FindFirstStream:
1054         if (win32func_FindFirstStreamW == NULL)
1055                 goto unnamed_only;
1056         hFind = win32func_FindFirstStreamW(path, FindStreamInfoStandard, &dat, 0);
1057         if (hFind == INVALID_HANDLE_VALUE) {
1058                 err = GetLastError();
1059                 if (err == ERROR_CALL_NOT_IMPLEMENTED ||
1060                     err == ERROR_NOT_SUPPORTED ||
1061                     err == ERROR_INVALID_FUNCTION ||
1062                     err == ERROR_INVALID_PARAMETER)
1063                         goto unnamed_only;
1064
1065                 /* Seems legal for this to return ERROR_HANDLE_EOF on reparse
1066                  * points and directories */
1067                 if ((inode->i_attributes &
1068                     (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
1069                     && err == ERROR_HANDLE_EOF)
1070                 {
1071                         DEBUG("ERROR_HANDLE_EOF (ok)");
1072                         return 0;
1073                 } else {
1074                         if (err == ERROR_ACCESS_DENIED) {
1075                                 WARNING("Failed to look up data streams "
1076                                         "of \"%ls\": Access denied!\n%ls",
1077                                         path, capture_access_denied_msg);
1078                                 return 0;
1079                         } else {
1080                                 set_errno_from_win32_error(err);
1081                                 ERROR_WITH_ERRNO("Failed to look up data streams "
1082                                                  "of \"%ls\"", path);
1083                                 return WIMLIB_ERR_READ;
1084                         }
1085                 }
1086         }
1087         do {
1088                 ret = win32_capture_stream(path,
1089                                            path_num_chars,
1090                                            inode, lookup_table,
1091                                            &dat);
1092                 if (ret)
1093                         goto out_find_close;
1094         } while (win32func_FindNextStreamW(hFind, &dat));
1095         err = GetLastError();
1096         if (err != ERROR_HANDLE_EOF) {
1097                 set_errno_from_win32_error(err);
1098                 ERROR_WITH_ERRNO("Error reading data streams from "
1099                                  "\"%ls\"", path);
1100                 ret = WIMLIB_ERR_READ;
1101         }
1102 out_find_close:
1103         FindClose(hFind);
1104         return ret;
1105
1106 unnamed_only:
1107         /* FindFirstStream() API is not available, or the volume does not
1108          * support named streams.  Only capture the unnamed data stream. */
1109         DEBUG("Only capturing unnamed data stream");
1110         if (inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
1111                                    FILE_ATTRIBUTE_REPARSE_POINT))
1112                 return 0;
1113
1114         wcscpy(dat.cStreamName, L"::$DATA");
1115         dat.StreamSize.QuadPart = file_size;
1116         return win32_capture_stream(path, path_num_chars,
1117                                     inode, lookup_table, &dat);
1118 }
1119
1120 static int
1121 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
1122                                   wchar_t *path,
1123                                   size_t path_num_chars,
1124                                   struct add_image_params *params,
1125                                   struct win32_capture_state *state,
1126                                   unsigned vol_flags)
1127 {
1128         struct wim_dentry *root = NULL;
1129         struct wim_inode *inode = NULL;
1130         DWORD err;
1131         u64 file_size;
1132         int ret;
1133         u8 *rpbuf;
1134         u16 rpbuflen;
1135         u16 not_rpfixed;
1136         HANDLE hFile = INVALID_HANDLE_VALUE;
1137         DWORD desiredAccess;
1138
1139
1140         if (exclude_path(path, path_num_chars, params->config, true)) {
1141                 if (params->add_flags & WIMLIB_ADD_FLAG_ROOT) {
1142                         ERROR("Cannot exclude the root directory from capture");
1143                         ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
1144                         goto out;
1145                 }
1146                 ret = 0;
1147                 goto out_progress;
1148         }
1149
1150 #if 0
1151         if (path_num_chars >= 4 &&
1152             !wmemcmp(path, L"\\\\?\\", 4) &&
1153             path_num_chars + 1 - 4 > MAX_PATH &&
1154             state->num_long_path_warnings < MAX_CAPTURE_LONG_PATH_WARNINGS)
1155         {
1156                 WARNING("Path \"%ls\" exceeds MAX_PATH", path);
1157                 if (++state->num_long_path_warnings == MAX_CAPTURE_LONG_PATH_WARNINGS)
1158                         WARNING("Suppressing further warnings about long paths.");
1159         }
1160 #endif
1161
1162         desiredAccess = FILE_READ_DATA | FILE_READ_ATTRIBUTES |
1163                         READ_CONTROL | ACCESS_SYSTEM_SECURITY;
1164 again:
1165         hFile = win32_open_existing_file(path, desiredAccess);
1166         if (hFile == INVALID_HANDLE_VALUE) {
1167                 err = GetLastError();
1168                 if (err == ERROR_ACCESS_DENIED || err == ERROR_PRIVILEGE_NOT_HELD) {
1169                         if (desiredAccess & ACCESS_SYSTEM_SECURITY) {
1170                                 desiredAccess &= ~ACCESS_SYSTEM_SECURITY;
1171                                 goto again;
1172                         }
1173                         if (desiredAccess & READ_CONTROL) {
1174                                 desiredAccess &= ~READ_CONTROL;
1175                                 goto again;
1176                         }
1177                 }
1178                 set_errno_from_GetLastError();
1179                 ERROR_WITH_ERRNO("Failed to open \"%ls\" for reading", path);
1180                 ret = WIMLIB_ERR_OPEN;
1181                 goto out;
1182         }
1183
1184         BY_HANDLE_FILE_INFORMATION file_info;
1185         if (!GetFileInformationByHandle(hFile, &file_info)) {
1186                 set_errno_from_GetLastError();
1187                 ERROR_WITH_ERRNO("Failed to get file information for \"%ls\"",
1188                                  path);
1189                 ret = WIMLIB_ERR_STAT;
1190                 goto out;
1191         }
1192
1193         if (file_info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1194                 rpbuf = alloca(REPARSE_POINT_MAX_SIZE);
1195                 ret = win32_get_reparse_data(hFile, path, params,
1196                                              rpbuf, &rpbuflen);
1197                 if (ret < 0) {
1198                         /* WIMLIB_ERR_* (inverted) */
1199                         ret = -ret;
1200                         goto out;
1201                 } else if (ret & RP_FIXED) {
1202                         not_rpfixed = 0;
1203                 } else if (ret == RP_EXCLUDED) {
1204                         ret = 0;
1205                         goto out_progress;
1206                 } else {
1207                         not_rpfixed = 1;
1208                 }
1209         }
1210
1211         /* Create a WIM dentry with an associated inode, which may be shared.
1212          *
1213          * However, we need to explicitly check for directories and files with
1214          * only 1 link and refuse to hard link them.  This is because Windows
1215          * has a bug where it can return duplicate File IDs for files and
1216          * directories on the FAT filesystem. */
1217         ret = inode_table_new_dentry(&params->inode_table,
1218                                      path_basename_with_len(path, path_num_chars),
1219                                      ((u64)file_info.nFileIndexHigh << 32) |
1220                                          (u64)file_info.nFileIndexLow,
1221                                      file_info.dwVolumeSerialNumber,
1222                                      (file_info.nNumberOfLinks <= 1 ||
1223                                         (file_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)),
1224                                      &root);
1225         if (ret)
1226                 goto out;
1227
1228         ret = win32_get_short_name(hFile, path, root);
1229         if (ret)
1230                 goto out;
1231
1232         inode = root->d_inode;
1233
1234         if (inode->i_nlink > 1) {
1235                 /* Shared inode; nothing more to do */
1236                 goto out_progress;
1237         }
1238
1239         inode->i_attributes = file_info.dwFileAttributes;
1240         inode->i_creation_time = FILETIME_to_u64(&file_info.ftCreationTime);
1241         inode->i_last_write_time = FILETIME_to_u64(&file_info.ftLastWriteTime);
1242         inode->i_last_access_time = FILETIME_to_u64(&file_info.ftLastAccessTime);
1243         inode->i_resolved = 1;
1244
1245         params->add_flags &= ~WIMLIB_ADD_FLAG_ROOT;
1246
1247         if (!(params->add_flags & WIMLIB_ADD_FLAG_NO_ACLS)
1248             && (vol_flags & FILE_PERSISTENT_ACLS))
1249         {
1250                 ret = win32_get_security_descriptor(hFile, path, inode,
1251                                                     &params->sd_set, state,
1252                                                     params->add_flags);
1253                 if (ret)
1254                         goto out;
1255         }
1256
1257         file_size = ((u64)file_info.nFileSizeHigh << 32) |
1258                      (u64)file_info.nFileSizeLow;
1259
1260
1261         /* Capture the unnamed data stream (only should be present for regular
1262          * files) and any alternate data streams. */
1263         ret = win32_capture_streams(&hFile,
1264                                     path,
1265                                     path_num_chars,
1266                                     inode,
1267                                     params->lookup_table,
1268                                     file_size,
1269                                     vol_flags);
1270         if (ret)
1271                 goto out;
1272
1273         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1274                 /* Reparse point: set the reparse data (which we read already)
1275                  * */
1276                 inode->i_not_rpfixed = not_rpfixed;
1277                 inode->i_reparse_tag = le32_to_cpu(*(le32*)rpbuf);
1278                 ret = inode_set_unnamed_stream(inode, rpbuf + 8, rpbuflen - 8,
1279                                                params->lookup_table);
1280         } else if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1281                 /* Directory (not a reparse point) --- recurse to children */
1282
1283                 if (hFile == INVALID_HANDLE_VALUE) {
1284                         /* Re-open handle that was closed to read raw encrypted
1285                          * data.  */
1286                         hFile = win32_open_existing_file(path, FILE_READ_DATA);
1287                         if (hFile == INVALID_HANDLE_VALUE) {
1288                                 set_errno_from_GetLastError();
1289                                 ERROR_WITH_ERRNO("Failed to reopen \"%ls\"",
1290                                                  path);
1291                                 ret = WIMLIB_ERR_OPEN;
1292                                 goto out;
1293                         }
1294                 }
1295                 ret = win32_recurse_directory(hFile,
1296                                               path,
1297                                               path_num_chars,
1298                                               root,
1299                                               params,
1300                                               state,
1301                                               vol_flags);
1302         }
1303         if (ret)
1304                 goto out;
1305
1306         path[path_num_chars] = '\0';
1307 out_progress:
1308         params->progress.scan.cur_path = path;
1309         if (root == NULL)
1310                 do_capture_progress(params, WIMLIB_SCAN_DENTRY_EXCLUDED, NULL);
1311         else
1312                 do_capture_progress(params, WIMLIB_SCAN_DENTRY_OK, inode);
1313 out:
1314         if (hFile != INVALID_HANDLE_VALUE)
1315                 CloseHandle(hFile);
1316         if (ret == 0)
1317                 *root_ret = root;
1318         else
1319                 free_dentry_tree(root, params->lookup_table);
1320         return ret;
1321 }
1322
1323 static void
1324 win32_do_capture_warnings(const wchar_t *path,
1325                           const struct win32_capture_state *state,
1326                           int add_flags)
1327 {
1328         if (state->num_get_sacl_priv_notheld == 0 &&
1329             state->num_get_sd_access_denied == 0)
1330                 return;
1331
1332         WARNING("Scan of \"%ls\" complete, but with one or more warnings:", path);
1333         if (state->num_get_sacl_priv_notheld != 0) {
1334                 WARNING("- Could not capture SACL (System Access Control List)\n"
1335                         "            on %lu files or directories.",
1336                         state->num_get_sacl_priv_notheld);
1337         }
1338         if (state->num_get_sd_access_denied != 0) {
1339                 WARNING("- Could not capture security descriptor at all\n"
1340                         "            on %lu files or directories.",
1341                         state->num_get_sd_access_denied);
1342         }
1343         WARNING("To fully capture all security descriptors, run the program\n"
1344                 "          with Administrator rights.");
1345 }
1346
1347 #define WINDOWS_NT_MAX_PATH 32768
1348
1349 /* Win32 version of capturing a directory tree */
1350 int
1351 win32_build_dentry_tree(struct wim_dentry **root_ret,
1352                         const wchar_t *root_disk_path,
1353                         struct add_image_params *params)
1354 {
1355         size_t path_nchars;
1356         wchar_t *path;
1357         int ret;
1358         struct win32_capture_state state;
1359         unsigned vol_flags;
1360         DWORD dret;
1361         bool need_prefix_free = false;
1362
1363         if (!win32func_FindFirstStreamW
1364 #ifdef WITH_NTDLL
1365             && !func_NtQueryInformationFile
1366 #endif
1367            )
1368         {
1369                 WARNING("Running on Windows XP or earlier; "
1370                         "alternate data streams will not be captured.");
1371         }
1372
1373         path_nchars = wcslen(root_disk_path);
1374         if (path_nchars > WINDOWS_NT_MAX_PATH)
1375                 return WIMLIB_ERR_INVALID_PARAM;
1376
1377         ret = win32_get_file_and_vol_ids(root_disk_path,
1378                                          &params->capture_root_ino,
1379                                          &params->capture_root_dev);
1380         if (ret) {
1381                 ERROR_WITH_ERRNO("Can't open %ls", root_disk_path);
1382                 return ret;
1383         }
1384
1385         win32_get_vol_flags(root_disk_path, &vol_flags, NULL);
1386
1387         /* WARNING: There is no check for overflow later when this buffer is
1388          * being used!  But it's as long as the maximum path length understood
1389          * by Windows NT (which is NOT the same as MAX_PATH). */
1390         path = MALLOC(WINDOWS_NT_MAX_PATH * sizeof(wchar_t));
1391         if (!path)
1392                 return WIMLIB_ERR_NOMEM;
1393
1394         /* Work around defective behavior in Windows where paths longer than 260
1395          * characters are not supported by default; instead they need to be
1396          * turned into absolute paths and prefixed with "\\?\".  */
1397
1398         if (wcsncmp(root_disk_path, L"\\\\?\\", 4)) {
1399                 dret = GetFullPathName(root_disk_path, WINDOWS_NT_MAX_PATH - 4,
1400                                        &path[4], NULL);
1401
1402                 if (dret == 0 || dret >= WINDOWS_NT_MAX_PATH - 4) {
1403                         WARNING("Can't get full path name for \"%ls\"", root_disk_path);
1404                         wmemcpy(path, root_disk_path, path_nchars + 1);
1405                 } else {
1406                         wmemcpy(path, L"\\\\?\\", 4);
1407                         path_nchars = 4 + dret;
1408                         /* Update pattern prefix */
1409                         if (params->config != NULL)
1410                         {
1411                                 params->config->_prefix = TSTRDUP(path);
1412                                 params->config->_prefix_num_tchars = path_nchars;
1413                                 if (params->config->_prefix == NULL)
1414                                 {
1415                                         ret = WIMLIB_ERR_NOMEM;
1416                                         goto out_free_path;
1417                                 }
1418                                 need_prefix_free = true;
1419                         }
1420                 }
1421         } else {
1422                 wmemcpy(path, root_disk_path, path_nchars + 1);
1423         }
1424
1425         memset(&state, 0, sizeof(state));
1426         ret = win32_build_dentry_tree_recursive(root_ret, path,
1427                                                 path_nchars, params,
1428                                                 &state, vol_flags);
1429         if (need_prefix_free)
1430                 FREE(params->config->_prefix);
1431 out_free_path:
1432         FREE(path);
1433         if (ret == 0)
1434                 win32_do_capture_warnings(root_disk_path, &state, params->add_flags);
1435         return ret;
1436 }
1437
1438 #endif /* __WIN32__ */