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