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