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