Refactor headers
[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 #define MAX_GET_SD_ACCESS_DENIED_WARNINGS 1
40 #define MAX_GET_SACL_PRIV_NOTHELD_WARNINGS 1
41 struct win32_capture_state {
42         unsigned long num_get_sd_access_denied;
43         unsigned long num_get_sacl_priv_notheld;
44 };
45
46
47 static const wchar_t *capture_access_denied_msg =
48 L"         If you are not running this program as the administrator, you may\n"
49  "         need to do so, so that all data and metadata can be backed up.\n"
50  "         Otherwise, there may be no way to access the desired data or\n"
51  "         metadata without taking ownership of the file or directory.\n"
52  ;
53
54 int
55 read_win32_file_prefix(const struct wim_lookup_table_entry *lte,
56                        u64 size,
57                        consume_data_callback_t cb,
58                        void *ctx_or_buf,
59                        int _ignored_flags)
60 {
61         int ret = 0;
62         void *out_buf;
63         DWORD err;
64         u64 bytes_remaining;
65
66         HANDLE hFile = win32_open_file_data_only(lte->file_on_disk);
67         if (hFile == INVALID_HANDLE_VALUE) {
68                 err = GetLastError();
69                 ERROR("Failed to open \"%ls\"", lte->file_on_disk);
70                 win32_error(err);
71                 return WIMLIB_ERR_OPEN;
72         }
73
74         if (cb)
75                 out_buf = alloca(WIM_CHUNK_SIZE);
76         else
77                 out_buf = ctx_or_buf;
78
79         bytes_remaining = size;
80         while (bytes_remaining) {
81                 DWORD bytesToRead, bytesRead;
82
83                 bytesToRead = min(WIM_CHUNK_SIZE, bytes_remaining);
84                 if (!ReadFile(hFile, out_buf, bytesToRead, &bytesRead, NULL) ||
85                     bytesRead != bytesToRead)
86                 {
87                         err = GetLastError();
88                         ERROR("Failed to read data from \"%ls\"", lte->file_on_disk);
89                         win32_error(err);
90                         ret = WIMLIB_ERR_READ;
91                         break;
92                 }
93                 bytes_remaining -= bytesRead;
94                 if (cb) {
95                         ret = (*cb)(out_buf, bytesRead, ctx_or_buf);
96                         if (ret)
97                                 break;
98                 } else {
99                         out_buf += bytesRead;
100                 }
101         }
102         CloseHandle(hFile);
103         return ret;
104 }
105
106 struct win32_encrypted_read_ctx {
107         consume_data_callback_t read_prefix_cb;
108         void *read_prefix_ctx_or_buf;
109         int wimlib_err_code;
110         void *buf;
111         size_t buf_filled;
112         u64 bytes_remaining;
113 };
114
115 static DWORD WINAPI
116 win32_encrypted_export_cb(unsigned char *_data, void *_ctx, unsigned long len)
117 {
118         const void *data = _data;
119         struct win32_encrypted_read_ctx *ctx = _ctx;
120         int ret;
121
122         DEBUG("len = %lu", len);
123         if (ctx->read_prefix_cb) {
124                 /* The length of the buffer passed to the ReadEncryptedFileRaw()
125                  * export callback is undocumented, so we assume it may be of
126                  * arbitrary size. */
127                 size_t bytes_to_buffer = min(ctx->bytes_remaining - ctx->buf_filled,
128                                              len);
129                 while (bytes_to_buffer) {
130                         size_t bytes_to_copy_to_buf =
131                                 min(bytes_to_buffer, WIM_CHUNK_SIZE - ctx->buf_filled);
132
133                         memcpy(ctx->buf + ctx->buf_filled, data,
134                                bytes_to_copy_to_buf);
135                         ctx->buf_filled += bytes_to_copy_to_buf;
136                         data += bytes_to_copy_to_buf;
137                         bytes_to_buffer -= bytes_to_copy_to_buf;
138
139                         if (ctx->buf_filled == WIM_CHUNK_SIZE ||
140                             ctx->buf_filled == ctx->bytes_remaining)
141                         {
142                                 ret = (*ctx->read_prefix_cb)(ctx->buf,
143                                                              ctx->buf_filled,
144                                                              ctx->read_prefix_ctx_or_buf);
145                                 if (ret) {
146                                         ctx->wimlib_err_code = ret;
147                                         /* Shouldn't matter what error code is returned
148                                          * here, as long as it isn't ERROR_SUCCESS. */
149                                         return ERROR_READ_FAULT;
150                                 }
151                                 ctx->bytes_remaining -= ctx->buf_filled;
152                                 ctx->buf_filled = 0;
153                         }
154                 }
155         } else {
156                 size_t len_to_copy = min(len, ctx->bytes_remaining);
157                 memcpy(ctx->read_prefix_ctx_or_buf, data, len_to_copy);
158                 ctx->bytes_remaining -= len_to_copy;
159                 ctx->read_prefix_ctx_or_buf += len_to_copy;
160         }
161         return ERROR_SUCCESS;
162 }
163
164 int
165 read_win32_encrypted_file_prefix(const struct wim_lookup_table_entry *lte,
166                                  u64 size,
167                                  consume_data_callback_t cb,
168                                  void *ctx_or_buf,
169                                  int _ignored_flags)
170 {
171         struct win32_encrypted_read_ctx export_ctx;
172         DWORD err;
173         void *file_ctx;
174         int ret;
175
176         DEBUG("Reading %"PRIu64" bytes from encryted file \"%ls\"",
177               size, lte->file_on_disk);
178
179         export_ctx.read_prefix_cb = cb;
180         export_ctx.read_prefix_ctx_or_buf = ctx_or_buf;
181         export_ctx.wimlib_err_code = 0;
182         if (cb) {
183                 export_ctx.buf = MALLOC(WIM_CHUNK_SIZE);
184                 if (!export_ctx.buf)
185                         return WIMLIB_ERR_NOMEM;
186         } else {
187                 export_ctx.buf = NULL;
188         }
189         export_ctx.buf_filled = 0;
190         export_ctx.bytes_remaining = size;
191
192         err = OpenEncryptedFileRawW(lte->file_on_disk, 0, &file_ctx);
193         if (err != ERROR_SUCCESS) {
194                 ERROR("Failed to open encrypted file \"%ls\" for raw read",
195                       lte->file_on_disk);
196                 win32_error(err);
197                 ret = WIMLIB_ERR_OPEN;
198                 goto out_free_buf;
199         }
200         err = ReadEncryptedFileRaw(win32_encrypted_export_cb,
201                                    &export_ctx, file_ctx);
202         if (err != ERROR_SUCCESS) {
203                 ERROR("Failed to read encrypted file \"%ls\"",
204                       lte->file_on_disk);
205                 win32_error(err);
206                 ret = export_ctx.wimlib_err_code;
207                 if (ret == 0)
208                         ret = WIMLIB_ERR_READ;
209         } else if (export_ctx.bytes_remaining != 0) {
210                 ERROR("Only could read %"PRIu64" of %"PRIu64" bytes from "
211                       "encryted file \"%ls\"",
212                       size - export_ctx.bytes_remaining, size,
213                       lte->file_on_disk);
214                 ret = WIMLIB_ERR_READ;
215         } else {
216                 ret = 0;
217         }
218         CloseEncryptedFileRaw(file_ctx);
219 out_free_buf:
220         FREE(export_ctx.buf);
221         return ret;
222 }
223
224
225 static u64
226 FILETIME_to_u64(const FILETIME *ft)
227 {
228         return ((u64)ft->dwHighDateTime << 32) | (u64)ft->dwLowDateTime;
229 }
230
231 static int
232 win32_get_short_name(struct wim_dentry *dentry, const wchar_t *path)
233 {
234         WIN32_FIND_DATAW dat;
235         HANDLE hFind;
236         int ret = 0;
237
238         /* If we can't read the short filename for some reason, we just ignore
239          * the error and assume the file has no short name.  I don't think this
240          * should be an issue, since the short names are essentially obsolete
241          * anyway. */
242         hFind = FindFirstFileW(path, &dat);
243         if (hFind != INVALID_HANDLE_VALUE) {
244                 if (dat.cAlternateFileName[0] != L'\0') {
245                         DEBUG("\"%ls\": short name \"%ls\"", path, dat.cAlternateFileName);
246                         size_t short_name_nbytes = wcslen(dat.cAlternateFileName) *
247                                                    sizeof(wchar_t);
248                         size_t n = short_name_nbytes + sizeof(wchar_t);
249                         dentry->short_name = MALLOC(n);
250                         if (dentry->short_name) {
251                                 memcpy(dentry->short_name, dat.cAlternateFileName, n);
252                                 dentry->short_name_nbytes = short_name_nbytes;
253                         } else {
254                                 ret = WIMLIB_ERR_NOMEM;
255                         }
256                 }
257                 FindClose(hFind);
258         }
259         return ret;
260 }
261
262 static int
263 win32_get_security_descriptor(struct wim_dentry *dentry,
264                               struct wim_sd_set *sd_set,
265                               const wchar_t *path,
266                               struct win32_capture_state *state,
267                               int add_flags)
268 {
269         SECURITY_INFORMATION requestedInformation;
270         DWORD lenNeeded = 0;
271         BOOL status;
272         DWORD err;
273         unsigned long n;
274
275         requestedInformation = DACL_SECURITY_INFORMATION |
276                                SACL_SECURITY_INFORMATION |
277                                OWNER_SECURITY_INFORMATION |
278                                GROUP_SECURITY_INFORMATION;
279 again:
280         /* Request length of security descriptor */
281         status = GetFileSecurityW(path, requestedInformation,
282                                   NULL, 0, &lenNeeded);
283         err = GetLastError();
284         if (!status && err == ERROR_INSUFFICIENT_BUFFER) {
285                 DWORD len = lenNeeded;
286                 char buf[len];
287                 if (GetFileSecurityW(path, requestedInformation,
288                                      (PSECURITY_DESCRIPTOR)buf, len, &lenNeeded))
289                 {
290                         int security_id = sd_set_add_sd(sd_set, buf, len);
291                         if (security_id < 0)
292                                 return WIMLIB_ERR_NOMEM;
293                         else {
294                                 dentry->d_inode->i_security_id = security_id;
295                                 return 0;
296                         }
297                 } else {
298                         err = GetLastError();
299                 }
300         }
301
302         if (add_flags & WIMLIB_ADD_FLAG_STRICT_ACLS)
303                 goto fail;
304
305         switch (err) {
306         case ERROR_PRIVILEGE_NOT_HELD:
307                 if (requestedInformation & SACL_SECURITY_INFORMATION) {
308                         n = state->num_get_sacl_priv_notheld++;
309                         requestedInformation &= ~SACL_SECURITY_INFORMATION;
310                         if (n < MAX_GET_SACL_PRIV_NOTHELD_WARNINGS) {
311                                 WARNING(
312 "We don't have enough privileges to read the full security\n"
313 "          descriptor of \"%ls\"!\n"
314 "          Re-trying with SACL omitted.\n", path);
315                         } else if (n == MAX_GET_SACL_PRIV_NOTHELD_WARNINGS) {
316                                 WARNING(
317 "Suppressing further privileges not held error messages when reading\n"
318 "          security descriptors.");
319                         }
320                         goto again;
321                 }
322                 /* Fall through */
323         case ERROR_ACCESS_DENIED:
324                 n = state->num_get_sd_access_denied++;
325                 if (n < MAX_GET_SD_ACCESS_DENIED_WARNINGS) {
326                         WARNING("Failed to read security descriptor of \"%ls\": "
327                                 "Access denied!\n%ls", path, capture_access_denied_msg);
328                 } else if (n == MAX_GET_SD_ACCESS_DENIED_WARNINGS) {
329                         WARNING("Suppressing further access denied errors messages i"
330                                 "when reading security descriptors");
331                 }
332                 return 0;
333         default:
334 fail:
335                 ERROR("Failed to read security descriptor of \"%ls\"", path);
336                 win32_error(err);
337                 return WIMLIB_ERR_READ;
338         }
339 }
340
341 static int
342 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
343                                   wchar_t *path,
344                                   size_t path_num_chars,
345                                   struct add_image_params *params,
346                                   struct win32_capture_state *state,
347                                   unsigned vol_flags);
348
349 /* Reads the directory entries of directory using a Win32 API and recursively
350  * calls win32_build_dentry_tree() on them. */
351 static int
352 win32_recurse_directory(struct wim_dentry *root,
353                         wchar_t *dir_path,
354                         size_t dir_path_num_chars,
355                         struct add_image_params *params,
356                         struct win32_capture_state *state,
357                         unsigned vol_flags)
358 {
359         WIN32_FIND_DATAW dat;
360         HANDLE hFind;
361         DWORD err;
362         int ret;
363
364         DEBUG("Recurse to directory \"%ls\"", dir_path);
365
366         /* Begin reading the directory by calling FindFirstFileW.  Unlike UNIX
367          * opendir(), FindFirstFileW has file globbing built into it.  But this
368          * isn't what we actually want, so just add a dummy glob to get all
369          * entries. */
370         dir_path[dir_path_num_chars] = L'/';
371         dir_path[dir_path_num_chars + 1] = L'*';
372         dir_path[dir_path_num_chars + 2] = L'\0';
373         hFind = FindFirstFileW(dir_path, &dat);
374         dir_path[dir_path_num_chars] = L'\0';
375
376         if (hFind == INVALID_HANDLE_VALUE) {
377                 err = GetLastError();
378                 if (err == ERROR_FILE_NOT_FOUND) {
379                         return 0;
380                 } else {
381                         ERROR("Failed to read directory \"%ls\"", dir_path);
382                         win32_error(err);
383                         return WIMLIB_ERR_READ;
384                 }
385         }
386         ret = 0;
387         do {
388                 /* Skip . and .. entries */
389                 if (dat.cFileName[0] == L'.' &&
390                     (dat.cFileName[1] == L'\0' ||
391                      (dat.cFileName[1] == L'.' &&
392                       dat.cFileName[2] == L'\0')))
393                         continue;
394                 size_t filename_len = wcslen(dat.cFileName);
395
396                 dir_path[dir_path_num_chars] = L'/';
397                 wmemcpy(dir_path + dir_path_num_chars + 1,
398                         dat.cFileName,
399                         filename_len + 1);
400
401                 struct wim_dentry *child;
402                 size_t path_len = dir_path_num_chars + 1 + filename_len;
403                 ret = win32_build_dentry_tree_recursive(&child,
404                                                         dir_path,
405                                                         path_len,
406                                                         params,
407                                                         state,
408                                                         vol_flags);
409                 dir_path[dir_path_num_chars] = L'\0';
410                 if (ret)
411                         goto out_find_close;
412                 if (child)
413                         dentry_add_child(root, child);
414         } while (FindNextFileW(hFind, &dat));
415         err = GetLastError();
416         if (err != ERROR_NO_MORE_FILES) {
417                 ERROR("Failed to read directory \"%ls\"", dir_path);
418                 win32_error(err);
419                 if (ret == 0)
420                         ret = WIMLIB_ERR_READ;
421         }
422 out_find_close:
423         FindClose(hFind);
424         return ret;
425 }
426
427 /* Reparse point fixup status code */
428 enum rp_status {
429         /* Reparse point corresponded to an absolute symbolic link or junction
430          * point that pointed outside the directory tree being captured, and
431          * therefore was excluded. */
432         RP_EXCLUDED       = 0x0,
433
434         /* Reparse point was not fixed as it was either a relative symbolic
435          * link, a mount point, or something else we could not understand. */
436         RP_NOT_FIXED      = 0x1,
437
438         /* Reparse point corresponded to an absolute symbolic link or junction
439          * point that pointed inside the directory tree being captured, where
440          * the target was specified by a "full" \??\ prefixed path, and
441          * therefore was fixed to be relative to the root of the directory tree
442          * being captured. */
443         RP_FIXED_FULLPATH = 0x2,
444
445         /* Same as RP_FIXED_FULLPATH, except the absolute link target did not
446          * have the \??\ prefix.  It may have begun with a drive letter though.
447          * */
448         RP_FIXED_ABSPATH  = 0x4,
449
450         /* Either RP_FIXED_FULLPATH or RP_FIXED_ABSPATH. */
451         RP_FIXED          = RP_FIXED_FULLPATH | RP_FIXED_ABSPATH,
452 };
453
454 /* Given the "substitute name" target of a Windows reparse point, try doing a
455  * fixup where we change it to be absolute relative to the root of the directory
456  * tree being captured.
457  *
458  * Note that this is only executed when WIMLIB_ADD_FLAG_RPFIX has been
459  * set.
460  *
461  * @capture_root_ino and @capture_root_dev indicate the inode number and device
462  * of the root of the directory tree being captured.  They are meant to identify
463  * this directory (as an alternative to its actual path, which could potentially
464  * be reached via multiple destinations due to other symbolic links).  This may
465  * not work properly on FAT, which doesn't seem to supply proper inode numbers
466  * or file IDs.  However, FAT doesn't support reparse points so this function
467  * wouldn't even be called anyway.
468  */
469 static enum rp_status
470 win32_capture_maybe_rpfix_target(wchar_t *target, u16 *target_nbytes_p,
471                                  u64 capture_root_ino, u64 capture_root_dev,
472                                  u32 rptag)
473 {
474         u16 target_nchars = *target_nbytes_p / 2;
475         size_t stripped_chars;
476         wchar_t *orig_target;
477         int ret;
478
479         ret = parse_substitute_name(target, *target_nbytes_p, rptag);
480         if (ret < 0)
481                 return RP_NOT_FIXED;
482         stripped_chars = ret;
483         if (stripped_chars)
484                 stripped_chars -= 2;
485         target[target_nchars] = L'\0';
486         orig_target = target;
487         target = capture_fixup_absolute_symlink(target + stripped_chars,
488                                                 capture_root_ino, capture_root_dev);
489         if (!target)
490                 return RP_EXCLUDED;
491         target_nchars = wcslen(target);
492         wmemmove(orig_target + stripped_chars, target, target_nchars + 1);
493         *target_nbytes_p = (target_nchars + stripped_chars) * sizeof(wchar_t);
494         DEBUG("Fixed reparse point (new target: \"%ls\")", orig_target);
495         if (stripped_chars)
496                 return RP_FIXED_FULLPATH;
497         else
498                 return RP_FIXED_ABSPATH;
499 }
500
501 /* Returns: `enum rp_status' value on success; negative WIMLIB_ERR_* value on
502  * failure. */
503 static int
504 win32_capture_try_rpfix(u8 *rpbuf, u16 *rpbuflen_p,
505                         u64 capture_root_ino, u64 capture_root_dev,
506                         const wchar_t *path)
507 {
508         struct reparse_data rpdata;
509         DWORD rpbuflen;
510         int ret;
511         enum rp_status rp_status;
512
513         rpbuflen = *rpbuflen_p;
514         ret = parse_reparse_data(rpbuf, rpbuflen, &rpdata);
515         if (ret)
516                 return -ret;
517
518         rp_status = win32_capture_maybe_rpfix_target(rpdata.substitute_name,
519                                                      &rpdata.substitute_name_nbytes,
520                                                      capture_root_ino,
521                                                      capture_root_dev,
522                                                      le32_to_cpu(*(u32*)rpbuf));
523         if (rp_status & RP_FIXED) {
524                 wimlib_assert(rpdata.substitute_name_nbytes % 2 == 0);
525                 utf16lechar substitute_name_copy[rpdata.substitute_name_nbytes / 2];
526                 wmemcpy(substitute_name_copy, rpdata.substitute_name,
527                         rpdata.substitute_name_nbytes / 2);
528                 rpdata.substitute_name = substitute_name_copy;
529                 rpdata.print_name = substitute_name_copy;
530                 rpdata.print_name_nbytes = rpdata.substitute_name_nbytes;
531                 if (rp_status == RP_FIXED_FULLPATH) {
532                         /* "full path", meaning \??\ prefixed.  We should not
533                          * include this prefix in the print name, as it is
534                          * apparently meant for the filesystem driver only. */
535                         rpdata.print_name += 4;
536                         rpdata.print_name_nbytes -= 8;
537                 }
538                 ret = make_reparse_buffer(&rpdata, rpbuf);
539                 if (ret == 0)
540                         ret = rp_status;
541                 else
542                         ret = -ret;
543         } else {
544                 if (rp_status == RP_EXCLUDED) {
545                         size_t print_name_nchars = rpdata.print_name_nbytes / 2;
546                         wchar_t print_name0[print_name_nchars + 1];
547                         print_name0[print_name_nchars] = L'\0';
548                         wmemcpy(print_name0, rpdata.print_name, print_name_nchars);
549                         WARNING("Ignoring %ls pointing out of capture directory:\n"
550                                 "          \"%ls\" -> \"%ls\"\n"
551                                 "          (Use --norpfix to capture all symbolic links "
552                                 "and junction points as-is)",
553                                 (rpdata.rptag == WIM_IO_REPARSE_TAG_SYMLINK) ?
554                                         L"absolute symbolic link" : L"junction point",
555                                 path, print_name0);
556                 }
557                 ret = rp_status;
558         }
559         return ret;
560 }
561
562 /*
563  * Loads the reparse point data from a reparse point into memory, optionally
564  * fixing the targets of absolute symbolic links and junction points to be
565  * relative to the root of capture.
566  *
567  * @hFile:  Open handle to the reparse point.
568  * @path:   Path to the reparse point.  Used for error messages only.
569  * @params: Additional parameters, including whether to do reparse point fixups
570  *          or not.
571  * @rpbuf:  Buffer of length at least REPARSE_POINT_MAX_SIZE bytes into which
572  *          the reparse point buffer will be loaded.
573  * @rpbuflen_ret:  On success, the length of the reparse point buffer in bytes
574  *                 is written to this location.
575  *
576  * Returns:
577  *      On success, returns an `enum rp_status' value that indicates if and/or
578  *      how the reparse point fixup was done.
579  *
580  *      On failure, returns a negative value that is a negated WIMLIB_ERR_*
581  *      code.
582  */
583 static int
584 win32_get_reparse_data(HANDLE hFile, const wchar_t *path,
585                        struct add_image_params *params,
586                        u8 *rpbuf, u16 *rpbuflen_ret)
587 {
588         DWORD bytesReturned;
589         u32 reparse_tag;
590         int ret;
591         u16 rpbuflen;
592
593         DEBUG("Loading reparse data from \"%ls\"", path);
594         if (!DeviceIoControl(hFile, FSCTL_GET_REPARSE_POINT,
595                              NULL, /* "Not used with this operation; set to NULL" */
596                              0, /* "Not used with this operation; set to 0" */
597                              rpbuf, /* "A pointer to a buffer that
598                                                    receives the reparse point data */
599                              REPARSE_POINT_MAX_SIZE, /* "The size of the output
600                                                         buffer, in bytes */
601                              &bytesReturned,
602                              NULL))
603         {
604                 DWORD err = GetLastError();
605                 ERROR("Failed to get reparse data of \"%ls\"", path);
606                 win32_error(err);
607                 return -WIMLIB_ERR_READ;
608         }
609         if (bytesReturned < 8 || bytesReturned > REPARSE_POINT_MAX_SIZE) {
610                 ERROR("Reparse data on \"%ls\" is invalid", path);
611                 return -WIMLIB_ERR_INVALID_REPARSE_DATA;
612         }
613
614         rpbuflen = bytesReturned;
615         reparse_tag = le32_to_cpu(*(u32*)rpbuf);
616         if (params->add_flags & WIMLIB_ADD_FLAG_RPFIX &&
617             (reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
618              reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT))
619         {
620                 /* Try doing reparse point fixup */
621                 ret = win32_capture_try_rpfix(rpbuf,
622                                               &rpbuflen,
623                                               params->capture_root_ino,
624                                               params->capture_root_dev,
625                                               path);
626         } else {
627                 ret = RP_NOT_FIXED;
628         }
629         *rpbuflen_ret = rpbuflen;
630         return ret;
631 }
632
633 static DWORD WINAPI
634 win32_tally_encrypted_size_cb(unsigned char *_data, void *_ctx,
635                               unsigned long len)
636 {
637         *(u64*)_ctx += len;
638         return ERROR_SUCCESS;
639 }
640
641 static int
642 win32_get_encrypted_file_size(const wchar_t *path, u64 *size_ret)
643 {
644         DWORD err;
645         void *file_ctx;
646         int ret;
647
648         *size_ret = 0;
649         err = OpenEncryptedFileRawW(path, 0, &file_ctx);
650         if (err != ERROR_SUCCESS) {
651                 ERROR("Failed to open encrypted file \"%ls\" for raw read", path);
652                 win32_error(err);
653                 return WIMLIB_ERR_OPEN;
654         }
655         err = ReadEncryptedFileRaw(win32_tally_encrypted_size_cb,
656                                    size_ret, file_ctx);
657         if (err != ERROR_SUCCESS) {
658                 ERROR("Failed to read raw encrypted data from \"%ls\"", path);
659                 win32_error(err);
660                 ret = WIMLIB_ERR_READ;
661         } else {
662                 ret = 0;
663         }
664         CloseEncryptedFileRaw(file_ctx);
665         return ret;
666 }
667
668 /* Scans an unnamed or named stream of a Win32 file (not a reparse point
669  * stream); calculates its SHA1 message digest and either creates a `struct
670  * wim_lookup_table_entry' in memory for it, or uses an existing 'struct
671  * wim_lookup_table_entry' for an identical stream.
672  *
673  * @path:               Path to the file (UTF-16LE).
674  *
675  * @path_num_chars:     Number of 2-byte characters in @path.
676  *
677  * @inode:              WIM inode to save the stream into.
678  *
679  * @lookup_table:       Stream lookup table for the WIM.
680  *
681  * @dat:                A `WIN32_FIND_STREAM_DATA' structure that specifies the
682  *                      stream name.
683  *
684  * Returns 0 on success; nonzero on failure.
685  */
686 static int
687 win32_capture_stream(const wchar_t *path,
688                      size_t path_num_chars,
689                      struct wim_inode *inode,
690                      struct wim_lookup_table *lookup_table,
691                      WIN32_FIND_STREAM_DATA *dat)
692 {
693         struct wim_ads_entry *ads_entry;
694         struct wim_lookup_table_entry *lte;
695         int ret;
696         wchar_t *stream_name, *colon;
697         size_t stream_name_nchars;
698         bool is_named_stream;
699         wchar_t *spath;
700         size_t spath_nchars;
701         size_t spath_buf_nbytes;
702         const wchar_t *relpath_prefix;
703         const wchar_t *colonchar;
704
705         DEBUG("Capture \"%ls\" stream \"%ls\"", path, dat->cStreamName);
706
707         /* The stream name should be returned as :NAME:TYPE */
708         stream_name = dat->cStreamName;
709         if (*stream_name != L':')
710                 goto out_invalid_stream_name;
711         stream_name += 1;
712         colon = wcschr(stream_name, L':');
713         if (colon == NULL)
714                 goto out_invalid_stream_name;
715
716         if (wcscmp(colon + 1, L"$DATA")) {
717                 /* Not a DATA stream */
718                 ret = 0;
719                 goto out;
720         }
721
722         *colon = '\0';
723
724         stream_name_nchars = colon - stream_name;
725         is_named_stream = (stream_name_nchars != 0);
726
727         if (is_named_stream) {
728                 /* Allocate an ADS entry for the named stream. */
729                 ads_entry = inode_add_ads_utf16le(inode, stream_name,
730                                                   stream_name_nchars * sizeof(wchar_t));
731                 if (!ads_entry) {
732                         ret = WIMLIB_ERR_NOMEM;
733                         goto out;
734                 }
735         }
736
737         /* If zero length stream, no lookup table entry needed. */
738         if ((u64)dat->StreamSize.QuadPart == 0) {
739                 ret = 0;
740                 goto out;
741         }
742
743         /* Create a UTF-16LE string @spath that gives the filename, then a
744          * colon, then the stream name.  Or, if it's an unnamed stream, just the
745          * filename.  It is MALLOC()'ed so that it can be saved in the
746          * wim_lookup_table_entry if needed.
747          *
748          * As yet another special case, relative paths need to be changed to
749          * begin with an explicit "./" so that, for example, a file t:ads, where
750          * :ads is the part we added, is not interpreted as a file on the t:
751          * drive. */
752         spath_nchars = path_num_chars;
753         relpath_prefix = L"";
754         colonchar = L"";
755         if (is_named_stream) {
756                 spath_nchars += 1 + stream_name_nchars;
757                 colonchar = L":";
758                 if (path_num_chars == 1 &&
759                     path[0] != L'/' &&
760                     path[0] != L'\\')
761                 {
762                         spath_nchars += 2;
763                         relpath_prefix = L"./";
764                 }
765         }
766
767         spath_buf_nbytes = (spath_nchars + 1) * sizeof(wchar_t);
768         spath = MALLOC(spath_buf_nbytes);
769
770         swprintf(spath, L"%ls%ls%ls%ls",
771                  relpath_prefix, path, colonchar, stream_name);
772
773         /* Make a new wim_lookup_table_entry */
774         lte = new_lookup_table_entry();
775         if (!lte) {
776                 ret = WIMLIB_ERR_NOMEM;
777                 goto out_free_spath;
778         }
779         lte->file_on_disk = spath;
780         spath = NULL;
781         if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED && !is_named_stream) {
782                 u64 encrypted_size;
783                 lte->resource_location = RESOURCE_WIN32_ENCRYPTED;
784                 ret = win32_get_encrypted_file_size(path, &encrypted_size);
785                 if (ret)
786                         goto out_free_spath;
787                 lte->resource_entry.original_size = encrypted_size;
788         } else {
789                 lte->resource_location = RESOURCE_WIN32;
790                 lte->resource_entry.original_size = (u64)dat->StreamSize.QuadPart;
791         }
792
793         u32 stream_id;
794         if (is_named_stream) {
795                 stream_id = ads_entry->stream_id;
796                 ads_entry->lte = lte;
797         } else {
798                 stream_id = 0;
799                 inode->i_lte = lte;
800         }
801         lookup_table_insert_unhashed(lookup_table, lte, inode, stream_id);
802         ret = 0;
803 out_free_spath:
804         FREE(spath);
805 out:
806         return ret;
807 out_invalid_stream_name:
808         ERROR("Invalid stream name: \"%ls:%ls\"", path, dat->cStreamName);
809         ret = WIMLIB_ERR_READ;
810         goto out;
811 }
812
813 /* Scans a Win32 file for unnamed and named data streams (not reparse point
814  * streams).
815  *
816  * @path:               Path to the file (UTF-16LE).
817  *
818  * @path_num_chars:     Number of 2-byte characters in @path.
819  *
820  * @inode:              WIM inode to save the stream into.
821  *
822  * @lookup_table:       Stream lookup table for the WIM.
823  *
824  * @file_size:          Size of unnamed data stream.  (Used only if alternate
825  *                      data streams API appears to be unavailable.)
826  *
827  * @vol_flags:          Flags that specify features of the volume being
828  *                      captured.
829  *
830  * Returns 0 on success; nonzero on failure.
831  */
832 static int
833 win32_capture_streams(const wchar_t *path,
834                       size_t path_num_chars,
835                       struct wim_inode *inode,
836                       struct wim_lookup_table *lookup_table,
837                       u64 file_size,
838                       unsigned vol_flags)
839 {
840         WIN32_FIND_STREAM_DATA dat;
841         int ret;
842         HANDLE hFind;
843         DWORD err;
844
845         DEBUG("Capturing streams from \"%ls\"", path);
846
847         if (win32func_FindFirstStreamW == NULL ||
848             !(vol_flags & FILE_NAMED_STREAMS))
849                 goto unnamed_only;
850
851         hFind = win32func_FindFirstStreamW(path, FindStreamInfoStandard, &dat, 0);
852         if (hFind == INVALID_HANDLE_VALUE) {
853                 err = GetLastError();
854                 if (err == ERROR_CALL_NOT_IMPLEMENTED)
855                         goto unnamed_only;
856
857                 /* Seems legal for this to return ERROR_HANDLE_EOF on reparse
858                  * points and directories */
859                 if ((inode->i_attributes &
860                     (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
861                     && err == ERROR_HANDLE_EOF)
862                 {
863                         DEBUG("ERROR_HANDLE_EOF (ok)");
864                         return 0;
865                 } else {
866                         if (err == ERROR_ACCESS_DENIED) {
867                                 WARNING("Failed to look up data streams "
868                                         "of \"%ls\": Access denied!\n%ls",
869                                         path, capture_access_denied_msg);
870                                 return 0;
871                         } else {
872                                 ERROR("Failed to look up data streams "
873                                       "of \"%ls\"", path);
874                                 win32_error(err);
875                                 return WIMLIB_ERR_READ;
876                         }
877                 }
878         }
879         do {
880                 ret = win32_capture_stream(path,
881                                            path_num_chars,
882                                            inode, lookup_table,
883                                            &dat);
884                 if (ret)
885                         goto out_find_close;
886         } while (win32func_FindNextStreamW(hFind, &dat));
887         err = GetLastError();
888         if (err != ERROR_HANDLE_EOF) {
889                 ERROR("Win32 API: Error reading data streams from \"%ls\"", path);
890                 win32_error(err);
891                 ret = WIMLIB_ERR_READ;
892         }
893 out_find_close:
894         FindClose(hFind);
895         return ret;
896 unnamed_only:
897         /* FindFirstStreamW() API is not available, or the volume does not
898          * support named streams.  Only capture the unnamed data stream. */
899         DEBUG("Only capturing unnamed data stream");
900         if (inode->i_attributes &
901              (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
902         {
903                 ret = 0;
904         } else {
905                 /* Just create our own WIN32_FIND_STREAM_DATA for an unnamed
906                  * stream to reduce the code to a call to the
907                  * already-implemented win32_capture_stream() */
908                 wcscpy(dat.cStreamName, L"::$DATA");
909                 dat.StreamSize.QuadPart = file_size;
910                 ret = win32_capture_stream(path,
911                                            path_num_chars,
912                                            inode, lookup_table,
913                                            &dat);
914         }
915         return ret;
916 }
917
918 static int
919 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
920                                   wchar_t *path,
921                                   size_t path_num_chars,
922                                   struct add_image_params *params,
923                                   struct win32_capture_state *state,
924                                   unsigned vol_flags)
925 {
926         struct wim_dentry *root = NULL;
927         struct wim_inode *inode;
928         DWORD err;
929         u64 file_size;
930         int ret;
931         u8 *rpbuf;
932         u16 rpbuflen;
933         u16 not_rpfixed;
934
935         if (exclude_path(path, path_num_chars, params->config, true)) {
936                 if (params->add_flags & WIMLIB_ADD_FLAG_ROOT) {
937                         ERROR("Cannot exclude the root directory from capture");
938                         ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
939                         goto out;
940                 }
941                 if ((params->add_flags & WIMLIB_ADD_FLAG_EXCLUDE_VERBOSE)
942                     && params->progress_func)
943                 {
944                         union wimlib_progress_info info;
945                         info.scan.cur_path = path;
946                         info.scan.excluded = true;
947                         params->progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
948                 }
949                 ret = 0;
950                 goto out;
951         }
952
953         if ((params->add_flags & WIMLIB_ADD_FLAG_VERBOSE)
954             && params->progress_func)
955         {
956                 union wimlib_progress_info info;
957                 info.scan.cur_path = path;
958                 info.scan.excluded = false;
959                 params->progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
960         }
961
962         HANDLE hFile = win32_open_existing_file(path,
963                                                 FILE_READ_DATA | FILE_READ_ATTRIBUTES);
964         if (hFile == INVALID_HANDLE_VALUE) {
965                 err = GetLastError();
966                 ERROR("Win32 API: Failed to open \"%ls\"", path);
967                 win32_error(err);
968                 ret = WIMLIB_ERR_OPEN;
969                 goto out;
970         }
971
972         BY_HANDLE_FILE_INFORMATION file_info;
973         if (!GetFileInformationByHandle(hFile, &file_info)) {
974                 err = GetLastError();
975                 ERROR("Win32 API: Failed to get file information for \"%ls\"",
976                       path);
977                 win32_error(err);
978                 ret = WIMLIB_ERR_STAT;
979                 goto out_close_handle;
980         }
981
982         if (file_info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
983                 rpbuf = alloca(REPARSE_POINT_MAX_SIZE);
984                 ret = win32_get_reparse_data(hFile, path, params,
985                                              rpbuf, &rpbuflen);
986                 if (ret < 0) {
987                         /* WIMLIB_ERR_* (inverted) */
988                         ret = -ret;
989                         goto out_close_handle;
990                 } else if (ret & RP_FIXED) {
991                         not_rpfixed = 0;
992                 } else if (ret == RP_EXCLUDED) {
993                         ret = 0;
994                         goto out_close_handle;
995                 } else {
996                         not_rpfixed = 1;
997                 }
998         }
999
1000         /* Create a WIM dentry with an associated inode, which may be shared.
1001          *
1002          * However, we need to explicitly check for directories and files with
1003          * only 1 link and refuse to hard link them.  This is because Windows
1004          * has a bug where it can return duplicate File IDs for files and
1005          * directories on the FAT filesystem. */
1006         ret = inode_table_new_dentry(&params->inode_table,
1007                                      path_basename_with_len(path, path_num_chars),
1008                                      ((u64)file_info.nFileIndexHigh << 32) |
1009                                          (u64)file_info.nFileIndexLow,
1010                                      file_info.dwVolumeSerialNumber,
1011                                      (file_info.nNumberOfLinks <= 1 ||
1012                                         (file_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)),
1013                                      &root);
1014         if (ret)
1015                 goto out_close_handle;
1016
1017         ret = win32_get_short_name(root, path);
1018         if (ret)
1019                 goto out_close_handle;
1020
1021         inode = root->d_inode;
1022
1023         if (inode->i_nlink > 1) /* Shared inode; nothing more to do */
1024                 goto out_close_handle;
1025
1026         inode->i_attributes = file_info.dwFileAttributes;
1027         inode->i_creation_time = FILETIME_to_u64(&file_info.ftCreationTime);
1028         inode->i_last_write_time = FILETIME_to_u64(&file_info.ftLastWriteTime);
1029         inode->i_last_access_time = FILETIME_to_u64(&file_info.ftLastAccessTime);
1030         inode->i_resolved = 1;
1031
1032         params->add_flags &= ~WIMLIB_ADD_FLAG_ROOT;
1033
1034         if (!(params->add_flags & WIMLIB_ADD_FLAG_NO_ACLS)
1035             && (vol_flags & FILE_PERSISTENT_ACLS))
1036         {
1037                 ret = win32_get_security_descriptor(root, &params->sd_set,
1038                                                     path, state,
1039                                                     params->add_flags);
1040                 if (ret)
1041                         goto out_close_handle;
1042         }
1043
1044         file_size = ((u64)file_info.nFileSizeHigh << 32) |
1045                      (u64)file_info.nFileSizeLow;
1046
1047         CloseHandle(hFile);
1048
1049         /* Capture the unnamed data stream (only should be present for regular
1050          * files) and any alternate data streams. */
1051         ret = win32_capture_streams(path,
1052                                     path_num_chars,
1053                                     inode,
1054                                     params->lookup_table,
1055                                     file_size,
1056                                     vol_flags);
1057         if (ret)
1058                 goto out;
1059
1060         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1061                 /* Reparse point: set the reparse data (which we read already)
1062                  * */
1063                 inode->i_not_rpfixed = not_rpfixed;
1064                 inode->i_reparse_tag = le32_to_cpu(*(u32*)rpbuf);
1065                 ret = inode_set_unnamed_stream(inode, rpbuf + 8, rpbuflen - 8,
1066                                                params->lookup_table);
1067         } else if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1068                 /* Directory (not a reparse point) --- recurse to children */
1069                 ret = win32_recurse_directory(root,
1070                                               path,
1071                                               path_num_chars,
1072                                               params,
1073                                               state,
1074                                               vol_flags);
1075         }
1076         goto out;
1077 out_close_handle:
1078         CloseHandle(hFile);
1079 out:
1080         if (ret == 0)
1081                 *root_ret = root;
1082         else
1083                 free_dentry_tree(root, params->lookup_table);
1084         return ret;
1085 }
1086
1087 static void
1088 win32_do_capture_warnings(const struct win32_capture_state *state,
1089                           int add_flags)
1090 {
1091         if (state->num_get_sacl_priv_notheld == 0 &&
1092             state->num_get_sd_access_denied == 0)
1093                 return;
1094
1095         WARNING("");
1096         WARNING("Built dentry tree successfully, but with the following problem(s):");
1097         if (state->num_get_sacl_priv_notheld != 0) {
1098                 WARNING("Could not capture SACL (System Access Control List)\n"
1099                         "          on %lu files or directories.",
1100                         state->num_get_sacl_priv_notheld);
1101         }
1102         if (state->num_get_sd_access_denied != 0) {
1103                 WARNING("Could not capture security descriptor at all\n"
1104                         "          on %lu files or directories.",
1105                         state->num_get_sd_access_denied);
1106         }
1107         WARNING(
1108           "Try running the program as the Administrator to make sure all the\n"
1109 "          desired metadata has been captured exactly.  However, if you\n"
1110 "          do not care about capturing security descriptors correctly, then\n"
1111 "          nothing more needs to be done%ls\n",
1112         (add_flags & WIMLIB_ADD_FLAG_NO_ACLS) ? L"." :
1113          L", although you might consider\n"
1114 "          using the --no-acls option to explicitly capture no security\n"
1115 "          descriptors.\n");
1116 }
1117
1118 /* Win32 version of capturing a directory tree */
1119 int
1120 win32_build_dentry_tree(struct wim_dentry **root_ret,
1121                         const wchar_t *root_disk_path,
1122                         struct add_image_params *params)
1123 {
1124         size_t path_nchars;
1125         wchar_t *path;
1126         int ret;
1127         struct win32_capture_state state;
1128         unsigned vol_flags;
1129
1130         if (!win32func_FindFirstStreamW) {
1131                 WARNING("Running on Windows XP or earlier; "
1132                         "alternate data streams will not be captured.");
1133         }
1134
1135         path_nchars = wcslen(root_disk_path);
1136         if (path_nchars > 32767)
1137                 return WIMLIB_ERR_INVALID_PARAM;
1138
1139         if (GetFileAttributesW(root_disk_path) == INVALID_FILE_ATTRIBUTES &&
1140             GetLastError() == ERROR_FILE_NOT_FOUND)
1141         {
1142                 ERROR("Capture directory \"%ls\" does not exist!",
1143                       root_disk_path);
1144                 return WIMLIB_ERR_OPENDIR;
1145         }
1146
1147         ret = win32_get_file_and_vol_ids(root_disk_path,
1148                                          &params->capture_root_ino,
1149                                          &params->capture_root_dev);
1150         if (ret)
1151                 return ret;
1152
1153         win32_get_vol_flags(root_disk_path, &vol_flags);
1154
1155         /* There is no check for overflow later when this buffer is being used!
1156          * But the max path length on NTFS is 32767 characters, and paths need
1157          * to be written specially to even go past 260 characters, so we should
1158          * be okay with 32770 characters. */
1159         path = MALLOC(32770 * sizeof(wchar_t));
1160         if (!path)
1161                 return WIMLIB_ERR_NOMEM;
1162
1163         wmemcpy(path, root_disk_path, path_nchars + 1);
1164
1165         memset(&state, 0, sizeof(state));
1166         ret = win32_build_dentry_tree_recursive(root_ret, path,
1167                                                 path_nchars, params,
1168                                                 &state, vol_flags);
1169         FREE(path);
1170         if (ret == 0)
1171                 win32_do_capture_warnings(&state, params->add_flags);
1172         return ret;
1173 }
1174
1175 #endif /* __WIN32__ */