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