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