a591dd6012f0b7cbd077a0a3a395c60f7f9c02db
[wimlib] / src / win32.c
1 /*
2  * win32.c
3  *
4  * All the library code specific to native Windows builds is in here.
5  */
6
7 /*
8  * Copyright (C) 2013 Eric Biggers
9  *
10  * This file is part of wimlib, a library for working with WIM files.
11  *
12  * wimlib is free software; you can redistribute it and/or modify it under the
13  * terms of the GNU General Public License as published by the Free
14  * Software Foundation; either version 3 of the License, or (at your option)
15  * any later version.
16  *
17  * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
18  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
19  * A PARTICULAR PURPOSE. See the GNU General Public License for more
20  * details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with wimlib; if not, see http://www.gnu.org/licenses/.
24  */
25
26 #ifdef __WIN32__
27
28 #include "config.h"
29 #include <windows.h>
30 #include <ntdef.h>
31 #include <wchar.h>
32 #include <shlwapi.h> /* for PathMatchSpecW() */
33 #include <aclapi.h> /* for SetSecurityInfo() */
34 #ifdef ERROR /* windows.h defines this */
35 #  undef ERROR
36 #endif
37
38 #include "win32.h"
39 #include "dentry.h"
40 #include "lookup_table.h"
41 #include "security.h"
42 #include "endianness.h"
43 #include "buffer_io.h"
44 #include <pthread.h>
45
46 #include <errno.h>
47
48 #define MAX_GET_SD_ACCESS_DENIED_WARNINGS 1
49 #define MAX_GET_SACL_PRIV_NOTHELD_WARNINGS 1
50 #define MAX_CREATE_HARD_LINK_WARNINGS 5
51 struct win32_capture_state {
52         unsigned long num_get_sd_access_denied;
53         unsigned long num_get_sacl_priv_notheld;
54 };
55
56 #define MAX_SET_SD_ACCESS_DENIED_WARNINGS 1
57 #define MAX_SET_SACL_PRIV_NOTHELD_WARNINGS 1
58
59 #ifdef ENABLE_ERROR_MESSAGES
60 static void
61 win32_error(u32 err_code)
62 {
63         wchar_t *buffer;
64         DWORD nchars;
65         nchars = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
66                                     FORMAT_MESSAGE_ALLOCATE_BUFFER,
67                                 NULL, err_code, 0,
68                                 (wchar_t*)&buffer, 0, NULL);
69         if (nchars == 0) {
70                 ERROR("Error printing error message! "
71                       "Computer will self-destruct in 3 seconds.");
72         } else {
73                 ERROR("Win32 error: %ls", buffer);
74                 LocalFree(buffer);
75         }
76 }
77 #else /* ENABLE_ERROR_MESSAGES */
78 #  define win32_error(err_code)
79 #endif /* !ENABLE_ERROR_MESSAGES */
80
81 /* Pointers to functions that are not available on all targetted versions of
82  * Windows (XP and later).  NOTE: The WINAPI annotations seem to be important; I
83  * assume it specifies a certain calling convention. */
84
85 /* Vista and later */
86 static HANDLE (WINAPI *win32func_FindFirstStreamW)(LPCWSTR lpFileName,
87                                             STREAM_INFO_LEVELS InfoLevel,
88                                             LPVOID lpFindStreamData,
89                                             DWORD dwFlags) = NULL;
90
91 /* Vista and later */
92 static BOOL (WINAPI *win32func_FindNextStreamW)(HANDLE hFindStream,
93                                          LPVOID lpFindStreamData) = NULL;
94
95 static HMODULE hKernel32 = NULL;
96
97 /* Try to dynamically load some functions */
98 void
99 win32_global_init()
100 {
101         DWORD err;
102
103         if (hKernel32 == NULL) {
104                 DEBUG("Loading Kernel32.dll");
105                 hKernel32 = LoadLibraryW(L"Kernel32.dll");
106                 if (hKernel32 == NULL) {
107                         err = GetLastError();
108                         WARNING("Can't load Kernel32.dll");
109                         win32_error(err);
110                         return;
111                 }
112         }
113
114         DEBUG("Looking for FindFirstStreamW");
115         win32func_FindFirstStreamW = (void*)GetProcAddress(hKernel32, "FindFirstStreamW");
116         if (!win32func_FindFirstStreamW) {
117                 WARNING("Could not find function FindFirstStreamW() in Kernel32.dll!");
118                 WARNING("Capturing alternate data streams will not be supported.");
119                 return;
120         }
121
122         DEBUG("Looking for FindNextStreamW");
123         win32func_FindNextStreamW = (void*)GetProcAddress(hKernel32, "FindNextStreamW");
124         if (!win32func_FindNextStreamW) {
125                 WARNING("Could not find function FindNextStreamW() in Kernel32.dll!");
126                 WARNING("Capturing alternate data streams will not be supported.");
127                 win32func_FindFirstStreamW = NULL;
128         }
129 }
130
131 void
132 win32_global_cleanup()
133 {
134         if (hKernel32 != NULL) {
135                 DEBUG("Closing Kernel32.dll");
136                 FreeLibrary(hKernel32);
137                 hKernel32 = NULL;
138         }
139 }
140
141 static const wchar_t *capture_access_denied_msg =
142 L"         If you are not running this program as the administrator, you may\n"
143  "         need to do so, so that all data and metadata can be backed up.\n"
144  "         Otherwise, there may be no way to access the desired data or\n"
145  "         metadata without taking ownership of the file or directory.\n"
146  ;
147
148 static const wchar_t *apply_access_denied_msg =
149 L"If you are not running this program as the administrator, you may\n"
150  "          need to do so, so that all data and metadata can be extracted\n"
151  "          exactly as the origignal copy.  However, if you do not care that\n"
152  "          the security descriptors are extracted correctly, you could run\n"
153  "          `wimlib-imagex apply' with the --no-acls flag instead.\n"
154  ;
155
156 static HANDLE
157 win32_open_existing_file(const wchar_t *path, DWORD dwDesiredAccess)
158 {
159         return CreateFileW(path,
160                            dwDesiredAccess,
161                            FILE_SHARE_READ,
162                            NULL, /* lpSecurityAttributes */
163                            OPEN_EXISTING,
164                            FILE_FLAG_BACKUP_SEMANTICS |
165                                FILE_FLAG_OPEN_REPARSE_POINT,
166                            NULL /* hTemplateFile */);
167 }
168
169 HANDLE
170 win32_open_file_data_only(const wchar_t *path)
171 {
172         return win32_open_existing_file(path, FILE_READ_DATA);
173 }
174
175 int
176 read_win32_file_prefix(const struct wim_lookup_table_entry *lte,
177                        u64 size,
178                        consume_data_callback_t cb,
179                        void *ctx_or_buf,
180                        int _ignored_flags)
181 {
182         int ret = 0;
183         void *out_buf;
184         DWORD err;
185         u64 bytes_remaining;
186
187         HANDLE hFile = win32_open_file_data_only(lte->file_on_disk);
188         if (hFile == INVALID_HANDLE_VALUE) {
189                 err = GetLastError();
190                 ERROR("Failed to open \"%ls\"", lte->file_on_disk);
191                 win32_error(err);
192                 return WIMLIB_ERR_OPEN;
193         }
194
195         if (cb)
196                 out_buf = alloca(WIM_CHUNK_SIZE);
197         else
198                 out_buf = ctx_or_buf;
199
200         bytes_remaining = size;
201         while (bytes_remaining) {
202                 DWORD bytesToRead, bytesRead;
203
204                 bytesToRead = min(WIM_CHUNK_SIZE, bytes_remaining);
205                 if (!ReadFile(hFile, out_buf, bytesToRead, &bytesRead, NULL) ||
206                     bytesRead != bytesToRead)
207                 {
208                         err = GetLastError();
209                         ERROR("Failed to read data from \"%ls\"", lte->file_on_disk);
210                         win32_error(err);
211                         ret = WIMLIB_ERR_READ;
212                         break;
213                 }
214                 bytes_remaining -= bytesRead;
215                 if (cb) {
216                         ret = (*cb)(out_buf, bytesRead, ctx_or_buf);
217                         if (ret)
218                                 break;
219                 } else {
220                         out_buf += bytesRead;
221                 }
222         }
223         CloseHandle(hFile);
224         return ret;
225 }
226
227 struct win32_encrypted_read_ctx {
228         consume_data_callback_t read_prefix_cb;
229         void *read_prefix_ctx_or_buf;
230         int wimlib_err_code;
231         void *buf;
232         size_t buf_filled;
233         u64 bytes_remaining;
234 };
235
236 static DWORD WINAPI
237 win32_encrypted_export_cb(unsigned char *_data, void *_ctx, unsigned long len)
238 {
239         const void *data = _data;
240         struct win32_encrypted_read_ctx *ctx = _ctx;
241         int ret;
242
243         DEBUG("len = %lu", len);
244         if (ctx->read_prefix_cb) {
245                 /* The length of the buffer passed to the ReadEncryptedFileRaw()
246                  * export callback is undocumented, so we assume it may be of
247                  * arbitrary size. */
248                 size_t bytes_to_buffer = min(ctx->bytes_remaining - ctx->buf_filled,
249                                              len);
250                 while (bytes_to_buffer) {
251                         size_t bytes_to_copy_to_buf =
252                                 min(bytes_to_buffer, WIM_CHUNK_SIZE - ctx->buf_filled);
253
254                         memcpy(ctx->buf + ctx->buf_filled, data,
255                                bytes_to_copy_to_buf);
256                         ctx->buf_filled += bytes_to_copy_to_buf;
257                         data += bytes_to_copy_to_buf;
258                         bytes_to_buffer -= bytes_to_copy_to_buf;
259
260                         if (ctx->buf_filled == WIM_CHUNK_SIZE ||
261                             ctx->buf_filled == ctx->bytes_remaining)
262                         {
263                                 ret = (*ctx->read_prefix_cb)(ctx->buf,
264                                                              ctx->buf_filled,
265                                                              ctx->read_prefix_ctx_or_buf);
266                                 if (ret) {
267                                         ctx->wimlib_err_code = ret;
268                                         /* Shouldn't matter what error code is returned
269                                          * here, as long as it isn't ERROR_SUCCESS. */
270                                         return ERROR_READ_FAULT;
271                                 }
272                                 ctx->bytes_remaining -= ctx->buf_filled;
273                                 ctx->buf_filled = 0;
274                         }
275                 }
276         } else {
277                 size_t len_to_copy = min(len, ctx->bytes_remaining);
278                 memcpy(ctx->read_prefix_ctx_or_buf, data, len_to_copy);
279                 ctx->bytes_remaining -= len_to_copy;
280                 ctx->read_prefix_ctx_or_buf += len_to_copy;
281         }
282         return ERROR_SUCCESS;
283 }
284
285 int
286 read_win32_encrypted_file_prefix(const struct wim_lookup_table_entry *lte,
287                                  u64 size,
288                                  consume_data_callback_t cb,
289                                  void *ctx_or_buf,
290                                  int _ignored_flags)
291 {
292         struct win32_encrypted_read_ctx export_ctx;
293         DWORD err;
294         void *file_ctx;
295         int ret;
296
297         DEBUG("Reading %"PRIu64" bytes from encryted file \"%ls\"",
298               size, lte->file_on_disk);
299
300         export_ctx.read_prefix_cb = cb;
301         export_ctx.read_prefix_ctx_or_buf = ctx_or_buf;
302         export_ctx.wimlib_err_code = 0;
303         if (cb) {
304                 export_ctx.buf = MALLOC(WIM_CHUNK_SIZE);
305                 if (!export_ctx.buf)
306                         return WIMLIB_ERR_NOMEM;
307         } else {
308                 export_ctx.buf = NULL;
309         }
310         export_ctx.bytes_remaining = size;
311
312         err = OpenEncryptedFileRawW(lte->file_on_disk, 0, &file_ctx);
313         if (err != ERROR_SUCCESS) {
314                 ERROR("Failed to open encrypted file \"%ls\" for raw read",
315                       lte->file_on_disk);
316                 win32_error(err);
317                 ret = WIMLIB_ERR_OPEN;
318                 goto out_free_buf;
319         }
320         err = ReadEncryptedFileRaw(win32_encrypted_export_cb,
321                                    &export_ctx, file_ctx);
322         if (err != ERROR_SUCCESS) {
323                 ERROR("Failed to read encrypted file \"%ls\"",
324                       lte->file_on_disk);
325                 win32_error(err);
326                 ret = export_ctx.wimlib_err_code;
327                 if (ret == 0)
328                         ret = WIMLIB_ERR_READ;
329         } else if (export_ctx.bytes_remaining != 0) {
330                 ERROR("Only could read %"PRIu64" of %"PRIu64" bytes from "
331                       "encryted file \"%ls\"",
332                       size - export_ctx.bytes_remaining, size,
333                       lte->file_on_disk);
334                 ret = WIMLIB_ERR_READ;
335         } else {
336                 ret = 0;
337         }
338         CloseEncryptedFileRaw(file_ctx);
339 out_free_buf:
340         FREE(export_ctx.buf);
341         return ret;
342 }
343
344 /* Given a path, which may not yet exist, get a set of flags that describe the
345  * features of the volume the path is on. */
346 static int
347 win32_get_vol_flags(const wchar_t *path, unsigned *vol_flags_ret)
348 {
349         wchar_t *volume;
350         BOOL bret;
351         DWORD vol_flags;
352
353         if (path[0] != L'\0' && path[0] != L'\\' &&
354             path[0] != L'/' && path[1] == L':')
355         {
356                 /* Path starts with a drive letter; use it. */
357                 volume = alloca(4 * sizeof(wchar_t));
358                 volume[0] = path[0];
359                 volume[1] = path[1];
360                 volume[2] = L'\\';
361                 volume[3] = L'\0';
362         } else {
363                 /* Path does not start with a drive letter; use the volume of
364                  * the current working directory. */
365                 volume = NULL;
366         }
367         bret = GetVolumeInformationW(volume, /* lpRootPathName */
368                                      NULL,  /* lpVolumeNameBuffer */
369                                      0,     /* nVolumeNameSize */
370                                      NULL,  /* lpVolumeSerialNumber */
371                                      NULL,  /* lpMaximumComponentLength */
372                                      &vol_flags, /* lpFileSystemFlags */
373                                      NULL,  /* lpFileSystemNameBuffer */
374                                      0);    /* nFileSystemNameSize */
375         if (!bret) {
376                 DWORD err = GetLastError();
377                 WARNING("Failed to get volume information for path \"%ls\"", path);
378                 win32_error(err);
379                 vol_flags = 0xffffffff;
380         }
381
382         DEBUG("using vol_flags = %x", vol_flags);
383         *vol_flags_ret = vol_flags;
384         return 0;
385 }
386
387
388 static u64
389 FILETIME_to_u64(const FILETIME *ft)
390 {
391         return ((u64)ft->dwHighDateTime << 32) | (u64)ft->dwLowDateTime;
392 }
393
394 static int
395 win32_get_short_name(struct wim_dentry *dentry, const wchar_t *path)
396 {
397         WIN32_FIND_DATAW dat;
398         HANDLE hFind;
399         int ret = 0;
400
401         /* If we can't read the short filename for some reason, we just ignore
402          * the error and assume the file has no short name.  I don't think this
403          * should be an issue, since the short names are essentially obsolete
404          * anyway. */
405         hFind = FindFirstFileW(path, &dat);
406         if (hFind != INVALID_HANDLE_VALUE) {
407                 if (dat.cAlternateFileName[0] != L'\0') {
408                         DEBUG("\"%ls\": short name \"%ls\"", path, dat.cAlternateFileName);
409                         size_t short_name_nbytes = wcslen(dat.cAlternateFileName) *
410                                                    sizeof(wchar_t);
411                         size_t n = short_name_nbytes + sizeof(wchar_t);
412                         dentry->short_name = MALLOC(n);
413                         if (dentry->short_name) {
414                                 memcpy(dentry->short_name, dat.cAlternateFileName, n);
415                                 dentry->short_name_nbytes = short_name_nbytes;
416                         } else {
417                                 ret = WIMLIB_ERR_NOMEM;
418                         }
419                 }
420                 FindClose(hFind);
421         }
422         return ret;
423 }
424
425 static int
426 win32_get_security_descriptor(struct wim_dentry *dentry,
427                               struct sd_set *sd_set,
428                               const wchar_t *path,
429                               struct win32_capture_state *state,
430                               int add_image_flags)
431 {
432         SECURITY_INFORMATION requestedInformation;
433         DWORD lenNeeded = 0;
434         BOOL status;
435         DWORD err;
436         unsigned long n;
437
438         requestedInformation = DACL_SECURITY_INFORMATION |
439                                SACL_SECURITY_INFORMATION |
440                                OWNER_SECURITY_INFORMATION |
441                                GROUP_SECURITY_INFORMATION;
442 again:
443         /* Request length of security descriptor */
444         status = GetFileSecurityW(path, requestedInformation,
445                                   NULL, 0, &lenNeeded);
446         err = GetLastError();
447         if (!status && err == ERROR_INSUFFICIENT_BUFFER) {
448                 DWORD len = lenNeeded;
449                 char buf[len];
450                 if (GetFileSecurityW(path, requestedInformation,
451                                      (PSECURITY_DESCRIPTOR)buf, len, &lenNeeded))
452                 {
453                         int security_id = sd_set_add_sd(sd_set, buf, len);
454                         if (security_id < 0)
455                                 return WIMLIB_ERR_NOMEM;
456                         else {
457                                 dentry->d_inode->i_security_id = security_id;
458                                 return 0;
459                         }
460                 } else {
461                         err = GetLastError();
462                 }
463         }
464
465         if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_STRICT_ACLS)
466                 goto fail;
467
468         switch (err) {
469         case ERROR_PRIVILEGE_NOT_HELD:
470                 if (requestedInformation & SACL_SECURITY_INFORMATION) {
471                         n = state->num_get_sacl_priv_notheld++;
472                         requestedInformation &= ~SACL_SECURITY_INFORMATION;
473                         if (n < MAX_GET_SACL_PRIV_NOTHELD_WARNINGS) {
474                                 WARNING(
475 "We don't have enough privileges to read the full security\n"
476 "          descriptor of \"%ls\"!\n"
477 "          Re-trying with SACL omitted.\n", path);
478                         } else if (n == MAX_GET_SACL_PRIV_NOTHELD_WARNINGS) {
479                                 WARNING(
480 "Suppressing further privileges not held error messages when reading\n"
481 "          security descriptors.");
482                         }
483                         goto again;
484                 }
485                 /* Fall through */
486         case ERROR_ACCESS_DENIED:
487                 n = state->num_get_sd_access_denied++;
488                 if (n < MAX_GET_SD_ACCESS_DENIED_WARNINGS) {
489                         WARNING("Failed to read security descriptor of \"%ls\": "
490                                 "Access denied!\n%ls", path, capture_access_denied_msg);
491                 } else if (n == MAX_GET_SD_ACCESS_DENIED_WARNINGS) {
492                         WARNING("Suppressing further access denied errors messages i"
493                                 "when reading security descriptors");
494                 }
495                 return 0;
496         default:
497 fail:
498                 ERROR("Failed to read security descriptor of \"%ls\"", path);
499                 win32_error(err);
500                 return WIMLIB_ERR_READ;
501         }
502 }
503
504 static int
505 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
506                                   wchar_t *path,
507                                   size_t path_num_chars,
508                                   struct add_image_params *params,
509                                   struct win32_capture_state *state,
510                                   unsigned vol_flags);
511
512 /* Reads the directory entries of directory using a Win32 API and recursively
513  * calls win32_build_dentry_tree() on them. */
514 static int
515 win32_recurse_directory(struct wim_dentry *root,
516                         wchar_t *dir_path,
517                         size_t dir_path_num_chars,
518                         struct add_image_params *params,
519                         struct win32_capture_state *state,
520                         unsigned vol_flags)
521 {
522         WIN32_FIND_DATAW dat;
523         HANDLE hFind;
524         DWORD err;
525         int ret;
526
527         DEBUG("Recurse to directory \"%ls\"", dir_path);
528
529         /* Begin reading the directory by calling FindFirstFileW.  Unlike UNIX
530          * opendir(), FindFirstFileW has file globbing built into it.  But this
531          * isn't what we actually want, so just add a dummy glob to get all
532          * entries. */
533         dir_path[dir_path_num_chars] = L'/';
534         dir_path[dir_path_num_chars + 1] = L'*';
535         dir_path[dir_path_num_chars + 2] = L'\0';
536         hFind = FindFirstFileW(dir_path, &dat);
537         dir_path[dir_path_num_chars] = L'\0';
538
539         if (hFind == INVALID_HANDLE_VALUE) {
540                 err = GetLastError();
541                 if (err == ERROR_FILE_NOT_FOUND) {
542                         return 0;
543                 } else {
544                         ERROR("Failed to read directory \"%ls\"", dir_path);
545                         win32_error(err);
546                         return WIMLIB_ERR_READ;
547                 }
548         }
549         ret = 0;
550         do {
551                 /* Skip . and .. entries */
552                 if (dat.cFileName[0] == L'.' &&
553                     (dat.cFileName[1] == L'\0' ||
554                      (dat.cFileName[1] == L'.' &&
555                       dat.cFileName[2] == L'\0')))
556                         continue;
557                 size_t filename_len = wcslen(dat.cFileName);
558
559                 dir_path[dir_path_num_chars] = L'/';
560                 wmemcpy(dir_path + dir_path_num_chars + 1,
561                         dat.cFileName,
562                         filename_len + 1);
563
564                 struct wim_dentry *child;
565                 size_t path_len = dir_path_num_chars + 1 + filename_len;
566                 ret = win32_build_dentry_tree_recursive(&child,
567                                                         dir_path,
568                                                         path_len,
569                                                         params,
570                                                         state,
571                                                         vol_flags);
572                 dir_path[dir_path_num_chars] = L'\0';
573                 if (ret)
574                         goto out_find_close;
575                 if (child)
576                         dentry_add_child(root, child);
577         } while (FindNextFileW(hFind, &dat));
578         err = GetLastError();
579         if (err != ERROR_NO_MORE_FILES) {
580                 ERROR("Failed to read directory \"%ls\"", dir_path);
581                 win32_error(err);
582                 if (ret == 0)
583                         ret = WIMLIB_ERR_READ;
584         }
585 out_find_close:
586         FindClose(hFind);
587         return ret;
588 }
589
590 int
591 win32_get_file_and_vol_ids(const wchar_t *path, u64 *ino_ret, u64 *dev_ret)
592 {
593         HANDLE hFile;
594         DWORD err;
595         BY_HANDLE_FILE_INFORMATION file_info;
596         int ret;
597
598         hFile = win32_open_existing_file(path, FILE_READ_ATTRIBUTES);
599         if (hFile == INVALID_HANDLE_VALUE) {
600                 err = GetLastError();
601                 WARNING("Failed to open \"%ls\" to get file and volume IDs",
602                         path);
603                 win32_error(err);
604                 return WIMLIB_ERR_OPEN;
605         }
606
607         if (!GetFileInformationByHandle(hFile, &file_info)) {
608                 err = GetLastError();
609                 ERROR("Failed to get file information for \"%ls\"", path);
610                 win32_error(err);
611                 ret = WIMLIB_ERR_STAT;
612         } else {
613                 *ino_ret = ((u64)file_info.nFileIndexHigh << 32) |
614                             (u64)file_info.nFileIndexLow;
615                 *dev_ret = file_info.dwVolumeSerialNumber;
616                 ret = 0;
617         }
618         CloseHandle(hFile);
619         return ret;
620 }
621
622 /* Reparse point fixup status code */
623 enum rp_status {
624         /* Reparse point corresponded to an absolute symbolic link or junction
625          * point that pointed outside the directory tree being captured, and
626          * therefore was excluded. */
627         RP_EXCLUDED       = 0x0,
628
629         /* Reparse point was not fixed as it was either a relative symbolic
630          * link, a mount point, or something else we could not understand. */
631         RP_NOT_FIXED      = 0x1,
632
633         /* Reparse point corresponded to an absolute symbolic link or junction
634          * point that pointed inside the directory tree being captured, where
635          * the target was specified by a "full" \??\ prefixed path, and
636          * therefore was fixed to be relative to the root of the directory tree
637          * being captured. */
638         RP_FIXED_FULLPATH = 0x2,
639
640         /* Same as RP_FIXED_FULLPATH, except the absolute link target did not
641          * have the \??\ prefix.  It may have begun with a drive letter though.
642          * */
643         RP_FIXED_ABSPATH  = 0x4,
644
645         /* Either RP_FIXED_FULLPATH or RP_FIXED_ABSPATH. */
646         RP_FIXED          = RP_FIXED_FULLPATH | RP_FIXED_ABSPATH,
647 };
648
649 /* Given the "substitute name" target of a Windows reparse point, try doing a
650  * fixup where we change it to be absolute relative to the root of the directory
651  * tree being captured.
652  *
653  * Note that this is only executed when WIMLIB_ADD_IMAGE_FLAG_RPFIX has been
654  * set.
655  *
656  * @capture_root_ino and @capture_root_dev indicate the inode number and device
657  * of the root of the directory tree being captured.  They are meant to identify
658  * this directory (as an alternative to its actual path, which could potentially
659  * be reached via multiple destinations due to other symbolic links).  This may
660  * not work properly on FAT, which doesn't seem to supply proper inode numbers
661  * or file IDs.  However, FAT doesn't support reparse points so this function
662  * wouldn't even be called anyway.  */
663 static enum rp_status
664 win32_maybe_rpfix_target(wchar_t *target, size_t *target_nchars_p,
665                          u64 capture_root_ino, u64 capture_root_dev)
666 {
667         size_t target_nchars= *target_nchars_p;
668         size_t stripped_chars;
669         wchar_t *orig_target;
670
671         if (target_nchars == 0)
672                 /* Invalid reparse point (empty target) */
673                 return RP_NOT_FIXED;
674
675         if (target[0] == L'\\') {
676                 if (target_nchars >= 2 && target[1] == L'\\') {
677                         /* Probably a volume.  Can't do anything with it. */
678                         DEBUG("Not fixing target (probably a volume)");
679                         return RP_NOT_FIXED;
680                 } else if (target_nchars >= 7 &&
681                            target[1] == '?' &&
682                            target[2] == '?' &&
683                            target[3] == '\\' &&
684                            target[4] != '\0' &&
685                            target[5] == ':' &&
686                            target[6] == '\\')
687                 {
688                         DEBUG("Full style path");
689                         /* Full \??\x:\ style path (may be junction or symlink)
690                          * */
691                         stripped_chars = 6;
692                 } else {
693                         DEBUG("Absolute target without drive letter");
694                         /* Absolute target, without drive letter */
695                         stripped_chars = 0;
696                 }
697         } else if (target_nchars >= 3 &&
698                    target[0] != L'\0' &&
699                    target[1] == L':' &&
700                    target[2] == L'\\')
701         {
702                 DEBUG("Absolute target with drive letter");
703                 /* Absolute target, with drive letter */
704                 stripped_chars = 2;
705         } else {
706                 DEBUG("Relative symlink or other link");
707                 /* Relative symlink or other unexpected format */
708                 return RP_NOT_FIXED;
709         }
710         target[target_nchars] = L'\0';
711         orig_target = target;
712         target = fixup_symlink(target + stripped_chars, capture_root_ino, capture_root_dev);
713         if (!target)
714                 return RP_EXCLUDED;
715         target_nchars = wcslen(target);
716         wmemmove(orig_target + stripped_chars, target, target_nchars + 1);
717         *target_nchars_p = target_nchars + stripped_chars;
718         DEBUG("Fixed reparse point (new target: \"%ls\")", orig_target);
719         if (stripped_chars == 6)
720                 return RP_FIXED_FULLPATH;
721         else
722                 return RP_FIXED_ABSPATH;
723 }
724
725 static enum rp_status
726 win32_try_capture_rpfix(char *rpbuf, DWORD *rpbuflen_p,
727                         u64 capture_root_ino, u64 capture_root_dev)
728 {
729         const char *p_get;
730         char *p_put;
731         u16 substitute_name_offset;
732         u16 substitute_name_len;
733         wchar_t *target;
734         size_t target_nchars;
735         enum rp_status status;
736         u32 rptag;
737         DWORD rpbuflen = *rpbuflen_p;
738
739         if (rpbuflen < 16) /* Invalid reparse point (length too small) */
740                 return RP_NOT_FIXED;
741         p_get = get_u32(rpbuf, &rptag);
742         p_get += 4;
743         p_get = get_u16(p_get, &substitute_name_offset);
744         p_get = get_u16(p_get, &substitute_name_len);
745         p_get += 4;
746         if (rptag == WIM_IO_REPARSE_TAG_SYMLINK) {
747                 if (rpbuflen < 20) /* Invalid reparse point (length too small) */
748                         return RP_NOT_FIXED;
749                 p_get += 4;
750         }
751         if ((DWORD)substitute_name_offset +
752             substitute_name_len + (p_get - rpbuf) > rpbuflen)
753                 /* Invalid reparse point (length too small) */
754                 return RP_NOT_FIXED;
755
756         target = (wchar_t*)&p_get[substitute_name_offset];
757         target_nchars = substitute_name_len / 2;
758         /* Note: target is not necessarily null-terminated */
759
760         status = win32_maybe_rpfix_target(target, &target_nchars,
761                                           capture_root_ino, capture_root_dev);
762         if (status & RP_FIXED) {
763                 size_t target_nbytes = target_nchars * 2;
764                 size_t print_nbytes = target_nbytes;
765                 wchar_t target_copy[target_nchars];
766                 wchar_t *print_name = target_copy;
767
768                 if (status == RP_FIXED_FULLPATH) {
769                         /* "full path", meaning \??\ prefixed.  We should not
770                          * include this prefix in the print name, as it is
771                          * apparently meant for the filesystem driver only. */
772                         print_nbytes -= 8;
773                         print_name += 4;
774                 }
775                 wmemcpy(target_copy, target, target_nchars);
776                 p_put = rpbuf + 8;
777                 p_put = put_u16(p_put, 0); /* Substitute name offset */
778                 p_put = put_u16(p_put, target_nbytes); /* Substitute name length */
779                 p_put = put_u16(p_put, target_nbytes + 2); /* Print name offset */
780                 p_put = put_u16(p_put, print_nbytes); /* Print name length */
781                 if (rptag == WIM_IO_REPARSE_TAG_SYMLINK)
782                         p_put = put_u32(p_put, 1);
783                 p_put = put_bytes(p_put, target_nbytes, target_copy);
784                 p_put = put_u16(p_put, 0);
785                 p_put = put_bytes(p_put, print_nbytes, print_name);
786                 p_put = put_u16(p_put, 0);
787
788                 /* Wrote the end of the reparse data.  Recalculate the length,
789                  * set the length field correctly, and return it. */
790                 rpbuflen = p_put - rpbuf;
791                 put_u16(rpbuf + 4, rpbuflen - 8);
792                 *rpbuflen_p = rpbuflen;
793         }
794         return status;
795 }
796
797 static int
798 win32_get_reparse_data(HANDLE hFile, const wchar_t *path,
799                        struct add_image_params *params,
800                        void *reparse_data, size_t *reparse_data_len_ret)
801 {
802         DWORD bytesReturned;
803         u32 reparse_tag;
804         enum rp_status status;
805
806         DEBUG("Loading reparse data from \"%ls\"", path);
807         if (!DeviceIoControl(hFile, FSCTL_GET_REPARSE_POINT,
808                              NULL, /* "Not used with this operation; set to NULL" */
809                              0, /* "Not used with this operation; set to 0" */
810                              reparse_data, /* "A pointer to a buffer that
811                                                    receives the reparse point data */
812                              REPARSE_POINT_MAX_SIZE, /* "The size of the output
813                                                         buffer, in bytes */
814                              &bytesReturned,
815                              NULL))
816         {
817                 DWORD err = GetLastError();
818                 ERROR("Failed to get reparse data of \"%ls\"", path);
819                 win32_error(err);
820                 return -WIMLIB_ERR_READ;
821         }
822         if (bytesReturned < 8) {
823                 ERROR("Reparse data on \"%ls\" is invalid", path);
824                 return -WIMLIB_ERR_READ;
825         }
826
827         reparse_tag = le32_to_cpu(*(u32*)reparse_data);
828         if (params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_RPFIX &&
829             (reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
830              reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT))
831         {
832                 /* Try doing reparse point fixup */
833                 status = win32_try_capture_rpfix(reparse_data,
834                                                  &bytesReturned,
835                                                  params->capture_root_ino,
836                                                  params->capture_root_dev);
837         } else {
838                 status = RP_NOT_FIXED;
839         }
840         *reparse_data_len_ret = bytesReturned;
841         return status;
842 }
843
844 /* Scans an unnamed or named stream of a Win32 file (not a reparse point
845  * stream); calculates its SHA1 message digest and either creates a `struct
846  * wim_lookup_table_entry' in memory for it, or uses an existing 'struct
847  * wim_lookup_table_entry' for an identical stream.
848  *
849  * @path:               Path to the file (UTF-16LE).
850  *
851  * @path_num_chars:     Number of 2-byte characters in @path.
852  *
853  * @inode:              WIM inode to save the stream into.
854  *
855  * @lookup_table:       Stream lookup table for the WIM.
856  *
857  * @dat:                A `WIN32_FIND_STREAM_DATA' structure that specifies the
858  *                      stream name.
859  *
860  * Returns 0 on success; nonzero on failure.
861  */
862 static int
863 win32_capture_stream(const wchar_t *path,
864                      size_t path_num_chars,
865                      struct wim_inode *inode,
866                      struct wim_lookup_table *lookup_table,
867                      WIN32_FIND_STREAM_DATA *dat)
868 {
869         struct wim_ads_entry *ads_entry;
870         struct wim_lookup_table_entry *lte;
871         int ret;
872         wchar_t *stream_name, *colon;
873         size_t stream_name_nchars;
874         bool is_named_stream;
875         wchar_t *spath;
876         size_t spath_nchars;
877         size_t spath_buf_nbytes;
878         const wchar_t *relpath_prefix;
879         const wchar_t *colonchar;
880
881         DEBUG("Capture \"%ls\" stream \"%ls\"", path, dat->cStreamName);
882
883         /* The stream name should be returned as :NAME:TYPE */
884         stream_name = dat->cStreamName;
885         if (*stream_name != L':')
886                 goto out_invalid_stream_name;
887         stream_name += 1;
888         colon = wcschr(stream_name, L':');
889         if (colon == NULL)
890                 goto out_invalid_stream_name;
891
892         if (wcscmp(colon + 1, L"$DATA")) {
893                 /* Not a DATA stream */
894                 ret = 0;
895                 goto out;
896         }
897
898         *colon = '\0';
899
900         stream_name_nchars = colon - stream_name;
901         is_named_stream = (stream_name_nchars != 0);
902
903         if (is_named_stream) {
904                 /* Allocate an ADS entry for the named stream. */
905                 ads_entry = inode_add_ads_utf16le(inode, stream_name,
906                                                   stream_name_nchars * sizeof(wchar_t));
907                 if (!ads_entry) {
908                         ret = WIMLIB_ERR_NOMEM;
909                         goto out;
910                 }
911         }
912
913         /* If zero length stream, no lookup table entry needed. */
914         if ((u64)dat->StreamSize.QuadPart == 0) {
915                 ret = 0;
916                 goto out;
917         }
918
919         /* Create a UTF-16LE string @spath that gives the filename, then a
920          * colon, then the stream name.  Or, if it's an unnamed stream, just the
921          * filename.  It is MALLOC()'ed so that it can be saved in the
922          * wim_lookup_table_entry if needed.
923          *
924          * As yet another special case, relative paths need to be changed to
925          * begin with an explicit "./" so that, for example, a file t:ads, where
926          * :ads is the part we added, is not interpreted as a file on the t:
927          * drive. */
928         spath_nchars = path_num_chars;
929         relpath_prefix = L"";
930         colonchar = L"";
931         if (is_named_stream) {
932                 spath_nchars += 1 + stream_name_nchars;
933                 colonchar = L":";
934                 if (path_num_chars == 1 &&
935                     path[0] != L'/' &&
936                     path[0] != L'\\')
937                 {
938                         spath_nchars += 2;
939                         relpath_prefix = L"./";
940                 }
941         }
942
943         spath_buf_nbytes = (spath_nchars + 1) * sizeof(wchar_t);
944         spath = MALLOC(spath_buf_nbytes);
945
946         swprintf(spath, L"%ls%ls%ls%ls",
947                  relpath_prefix, path, colonchar, stream_name);
948
949         /* Make a new wim_lookup_table_entry */
950         lte = new_lookup_table_entry();
951         if (!lte) {
952                 ret = WIMLIB_ERR_NOMEM;
953                 goto out_free_spath;
954         }
955         lte->file_on_disk = spath;
956         spath = NULL;
957         if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED && !is_named_stream)
958                 lte->resource_location = RESOURCE_WIN32_ENCRYPTED;
959         else
960                 lte->resource_location = RESOURCE_WIN32;
961         lte->resource_entry.original_size = (u64)dat->StreamSize.QuadPart;
962
963         u32 stream_id;
964         if (is_named_stream) {
965                 stream_id = ads_entry->stream_id;
966                 ads_entry->lte = lte;
967         } else {
968                 stream_id = 0;
969                 inode->i_lte = lte;
970         }
971         lookup_table_insert_unhashed(lookup_table, lte, inode, stream_id);
972         ret = 0;
973 out_free_spath:
974         FREE(spath);
975 out:
976         return ret;
977 out_invalid_stream_name:
978         ERROR("Invalid stream name: \"%ls:%ls\"", path, dat->cStreamName);
979         ret = WIMLIB_ERR_READ;
980         goto out;
981 }
982
983 /* Scans a Win32 file for unnamed and named data streams (not reparse point
984  * streams).
985  *
986  * @path:               Path to the file (UTF-16LE).
987  *
988  * @path_num_chars:     Number of 2-byte characters in @path.
989  *
990  * @inode:              WIM inode to save the stream into.
991  *
992  * @lookup_table:       Stream lookup table for the WIM.
993  *
994  * @file_size:          Size of unnamed data stream.  (Used only if alternate
995  *                      data streams API appears to be unavailable.)
996  *
997  * @vol_flags:          Flags that specify features of the volume being
998  *                      captured.
999  *
1000  * Returns 0 on success; nonzero on failure.
1001  */
1002 static int
1003 win32_capture_streams(const wchar_t *path,
1004                       size_t path_num_chars,
1005                       struct wim_inode *inode,
1006                       struct wim_lookup_table *lookup_table,
1007                       u64 file_size,
1008                       unsigned vol_flags)
1009 {
1010         WIN32_FIND_STREAM_DATA dat;
1011         int ret;
1012         HANDLE hFind;
1013         DWORD err;
1014
1015         DEBUG("Capturing streams from \"%ls\"", path);
1016
1017         if (win32func_FindFirstStreamW == NULL ||
1018             !(vol_flags & FILE_NAMED_STREAMS))
1019                 goto unnamed_only;
1020
1021         hFind = win32func_FindFirstStreamW(path, FindStreamInfoStandard, &dat, 0);
1022         if (hFind == INVALID_HANDLE_VALUE) {
1023                 err = GetLastError();
1024                 if (err == ERROR_CALL_NOT_IMPLEMENTED)
1025                         goto unnamed_only;
1026
1027                 /* Seems legal for this to return ERROR_HANDLE_EOF on reparse
1028                  * points and directories */
1029                 if ((inode->i_attributes &
1030                     (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
1031                     && err == ERROR_HANDLE_EOF)
1032                 {
1033                         DEBUG("ERROR_HANDLE_EOF (ok)");
1034                         return 0;
1035                 } else {
1036                         if (err == ERROR_ACCESS_DENIED) {
1037                                 ERROR("Failed to look up data streams "
1038                                       "of \"%ls\": Access denied!\n%ls",
1039                                       path, capture_access_denied_msg);
1040                                 return WIMLIB_ERR_READ;
1041                         } else {
1042                                 ERROR("Failed to look up data streams "
1043                                       "of \"%ls\"", path);
1044                                 win32_error(err);
1045                                 return WIMLIB_ERR_READ;
1046                         }
1047                 }
1048         }
1049         do {
1050                 ret = win32_capture_stream(path,
1051                                            path_num_chars,
1052                                            inode, lookup_table,
1053                                            &dat);
1054                 if (ret)
1055                         goto out_find_close;
1056         } while (win32func_FindNextStreamW(hFind, &dat));
1057         err = GetLastError();
1058         if (err != ERROR_HANDLE_EOF) {
1059                 ERROR("Win32 API: Error reading data streams from \"%ls\"", path);
1060                 win32_error(err);
1061                 ret = WIMLIB_ERR_READ;
1062         }
1063 out_find_close:
1064         FindClose(hFind);
1065         return ret;
1066 unnamed_only:
1067         /* FindFirstStreamW() API is not available, or the volume does not
1068          * support named streams.  Only capture the unnamed data stream. */
1069         DEBUG("Only capturing unnamed data stream");
1070         if (inode->i_attributes &
1071              (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
1072         {
1073                 ret = 0;
1074         } else {
1075                 /* Just create our own WIN32_FIND_STREAM_DATA for an unnamed
1076                  * stream to reduce the code to a call to the
1077                  * already-implemented win32_capture_stream() */
1078                 wcscpy(dat.cStreamName, L"::$DATA");
1079                 dat.StreamSize.QuadPart = file_size;
1080                 ret = win32_capture_stream(path,
1081                                            path_num_chars,
1082                                            inode, lookup_table,
1083                                            &dat);
1084         }
1085         return ret;
1086 }
1087
1088 static int
1089 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
1090                                   wchar_t *path,
1091                                   size_t path_num_chars,
1092                                   struct add_image_params *params,
1093                                   struct win32_capture_state *state,
1094                                   unsigned vol_flags)
1095 {
1096         struct wim_dentry *root = NULL;
1097         struct wim_inode *inode;
1098         DWORD err;
1099         u64 file_size;
1100         int ret;
1101         void *reparse_data;
1102         size_t reparse_data_len;
1103         u16 not_rpfixed;
1104
1105         if (exclude_path(path, path_num_chars, params->config, true)) {
1106                 if (params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT) {
1107                         ERROR("Cannot exclude the root directory from capture");
1108                         ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
1109                         goto out;
1110                 }
1111                 if ((params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_EXCLUDE_VERBOSE)
1112                     && params->progress_func)
1113                 {
1114                         union wimlib_progress_info info;
1115                         info.scan.cur_path = path;
1116                         info.scan.excluded = true;
1117                         params->progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
1118                 }
1119                 ret = 0;
1120                 goto out;
1121         }
1122
1123         if ((params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
1124             && params->progress_func)
1125         {
1126                 union wimlib_progress_info info;
1127                 info.scan.cur_path = path;
1128                 info.scan.excluded = false;
1129                 params->progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
1130         }
1131
1132         HANDLE hFile = win32_open_existing_file(path,
1133                                                 FILE_READ_DATA | FILE_READ_ATTRIBUTES);
1134         if (hFile == INVALID_HANDLE_VALUE) {
1135                 err = GetLastError();
1136                 ERROR("Win32 API: Failed to open \"%ls\"", path);
1137                 win32_error(err);
1138                 ret = WIMLIB_ERR_OPEN;
1139                 goto out;
1140         }
1141
1142         BY_HANDLE_FILE_INFORMATION file_info;
1143         if (!GetFileInformationByHandle(hFile, &file_info)) {
1144                 err = GetLastError();
1145                 ERROR("Win32 API: Failed to get file information for \"%ls\"",
1146                       path);
1147                 win32_error(err);
1148                 ret = WIMLIB_ERR_STAT;
1149                 goto out_close_handle;
1150         }
1151
1152         if (file_info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1153                 reparse_data = alloca(REPARSE_POINT_MAX_SIZE);
1154                 ret = win32_get_reparse_data(hFile, path, params,
1155                                              reparse_data, &reparse_data_len);
1156                 if (ret < 0) {
1157                         /* WIMLIB_ERR_* (inverted) */
1158                         ret = -ret;
1159                         goto out_close_handle;
1160                 } else if (ret & RP_FIXED) {
1161                         not_rpfixed = 0;
1162                 } else if (ret == RP_EXCLUDED) {
1163                         ret = 0;
1164                         goto out_close_handle;
1165                 } else {
1166                         not_rpfixed = 1;
1167                 }
1168         }
1169
1170         /* Create a WIM dentry with an associated inode, which may be shared.
1171          *
1172          * However, we need to explicitly check for directories and files with
1173          * only 1 link and refuse to hard link them.  This is because Windows
1174          * has a bug where it can return duplicate File IDs for files and
1175          * directories on the FAT filesystem. */
1176         ret = inode_table_new_dentry(params->inode_table,
1177                                      path_basename_with_len(path, path_num_chars),
1178                                      ((u64)file_info.nFileIndexHigh << 32) |
1179                                          (u64)file_info.nFileIndexLow,
1180                                      file_info.dwVolumeSerialNumber,
1181                                      (file_info.nNumberOfLinks <= 1 ||
1182                                         (file_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)),
1183                                      &root);
1184         if (ret)
1185                 goto out_close_handle;
1186
1187         ret = win32_get_short_name(root, path);
1188         if (ret)
1189                 goto out_close_handle;
1190
1191         inode = root->d_inode;
1192
1193         if (inode->i_nlink > 1) /* Shared inode; nothing more to do */
1194                 goto out_close_handle;
1195
1196         inode->i_attributes = file_info.dwFileAttributes;
1197         inode->i_creation_time = FILETIME_to_u64(&file_info.ftCreationTime);
1198         inode->i_last_write_time = FILETIME_to_u64(&file_info.ftLastWriteTime);
1199         inode->i_last_access_time = FILETIME_to_u64(&file_info.ftLastAccessTime);
1200         inode->i_resolved = 1;
1201
1202         params->add_image_flags &= ~(WIMLIB_ADD_IMAGE_FLAG_ROOT | WIMLIB_ADD_IMAGE_FLAG_SOURCE);
1203
1204         if (!(params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NO_ACLS)
1205             && (vol_flags & FILE_PERSISTENT_ACLS))
1206         {
1207                 ret = win32_get_security_descriptor(root, params->sd_set,
1208                                                     path, state,
1209                                                     params->add_image_flags);
1210                 if (ret)
1211                         goto out_close_handle;
1212         }
1213
1214         file_size = ((u64)file_info.nFileSizeHigh << 32) |
1215                      (u64)file_info.nFileSizeLow;
1216
1217         /* Capture the unnamed data stream (only should be present for regular
1218          * files) and any alternate data streams. */
1219         ret = win32_capture_streams(path,
1220                                     path_num_chars,
1221                                     inode,
1222                                     params->lookup_table,
1223                                     file_size,
1224                                     vol_flags);
1225         if (ret)
1226                 goto out_close_handle;
1227
1228         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1229                 /* Reparse point: set the reparse data (which we read already)
1230                  * */
1231                 inode->i_not_rpfixed = not_rpfixed;
1232                 inode->i_reparse_tag = le32_to_cpu(*(u32*)reparse_data);
1233                 ret = inode_set_unnamed_stream(inode, reparse_data + 8,
1234                                                reparse_data_len - 8,
1235                                                params->lookup_table);
1236         } else if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1237                 /* Directory (not a reparse point) --- recurse to children */
1238                 ret = win32_recurse_directory(root,
1239                                               path,
1240                                               path_num_chars,
1241                                               params,
1242                                               state,
1243                                               vol_flags);
1244         }
1245 out_close_handle:
1246         CloseHandle(hFile);
1247 out:
1248         if (ret == 0)
1249                 *root_ret = root;
1250         else
1251                 free_dentry_tree(root, params->lookup_table);
1252         return ret;
1253 }
1254
1255 static void
1256 win32_do_capture_warnings(const struct win32_capture_state *state,
1257                           int add_image_flags)
1258 {
1259         if (state->num_get_sacl_priv_notheld == 0 &&
1260             state->num_get_sd_access_denied == 0)
1261                 return;
1262
1263         WARNING("");
1264         WARNING("Built dentry tree successfully, but with the following problem(s):");
1265         if (state->num_get_sacl_priv_notheld != 0) {
1266                 WARNING("Could not capture SACL (System Access Control List)\n"
1267                         "          on %lu files or directories.",
1268                         state->num_get_sacl_priv_notheld);
1269         }
1270         if (state->num_get_sd_access_denied != 0) {
1271                 WARNING("Could not capture security descriptor at all\n"
1272                         "          on %lu files or directories.",
1273                         state->num_get_sd_access_denied);
1274         }
1275         WARNING(
1276           "Try running the program as the Administrator to make sure all the\n"
1277 "          desired metadata has been captured exactly.  However, if you\n"
1278 "          do not care about capturing security descriptors correctly, then\n"
1279 "          nothing more needs to be done%ls\n",
1280         (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NO_ACLS) ? L"." :
1281          L", although you might consider\n"
1282 "          passing the --no-acls flag to `wimlib-imagex capture' or\n"
1283 "          `wimlib-imagex append' to explicitly capture no security\n"
1284 "          descriptors.\n");
1285 }
1286
1287 /* Win32 version of capturing a directory tree */
1288 int
1289 win32_build_dentry_tree(struct wim_dentry **root_ret,
1290                         const wchar_t *root_disk_path,
1291                         struct add_image_params *params)
1292 {
1293         size_t path_nchars;
1294         wchar_t *path;
1295         int ret;
1296         struct win32_capture_state state;
1297         unsigned vol_flags;
1298
1299
1300         path_nchars = wcslen(root_disk_path);
1301         if (path_nchars > 32767)
1302                 return WIMLIB_ERR_INVALID_PARAM;
1303
1304         ret = win32_get_file_and_vol_ids(root_disk_path,
1305                                          &params->capture_root_ino,
1306                                          &params->capture_root_dev);
1307         if (ret)
1308                 return ret;
1309
1310         win32_get_vol_flags(root_disk_path, &vol_flags);
1311
1312         /* There is no check for overflow later when this buffer is being used!
1313          * But the max path length on NTFS is 32767 characters, and paths need
1314          * to be written specially to even go past 260 characters, so we should
1315          * be okay with 32770 characters. */
1316         path = MALLOC(32770 * sizeof(wchar_t));
1317         if (!path)
1318                 return WIMLIB_ERR_NOMEM;
1319
1320         wmemcpy(path, root_disk_path, path_nchars + 1);
1321
1322         memset(&state, 0, sizeof(state));
1323         ret = win32_build_dentry_tree_recursive(root_ret, path,
1324                                                 path_nchars, params,
1325                                                 &state, vol_flags);
1326         FREE(path);
1327         if (ret == 0)
1328                 win32_do_capture_warnings(&state, params->add_image_flags);
1329         return ret;
1330 }
1331
1332 static int
1333 win32_set_reparse_data(HANDLE h,
1334                        u32 reparse_tag,
1335                        const struct wim_lookup_table_entry *lte,
1336                        const wchar_t *path)
1337 {
1338         int ret;
1339         u8 *buf;
1340         size_t len;
1341
1342         if (!lte) {
1343                 WARNING("\"%ls\" is marked as a reparse point but had no reparse data",
1344                         path);
1345                 return 0;
1346         }
1347         len = wim_resource_size(lte);
1348         if (len > 16 * 1024 - 8) {
1349                 WARNING("\"%ls\": reparse data too long!", path);
1350                 return 0;
1351         }
1352
1353         /* The WIM stream omits the ReparseTag and ReparseDataLength fields, so
1354          * leave 8 bytes of space for them at the beginning of the buffer, then
1355          * set them manually. */
1356         buf = alloca(len + 8);
1357         ret = read_full_resource_into_buf(lte, buf + 8, false);
1358         if (ret)
1359                 return ret;
1360         *(u32*)(buf + 0) = cpu_to_le32(reparse_tag);
1361         *(u16*)(buf + 4) = cpu_to_le16(len);
1362         *(u16*)(buf + 6) = 0;
1363
1364         /* Set the reparse data on the open file using the
1365          * FSCTL_SET_REPARSE_POINT ioctl.
1366          *
1367          * There are contradictions in Microsoft's documentation for this:
1368          *
1369          * "If hDevice was opened without specifying FILE_FLAG_OVERLAPPED,
1370          * lpOverlapped is ignored."
1371          *
1372          * --- So setting lpOverlapped to NULL is okay since it's ignored.
1373          *
1374          * "If lpOverlapped is NULL, lpBytesReturned cannot be NULL. Even when an
1375          * operation returns no output data and lpOutBuffer is NULL,
1376          * DeviceIoControl makes use of lpBytesReturned. After such an
1377          * operation, the value of lpBytesReturned is meaningless."
1378          *
1379          * --- So lpOverlapped not really ignored, as it affects another
1380          *  parameter.  This is the actual behavior: lpBytesReturned must be
1381          *  specified, even though lpBytesReturned is documented as:
1382          *
1383          *  "Not used with this operation; set to NULL."
1384          */
1385         DWORD bytesReturned;
1386         if (!DeviceIoControl(h, FSCTL_SET_REPARSE_POINT, buf, len + 8,
1387                              NULL, 0,
1388                              &bytesReturned /* lpBytesReturned */,
1389                              NULL /* lpOverlapped */))
1390         {
1391                 DWORD err = GetLastError();
1392                 ERROR("Failed to set reparse data on \"%ls\"", path);
1393                 win32_error(err);
1394                 if (err == ERROR_ACCESS_DENIED || err == ERROR_PRIVILEGE_NOT_HELD)
1395                         return WIMLIB_ERR_INSUFFICIENT_PRIVILEGES_TO_EXTRACT;
1396                 else if (reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
1397                          reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT)
1398                         return WIMLIB_ERR_LINK;
1399                 else
1400                         return WIMLIB_ERR_WRITE;
1401         }
1402         return 0;
1403 }
1404
1405 static int
1406 win32_set_compression_state(HANDLE hFile, USHORT format, const wchar_t *path)
1407 {
1408         DWORD bytesReturned = 0;
1409         if (!DeviceIoControl(hFile, FSCTL_SET_COMPRESSION,
1410                              &format, sizeof(USHORT),
1411                              NULL, 0,
1412                              &bytesReturned, NULL))
1413         {
1414                 /* Could be a warning only, but we only call this if the volume
1415                  * supports compression.  So I'm calling this an error. */
1416                 DWORD err = GetLastError();
1417                 ERROR("Failed to set compression flag on \"%ls\"", path);
1418                 win32_error(err);
1419                 if (err == ERROR_ACCESS_DENIED || err == ERROR_PRIVILEGE_NOT_HELD)
1420                         return WIMLIB_ERR_INSUFFICIENT_PRIVILEGES_TO_EXTRACT;
1421                 else
1422                         return WIMLIB_ERR_WRITE;
1423         }
1424         return 0;
1425 }
1426
1427 static int
1428 win32_set_sparse(HANDLE hFile, const wchar_t *path)
1429 {
1430         DWORD bytesReturned = 0;
1431         if (!DeviceIoControl(hFile, FSCTL_SET_SPARSE,
1432                              NULL, 0,
1433                              NULL, 0,
1434                              &bytesReturned, NULL))
1435         {
1436                 /* Could be a warning only, but we only call this if the volume
1437                  * supports sparse files.  So I'm calling this an error. */
1438                 DWORD err = GetLastError();
1439                 WARNING("Failed to set sparse flag on \"%ls\"", path);
1440                 win32_error(err);
1441                 if (err == ERROR_ACCESS_DENIED || err == ERROR_PRIVILEGE_NOT_HELD)
1442                         return WIMLIB_ERR_INSUFFICIENT_PRIVILEGES_TO_EXTRACT;
1443                 else
1444                         return WIMLIB_ERR_WRITE;
1445         }
1446         return 0;
1447 }
1448
1449 /*
1450  * Sets the security descriptor on an extracted file.
1451  */
1452 static int
1453 win32_set_security_data(const struct wim_inode *inode,
1454                         HANDLE hFile,
1455                         const wchar_t *path,
1456                         struct apply_args *args)
1457 {
1458         PSECURITY_DESCRIPTOR descriptor;
1459         unsigned long n;
1460         DWORD err;
1461         const struct wim_security_data *sd;
1462
1463         SECURITY_INFORMATION securityInformation = 0;
1464
1465         void *owner = NULL;
1466         void *group = NULL;
1467         ACL *dacl = NULL;
1468         ACL *sacl = NULL;
1469
1470         BOOL owner_defaulted;
1471         BOOL group_defaulted;
1472         BOOL dacl_present;
1473         BOOL dacl_defaulted;
1474         BOOL sacl_present;
1475         BOOL sacl_defaulted;
1476
1477         sd = wim_const_security_data(args->w);
1478         descriptor = sd->descriptors[inode->i_security_id];
1479
1480         GetSecurityDescriptorOwner(descriptor, &owner, &owner_defaulted);
1481         if (owner)
1482                 securityInformation |= OWNER_SECURITY_INFORMATION;
1483
1484         GetSecurityDescriptorGroup(descriptor, &group, &group_defaulted);
1485         if (group)
1486                 securityInformation |= GROUP_SECURITY_INFORMATION;
1487
1488         GetSecurityDescriptorDacl(descriptor, &dacl_present,
1489                                   &dacl, &dacl_defaulted);
1490         if (dacl)
1491                 securityInformation |= DACL_SECURITY_INFORMATION;
1492
1493         GetSecurityDescriptorSacl(descriptor, &sacl_present,
1494                                   &sacl, &sacl_defaulted);
1495         if (sacl)
1496                 securityInformation |= SACL_SECURITY_INFORMATION;
1497
1498 again:
1499         if (securityInformation == 0)
1500                 return 0;
1501         if (SetSecurityInfo(hFile, SE_FILE_OBJECT,
1502                             securityInformation, owner, group, dacl, sacl))
1503                 return 0;
1504         err = GetLastError();
1505         if (args->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS)
1506                 goto fail;
1507         switch (err) {
1508         case ERROR_PRIVILEGE_NOT_HELD:
1509                 if (securityInformation & SACL_SECURITY_INFORMATION) {
1510                         n = args->num_set_sacl_priv_notheld++;
1511                         securityInformation &= ~SACL_SECURITY_INFORMATION;
1512                         sacl = NULL;
1513                         if (n < MAX_SET_SACL_PRIV_NOTHELD_WARNINGS) {
1514                                 WARNING(
1515 "We don't have enough privileges to set the full security\n"
1516 "          descriptor on \"%ls\"!\n", path);
1517                                 if (args->num_set_sd_access_denied +
1518                                     args->num_set_sacl_priv_notheld == 1)
1519                                 {
1520                                         WARNING("%ls", apply_access_denied_msg);
1521                                 }
1522                                 WARNING("Re-trying with SACL omitted.\n", path);
1523                         } else if (n == MAX_GET_SACL_PRIV_NOTHELD_WARNINGS) {
1524                                 WARNING(
1525 "Suppressing further 'privileges not held' error messages when setting\n"
1526 "          security descriptors.");
1527                         }
1528                         goto again;
1529                 }
1530                 /* Fall through */
1531         case ERROR_INVALID_OWNER:
1532         case ERROR_ACCESS_DENIED:
1533                 n = args->num_set_sd_access_denied++;
1534                 if (n < MAX_SET_SD_ACCESS_DENIED_WARNINGS) {
1535                         WARNING("Failed to set security descriptor on \"%ls\": "
1536                                 "Access denied!\n", path);
1537                         if (args->num_set_sd_access_denied +
1538                             args->num_set_sacl_priv_notheld == 1)
1539                         {
1540                                 WARNING("%ls", apply_access_denied_msg);
1541                         }
1542                 } else if (n == MAX_SET_SD_ACCESS_DENIED_WARNINGS) {
1543                         WARNING(
1544 "Suppressing further access denied error messages when setting\n"
1545 "          security descriptors");
1546                 }
1547                 return 0;
1548         default:
1549 fail:
1550                 ERROR("Failed to set security descriptor on \"%ls\"", path);
1551                 win32_error(err);
1552                 if (err == ERROR_ACCESS_DENIED || err == ERROR_PRIVILEGE_NOT_HELD)
1553                         return WIMLIB_ERR_INSUFFICIENT_PRIVILEGES_TO_EXTRACT;
1554                 else
1555                         return WIMLIB_ERR_WRITE;
1556         }
1557 }
1558
1559
1560 static int
1561 win32_extract_chunk(const void *buf, size_t len, void *arg)
1562 {
1563         HANDLE hStream = arg;
1564
1565         DWORD nbytes_written;
1566         wimlib_assert(len <= 0xffffffff);
1567
1568         if (!WriteFile(hStream, buf, len, &nbytes_written, NULL) ||
1569             nbytes_written != len)
1570         {
1571                 DWORD err = GetLastError();
1572                 ERROR("WriteFile(): write error");
1573                 win32_error(err);
1574                 return WIMLIB_ERR_WRITE;
1575         }
1576         return 0;
1577 }
1578
1579 static int
1580 do_win32_extract_stream(HANDLE hStream, struct wim_lookup_table_entry *lte)
1581 {
1582         return extract_wim_resource(lte, wim_resource_size(lte),
1583                                     win32_extract_chunk, hStream);
1584 }
1585
1586 static int
1587 do_win32_extract_encrypted_stream(const wchar_t *path,
1588                                   const struct wim_lookup_table_entry *lte)
1589 {
1590         ERROR("Extracting encryted streams not implemented");
1591         return WIMLIB_ERR_INVALID_PARAM;
1592 }
1593
1594 static bool
1595 path_is_root_of_drive(const wchar_t *path)
1596 {
1597         if (!*path)
1598                 return false;
1599
1600         if (*path != L'/' && *path != L'\\') {
1601                 if (*(path + 1) == L':')
1602                         path += 2;
1603                 else
1604                         return false;
1605         }
1606         while (*path == L'/' || *path == L'\\')
1607                 path++;
1608         return (*path == L'\0');
1609 }
1610
1611 static DWORD
1612 win32_get_create_flags_and_attributes(DWORD i_attributes)
1613 {
1614         DWORD attributes;
1615
1616         /*
1617          * Some attributes cannot be set by passing them to CreateFile().  In
1618          * particular:
1619          *
1620          * FILE_ATTRIBUTE_DIRECTORY:
1621          *   CreateDirectory() must be called instead of CreateFile().
1622          *
1623          * FILE_ATTRIBUTE_SPARSE_FILE:
1624          *   Needs an ioctl.
1625          *   See: win32_set_sparse().
1626          *
1627          * FILE_ATTRIBUTE_COMPRESSED:
1628          *   Not clear from the documentation, but apparently this needs an
1629          *   ioctl as well.
1630          *   See: win32_set_compressed().
1631          *
1632          * FILE_ATTRIBUTE_REPARSE_POINT:
1633          *   Needs an ioctl, with the reparse data specified.
1634          *   See: win32_set_reparse_data().
1635          *
1636          * In addition, clear any file flags in the attributes that we don't
1637          * want, but also specify FILE_FLAG_OPEN_REPARSE_POINT and
1638          * FILE_FLAG_BACKUP_SEMANTICS as we are a backup application.
1639          */
1640         attributes = i_attributes & ~(FILE_ATTRIBUTE_SPARSE_FILE |
1641                                       FILE_ATTRIBUTE_COMPRESSED |
1642                                       FILE_ATTRIBUTE_REPARSE_POINT |
1643                                       FILE_ATTRIBUTE_DIRECTORY |
1644                                       FILE_FLAG_DELETE_ON_CLOSE |
1645                                       FILE_FLAG_NO_BUFFERING |
1646                                       FILE_FLAG_OPEN_NO_RECALL |
1647                                       FILE_FLAG_OVERLAPPED |
1648                                       FILE_FLAG_RANDOM_ACCESS |
1649                                       /*FILE_FLAG_SESSION_AWARE |*/
1650                                       FILE_FLAG_SEQUENTIAL_SCAN |
1651                                       FILE_FLAG_WRITE_THROUGH);
1652         return attributes |
1653                FILE_FLAG_OPEN_REPARSE_POINT |
1654                FILE_FLAG_BACKUP_SEMANTICS;
1655 }
1656
1657 /* Set compression or sparse attributes, and reparse data, if supported by the
1658  * volume. */
1659 static int
1660 win32_set_special_attributes(HANDLE hFile, const struct wim_inode *inode,
1661                              struct wim_lookup_table_entry *unnamed_stream_lte,
1662                              const wchar_t *path, unsigned vol_flags)
1663 {
1664         int ret;
1665
1666         /* Encrypted files cannot be [de]compressed. */
1667         if (!(inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED)) {
1668                 if (vol_flags & FILE_FILE_COMPRESSION) {
1669                         USHORT format;
1670                         if (inode->i_attributes & FILE_ATTRIBUTE_COMPRESSED) {
1671                                 format = COMPRESSION_FORMAT_DEFAULT;
1672                                 DEBUG("Setting compression flag on \"%ls\"", path);
1673                         } else {
1674                                 format = COMPRESSION_FORMAT_NONE;
1675                                 DEBUG("Clearing compression flag on \"%ls\"", path);
1676                         }
1677                         ret = win32_set_compression_state(hFile, format, path);
1678                         if (ret)
1679                                 return ret;
1680                 } else {
1681                         if (inode->i_attributes & FILE_ATTRIBUTE_COMPRESSED) {
1682                                 DEBUG("Cannot set compression attribute on \"%ls\": "
1683                                       "volume does not support transparent compression",
1684                                       path);
1685                         }
1686                 }
1687         }
1688
1689         if (inode->i_attributes & FILE_ATTRIBUTE_SPARSE_FILE) {
1690                 if (vol_flags & FILE_SUPPORTS_SPARSE_FILES) {
1691                         DEBUG("Setting sparse flag on \"%ls\"", path);
1692                         ret = win32_set_sparse(hFile, path);
1693                         if (ret)
1694                                 return ret;
1695                 } else {
1696                         DEBUG("Cannot set sparse attribute on \"%ls\": "
1697                               "volume does not support sparse files",
1698                               path);
1699                 }
1700         }
1701
1702         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1703                 if (vol_flags & FILE_SUPPORTS_REPARSE_POINTS) {
1704                         DEBUG("Setting reparse data on \"%ls\"", path);
1705                         ret = win32_set_reparse_data(hFile, inode->i_reparse_tag,
1706                                                      unnamed_stream_lte, path);
1707                         if (ret)
1708                                 return ret;
1709                 } else {
1710                         DEBUG("Cannot set reparse data on \"%ls\": volume "
1711                               "does not support reparse points", path);
1712                 }
1713         }
1714         return 0;
1715 }
1716
1717 static int
1718 win32_extract_stream(const struct wim_inode *inode,
1719                      const wchar_t *path,
1720                      const wchar_t *stream_name_utf16,
1721                      struct wim_lookup_table_entry *lte,
1722                      struct apply_args *args)
1723 {
1724         wchar_t *stream_path;
1725         HANDLE h;
1726         int ret;
1727         DWORD err;
1728         DWORD creationDisposition = CREATE_ALWAYS;
1729         DWORD requestedAccess;
1730
1731         if (stream_name_utf16) {
1732                 /* Named stream.  Create a buffer that contains the UTF-16LE
1733                  * string [./]path:stream_name_utf16.  This is needed to
1734                  * create and open the stream using CreateFileW().  I'm not
1735                  * aware of any other APIs to do this.  Note: the '$DATA' suffix
1736                  * seems to be unneeded.  Additional note: a "./" prefix needs
1737                  * to be added when the path is not absolute to avoid ambiguity
1738                  * with drive letters. */
1739                 size_t stream_path_nchars;
1740                 size_t path_nchars;
1741                 size_t stream_name_nchars;
1742                 const wchar_t *prefix;
1743
1744                 path_nchars = wcslen(path);
1745                 stream_name_nchars = wcslen(stream_name_utf16);
1746                 stream_path_nchars = path_nchars + 1 + stream_name_nchars;
1747                 if (path[0] != cpu_to_le16(L'\0') &&
1748                     path[0] != cpu_to_le16(L'/') &&
1749                     path[0] != cpu_to_le16(L'\\') &&
1750                     path[1] != cpu_to_le16(L':'))
1751                 {
1752                         prefix = L"./";
1753                         stream_path_nchars += 2;
1754                 } else {
1755                         prefix = L"";
1756                 }
1757                 stream_path = alloca((stream_path_nchars + 1) * sizeof(wchar_t));
1758                 swprintf(stream_path, L"%ls%ls:%ls",
1759                          prefix, path, stream_name_utf16);
1760         } else {
1761                 /* Unnamed stream; its path is just the path to the file itself.
1762                  * */
1763                 stream_path = (wchar_t*)path;
1764
1765                 /* Directories must be created with CreateDirectoryW().  Then
1766                  * the call to CreateFileW() will merely open the directory that
1767                  * was already created rather than creating a new file. */
1768                 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1769                         if (!CreateDirectoryW(stream_path, NULL)) {
1770                                 err = GetLastError();
1771                                 switch (err) {
1772                                 case ERROR_ALREADY_EXISTS:
1773                                         break;
1774                                 case ERROR_ACCESS_DENIED:
1775                                         if (path_is_root_of_drive(path))
1776                                                 break;
1777                                         /* Fall through */
1778                                 default:
1779                                         ERROR("Failed to create directory \"%ls\"",
1780                                               stream_path);
1781                                         win32_error(err);
1782                                         ret = WIMLIB_ERR_MKDIR;
1783                                         goto fail;
1784                                 }
1785                         }
1786                         DEBUG("Created directory \"%ls\"", stream_path);
1787                         creationDisposition = OPEN_EXISTING;
1788                 }
1789         }
1790
1791         DEBUG("Opening \"%ls\"", stream_path);
1792         requestedAccess = GENERIC_READ | GENERIC_WRITE |
1793                           ACCESS_SYSTEM_SECURITY;
1794 try_open_again:
1795         h = CreateFileW(stream_path,
1796                         requestedAccess,
1797                         0,
1798                         NULL,
1799                         creationDisposition,
1800                         win32_get_create_flags_and_attributes(inode->i_attributes),
1801                         NULL);
1802         if (h == INVALID_HANDLE_VALUE) {
1803                 err = GetLastError();
1804                 if (err == ERROR_PRIVILEGE_NOT_HELD &&
1805                     (requestedAccess & ACCESS_SYSTEM_SECURITY))
1806                 {
1807                         requestedAccess &= ~ACCESS_SYSTEM_SECURITY;
1808                         goto try_open_again;
1809                 }
1810                 ERROR("Failed to create \"%ls\"", stream_path);
1811                 win32_error(err);
1812                 ret = WIMLIB_ERR_OPEN;
1813                 goto fail;
1814         }
1815
1816         if (stream_name_utf16 == NULL) {
1817                 if (inode->i_security_id >= 0 &&
1818                     !(args->extract_flags & WIMLIB_EXTRACT_FLAG_NO_ACLS)
1819                     && (args->vol_flags & FILE_PERSISTENT_ACLS))
1820                 {
1821                         ret = win32_set_security_data(inode, h, path, args);
1822                         if (ret)
1823                                 goto fail_close_handle;
1824                 }
1825
1826                 ret = win32_set_special_attributes(h, inode, lte, path,
1827                                                    args->vol_flags);
1828                 if (ret)
1829                         goto fail_close_handle;
1830         }
1831
1832         if (!(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
1833                 if (lte) {
1834                         DEBUG("Extracting \"%ls\" (len = %"PRIu64")",
1835                               stream_path, wim_resource_size(lte));
1836                         if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED
1837                             && stream_name_utf16 == NULL
1838                             && (args->vol_flags & FILE_SUPPORTS_ENCRYPTION))
1839                         {
1840                                 ret = do_win32_extract_encrypted_stream(stream_path,
1841                                                                         lte);
1842                         } else {
1843                                 ret = do_win32_extract_stream(h, lte);
1844                         }
1845                         if (ret)
1846                                 goto fail_close_handle;
1847                 }
1848         }
1849
1850         DEBUG("Closing \"%ls\"", stream_path);
1851         if (!CloseHandle(h)) {
1852                 err = GetLastError();
1853                 ERROR("Failed to close \"%ls\"", stream_path);
1854                 win32_error(err);
1855                 ret = WIMLIB_ERR_WRITE;
1856                 goto fail;
1857         }
1858         ret = 0;
1859         goto out;
1860 fail_close_handle:
1861         CloseHandle(h);
1862 fail:
1863         ERROR("Error extracting %ls", stream_path);
1864 out:
1865         return ret;
1866 }
1867
1868 /*
1869  * Creates a file, directory, or reparse point and extracts all streams to it
1870  * (unnamed data stream and/or reparse point stream, plus any alternate data
1871  * streams).
1872  *
1873  * @inode:      WIM inode for this file or directory.
1874  * @path:       UTF-16LE external path to extract the inode to.
1875  * @args:       Additional extraction context.
1876  *
1877  * Returns 0 on success; nonzero on failure.
1878  */
1879 static int
1880 win32_extract_streams(const struct wim_inode *inode,
1881                       const wchar_t *path, struct apply_args *args)
1882 {
1883         struct wim_lookup_table_entry *unnamed_lte;
1884         int ret;
1885
1886         /* Extract the unnamed stream. */
1887
1888         unnamed_lte = inode_unnamed_lte_resolved(inode);
1889         ret = win32_extract_stream(inode, path, NULL, unnamed_lte, args);
1890         if (ret)
1891                 goto out;
1892         if (unnamed_lte && inode->i_extracted_file == NULL)
1893         {
1894                 args->progress.extract.completed_bytes +=
1895                         wim_resource_size(unnamed_lte);
1896         }
1897
1898         /* Extract any named streams, if supported by the volume. */
1899
1900         if (!(args->vol_flags & FILE_NAMED_STREAMS))
1901                 goto out;
1902         for (u16 i = 0; i < inode->i_num_ads; i++) {
1903                 const struct wim_ads_entry *ads_entry = &inode->i_ads_entries[i];
1904
1905                 /* Skip the unnamed stream if it's in the ADS entries (we
1906                  * already extracted it...) */
1907                 if (ads_entry->stream_name_nbytes == 0)
1908                         continue;
1909
1910                 /* Skip special UNIX data entries (see documentation for
1911                  * WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA) */
1912                 if (ads_entry->stream_name_nbytes == WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES
1913                     && !memcmp(ads_entry->stream_name,
1914                                WIMLIB_UNIX_DATA_TAG_UTF16LE,
1915                                WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES))
1916                         continue;
1917
1918                 /* Extract the named stream */
1919                 ret = win32_extract_stream(inode,
1920                                            path,
1921                                            ads_entry->stream_name,
1922                                            ads_entry->lte,
1923                                            args);
1924                 if (ret)
1925                         break;
1926
1927                 /* Tally the bytes extracted, unless this was supposed to be a
1928                  * hard link and we are extracting the data again only as a
1929                  * fallback. */
1930                 if (ads_entry->lte && inode->i_extracted_file == NULL)
1931                 {
1932                         args->progress.extract.completed_bytes +=
1933                                 wim_resource_size(ads_entry->lte);
1934                 }
1935         }
1936 out:
1937         return ret;
1938 }
1939
1940 static int
1941 win32_check_vol_flags(const wchar_t *output_path, struct apply_args *args)
1942 {
1943         if (args->have_vol_flags)
1944                 return 0;
1945
1946         win32_get_vol_flags(output_path, &args->vol_flags);
1947         args->have_vol_flags = true;
1948         /* Warn the user about data that may not be extracted. */
1949         if (!(args->vol_flags & FILE_SUPPORTS_SPARSE_FILES))
1950                 WARNING("Volume does not support sparse files!\n"
1951                         "          Sparse files will be extracted as non-sparse.");
1952         if (!(args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS))
1953                 WARNING("Volume does not support reparse points!\n"
1954                         "          Reparse point data will not be extracted.");
1955         if (!(args->vol_flags & FILE_NAMED_STREAMS)) {
1956                 WARNING("Volume does not support named data streams!\n"
1957                         "          Named data streams will not be extracted.");
1958         }
1959         if (!(args->vol_flags & FILE_SUPPORTS_ENCRYPTION)) {
1960                 WARNING("Volume does not support encryption!\n"
1961                         "          Encrypted files will be extracted as raw data.");
1962         }
1963         if (!(args->vol_flags & FILE_FILE_COMPRESSION)) {
1964                 WARNING("Volume does not support transparent compression!\n"
1965                         "          Compressed files will be extracted as non-compressed.");
1966         }
1967         if (!(args->vol_flags & FILE_PERSISTENT_ACLS)) {
1968                 if (args->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS) {
1969                         ERROR("Strict ACLs requested, but the volume does not "
1970                               "support ACLs!");
1971                         return WIMLIB_ERR_VOLUME_LACKS_FEATURES;
1972                 } else {
1973                         WARNING("Volume does not support persistent ACLS!\n"
1974                                 "          File permissions will not be extracted.");
1975                 }
1976         }
1977         return 0;
1978 }
1979
1980 static int
1981 win32_try_hard_link(const wchar_t *output_path, const struct wim_inode *inode,
1982                     struct apply_args *args)
1983 {
1984         DWORD err;
1985
1986         /* There is a volume flag for this (FILE_SUPPORTS_HARD_LINKS),
1987          * but it's only available on Windows 7 and later.  So no use
1988          * even checking it, really.  Instead, CreateHardLinkW() will
1989          * apparently return ERROR_INVALID_FUNCTION if the volume does
1990          * not support hard links. */
1991         DEBUG("Creating hard link \"%ls => %ls\"",
1992               output_path, inode->i_extracted_file);
1993         if (CreateHardLinkW(output_path, inode->i_extracted_file, NULL))
1994                 return 0;
1995
1996         err = GetLastError();
1997         if (err != ERROR_INVALID_FUNCTION) {
1998                 ERROR("Can't create hard link \"%ls => %ls\"",
1999                       output_path, inode->i_extracted_file);
2000                 win32_error(err);
2001                 return WIMLIB_ERR_LINK;
2002         } else {
2003                 args->num_hard_links_failed++;
2004                 if (args->num_hard_links_failed < MAX_CREATE_HARD_LINK_WARNINGS) {
2005                         WARNING("Can't create hard link \"%ls => %ls\":\n"
2006                                 "          Volume does not support hard links!\n"
2007                                 "          Falling back to extracting a copy of the file.",
2008                                 output_path, inode->i_extracted_file);
2009                 } else if (args->num_hard_links_failed == MAX_CREATE_HARD_LINK_WARNINGS) {
2010                         WARNING("Suppressing further hard linking warnings...");
2011                 }
2012                 return -1;
2013         }
2014 }
2015
2016 /* Extract a file, directory, reparse point, or hard link to an
2017  * already-extracted file using the Win32 API */
2018 int
2019 win32_do_apply_dentry(const wchar_t *output_path,
2020                       size_t output_path_num_chars,
2021                       struct wim_dentry *dentry,
2022                       struct apply_args *args)
2023 {
2024         int ret;
2025         struct wim_inode *inode = dentry->d_inode;
2026
2027         ret = win32_check_vol_flags(output_path, args);
2028         if (ret)
2029                 return ret;
2030         if (inode->i_nlink > 1 && inode->i_extracted_file != NULL) {
2031                 /* Linked file, with another name already extracted.  Create a
2032                  * hard link. */
2033                 ret = win32_try_hard_link(output_path, inode, args);
2034                 if (ret >= 0)
2035                         return ret;
2036                 /* Falling back to extracting copy of file */
2037         }
2038
2039         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT &&
2040             !(args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS))
2041         {
2042                 WARNING("Skipping extraction of reparse point \"%ls\":\n"
2043                         "          Not supported by destination filesystem",
2044                         output_path);
2045                 struct wim_lookup_table_entry *lte;
2046                 lte = inode_unnamed_lte_resolved(inode);
2047                 if (lte)
2048                         args->progress.extract.completed_bytes += wim_resource_size(lte);
2049                 return 0;
2050         }
2051
2052         /* Create the file, directory, or reparse point, and extract the
2053          * data streams. */
2054         ret = win32_extract_streams(inode, output_path, args);
2055         if (ret)
2056                 return ret;
2057
2058         if (inode->i_nlink > 1) {
2059                 /* Save extracted path for a later call to
2060                  * CreateHardLinkW() if this inode has multiple links.
2061                  * */
2062                 inode->i_extracted_file = WSTRDUP(output_path);
2063                 if (!inode->i_extracted_file)
2064                         ret = WIMLIB_ERR_NOMEM;
2065         }
2066         return ret;
2067 }
2068
2069 /* Set timestamps on an extracted file using the Win32 API */
2070 int
2071 win32_do_apply_dentry_timestamps(const wchar_t *path,
2072                                  size_t path_num_chars,
2073                                  const struct wim_dentry *dentry,
2074                                  const struct apply_args *args)
2075 {
2076         DWORD err;
2077         HANDLE h;
2078         const struct wim_inode *inode = dentry->d_inode;
2079
2080         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT &&
2081             !(args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS))
2082         {
2083                 /* Skip reparse points not extracted */
2084                 return 0;
2085         }
2086
2087         /* Windows doesn't let you change the timestamps of the root directory
2088          * (at least on FAT, which is dumb but expected since FAT doesn't store
2089          * any metadata about the root directory...) */
2090         if (path_is_root_of_drive(path))
2091                 return 0;
2092
2093         DEBUG("Opening \"%ls\" to set timestamps", path);
2094         h = win32_open_existing_file(path, FILE_WRITE_ATTRIBUTES);
2095         if (h == INVALID_HANDLE_VALUE) {
2096                 err = GetLastError();
2097                 goto fail;
2098         }
2099
2100         FILETIME creationTime = {.dwLowDateTime = inode->i_creation_time & 0xffffffff,
2101                                  .dwHighDateTime = inode->i_creation_time >> 32};
2102         FILETIME lastAccessTime = {.dwLowDateTime = inode->i_last_access_time & 0xffffffff,
2103                                   .dwHighDateTime = inode->i_last_access_time >> 32};
2104         FILETIME lastWriteTime = {.dwLowDateTime = inode->i_last_write_time & 0xffffffff,
2105                                   .dwHighDateTime = inode->i_last_write_time >> 32};
2106
2107         DEBUG("Calling SetFileTime() on \"%ls\"", path);
2108         if (!SetFileTime(h, &creationTime, &lastAccessTime, &lastWriteTime)) {
2109                 err = GetLastError();
2110                 CloseHandle(h);
2111                 goto fail;
2112         }
2113         DEBUG("Closing \"%ls\"", path);
2114         if (!CloseHandle(h)) {
2115                 err = GetLastError();
2116                 goto fail;
2117         }
2118         goto out;
2119 fail:
2120         /* Only warn if setting timestamps failed; still return 0. */
2121         WARNING("Can't set timestamps on \"%ls\"", path);
2122         win32_error(err);
2123 out:
2124         return 0;
2125 }
2126
2127 /* Replacement for POSIX fsync() */
2128 int
2129 fsync(int fd)
2130 {
2131         DWORD err;
2132         HANDLE h;
2133
2134         h = (HANDLE)_get_osfhandle(fd);
2135         if (h == INVALID_HANDLE_VALUE) {
2136                 err = GetLastError();
2137                 ERROR("Could not get Windows handle for file descriptor");
2138                 win32_error(err);
2139                 errno = EBADF;
2140                 return -1;
2141         }
2142         if (!FlushFileBuffers(h)) {
2143                 err = GetLastError();
2144                 ERROR("Could not flush file buffers to disk");
2145                 win32_error(err);
2146                 errno = EIO;
2147                 return -1;
2148         }
2149         return 0;
2150 }
2151
2152 /* Use the Win32 API to get the number of processors */
2153 unsigned
2154 win32_get_number_of_processors()
2155 {
2156         SYSTEM_INFO sysinfo;
2157         GetSystemInfo(&sysinfo);
2158         return sysinfo.dwNumberOfProcessors;
2159 }
2160
2161 /* Replacement for POSIX-2008 realpath().  Warning: partial functionality only
2162  * (resolved_path must be NULL).   Also I highly doubt that GetFullPathName
2163  * really does the right thing under all circumstances. */
2164 wchar_t *
2165 realpath(const wchar_t *path, wchar_t *resolved_path)
2166 {
2167         DWORD ret;
2168         wimlib_assert(resolved_path == NULL);
2169         DWORD err;
2170
2171         ret = GetFullPathNameW(path, 0, NULL, NULL);
2172         if (!ret) {
2173                 err = GetLastError();
2174                 goto fail_win32;
2175         }
2176
2177         resolved_path = TMALLOC(ret);
2178         if (!resolved_path)
2179                 goto out;
2180         ret = GetFullPathNameW(path, ret, resolved_path, NULL);
2181         if (!ret) {
2182                 err = GetLastError();
2183                 free(resolved_path);
2184                 resolved_path = NULL;
2185                 goto fail_win32;
2186         }
2187         goto out;
2188 fail_win32:
2189         win32_error(err);
2190         errno = -1;
2191 out:
2192         return resolved_path;
2193 }
2194
2195 /* rename() on Windows fails if the destination file exists.  And we need to
2196  * make it work on wide characters.  Fix it. */
2197 int
2198 win32_rename_replacement(const wchar_t *oldpath, const wchar_t *newpath)
2199 {
2200         if (MoveFileExW(oldpath, newpath, MOVEFILE_REPLACE_EXISTING)) {
2201                 return 0;
2202         } else {
2203                 /* As usual, the possible error values are not documented */
2204                 DWORD err = GetLastError();
2205                 ERROR("MoveFileEx(): Can't rename \"%ls\" to \"%ls\"",
2206                       oldpath, newpath);
2207                 win32_error(err);
2208                 errno = -1;
2209                 return -1;
2210         }
2211 }
2212
2213 /* Replacement for POSIX fnmatch() (partial functionality only) */
2214 int
2215 fnmatch(const wchar_t *pattern, const wchar_t *string, int flags)
2216 {
2217         if (PathMatchSpecW(string, pattern))
2218                 return 0;
2219         else
2220                 return FNM_NOMATCH;
2221 }
2222
2223 /* truncate() replacement */
2224 int
2225 win32_truncate_replacement(const wchar_t *path, off_t size)
2226 {
2227         DWORD err = NO_ERROR;
2228         LARGE_INTEGER liOffset;
2229
2230         HANDLE h = win32_open_existing_file(path, GENERIC_WRITE);
2231         if (h == INVALID_HANDLE_VALUE)
2232                 goto fail;
2233
2234         liOffset.QuadPart = size;
2235         if (!SetFilePointerEx(h, liOffset, NULL, FILE_BEGIN))
2236                 goto fail_close_handle;
2237
2238         if (!SetEndOfFile(h))
2239                 goto fail_close_handle;
2240         CloseHandle(h);
2241         return 0;
2242
2243 fail_close_handle:
2244         err = GetLastError();
2245         CloseHandle(h);
2246 fail:
2247         if (err == NO_ERROR)
2248                 err = GetLastError();
2249         ERROR("Can't truncate \"%ls\" to %"PRIu64" bytes", path, size);
2250         win32_error(err);
2251         errno = -1;
2252         return -1;
2253 }
2254
2255
2256 /* This really could be replaced with _wcserror_s, but this doesn't seem to
2257  * actually be available in MSVCRT.DLL on Windows XP (perhaps it's statically
2258  * linked in by Visual Studio...?). */
2259 extern int
2260 win32_strerror_r_replacement(int errnum, wchar_t *buf, size_t buflen)
2261 {
2262         static pthread_mutex_t strerror_lock = PTHREAD_MUTEX_INITIALIZER;
2263
2264         pthread_mutex_lock(&strerror_lock);
2265         mbstowcs(buf, strerror(errnum), buflen);
2266         buf[buflen - 1] = '\0';
2267         pthread_mutex_unlock(&strerror_lock);
2268         return 0;
2269 }
2270
2271 #endif /* __WIN32__ */