win32_get_short_name(): Add missing FindClose
[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
1077         if (exclude_path(path, path_num_chars, params->config, true)) {
1078                 if (params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT) {
1079                         ERROR("Cannot exclude the root directory from capture");
1080                         ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
1081                         goto out;
1082                 }
1083                 if ((params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_EXCLUDE_VERBOSE)
1084                     && params->progress_func)
1085                 {
1086                         union wimlib_progress_info info;
1087                         info.scan.cur_path = path;
1088                         info.scan.excluded = true;
1089                         params->progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
1090                 }
1091                 goto out;
1092         }
1093
1094         if ((params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
1095             && params->progress_func)
1096         {
1097                 union wimlib_progress_info info;
1098                 info.scan.cur_path = path;
1099                 info.scan.excluded = false;
1100                 params->progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
1101         }
1102
1103         HANDLE hFile = win32_open_existing_file(path,
1104                                                 FILE_READ_DATA | FILE_READ_ATTRIBUTES);
1105         if (hFile == INVALID_HANDLE_VALUE) {
1106                 err = GetLastError();
1107                 ERROR("Win32 API: Failed to open \"%ls\"", path);
1108                 win32_error(err);
1109                 ret = WIMLIB_ERR_OPEN;
1110                 goto out;
1111         }
1112
1113         BY_HANDLE_FILE_INFORMATION file_info;
1114         if (!GetFileInformationByHandle(hFile, &file_info)) {
1115                 err = GetLastError();
1116                 ERROR("Win32 API: Failed to get file information for \"%ls\"",
1117                       path);
1118                 win32_error(err);
1119                 ret = WIMLIB_ERR_STAT;
1120                 goto out_close_handle;
1121         }
1122
1123         /* Create a WIM dentry with an associated inode, which may be shared */
1124         ret = inode_table_new_dentry(params->inode_table,
1125                                      path_basename_with_len(path, path_num_chars),
1126                                      ((u64)file_info.nFileIndexHigh << 32) |
1127                                          (u64)file_info.nFileIndexLow,
1128                                      file_info.dwVolumeSerialNumber,
1129                                      &root);
1130         if (ret)
1131                 goto out_close_handle;
1132
1133         ret = win32_get_short_name(root, path);
1134         if (ret)
1135                 goto out_close_handle;
1136
1137         inode = root->d_inode;
1138
1139         if (inode->i_nlink > 1) /* Shared inode; nothing more to do */
1140                 goto out_close_handle;
1141
1142         inode->i_attributes = file_info.dwFileAttributes;
1143         inode->i_creation_time = FILETIME_to_u64(&file_info.ftCreationTime);
1144         inode->i_last_write_time = FILETIME_to_u64(&file_info.ftLastWriteTime);
1145         inode->i_last_access_time = FILETIME_to_u64(&file_info.ftLastAccessTime);
1146         inode->i_resolved = 1;
1147
1148         params->add_image_flags &= ~(WIMLIB_ADD_IMAGE_FLAG_ROOT | WIMLIB_ADD_IMAGE_FLAG_SOURCE);
1149
1150         if (!(params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NO_ACLS)
1151             && (vol_flags & FILE_PERSISTENT_ACLS))
1152         {
1153                 ret = win32_get_security_descriptor(root, params->sd_set,
1154                                                     path, state,
1155                                                     params->add_image_flags);
1156                 if (ret)
1157                         goto out_close_handle;
1158         }
1159
1160         file_size = ((u64)file_info.nFileSizeHigh << 32) |
1161                      (u64)file_info.nFileSizeLow;
1162
1163         if (inode_is_directory(inode)) {
1164                 /* Directory (not a reparse point) --- recurse to children */
1165
1166                 /* But first... directories may have alternate data streams that
1167                  * need to be captured. */
1168                 ret = win32_capture_streams(path,
1169                                             path_num_chars,
1170                                             inode,
1171                                             params->lookup_table,
1172                                             file_size,
1173                                             vol_flags);
1174                 if (ret)
1175                         goto out_close_handle;
1176                 ret = win32_recurse_directory(root,
1177                                               path,
1178                                               path_num_chars,
1179                                               params,
1180                                               state,
1181                                               vol_flags);
1182         } else if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1183                 /* Reparse point: save the reparse tag and data.  Alternate data
1184                  * streams are not captured, if it's even possible for a reparse
1185                  * point to have alternate data streams... */
1186                 ret = win32_capture_reparse_point(&root, hFile, inode, path, params);
1187         } else {
1188                 /* Not a directory, not a reparse point; capture the default
1189                  * file contents and any alternate data streams. */
1190                 ret = win32_capture_streams(path,
1191                                             path_num_chars,
1192                                             inode,
1193                                             params->lookup_table,
1194                                             file_size,
1195                                             vol_flags);
1196         }
1197 out_close_handle:
1198         CloseHandle(hFile);
1199 out:
1200         if (ret == 0)
1201                 *root_ret = root;
1202         else
1203                 free_dentry_tree(root, params->lookup_table);
1204         return ret;
1205 }
1206
1207 static void
1208 win32_do_capture_warnings(const struct win32_capture_state *state,
1209                           int add_image_flags)
1210 {
1211         if (state->num_get_sacl_priv_notheld == 0 &&
1212             state->num_get_sd_access_denied == 0)
1213                 return;
1214
1215         WARNING("");
1216         WARNING("Built dentry tree successfully, but with the following problem(s):");
1217         if (state->num_get_sacl_priv_notheld != 0) {
1218                 WARNING("Could not capture SACL (System Access Control List)\n"
1219                         "          on %lu files or directories.",
1220                         state->num_get_sacl_priv_notheld);
1221         }
1222         if (state->num_get_sd_access_denied != 0) {
1223                 WARNING("Could not capture security descriptor at all\n"
1224                         "          on %lu files or directories.",
1225                         state->num_get_sd_access_denied);
1226         }
1227         WARNING(
1228           "Try running the program as the Administrator to make sure all the\n"
1229 "          desired metadata has been captured exactly.  However, if you\n"
1230 "          do not care about capturing security descriptors correctly, then\n"
1231 "          nothing more needs to be done%ls\n",
1232         (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NO_ACLS) ? L"." :
1233          L", although you might consider\n"
1234 "          passing the --no-acls flag to `wimlib-imagex capture' or\n"
1235 "          `wimlib-imagex append' to explicitly capture no security\n"
1236 "          descriptors.\n");
1237 }
1238
1239 /* Win32 version of capturing a directory tree */
1240 int
1241 win32_build_dentry_tree(struct wim_dentry **root_ret,
1242                         const wchar_t *root_disk_path,
1243                         struct add_image_params *params)
1244 {
1245         size_t path_nchars;
1246         wchar_t *path;
1247         int ret;
1248         struct win32_capture_state state;
1249         unsigned vol_flags;
1250
1251
1252         path_nchars = wcslen(root_disk_path);
1253         if (path_nchars > 32767)
1254                 return WIMLIB_ERR_INVALID_PARAM;
1255
1256         ret = win32_get_file_and_vol_ids(root_disk_path,
1257                                          &params->capture_root_ino,
1258                                          &params->capture_root_dev);
1259         if (ret)
1260                 return ret;
1261
1262         win32_get_vol_flags(root_disk_path, &vol_flags);
1263
1264         /* There is no check for overflow later when this buffer is being used!
1265          * But the max path length on NTFS is 32767 characters, and paths need
1266          * to be written specially to even go past 260 characters, so we should
1267          * be okay with 32770 characters. */
1268         path = MALLOC(32770 * sizeof(wchar_t));
1269         if (!path)
1270                 return WIMLIB_ERR_NOMEM;
1271
1272         wmemcpy(path, root_disk_path, path_nchars + 1);
1273
1274         memset(&state, 0, sizeof(state));
1275         ret = win32_build_dentry_tree_recursive(root_ret, path,
1276                                                 path_nchars, params,
1277                                                 &state, vol_flags);
1278         FREE(path);
1279         if (ret == 0)
1280                 win32_do_capture_warnings(&state, params->add_image_flags);
1281         return ret;
1282 }
1283
1284 static int
1285 win32_set_reparse_data(HANDLE h,
1286                        u32 reparse_tag,
1287                        const struct wim_lookup_table_entry *lte,
1288                        const wchar_t *path)
1289 {
1290         int ret;
1291         u8 *buf;
1292         size_t len;
1293
1294         if (!lte) {
1295                 WARNING("\"%ls\" is marked as a reparse point but had no reparse data",
1296                         path);
1297                 return 0;
1298         }
1299         len = wim_resource_size(lte);
1300         if (len > 16 * 1024 - 8) {
1301                 WARNING("\"%ls\": reparse data too long!", path);
1302                 return 0;
1303         }
1304
1305         /* The WIM stream omits the ReparseTag and ReparseDataLength fields, so
1306          * leave 8 bytes of space for them at the beginning of the buffer, then
1307          * set them manually. */
1308         buf = alloca(len + 8);
1309         ret = read_full_resource_into_buf(lte, buf + 8, false);
1310         if (ret)
1311                 return ret;
1312         *(u32*)(buf + 0) = cpu_to_le32(reparse_tag);
1313         *(u16*)(buf + 4) = cpu_to_le16(len);
1314         *(u16*)(buf + 6) = 0;
1315
1316         /* Set the reparse data on the open file using the
1317          * FSCTL_SET_REPARSE_POINT ioctl.
1318          *
1319          * There are contradictions in Microsoft's documentation for this:
1320          *
1321          * "If hDevice was opened without specifying FILE_FLAG_OVERLAPPED,
1322          * lpOverlapped is ignored."
1323          *
1324          * --- So setting lpOverlapped to NULL is okay since it's ignored.
1325          *
1326          * "If lpOverlapped is NULL, lpBytesReturned cannot be NULL. Even when an
1327          * operation returns no output data and lpOutBuffer is NULL,
1328          * DeviceIoControl makes use of lpBytesReturned. After such an
1329          * operation, the value of lpBytesReturned is meaningless."
1330          *
1331          * --- So lpOverlapped not really ignored, as it affects another
1332          *  parameter.  This is the actual behavior: lpBytesReturned must be
1333          *  specified, even though lpBytesReturned is documented as:
1334          *
1335          *  "Not used with this operation; set to NULL."
1336          */
1337         DWORD bytesReturned;
1338         if (!DeviceIoControl(h, FSCTL_SET_REPARSE_POINT, buf, len + 8,
1339                              NULL, 0,
1340                              &bytesReturned /* lpBytesReturned */,
1341                              NULL /* lpOverlapped */))
1342         {
1343                 DWORD err = GetLastError();
1344                 ERROR("Failed to set reparse data on \"%ls\"", path);
1345                 win32_error(err);
1346                 return WIMLIB_ERR_WRITE;
1347         }
1348         return 0;
1349 }
1350
1351 static int
1352 win32_set_compressed(HANDLE hFile, const wchar_t *path)
1353 {
1354         USHORT format = COMPRESSION_FORMAT_DEFAULT;
1355         DWORD bytesReturned = 0;
1356         if (!DeviceIoControl(hFile, FSCTL_SET_COMPRESSION,
1357                              &format, sizeof(USHORT),
1358                              NULL, 0,
1359                              &bytesReturned, NULL))
1360         {
1361                 /* Could be a warning only, but we only call this if the volume
1362                  * supports compression.  So I'm calling this an error. */
1363                 DWORD err = GetLastError();
1364                 ERROR("Failed to set compression flag on \"%ls\"", path);
1365                 win32_error(err);
1366                 return WIMLIB_ERR_WRITE;
1367         }
1368         return 0;
1369 }
1370
1371 static int
1372 win32_set_sparse(HANDLE hFile, const wchar_t *path)
1373 {
1374         DWORD bytesReturned = 0;
1375         if (!DeviceIoControl(hFile, FSCTL_SET_SPARSE,
1376                              NULL, 0,
1377                              NULL, 0,
1378                              &bytesReturned, NULL))
1379         {
1380                 /* Could be a warning only, but we only call this if the volume
1381                  * supports sparse files.  So I'm calling this an error. */
1382                 DWORD err = GetLastError();
1383                 WARNING("Failed to set sparse flag on \"%ls\"", path);
1384                 win32_error(err);
1385                 return WIMLIB_ERR_WRITE;
1386         }
1387         return 0;
1388 }
1389
1390 /*
1391  * Sets the security descriptor on an extracted file.
1392  */
1393 static int
1394 win32_set_security_data(const struct wim_inode *inode,
1395                         const wchar_t *path,
1396                         struct apply_args *args)
1397 {
1398         PSECURITY_DESCRIPTOR descriptor;
1399         unsigned long n;
1400         DWORD err;
1401
1402         descriptor = wim_const_security_data(args->w)->descriptors[inode->i_security_id];
1403
1404         SECURITY_INFORMATION securityInformation = DACL_SECURITY_INFORMATION |
1405                                                    SACL_SECURITY_INFORMATION |
1406                                                    OWNER_SECURITY_INFORMATION |
1407                                                    GROUP_SECURITY_INFORMATION;
1408 again:
1409         if (SetFileSecurityW(path, securityInformation, descriptor))
1410                 return 0;
1411         err = GetLastError();
1412         if (args->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS)
1413                 goto fail;
1414         switch (err) {
1415         case ERROR_PRIVILEGE_NOT_HELD:
1416                 if (securityInformation & SACL_SECURITY_INFORMATION) {
1417                         n = args->num_set_sacl_priv_notheld++;
1418                         securityInformation &= ~SACL_SECURITY_INFORMATION;
1419                         if (n < MAX_SET_SACL_PRIV_NOTHELD_WARNINGS) {
1420                                 WARNING(
1421 "We don't have enough privileges to set the full security\n"
1422 "          descriptor on \"%ls\"!\n", path);
1423                                 if (args->num_set_sd_access_denied +
1424                                     args->num_set_sacl_priv_notheld == 1)
1425                                 {
1426                                         WARNING("%ls", apply_access_denied_msg);
1427                                 }
1428                                 WARNING("Re-trying with SACL omitted.\n", path);
1429                         } else if (n == MAX_GET_SACL_PRIV_NOTHELD_WARNINGS) {
1430                                 WARNING(
1431 "Suppressing further 'privileges not held' error messages when setting\n"
1432 "          security descriptors.");
1433                         }
1434                         goto again;
1435                 }
1436                 /* Fall through */
1437         case ERROR_INVALID_OWNER:
1438         case ERROR_ACCESS_DENIED:
1439                 n = args->num_set_sd_access_denied++;
1440                 if (n < MAX_SET_SD_ACCESS_DENIED_WARNINGS) {
1441                         WARNING("Failed to set security descriptor on \"%ls\": "
1442                                 "Access denied!\n", path);
1443                         if (args->num_set_sd_access_denied +
1444                             args->num_set_sacl_priv_notheld == 1)
1445                         {
1446                                 WARNING("%ls", apply_access_denied_msg);
1447                         }
1448                 } else if (n == MAX_SET_SD_ACCESS_DENIED_WARNINGS) {
1449                         WARNING(
1450 "Suppressing further access denied error messages when setting\n"
1451 "          security descriptors");
1452                 }
1453                 return 0;
1454         default:
1455 fail:
1456                 ERROR("Failed to set security descriptor on \"%ls\"", path);
1457                 win32_error(err);
1458                 return WIMLIB_ERR_WRITE;
1459         }
1460 }
1461
1462
1463 static int
1464 win32_extract_chunk(const void *buf, size_t len, void *arg)
1465 {
1466         HANDLE hStream = arg;
1467
1468         DWORD nbytes_written;
1469         wimlib_assert(len <= 0xffffffff);
1470
1471         if (!WriteFile(hStream, buf, len, &nbytes_written, NULL) ||
1472             nbytes_written != len)
1473         {
1474                 DWORD err = GetLastError();
1475                 ERROR("WriteFile(): write error");
1476                 win32_error(err);
1477                 return WIMLIB_ERR_WRITE;
1478         }
1479         return 0;
1480 }
1481
1482 static int
1483 do_win32_extract_stream(HANDLE hStream, struct wim_lookup_table_entry *lte)
1484 {
1485         return extract_wim_resource(lte, wim_resource_size(lte),
1486                                     win32_extract_chunk, hStream);
1487 }
1488
1489 static int
1490 do_win32_extract_encrypted_stream(const wchar_t *path,
1491                                   const struct wim_lookup_table_entry *lte)
1492 {
1493         ERROR("Extracting encryted streams not implemented");
1494         return WIMLIB_ERR_INVALID_PARAM;
1495 }
1496
1497 static bool
1498 path_is_root_of_drive(const wchar_t *path)
1499 {
1500         if (!*path)
1501                 return false;
1502
1503         if (*path != L'/' && *path != L'\\') {
1504                 if (*(path + 1) == L':')
1505                         path += 2;
1506                 else
1507                         return false;
1508         }
1509         while (*path == L'/' || *path == L'\\')
1510                 path++;
1511         return (*path == L'\0');
1512 }
1513
1514 static DWORD
1515 win32_get_create_flags_and_attributes(DWORD i_attributes)
1516 {
1517         DWORD attributes;
1518
1519         /*
1520          * Some attributes cannot be set by passing them to CreateFile().  In
1521          * particular:
1522          *
1523          * FILE_ATTRIBUTE_DIRECTORY:
1524          *   CreateDirectory() must be called instead of CreateFile().
1525          *
1526          * FILE_ATTRIBUTE_SPARSE_FILE:
1527          *   Needs an ioctl.
1528          *   See: win32_set_sparse().
1529          *
1530          * FILE_ATTRIBUTE_COMPRESSED:
1531          *   Not clear from the documentation, but apparently this needs an
1532          *   ioctl as well.
1533          *   See: win32_set_compressed().
1534          *
1535          * FILE_ATTRIBUTE_REPARSE_POINT:
1536          *   Needs an ioctl, with the reparse data specified.
1537          *   See: win32_set_reparse_data().
1538          *
1539          * In addition, clear any file flags in the attributes that we don't
1540          * want, but also specify FILE_FLAG_OPEN_REPARSE_POINT and
1541          * FILE_FLAG_BACKUP_SEMANTICS as we are a backup application.
1542          */
1543         attributes = i_attributes & ~(FILE_ATTRIBUTE_SPARSE_FILE |
1544                                       FILE_ATTRIBUTE_COMPRESSED |
1545                                       FILE_ATTRIBUTE_REPARSE_POINT |
1546                                       FILE_ATTRIBUTE_DIRECTORY |
1547                                       FILE_FLAG_DELETE_ON_CLOSE |
1548                                       FILE_FLAG_NO_BUFFERING |
1549                                       FILE_FLAG_OPEN_NO_RECALL |
1550                                       FILE_FLAG_OVERLAPPED |
1551                                       FILE_FLAG_RANDOM_ACCESS |
1552                                       /*FILE_FLAG_SESSION_AWARE |*/
1553                                       FILE_FLAG_SEQUENTIAL_SCAN |
1554                                       FILE_FLAG_WRITE_THROUGH);
1555         return attributes |
1556                FILE_FLAG_OPEN_REPARSE_POINT |
1557                FILE_FLAG_BACKUP_SEMANTICS;
1558 }
1559
1560 static bool
1561 inode_has_special_attributes(const struct wim_inode *inode)
1562 {
1563         return (inode->i_attributes & (FILE_ATTRIBUTE_COMPRESSED |
1564                                        FILE_ATTRIBUTE_REPARSE_POINT |
1565                                        FILE_ATTRIBUTE_SPARSE_FILE)) != 0;
1566 }
1567
1568 /* Set compression or sparse attributes, and reparse data, if supported by the
1569  * volume. */
1570 static int
1571 win32_set_special_attributes(HANDLE hFile, const struct wim_inode *inode,
1572                              struct wim_lookup_table_entry *unnamed_stream_lte,
1573                              const wchar_t *path, unsigned vol_flags)
1574 {
1575         int ret;
1576
1577         if (inode->i_attributes & FILE_ATTRIBUTE_COMPRESSED) {
1578                 if (vol_flags & FILE_FILE_COMPRESSION) {
1579                         DEBUG("Setting compression flag on \"%ls\"", path);
1580                         ret = win32_set_compressed(hFile, path);
1581                         if (ret)
1582                                 return ret;
1583                 } else {
1584                         DEBUG("Cannot set compression attribute on \"%ls\": "
1585                               "volume does not support transparent compression",
1586                               path);
1587                 }
1588         }
1589
1590         if (inode->i_attributes & FILE_ATTRIBUTE_SPARSE_FILE) {
1591                 if (vol_flags & FILE_SUPPORTS_SPARSE_FILES) {
1592                         DEBUG("Setting sparse flag on \"%ls\"", path);
1593                         ret = win32_set_sparse(hFile, path);
1594                         if (ret)
1595                                 return ret;
1596                 } else {
1597                         DEBUG("Cannot set sparse attribute on \"%ls\": "
1598                               "volume does not support sparse files",
1599                               path);
1600                 }
1601         }
1602
1603         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1604                 if (vol_flags & FILE_SUPPORTS_REPARSE_POINTS) {
1605                         DEBUG("Setting reparse data on \"%ls\"", path);
1606                         ret = win32_set_reparse_data(hFile, inode->i_reparse_tag,
1607                                                      unnamed_stream_lte, path);
1608                         if (ret)
1609                                 return ret;
1610                 } else {
1611                         DEBUG("Cannot set reparse data on \"%ls\": volume "
1612                               "does not support reparse points", path);
1613                 }
1614         }
1615
1616         return 0;
1617 }
1618
1619 static int
1620 win32_extract_stream(const struct wim_inode *inode,
1621                      const wchar_t *path,
1622                      const wchar_t *stream_name_utf16,
1623                      struct wim_lookup_table_entry *lte,
1624                      unsigned vol_flags)
1625 {
1626         wchar_t *stream_path;
1627         HANDLE h;
1628         int ret;
1629         DWORD err;
1630         DWORD creationDisposition = CREATE_ALWAYS;
1631
1632         if (stream_name_utf16) {
1633                 /* Named stream.  Create a buffer that contains the UTF-16LE
1634                  * string [.\]@path:@stream_name_utf16.  This is needed to
1635                  * create and open the stream using CreateFileW().  I'm not
1636                  * aware of any other APIs to do this.  Note: the '$DATA' suffix
1637                  * seems to be unneeded.  Additional note: a "./" prefix needs
1638                  * to be added when the path is not absolute to avoid ambiguity
1639                  * with drive letters. */
1640                 size_t stream_path_nchars;
1641                 size_t path_nchars;
1642                 size_t stream_name_nchars;
1643                 const wchar_t *prefix;
1644
1645                 path_nchars = wcslen(path);
1646                 stream_name_nchars = wcslen(stream_name_utf16);
1647                 stream_path_nchars = path_nchars + 1 + stream_name_nchars;
1648                 if (path[0] != cpu_to_le16(L'\0') &&
1649                     path[0] != cpu_to_le16(L'/') &&
1650                     path[0] != cpu_to_le16(L'\\') &&
1651                     path[1] != cpu_to_le16(L':'))
1652                 {
1653                         prefix = L"./";
1654                         stream_path_nchars += 2;
1655                 } else {
1656                         prefix = L"";
1657                 }
1658                 stream_path = alloca((stream_path_nchars + 1) * sizeof(wchar_t));
1659                 swprintf(stream_path, L"%ls%ls:%ls",
1660                          prefix, path, stream_name_utf16);
1661         } else {
1662                 /* Unnamed stream; its path is just the path to the file itself.
1663                  * */
1664                 stream_path = (wchar_t*)path;
1665
1666                 /* Directories must be created with CreateDirectoryW().  Then
1667                  * the call to CreateFileW() will merely open the directory that
1668                  * was already created rather than creating a new file. */
1669                 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1670                         if (!CreateDirectoryW(stream_path, NULL)) {
1671                                 err = GetLastError();
1672                                 switch (err) {
1673                                 case ERROR_ALREADY_EXISTS:
1674                                         break;
1675                                 case ERROR_ACCESS_DENIED:
1676                                         if (path_is_root_of_drive(path))
1677                                                 break;
1678                                         /* Fall through */
1679                                 default:
1680                                         ERROR("Failed to create directory \"%ls\"",
1681                                               stream_path);
1682                                         win32_error(err);
1683                                         ret = WIMLIB_ERR_MKDIR;
1684                                         goto fail;
1685                                 }
1686                         }
1687                         DEBUG("Created directory \"%ls\"", stream_path);
1688                         if (!inode_has_special_attributes(inode)) {
1689                                 ret = 0;
1690                                 goto out;
1691                         }
1692                         DEBUG("Directory \"%ls\" has special attributes!",
1693                               stream_path);
1694                         creationDisposition = OPEN_EXISTING;
1695                 }
1696         }
1697
1698         DEBUG("Opening \"%ls\"", stream_path);
1699         h = CreateFileW(stream_path,
1700                         GENERIC_READ | GENERIC_WRITE,
1701                         0,
1702                         NULL,
1703                         creationDisposition,
1704                         win32_get_create_flags_and_attributes(inode->i_attributes),
1705                         NULL);
1706         if (h == INVALID_HANDLE_VALUE) {
1707                 err = GetLastError();
1708                 ERROR("Failed to create \"%ls\"", stream_path);
1709                 win32_error(err);
1710                 ret = WIMLIB_ERR_OPEN;
1711                 goto fail;
1712         }
1713
1714         if (stream_name_utf16 == NULL && inode_has_special_attributes(inode)) {
1715                 ret = win32_set_special_attributes(h, inode, lte, path,
1716                                                    vol_flags);
1717                 if (ret)
1718                         goto fail_close_handle;
1719         }
1720
1721         if (!(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
1722                 if (lte) {
1723                         DEBUG("Extracting \"%ls\" (len = %"PRIu64")",
1724                               stream_path, wim_resource_size(lte));
1725                         if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED
1726                             && stream_name_utf16 == NULL
1727                             && (vol_flags & FILE_SUPPORTS_ENCRYPTION))
1728                         {
1729                                 ret = do_win32_extract_encrypted_stream(stream_path,
1730                                                                         lte);
1731                         } else {
1732                                 ret = do_win32_extract_stream(h, lte);
1733                         }
1734                         if (ret)
1735                                 goto fail_close_handle;
1736                 }
1737         }
1738
1739         DEBUG("Closing \"%ls\"", stream_path);
1740         if (!CloseHandle(h)) {
1741                 err = GetLastError();
1742                 ERROR("Failed to close \"%ls\"", stream_path);
1743                 win32_error(err);
1744                 ret = WIMLIB_ERR_WRITE;
1745                 goto fail;
1746         }
1747         ret = 0;
1748         goto out;
1749 fail_close_handle:
1750         CloseHandle(h);
1751 fail:
1752         ERROR("Error extracting %ls", stream_path);
1753 out:
1754         return ret;
1755 }
1756
1757 /*
1758  * Creates a file, directory, or reparse point and extracts all streams to it
1759  * (unnamed data stream and/or reparse point stream, plus any alternate data
1760  * streams).  This in Win32-specific code.
1761  *
1762  * @inode:      WIM inode for this file or directory.
1763  * @path:       UTF-16LE external path to extract the inode to.
1764  *
1765  * Returns 0 on success; nonzero on failure.
1766  */
1767 static int
1768 win32_extract_streams(const struct wim_inode *inode,
1769                       const wchar_t *path, u64 *completed_bytes_p,
1770                       unsigned vol_flags)
1771 {
1772         struct wim_lookup_table_entry *unnamed_lte;
1773         int ret;
1774
1775         unnamed_lte = inode_unnamed_lte_resolved(inode);
1776         ret = win32_extract_stream(inode, path, NULL, unnamed_lte,
1777                                    vol_flags);
1778         if (ret)
1779                 goto out;
1780         if (unnamed_lte && inode->i_extracted_file == NULL)
1781                 *completed_bytes_p += wim_resource_size(unnamed_lte);
1782
1783         if (!(vol_flags & FILE_NAMED_STREAMS))
1784                 goto out;
1785         for (u16 i = 0; i < inode->i_num_ads; i++) {
1786                 const struct wim_ads_entry *ads_entry = &inode->i_ads_entries[i];
1787                 if (ads_entry->stream_name_nbytes != 0) {
1788                         /* Skip special UNIX data entries (see documentation for
1789                          * WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA) */
1790                         if (ads_entry->stream_name_nbytes == WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES
1791                             && !memcmp(ads_entry->stream_name,
1792                                        WIMLIB_UNIX_DATA_TAG_UTF16LE,
1793                                        WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES))
1794                                 continue;
1795                         ret = win32_extract_stream(inode,
1796                                                    path,
1797                                                    ads_entry->stream_name,
1798                                                    ads_entry->lte,
1799                                                    vol_flags);
1800                         if (ret)
1801                                 break;
1802                         if (ads_entry->lte && inode->i_extracted_file == NULL)
1803                                 *completed_bytes_p += wim_resource_size(ads_entry->lte);
1804                 }
1805         }
1806 out:
1807         return ret;
1808 }
1809
1810 /* Extract a file, directory, reparse point, or hard link to an
1811  * already-extracted file using the Win32 API */
1812 int
1813 win32_do_apply_dentry(const wchar_t *output_path,
1814                       size_t output_path_num_chars,
1815                       struct wim_dentry *dentry,
1816                       struct apply_args *args)
1817 {
1818         int ret;
1819         struct wim_inode *inode = dentry->d_inode;
1820         DWORD err;
1821
1822         if (!args->have_vol_flags) {
1823                 win32_get_vol_flags(output_path, &args->vol_flags);
1824                 args->have_vol_flags = true;
1825                 /* Warn the user about data that may not be extracted. */
1826                 if (!(args->vol_flags & FILE_SUPPORTS_SPARSE_FILES))
1827                         WARNING("Volume does not support sparse files!\n"
1828                                 "          Sparse files will be extracted as non-sparse.");
1829                 if (!(args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS))
1830                         WARNING("Volume does not support reparse points!\n"
1831                                 "          Reparse point data will not be extracted.");
1832                 if (!(args->vol_flags & FILE_NAMED_STREAMS)) {
1833                         WARNING("Volume does not support named data streams!\n"
1834                                 "          Named data streams will not be extracted.");
1835                 }
1836                 if (!(args->vol_flags & FILE_SUPPORTS_ENCRYPTION)) {
1837                         WARNING("Volume does not support encryption!\n"
1838                                 "          Encrypted files will be extracted as raw data.");
1839                 }
1840                 if (!(args->vol_flags & FILE_FILE_COMPRESSION)) {
1841                         WARNING("Volume does not support transparent compression!\n"
1842                                 "          Compressed files will be extracted as non-compressed.");
1843                 }
1844                 if (!(args->vol_flags & FILE_PERSISTENT_ACLS)) {
1845                         if (args->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS) {
1846                                 ERROR("Strict ACLs requested, but the volume does not "
1847                                       "support ACLs!");
1848                                 return WIMLIB_ERR_VOLUME_LACKS_FEATURES;
1849                         } else {
1850                                 WARNING("Volume does not support persistent ACLS!\n"
1851                                         "          File permissions will not be extracted.");
1852                         }
1853                 }
1854         }
1855
1856         if (inode->i_nlink > 1 && inode->i_extracted_file != NULL) {
1857                 /* Linked file, with another name already extracted.  Create a
1858                  * hard link. */
1859
1860                 /* There is a volume flag for this (FILE_SUPPORTS_HARD_LINKS),
1861                  * but it's only available on Windows 7 and later.  So no use
1862                  * even checking it, really.  Instead, CreateHardLinkW() will
1863                  * apparently return ERROR_INVALID_FUNCTION if the volume does
1864                  * not support hard links. */
1865                 DEBUG("Creating hard link \"%ls => %ls\"",
1866                       output_path, inode->i_extracted_file);
1867                 if (CreateHardLinkW(output_path, inode->i_extracted_file, NULL))
1868                         return 0;
1869
1870                 err = GetLastError();
1871                 if (err != ERROR_INVALID_FUNCTION) {
1872                         ERROR("Can't create hard link \"%ls => %ls\"",
1873                               output_path, inode->i_extracted_file);
1874                         win32_error(err);
1875                         return WIMLIB_ERR_LINK;
1876                 } else {
1877                         args->num_hard_links_failed++;
1878                         if (args->num_hard_links_failed < MAX_CREATE_HARD_LINK_WARNINGS) {
1879                                 WARNING("Can't create hard link \"%ls => %ls\":\n"
1880                                         "          Volume does not support hard links!\n"
1881                                         "          Falling back to extracting a copy of the file.",
1882                                         output_path, inode->i_extracted_file);
1883                         } else if (args->num_hard_links_failed == MAX_CREATE_HARD_LINK_WARNINGS) {
1884                                 WARNING("Suppressing further hard linking warnings...");
1885                         }
1886                 }
1887         }
1888
1889         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT &&
1890             !(args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS))
1891         {
1892                 WARNING("Skipping extraction of reparse point \"%ls\":\n"
1893                         "          Not supported by destination filesystem",
1894                         output_path);
1895                 struct wim_lookup_table_entry *lte;
1896                 lte = inode_unnamed_lte_resolved(inode);
1897                 if (lte)
1898                         args->progress.extract.completed_bytes += wim_resource_size(lte);
1899                 return 0;
1900         }
1901
1902         /* Create the file, directory, or reparse point, and extract the
1903          * data streams. */
1904         ret = win32_extract_streams(inode, output_path,
1905                                     &args->progress.extract.completed_bytes,
1906                                     args->vol_flags);
1907         if (ret)
1908                 return ret;
1909
1910         if (inode->i_security_id >= 0 &&
1911             !(args->extract_flags & WIMLIB_EXTRACT_FLAG_NO_ACLS)
1912             && (args->vol_flags & FILE_PERSISTENT_ACLS))
1913         {
1914                 ret = win32_set_security_data(inode, output_path, args);
1915                 if (ret)
1916                         return ret;
1917         }
1918         if (inode->i_nlink > 1) {
1919                 /* Save extracted path for a later call to
1920                  * CreateHardLinkW() if this inode has multiple links.
1921                  * */
1922                 inode->i_extracted_file = WSTRDUP(output_path);
1923                 if (!inode->i_extracted_file)
1924                         ret = WIMLIB_ERR_NOMEM;
1925         }
1926         return 0;
1927 }
1928
1929 /* Set timestamps on an extracted file using the Win32 API */
1930 int
1931 win32_do_apply_dentry_timestamps(const wchar_t *path,
1932                                  size_t path_num_chars,
1933                                  const struct wim_dentry *dentry,
1934                                  const struct apply_args *args)
1935 {
1936         DWORD err;
1937         HANDLE h;
1938         const struct wim_inode *inode = dentry->d_inode;
1939
1940         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT &&
1941             !(args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS))
1942         {
1943                 /* Skip reparse points not extracted */
1944                 return 0;
1945         }
1946
1947         /* Windows doesn't let you change the timestamps of the root directory
1948          * (at least on FAT, which is dumb but expected since FAT doesn't store
1949          * any metadata about the root directory...) */
1950         if (path_is_root_of_drive(path))
1951                 return 0;
1952
1953         DEBUG("Opening \"%ls\" to set timestamps", path);
1954         h = win32_open_existing_file(path, FILE_WRITE_ATTRIBUTES);
1955         if (h == INVALID_HANDLE_VALUE) {
1956                 err = GetLastError();
1957                 goto fail;
1958         }
1959
1960         FILETIME creationTime = {.dwLowDateTime = inode->i_creation_time & 0xffffffff,
1961                                  .dwHighDateTime = inode->i_creation_time >> 32};
1962         FILETIME lastAccessTime = {.dwLowDateTime = inode->i_last_access_time & 0xffffffff,
1963                                   .dwHighDateTime = inode->i_last_access_time >> 32};
1964         FILETIME lastWriteTime = {.dwLowDateTime = inode->i_last_write_time & 0xffffffff,
1965                                   .dwHighDateTime = inode->i_last_write_time >> 32};
1966
1967         DEBUG("Calling SetFileTime() on \"%ls\"", path);
1968         if (!SetFileTime(h, &creationTime, &lastAccessTime, &lastWriteTime)) {
1969                 err = GetLastError();
1970                 CloseHandle(h);
1971                 goto fail;
1972         }
1973         DEBUG("Closing \"%ls\"", path);
1974         if (!CloseHandle(h)) {
1975                 err = GetLastError();
1976                 goto fail;
1977         }
1978         goto out;
1979 fail:
1980         /* Only warn if setting timestamps failed; still return 0. */
1981         WARNING("Can't set timestamps on \"%ls\"", path);
1982         win32_error(err);
1983 out:
1984         return 0;
1985 }
1986
1987 /* Replacement for POSIX fsync() */
1988 int
1989 fsync(int fd)
1990 {
1991         DWORD err;
1992         HANDLE h;
1993
1994         h = (HANDLE)_get_osfhandle(fd);
1995         if (h == INVALID_HANDLE_VALUE) {
1996                 err = GetLastError();
1997                 ERROR("Could not get Windows handle for file descriptor");
1998                 win32_error(err);
1999                 errno = EBADF;
2000                 return -1;
2001         }
2002         if (!FlushFileBuffers(h)) {
2003                 err = GetLastError();
2004                 ERROR("Could not flush file buffers to disk");
2005                 win32_error(err);
2006                 errno = EIO;
2007                 return -1;
2008         }
2009         return 0;
2010 }
2011
2012 /* Use the Win32 API to get the number of processors */
2013 unsigned
2014 win32_get_number_of_processors()
2015 {
2016         SYSTEM_INFO sysinfo;
2017         GetSystemInfo(&sysinfo);
2018         return sysinfo.dwNumberOfProcessors;
2019 }
2020
2021 /* Replacement for POSIX-2008 realpath().  Warning: partial functionality only
2022  * (resolved_path must be NULL).   Also I highly doubt that GetFullPathName
2023  * really does the right thing under all circumstances. */
2024 wchar_t *
2025 realpath(const wchar_t *path, wchar_t *resolved_path)
2026 {
2027         DWORD ret;
2028         wimlib_assert(resolved_path == NULL);
2029         DWORD err;
2030
2031         ret = GetFullPathNameW(path, 0, NULL, NULL);
2032         if (!ret) {
2033                 err = GetLastError();
2034                 goto fail_win32;
2035         }
2036
2037         resolved_path = TMALLOC(ret);
2038         if (!resolved_path)
2039                 goto out;
2040         ret = GetFullPathNameW(path, ret, resolved_path, NULL);
2041         if (!ret) {
2042                 err = GetLastError();
2043                 free(resolved_path);
2044                 resolved_path = NULL;
2045                 goto fail_win32;
2046         }
2047         goto out;
2048 fail_win32:
2049         win32_error(err);
2050         errno = -1;
2051 out:
2052         return resolved_path;
2053 }
2054
2055 /* rename() on Windows fails if the destination file exists.  And we need to
2056  * make it work on wide characters.  Fix it. */
2057 int
2058 win32_rename_replacement(const wchar_t *oldpath, const wchar_t *newpath)
2059 {
2060         if (MoveFileExW(oldpath, newpath, MOVEFILE_REPLACE_EXISTING)) {
2061                 return 0;
2062         } else {
2063                 /* As usual, the possible error values are not documented */
2064                 DWORD err = GetLastError();
2065                 ERROR("MoveFileEx(): Can't rename \"%ls\" to \"%ls\"",
2066                       oldpath, newpath);
2067                 win32_error(err);
2068                 errno = -1;
2069                 return -1;
2070         }
2071 }
2072
2073 /* Replacement for POSIX fnmatch() (partial functionality only) */
2074 int
2075 fnmatch(const wchar_t *pattern, const wchar_t *string, int flags)
2076 {
2077         if (PathMatchSpecW(string, pattern))
2078                 return 0;
2079         else
2080                 return FNM_NOMATCH;
2081 }
2082
2083 /* truncate() replacement */
2084 int
2085 win32_truncate_replacement(const wchar_t *path, off_t size)
2086 {
2087         DWORD err = NO_ERROR;
2088         LARGE_INTEGER liOffset;
2089
2090         HANDLE h = win32_open_existing_file(path, GENERIC_WRITE);
2091         if (h == INVALID_HANDLE_VALUE)
2092                 goto fail;
2093
2094         liOffset.QuadPart = size;
2095         if (!SetFilePointerEx(h, liOffset, NULL, FILE_BEGIN))
2096                 goto fail_close_handle;
2097
2098         if (!SetEndOfFile(h))
2099                 goto fail_close_handle;
2100         CloseHandle(h);
2101         return 0;
2102
2103 fail_close_handle:
2104         err = GetLastError();
2105         CloseHandle(h);
2106 fail:
2107         if (err == NO_ERROR)
2108                 err = GetLastError();
2109         ERROR("Can't truncate \"%ls\" to %"PRIu64" bytes", path, size);
2110         win32_error(err);
2111         errno = -1;
2112         return -1;
2113 }
2114
2115
2116 /* This really could be replaced with _wcserror_s, but this doesn't seem to
2117  * actually be available in MSVCRT.DLL on Windows XP (perhaps it's statically
2118  * linked in by Visual Studio...?). */
2119 extern int
2120 win32_strerror_r_replacement(int errnum, wchar_t *buf, size_t buflen)
2121 {
2122         static pthread_mutex_t strerror_lock = PTHREAD_MUTEX_INITIALIZER;
2123
2124         pthread_mutex_lock(&strerror_lock);
2125         mbstowcs(buf, strerror(errnum), buflen);
2126         buf[buflen - 1] = '\0';
2127         pthread_mutex_unlock(&strerror_lock);
2128         return 0;
2129 }
2130
2131 #endif /* __WIN32__ */