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