]> wimlib.net Git - wimlib/blob - src/win32_capture.c
Win32 capture/apply: Simplify opening existing files
[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_existing_file(lte->file_on_disk,
94                                                 FILE_READ_DATA);
95         if (hFile == INVALID_HANDLE_VALUE) {
96                 set_errno_from_GetLastError();
97                 ERROR_WITH_ERRNO("Failed to open \"%ls\"", lte->file_on_disk);
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                         set_errno_from_GetLastError();
115                         ERROR_WITH_ERRNO("Failed to read data from \"%ls\"",
116                                          lte->file_on_disk);
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                 set_errno_from_win32_error(err);
223                 ERROR_WITH_ERRNO("Failed to open encrypted file \"%ls\" "
224                                  "for raw read", lte->file_on_disk);
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                 set_errno_from_win32_error(err);
232                 ERROR_WITH_ERRNO("Failed to read encrypted file \"%ls\"",
233                                  lte->file_on_disk);
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  * 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                                 SECURITY_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[4096];
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                                                       (SECURITY_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                         set_errno_from_win32_error(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                                 set_errno_from_nt_status(status);
494                                 ERROR_WITH_ERRNO("Failed to read directory "
495                                                  "\"%ls\"", dir_path);
496                                 ret = WIMLIB_ERR_READ;
497                         }
498                         goto out_free_buf;
499                 }
500                 wimlib_assert(io_status.Information != 0);
501                 info = (const FILE_NAMES_INFORMATION*)buf;
502                 for (;;) {
503                         if (!(info->FileNameLength == 2 && info->FileName[0] == L'.') &&
504                             !(info->FileNameLength == 4 && info->FileName[0] == L'.' &&
505                                                            info->FileName[1] == L'.'))
506                         {
507                                 wchar_t *p;
508                                 struct wim_dentry *child;
509
510                                 p = dir_path + dir_path_num_chars;
511                                 *p++ = L'\\';
512                                 p = wmempcpy(p, info->FileName,
513                                              info->FileNameLength / 2);
514                                 *p = '\0';
515
516                                 ret = win32_build_dentry_tree_recursive(
517                                                                 &child,
518                                                                 dir_path,
519                                                                 p - dir_path,
520                                                                 params,
521                                                                 state,
522                                                                 vol_flags);
523
524                                 dir_path[dir_path_num_chars] = L'\0';
525
526                                 if (ret)
527                                         goto out_free_buf;
528                                 if (child)
529                                         dentry_add_child(root, child);
530                         }
531                         if (info->NextEntryOffset == 0)
532                                 break;
533                         info = (const FILE_NAMES_INFORMATION*)
534                                         ((const u8*)info + info->NextEntryOffset);
535                 }
536         }
537 out_free_buf:
538         FREE(buf);
539         return ret;
540 #else
541         WIN32_FIND_DATAW dat;
542         HANDLE hFind;
543         DWORD err;
544
545         /* Begin reading the directory by calling FindFirstFileW.  Unlike UNIX
546          * opendir(), FindFirstFileW has file globbing built into it.  But this
547          * isn't what we actually want, so just add a dummy glob to get all
548          * entries. */
549         dir_path[dir_path_num_chars] = OS_PREFERRED_PATH_SEPARATOR;
550         dir_path[dir_path_num_chars + 1] = L'*';
551         dir_path[dir_path_num_chars + 2] = L'\0';
552         hFind = FindFirstFileW(dir_path, &dat);
553         dir_path[dir_path_num_chars] = L'\0';
554
555         if (hFind == INVALID_HANDLE_VALUE) {
556                 err = GetLastError();
557                 if (err == ERROR_FILE_NOT_FOUND) {
558                         return 0;
559                 } else {
560                         set_errno_from_win32_error(err);
561                         ERROR_WITH_ERRNO("Failed to read directory \"%ls\"",
562                                          dir_path);
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                 set_errno_from_win32_error(err);
598                 ERROR_WITH_ERRNO("Failed to read directory \"%ls\"", dir_path);
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                 set_errno_from_GetLastError();
784                 ERROR_WITH_ERRNO("Failed to get reparse data of \"%ls\"", path);
785                 return -WIMLIB_ERR_READ;
786         }
787         if (bytesReturned < 8 || bytesReturned > REPARSE_POINT_MAX_SIZE) {
788                 ERROR("Reparse data on \"%ls\" is invalid", path);
789                 return -WIMLIB_ERR_INVALID_REPARSE_DATA;
790         }
791
792         rpbuflen = bytesReturned;
793         reparse_tag = le32_to_cpu(*(le32*)rpbuf);
794         if (params->add_flags & WIMLIB_ADD_FLAG_RPFIX &&
795             (reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
796              reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT))
797         {
798                 /* Try doing reparse point fixup */
799                 ret = win32_capture_try_rpfix(rpbuf,
800                                               &rpbuflen,
801                                               params->capture_root_ino,
802                                               params->capture_root_dev,
803                                               path);
804         } else {
805                 ret = RP_NOT_FIXED;
806         }
807         *rpbuflen_ret = rpbuflen;
808         return ret;
809 }
810
811 static DWORD WINAPI
812 win32_tally_encrypted_size_cb(unsigned char *_data, void *_ctx,
813                               unsigned long len)
814 {
815         *(u64*)_ctx += len;
816         return ERROR_SUCCESS;
817 }
818
819 static int
820 win32_get_encrypted_file_size(const wchar_t *path, u64 *size_ret)
821 {
822         DWORD err;
823         void *file_ctx;
824         int ret;
825
826         *size_ret = 0;
827         err = OpenEncryptedFileRawW(path, 0, &file_ctx);
828         if (err != ERROR_SUCCESS) {
829                 set_errno_from_win32_error(err);
830                 ERROR_WITH_ERRNO("Failed to open encrypted file \"%ls\" "
831                                  "for raw read", path);
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                 set_errno_from_win32_error(err);
838                 ERROR_WITH_ERRNO("Failed to read raw encrypted data from "
839                                  "\"%ls\"", path);
840                 ret = WIMLIB_ERR_READ;
841         } else {
842                 ret = 0;
843         }
844         CloseEncryptedFileRaw(file_ctx);
845         return ret;
846 }
847
848 /* Scans an unnamed or named stream of a Win32 file (not a reparse point
849  * stream); calculates its SHA1 message digest and either creates a `struct
850  * wim_lookup_table_entry' in memory for it, or uses an existing 'struct
851  * wim_lookup_table_entry' for an identical stream.
852  *
853  * @path:               Path to the file (UTF-16LE).
854  *
855  * @path_num_chars:     Number of 2-byte characters in @path.
856  *
857  * @inode:              WIM inode to save the stream into.
858  *
859  * @lookup_table:       Stream lookup table for the WIM.
860  *
861  * @dat:                A `WIN32_FIND_STREAM_DATA' structure that specifies the
862  *                      stream name.
863  *
864  * Returns 0 on success; nonzero on failure.
865  */
866 static int
867 win32_capture_stream(const wchar_t *path,
868                      size_t path_num_chars,
869                      struct wim_inode *inode,
870                      struct wim_lookup_table *lookup_table,
871                      WIN32_FIND_STREAM_DATA *dat)
872 {
873         struct wim_ads_entry *ads_entry;
874         struct wim_lookup_table_entry *lte;
875         int ret;
876         wchar_t *stream_name, *colon;
877         size_t stream_name_nchars;
878         bool is_named_stream;
879         wchar_t *spath;
880         size_t spath_nchars;
881         size_t spath_buf_nbytes;
882         const wchar_t *relpath_prefix;
883         const wchar_t *colonchar;
884
885         DEBUG("Capture \"%ls\" stream \"%ls\"", path, dat->cStreamName);
886
887         /* The stream name should be returned as :NAME:TYPE */
888         stream_name = dat->cStreamName;
889         if (*stream_name != L':')
890                 goto out_invalid_stream_name;
891         stream_name += 1;
892         colon = wcschr(stream_name, L':');
893         if (colon == NULL)
894                 goto out_invalid_stream_name;
895
896         if (wcscmp(colon + 1, L"$DATA")) {
897                 /* Not a DATA stream */
898                 ret = 0;
899                 goto out;
900         }
901
902         *colon = '\0';
903
904         stream_name_nchars = colon - stream_name;
905         is_named_stream = (stream_name_nchars != 0);
906
907         if (is_named_stream) {
908                 /* Allocate an ADS entry for the named stream. */
909                 ads_entry = inode_add_ads_utf16le(inode, stream_name,
910                                                   stream_name_nchars * sizeof(wchar_t));
911                 if (!ads_entry) {
912                         ret = WIMLIB_ERR_NOMEM;
913                         goto out;
914                 }
915         }
916
917         /* If zero length stream, no lookup table entry needed. */
918         if ((u64)dat->StreamSize.QuadPart == 0) {
919                 ret = 0;
920                 goto out;
921         }
922
923         /* Create a UTF-16LE string @spath that gives the filename, then a
924          * colon, then the stream name.  Or, if it's an unnamed stream, just the
925          * filename.  It is MALLOC()'ed so that it can be saved in the
926          * wim_lookup_table_entry if needed.
927          *
928          * As yet another special case, relative paths need to be changed to
929          * begin with an explicit "./" so that, for example, a file t:ads, where
930          * :ads is the part we added, is not interpreted as a file on the t:
931          * drive. */
932         spath_nchars = path_num_chars;
933         relpath_prefix = L"";
934         colonchar = L"";
935         if (is_named_stream) {
936                 spath_nchars += 1 + stream_name_nchars;
937                 colonchar = L":";
938                 if (path_num_chars == 1 && !is_any_path_separator(path[0])) {
939                         spath_nchars += 2;
940                         static const wchar_t _relpath_prefix[] =
941                                 {L'.', OS_PREFERRED_PATH_SEPARATOR, L'\0'};
942                         relpath_prefix = _relpath_prefix;
943                 }
944         }
945
946         spath_buf_nbytes = (spath_nchars + 1) * sizeof(wchar_t);
947         spath = MALLOC(spath_buf_nbytes);
948
949         swprintf(spath, L"%ls%ls%ls%ls",
950                  relpath_prefix, path, colonchar, stream_name);
951
952         /* Make a new wim_lookup_table_entry */
953         lte = new_lookup_table_entry();
954         if (!lte) {
955                 ret = WIMLIB_ERR_NOMEM;
956                 goto out_free_spath;
957         }
958         lte->file_on_disk = spath;
959         spath = NULL;
960         if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED && !is_named_stream) {
961                 u64 encrypted_size;
962                 lte->resource_location = RESOURCE_WIN32_ENCRYPTED;
963                 ret = win32_get_encrypted_file_size(path, &encrypted_size);
964                 if (ret)
965                         goto out_free_spath;
966                 lte->resource_entry.original_size = encrypted_size;
967         } else {
968                 lte->resource_location = RESOURCE_IN_FILE_ON_DISK;
969                 lte->resource_entry.original_size = (u64)dat->StreamSize.QuadPart;
970         }
971
972         u32 stream_id;
973         if (is_named_stream) {
974                 stream_id = ads_entry->stream_id;
975                 ads_entry->lte = lte;
976         } else {
977                 stream_id = 0;
978                 inode->i_lte = lte;
979         }
980         lookup_table_insert_unhashed(lookup_table, lte, inode, stream_id);
981         ret = 0;
982 out_free_spath:
983         FREE(spath);
984 out:
985         return ret;
986 out_invalid_stream_name:
987         ERROR("Invalid stream name: \"%ls:%ls\"", path, dat->cStreamName);
988         ret = WIMLIB_ERR_READ;
989         goto out;
990 }
991
992 /* Load information about the streams of an open file into a WIM inode.
993  *
994  * By default, we use the NtQueryInformationFile() system call instead of
995  * FindFirstStream() and FindNextStream().  This is done for two reasons:
996  *
997  * - FindFirstStream() opens its own handle to the file or directory and
998  *   apparently does so without specifying FILE_FLAG_BACKUP_SEMANTICS, thereby
999  *   causing access denied errors on certain files (even when running as the
1000  *   Administrator).
1001  * - FindFirstStream() and FindNextStream() is only available on Windows Vista
1002  *   and later, whereas the stream support in NtQueryInformationFile() was
1003  *   already present in Windows XP.
1004  */
1005 static int
1006 win32_capture_streams(HANDLE hFile,
1007                       const wchar_t *path,
1008                       size_t path_num_chars,
1009                       struct wim_inode *inode,
1010                       struct wim_lookup_table *lookup_table,
1011                       u64 file_size,
1012                       unsigned vol_flags)
1013 {
1014         WIN32_FIND_STREAM_DATA dat;
1015         int ret;
1016 #ifdef WITH_NTDLL
1017         u8 _buf[8192] _aligned_attribute(8);
1018         u8 *buf;
1019         size_t bufsize;
1020         IO_STATUS_BLOCK io_status;
1021         NTSTATUS status;
1022         const FILE_STREAM_INFORMATION *info;
1023 #else
1024         HANDLE hFind;
1025         DWORD err;
1026 #endif
1027
1028         DEBUG("Capturing streams from \"%ls\"", path);
1029
1030         if (!(vol_flags & FILE_NAMED_STREAMS))
1031                 goto unnamed_only;
1032 #ifndef WITH_NTDLL
1033         if (win32func_FindFirstStreamW == NULL)
1034                 goto unnamed_only;
1035 #endif
1036
1037 #ifdef WITH_NTDLL
1038         buf = _buf;
1039         bufsize = sizeof(_buf);
1040
1041         /* Get a buffer containing the stream information.  */
1042         for (;;) {
1043                 status = NtQueryInformationFile(hFile, &io_status, buf, bufsize,
1044                                                 FileStreamInformation);
1045                 if (status == STATUS_SUCCESS) {
1046                         break;
1047                 } else if (status == STATUS_BUFFER_OVERFLOW) {
1048                         u8 *newbuf;
1049
1050                         bufsize *= 2;
1051                         if (buf == _buf)
1052                                 newbuf = MALLOC(bufsize);
1053                         else
1054                                 newbuf = REALLOC(buf, bufsize);
1055
1056                         if (!newbuf) {
1057                                 ret = WIMLIB_ERR_NOMEM;
1058                                 goto out_free_buf;
1059                         }
1060                         buf = newbuf;
1061                 } else {
1062                         set_errno_from_nt_status(status);
1063                         ERROR_WITH_ERRNO("Failed to read streams of %ls", path);
1064                         ret = WIMLIB_ERR_READ;
1065                         goto out_free_buf;
1066                 }
1067         }
1068
1069         if (io_status.Information == 0) {
1070                 /* No stream information.  */
1071                 ret = 0;
1072                 goto out_free_buf;
1073         }
1074
1075         /* Parse one or more stream information structures.  */
1076         info = (const FILE_STREAM_INFORMATION*)buf;
1077         for (;;) {
1078                 if (info->StreamNameLength <= sizeof(dat.cStreamName) - 2) {
1079                         dat.StreamSize = info->StreamSize;
1080                         memcpy(dat.cStreamName, info->StreamName, info->StreamNameLength);
1081                         dat.cStreamName[info->StreamNameLength / 2] = L'\0';
1082
1083                         /* Capture the stream.  */
1084                         ret = win32_capture_stream(path, path_num_chars, inode,
1085                                                    lookup_table, &dat);
1086                         if (ret)
1087                                 goto out_free_buf;
1088                 }
1089                 if (info->NextEntryOffset == 0) {
1090                         /* No more stream information.  */
1091                         ret = 0;
1092                         break;
1093                 }
1094                 /* Advance to next stream information.  */
1095                 info = (const FILE_STREAM_INFORMATION*)
1096                                 ((const u8*)info + info->NextEntryOffset);
1097         }
1098 out_free_buf:
1099         /* Free buffer if allocated on heap.  */
1100         if (buf != _buf)
1101                 FREE(buf);
1102         return ret;
1103
1104 #else /* WITH_NTDLL */
1105         hFind = win32func_FindFirstStreamW(path, FindStreamInfoStandard, &dat, 0);
1106         if (hFind == INVALID_HANDLE_VALUE) {
1107                 err = GetLastError();
1108                 if (err == ERROR_CALL_NOT_IMPLEMENTED)
1109                         goto unnamed_only;
1110
1111                 /* Seems legal for this to return ERROR_HANDLE_EOF on reparse
1112                  * points and directories */
1113                 if ((inode->i_attributes &
1114                     (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
1115                     && err == ERROR_HANDLE_EOF)
1116                 {
1117                         DEBUG("ERROR_HANDLE_EOF (ok)");
1118                         return 0;
1119                 } else {
1120                         if (err == ERROR_ACCESS_DENIED) {
1121                                 WARNING("Failed to look up data streams "
1122                                         "of \"%ls\": Access denied!\n%ls",
1123                                         path, capture_access_denied_msg);
1124                                 return 0;
1125                         } else {
1126                                 set_errno_from_win32_error(err);
1127                                 ERROR_WITH_ERRNO("Failed to look up data streams "
1128                                                  "of \"%ls\"", path);
1129                                 return WIMLIB_ERR_READ;
1130                         }
1131                 }
1132         }
1133         do {
1134                 ret = win32_capture_stream(path,
1135                                            path_num_chars,
1136                                            inode, lookup_table,
1137                                            &dat);
1138                 if (ret)
1139                         goto out_find_close;
1140         } while (win32func_FindNextStreamW(hFind, &dat));
1141         err = GetLastError();
1142         if (err != ERROR_HANDLE_EOF) {
1143                 set_errno_from_win32_error(err);
1144                 ERROR_WITH_ERRNO("Error reading data streams from "
1145                                  "\"%ls\"", path);
1146                 ret = WIMLIB_ERR_READ;
1147         }
1148 out_find_close:
1149         FindClose(hFind);
1150         return ret;
1151 #endif /* !WITH_NTDLL */
1152
1153 unnamed_only:
1154         /* FindFirstStreamW() API is not available, or the volume does not
1155          * support named streams.  Only capture the unnamed data stream. */
1156         DEBUG("Only capturing unnamed data stream");
1157         if (!(inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
1158                                      FILE_ATTRIBUTE_REPARSE_POINT)))
1159         {
1160                 wcscpy(dat.cStreamName, L"::$DATA");
1161                 dat.StreamSize.QuadPart = file_size;
1162                 ret = win32_capture_stream(path,
1163                                            path_num_chars,
1164                                            inode, lookup_table,
1165                                            &dat);
1166                 if (ret)
1167                         return ret;
1168         }
1169         return ret;
1170 }
1171
1172 static int
1173 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
1174                                   wchar_t *path,
1175                                   size_t path_num_chars,
1176                                   struct add_image_params *params,
1177                                   struct win32_capture_state *state,
1178                                   unsigned vol_flags)
1179 {
1180         struct wim_dentry *root = NULL;
1181         struct wim_inode *inode;
1182         DWORD err;
1183         u64 file_size;
1184         int ret;
1185         u8 *rpbuf;
1186         u16 rpbuflen;
1187         u16 not_rpfixed;
1188         HANDLE hFile;
1189         DWORD desiredAccess;
1190
1191         params->progress.scan.cur_path = path;
1192
1193         if (exclude_path(path, path_num_chars, params->config, true)) {
1194                 if (params->add_flags & WIMLIB_ADD_FLAG_ROOT) {
1195                         ERROR("Cannot exclude the root directory from capture");
1196                         ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
1197                         goto out;
1198                 }
1199                 do_capture_progress(params, WIMLIB_SCAN_DENTRY_EXCLUDED);
1200                 ret = 0;
1201                 goto out;
1202         }
1203
1204 #if 0
1205         if (path_num_chars >= 4 &&
1206             !wmemcmp(path, L"\\\\?\\", 4) &&
1207             path_num_chars + 1 - 4 > MAX_PATH &&
1208             state->num_long_path_warnings < MAX_CAPTURE_LONG_PATH_WARNINGS)
1209         {
1210                 WARNING("Path \"%ls\" exceeds MAX_PATH", path);
1211                 if (++state->num_long_path_warnings == MAX_CAPTURE_LONG_PATH_WARNINGS)
1212                         WARNING("Suppressing further warnings about long paths.");
1213         }
1214 #endif
1215
1216         do_capture_progress(params, WIMLIB_SCAN_DENTRY_OK);
1217
1218         desiredAccess = FILE_READ_DATA | FILE_READ_ATTRIBUTES |
1219                         READ_CONTROL | ACCESS_SYSTEM_SECURITY;
1220 again:
1221         hFile = win32_open_existing_file(path, desiredAccess);
1222         if (hFile == INVALID_HANDLE_VALUE) {
1223                 err = GetLastError();
1224                 if (err == ERROR_ACCESS_DENIED || err == ERROR_PRIVILEGE_NOT_HELD) {
1225                         if (desiredAccess & ACCESS_SYSTEM_SECURITY) {
1226                                 desiredAccess &= ~ACCESS_SYSTEM_SECURITY;
1227                                 goto again;
1228                         }
1229                         if (desiredAccess & READ_CONTROL) {
1230                                 desiredAccess &= ~READ_CONTROL;
1231                                 goto again;
1232                         }
1233                 }
1234                 set_errno_from_GetLastError();
1235                 ERROR_WITH_ERRNO("Failed to open \"%ls\" for reading", path);
1236                 ret = WIMLIB_ERR_OPEN;
1237                 goto out;
1238         }
1239
1240         BY_HANDLE_FILE_INFORMATION file_info;
1241         if (!GetFileInformationByHandle(hFile, &file_info)) {
1242                 set_errno_from_GetLastError();
1243                 ERROR_WITH_ERRNO("Failed to get file information for \"%ls\"",
1244                                  path);
1245                 ret = WIMLIB_ERR_STAT;
1246                 goto out_close_handle;
1247         }
1248
1249         if (file_info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1250                 rpbuf = alloca(REPARSE_POINT_MAX_SIZE);
1251                 ret = win32_get_reparse_data(hFile, path, params,
1252                                              rpbuf, &rpbuflen);
1253                 if (ret < 0) {
1254                         /* WIMLIB_ERR_* (inverted) */
1255                         ret = -ret;
1256                         goto out_close_handle;
1257                 } else if (ret & RP_FIXED) {
1258                         not_rpfixed = 0;
1259                 } else if (ret == RP_EXCLUDED) {
1260                         ret = 0;
1261                         goto out_close_handle;
1262                 } else {
1263                         not_rpfixed = 1;
1264                 }
1265         }
1266
1267         /* Create a WIM dentry with an associated inode, which may be shared.
1268          *
1269          * However, we need to explicitly check for directories and files with
1270          * only 1 link and refuse to hard link them.  This is because Windows
1271          * has a bug where it can return duplicate File IDs for files and
1272          * directories on the FAT filesystem. */
1273         ret = inode_table_new_dentry(&params->inode_table,
1274                                      path_basename_with_len(path, path_num_chars),
1275                                      ((u64)file_info.nFileIndexHigh << 32) |
1276                                          (u64)file_info.nFileIndexLow,
1277                                      file_info.dwVolumeSerialNumber,
1278                                      (file_info.nNumberOfLinks <= 1 ||
1279                                         (file_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)),
1280                                      &root);
1281         if (ret)
1282                 goto out_close_handle;
1283
1284         ret = win32_get_short_name(hFile, path, root);
1285         if (ret)
1286                 goto out_close_handle;
1287
1288         inode = root->d_inode;
1289
1290         if (inode->i_nlink > 1) /* Shared inode; nothing more to do */
1291                 goto out_close_handle;
1292
1293         inode->i_attributes = file_info.dwFileAttributes;
1294         inode->i_creation_time = FILETIME_to_u64(&file_info.ftCreationTime);
1295         inode->i_last_write_time = FILETIME_to_u64(&file_info.ftLastWriteTime);
1296         inode->i_last_access_time = FILETIME_to_u64(&file_info.ftLastAccessTime);
1297         inode->i_resolved = 1;
1298
1299         params->add_flags &= ~WIMLIB_ADD_FLAG_ROOT;
1300
1301         if (!(params->add_flags & WIMLIB_ADD_FLAG_NO_ACLS)
1302             && (vol_flags & FILE_PERSISTENT_ACLS))
1303         {
1304                 ret = win32_get_security_descriptor(hFile, path, inode,
1305                                                     &params->sd_set, state,
1306                                                     params->add_flags);
1307                 if (ret)
1308                         goto out_close_handle;
1309         }
1310
1311         file_size = ((u64)file_info.nFileSizeHigh << 32) |
1312                      (u64)file_info.nFileSizeLow;
1313
1314
1315         /* Capture the unnamed data stream (only should be present for regular
1316          * files) and any alternate data streams. */
1317         ret = win32_capture_streams(hFile,
1318                                     path,
1319                                     path_num_chars,
1320                                     inode,
1321                                     params->lookup_table,
1322                                     file_size,
1323                                     vol_flags);
1324         if (ret)
1325                 goto out_close_handle;
1326
1327         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1328                 /* Reparse point: set the reparse data (which we read already)
1329                  * */
1330                 inode->i_not_rpfixed = not_rpfixed;
1331                 inode->i_reparse_tag = le32_to_cpu(*(le32*)rpbuf);
1332                 ret = inode_set_unnamed_stream(inode, rpbuf + 8, rpbuflen - 8,
1333                                                params->lookup_table);
1334         } else if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1335                 /* Directory (not a reparse point) --- recurse to children */
1336                 ret = win32_recurse_directory(hFile,
1337                                               path,
1338                                               path_num_chars,
1339                                               root,
1340                                               params,
1341                                               state,
1342                                               vol_flags);
1343         }
1344 out_close_handle:
1345         CloseHandle(hFile);
1346 out:
1347         if (ret == 0)
1348                 *root_ret = root;
1349         else
1350                 free_dentry_tree(root, params->lookup_table);
1351         return ret;
1352 }
1353
1354 static void
1355 win32_do_capture_warnings(const wchar_t *path,
1356                           const struct win32_capture_state *state,
1357                           int add_flags)
1358 {
1359         if (state->num_get_sacl_priv_notheld == 0 &&
1360             state->num_get_sd_access_denied == 0)
1361                 return;
1362
1363         WARNING("Scan of \"%ls\" complete, but with one or more warnings:", path);
1364         if (state->num_get_sacl_priv_notheld != 0) {
1365                 WARNING("- Could not capture SACL (System Access Control List)\n"
1366                         "            on %lu files or directories.",
1367                         state->num_get_sacl_priv_notheld);
1368         }
1369         if (state->num_get_sd_access_denied != 0) {
1370                 WARNING("- Could not capture security descriptor at all\n"
1371                         "            on %lu files or directories.",
1372                         state->num_get_sd_access_denied);
1373         }
1374         WARNING("To fully capture all security descriptors, run the program\n"
1375                 "          with Administrator rights.");
1376 }
1377
1378 #define WINDOWS_NT_MAX_PATH 32768
1379
1380 /* Win32 version of capturing a directory tree */
1381 int
1382 win32_build_dentry_tree(struct wim_dentry **root_ret,
1383                         const wchar_t *root_disk_path,
1384                         struct add_image_params *params)
1385 {
1386         size_t path_nchars;
1387         wchar_t *path;
1388         int ret;
1389         struct win32_capture_state state;
1390         unsigned vol_flags;
1391         DWORD dret;
1392         bool need_prefix_free = false;
1393
1394 #ifndef WITH_NTDLL
1395         if (!win32func_FindFirstStreamW) {
1396                 WARNING("Running on Windows XP or earlier; "
1397                         "alternate data streams will not be captured.");
1398         }
1399 #endif
1400
1401         path_nchars = wcslen(root_disk_path);
1402         if (path_nchars > WINDOWS_NT_MAX_PATH)
1403                 return WIMLIB_ERR_INVALID_PARAM;
1404
1405         ret = win32_get_file_and_vol_ids(root_disk_path,
1406                                          &params->capture_root_ino,
1407                                          &params->capture_root_dev);
1408         if (ret) {
1409                 ERROR_WITH_ERRNO("Can't open %ls", root_disk_path);
1410                 return ret;
1411         }
1412
1413         win32_get_vol_flags(root_disk_path, &vol_flags, NULL);
1414
1415         /* WARNING: There is no check for overflow later when this buffer is
1416          * being used!  But it's as long as the maximum path length understood
1417          * by Windows NT (which is NOT the same as MAX_PATH). */
1418         path = MALLOC(WINDOWS_NT_MAX_PATH * sizeof(wchar_t));
1419         if (!path)
1420                 return WIMLIB_ERR_NOMEM;
1421
1422         /* Work around defective behavior in Windows where paths longer than 260
1423          * characters are not supported by default; instead they need to be
1424          * turned into absolute paths and prefixed with "\\?\".  */
1425
1426         if (wcsncmp(root_disk_path, L"\\\\?\\", 4)) {
1427                 dret = GetFullPathName(root_disk_path, WINDOWS_NT_MAX_PATH - 4,
1428                                        &path[4], NULL);
1429
1430                 if (dret == 0 || dret >= WINDOWS_NT_MAX_PATH - 4) {
1431                         WARNING("Can't get full path name for \"%ls\"", root_disk_path);
1432                         wmemcpy(path, root_disk_path, path_nchars + 1);
1433                 } else {
1434                         wmemcpy(path, L"\\\\?\\", 4);
1435                         path_nchars = 4 + dret;
1436                         /* Update pattern prefix */
1437                         if (params->config != NULL)
1438                         {
1439                                 params->config->_prefix = TSTRDUP(path);
1440                                 params->config->_prefix_num_tchars = path_nchars;
1441                                 if (params->config->_prefix == NULL)
1442                                 {
1443                                         ret = WIMLIB_ERR_NOMEM;
1444                                         goto out_free_path;
1445                                 }
1446                                 need_prefix_free = true;
1447                         }
1448                 }
1449         } else {
1450                 wmemcpy(path, root_disk_path, path_nchars + 1);
1451         }
1452
1453         memset(&state, 0, sizeof(state));
1454         ret = win32_build_dentry_tree_recursive(root_ret, path,
1455                                                 path_nchars, params,
1456                                                 &state, vol_flags);
1457         if (need_prefix_free)
1458                 FREE(params->config->_prefix);
1459 out_free_path:
1460         FREE(path);
1461         if (ret == 0)
1462                 win32_do_capture_warnings(root_disk_path, &state, params->add_flags);
1463         return ret;
1464 }
1465
1466 #endif /* __WIN32__ */