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