Win32 capture: Fix sharing violation when getting size of encrypted stream
[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 = OpenEncryptedFileRaw(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 = FindFirstFile(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 (FindNextFile(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 *_size_ret,
813                               unsigned long len)
814 {
815         *(u64*)_size_ret += 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         err = OpenEncryptedFileRaw(path, 0, &file_ctx);
827         if (err != ERROR_SUCCESS) {
828                 set_errno_from_win32_error(err);
829                 ERROR_WITH_ERRNO("Failed to open encrypted file \"%ls\" "
830                                  "for raw read", path);
831                 return WIMLIB_ERR_OPEN;
832         }
833         *size_ret = 0;
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_p,
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_p, &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         if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED) {
1076                 /* OpenEncryptedFileRaw() seems to fail with
1077                  * ERROR_SHARING_VIOLATION if there are any handles opened to
1078                  * the file.  */
1079                 CloseHandle(*hFile_p);
1080                 *hFile_p = INVALID_HANDLE_VALUE;
1081         }
1082
1083         /* Parse one or more stream information structures.  */
1084         info = (const FILE_STREAM_INFORMATION*)buf;
1085         for (;;) {
1086                 if (info->StreamNameLength <= sizeof(dat.cStreamName) - 2) {
1087                         dat.StreamSize = info->StreamSize;
1088                         memcpy(dat.cStreamName, info->StreamName, info->StreamNameLength);
1089                         dat.cStreamName[info->StreamNameLength / 2] = L'\0';
1090
1091                         /* Capture the stream.  */
1092                         ret = win32_capture_stream(path, path_num_chars, inode,
1093                                                    lookup_table, &dat);
1094                         if (ret)
1095                                 goto out_free_buf;
1096                 }
1097                 if (info->NextEntryOffset == 0) {
1098                         /* No more stream information.  */
1099                         ret = 0;
1100                         break;
1101                 }
1102                 /* Advance to next stream information.  */
1103                 info = (const FILE_STREAM_INFORMATION*)
1104                                 ((const u8*)info + info->NextEntryOffset);
1105         }
1106 out_free_buf:
1107         /* Free buffer if allocated on heap.  */
1108         if (buf != _buf)
1109                 FREE(buf);
1110         return ret;
1111
1112 #else /* WITH_NTDLL */
1113         hFind = win32func_FindFirstStreamW(path, FindStreamInfoStandard, &dat, 0);
1114         if (hFind == INVALID_HANDLE_VALUE) {
1115                 err = GetLastError();
1116                 if (err == ERROR_CALL_NOT_IMPLEMENTED)
1117                         goto unnamed_only;
1118
1119                 /* Seems legal for this to return ERROR_HANDLE_EOF on reparse
1120                  * points and directories */
1121                 if ((inode->i_attributes &
1122                     (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
1123                     && err == ERROR_HANDLE_EOF)
1124                 {
1125                         DEBUG("ERROR_HANDLE_EOF (ok)");
1126                         return 0;
1127                 } else {
1128                         if (err == ERROR_ACCESS_DENIED) {
1129                                 WARNING("Failed to look up data streams "
1130                                         "of \"%ls\": Access denied!\n%ls",
1131                                         path, capture_access_denied_msg);
1132                                 return 0;
1133                         } else {
1134                                 set_errno_from_win32_error(err);
1135                                 ERROR_WITH_ERRNO("Failed to look up data streams "
1136                                                  "of \"%ls\"", path);
1137                                 return WIMLIB_ERR_READ;
1138                         }
1139                 }
1140         }
1141         do {
1142                 ret = win32_capture_stream(path,
1143                                            path_num_chars,
1144                                            inode, lookup_table,
1145                                            &dat);
1146                 if (ret)
1147                         goto out_find_close;
1148         } while (win32func_FindNextStreamW(hFind, &dat));
1149         err = GetLastError();
1150         if (err != ERROR_HANDLE_EOF) {
1151                 set_errno_from_win32_error(err);
1152                 ERROR_WITH_ERRNO("Error reading data streams from "
1153                                  "\"%ls\"", path);
1154                 ret = WIMLIB_ERR_READ;
1155         }
1156 out_find_close:
1157         FindClose(hFind);
1158         return ret;
1159 #endif /* !WITH_NTDLL */
1160
1161 unnamed_only:
1162         /* FindFirstStream() API is not available, or the volume does not
1163          * support named streams.  Only capture the unnamed data stream. */
1164         DEBUG("Only capturing unnamed data stream");
1165         if (!(inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
1166                                      FILE_ATTRIBUTE_REPARSE_POINT)))
1167         {
1168                 wcscpy(dat.cStreamName, L"::$DATA");
1169                 dat.StreamSize.QuadPart = file_size;
1170                 ret = win32_capture_stream(path,
1171                                            path_num_chars,
1172                                            inode, lookup_table,
1173                                            &dat);
1174                 if (ret)
1175                         return ret;
1176         }
1177         return ret;
1178 }
1179
1180 static int
1181 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
1182                                   wchar_t *path,
1183                                   size_t path_num_chars,
1184                                   struct add_image_params *params,
1185                                   struct win32_capture_state *state,
1186                                   unsigned vol_flags)
1187 {
1188         struct wim_dentry *root = NULL;
1189         struct wim_inode *inode;
1190         DWORD err;
1191         u64 file_size;
1192         int ret;
1193         u8 *rpbuf;
1194         u16 rpbuflen;
1195         u16 not_rpfixed;
1196         HANDLE hFile;
1197         DWORD desiredAccess;
1198
1199         params->progress.scan.cur_path = path;
1200
1201         if (exclude_path(path, path_num_chars, params->config, true)) {
1202                 if (params->add_flags & WIMLIB_ADD_FLAG_ROOT) {
1203                         ERROR("Cannot exclude the root directory from capture");
1204                         ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
1205                         goto out;
1206                 }
1207                 do_capture_progress(params, WIMLIB_SCAN_DENTRY_EXCLUDED);
1208                 ret = 0;
1209                 goto out;
1210         }
1211
1212 #if 0
1213         if (path_num_chars >= 4 &&
1214             !wmemcmp(path, L"\\\\?\\", 4) &&
1215             path_num_chars + 1 - 4 > MAX_PATH &&
1216             state->num_long_path_warnings < MAX_CAPTURE_LONG_PATH_WARNINGS)
1217         {
1218                 WARNING("Path \"%ls\" exceeds MAX_PATH", path);
1219                 if (++state->num_long_path_warnings == MAX_CAPTURE_LONG_PATH_WARNINGS)
1220                         WARNING("Suppressing further warnings about long paths.");
1221         }
1222 #endif
1223
1224         do_capture_progress(params, WIMLIB_SCAN_DENTRY_OK);
1225
1226         desiredAccess = FILE_READ_DATA | FILE_READ_ATTRIBUTES |
1227                         READ_CONTROL | ACCESS_SYSTEM_SECURITY;
1228 again:
1229         hFile = win32_open_existing_file(path, desiredAccess);
1230         if (hFile == INVALID_HANDLE_VALUE) {
1231                 err = GetLastError();
1232                 if (err == ERROR_ACCESS_DENIED || err == ERROR_PRIVILEGE_NOT_HELD) {
1233                         if (desiredAccess & ACCESS_SYSTEM_SECURITY) {
1234                                 desiredAccess &= ~ACCESS_SYSTEM_SECURITY;
1235                                 goto again;
1236                         }
1237                         if (desiredAccess & READ_CONTROL) {
1238                                 desiredAccess &= ~READ_CONTROL;
1239                                 goto again;
1240                         }
1241                 }
1242                 set_errno_from_GetLastError();
1243                 ERROR_WITH_ERRNO("Failed to open \"%ls\" for reading", path);
1244                 ret = WIMLIB_ERR_OPEN;
1245                 goto out;
1246         }
1247
1248         BY_HANDLE_FILE_INFORMATION file_info;
1249         if (!GetFileInformationByHandle(hFile, &file_info)) {
1250                 set_errno_from_GetLastError();
1251                 ERROR_WITH_ERRNO("Failed to get file information for \"%ls\"",
1252                                  path);
1253                 ret = WIMLIB_ERR_STAT;
1254                 goto out_close_handle;
1255         }
1256
1257         if (file_info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1258                 rpbuf = alloca(REPARSE_POINT_MAX_SIZE);
1259                 ret = win32_get_reparse_data(hFile, path, params,
1260                                              rpbuf, &rpbuflen);
1261                 if (ret < 0) {
1262                         /* WIMLIB_ERR_* (inverted) */
1263                         ret = -ret;
1264                         goto out_close_handle;
1265                 } else if (ret & RP_FIXED) {
1266                         not_rpfixed = 0;
1267                 } else if (ret == RP_EXCLUDED) {
1268                         ret = 0;
1269                         goto out_close_handle;
1270                 } else {
1271                         not_rpfixed = 1;
1272                 }
1273         }
1274
1275         /* Create a WIM dentry with an associated inode, which may be shared.
1276          *
1277          * However, we need to explicitly check for directories and files with
1278          * only 1 link and refuse to hard link them.  This is because Windows
1279          * has a bug where it can return duplicate File IDs for files and
1280          * directories on the FAT filesystem. */
1281         ret = inode_table_new_dentry(&params->inode_table,
1282                                      path_basename_with_len(path, path_num_chars),
1283                                      ((u64)file_info.nFileIndexHigh << 32) |
1284                                          (u64)file_info.nFileIndexLow,
1285                                      file_info.dwVolumeSerialNumber,
1286                                      (file_info.nNumberOfLinks <= 1 ||
1287                                         (file_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)),
1288                                      &root);
1289         if (ret)
1290                 goto out_close_handle;
1291
1292         ret = win32_get_short_name(hFile, path, root);
1293         if (ret)
1294                 goto out_close_handle;
1295
1296         inode = root->d_inode;
1297
1298         if (inode->i_nlink > 1) /* Shared inode; nothing more to do */
1299                 goto out_close_handle;
1300
1301         inode->i_attributes = file_info.dwFileAttributes;
1302         inode->i_creation_time = FILETIME_to_u64(&file_info.ftCreationTime);
1303         inode->i_last_write_time = FILETIME_to_u64(&file_info.ftLastWriteTime);
1304         inode->i_last_access_time = FILETIME_to_u64(&file_info.ftLastAccessTime);
1305         inode->i_resolved = 1;
1306
1307         params->add_flags &= ~WIMLIB_ADD_FLAG_ROOT;
1308
1309         if (!(params->add_flags & WIMLIB_ADD_FLAG_NO_ACLS)
1310             && (vol_flags & FILE_PERSISTENT_ACLS))
1311         {
1312                 ret = win32_get_security_descriptor(hFile, path, inode,
1313                                                     &params->sd_set, state,
1314                                                     params->add_flags);
1315                 if (ret)
1316                         goto out_close_handle;
1317         }
1318
1319         file_size = ((u64)file_info.nFileSizeHigh << 32) |
1320                      (u64)file_info.nFileSizeLow;
1321
1322
1323         /* Capture the unnamed data stream (only should be present for regular
1324          * files) and any alternate data streams. */
1325         ret = win32_capture_streams(&hFile,
1326                                     path,
1327                                     path_num_chars,
1328                                     inode,
1329                                     params->lookup_table,
1330                                     file_size,
1331                                     vol_flags);
1332         if (ret)
1333                 goto out_close_handle;
1334
1335         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1336                 /* Reparse point: set the reparse data (which we read already)
1337                  * */
1338                 inode->i_not_rpfixed = not_rpfixed;
1339                 inode->i_reparse_tag = le32_to_cpu(*(le32*)rpbuf);
1340                 ret = inode_set_unnamed_stream(inode, rpbuf + 8, rpbuflen - 8,
1341                                                params->lookup_table);
1342         } else if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1343                 /* Directory (not a reparse point) --- recurse to children */
1344
1345                 if (hFile == INVALID_HANDLE_VALUE) {
1346                         /* Re-open handle that was closed to read raw encrypted
1347                          * data.  */
1348                         hFile = win32_open_existing_file(path, FILE_READ_DATA);
1349                         if (hFile == INVALID_HANDLE_VALUE) {
1350                                 set_errno_from_GetLastError();
1351                                 ERROR_WITH_ERRNO("Failed to reopen \"%ls\"",
1352                                                  path);
1353                                 ret = WIMLIB_ERR_OPEN;
1354                                 goto out_close_handle;
1355                         }
1356                 }
1357                 ret = win32_recurse_directory(hFile,
1358                                               path,
1359                                               path_num_chars,
1360                                               root,
1361                                               params,
1362                                               state,
1363                                               vol_flags);
1364         }
1365 out_close_handle:
1366         CloseHandle(hFile);
1367 out:
1368         if (ret == 0)
1369                 *root_ret = root;
1370         else
1371                 free_dentry_tree(root, params->lookup_table);
1372         return ret;
1373 }
1374
1375 static void
1376 win32_do_capture_warnings(const wchar_t *path,
1377                           const struct win32_capture_state *state,
1378                           int add_flags)
1379 {
1380         if (state->num_get_sacl_priv_notheld == 0 &&
1381             state->num_get_sd_access_denied == 0)
1382                 return;
1383
1384         WARNING("Scan of \"%ls\" complete, but with one or more warnings:", path);
1385         if (state->num_get_sacl_priv_notheld != 0) {
1386                 WARNING("- Could not capture SACL (System Access Control List)\n"
1387                         "            on %lu files or directories.",
1388                         state->num_get_sacl_priv_notheld);
1389         }
1390         if (state->num_get_sd_access_denied != 0) {
1391                 WARNING("- Could not capture security descriptor at all\n"
1392                         "            on %lu files or directories.",
1393                         state->num_get_sd_access_denied);
1394         }
1395         WARNING("To fully capture all security descriptors, run the program\n"
1396                 "          with Administrator rights.");
1397 }
1398
1399 #define WINDOWS_NT_MAX_PATH 32768
1400
1401 /* Win32 version of capturing a directory tree */
1402 int
1403 win32_build_dentry_tree(struct wim_dentry **root_ret,
1404                         const wchar_t *root_disk_path,
1405                         struct add_image_params *params)
1406 {
1407         size_t path_nchars;
1408         wchar_t *path;
1409         int ret;
1410         struct win32_capture_state state;
1411         unsigned vol_flags;
1412         DWORD dret;
1413         bool need_prefix_free = false;
1414
1415 #ifndef WITH_NTDLL
1416         if (!win32func_FindFirstStreamW) {
1417                 WARNING("Running on Windows XP or earlier; "
1418                         "alternate data streams will not be captured.");
1419         }
1420 #endif
1421
1422         path_nchars = wcslen(root_disk_path);
1423         if (path_nchars > WINDOWS_NT_MAX_PATH)
1424                 return WIMLIB_ERR_INVALID_PARAM;
1425
1426         ret = win32_get_file_and_vol_ids(root_disk_path,
1427                                          &params->capture_root_ino,
1428                                          &params->capture_root_dev);
1429         if (ret) {
1430                 ERROR_WITH_ERRNO("Can't open %ls", root_disk_path);
1431                 return ret;
1432         }
1433
1434         win32_get_vol_flags(root_disk_path, &vol_flags, NULL);
1435
1436         /* WARNING: There is no check for overflow later when this buffer is
1437          * being used!  But it's as long as the maximum path length understood
1438          * by Windows NT (which is NOT the same as MAX_PATH). */
1439         path = MALLOC(WINDOWS_NT_MAX_PATH * sizeof(wchar_t));
1440         if (!path)
1441                 return WIMLIB_ERR_NOMEM;
1442
1443         /* Work around defective behavior in Windows where paths longer than 260
1444          * characters are not supported by default; instead they need to be
1445          * turned into absolute paths and prefixed with "\\?\".  */
1446
1447         if (wcsncmp(root_disk_path, L"\\\\?\\", 4)) {
1448                 dret = GetFullPathName(root_disk_path, WINDOWS_NT_MAX_PATH - 4,
1449                                        &path[4], NULL);
1450
1451                 if (dret == 0 || dret >= WINDOWS_NT_MAX_PATH - 4) {
1452                         WARNING("Can't get full path name for \"%ls\"", root_disk_path);
1453                         wmemcpy(path, root_disk_path, path_nchars + 1);
1454                 } else {
1455                         wmemcpy(path, L"\\\\?\\", 4);
1456                         path_nchars = 4 + dret;
1457                         /* Update pattern prefix */
1458                         if (params->config != NULL)
1459                         {
1460                                 params->config->_prefix = TSTRDUP(path);
1461                                 params->config->_prefix_num_tchars = path_nchars;
1462                                 if (params->config->_prefix == NULL)
1463                                 {
1464                                         ret = WIMLIB_ERR_NOMEM;
1465                                         goto out_free_path;
1466                                 }
1467                                 need_prefix_free = true;
1468                         }
1469                 }
1470         } else {
1471                 wmemcpy(path, root_disk_path, path_nchars + 1);
1472         }
1473
1474         memset(&state, 0, sizeof(state));
1475         ret = win32_build_dentry_tree_recursive(root_ret, path,
1476                                                 path_nchars, params,
1477                                                 &state, vol_flags);
1478         if (need_prefix_free)
1479                 FREE(params->config->_prefix);
1480 out_free_path:
1481         FREE(path);
1482         if (ret == 0)
1483                 win32_do_capture_warnings(root_disk_path, &state, params->add_flags);
1484         return ret;
1485 }
1486
1487 #endif /* __WIN32__ */