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