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