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