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