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