Add Windows implementations of pread(), pwrite(), writev()
[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 static int
82 win32_error_to_errno(DWORD err_code)
83 {
84         /* This mapping is that used in Cygwin.
85          * Some of these choices are arbitrary. */
86         switch (err_code) {
87         case ERROR_ACCESS_DENIED:
88                 return EACCES;
89         case ERROR_ACTIVE_CONNECTIONS:
90                 return EAGAIN;
91         case ERROR_ALREADY_EXISTS:
92                 return EEXIST;
93         case ERROR_BAD_DEVICE:
94                 return ENODEV;
95         case ERROR_BAD_EXE_FORMAT:
96                 return ENOEXEC;
97         case ERROR_BAD_NETPATH:
98                 return ENOENT;
99         case ERROR_BAD_NET_NAME:
100                 return ENOENT;
101         case ERROR_BAD_NET_RESP:
102                 return ENOSYS;
103         case ERROR_BAD_PATHNAME:
104                 return ENOENT;
105         case ERROR_BAD_PIPE:
106                 return EINVAL;
107         case ERROR_BAD_UNIT:
108                 return ENODEV;
109         case ERROR_BAD_USERNAME:
110                 return EINVAL;
111         case ERROR_BEGINNING_OF_MEDIA:
112                 return EIO;
113         case ERROR_BROKEN_PIPE:
114                 return EPIPE;
115         case ERROR_BUSY:
116                 return EBUSY;
117         case ERROR_BUS_RESET:
118                 return EIO;
119         case ERROR_CALL_NOT_IMPLEMENTED:
120                 return ENOSYS;
121         case ERROR_CANNOT_MAKE:
122                 return EPERM;
123         case ERROR_CHILD_NOT_COMPLETE:
124                 return EBUSY;
125         case ERROR_COMMITMENT_LIMIT:
126                 return EAGAIN;
127         case ERROR_CRC:
128                 return EIO;
129         case ERROR_DEVICE_DOOR_OPEN:
130                 return EIO;
131         case ERROR_DEVICE_IN_USE:
132                 return EAGAIN;
133         case ERROR_DEVICE_REQUIRES_CLEANING:
134                 return EIO;
135         case ERROR_DIRECTORY:
136                 return ENOTDIR;
137         case ERROR_DIR_NOT_EMPTY:
138                 return ENOTEMPTY;
139         case ERROR_DISK_CORRUPT:
140                 return EIO;
141         case ERROR_DISK_FULL:
142                 return ENOSPC;
143 #ifdef ENOTUNIQ
144         case ERROR_DUP_NAME:
145                 return ENOTUNIQ;
146 #endif
147         case ERROR_EAS_DIDNT_FIT:
148                 return ENOSPC;
149         case ERROR_EAS_NOT_SUPPORTED:
150                 return ENOTSUP;
151         case ERROR_EA_LIST_INCONSISTENT:
152                 return EINVAL;
153         case ERROR_EA_TABLE_FULL:
154                 return ENOSPC;
155         case ERROR_END_OF_MEDIA:
156                 return ENOSPC;
157         case ERROR_EOM_OVERFLOW:
158                 return EIO;
159         case ERROR_EXE_MACHINE_TYPE_MISMATCH:
160                 return ENOEXEC;
161         case ERROR_EXE_MARKED_INVALID:
162                 return ENOEXEC;
163         case ERROR_FILEMARK_DETECTED:
164                 return EIO;
165         case ERROR_FILENAME_EXCED_RANGE:
166                 return ENAMETOOLONG;
167         case ERROR_FILE_CORRUPT:
168                 return EEXIST;
169         case ERROR_FILE_EXISTS:
170                 return EEXIST;
171         case ERROR_FILE_INVALID:
172                 return ENXIO;
173         case ERROR_FILE_NOT_FOUND:
174                 return ENOENT;
175         case ERROR_HANDLE_DISK_FULL:
176                 return ENOSPC;
177 #ifdef ENODATA
178         case ERROR_HANDLE_EOF:
179                 return ENODATA;
180 #endif
181         case ERROR_INVALID_ADDRESS:
182                 return EINVAL;
183         case ERROR_INVALID_AT_INTERRUPT_TIME:
184                 return EINTR;
185         case ERROR_INVALID_BLOCK_LENGTH:
186                 return EIO;
187         case ERROR_INVALID_DATA:
188                 return EINVAL;
189         case ERROR_INVALID_DRIVE:
190                 return ENODEV;
191         case ERROR_INVALID_EA_NAME:
192                 return EINVAL;
193         case ERROR_INVALID_EXE_SIGNATURE:
194                 return ENOEXEC;
195 #ifdef EBADRQC
196         case ERROR_INVALID_FUNCTION:
197                 return EBADRQC;
198 #endif
199         case ERROR_INVALID_HANDLE:
200                 return EBADF;
201         case ERROR_INVALID_NAME:
202                 return ENOENT;
203         case ERROR_INVALID_PARAMETER:
204                 return EINVAL;
205         case ERROR_INVALID_SIGNAL_NUMBER:
206                 return EINVAL;
207         case ERROR_IOPL_NOT_ENABLED:
208                 return ENOEXEC;
209         case ERROR_IO_DEVICE:
210                 return EIO;
211         case ERROR_IO_INCOMPLETE:
212                 return EAGAIN;
213         case ERROR_IO_PENDING:
214                 return EAGAIN;
215         case ERROR_LOCK_VIOLATION:
216                 return EBUSY;
217         case ERROR_MAX_THRDS_REACHED:
218                 return EAGAIN;
219         case ERROR_META_EXPANSION_TOO_LONG:
220                 return EINVAL;
221         case ERROR_MOD_NOT_FOUND:
222                 return ENOENT;
223 #ifdef EMSGSIZE
224         case ERROR_MORE_DATA:
225                 return EMSGSIZE;
226 #endif
227         case ERROR_NEGATIVE_SEEK:
228                 return EINVAL;
229         case ERROR_NETNAME_DELETED:
230                 return ENOENT;
231         case ERROR_NOACCESS:
232                 return EFAULT;
233         case ERROR_NONE_MAPPED:
234                 return EINVAL;
235         case ERROR_NONPAGED_SYSTEM_RESOURCES:
236                 return EAGAIN;
237 #ifdef ENOLINK
238         case ERROR_NOT_CONNECTED:
239                 return ENOLINK;
240 #endif
241         case ERROR_NOT_ENOUGH_MEMORY:
242                 return ENOMEM;
243         case ERROR_NOT_OWNER:
244                 return EPERM;
245 #ifdef ENOMEDIUM
246         case ERROR_NOT_READY:
247                 return ENOMEDIUM;
248 #endif
249         case ERROR_NOT_SAME_DEVICE:
250                 return EXDEV;
251         case ERROR_NOT_SUPPORTED:
252                 return ENOSYS;
253         case ERROR_NO_DATA:
254                 return EPIPE;
255         case ERROR_NO_DATA_DETECTED:
256                 return EIO;
257 #ifdef ENOMEDIUM
258         case ERROR_NO_MEDIA_IN_DRIVE:
259                 return ENOMEDIUM;
260 #endif
261 #ifdef ENMFILE
262         case ERROR_NO_MORE_FILES:
263                 return ENMFILE;
264 #endif
265 #ifdef ENMFILE
266         case ERROR_NO_MORE_ITEMS:
267                 return ENMFILE;
268 #endif
269         case ERROR_NO_MORE_SEARCH_HANDLES:
270                 return ENFILE;
271         case ERROR_NO_PROC_SLOTS:
272                 return EAGAIN;
273         case ERROR_NO_SIGNAL_SENT:
274                 return EIO;
275         case ERROR_NO_SYSTEM_RESOURCES:
276                 return EFBIG;
277         case ERROR_NO_TOKEN:
278                 return EINVAL;
279         case ERROR_OPEN_FAILED:
280                 return EIO;
281         case ERROR_OPEN_FILES:
282                 return EAGAIN;
283         case ERROR_OUTOFMEMORY:
284                 return ENOMEM;
285         case ERROR_PAGED_SYSTEM_RESOURCES:
286                 return EAGAIN;
287         case ERROR_PAGEFILE_QUOTA:
288                 return EAGAIN;
289         case ERROR_PATH_NOT_FOUND:
290                 return ENOENT;
291         case ERROR_PIPE_BUSY:
292                 return EBUSY;
293         case ERROR_PIPE_CONNECTED:
294                 return EBUSY;
295 #ifdef ECOMM
296         case ERROR_PIPE_LISTENING:
297                 return ECOMM;
298         case ERROR_PIPE_NOT_CONNECTED:
299                 return ECOMM;
300 #endif
301         case ERROR_POSSIBLE_DEADLOCK:
302                 return EDEADLOCK;
303         case ERROR_PRIVILEGE_NOT_HELD:
304                 return EPERM;
305         case ERROR_PROCESS_ABORTED:
306                 return EFAULT;
307         case ERROR_PROC_NOT_FOUND:
308                 return ESRCH;
309 #ifdef ENONET
310         case ERROR_REM_NOT_LIST:
311                 return ENONET;
312 #endif
313         case ERROR_SECTOR_NOT_FOUND:
314                 return EINVAL;
315         case ERROR_SEEK:
316                 return EINVAL;
317         case ERROR_SETMARK_DETECTED:
318                 return EIO;
319         case ERROR_SHARING_BUFFER_EXCEEDED:
320                 return ENOLCK;
321         case ERROR_SHARING_VIOLATION:
322                 return EBUSY;
323         case ERROR_SIGNAL_PENDING:
324                 return EBUSY;
325         case ERROR_SIGNAL_REFUSED:
326                 return EIO;
327 #ifdef ELIBBAD
328         case ERROR_SXS_CANT_GEN_ACTCTX:
329                 return ELIBBAD;
330 #endif
331         case ERROR_THREAD_1_INACTIVE:
332                 return EINVAL;
333         case ERROR_TOO_MANY_LINKS:
334                 return EMLINK;
335         case ERROR_TOO_MANY_OPEN_FILES:
336                 return EMFILE;
337         case ERROR_WAIT_NO_CHILDREN:
338                 return ECHILD;
339         case ERROR_WORKING_SET_QUOTA:
340                 return EAGAIN;
341         case ERROR_WRITE_PROTECT:
342                 return EROFS;
343         default:
344                 return -1;
345         }
346 }
347
348 static void
349 set_errno_from_GetLastError()
350 {
351         errno = win32_error_to_errno(GetLastError());
352 }
353
354 /* Pointers to functions that are not available on all targetted versions of
355  * Windows (XP and later).  NOTE: The WINAPI annotations seem to be important; I
356  * assume it specifies a certain calling convention. */
357
358 /* Vista and later */
359 static HANDLE (WINAPI *win32func_FindFirstStreamW)(LPCWSTR lpFileName,
360                                             STREAM_INFO_LEVELS InfoLevel,
361                                             LPVOID lpFindStreamData,
362                                             DWORD dwFlags) = NULL;
363
364 /* Vista and later */
365 static BOOL (WINAPI *win32func_FindNextStreamW)(HANDLE hFindStream,
366                                          LPVOID lpFindStreamData) = NULL;
367
368 static HMODULE hKernel32 = NULL;
369
370 /* Try to dynamically load some functions */
371 void
372 win32_global_init()
373 {
374         DWORD err;
375
376         if (hKernel32 == NULL) {
377                 DEBUG("Loading Kernel32.dll");
378                 hKernel32 = LoadLibraryW(L"Kernel32.dll");
379                 if (hKernel32 == NULL) {
380                         err = GetLastError();
381                         WARNING("Can't load Kernel32.dll");
382                         win32_error(err);
383                         return;
384                 }
385         }
386
387         DEBUG("Looking for FindFirstStreamW");
388         win32func_FindFirstStreamW = (void*)GetProcAddress(hKernel32, "FindFirstStreamW");
389         if (!win32func_FindFirstStreamW) {
390                 WARNING("Could not find function FindFirstStreamW() in Kernel32.dll!");
391                 WARNING("Capturing alternate data streams will not be supported.");
392                 return;
393         }
394
395         DEBUG("Looking for FindNextStreamW");
396         win32func_FindNextStreamW = (void*)GetProcAddress(hKernel32, "FindNextStreamW");
397         if (!win32func_FindNextStreamW) {
398                 WARNING("Could not find function FindNextStreamW() in Kernel32.dll!");
399                 WARNING("Capturing alternate data streams will not be supported.");
400                 win32func_FindFirstStreamW = NULL;
401         }
402 }
403
404 void
405 win32_global_cleanup()
406 {
407         if (hKernel32 != NULL) {
408                 DEBUG("Closing Kernel32.dll");
409                 FreeLibrary(hKernel32);
410                 hKernel32 = NULL;
411         }
412 }
413
414 static const wchar_t *capture_access_denied_msg =
415 L"         If you are not running this program as the administrator, you may\n"
416  "         need to do so, so that all data and metadata can be backed up.\n"
417  "         Otherwise, there may be no way to access the desired data or\n"
418  "         metadata without taking ownership of the file or directory.\n"
419  ;
420
421 static const wchar_t *apply_access_denied_msg =
422 L"If you are not running this program as the administrator, you may\n"
423  "          need to do so, so that all data and metadata can be extracted\n"
424  "          exactly as the origignal copy.  However, if you do not care that\n"
425  "          the security descriptors are extracted correctly, you could run\n"
426  "          `wimlib-imagex apply' with the --no-acls flag instead.\n"
427  ;
428
429 static HANDLE
430 win32_open_existing_file(const wchar_t *path, DWORD dwDesiredAccess)
431 {
432         return CreateFileW(path,
433                            dwDesiredAccess,
434                            FILE_SHARE_READ,
435                            NULL, /* lpSecurityAttributes */
436                            OPEN_EXISTING,
437                            FILE_FLAG_BACKUP_SEMANTICS |
438                                FILE_FLAG_OPEN_REPARSE_POINT,
439                            NULL /* hTemplateFile */);
440 }
441
442 HANDLE
443 win32_open_file_data_only(const wchar_t *path)
444 {
445         return win32_open_existing_file(path, FILE_READ_DATA);
446 }
447
448 int
449 read_win32_file_prefix(const struct wim_lookup_table_entry *lte,
450                        u64 size,
451                        consume_data_callback_t cb,
452                        void *ctx_or_buf,
453                        int _ignored_flags)
454 {
455         int ret = 0;
456         void *out_buf;
457         DWORD err;
458         u64 bytes_remaining;
459
460         HANDLE hFile = win32_open_file_data_only(lte->file_on_disk);
461         if (hFile == INVALID_HANDLE_VALUE) {
462                 err = GetLastError();
463                 ERROR("Failed to open \"%ls\"", lte->file_on_disk);
464                 win32_error(err);
465                 return WIMLIB_ERR_OPEN;
466         }
467
468         if (cb)
469                 out_buf = alloca(WIM_CHUNK_SIZE);
470         else
471                 out_buf = ctx_or_buf;
472
473         bytes_remaining = size;
474         while (bytes_remaining) {
475                 DWORD bytesToRead, bytesRead;
476
477                 bytesToRead = min(WIM_CHUNK_SIZE, bytes_remaining);
478                 if (!ReadFile(hFile, out_buf, bytesToRead, &bytesRead, NULL) ||
479                     bytesRead != bytesToRead)
480                 {
481                         err = GetLastError();
482                         ERROR("Failed to read data from \"%ls\"", lte->file_on_disk);
483                         win32_error(err);
484                         ret = WIMLIB_ERR_READ;
485                         break;
486                 }
487                 bytes_remaining -= bytesRead;
488                 if (cb) {
489                         ret = (*cb)(out_buf, bytesRead, ctx_or_buf);
490                         if (ret)
491                                 break;
492                 } else {
493                         out_buf += bytesRead;
494                 }
495         }
496         CloseHandle(hFile);
497         return ret;
498 }
499
500 struct win32_encrypted_read_ctx {
501         consume_data_callback_t read_prefix_cb;
502         void *read_prefix_ctx_or_buf;
503         int wimlib_err_code;
504         void *buf;
505         size_t buf_filled;
506         u64 bytes_remaining;
507 };
508
509 static DWORD WINAPI
510 win32_encrypted_export_cb(unsigned char *_data, void *_ctx, unsigned long len)
511 {
512         const void *data = _data;
513         struct win32_encrypted_read_ctx *ctx = _ctx;
514         int ret;
515
516         DEBUG("len = %lu", len);
517         if (ctx->read_prefix_cb) {
518                 /* The length of the buffer passed to the ReadEncryptedFileRaw()
519                  * export callback is undocumented, so we assume it may be of
520                  * arbitrary size. */
521                 size_t bytes_to_buffer = min(ctx->bytes_remaining - ctx->buf_filled,
522                                              len);
523                 while (bytes_to_buffer) {
524                         size_t bytes_to_copy_to_buf =
525                                 min(bytes_to_buffer, WIM_CHUNK_SIZE - ctx->buf_filled);
526
527                         memcpy(ctx->buf + ctx->buf_filled, data,
528                                bytes_to_copy_to_buf);
529                         ctx->buf_filled += bytes_to_copy_to_buf;
530                         data += bytes_to_copy_to_buf;
531                         bytes_to_buffer -= bytes_to_copy_to_buf;
532
533                         if (ctx->buf_filled == WIM_CHUNK_SIZE ||
534                             ctx->buf_filled == ctx->bytes_remaining)
535                         {
536                                 ret = (*ctx->read_prefix_cb)(ctx->buf,
537                                                              ctx->buf_filled,
538                                                              ctx->read_prefix_ctx_or_buf);
539                                 if (ret) {
540                                         ctx->wimlib_err_code = ret;
541                                         /* Shouldn't matter what error code is returned
542                                          * here, as long as it isn't ERROR_SUCCESS. */
543                                         return ERROR_READ_FAULT;
544                                 }
545                                 ctx->bytes_remaining -= ctx->buf_filled;
546                                 ctx->buf_filled = 0;
547                         }
548                 }
549         } else {
550                 size_t len_to_copy = min(len, ctx->bytes_remaining);
551                 memcpy(ctx->read_prefix_ctx_or_buf, data, len_to_copy);
552                 ctx->bytes_remaining -= len_to_copy;
553                 ctx->read_prefix_ctx_or_buf += len_to_copy;
554         }
555         return ERROR_SUCCESS;
556 }
557
558 int
559 read_win32_encrypted_file_prefix(const struct wim_lookup_table_entry *lte,
560                                  u64 size,
561                                  consume_data_callback_t cb,
562                                  void *ctx_or_buf,
563                                  int _ignored_flags)
564 {
565         struct win32_encrypted_read_ctx export_ctx;
566         DWORD err;
567         void *file_ctx;
568         int ret;
569
570         DEBUG("Reading %"PRIu64" bytes from encryted file \"%ls\"",
571               size, lte->file_on_disk);
572
573         export_ctx.read_prefix_cb = cb;
574         export_ctx.read_prefix_ctx_or_buf = ctx_or_buf;
575         export_ctx.wimlib_err_code = 0;
576         if (cb) {
577                 export_ctx.buf = MALLOC(WIM_CHUNK_SIZE);
578                 if (!export_ctx.buf)
579                         return WIMLIB_ERR_NOMEM;
580         } else {
581                 export_ctx.buf = NULL;
582         }
583         export_ctx.buf_filled = 0;
584         export_ctx.bytes_remaining = size;
585
586         err = OpenEncryptedFileRawW(lte->file_on_disk, 0, &file_ctx);
587         if (err != ERROR_SUCCESS) {
588                 ERROR("Failed to open encrypted file \"%ls\" for raw read",
589                       lte->file_on_disk);
590                 win32_error(err);
591                 ret = WIMLIB_ERR_OPEN;
592                 goto out_free_buf;
593         }
594         err = ReadEncryptedFileRaw(win32_encrypted_export_cb,
595                                    &export_ctx, file_ctx);
596         if (err != ERROR_SUCCESS) {
597                 ERROR("Failed to read encrypted file \"%ls\"",
598                       lte->file_on_disk);
599                 win32_error(err);
600                 ret = export_ctx.wimlib_err_code;
601                 if (ret == 0)
602                         ret = WIMLIB_ERR_READ;
603         } else if (export_ctx.bytes_remaining != 0) {
604                 ERROR("Only could read %"PRIu64" of %"PRIu64" bytes from "
605                       "encryted file \"%ls\"",
606                       size - export_ctx.bytes_remaining, size,
607                       lte->file_on_disk);
608                 ret = WIMLIB_ERR_READ;
609         } else {
610                 ret = 0;
611         }
612         CloseEncryptedFileRaw(file_ctx);
613 out_free_buf:
614         FREE(export_ctx.buf);
615         return ret;
616 }
617
618 /* Given a path, which may not yet exist, get a set of flags that describe the
619  * features of the volume the path is on. */
620 static int
621 win32_get_vol_flags(const wchar_t *path, unsigned *vol_flags_ret)
622 {
623         wchar_t *volume;
624         BOOL bret;
625         DWORD vol_flags;
626
627         if (path[0] != L'\0' && path[0] != L'\\' &&
628             path[0] != L'/' && path[1] == L':')
629         {
630                 /* Path starts with a drive letter; use it. */
631                 volume = alloca(4 * sizeof(wchar_t));
632                 volume[0] = path[0];
633                 volume[1] = path[1];
634                 volume[2] = L'\\';
635                 volume[3] = L'\0';
636         } else {
637                 /* Path does not start with a drive letter; use the volume of
638                  * the current working directory. */
639                 volume = NULL;
640         }
641         bret = GetVolumeInformationW(volume, /* lpRootPathName */
642                                      NULL,  /* lpVolumeNameBuffer */
643                                      0,     /* nVolumeNameSize */
644                                      NULL,  /* lpVolumeSerialNumber */
645                                      NULL,  /* lpMaximumComponentLength */
646                                      &vol_flags, /* lpFileSystemFlags */
647                                      NULL,  /* lpFileSystemNameBuffer */
648                                      0);    /* nFileSystemNameSize */
649         if (!bret) {
650                 DWORD err = GetLastError();
651                 WARNING("Failed to get volume information for path \"%ls\"", path);
652                 win32_error(err);
653                 vol_flags = 0xffffffff;
654         }
655
656         DEBUG("using vol_flags = %x", vol_flags);
657         *vol_flags_ret = vol_flags;
658         return 0;
659 }
660
661
662 static u64
663 FILETIME_to_u64(const FILETIME *ft)
664 {
665         return ((u64)ft->dwHighDateTime << 32) | (u64)ft->dwLowDateTime;
666 }
667
668 static int
669 win32_get_short_name(struct wim_dentry *dentry, const wchar_t *path)
670 {
671         WIN32_FIND_DATAW dat;
672         HANDLE hFind;
673         int ret = 0;
674
675         /* If we can't read the short filename for some reason, we just ignore
676          * the error and assume the file has no short name.  I don't think this
677          * should be an issue, since the short names are essentially obsolete
678          * anyway. */
679         hFind = FindFirstFileW(path, &dat);
680         if (hFind != INVALID_HANDLE_VALUE) {
681                 if (dat.cAlternateFileName[0] != L'\0') {
682                         DEBUG("\"%ls\": short name \"%ls\"", path, dat.cAlternateFileName);
683                         size_t short_name_nbytes = wcslen(dat.cAlternateFileName) *
684                                                    sizeof(wchar_t);
685                         size_t n = short_name_nbytes + sizeof(wchar_t);
686                         dentry->short_name = MALLOC(n);
687                         if (dentry->short_name) {
688                                 memcpy(dentry->short_name, dat.cAlternateFileName, n);
689                                 dentry->short_name_nbytes = short_name_nbytes;
690                         } else {
691                                 ret = WIMLIB_ERR_NOMEM;
692                         }
693                 }
694                 FindClose(hFind);
695         }
696         return ret;
697 }
698
699 static int
700 win32_get_security_descriptor(struct wim_dentry *dentry,
701                               struct sd_set *sd_set,
702                               const wchar_t *path,
703                               struct win32_capture_state *state,
704                               int add_image_flags)
705 {
706         SECURITY_INFORMATION requestedInformation;
707         DWORD lenNeeded = 0;
708         BOOL status;
709         DWORD err;
710         unsigned long n;
711
712         requestedInformation = DACL_SECURITY_INFORMATION |
713                                SACL_SECURITY_INFORMATION |
714                                OWNER_SECURITY_INFORMATION |
715                                GROUP_SECURITY_INFORMATION;
716 again:
717         /* Request length of security descriptor */
718         status = GetFileSecurityW(path, requestedInformation,
719                                   NULL, 0, &lenNeeded);
720         err = GetLastError();
721         if (!status && err == ERROR_INSUFFICIENT_BUFFER) {
722                 DWORD len = lenNeeded;
723                 char buf[len];
724                 if (GetFileSecurityW(path, requestedInformation,
725                                      (PSECURITY_DESCRIPTOR)buf, len, &lenNeeded))
726                 {
727                         int security_id = sd_set_add_sd(sd_set, buf, len);
728                         if (security_id < 0)
729                                 return WIMLIB_ERR_NOMEM;
730                         else {
731                                 dentry->d_inode->i_security_id = security_id;
732                                 return 0;
733                         }
734                 } else {
735                         err = GetLastError();
736                 }
737         }
738
739         if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_STRICT_ACLS)
740                 goto fail;
741
742         switch (err) {
743         case ERROR_PRIVILEGE_NOT_HELD:
744                 if (requestedInformation & SACL_SECURITY_INFORMATION) {
745                         n = state->num_get_sacl_priv_notheld++;
746                         requestedInformation &= ~SACL_SECURITY_INFORMATION;
747                         if (n < MAX_GET_SACL_PRIV_NOTHELD_WARNINGS) {
748                                 WARNING(
749 "We don't have enough privileges to read the full security\n"
750 "          descriptor of \"%ls\"!\n"
751 "          Re-trying with SACL omitted.\n", path);
752                         } else if (n == MAX_GET_SACL_PRIV_NOTHELD_WARNINGS) {
753                                 WARNING(
754 "Suppressing further privileges not held error messages when reading\n"
755 "          security descriptors.");
756                         }
757                         goto again;
758                 }
759                 /* Fall through */
760         case ERROR_ACCESS_DENIED:
761                 n = state->num_get_sd_access_denied++;
762                 if (n < MAX_GET_SD_ACCESS_DENIED_WARNINGS) {
763                         WARNING("Failed to read security descriptor of \"%ls\": "
764                                 "Access denied!\n%ls", path, capture_access_denied_msg);
765                 } else if (n == MAX_GET_SD_ACCESS_DENIED_WARNINGS) {
766                         WARNING("Suppressing further access denied errors messages i"
767                                 "when reading security descriptors");
768                 }
769                 return 0;
770         default:
771 fail:
772                 ERROR("Failed to read security descriptor of \"%ls\"", path);
773                 win32_error(err);
774                 return WIMLIB_ERR_READ;
775         }
776 }
777
778 static int
779 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
780                                   wchar_t *path,
781                                   size_t path_num_chars,
782                                   struct add_image_params *params,
783                                   struct win32_capture_state *state,
784                                   unsigned vol_flags);
785
786 /* Reads the directory entries of directory using a Win32 API and recursively
787  * calls win32_build_dentry_tree() on them. */
788 static int
789 win32_recurse_directory(struct wim_dentry *root,
790                         wchar_t *dir_path,
791                         size_t dir_path_num_chars,
792                         struct add_image_params *params,
793                         struct win32_capture_state *state,
794                         unsigned vol_flags)
795 {
796         WIN32_FIND_DATAW dat;
797         HANDLE hFind;
798         DWORD err;
799         int ret;
800
801         DEBUG("Recurse to directory \"%ls\"", dir_path);
802
803         /* Begin reading the directory by calling FindFirstFileW.  Unlike UNIX
804          * opendir(), FindFirstFileW has file globbing built into it.  But this
805          * isn't what we actually want, so just add a dummy glob to get all
806          * entries. */
807         dir_path[dir_path_num_chars] = L'/';
808         dir_path[dir_path_num_chars + 1] = L'*';
809         dir_path[dir_path_num_chars + 2] = L'\0';
810         hFind = FindFirstFileW(dir_path, &dat);
811         dir_path[dir_path_num_chars] = L'\0';
812
813         if (hFind == INVALID_HANDLE_VALUE) {
814                 err = GetLastError();
815                 if (err == ERROR_FILE_NOT_FOUND) {
816                         return 0;
817                 } else {
818                         ERROR("Failed to read directory \"%ls\"", dir_path);
819                         win32_error(err);
820                         return WIMLIB_ERR_READ;
821                 }
822         }
823         ret = 0;
824         do {
825                 /* Skip . and .. entries */
826                 if (dat.cFileName[0] == L'.' &&
827                     (dat.cFileName[1] == L'\0' ||
828                      (dat.cFileName[1] == L'.' &&
829                       dat.cFileName[2] == L'\0')))
830                         continue;
831                 size_t filename_len = wcslen(dat.cFileName);
832
833                 dir_path[dir_path_num_chars] = L'/';
834                 wmemcpy(dir_path + dir_path_num_chars + 1,
835                         dat.cFileName,
836                         filename_len + 1);
837
838                 struct wim_dentry *child;
839                 size_t path_len = dir_path_num_chars + 1 + filename_len;
840                 ret = win32_build_dentry_tree_recursive(&child,
841                                                         dir_path,
842                                                         path_len,
843                                                         params,
844                                                         state,
845                                                         vol_flags);
846                 dir_path[dir_path_num_chars] = L'\0';
847                 if (ret)
848                         goto out_find_close;
849                 if (child)
850                         dentry_add_child(root, child);
851         } while (FindNextFileW(hFind, &dat));
852         err = GetLastError();
853         if (err != ERROR_NO_MORE_FILES) {
854                 ERROR("Failed to read directory \"%ls\"", dir_path);
855                 win32_error(err);
856                 if (ret == 0)
857                         ret = WIMLIB_ERR_READ;
858         }
859 out_find_close:
860         FindClose(hFind);
861         return ret;
862 }
863
864 int
865 win32_get_file_and_vol_ids(const wchar_t *path, u64 *ino_ret, u64 *dev_ret)
866 {
867         HANDLE hFile;
868         DWORD err;
869         BY_HANDLE_FILE_INFORMATION file_info;
870         int ret;
871
872         hFile = win32_open_existing_file(path, FILE_READ_ATTRIBUTES);
873         if (hFile == INVALID_HANDLE_VALUE) {
874                 err = GetLastError();
875                 if (err != ERROR_FILE_NOT_FOUND) {
876                         WARNING("Failed to open \"%ls\" to get file "
877                                 "and volume IDs", path);
878                         win32_error(err);
879                 }
880                 return WIMLIB_ERR_OPEN;
881         }
882
883         if (!GetFileInformationByHandle(hFile, &file_info)) {
884                 err = GetLastError();
885                 ERROR("Failed to get file information for \"%ls\"", path);
886                 win32_error(err);
887                 ret = WIMLIB_ERR_STAT;
888         } else {
889                 *ino_ret = ((u64)file_info.nFileIndexHigh << 32) |
890                             (u64)file_info.nFileIndexLow;
891                 *dev_ret = file_info.dwVolumeSerialNumber;
892                 ret = 0;
893         }
894         CloseHandle(hFile);
895         return ret;
896 }
897
898 /* Reparse point fixup status code */
899 enum rp_status {
900         /* Reparse point corresponded to an absolute symbolic link or junction
901          * point that pointed outside the directory tree being captured, and
902          * therefore was excluded. */
903         RP_EXCLUDED       = 0x0,
904
905         /* Reparse point was not fixed as it was either a relative symbolic
906          * link, a mount point, or something else we could not understand. */
907         RP_NOT_FIXED      = 0x1,
908
909         /* Reparse point corresponded to an absolute symbolic link or junction
910          * point that pointed inside the directory tree being captured, where
911          * the target was specified by a "full" \??\ prefixed path, and
912          * therefore was fixed to be relative to the root of the directory tree
913          * being captured. */
914         RP_FIXED_FULLPATH = 0x2,
915
916         /* Same as RP_FIXED_FULLPATH, except the absolute link target did not
917          * have the \??\ prefix.  It may have begun with a drive letter though.
918          * */
919         RP_FIXED_ABSPATH  = 0x4,
920
921         /* Either RP_FIXED_FULLPATH or RP_FIXED_ABSPATH. */
922         RP_FIXED          = RP_FIXED_FULLPATH | RP_FIXED_ABSPATH,
923 };
924
925 /* Given the "substitute name" target of a Windows reparse point, try doing a
926  * fixup where we change it to be absolute relative to the root of the directory
927  * tree being captured.
928  *
929  * Note that this is only executed when WIMLIB_ADD_IMAGE_FLAG_RPFIX has been
930  * set.
931  *
932  * @capture_root_ino and @capture_root_dev indicate the inode number and device
933  * of the root of the directory tree being captured.  They are meant to identify
934  * this directory (as an alternative to its actual path, which could potentially
935  * be reached via multiple destinations due to other symbolic links).  This may
936  * not work properly on FAT, which doesn't seem to supply proper inode numbers
937  * or file IDs.  However, FAT doesn't support reparse points so this function
938  * wouldn't even be called anyway.
939  */
940 static enum rp_status
941 win32_capture_maybe_rpfix_target(wchar_t *target, u16 *target_nbytes_p,
942                                  u64 capture_root_ino, u64 capture_root_dev,
943                                  u32 rptag)
944 {
945         u16 target_nchars = *target_nbytes_p / 2;
946         size_t stripped_chars;
947         wchar_t *orig_target;
948         int ret;
949
950         ret = parse_substitute_name(target, *target_nbytes_p, rptag);
951         if (ret < 0)
952                 return RP_NOT_FIXED;
953         stripped_chars = ret;
954         if (stripped_chars)
955                 stripped_chars -= 2;
956         target[target_nchars] = L'\0';
957         orig_target = target;
958         target = capture_fixup_absolute_symlink(target + stripped_chars,
959                                                 capture_root_ino, capture_root_dev);
960         if (!target)
961                 return RP_EXCLUDED;
962         target_nchars = wcslen(target);
963         wmemmove(orig_target + stripped_chars, target, target_nchars + 1);
964         *target_nbytes_p = (target_nchars + stripped_chars) * sizeof(wchar_t);
965         DEBUG("Fixed reparse point (new target: \"%ls\")", orig_target);
966         if (stripped_chars)
967                 return RP_FIXED_FULLPATH;
968         else
969                 return RP_FIXED_ABSPATH;
970 }
971
972 /* Returns: `enum rp_status' value on success; negative WIMLIB_ERR_* value on
973  * failure. */
974 static int
975 win32_capture_try_rpfix(u8 *rpbuf, u16 *rpbuflen_p,
976                         u64 capture_root_ino, u64 capture_root_dev,
977                         const wchar_t *path)
978 {
979         struct reparse_data rpdata;
980         DWORD rpbuflen;
981         int ret;
982         enum rp_status rp_status;
983
984         rpbuflen = *rpbuflen_p;
985         ret = parse_reparse_data(rpbuf, rpbuflen, &rpdata);
986         if (ret)
987                 return -ret;
988
989         rp_status = win32_capture_maybe_rpfix_target(rpdata.substitute_name,
990                                                      &rpdata.substitute_name_nbytes,
991                                                      capture_root_ino,
992                                                      capture_root_dev,
993                                                      le32_to_cpu(*(u32*)rpbuf));
994         if (rp_status & RP_FIXED) {
995                 wimlib_assert(rpdata.substitute_name_nbytes % 2 == 0);
996                 utf16lechar substitute_name_copy[rpdata.substitute_name_nbytes / 2];
997                 wmemcpy(substitute_name_copy, rpdata.substitute_name,
998                         rpdata.substitute_name_nbytes / 2);
999                 rpdata.substitute_name = substitute_name_copy;
1000                 rpdata.print_name = substitute_name_copy;
1001                 rpdata.print_name_nbytes = rpdata.substitute_name_nbytes;
1002                 if (rp_status == RP_FIXED_FULLPATH) {
1003                         /* "full path", meaning \??\ prefixed.  We should not
1004                          * include this prefix in the print name, as it is
1005                          * apparently meant for the filesystem driver only. */
1006                         rpdata.print_name += 4;
1007                         rpdata.print_name_nbytes -= 8;
1008                 }
1009                 ret = make_reparse_buffer(&rpdata, rpbuf);
1010                 if (ret == 0)
1011                         ret = rp_status;
1012                 else
1013                         ret = -ret;
1014         } else {
1015                 if (rp_status == RP_EXCLUDED) {
1016                         size_t print_name_nchars = rpdata.print_name_nbytes / 2;
1017                         wchar_t print_name0[print_name_nchars + 1];
1018                         print_name0[print_name_nchars] = L'\0';
1019                         wmemcpy(print_name0, rpdata.print_name, print_name_nchars);
1020                         WARNING("Ignoring %ls pointing out of capture directory:\n"
1021                                 "          \"%ls\" -> \"%ls\"\n"
1022                                 "          (Use --norpfix to capture all symbolic links "
1023                                 "and junction points as-is)",
1024                                 (rpdata.rptag == WIM_IO_REPARSE_TAG_SYMLINK) ?
1025                                         L"absolute symbolic link" : L"junction point",
1026                                 path, print_name0);
1027                 }
1028                 ret = rp_status;
1029         }
1030         return ret;
1031 }
1032
1033 /*
1034  * Loads the reparse point data from a reparse point into memory, optionally
1035  * fixing the targets of absolute symbolic links and junction points to be
1036  * relative to the root of capture.
1037  *
1038  * @hFile:  Open handle to the reparse point.
1039  * @path:   Path to the reparse point.  Used for error messages only.
1040  * @params: Additional parameters, including whether to do reparse point fixups
1041  *          or not.
1042  * @rpbuf:  Buffer of length at least REPARSE_POINT_MAX_SIZE bytes into which
1043  *          the reparse point buffer will be loaded.
1044  * @rpbuflen_ret:  On success, the length of the reparse point buffer in bytes
1045  *                 is written to this location.
1046  *
1047  * Returns:
1048  *      On success, returns an `enum rp_status' value that indicates if and/or
1049  *      how the reparse point fixup was done.
1050  *
1051  *      On failure, returns a negative value that is a negated WIMLIB_ERR_*
1052  *      code.
1053  */
1054 static int
1055 win32_get_reparse_data(HANDLE hFile, const wchar_t *path,
1056                        struct add_image_params *params,
1057                        u8 *rpbuf, u16 *rpbuflen_ret)
1058 {
1059         DWORD bytesReturned;
1060         u32 reparse_tag;
1061         int ret;
1062         u16 rpbuflen;
1063
1064         DEBUG("Loading reparse data from \"%ls\"", path);
1065         if (!DeviceIoControl(hFile, FSCTL_GET_REPARSE_POINT,
1066                              NULL, /* "Not used with this operation; set to NULL" */
1067                              0, /* "Not used with this operation; set to 0" */
1068                              rpbuf, /* "A pointer to a buffer that
1069                                                    receives the reparse point data */
1070                              REPARSE_POINT_MAX_SIZE, /* "The size of the output
1071                                                         buffer, in bytes */
1072                              &bytesReturned,
1073                              NULL))
1074         {
1075                 DWORD err = GetLastError();
1076                 ERROR("Failed to get reparse data of \"%ls\"", path);
1077                 win32_error(err);
1078                 return -WIMLIB_ERR_READ;
1079         }
1080         if (bytesReturned < 8 || bytesReturned > REPARSE_POINT_MAX_SIZE) {
1081                 ERROR("Reparse data on \"%ls\" is invalid", path);
1082                 return -WIMLIB_ERR_INVALID_REPARSE_DATA;
1083         }
1084
1085         rpbuflen = bytesReturned;
1086         reparse_tag = le32_to_cpu(*(u32*)rpbuf);
1087         if (params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_RPFIX &&
1088             (reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
1089              reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT))
1090         {
1091                 /* Try doing reparse point fixup */
1092                 ret = win32_capture_try_rpfix(rpbuf,
1093                                               &rpbuflen,
1094                                               params->capture_root_ino,
1095                                               params->capture_root_dev,
1096                                               path);
1097         } else {
1098                 ret = RP_NOT_FIXED;
1099         }
1100         *rpbuflen_ret = rpbuflen;
1101         return ret;
1102 }
1103
1104 static DWORD WINAPI
1105 win32_tally_encrypted_size_cb(unsigned char *_data, void *_ctx,
1106                               unsigned long len)
1107 {
1108         *(u64*)_ctx += len;
1109         return ERROR_SUCCESS;
1110 }
1111
1112 static int
1113 win32_get_encrypted_file_size(const wchar_t *path, u64 *size_ret)
1114 {
1115         DWORD err;
1116         void *file_ctx;
1117         int ret;
1118
1119         *size_ret = 0;
1120         err = OpenEncryptedFileRawW(path, 0, &file_ctx);
1121         if (err != ERROR_SUCCESS) {
1122                 ERROR("Failed to open encrypted file \"%ls\" for raw read", path);
1123                 win32_error(err);
1124                 return WIMLIB_ERR_OPEN;
1125         }
1126         err = ReadEncryptedFileRaw(win32_tally_encrypted_size_cb,
1127                                    size_ret, file_ctx);
1128         if (err != ERROR_SUCCESS) {
1129                 ERROR("Failed to read raw encrypted data from \"%ls\"", path);
1130                 win32_error(err);
1131                 ret = WIMLIB_ERR_READ;
1132         } else {
1133                 ret = 0;
1134         }
1135         CloseEncryptedFileRaw(file_ctx);
1136         return ret;
1137 }
1138
1139 /* Scans an unnamed or named stream of a Win32 file (not a reparse point
1140  * stream); calculates its SHA1 message digest and either creates a `struct
1141  * wim_lookup_table_entry' in memory for it, or uses an existing 'struct
1142  * wim_lookup_table_entry' for an identical stream.
1143  *
1144  * @path:               Path to the file (UTF-16LE).
1145  *
1146  * @path_num_chars:     Number of 2-byte characters in @path.
1147  *
1148  * @inode:              WIM inode to save the stream into.
1149  *
1150  * @lookup_table:       Stream lookup table for the WIM.
1151  *
1152  * @dat:                A `WIN32_FIND_STREAM_DATA' structure that specifies the
1153  *                      stream name.
1154  *
1155  * Returns 0 on success; nonzero on failure.
1156  */
1157 static int
1158 win32_capture_stream(const wchar_t *path,
1159                      size_t path_num_chars,
1160                      struct wim_inode *inode,
1161                      struct wim_lookup_table *lookup_table,
1162                      WIN32_FIND_STREAM_DATA *dat)
1163 {
1164         struct wim_ads_entry *ads_entry;
1165         struct wim_lookup_table_entry *lte;
1166         int ret;
1167         wchar_t *stream_name, *colon;
1168         size_t stream_name_nchars;
1169         bool is_named_stream;
1170         wchar_t *spath;
1171         size_t spath_nchars;
1172         size_t spath_buf_nbytes;
1173         const wchar_t *relpath_prefix;
1174         const wchar_t *colonchar;
1175
1176         DEBUG("Capture \"%ls\" stream \"%ls\"", path, dat->cStreamName);
1177
1178         /* The stream name should be returned as :NAME:TYPE */
1179         stream_name = dat->cStreamName;
1180         if (*stream_name != L':')
1181                 goto out_invalid_stream_name;
1182         stream_name += 1;
1183         colon = wcschr(stream_name, L':');
1184         if (colon == NULL)
1185                 goto out_invalid_stream_name;
1186
1187         if (wcscmp(colon + 1, L"$DATA")) {
1188                 /* Not a DATA stream */
1189                 ret = 0;
1190                 goto out;
1191         }
1192
1193         *colon = '\0';
1194
1195         stream_name_nchars = colon - stream_name;
1196         is_named_stream = (stream_name_nchars != 0);
1197
1198         if (is_named_stream) {
1199                 /* Allocate an ADS entry for the named stream. */
1200                 ads_entry = inode_add_ads_utf16le(inode, stream_name,
1201                                                   stream_name_nchars * sizeof(wchar_t));
1202                 if (!ads_entry) {
1203                         ret = WIMLIB_ERR_NOMEM;
1204                         goto out;
1205                 }
1206         }
1207
1208         /* If zero length stream, no lookup table entry needed. */
1209         if ((u64)dat->StreamSize.QuadPart == 0) {
1210                 ret = 0;
1211                 goto out;
1212         }
1213
1214         /* Create a UTF-16LE string @spath that gives the filename, then a
1215          * colon, then the stream name.  Or, if it's an unnamed stream, just the
1216          * filename.  It is MALLOC()'ed so that it can be saved in the
1217          * wim_lookup_table_entry if needed.
1218          *
1219          * As yet another special case, relative paths need to be changed to
1220          * begin with an explicit "./" so that, for example, a file t:ads, where
1221          * :ads is the part we added, is not interpreted as a file on the t:
1222          * drive. */
1223         spath_nchars = path_num_chars;
1224         relpath_prefix = L"";
1225         colonchar = L"";
1226         if (is_named_stream) {
1227                 spath_nchars += 1 + stream_name_nchars;
1228                 colonchar = L":";
1229                 if (path_num_chars == 1 &&
1230                     path[0] != L'/' &&
1231                     path[0] != L'\\')
1232                 {
1233                         spath_nchars += 2;
1234                         relpath_prefix = L"./";
1235                 }
1236         }
1237
1238         spath_buf_nbytes = (spath_nchars + 1) * sizeof(wchar_t);
1239         spath = MALLOC(spath_buf_nbytes);
1240
1241         swprintf(spath, L"%ls%ls%ls%ls",
1242                  relpath_prefix, path, colonchar, stream_name);
1243
1244         /* Make a new wim_lookup_table_entry */
1245         lte = new_lookup_table_entry();
1246         if (!lte) {
1247                 ret = WIMLIB_ERR_NOMEM;
1248                 goto out_free_spath;
1249         }
1250         lte->file_on_disk = spath;
1251         spath = NULL;
1252         if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED && !is_named_stream) {
1253                 u64 encrypted_size;
1254                 lte->resource_location = RESOURCE_WIN32_ENCRYPTED;
1255                 ret = win32_get_encrypted_file_size(path, &encrypted_size);
1256                 if (ret)
1257                         goto out_free_spath;
1258                 lte->resource_entry.original_size = encrypted_size;
1259         } else {
1260                 lte->resource_location = RESOURCE_WIN32;
1261                 lte->resource_entry.original_size = (u64)dat->StreamSize.QuadPart;
1262         }
1263
1264         u32 stream_id;
1265         if (is_named_stream) {
1266                 stream_id = ads_entry->stream_id;
1267                 ads_entry->lte = lte;
1268         } else {
1269                 stream_id = 0;
1270                 inode->i_lte = lte;
1271         }
1272         lookup_table_insert_unhashed(lookup_table, lte, inode, stream_id);
1273         ret = 0;
1274 out_free_spath:
1275         FREE(spath);
1276 out:
1277         return ret;
1278 out_invalid_stream_name:
1279         ERROR("Invalid stream name: \"%ls:%ls\"", path, dat->cStreamName);
1280         ret = WIMLIB_ERR_READ;
1281         goto out;
1282 }
1283
1284 /* Scans a Win32 file for unnamed and named data streams (not reparse point
1285  * streams).
1286  *
1287  * @path:               Path to the file (UTF-16LE).
1288  *
1289  * @path_num_chars:     Number of 2-byte characters in @path.
1290  *
1291  * @inode:              WIM inode to save the stream into.
1292  *
1293  * @lookup_table:       Stream lookup table for the WIM.
1294  *
1295  * @file_size:          Size of unnamed data stream.  (Used only if alternate
1296  *                      data streams API appears to be unavailable.)
1297  *
1298  * @vol_flags:          Flags that specify features of the volume being
1299  *                      captured.
1300  *
1301  * Returns 0 on success; nonzero on failure.
1302  */
1303 static int
1304 win32_capture_streams(const wchar_t *path,
1305                       size_t path_num_chars,
1306                       struct wim_inode *inode,
1307                       struct wim_lookup_table *lookup_table,
1308                       u64 file_size,
1309                       unsigned vol_flags)
1310 {
1311         WIN32_FIND_STREAM_DATA dat;
1312         int ret;
1313         HANDLE hFind;
1314         DWORD err;
1315
1316         DEBUG("Capturing streams from \"%ls\"", path);
1317
1318         if (win32func_FindFirstStreamW == NULL ||
1319             !(vol_flags & FILE_NAMED_STREAMS))
1320                 goto unnamed_only;
1321
1322         hFind = win32func_FindFirstStreamW(path, FindStreamInfoStandard, &dat, 0);
1323         if (hFind == INVALID_HANDLE_VALUE) {
1324                 err = GetLastError();
1325                 if (err == ERROR_CALL_NOT_IMPLEMENTED)
1326                         goto unnamed_only;
1327
1328                 /* Seems legal for this to return ERROR_HANDLE_EOF on reparse
1329                  * points and directories */
1330                 if ((inode->i_attributes &
1331                     (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
1332                     && err == ERROR_HANDLE_EOF)
1333                 {
1334                         DEBUG("ERROR_HANDLE_EOF (ok)");
1335                         return 0;
1336                 } else {
1337                         if (err == ERROR_ACCESS_DENIED) {
1338                                 WARNING("Failed to look up data streams "
1339                                         "of \"%ls\": Access denied!\n%ls",
1340                                         path, capture_access_denied_msg);
1341                                 return 0;
1342                         } else {
1343                                 ERROR("Failed to look up data streams "
1344                                       "of \"%ls\"", path);
1345                                 win32_error(err);
1346                                 return WIMLIB_ERR_READ;
1347                         }
1348                 }
1349         }
1350         do {
1351                 ret = win32_capture_stream(path,
1352                                            path_num_chars,
1353                                            inode, lookup_table,
1354                                            &dat);
1355                 if (ret)
1356                         goto out_find_close;
1357         } while (win32func_FindNextStreamW(hFind, &dat));
1358         err = GetLastError();
1359         if (err != ERROR_HANDLE_EOF) {
1360                 ERROR("Win32 API: Error reading data streams from \"%ls\"", path);
1361                 win32_error(err);
1362                 ret = WIMLIB_ERR_READ;
1363         }
1364 out_find_close:
1365         FindClose(hFind);
1366         return ret;
1367 unnamed_only:
1368         /* FindFirstStreamW() API is not available, or the volume does not
1369          * support named streams.  Only capture the unnamed data stream. */
1370         DEBUG("Only capturing unnamed data stream");
1371         if (inode->i_attributes &
1372              (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
1373         {
1374                 ret = 0;
1375         } else {
1376                 /* Just create our own WIN32_FIND_STREAM_DATA for an unnamed
1377                  * stream to reduce the code to a call to the
1378                  * already-implemented win32_capture_stream() */
1379                 wcscpy(dat.cStreamName, L"::$DATA");
1380                 dat.StreamSize.QuadPart = file_size;
1381                 ret = win32_capture_stream(path,
1382                                            path_num_chars,
1383                                            inode, lookup_table,
1384                                            &dat);
1385         }
1386         return ret;
1387 }
1388
1389 static int
1390 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
1391                                   wchar_t *path,
1392                                   size_t path_num_chars,
1393                                   struct add_image_params *params,
1394                                   struct win32_capture_state *state,
1395                                   unsigned vol_flags)
1396 {
1397         struct wim_dentry *root = NULL;
1398         struct wim_inode *inode;
1399         DWORD err;
1400         u64 file_size;
1401         int ret;
1402         u8 *rpbuf;
1403         u16 rpbuflen;
1404         u16 not_rpfixed;
1405
1406         if (exclude_path(path, path_num_chars, params->config, true)) {
1407                 if (params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT) {
1408                         ERROR("Cannot exclude the root directory from capture");
1409                         ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
1410                         goto out;
1411                 }
1412                 if ((params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_EXCLUDE_VERBOSE)
1413                     && params->progress_func)
1414                 {
1415                         union wimlib_progress_info info;
1416                         info.scan.cur_path = path;
1417                         info.scan.excluded = true;
1418                         params->progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
1419                 }
1420                 ret = 0;
1421                 goto out;
1422         }
1423
1424         if ((params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
1425             && params->progress_func)
1426         {
1427                 union wimlib_progress_info info;
1428                 info.scan.cur_path = path;
1429                 info.scan.excluded = false;
1430                 params->progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
1431         }
1432
1433         HANDLE hFile = win32_open_existing_file(path,
1434                                                 FILE_READ_DATA | FILE_READ_ATTRIBUTES);
1435         if (hFile == INVALID_HANDLE_VALUE) {
1436                 err = GetLastError();
1437                 ERROR("Win32 API: Failed to open \"%ls\"", path);
1438                 win32_error(err);
1439                 ret = WIMLIB_ERR_OPEN;
1440                 goto out;
1441         }
1442
1443         BY_HANDLE_FILE_INFORMATION file_info;
1444         if (!GetFileInformationByHandle(hFile, &file_info)) {
1445                 err = GetLastError();
1446                 ERROR("Win32 API: Failed to get file information for \"%ls\"",
1447                       path);
1448                 win32_error(err);
1449                 ret = WIMLIB_ERR_STAT;
1450                 goto out_close_handle;
1451         }
1452
1453         if (file_info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1454                 rpbuf = alloca(REPARSE_POINT_MAX_SIZE);
1455                 ret = win32_get_reparse_data(hFile, path, params,
1456                                              rpbuf, &rpbuflen);
1457                 if (ret < 0) {
1458                         /* WIMLIB_ERR_* (inverted) */
1459                         ret = -ret;
1460                         goto out_close_handle;
1461                 } else if (ret & RP_FIXED) {
1462                         not_rpfixed = 0;
1463                 } else if (ret == RP_EXCLUDED) {
1464                         ret = 0;
1465                         goto out_close_handle;
1466                 } else {
1467                         not_rpfixed = 1;
1468                 }
1469         }
1470
1471         /* Create a WIM dentry with an associated inode, which may be shared.
1472          *
1473          * However, we need to explicitly check for directories and files with
1474          * only 1 link and refuse to hard link them.  This is because Windows
1475          * has a bug where it can return duplicate File IDs for files and
1476          * directories on the FAT filesystem. */
1477         ret = inode_table_new_dentry(params->inode_table,
1478                                      path_basename_with_len(path, path_num_chars),
1479                                      ((u64)file_info.nFileIndexHigh << 32) |
1480                                          (u64)file_info.nFileIndexLow,
1481                                      file_info.dwVolumeSerialNumber,
1482                                      (file_info.nNumberOfLinks <= 1 ||
1483                                         (file_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)),
1484                                      &root);
1485         if (ret)
1486                 goto out_close_handle;
1487
1488         ret = win32_get_short_name(root, path);
1489         if (ret)
1490                 goto out_close_handle;
1491
1492         inode = root->d_inode;
1493
1494         if (inode->i_nlink > 1) /* Shared inode; nothing more to do */
1495                 goto out_close_handle;
1496
1497         inode->i_attributes = file_info.dwFileAttributes;
1498         inode->i_creation_time = FILETIME_to_u64(&file_info.ftCreationTime);
1499         inode->i_last_write_time = FILETIME_to_u64(&file_info.ftLastWriteTime);
1500         inode->i_last_access_time = FILETIME_to_u64(&file_info.ftLastAccessTime);
1501         inode->i_resolved = 1;
1502
1503         params->add_image_flags &= ~(WIMLIB_ADD_IMAGE_FLAG_ROOT | WIMLIB_ADD_IMAGE_FLAG_SOURCE);
1504
1505         if (!(params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NO_ACLS)
1506             && (vol_flags & FILE_PERSISTENT_ACLS))
1507         {
1508                 ret = win32_get_security_descriptor(root, params->sd_set,
1509                                                     path, state,
1510                                                     params->add_image_flags);
1511                 if (ret)
1512                         goto out_close_handle;
1513         }
1514
1515         file_size = ((u64)file_info.nFileSizeHigh << 32) |
1516                      (u64)file_info.nFileSizeLow;
1517
1518         CloseHandle(hFile);
1519
1520         /* Capture the unnamed data stream (only should be present for regular
1521          * files) and any alternate data streams. */
1522         ret = win32_capture_streams(path,
1523                                     path_num_chars,
1524                                     inode,
1525                                     params->lookup_table,
1526                                     file_size,
1527                                     vol_flags);
1528         if (ret)
1529                 goto out;
1530
1531         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1532                 /* Reparse point: set the reparse data (which we read already)
1533                  * */
1534                 inode->i_not_rpfixed = not_rpfixed;
1535                 inode->i_reparse_tag = le32_to_cpu(*(u32*)rpbuf);
1536                 ret = inode_set_unnamed_stream(inode, rpbuf + 8, rpbuflen - 8,
1537                                                params->lookup_table);
1538         } else if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1539                 /* Directory (not a reparse point) --- recurse to children */
1540                 ret = win32_recurse_directory(root,
1541                                               path,
1542                                               path_num_chars,
1543                                               params,
1544                                               state,
1545                                               vol_flags);
1546         }
1547         goto out;
1548 out_close_handle:
1549         CloseHandle(hFile);
1550 out:
1551         if (ret == 0)
1552                 *root_ret = root;
1553         else
1554                 free_dentry_tree(root, params->lookup_table);
1555         return ret;
1556 }
1557
1558 static void
1559 win32_do_capture_warnings(const struct win32_capture_state *state,
1560                           int add_image_flags)
1561 {
1562         if (state->num_get_sacl_priv_notheld == 0 &&
1563             state->num_get_sd_access_denied == 0)
1564                 return;
1565
1566         WARNING("");
1567         WARNING("Built dentry tree successfully, but with the following problem(s):");
1568         if (state->num_get_sacl_priv_notheld != 0) {
1569                 WARNING("Could not capture SACL (System Access Control List)\n"
1570                         "          on %lu files or directories.",
1571                         state->num_get_sacl_priv_notheld);
1572         }
1573         if (state->num_get_sd_access_denied != 0) {
1574                 WARNING("Could not capture security descriptor at all\n"
1575                         "          on %lu files or directories.",
1576                         state->num_get_sd_access_denied);
1577         }
1578         WARNING(
1579           "Try running the program as the Administrator to make sure all the\n"
1580 "          desired metadata has been captured exactly.  However, if you\n"
1581 "          do not care about capturing security descriptors correctly, then\n"
1582 "          nothing more needs to be done%ls\n",
1583         (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NO_ACLS) ? L"." :
1584          L", although you might consider\n"
1585 "          passing the --no-acls flag to `wimlib-imagex capture' or\n"
1586 "          `wimlib-imagex append' to explicitly capture no security\n"
1587 "          descriptors.\n");
1588 }
1589
1590 /* Win32 version of capturing a directory tree */
1591 int
1592 win32_build_dentry_tree(struct wim_dentry **root_ret,
1593                         const wchar_t *root_disk_path,
1594                         struct add_image_params *params)
1595 {
1596         size_t path_nchars;
1597         wchar_t *path;
1598         int ret;
1599         struct win32_capture_state state;
1600         unsigned vol_flags;
1601
1602
1603         path_nchars = wcslen(root_disk_path);
1604         if (path_nchars > 32767)
1605                 return WIMLIB_ERR_INVALID_PARAM;
1606
1607         if (GetFileAttributesW(root_disk_path) == INVALID_FILE_ATTRIBUTES &&
1608             GetLastError() == ERROR_FILE_NOT_FOUND)
1609         {
1610                 ERROR("Capture directory \"%ls\" does not exist!",
1611                       root_disk_path);
1612                 return WIMLIB_ERR_OPENDIR;
1613         }
1614
1615         ret = win32_get_file_and_vol_ids(root_disk_path,
1616                                          &params->capture_root_ino,
1617                                          &params->capture_root_dev);
1618         if (ret)
1619                 return ret;
1620
1621         win32_get_vol_flags(root_disk_path, &vol_flags);
1622
1623         /* There is no check for overflow later when this buffer is being used!
1624          * But the max path length on NTFS is 32767 characters, and paths need
1625          * to be written specially to even go past 260 characters, so we should
1626          * be okay with 32770 characters. */
1627         path = MALLOC(32770 * sizeof(wchar_t));
1628         if (!path)
1629                 return WIMLIB_ERR_NOMEM;
1630
1631         wmemcpy(path, root_disk_path, path_nchars + 1);
1632
1633         memset(&state, 0, sizeof(state));
1634         ret = win32_build_dentry_tree_recursive(root_ret, path,
1635                                                 path_nchars, params,
1636                                                 &state, vol_flags);
1637         FREE(path);
1638         if (ret == 0)
1639                 win32_do_capture_warnings(&state, params->add_image_flags);
1640         return ret;
1641 }
1642
1643 static int
1644 win32_extract_try_rpfix(u8 *rpbuf,
1645                         const wchar_t *extract_root_realpath,
1646                         unsigned extract_root_realpath_nchars)
1647 {
1648         struct reparse_data rpdata;
1649         wchar_t *target;
1650         size_t target_nchars;
1651         size_t stripped_nchars;
1652         wchar_t *stripped_target;
1653         wchar_t stripped_target_nchars;
1654         int ret;
1655
1656         utf16lechar *new_target;
1657         utf16lechar *new_print_name;
1658         size_t new_target_nchars;
1659         size_t new_print_name_nchars;
1660         utf16lechar *p;
1661
1662         ret = parse_reparse_data(rpbuf, 8 + le16_to_cpu(*(u16*)(rpbuf + 4)),
1663                                  &rpdata);
1664         if (ret)
1665                 return ret;
1666
1667         if (extract_root_realpath[0] == L'\0' ||
1668             extract_root_realpath[1] != L':' ||
1669             extract_root_realpath[2] != L'\\')
1670         {
1671                 ERROR("Can't understand full path format \"%ls\".  "
1672                       "Try turning reparse point fixups off...",
1673                       extract_root_realpath);
1674                 return WIMLIB_ERR_REPARSE_POINT_FIXUP_FAILED;
1675         }
1676
1677         ret = parse_substitute_name(rpdata.substitute_name,
1678                                     rpdata.substitute_name_nbytes,
1679                                     rpdata.rptag);
1680         if (ret < 0)
1681                 return 0;
1682         stripped_nchars = ret;
1683         target = rpdata.substitute_name;
1684         target_nchars = rpdata.substitute_name_nbytes / sizeof(utf16lechar);
1685         stripped_target = target + 6;
1686         stripped_target_nchars = target_nchars - stripped_nchars;
1687
1688         new_target = alloca((6 + extract_root_realpath_nchars +
1689                              stripped_target_nchars) * sizeof(utf16lechar));
1690
1691         p = new_target;
1692         if (stripped_nchars == 6) {
1693                 /* Include \??\ prefix if it was present before */
1694                 wmemcpy(p, L"\\??\\", 4);
1695                 p += 4;
1696         }
1697
1698         /* Print name excludes the \??\ if present. */
1699         new_print_name = p;
1700         if (stripped_nchars != 0) {
1701                 /* Get drive letter from real path to extract root, if a drive
1702                  * letter was present before. */
1703                 *p++ = extract_root_realpath[0];
1704                 *p++ = extract_root_realpath[1];
1705         }
1706         /* Copy the rest of the extract root */
1707         wmemcpy(p, extract_root_realpath + 2, extract_root_realpath_nchars - 2);
1708         p += extract_root_realpath_nchars - 2;
1709
1710         /* Append the stripped target */
1711         wmemcpy(p, stripped_target, stripped_target_nchars);
1712         p += stripped_target_nchars;
1713         new_target_nchars = p - new_target;
1714         new_print_name_nchars = p - new_print_name;
1715
1716         if (new_target_nchars * sizeof(utf16lechar) >= REPARSE_POINT_MAX_SIZE ||
1717             new_print_name_nchars * sizeof(utf16lechar) >= REPARSE_POINT_MAX_SIZE)
1718         {
1719                 ERROR("Path names too long to do reparse point fixup!");
1720                 return WIMLIB_ERR_REPARSE_POINT_FIXUP_FAILED;
1721         }
1722         rpdata.substitute_name = new_target;
1723         rpdata.substitute_name_nbytes = new_target_nchars * sizeof(utf16lechar);
1724         rpdata.print_name = new_print_name;
1725         rpdata.print_name_nbytes = new_print_name_nchars * sizeof(utf16lechar);
1726         return make_reparse_buffer(&rpdata, rpbuf);
1727 }
1728
1729 /* Wrapper around the FSCTL_SET_REPARSE_POINT ioctl to set the reparse data on
1730  * an extracted reparse point. */
1731 static int
1732 win32_set_reparse_data(HANDLE h,
1733                        const struct wim_inode *inode,
1734                        const struct wim_lookup_table_entry *lte,
1735                        const wchar_t *path,
1736                        const struct apply_args *args)
1737 {
1738         int ret;
1739         u8 rpbuf[REPARSE_POINT_MAX_SIZE];
1740         DWORD bytesReturned;
1741
1742         DEBUG("Setting reparse data on \"%ls\"", path);
1743
1744         ret = wim_inode_get_reparse_data(inode, rpbuf);
1745         if (ret)
1746                 return ret;
1747
1748         if (args->extract_flags & WIMLIB_EXTRACT_FLAG_RPFIX &&
1749             (inode->i_reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
1750              inode->i_reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT) &&
1751             !inode->i_not_rpfixed)
1752         {
1753                 ret = win32_extract_try_rpfix(rpbuf,
1754                                               args->target_realpath,
1755                                               args->target_realpath_len);
1756                 if (ret)
1757                         return WIMLIB_ERR_REPARSE_POINT_FIXUP_FAILED;
1758         }
1759
1760         /* Set the reparse data on the open file using the
1761          * FSCTL_SET_REPARSE_POINT ioctl.
1762          *
1763          * There are contradictions in Microsoft's documentation for this:
1764          *
1765          * "If hDevice was opened without specifying FILE_FLAG_OVERLAPPED,
1766          * lpOverlapped is ignored."
1767          *
1768          * --- So setting lpOverlapped to NULL is okay since it's ignored.
1769          *
1770          * "If lpOverlapped is NULL, lpBytesReturned cannot be NULL. Even when an
1771          * operation returns no output data and lpOutBuffer is NULL,
1772          * DeviceIoControl makes use of lpBytesReturned. After such an
1773          * operation, the value of lpBytesReturned is meaningless."
1774          *
1775          * --- So lpOverlapped not really ignored, as it affects another
1776          *  parameter.  This is the actual behavior: lpBytesReturned must be
1777          *  specified, even though lpBytesReturned is documented as:
1778          *
1779          *  "Not used with this operation; set to NULL."
1780          */
1781         if (!DeviceIoControl(h, FSCTL_SET_REPARSE_POINT, rpbuf,
1782                              8 + le16_to_cpu(*(u16*)(rpbuf + 4)),
1783                              NULL, 0,
1784                              &bytesReturned /* lpBytesReturned */,
1785                              NULL /* lpOverlapped */))
1786         {
1787                 DWORD err = GetLastError();
1788                 ERROR("Failed to set reparse data on \"%ls\"", path);
1789                 win32_error(err);
1790                 if (err == ERROR_ACCESS_DENIED || err == ERROR_PRIVILEGE_NOT_HELD)
1791                         return WIMLIB_ERR_INSUFFICIENT_PRIVILEGES_TO_EXTRACT;
1792                 else if (inode->i_reparse_tag == WIM_IO_REPARSE_TAG_SYMLINK ||
1793                          inode->i_reparse_tag == WIM_IO_REPARSE_TAG_MOUNT_POINT)
1794                         return WIMLIB_ERR_LINK;
1795                 else
1796                         return WIMLIB_ERR_WRITE;
1797         }
1798         return 0;
1799 }
1800
1801 /* Wrapper around the FSCTL_SET_COMPRESSION ioctl to change the
1802  * FILE_ATTRIBUTE_COMPRESSED flag of a file or directory. */
1803 static int
1804 win32_set_compression_state(HANDLE hFile, USHORT format, const wchar_t *path)
1805 {
1806         DWORD bytesReturned;
1807         if (!DeviceIoControl(hFile, FSCTL_SET_COMPRESSION,
1808                              &format, sizeof(USHORT),
1809                              NULL, 0,
1810                              &bytesReturned, NULL))
1811         {
1812                 /* Could be a warning only, but we only call this if the volume
1813                  * supports compression.  So I'm calling this an error. */
1814                 DWORD err = GetLastError();
1815                 ERROR("Failed to set compression flag on \"%ls\"", path);
1816                 win32_error(err);
1817                 if (err == ERROR_ACCESS_DENIED || err == ERROR_PRIVILEGE_NOT_HELD)
1818                         return WIMLIB_ERR_INSUFFICIENT_PRIVILEGES_TO_EXTRACT;
1819                 else
1820                         return WIMLIB_ERR_WRITE;
1821         }
1822         return 0;
1823 }
1824
1825 /* Wrapper around FSCTL_SET_SPARSE ioctl to set a file as sparse. */
1826 static int
1827 win32_set_sparse(HANDLE hFile, const wchar_t *path)
1828 {
1829         DWORD bytesReturned;
1830         if (!DeviceIoControl(hFile, FSCTL_SET_SPARSE,
1831                              NULL, 0,
1832                              NULL, 0,
1833                              &bytesReturned, NULL))
1834         {
1835                 /* Could be a warning only, but we only call this if the volume
1836                  * supports sparse files.  So I'm calling this an error. */
1837                 DWORD err = GetLastError();
1838                 WARNING("Failed to set sparse flag on \"%ls\"", path);
1839                 win32_error(err);
1840                 if (err == ERROR_ACCESS_DENIED || err == ERROR_PRIVILEGE_NOT_HELD)
1841                         return WIMLIB_ERR_INSUFFICIENT_PRIVILEGES_TO_EXTRACT;
1842                 else
1843                         return WIMLIB_ERR_WRITE;
1844         }
1845         return 0;
1846 }
1847
1848 /*
1849  * Sets the security descriptor on an extracted file.
1850  */
1851 static int
1852 win32_set_security_data(const struct wim_inode *inode,
1853                         HANDLE hFile,
1854                         const wchar_t *path,
1855                         struct apply_args *args)
1856 {
1857         PSECURITY_DESCRIPTOR descriptor;
1858         unsigned long n;
1859         DWORD err;
1860         const struct wim_security_data *sd;
1861
1862         SECURITY_INFORMATION securityInformation = 0;
1863
1864         void *owner = NULL;
1865         void *group = NULL;
1866         ACL *dacl = NULL;
1867         ACL *sacl = NULL;
1868
1869         BOOL owner_defaulted;
1870         BOOL group_defaulted;
1871         BOOL dacl_present;
1872         BOOL dacl_defaulted;
1873         BOOL sacl_present;
1874         BOOL sacl_defaulted;
1875
1876         sd = wim_const_security_data(args->w);
1877         descriptor = sd->descriptors[inode->i_security_id];
1878
1879         GetSecurityDescriptorOwner(descriptor, &owner, &owner_defaulted);
1880         if (owner)
1881                 securityInformation |= OWNER_SECURITY_INFORMATION;
1882
1883         GetSecurityDescriptorGroup(descriptor, &group, &group_defaulted);
1884         if (group)
1885                 securityInformation |= GROUP_SECURITY_INFORMATION;
1886
1887         GetSecurityDescriptorDacl(descriptor, &dacl_present,
1888                                   &dacl, &dacl_defaulted);
1889         if (dacl)
1890                 securityInformation |= DACL_SECURITY_INFORMATION;
1891
1892         GetSecurityDescriptorSacl(descriptor, &sacl_present,
1893                                   &sacl, &sacl_defaulted);
1894         if (sacl)
1895                 securityInformation |= SACL_SECURITY_INFORMATION;
1896
1897 again:
1898         if (securityInformation == 0)
1899                 return 0;
1900         if (SetSecurityInfo(hFile, SE_FILE_OBJECT,
1901                             securityInformation, owner, group, dacl, sacl))
1902                 return 0;
1903         err = GetLastError();
1904         if (args->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS)
1905                 goto fail;
1906         switch (err) {
1907         case ERROR_PRIVILEGE_NOT_HELD:
1908                 if (securityInformation & SACL_SECURITY_INFORMATION) {
1909                         n = args->num_set_sacl_priv_notheld++;
1910                         securityInformation &= ~SACL_SECURITY_INFORMATION;
1911                         sacl = NULL;
1912                         if (n < MAX_SET_SACL_PRIV_NOTHELD_WARNINGS) {
1913                                 WARNING(
1914 "We don't have enough privileges to set the full security\n"
1915 "          descriptor on \"%ls\"!\n", path);
1916                                 if (args->num_set_sd_access_denied +
1917                                     args->num_set_sacl_priv_notheld == 1)
1918                                 {
1919                                         WARNING("%ls", apply_access_denied_msg);
1920                                 }
1921                                 WARNING("Re-trying with SACL omitted.\n", path);
1922                         } else if (n == MAX_GET_SACL_PRIV_NOTHELD_WARNINGS) {
1923                                 WARNING(
1924 "Suppressing further 'privileges not held' error messages when setting\n"
1925 "          security descriptors.");
1926                         }
1927                         goto again;
1928                 }
1929                 /* Fall through */
1930         case ERROR_INVALID_OWNER:
1931         case ERROR_ACCESS_DENIED:
1932                 n = args->num_set_sd_access_denied++;
1933                 if (n < MAX_SET_SD_ACCESS_DENIED_WARNINGS) {
1934                         WARNING("Failed to set security descriptor on \"%ls\": "
1935                                 "Access denied!\n", path);
1936                         if (args->num_set_sd_access_denied +
1937                             args->num_set_sacl_priv_notheld == 1)
1938                         {
1939                                 WARNING("%ls", apply_access_denied_msg);
1940                         }
1941                 } else if (n == MAX_SET_SD_ACCESS_DENIED_WARNINGS) {
1942                         WARNING(
1943 "Suppressing further access denied error messages when setting\n"
1944 "          security descriptors");
1945                 }
1946                 return 0;
1947         default:
1948 fail:
1949                 ERROR("Failed to set security descriptor on \"%ls\"", path);
1950                 win32_error(err);
1951                 if (err == ERROR_ACCESS_DENIED || err == ERROR_PRIVILEGE_NOT_HELD)
1952                         return WIMLIB_ERR_INSUFFICIENT_PRIVILEGES_TO_EXTRACT;
1953                 else
1954                         return WIMLIB_ERR_WRITE;
1955         }
1956 }
1957
1958
1959 static int
1960 win32_extract_chunk(const void *buf, size_t len, void *arg)
1961 {
1962         HANDLE hStream = arg;
1963
1964         DWORD nbytes_written;
1965         wimlib_assert(len <= 0xffffffff);
1966
1967         if (!WriteFile(hStream, buf, len, &nbytes_written, NULL) ||
1968             nbytes_written != len)
1969         {
1970                 DWORD err = GetLastError();
1971                 ERROR("WriteFile(): write error");
1972                 win32_error(err);
1973                 return WIMLIB_ERR_WRITE;
1974         }
1975         return 0;
1976 }
1977
1978 static int
1979 do_win32_extract_stream(HANDLE hStream, const struct wim_lookup_table_entry *lte)
1980 {
1981         return extract_wim_resource(lte, wim_resource_size(lte),
1982                                     win32_extract_chunk, hStream);
1983 }
1984
1985 struct win32_encrypted_extract_ctx {
1986         const struct wim_lookup_table_entry *lte;
1987         u64 offset;
1988 };
1989
1990 static DWORD WINAPI
1991 win32_encrypted_import_cb(unsigned char *data, void *_ctx,
1992                           unsigned long *len_p)
1993 {
1994         struct win32_encrypted_extract_ctx *ctx = _ctx;
1995         unsigned long len = *len_p;
1996         const struct wim_lookup_table_entry *lte = ctx->lte;
1997
1998         len = min(len, wim_resource_size(lte) - ctx->offset);
1999
2000         if (read_partial_wim_resource_into_buf(lte, len, ctx->offset, data))
2001                 return ERROR_READ_FAULT;
2002
2003         ctx->offset += len;
2004         *len_p = len;
2005         return ERROR_SUCCESS;
2006 }
2007
2008 /* Create an encrypted file and extract the raw encrypted data to it.
2009  *
2010  * @path:  Path to encrypted file to create.
2011  * @lte:   WIM lookup_table entry for the raw encrypted data.
2012  *
2013  * This is separate from do_win32_extract_stream() because the WIM is supposed
2014  * to contain the *raw* encrypted data, which needs to be extracted ("imported")
2015  * using the special APIs OpenEncryptedFileRawW(), WriteEncryptedFileRaw(), and
2016  * CloseEncryptedFileRaw().
2017  *
2018  * Returns 0 on success; nonzero on failure.
2019  */
2020 static int
2021 do_win32_extract_encrypted_stream(const wchar_t *path,
2022                                   const struct wim_lookup_table_entry *lte)
2023 {
2024         void *file_ctx;
2025         int ret;
2026
2027         DEBUG("Opening file \"%ls\" to extract raw encrypted data", path);
2028
2029         ret = OpenEncryptedFileRawW(path, CREATE_FOR_IMPORT, &file_ctx);
2030         if (ret) {
2031                 ERROR("Failed to open \"%ls\" to write raw encrypted data", path);
2032                 win32_error(ret);
2033                 return WIMLIB_ERR_OPEN;
2034         }
2035
2036         if (lte) {
2037                 struct win32_encrypted_extract_ctx ctx;
2038
2039                 ctx.lte = lte;
2040                 ctx.offset = 0;
2041                 ret = WriteEncryptedFileRaw(win32_encrypted_import_cb, &ctx, file_ctx);
2042                 if (ret == ERROR_SUCCESS) {
2043                         ret = 0;
2044                 } else {
2045                         ret = WIMLIB_ERR_WRITE;
2046                         ERROR("Failed to extract encrypted file \"%ls\"", path);
2047                 }
2048         }
2049         CloseEncryptedFileRaw(file_ctx);
2050         return ret;
2051 }
2052
2053 static bool
2054 path_is_root_of_drive(const wchar_t *path)
2055 {
2056         if (!*path)
2057                 return false;
2058
2059         if (*path != L'/' && *path != L'\\') {
2060                 if (*(path + 1) == L':')
2061                         path += 2;
2062                 else
2063                         return false;
2064         }
2065         while (*path == L'/' || *path == L'\\')
2066                 path++;
2067         return (*path == L'\0');
2068 }
2069
2070 static inline DWORD
2071 win32_mask_attributes(DWORD i_attributes)
2072 {
2073         return i_attributes & ~(FILE_ATTRIBUTE_SPARSE_FILE |
2074                                 FILE_ATTRIBUTE_COMPRESSED |
2075                                 FILE_ATTRIBUTE_REPARSE_POINT |
2076                                 FILE_ATTRIBUTE_DIRECTORY |
2077                                 FILE_ATTRIBUTE_ENCRYPTED |
2078                                 FILE_FLAG_DELETE_ON_CLOSE |
2079                                 FILE_FLAG_NO_BUFFERING |
2080                                 FILE_FLAG_OPEN_NO_RECALL |
2081                                 FILE_FLAG_OVERLAPPED |
2082                                 FILE_FLAG_RANDOM_ACCESS |
2083                                 /*FILE_FLAG_SESSION_AWARE |*/
2084                                 FILE_FLAG_SEQUENTIAL_SCAN |
2085                                 FILE_FLAG_WRITE_THROUGH);
2086 }
2087
2088 static inline DWORD
2089 win32_get_create_flags_and_attributes(DWORD i_attributes)
2090 {
2091         /*
2092          * Some attributes cannot be set by passing them to CreateFile().  In
2093          * particular:
2094          *
2095          * FILE_ATTRIBUTE_DIRECTORY:
2096          *   CreateDirectory() must be called instead of CreateFile().
2097          *
2098          * FILE_ATTRIBUTE_SPARSE_FILE:
2099          *   Needs an ioctl.
2100          *   See: win32_set_sparse().
2101          *
2102          * FILE_ATTRIBUTE_COMPRESSED:
2103          *   Not clear from the documentation, but apparently this needs an
2104          *   ioctl as well.
2105          *   See: win32_set_compressed().
2106          *
2107          * FILE_ATTRIBUTE_REPARSE_POINT:
2108          *   Needs an ioctl, with the reparse data specified.
2109          *   See: win32_set_reparse_data().
2110          *
2111          * In addition, clear any file flags in the attributes that we don't
2112          * want, but also specify FILE_FLAG_OPEN_REPARSE_POINT and
2113          * FILE_FLAG_BACKUP_SEMANTICS as we are a backup application.
2114          */
2115         return win32_mask_attributes(i_attributes) |
2116                 FILE_FLAG_OPEN_REPARSE_POINT |
2117                 FILE_FLAG_BACKUP_SEMANTICS;
2118 }
2119
2120 /* Set compression and/or sparse attributes on a stream, if supported by the
2121  * volume. */
2122 static int
2123 win32_set_special_stream_attributes(HANDLE hFile, const struct wim_inode *inode,
2124                                     struct wim_lookup_table_entry *unnamed_stream_lte,
2125                                     const wchar_t *path, unsigned vol_flags)
2126 {
2127         int ret;
2128
2129         if (inode->i_attributes & FILE_ATTRIBUTE_COMPRESSED) {
2130                 if (vol_flags & FILE_FILE_COMPRESSION) {
2131                         ret = win32_set_compression_state(hFile,
2132                                                           COMPRESSION_FORMAT_DEFAULT,
2133                                                           path);
2134                         if (ret)
2135                                 return ret;
2136                 } else {
2137                         DEBUG("Cannot set compression attribute on \"%ls\": "
2138                               "volume does not support transparent compression",
2139                               path);
2140                 }
2141         }
2142
2143         if (inode->i_attributes & FILE_ATTRIBUTE_SPARSE_FILE) {
2144                 if (vol_flags & FILE_SUPPORTS_SPARSE_FILES) {
2145                         DEBUG("Setting sparse flag on \"%ls\"", path);
2146                         ret = win32_set_sparse(hFile, path);
2147                         if (ret)
2148                                 return ret;
2149                 } else {
2150                         DEBUG("Cannot set sparse attribute on \"%ls\": "
2151                               "volume does not support sparse files",
2152                               path);
2153                 }
2154         }
2155         return 0;
2156 }
2157
2158 /* Pre-create directories; extract encrypted streams */
2159 static int
2160 win32_begin_extract_unnamed_stream(const struct wim_inode *inode,
2161                                    const struct wim_lookup_table_entry *lte,
2162                                    const wchar_t *path,
2163                                    DWORD *creationDisposition_ret,
2164                                    unsigned int vol_flags)
2165 {
2166         DWORD err;
2167         int ret;
2168
2169         /* Directories must be created with CreateDirectoryW().  Then the call
2170          * to CreateFileW() will merely open the directory that was already
2171          * created rather than creating a new file. */
2172         if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY &&
2173             !path_is_root_of_drive(path)) {
2174                 if (!CreateDirectoryW(path, NULL)) {
2175                         err = GetLastError();
2176                         if (err != ERROR_ALREADY_EXISTS) {
2177                                 ERROR("Failed to create directory \"%ls\"",
2178                                       path);
2179                                 win32_error(err);
2180                                 return WIMLIB_ERR_MKDIR;
2181                         }
2182                 }
2183                 DEBUG("Created directory \"%ls\"", path);
2184                 *creationDisposition_ret = OPEN_EXISTING;
2185         }
2186         if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED &&
2187             vol_flags & FILE_SUPPORTS_ENCRYPTION)
2188         {
2189                 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
2190                         unsigned remaining_sharing_violations = 100;
2191                         while (!EncryptFile(path)) {
2192                                 if (remaining_sharing_violations &&
2193                                     err == ERROR_SHARING_VIOLATION)
2194                                 {
2195                                         WARNING("Couldn't encrypt directory \"%ls\" "
2196                                                 "due to sharing violation; re-trying "
2197                                                 "after 100 ms", path);
2198                                         Sleep(100);
2199                                         remaining_sharing_violations--;
2200                                 } else {
2201                                         err = GetLastError();
2202                                         ERROR("Failed to encrypt directory \"%ls\"",
2203                                               path);
2204                                         win32_error(err);
2205                                         return WIMLIB_ERR_WRITE;
2206                                 }
2207                         }
2208                 } else {
2209                         ret = do_win32_extract_encrypted_stream(path, lte);
2210                         if (ret)
2211                                 return ret;
2212                         DEBUG("Extracted encrypted file \"%ls\"", path);
2213                 }
2214                 *creationDisposition_ret = OPEN_EXISTING;
2215         }
2216
2217         /* Set file attributes if we created the file.  Otherwise, we haven't
2218          * created the file set and we will set the attributes in the call to
2219          * CreateFileW().
2220          *
2221          * The FAT filesystem does not let you change the attributes of the root
2222          * directory, so treat that as a special case and do not set attributes.
2223          * */
2224         if (*creationDisposition_ret == OPEN_EXISTING &&
2225             !path_is_root_of_drive(path))
2226         {
2227                 if (!SetFileAttributesW(path,
2228                                         win32_mask_attributes(inode->i_attributes)))
2229                 {
2230                         err = GetLastError();
2231                         ERROR("Failed to set attributes on \"%ls\"", path);
2232                         win32_error(err);
2233                         return WIMLIB_ERR_WRITE;
2234                 }
2235         }
2236         return 0;
2237 }
2238
2239 /* Set security descriptor and extract stream data or reparse data (skip the
2240  * unnamed data stream of encrypted files, which was already extracted). */
2241 static int
2242 win32_finish_extract_stream(HANDLE h, const struct wim_dentry *dentry,
2243                             const struct wim_lookup_table_entry *lte,
2244                             const wchar_t *stream_path,
2245                             const wchar_t *stream_name_utf16,
2246                             struct apply_args *args)
2247 {
2248         int ret = 0;
2249         const struct wim_inode *inode = dentry->d_inode;
2250         const wchar_t *short_name;
2251         if (stream_name_utf16 == NULL) {
2252                 /* Unnamed stream. */
2253
2254                 /* Set security descriptor, unless the extract_flags indicate
2255                  * not to or the volume does not supported it.  Note that this
2256                  * is only done when the unnamed stream is being extracted, as
2257                  * security descriptors are per-file and not per-stream. */
2258                 if (inode->i_security_id >= 0 &&
2259                     !(args->extract_flags & WIMLIB_EXTRACT_FLAG_NO_ACLS)
2260                     && (args->vol_flags & FILE_PERSISTENT_ACLS))
2261                 {
2262                         ret = win32_set_security_data(inode, h, stream_path, args);
2263                         if (ret)
2264                                 return ret;
2265                 }
2266
2267                 /* Handle reparse points.  The data for them needs to be set
2268                  * using a special ioctl.  Note that the reparse point may have
2269                  * been created using CreateFileW() in the case of
2270                  * non-directories or CreateDirectoryW() in the case of
2271                  * directories; but the ioctl works either way.  Also, it is
2272                  * only this step that actually sets the
2273                  * FILE_ATTRIBUTE_REPARSE_POINT, as it is not valid to set it
2274                  * using SetFileAttributesW() or CreateFileW().
2275                  *
2276                  * If the volume does not support reparse points we simply
2277                  * ignore the reparse data.  (N.B. the code currently doesn't
2278                  * actually reach this case because reparse points are skipped
2279                  * entirely on such volumes.) */
2280                 if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
2281                         if (args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS) {
2282                                 ret = win32_set_reparse_data(h, inode,
2283                                                              lte, stream_path,
2284                                                              args);
2285                                 if (ret)
2286                                         return ret;
2287                         } else {
2288                                 DEBUG("Cannot set reparse data on \"%ls\": volume "
2289                                       "does not support reparse points", stream_path);
2290                         }
2291                 } else if (lte != NULL &&
2292                            !(args->vol_flags & FILE_SUPPORTS_ENCRYPTION &&
2293                              inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED))
2294                 {
2295                         /* Extract the data of the unnamed stream, unless the
2296                          * lookup table entry is NULL (indicating an empty
2297                          * stream for which no data needs to be extracted), or
2298                          * the stream is encrypted and therefore was already
2299                          * extracted as a special case. */
2300                         ret = do_win32_extract_stream(h, lte);
2301                         if (ret)
2302                                 return ret;
2303                 }
2304
2305                 if (dentry_has_short_name(dentry))
2306                         short_name = dentry->short_name;
2307                 else
2308                         short_name = L"";
2309                 /* Set short name */
2310                 if (!SetFileShortNameW(h, short_name)) {
2311                 #if 0
2312                         DWORD err = GetLastError();
2313                         ERROR("Could not set short name on \"%ls\"", stream_path);
2314                         win32_error(err);
2315                 #endif
2316                 }
2317         } else {
2318                 /* Extract the data for a named data stream. */
2319                 if (lte != NULL) {
2320                         DEBUG("Extracting named data stream \"%ls\" (len = %"PRIu64")",
2321                               stream_path, wim_resource_size(lte));
2322                         ret = do_win32_extract_stream(h, lte);
2323                 }
2324         }
2325         return ret;
2326 }
2327
2328 static int
2329 win32_decrypt_file(HANDLE open_handle, const wchar_t *path)
2330 {
2331         DWORD err;
2332         /* We cannot call DecryptFileW() while there is an open handle to the
2333          * file.  So close it first. */
2334         if (!CloseHandle(open_handle)) {
2335                 err = GetLastError();
2336                 ERROR("Failed to close handle for \"%ls\"", path);
2337                 win32_error(err);
2338                 return WIMLIB_ERR_WRITE;
2339         }
2340         if (!DecryptFileW(path, 0 /* reserved parameter; set to 0 */)) {
2341                 err = GetLastError();
2342                 ERROR("Failed to decrypt file \"%ls\"", path);
2343                 win32_error(err);
2344                 return WIMLIB_ERR_WRITE;
2345         }
2346         return 0;
2347 }
2348
2349 /*
2350  * Create and extract a stream to a file, or create a directory, using the
2351  * Windows API.
2352  *
2353  * This handles reparse points, directories, alternate data streams, encrypted
2354  * files, compressed files, etc.
2355  *
2356  * @dentry: WIM dentry for the file or directory being extracted.
2357  *
2358  * @path:  Path to extract the file to.
2359  *
2360  * @stream_name_utf16:
2361  *         Name of the stream, or NULL if the stream is unnamed.  This will
2362  *         be called with a NULL stream_name_utf16 before any non-NULL
2363  *         stream_name_utf16's.
2364  *
2365  * @lte:   WIM lookup table entry for the stream.  May be NULL to indicate
2366  *         a stream of length 0.
2367  *
2368  * @args:  Additional apply context, including flags indicating supported
2369  *         volume features.
2370  *
2371  * Returns 0 on success; nonzero on failure.
2372  */
2373 static int
2374 win32_extract_stream(const struct wim_dentry *dentry,
2375                      const wchar_t *path,
2376                      const wchar_t *stream_name_utf16,
2377                      struct wim_lookup_table_entry *lte,
2378                      struct apply_args *args)
2379 {
2380         wchar_t *stream_path;
2381         HANDLE h;
2382         int ret;
2383         DWORD err;
2384         DWORD creationDisposition = CREATE_ALWAYS;
2385         DWORD requestedAccess;
2386         BY_HANDLE_FILE_INFORMATION file_info;
2387         unsigned remaining_sharing_violations = 1000;
2388         const struct wim_inode *inode = dentry->d_inode;
2389
2390         if (stream_name_utf16) {
2391                 /* Named stream.  Create a buffer that contains the UTF-16LE
2392                  * string [./]path:stream_name_utf16.  This is needed to
2393                  * create and open the stream using CreateFileW().  I'm not
2394                  * aware of any other APIs to do this.  Note: the '$DATA' suffix
2395                  * seems to be unneeded.  Additional note: a "./" prefix needs
2396                  * to be added when the path is not absolute to avoid ambiguity
2397                  * with drive letters. */
2398                 size_t stream_path_nchars;
2399                 size_t path_nchars;
2400                 size_t stream_name_nchars;
2401                 const wchar_t *prefix;
2402
2403                 path_nchars = wcslen(path);
2404                 stream_name_nchars = wcslen(stream_name_utf16);
2405                 stream_path_nchars = path_nchars + 1 + stream_name_nchars;
2406                 if (path[0] != cpu_to_le16(L'\0') &&
2407                     path[0] != cpu_to_le16(L'/') &&
2408                     path[0] != cpu_to_le16(L'\\') &&
2409                     path[1] != cpu_to_le16(L':'))
2410                 {
2411                         prefix = L"./";
2412                         stream_path_nchars += 2;
2413                 } else {
2414                         prefix = L"";
2415                 }
2416                 stream_path = alloca((stream_path_nchars + 1) * sizeof(wchar_t));
2417                 swprintf(stream_path, L"%ls%ls:%ls",
2418                          prefix, path, stream_name_utf16);
2419         } else {
2420                 /* Unnamed stream; its path is just the path to the file itself.
2421                  * */
2422                 stream_path = (wchar_t*)path;
2423
2424                 ret = win32_begin_extract_unnamed_stream(inode, lte, path,
2425                                                          &creationDisposition,
2426                                                          args->vol_flags);
2427                 if (ret)
2428                         goto fail;
2429         }
2430
2431         DEBUG("Opening \"%ls\"", stream_path);
2432         /* DELETE access is needed for SetFileShortNameW(), for some reason. */
2433         requestedAccess = GENERIC_READ | GENERIC_WRITE | DELETE |
2434                           ACCESS_SYSTEM_SECURITY;
2435 try_open_again:
2436         /* Open the stream to be extracted.  Depending on what we have set
2437          * creationDisposition to, we may be creating this for the first time,
2438          * or we may be opening on existing stream we already created using
2439          * CreateDirectoryW() or OpenEncryptedFileRawW(). */
2440         h = CreateFileW(stream_path,
2441                         requestedAccess,
2442                         FILE_SHARE_READ,
2443                         NULL,
2444                         creationDisposition,
2445                         win32_get_create_flags_and_attributes(inode->i_attributes),
2446                         NULL);
2447         if (h == INVALID_HANDLE_VALUE) {
2448                 err = GetLastError();
2449                 if (err == ERROR_ACCESS_DENIED &&
2450                     path_is_root_of_drive(stream_path))
2451                 {
2452                         ret = 0;
2453                         goto out;
2454                 }
2455                 if ((err == ERROR_PRIVILEGE_NOT_HELD ||
2456                      err == ERROR_ACCESS_DENIED) &&
2457                     (requestedAccess & ACCESS_SYSTEM_SECURITY))
2458                 {
2459                         /* Try opening the file again without privilege to
2460                          * modify SACL. */
2461                         requestedAccess &= ~ACCESS_SYSTEM_SECURITY;
2462                         goto try_open_again;
2463                 }
2464                 if (err == ERROR_SHARING_VIOLATION) {
2465                         if (remaining_sharing_violations) {
2466                                 --remaining_sharing_violations;
2467                                 /* This can happen when restoring encrypted directories
2468                                  * for some reason.  Probably a bug in EncryptFile(). */
2469                                 WARNING("Couldn't open \"%ls\" due to sharing violation; "
2470                                         "re-trying after 100ms", stream_path);
2471                                 Sleep(100);
2472                                 goto try_open_again;
2473                         } else {
2474                                 ERROR("Too many sharing violations; giving up...");
2475                         }
2476                 } else {
2477                         if (creationDisposition == OPEN_EXISTING)
2478                                 ERROR("Failed to open \"%ls\"", stream_path);
2479                         else
2480                                 ERROR("Failed to create \"%ls\"", stream_path);
2481                         win32_error(err);
2482                 }
2483                 ret = WIMLIB_ERR_OPEN;
2484                 goto fail;
2485         }
2486
2487         /* Check the attributes of the file we just opened, and remove
2488          * encryption or compression if either was set by default but is not
2489          * supposed to be set based on the WIM inode attributes. */
2490         if (!GetFileInformationByHandle(h, &file_info)) {
2491                 err = GetLastError();
2492                 ERROR("Failed to get attributes of \"%ls\"", stream_path);
2493                 win32_error(err);
2494                 ret = WIMLIB_ERR_STAT;
2495                 goto fail_close_handle;
2496         }
2497
2498         /* Remove encryption? */
2499         if (file_info.dwFileAttributes & FILE_ATTRIBUTE_ENCRYPTED &&
2500             !(inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED))
2501         {
2502                 /* File defaulted to encrypted due to being in an encrypted
2503                  * directory, but is not actually supposed to be encrypted.
2504                  *
2505                  * This is a workaround, because I'm not aware of any way to
2506                  * directly (e.g. with CreateFileW()) create an unencrypted file
2507                  * in a directory with FILE_ATTRIBUTE_ENCRYPTED set. */
2508                 ret = win32_decrypt_file(h, stream_path);
2509                 if (ret)
2510                         goto fail; /* win32_decrypt_file() closed the handle. */
2511                 creationDisposition = OPEN_EXISTING;
2512                 goto try_open_again;
2513         }
2514
2515         /* Remove compression? */
2516         if (file_info.dwFileAttributes & FILE_ATTRIBUTE_COMPRESSED &&
2517             !(inode->i_attributes & FILE_ATTRIBUTE_COMPRESSED))
2518         {
2519                 /* Similar to the encrypted case, above, if the file defaulted
2520                  * to compressed due to being in an compressed directory, but is
2521                  * not actually supposed to be compressed, explicitly set the
2522                  * compression format to COMPRESSION_FORMAT_NONE. */
2523                 ret = win32_set_compression_state(h, COMPRESSION_FORMAT_NONE,
2524                                                   stream_path);
2525                 if (ret)
2526                         goto fail_close_handle;
2527         }
2528
2529         /* Set compression and/or sparse attributes if needed */
2530         ret = win32_set_special_stream_attributes(h, inode, lte, path,
2531                                                   args->vol_flags);
2532
2533         if (ret)
2534                 goto fail_close_handle;
2535
2536         /* At this point we have at least created the needed stream with the
2537          * appropriate attributes.  We have yet to set the appropriate security
2538          * descriptor and actually extract the stream data (other than for
2539          * extracted files, which were already extracted).
2540          * win32_finish_extract_stream() handles these additional steps. */
2541         ret = win32_finish_extract_stream(h, dentry, lte, stream_path,
2542                                           stream_name_utf16, args);
2543         if (ret)
2544                 goto fail_close_handle;
2545
2546         /* Done extracting the stream.  Close the handle and return. */
2547         DEBUG("Closing \"%ls\"", stream_path);
2548         if (!CloseHandle(h)) {
2549                 err = GetLastError();
2550                 ERROR("Failed to close \"%ls\"", stream_path);
2551                 win32_error(err);
2552                 ret = WIMLIB_ERR_WRITE;
2553                 goto fail;
2554         }
2555         ret = 0;
2556         goto out;
2557 fail_close_handle:
2558         CloseHandle(h);
2559 fail:
2560         ERROR("Error extracting \"%ls\"", stream_path);
2561 out:
2562         return ret;
2563 }
2564
2565 /*
2566  * Creates a file, directory, or reparse point and extracts all streams to it
2567  * (unnamed data stream and/or reparse point stream, plus any alternate data
2568  * streams).  Handles sparse, compressed, and/or encrypted files.
2569  *
2570  * @dentry:     WIM dentry for this file or directory.
2571  * @path:       UTF-16LE external path to extract the inode to.
2572  * @args:       Additional extraction context.
2573  *
2574  * Returns 0 on success; nonzero on failure.
2575  */
2576 static int
2577 win32_extract_streams(const struct wim_dentry *dentry,
2578                       const wchar_t *path, struct apply_args *args)
2579 {
2580         struct wim_lookup_table_entry *unnamed_lte;
2581         int ret;
2582         const struct wim_inode *inode = dentry->d_inode;
2583
2584         /* First extract the unnamed stream. */
2585
2586         unnamed_lte = inode_unnamed_lte_resolved(inode);
2587         ret = win32_extract_stream(dentry, path, NULL, unnamed_lte, args);
2588         if (ret)
2589                 goto out;
2590
2591         /* Extract any named streams, if supported by the volume. */
2592
2593         if (!(args->vol_flags & FILE_NAMED_STREAMS))
2594                 goto out;
2595         for (u16 i = 0; i < inode->i_num_ads; i++) {
2596                 const struct wim_ads_entry *ads_entry = &inode->i_ads_entries[i];
2597
2598                 /* Skip the unnamed stream if it's in the ADS entries (we
2599                  * already extracted it...) */
2600                 if (ads_entry->stream_name_nbytes == 0)
2601                         continue;
2602
2603                 /* Skip special UNIX data entries (see documentation for
2604                  * WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA) */
2605                 if (ads_entry->stream_name_nbytes == WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES
2606                     && !memcmp(ads_entry->stream_name,
2607                                WIMLIB_UNIX_DATA_TAG_UTF16LE,
2608                                WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES))
2609                         continue;
2610
2611                 /* Extract the named stream */
2612                 ret = win32_extract_stream(dentry,
2613                                            path,
2614                                            ads_entry->stream_name,
2615                                            ads_entry->lte,
2616                                            args);
2617                 if (ret)
2618                         break;
2619         }
2620 out:
2621         return ret;
2622 }
2623
2624 /* If not done already, load the supported feature flags for the volume onto
2625  * which the image is being extracted, and warn the user about any missing
2626  * features that could be important. */
2627 static int
2628 win32_check_vol_flags(const wchar_t *output_path, struct apply_args *args)
2629 {
2630         if (args->have_vol_flags)
2631                 return 0;
2632
2633         win32_get_vol_flags(output_path, &args->vol_flags);
2634         args->have_vol_flags = true;
2635         /* Warn the user about data that may not be extracted. */
2636         if (!(args->vol_flags & FILE_SUPPORTS_SPARSE_FILES))
2637                 WARNING("Volume does not support sparse files!\n"
2638                         "          Sparse files will be extracted as non-sparse.");
2639         if (!(args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS))
2640                 WARNING("Volume does not support reparse points!\n"
2641                         "          Reparse point data will not be extracted.");
2642         if (!(args->vol_flags & FILE_NAMED_STREAMS)) {
2643                 WARNING("Volume does not support named data streams!\n"
2644                         "          Named data streams will not be extracted.");
2645         }
2646         if (!(args->vol_flags & FILE_SUPPORTS_ENCRYPTION)) {
2647                 WARNING("Volume does not support encryption!\n"
2648                         "          Encrypted files will be extracted as raw data.");
2649         }
2650         if (!(args->vol_flags & FILE_FILE_COMPRESSION)) {
2651                 WARNING("Volume does not support transparent compression!\n"
2652                         "          Compressed files will be extracted as non-compressed.");
2653         }
2654         if (!(args->vol_flags & FILE_PERSISTENT_ACLS)) {
2655                 if (args->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS) {
2656                         ERROR("Strict ACLs requested, but the volume does not "
2657                               "support ACLs!");
2658                         return WIMLIB_ERR_VOLUME_LACKS_FEATURES;
2659                 } else {
2660                         WARNING("Volume does not support persistent ACLS!\n"
2661                                 "          File permissions will not be extracted.");
2662                 }
2663         }
2664         return 0;
2665 }
2666
2667 /*
2668  * Try extracting a hard link.
2669  *
2670  * @output_path:  Path to link to be extracted.
2671  *
2672  * @inode:        WIM inode that the link is to; inode->i_extracted_file
2673  *                the path to a name of the file that has already been
2674  *                extracted (we use this to create the hard link).
2675  *
2676  * @args:         Additional apply context, used here to keep track of
2677  *                the number of times creating a hard link failed due to
2678  *                ERROR_INVALID_FUNCTION.  This error should indicate that hard
2679  *                links are not supported by the volume, and we would like to
2680  *                warn the user a few times, but not too many times.
2681  *
2682  * Returns 0 if the hard link was successfully extracted.  Returns
2683  * WIMLIB_ERR_LINK (> 0) if an error occurred, other than hard links possibly
2684  * being unsupported by the volume.  Returns a negative value if creating the
2685  * hard link failed due to ERROR_INVALID_FUNCTION.
2686  */
2687 static int
2688 win32_try_hard_link(const wchar_t *output_path, const struct wim_inode *inode,
2689                     struct apply_args *args)
2690 {
2691         DWORD err;
2692
2693         /* There is a volume flag for this (FILE_SUPPORTS_HARD_LINKS),
2694          * but it's only available on Windows 7 and later.  So no use
2695          * even checking it, really.  Instead, CreateHardLinkW() will
2696          * apparently return ERROR_INVALID_FUNCTION if the volume does
2697          * not support hard links. */
2698         DEBUG("Creating hard link \"%ls => %ls\"",
2699               output_path, inode->i_extracted_file);
2700         if (CreateHardLinkW(output_path, inode->i_extracted_file, NULL))
2701                 return 0;
2702
2703         err = GetLastError();
2704         if (err != ERROR_INVALID_FUNCTION) {
2705                 ERROR("Can't create hard link \"%ls => %ls\"",
2706                       output_path, inode->i_extracted_file);
2707                 win32_error(err);
2708                 return WIMLIB_ERR_LINK;
2709         } else {
2710                 args->num_hard_links_failed++;
2711                 if (args->num_hard_links_failed < MAX_CREATE_HARD_LINK_WARNINGS) {
2712                         WARNING("Can't create hard link \"%ls => %ls\":\n"
2713                                 "          Volume does not support hard links!\n"
2714                                 "          Falling back to extracting a copy of the file.",
2715                                 output_path, inode->i_extracted_file);
2716                 } else if (args->num_hard_links_failed == MAX_CREATE_HARD_LINK_WARNINGS) {
2717                         WARNING("Suppressing further hard linking warnings...");
2718                 }
2719                 return -1;
2720         }
2721 }
2722
2723 /* Extract a file, directory, reparse point, or hard link to an
2724  * already-extracted file using the Win32 API */
2725 int
2726 win32_do_apply_dentry(const wchar_t *output_path,
2727                       size_t output_path_num_chars,
2728                       struct wim_dentry *dentry,
2729                       struct apply_args *args)
2730 {
2731         int ret;
2732         struct wim_inode *inode = dentry->d_inode;
2733
2734         ret = win32_check_vol_flags(output_path, args);
2735         if (ret)
2736                 return ret;
2737         if (inode->i_nlink > 1 && inode->i_extracted_file != NULL) {
2738                 /* Linked file, with another name already extracted.  Create a
2739                  * hard link. */
2740                 ret = win32_try_hard_link(output_path, inode, args);
2741                 if (ret >= 0)
2742                         return ret;
2743                 /* Negative return value from win32_try_hard_link() indicates
2744                  * that hard links are probably not supported by the volume.
2745                  * Fall back to extracting a copy of the file. */
2746         }
2747
2748         /* If this is a reparse point and the volume does not support reparse
2749          * points, just skip it completely. */
2750         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT &&
2751             !(args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS))
2752         {
2753                 WARNING("Skipping extraction of reparse point \"%ls\":\n"
2754                         "          Not supported by destination filesystem",
2755                         output_path);
2756         } else {
2757                 /* Create the file, directory, or reparse point, and extract the
2758                  * data streams. */
2759                 ret = win32_extract_streams(dentry, output_path, args);
2760                 if (ret)
2761                         return ret;
2762         }
2763         if (inode->i_extracted_file == NULL) {
2764                 const struct wim_lookup_table_entry *lte;
2765
2766                 /* Tally bytes extracted, including all alternate data streams,
2767                  * unless we extracted a hard link (or, at least extracted a
2768                  * name that was supposed to be a hard link) */
2769                 for (unsigned i = 0; i <= inode->i_num_ads; i++) {
2770                         lte = inode_stream_lte_resolved(inode, i);
2771                         if (lte)
2772                                 args->progress.extract.completed_bytes +=
2773                                                         wim_resource_size(lte);
2774                 }
2775                 if (inode->i_nlink > 1) {
2776                         /* Save extracted path for a later call to
2777                          * CreateHardLinkW() if this inode has multiple links.
2778                          * */
2779                         inode->i_extracted_file = WSTRDUP(output_path);
2780                         if (!inode->i_extracted_file)
2781                                 return WIMLIB_ERR_NOMEM;
2782                 }
2783         }
2784         return 0;
2785 }
2786
2787 /* Set timestamps on an extracted file using the Win32 API */
2788 int
2789 win32_do_apply_dentry_timestamps(const wchar_t *path,
2790                                  size_t path_num_chars,
2791                                  const struct wim_dentry *dentry,
2792                                  const struct apply_args *args)
2793 {
2794         DWORD err;
2795         HANDLE h;
2796         const struct wim_inode *inode = dentry->d_inode;
2797
2798         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT &&
2799             !(args->vol_flags & FILE_SUPPORTS_REPARSE_POINTS))
2800         {
2801                 /* Skip reparse points not extracted */
2802                 return 0;
2803         }
2804
2805         /* Windows doesn't let you change the timestamps of the root directory
2806          * (at least on FAT, which is dumb but expected since FAT doesn't store
2807          * any metadata about the root directory...) */
2808         if (path_is_root_of_drive(path))
2809                 return 0;
2810
2811         DEBUG("Opening \"%ls\" to set timestamps", path);
2812         h = win32_open_existing_file(path, FILE_WRITE_ATTRIBUTES);
2813         if (h == INVALID_HANDLE_VALUE) {
2814                 err = GetLastError();
2815                 goto fail;
2816         }
2817
2818         FILETIME creationTime = {.dwLowDateTime = inode->i_creation_time & 0xffffffff,
2819                                  .dwHighDateTime = inode->i_creation_time >> 32};
2820         FILETIME lastAccessTime = {.dwLowDateTime = inode->i_last_access_time & 0xffffffff,
2821                                   .dwHighDateTime = inode->i_last_access_time >> 32};
2822         FILETIME lastWriteTime = {.dwLowDateTime = inode->i_last_write_time & 0xffffffff,
2823                                   .dwHighDateTime = inode->i_last_write_time >> 32};
2824
2825         DEBUG("Calling SetFileTime() on \"%ls\"", path);
2826         if (!SetFileTime(h, &creationTime, &lastAccessTime, &lastWriteTime)) {
2827                 err = GetLastError();
2828                 CloseHandle(h);
2829                 goto fail;
2830         }
2831         DEBUG("Closing \"%ls\"", path);
2832         if (!CloseHandle(h)) {
2833                 err = GetLastError();
2834                 goto fail;
2835         }
2836         goto out;
2837 fail:
2838         /* Only warn if setting timestamps failed; still return 0. */
2839         WARNING("Can't set timestamps on \"%ls\"", path);
2840         win32_error(err);
2841 out:
2842         return 0;
2843 }
2844
2845 /* Replacement for POSIX fsync() */
2846 int
2847 fsync(int fd)
2848 {
2849         DWORD err;
2850         HANDLE h;
2851
2852         h = (HANDLE)_get_osfhandle(fd);
2853         if (h == INVALID_HANDLE_VALUE)
2854                 goto err;
2855         if (!FlushFileBuffers(h))
2856                 goto err;
2857         return 0;
2858 err:
2859         set_errno_from_GetLastError();
2860         return -1;
2861 }
2862
2863 /* Use the Win32 API to get the number of processors */
2864 unsigned
2865 win32_get_number_of_processors()
2866 {
2867         SYSTEM_INFO sysinfo;
2868         GetSystemInfo(&sysinfo);
2869         return sysinfo.dwNumberOfProcessors;
2870 }
2871
2872 /* Replacement for POSIX-2008 realpath().  Warning: partial functionality only
2873  * (resolved_path must be NULL).   Also I highly doubt that GetFullPathName
2874  * really does the right thing under all circumstances. */
2875 wchar_t *
2876 realpath(const wchar_t *path, wchar_t *resolved_path)
2877 {
2878         DWORD ret;
2879         DWORD err;
2880         wimlib_assert(resolved_path == NULL);
2881
2882         ret = GetFullPathNameW(path, 0, NULL, NULL);
2883         if (!ret) {
2884                 err = GetLastError();
2885                 goto fail_win32;
2886         }
2887
2888         resolved_path = TMALLOC(ret);
2889         if (!resolved_path)
2890                 goto out;
2891         ret = GetFullPathNameW(path, ret, resolved_path, NULL);
2892         if (!ret) {
2893                 err = GetLastError();
2894                 free(resolved_path);
2895                 resolved_path = NULL;
2896                 goto fail_win32;
2897         }
2898         goto out;
2899 fail_win32:
2900         errno = win32_error_to_errno(err);
2901 out:
2902         return resolved_path;
2903 }
2904
2905 /* rename() on Windows fails if the destination file exists.  And we need to
2906  * make it work on wide characters.  Fix it. */
2907 int
2908 win32_rename_replacement(const wchar_t *oldpath, const wchar_t *newpath)
2909 {
2910         if (MoveFileExW(oldpath, newpath, MOVEFILE_REPLACE_EXISTING)) {
2911                 return 0;
2912         } else {
2913                 set_errno_from_GetLastError();
2914                 return -1;
2915         }
2916 }
2917
2918 /* Replacement for POSIX fnmatch() (partial functionality only) */
2919 int
2920 fnmatch(const wchar_t *pattern, const wchar_t *string, int flags)
2921 {
2922         if (PathMatchSpecW(string, pattern))
2923                 return 0;
2924         else
2925                 return FNM_NOMATCH;
2926 }
2927
2928 /* truncate() replacement */
2929 int
2930 win32_truncate_replacement(const wchar_t *path, off_t size)
2931 {
2932         DWORD err = NO_ERROR;
2933         LARGE_INTEGER liOffset;
2934
2935         HANDLE h = win32_open_existing_file(path, GENERIC_WRITE);
2936         if (h == INVALID_HANDLE_VALUE)
2937                 goto fail;
2938
2939         liOffset.QuadPart = size;
2940         if (!SetFilePointerEx(h, liOffset, NULL, FILE_BEGIN))
2941                 goto fail_close_handle;
2942
2943         if (!SetEndOfFile(h))
2944                 goto fail_close_handle;
2945         CloseHandle(h);
2946         return 0;
2947
2948 fail_close_handle:
2949         err = GetLastError();
2950         CloseHandle(h);
2951 fail:
2952         if (err == NO_ERROR)
2953                 err = GetLastError();
2954         errno = win32_error_to_errno(err);
2955         return -1;
2956 }
2957
2958
2959 /* This really could be replaced with _wcserror_s, but this doesn't seem to
2960  * actually be available in MSVCRT.DLL on Windows XP (perhaps it's statically
2961  * linked in by Visual Studio...?). */
2962 extern int
2963 win32_strerror_r_replacement(int errnum, wchar_t *buf, size_t buflen)
2964 {
2965         static pthread_mutex_t strerror_lock = PTHREAD_MUTEX_INITIALIZER;
2966
2967         pthread_mutex_lock(&strerror_lock);
2968         mbstowcs(buf, strerror(errnum), buflen);
2969         buf[buflen - 1] = '\0';
2970         pthread_mutex_unlock(&strerror_lock);
2971         return 0;
2972 }
2973
2974 static int
2975 do_pread_or_pwrite(int fd, void *buf, size_t count, off_t offset,
2976                    bool is_pwrite)
2977 {
2978         HANDLE h;
2979         LARGE_INTEGER orig_offset;
2980         DWORD bytes_read_or_written;
2981         LARGE_INTEGER relative_offset;
2982         OVERLAPPED overlapped;
2983         BOOL bret;
2984
2985         wimlib_assert(count <= 0xffffffff);
2986
2987         h = (HANDLE)_get_osfhandle(fd);
2988         if (h == INVALID_HANDLE_VALUE) {
2989                 errno = EBADF;
2990                 return -1;
2991         }
2992
2993         /* Get original position */
2994         relative_offset.QuadPart = 0;
2995         if (!SetFilePointerEx(h, relative_offset, &orig_offset, FILE_CURRENT))
2996                 goto err;
2997
2998         memset(&overlapped, 0, sizeof(overlapped));
2999         overlapped.Offset = offset;
3000         overlapped.OffsetHigh = offset >> 32;
3001
3002         /* Do the read or write at the specified offset */
3003         if (is_pwrite)
3004                 bret = WriteFile(h, buf, count, &bytes_read_or_written, &overlapped);
3005         else
3006                 bret = ReadFile(h, buf, count, &bytes_read_or_written, &overlapped);
3007         if (!bret)
3008                 goto err;
3009
3010         /* Restore the original position */
3011         if (!SetFilePointerEx(h, orig_offset, NULL, FILE_BEGIN))
3012                 goto err;
3013
3014         return bytes_read_or_written;
3015 err:
3016         set_errno_from_GetLastError();
3017         return -1;
3018 }
3019
3020 /* Dumb Windows implementation of pread().  It temporarily changes the file
3021  * offset, so it is not safe to use with readers/writers on the same file
3022  * descriptor.  */
3023 extern ssize_t
3024 win32_pread(int fd, void *buf, size_t count, off_t offset)
3025 {
3026         return do_pread_or_pwrite(fd, buf, count, offset, false);
3027 }
3028
3029 /* Dumb Windows implementation of pwrite().  It temporarily changes the file
3030  * offset, so it is not safe to use with readers/writers on the same file
3031  * descriptor. */
3032 extern ssize_t
3033 win32_pwrite(int fd, const void *buf, size_t count, off_t offset)
3034 {
3035         return do_pread_or_pwrite(fd, (void*)buf, count, offset, true);
3036 }
3037
3038 /* Dumb Windows implementation of writev().  It writes the vectors one at a
3039  * time. */
3040 extern ssize_t
3041 win32_writev(int fd, const struct iovec *iov, int iovcnt)
3042 {
3043         size_t total_bytes_written = 0;
3044         for (int i = 0; i < iovcnt; i++) {
3045                 size_t bytes_written;
3046
3047                 bytes_written = full_write(fd, iov[i].iov_base, iov[i].iov_len);
3048                 total_bytes_written += bytes_written;
3049                 if (bytes_written != iov[i].iov_len)
3050                         break;
3051         }
3052         return total_bytes_written;
3053 }
3054
3055 #endif /* __WIN32__ */