]> wimlib.net Git - wimlib/blob - src/win32.c
8b8620fe11b01fdea8345e7518fdcb4b3768e9a8
[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 #ifndef __WIN32__
27 #  error "This file contains Windows code"
28 #endif
29
30 #include "config.h"
31 #include <windows.h>
32 #include <ntdef.h>
33 #include <wchar.h>
34 #include <shlwapi.h> /* shlwapi.h for PathMatchSpecA() */
35 #ifdef ERROR /* windows.h defines this */
36 #  undef ERROR
37 #endif
38
39 #include "win32.h"
40 #include "dentry.h"
41 #include "lookup_table.h"
42 #include "security.h"
43 #include "endianness.h"
44
45 #include <errno.h>
46
47 static const char *access_denied_msg =
48 "         If you are not running this program as the administrator, you may\n"
49 "         need to do so, so that all data and metadata can be backed up.\n"
50 "         Otherwise, there may be no way to access the desired data or\n"
51 "         metadata without taking ownership of the file or directory.\n";
52
53 #ifdef ENABLE_ERROR_MESSAGES
54 void
55 win32_error(u32 err_code)
56 {
57         char *buffer;
58         DWORD nchars;
59         nchars = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
60                                 NULL, err_code, 0,
61                                 (char*)&buffer, 0, NULL);
62         if (nchars == 0) {
63                 ERROR("Error printing error message! "
64                       "Computer will self-destruct in 3 seconds.");
65         } else {
66                 ERROR("Win32 error: %s", buffer);
67                 LocalFree(buffer);
68         }
69 }
70
71 void
72 win32_error_last()
73 {
74         win32_error(GetLastError());
75 }
76 #endif
77
78 static HANDLE
79 win32_open_existing_file(const wchar_t *path, DWORD dwDesiredAccess)
80 {
81         return CreateFileW(path,
82                            dwDesiredAccess,
83                            FILE_SHARE_READ,
84                            NULL, /* lpSecurityAttributes */
85                            OPEN_EXISTING,
86                            FILE_FLAG_BACKUP_SEMANTICS |
87                                FILE_FLAG_OPEN_REPARSE_POINT,
88                            NULL /* hTemplateFile */);
89 }
90
91 HANDLE
92 win32_open_file_data_only(const wchar_t *path)
93 {
94         return win32_open_existing_file(path, FILE_READ_DATA);
95 }
96
97 int
98 win32_read_file(const mbchar *filename,
99                 void *handle, u64 offset, size_t size, void *buf)
100 {
101         HANDLE h = handle;
102         DWORD err;
103         DWORD bytesRead;
104         LARGE_INTEGER liOffset = {.QuadPart = offset};
105
106         wimlib_assert(size <= 0xffffffff);
107
108         if (SetFilePointerEx(h, liOffset, NULL, FILE_BEGIN))
109                 if (ReadFile(h, buf, size, &bytesRead, NULL) && bytesRead == size)
110                         return 0;
111         err = GetLastError();
112         ERROR("Error reading \"%s\"", filename);
113         win32_error(err);
114         return WIMLIB_ERR_READ;
115 }
116
117 void
118 win32_close_file(void *handle)
119 {
120         CloseHandle((HANDLE)handle);
121 }
122
123 static u64
124 FILETIME_to_u64(const FILETIME *ft)
125 {
126         return ((u64)ft->dwHighDateTime << 32) | (u64)ft->dwLowDateTime;
127 }
128
129 static int
130 win32_get_short_name(struct wim_dentry *dentry,
131                      const wchar_t *path_utf16)
132 {
133         WIN32_FIND_DATAW dat;
134         if (FindFirstFileW(path_utf16, &dat) &&
135             dat.cAlternateFileName[0] != L'\0')
136         {
137                 size_t short_name_nbytes = wcslen(dat.cAlternateFileName) * 2;
138                 size_t n = short_name_nbytes + sizeof(wchar_t);
139                 dentry->short_name = MALLOC(n);
140                 if (!dentry->short_name)
141                         return WIMLIB_ERR_NOMEM;
142                 memcpy(dentry->short_name, dat.cAlternateFileName, n);
143                 dentry->short_name_nbytes = short_name_nbytes;
144         }
145         return 0;
146 }
147
148 static int
149 win32_get_security_descriptor(struct wim_dentry *dentry,
150                               struct sd_set *sd_set,
151                               const wchar_t *path_utf16)
152 {
153         SECURITY_INFORMATION requestedInformation;
154         DWORD lenNeeded = 0;
155         BOOL status;
156         DWORD err;
157
158         requestedInformation = DACL_SECURITY_INFORMATION |
159                                SACL_SECURITY_INFORMATION |
160                                OWNER_SECURITY_INFORMATION |
161                                GROUP_SECURITY_INFORMATION;
162         /* Request length of security descriptor */
163         status = GetFileSecurityW(path_utf16, requestedInformation,
164                                   NULL, 0, &lenNeeded);
165         err = GetLastError();
166         if (!status && err == ERROR_INSUFFICIENT_BUFFER) {
167                 DWORD len = lenNeeded;
168                 char buf[len];
169                 if (GetFileSecurityW(path_utf16, requestedInformation,
170                                      (PSECURITY_DESCRIPTOR)buf, len, &lenNeeded))
171                 {
172                         int security_id = sd_set_add_sd(sd_set, buf, len);
173                         if (security_id < 0)
174                                 return WIMLIB_ERR_NOMEM;
175                         else {
176                                 dentry->d_inode->i_security_id = security_id;
177                                 return 0;
178                         }
179                 } else {
180                         err = GetLastError();
181                 }
182         }
183
184         if (err == ERROR_ACCESS_DENIED) {
185                 WARNING("Failed to read security descriptor of \"%ls\": "
186                         "Access denied!\n%s", path_utf16, access_denied_msg);
187                 return 0;
188         } else {
189                 ERROR("Win32 API: Failed to read security descriptor of \"%ls\"",
190                       path_utf16);
191                 win32_error(err);
192                 return WIMLIB_ERR_READ;
193         }
194 }
195
196 /* Reads the directory entries of directory using a Win32 API and recursively
197  * calls win32_build_dentry_tree() on them. */
198 static int
199 win32_recurse_directory(struct wim_dentry *root,
200                         const mbchar *root_disk_path,
201                         struct wim_lookup_table *lookup_table,
202                         struct wim_security_data *sd,
203                         const struct capture_config *config,
204                         int add_image_flags,
205                         wimlib_progress_func_t progress_func,
206                         struct sd_set *sd_set,
207                         const wchar_t *path_utf16,
208                         size_t path_utf16_nchars)
209 {
210         WIN32_FIND_DATAW dat;
211         HANDLE hFind;
212         DWORD err;
213         int ret;
214
215         {
216                 /* Begin reading the directory by calling FindFirstFileW.
217                  * Unlike UNIX opendir(), FindFirstFileW has file globbing built
218                  * into it.  But this isn't what we actually want, so just add a
219                  * dummy glob to get all entries. */
220                 wchar_t pattern_buf[path_utf16_nchars + 3];
221                 memcpy(pattern_buf, path_utf16,
222                        path_utf16_nchars * sizeof(wchar_t));
223                 pattern_buf[path_utf16_nchars] = L'/';
224                 pattern_buf[path_utf16_nchars + 1] = L'*';
225                 pattern_buf[path_utf16_nchars + 2] = L'\0';
226                 hFind = FindFirstFileW(pattern_buf, &dat);
227         }
228         if (hFind == INVALID_HANDLE_VALUE) {
229                 err = GetLastError();
230                 if (err == ERROR_FILE_NOT_FOUND) {
231                         return 0;
232                 } else {
233                         ERROR("Win32 API: Failed to read directory \"%s\"",
234                               root_disk_path);
235                         win32_error(err);
236                         return WIMLIB_ERR_READ;
237                 }
238         }
239         ret = 0;
240         do {
241                 /* Skip . and .. entries */
242                 if (!(dat.cFileName[0] == cpu_to_le16(L'.') &&
243                       (dat.cFileName[1] == cpu_to_le16(L'\0') ||
244                        (dat.cFileName[1] == cpu_to_le16(L'.') &&
245                         dat.cFileName[2] == cpu_to_le16(L'\0')))))
246                 {
247                         struct wim_dentry *child;
248
249                         mbchar *mbs_name;
250                         size_t mbs_name_nbytes;
251                         ret = utf16le_to_mbs(dat.cFileName,
252                                              wcslen(dat.cFileName) * sizeof(wchar_t),
253                                              &mbs_name,
254                                              &mbs_name_nbytes);
255                         if (ret)
256                                 goto out_find_close;
257
258                         mbchar name[strlen(root_disk_path) + 1 + mbs_name_nbytes + 1];
259                         sprintf(name, "%s/%s", root_disk_path, mbs_name);
260                         FREE(mbs_name);
261                         ret = win32_build_dentry_tree(&child, name, lookup_table,
262                                                       sd, config, add_image_flags,
263                                                       progress_func, sd_set);
264                         if (ret)
265                                 goto out_find_close;
266                         if (child)
267                                 dentry_add_child(root, child);
268                 }
269         } while (FindNextFileW(hFind, &dat));
270         err = GetLastError();
271         if (err != ERROR_NO_MORE_FILES) {
272                 ERROR("Win32 API: Failed to read directory \"%s\"", root_disk_path);
273                 win32_error(err);
274                 if (ret == 0)
275                         ret = WIMLIB_ERR_READ;
276         }
277 out_find_close:
278         FindClose(hFind);
279         return ret;
280 }
281
282 /* Load a reparse point into a WIM inode.  It is just stored in memory.
283  *
284  * @hFile:  Open handle to a reparse point, with permission to read the reparse
285  *          data.
286  *
287  * @inode:  WIM inode for the reparse point.
288  *
289  * @lookup_table:  Stream lookup table for the WIM; an entry will be added to it
290  *                 for the reparse point unless an entry already exists for
291  *                 the exact same data stream.
292  *
293  * @path:  External path to the reparse point.  Used for error messages only.
294  *
295  * Returns 0 on success; nonzero on failure. */
296 static int
297 win32_capture_reparse_point(HANDLE hFile,
298                             struct wim_inode *inode,
299                             struct wim_lookup_table *lookup_table,
300                             const mbchar *path)
301 {
302         /* "Reparse point data, including the tag and optional GUID,
303          * cannot exceed 16 kilobytes." - MSDN  */
304         char reparse_point_buf[16 * 1024];
305         DWORD bytesReturned;
306
307         if (!DeviceIoControl(hFile, FSCTL_GET_REPARSE_POINT,
308                              NULL, /* "Not used with this operation; set to NULL" */
309                              0, /* "Not used with this operation; set to 0" */
310                              reparse_point_buf, /* "A pointer to a buffer that
311                                                    receives the reparse point data */
312                              sizeof(reparse_point_buf), /* "The size of the output
313                                                            buffer, in bytes */
314                              &bytesReturned,
315                              NULL))
316         {
317                 DWORD err = GetLastError();
318                 ERROR("Win32 API: Failed to get reparse data of \"%s\"", path);
319                 win32_error(err);
320                 return WIMLIB_ERR_READ;
321         }
322         if (bytesReturned < 8) {
323                 ERROR("Reparse data on \"%s\" is invalid", path);
324                 return WIMLIB_ERR_READ;
325         }
326         inode->i_reparse_tag = le32_to_cpu(*(u32*)reparse_point_buf);
327         return inode_add_ads_with_data(inode, "",
328                                        reparse_point_buf + 8,
329                                        bytesReturned - 8, lookup_table);
330 }
331
332 /* Calculate the SHA1 message digest of a Win32 data stream, which may be either
333  * an unnamed or named data stream.
334  *
335  * @path:       Path to the file, with the stream noted at the end for named
336  *              streams.  UTF-16LE encoding.
337  *
338  * @hash:       On success, the SHA1 message digest of the stream is written to
339  *              this location.
340  *
341  * Returns 0 on success; nonzero on failure.
342  */
343 static int
344 win32_sha1sum(const wchar_t *path, u8 hash[SHA1_HASH_SIZE])
345 {
346         HANDLE hFile;
347         SHA_CTX ctx;
348         u8 buf[32768];
349         DWORD bytesRead;
350         int ret;
351
352         hFile = win32_open_file_data_only(path);
353         if (hFile == INVALID_HANDLE_VALUE)
354                 return WIMLIB_ERR_OPEN;
355
356         sha1_init(&ctx);
357         for (;;) {
358                 if (!ReadFile(hFile, buf, sizeof(buf), &bytesRead, NULL)) {
359                         ret = WIMLIB_ERR_READ;
360                         goto out_close_handle;
361                 }
362                 if (bytesRead == 0)
363                         break;
364                 sha1_update(&ctx, buf, bytesRead);
365         }
366         ret = 0;
367         sha1_final(hash, &ctx);
368 out_close_handle:
369         CloseHandle(hFile);
370         return ret;
371 }
372
373 /* Scans an unnamed or named stream of a Win32 file (not a reparse point
374  * stream); calculates its SHA1 message digest and either creates a `struct
375  * wim_lookup_table_entry' in memory for it, or uses an existing 'struct
376  * wim_lookup_table_entry' for an identical stream.
377  *
378  * @path_utf16:         Path to the file (UTF-16LE).
379  *
380  * @path_utf16_nchars:  Number of 2-byte characters in @path_utf16.
381  *
382  * @inode:              WIM inode to save the stream into.
383  *
384  * @lookup_table:       Stream lookup table for the WIM.
385  *
386  * @dat:                A `WIN32_FIND_STREAM_DATA' structure that specifies the
387  *                      stream name.
388  *
389  * Returns 0 on success; nonzero on failure.
390  */
391 static int
392 win32_capture_stream(const wchar_t *path_utf16,
393                      size_t path_utf16_nchars,
394                      struct wim_inode *inode,
395                      struct wim_lookup_table *lookup_table,
396                      WIN32_FIND_STREAM_DATA *dat)
397 {
398         struct wim_ads_entry *ads_entry;
399         u8 hash[SHA1_HASH_SIZE];
400         struct wim_lookup_table_entry *lte;
401         int ret;
402         wchar_t *stream_name, *colon;
403         size_t stream_name_nchars;
404         bool is_named_stream;
405         wchar_t *spath;
406         size_t spath_nchars;
407         DWORD err;
408         size_t spath_buf_nbytes;
409         const wchar_t *relpath_prefix;
410         const wchar_t *colonchar;
411
412         /* The stream name should be returned as :NAME:TYPE */
413         stream_name = dat->cStreamName;
414         if (*stream_name != L':')
415                 goto out_invalid_stream_name;
416         stream_name += 1;
417         colon = wcschr(stream_name, L':');
418         if (colon == NULL)
419                 goto out_invalid_stream_name;
420
421         if (wcscmp(colon + 1, L"$DATA")) {
422                 /* Not a DATA stream */
423                 ret = 0;
424                 goto out;
425         }
426
427         *colon = '\0';
428
429         stream_name_nchars = colon - stream_name;
430         is_named_stream = (stream_name_nchars != 0);
431
432         if (is_named_stream) {
433                 /* Allocate an ADS entry for the named stream. */
434                 ads_entry = inode_add_ads_utf16le(inode, stream_name,
435                                                   stream_name_nchars * 2);
436                 if (!ads_entry) {
437                         ret = WIMLIB_ERR_NOMEM;
438                         goto out;
439                 }
440         }
441
442         /* Create a UTF-16LE string @spath that gives the filename, then a
443          * colon, then the stream name.  Or, if it's an unnamed stream, just the
444          * filename.  It is MALLOC()'ed so that it can be saved in the
445          * wim_lookup_table_entry if needed.
446          *
447          * As yet another special case, relative paths need to be changed to
448          * begin with an explicit "./" so that, for example, a file t:ads, where
449          * :ads is the part we added, is not interpreted as a file on the t:
450          * drive. */
451         spath_nchars = path_utf16_nchars;
452         relpath_prefix = L"";
453         colonchar = L"";
454         if (is_named_stream) {
455                 spath_nchars += 1 + stream_name_nchars;
456                 colonchar = L":";
457                 if (path_utf16_nchars == 1 &&
458                     path_utf16[0] != cpu_to_le16('/') &&
459                     path_utf16[0] != cpu_to_le16('\\'))
460                 {
461                         spath_nchars += 2;
462                         relpath_prefix = L"./";
463                 }
464         }
465
466         spath_buf_nbytes = (spath_nchars + 1) * sizeof(wchar_t);
467         spath = MALLOC(spath_buf_nbytes);
468
469         swprintf(spath, spath_buf_nbytes, L"%ls%ls%ls%ls",
470                  relpath_prefix, path_utf16, colonchar, stream_name);
471
472         ret = win32_sha1sum(spath, hash);
473         if (ret) {
474                 err = GetLastError();
475                 ERROR("Win32 API: Failed to read \"%ls\" to calculate SHA1sum",
476                       spath);
477                 win32_error(err);
478                 goto out_free_spath;
479         }
480
481         lte = __lookup_resource(lookup_table, hash);
482         if (lte) {
483                 /* Use existing wim_lookup_table_entry that has the same SHA1
484                  * message digest */
485                 lte->refcnt++;
486         } else {
487                 /* Make a new wim_lookup_table_entry */
488                 lte = new_lookup_table_entry();
489                 if (!lte) {
490                         ret = WIMLIB_ERR_NOMEM;
491                         goto out_free_spath;
492                 }
493                 lte->win32_file_on_disk = spath;
494                 lte->file_on_disk_fp = INVALID_HANDLE_VALUE;
495                 spath = NULL;
496                 lte->resource_location = RESOURCE_WIN32;
497                 lte->resource_entry.original_size = (uint64_t)dat->StreamSize.QuadPart;
498                 lte->resource_entry.size = (uint64_t)dat->StreamSize.QuadPart;
499                 copy_hash(lte->hash, hash);
500                 lookup_table_insert(lookup_table, lte);
501         }
502         if (is_named_stream)
503                 ads_entry->lte = lte;
504         else
505                 inode->i_lte = lte;
506 out_free_spath:
507         FREE(spath);
508 out:
509         return ret;
510 out_invalid_stream_name:
511         ERROR("Invalid stream name: \"%ls:%ls\"", path_utf16, dat->cStreamName);
512         ret = WIMLIB_ERR_READ;
513         goto out;
514 }
515
516 /* Scans a Win32 file for unnamed and named data streams (not reparse point
517  * streams).
518  *
519  * @path_utf16:         Path to the file (UTF-16LE).
520  *
521  * @path_utf16_nchars:  Number of 2-byte characters in @path_utf16.
522  *
523  * @inode:              WIM inode to save the stream into.
524  *
525  * @lookup_table:       Stream lookup table for the WIM.
526  *
527  * Returns 0 on success; nonzero on failure.
528  */
529 static int
530 win32_capture_streams(const wchar_t *path_utf16,
531                       size_t path_utf16_nchars,
532                       struct wim_inode *inode,
533                       struct wim_lookup_table *lookup_table)
534 {
535         WIN32_FIND_STREAM_DATA dat;
536         int ret;
537         HANDLE hFind;
538         DWORD err;
539
540         hFind = FindFirstStreamW(path_utf16, FindStreamInfoStandard, &dat, 0);
541         if (hFind == INVALID_HANDLE_VALUE) {
542                 err = GetLastError();
543
544                 /* Seems legal for this to return ERROR_HANDLE_EOF on reparse
545                  * points and directories */
546                 if ((inode->i_attributes &
547                     (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
548                     && err == ERROR_HANDLE_EOF)
549                 {
550                         return 0;
551                 } else {
552                         if (err == ERROR_ACCESS_DENIED) {
553                                 WARNING("Failed to look up data streams of \"%ls\": "
554                                         "Access denied!\n%s", path_utf16,
555                                         access_denied_msg);
556                                 return 0;
557                         } else {
558                                 ERROR("Win32 API: Failed to look up data streams of \"%ls\"",
559                                       path_utf16);
560                                 win32_error(err);
561                                 return WIMLIB_ERR_READ;
562                         }
563                 }
564         }
565         do {
566                 ret = win32_capture_stream(path_utf16,
567                                            path_utf16_nchars,
568                                            inode, lookup_table,
569                                            &dat);
570                 if (ret)
571                         goto out_find_close;
572         } while (FindNextStreamW(hFind, &dat));
573         err = GetLastError();
574         if (err != ERROR_HANDLE_EOF) {
575                 ERROR("Win32 API: Error reading data streams from \"%ls\"", path_utf16);
576                 win32_error(err);
577                 ret = WIMLIB_ERR_READ;
578         }
579 out_find_close:
580         FindClose(hFind);
581         return ret;
582 }
583
584 /* Win32 version of capturing a directory tree */
585 int
586 win32_build_dentry_tree(struct wim_dentry **root_ret,
587                         const mbchar *root_disk_path,
588                         struct wim_lookup_table *lookup_table,
589                         struct wim_security_data *sd,
590                         const struct capture_config *config,
591                         int add_image_flags,
592                         wimlib_progress_func_t progress_func,
593                         void *extra_arg)
594 {
595         struct wim_dentry *root = NULL;
596         int ret = 0;
597         struct wim_inode *inode;
598
599         wchar_t *path_utf16;
600         size_t path_utf16_nbytes;
601         size_t path_utf16_nchars;
602         struct sd_set *sd_set;
603         DWORD err;
604
605         if (exclude_path(root_disk_path, config, true)) {
606                 if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT) {
607                         ERROR("Cannot exclude the root directory from capture");
608                         ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
609                         goto out;
610                 }
611                 if ((add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
612                     && progress_func)
613                 {
614                         union wimlib_progress_info info;
615                         info.scan.cur_path = root_disk_path;
616                         info.scan.excluded = true;
617                         progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
618                 }
619                 goto out;
620         }
621
622         if ((add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
623             && progress_func)
624         {
625                 union wimlib_progress_info info;
626                 info.scan.cur_path = root_disk_path;
627                 info.scan.excluded = false;
628                 progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
629         }
630
631         if (extra_arg == NULL) {
632                 sd_set = alloca(sizeof(struct sd_set));
633                 sd_set->rb_root.rb_node = NULL,
634                 sd_set->sd = sd;
635         } else {
636                 sd_set = extra_arg;
637         }
638
639         ret = mbs_to_utf16le(root_disk_path, strlen(root_disk_path),
640                              &path_utf16, &path_utf16_nbytes);
641         if (ret)
642                 goto out_destroy_sd_set;
643         path_utf16_nchars = path_utf16_nbytes / sizeof(wchar_t);
644
645         HANDLE hFile = win32_open_existing_file(path_utf16,
646                                                 FILE_READ_DATA | FILE_READ_ATTRIBUTES);
647         if (hFile == INVALID_HANDLE_VALUE) {
648                 err = GetLastError();
649                 ERROR("Win32 API: Failed to open \"%s\"", root_disk_path);
650                 win32_error(err);
651                 ret = WIMLIB_ERR_OPEN;
652                 goto out_free_path_utf16;
653         }
654
655         BY_HANDLE_FILE_INFORMATION file_info;
656         if (!GetFileInformationByHandle(hFile, &file_info)) {
657                 err = GetLastError();
658                 ERROR("Win32 API: Failed to get file information for \"%s\"",
659                       root_disk_path);
660                 win32_error(err);
661                 ret = WIMLIB_ERR_STAT;
662                 goto out_close_handle;
663         }
664
665         /* Create a WIM dentry */
666         ret = new_dentry_with_timeless_inode(path_basename(root_disk_path), &root);
667         if (ret)
668                 goto out_close_handle;
669
670         /* Start preparing the associated WIM inode */
671         inode = root->d_inode;
672
673         inode->i_attributes = file_info.dwFileAttributes;
674         inode->i_creation_time = FILETIME_to_u64(&file_info.ftCreationTime);
675         inode->i_last_write_time = FILETIME_to_u64(&file_info.ftLastWriteTime);
676         inode->i_last_access_time = FILETIME_to_u64(&file_info.ftLastAccessTime);
677         inode->i_ino = ((u64)file_info.nFileIndexHigh << 32) |
678                         (u64)file_info.nFileIndexLow;
679
680         inode->i_resolved = 1;
681         add_image_flags &= ~(WIMLIB_ADD_IMAGE_FLAG_ROOT | WIMLIB_ADD_IMAGE_FLAG_SOURCE);
682
683         /* Get DOS name and security descriptor (if any). */
684         ret = win32_get_short_name(root, path_utf16);
685         if (ret)
686                 goto out_close_handle;
687
688         if (!(add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NO_ACLS)) {
689                 ret = win32_get_security_descriptor(root, sd_set, path_utf16);
690                 if (ret)
691                         goto out_close_handle;
692         }
693
694         if (inode_is_directory(inode)) {
695                 /* Directory (not a reparse point) --- recurse to children */
696
697                 /* But first... directories may have alternate data streams that
698                  * need to be captured. */
699                 ret = win32_capture_streams(path_utf16,
700                                             path_utf16_nchars,
701                                             inode,
702                                             lookup_table);
703                 if (ret)
704                         goto out_close_handle;
705                 ret = win32_recurse_directory(root,
706                                               root_disk_path,
707                                               lookup_table,
708                                               sd,
709                                               config,
710                                               add_image_flags,
711                                               progress_func,
712                                               sd_set,
713                                               path_utf16,
714                                               path_utf16_nchars);
715         } else if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
716                 /* Reparse point: save the reparse tag and data */
717                 ret = win32_capture_reparse_point(hFile,
718                                                   inode,
719                                                   lookup_table,
720                                                   root_disk_path);
721         } else {
722                 /* Not a directory, not a reparse point; capture the default
723                  * file contents and any alternate data streams. */
724                 ret = win32_capture_streams(path_utf16,
725                                             path_utf16_nchars,
726                                             inode,
727                                             lookup_table);
728         }
729 out_close_handle:
730         CloseHandle(hFile);
731 out_free_path_utf16:
732         FREE(path_utf16);
733 out_destroy_sd_set:
734         if (extra_arg == NULL)
735                 destroy_sd_set(sd_set);
736 out:
737         if (ret == 0)
738                 *root_ret = root;
739         else
740                 free_dentry_tree(root, lookup_table);
741         return ret;
742 }
743
744 /* Replacement for POSIX fnmatch() (partial functionality only) */
745 int
746 fnmatch(const char *pattern, const char *string, int flags)
747 {
748         if (PathMatchSpecA(string, pattern))
749                 return 0;
750         else
751                 return FNM_NOMATCH;
752 }
753
754 static int
755 win32_set_reparse_data(HANDLE h,
756                        u32 reparse_tag,
757                        const struct wim_lookup_table_entry *lte,
758                        const wchar_t *path)
759 {
760         int ret;
761         u8 *buf;
762         size_t len;
763
764         if (!lte) {
765                 WARNING("\"%ls\" is marked as a reparse point but had no reparse data",
766                         path);
767                 return 0;
768         }
769         len = wim_resource_size(lte);
770         if (len > 16 * 1024 - 8) {
771                 WARNING("\"%ls\": reparse data too long!", path);
772                 return 0;
773         }
774
775         /* The WIM stream omits the ReparseTag and ReparseDataLength fields, so
776          * leave 8 bytes of space for them at the beginning of the buffer, then
777          * set them manually. */
778         buf = alloca(len + 8);
779         ret = read_full_wim_resource(lte, buf + 8, 0);
780         if (ret)
781                 return ret;
782         *(u32*)(buf + 0) = cpu_to_le32(reparse_tag);
783         *(u16*)(buf + 4) = cpu_to_le16(len);
784         *(u16*)(buf + 6) = 0;
785
786         /* Set the reparse data on the open file using the
787          * FSCTL_SET_REPARSE_POINT ioctl.
788          *
789          * There are contradictions in Microsoft's documentation for this:
790          *
791          * "If hDevice was opened without specifying FILE_FLAG_OVERLAPPED,
792          * lpOverlapped is ignored."
793          *
794          * --- So setting lpOverlapped to NULL is okay since it's ignored.
795          *
796          * "If lpOverlapped is NULL, lpBytesReturned cannot be NULL. Even when an
797          * operation returns no output data and lpOutBuffer is NULL,
798          * DeviceIoControl makes use of lpBytesReturned. After such an
799          * operation, the value of lpBytesReturned is meaningless."
800          *
801          * --- So lpOverlapped not really ignored, as it affects another
802          *  parameter.  This is the actual behavior: lpBytesReturned must be
803          *  specified, even though lpBytesReturned is documented as:
804          *
805          *  "Not used with this operation; set to NULL."
806          */
807         DWORD bytesReturned;
808         if (!DeviceIoControl(h, FSCTL_SET_REPARSE_POINT, buf, len + 8,
809                              NULL, 0,
810                              &bytesReturned /* lpBytesReturned */,
811                              NULL /* lpOverlapped */))
812         {
813                 DWORD err = GetLastError();
814                 ERROR("Failed to set reparse data on \"%ls\"", path);
815                 win32_error(err);
816                 return WIMLIB_ERR_WRITE;
817         }
818         return 0;
819 }
820
821
822 static int
823 win32_extract_chunk(const void *buf, size_t len, u64 offset, void *arg)
824 {
825         HANDLE hStream = arg;
826
827         DWORD nbytes_written;
828         wimlib_assert(len <= 0xffffffff);
829
830         if (!WriteFile(hStream, buf, len, &nbytes_written, NULL) ||
831             nbytes_written != len)
832         {
833                 DWORD err = GetLastError();
834                 ERROR("WriteFile(): write error");
835                 win32_error(err);
836                 return WIMLIB_ERR_WRITE;
837         }
838         return 0;
839 }
840
841 static int
842 do_win32_extract_stream(HANDLE hStream, struct wim_lookup_table_entry *lte)
843 {
844         return extract_wim_resource(lte, wim_resource_size(lte),
845                                     win32_extract_chunk, hStream);
846 }
847
848 static int
849 win32_extract_stream(const struct wim_inode *inode,
850                      const wchar_t *path,
851                      const wchar_t *stream_name_utf16,
852                      struct wim_lookup_table_entry *lte,
853                      const struct wim_security_data *security_data)
854 {
855         wchar_t *stream_path;
856         HANDLE h;
857         int ret;
858         DWORD err;
859         DWORD creationDisposition = CREATE_ALWAYS;
860
861         SECURITY_ATTRIBUTES *secattr;
862
863         if (security_data && inode->i_security_id != -1) {
864                 secattr = alloca(sizeof(*secattr));
865                 secattr->nLength = sizeof(*secattr);
866                 secattr->lpSecurityDescriptor = security_data->descriptors[inode->i_security_id];
867                 secattr->bInheritHandle = FALSE;
868         } else {
869                 secattr = NULL;
870         }
871
872         if (stream_name_utf16) {
873                 /* Named stream.  Create a buffer that contains the UTF-16LE
874                  * string [.\]@path:@stream_name_utf16.  This is needed to
875                  * create and open the stream using CreateFileW().  I'm not
876                  * aware of any other APIs to do this.  Note: the '$DATA' suffix
877                  * seems to be unneeded.  Additional note: a "./" prefix needs
878                  * to be added when the path is not absolute to avoid ambiguity
879                  * with drive letters. */
880                 size_t stream_path_nchars;
881                 size_t path_nchars;
882                 size_t stream_name_nchars;
883                 const wchar_t *prefix;
884
885                 path_nchars = wcslen(path);
886                 stream_name_nchars = wcslen(stream_name_utf16);
887                 stream_path_nchars = path_nchars + 1 + stream_name_nchars;
888                 if (path[0] != cpu_to_le16(L'\0') &&
889                     path[0] != cpu_to_le16(L'/') &&
890                     path[0] != cpu_to_le16(L'\\') &&
891                     path[1] != cpu_to_le16(L':'))
892                 {
893                         prefix = L"./";
894                         stream_path_nchars += 2;
895                 } else {
896                         prefix = L"";
897                 }
898                 stream_path = alloca((stream_path_nchars + 1) * sizeof(wchar_t));
899                 swprintf(stream_path, stream_path_nchars + 1, L"%ls%ls:%ls",
900                          prefix, path, stream_name_utf16);
901         } else {
902                 /* Unnamed stream; its path is just the path to the file itself.
903                  * */
904                 stream_path = (wchar_t*)path;
905
906                 /* Directories must be created with CreateDirectoryW().  Then
907                  * the call to CreateFileW() will merely open the directory that
908                  * was already created rather than creating a new file. */
909                 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
910                         if (!CreateDirectoryW(stream_path, secattr)) {
911                                 err = GetLastError();
912                                 if (err != ERROR_ALREADY_EXISTS) {
913                                         ERROR("Failed to create directory \"%ls\"",
914                                               stream_path);
915                                         win32_error(err);
916                                         ret = WIMLIB_ERR_MKDIR;
917                                         goto fail;
918                                 }
919                         }
920                         DEBUG("Created directory \"%ls\"", stream_path);
921                         if (!(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
922                                 ret = 0;
923                                 goto out;
924                         }
925                         creationDisposition = OPEN_EXISTING;
926                 }
927         }
928
929         DEBUG("Opening \"%ls\"", stream_path);
930         h = CreateFileW(stream_path,
931                         GENERIC_WRITE,
932                         0,
933                         secattr,
934                         creationDisposition,
935                         FILE_FLAG_OPEN_REPARSE_POINT |
936                             FILE_FLAG_BACKUP_SEMANTICS |
937                             inode->i_attributes,
938                         NULL);
939         if (h == INVALID_HANDLE_VALUE) {
940                 err = GetLastError();
941                 ERROR("Failed to create \"%ls\"", stream_path);
942                 win32_error(err);
943                 ret = WIMLIB_ERR_OPEN;
944                 goto fail;
945         }
946
947         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT &&
948             stream_name_utf16 == NULL)
949         {
950                 DEBUG("Setting reparse data on \"%ls\"", path);
951                 ret = win32_set_reparse_data(h, inode->i_reparse_tag, lte, path);
952                 if (ret)
953                         goto fail_close_handle;
954         } else {
955                 if (lte) {
956                         DEBUG("Extracting \"%ls\" (len = %"PRIu64")",
957                               stream_path, wim_resource_size(lte));
958                         ret = do_win32_extract_stream(h, lte);
959                         if (ret)
960                                 goto fail_close_handle;
961                 }
962         }
963
964         DEBUG("Closing \"%ls\"", stream_path);
965         if (!CloseHandle(h)) {
966                 err = GetLastError();
967                 ERROR("Failed to close \"%ls\"", stream_path);
968                 win32_error(err);
969                 ret = WIMLIB_ERR_WRITE;
970                 goto fail;
971         }
972         ret = 0;
973         goto out;
974 fail_close_handle:
975         CloseHandle(h);
976 fail:
977         ERROR("Error extracting %ls", stream_path);
978 out:
979         return ret;
980 }
981
982 /*
983  * Creates a file, directory, or reparse point and extracts all streams to it
984  * (unnamed data stream and/or reparse point stream, plus any alternate data
985  * streams).  This in Win32-specific code.
986  *
987  * @inode:      WIM inode for this file or directory.
988  * @path:       UTF-16LE external path to extract the inode to.
989  *
990  * Returns 0 on success; nonzero on failure.
991  */
992 static int
993 win32_extract_streams(const struct wim_inode *inode,
994                       const wchar_t *path, u64 *completed_bytes_p,
995                       const struct wim_security_data *security_data)
996 {
997         struct wim_lookup_table_entry *unnamed_lte;
998         int ret;
999
1000         unnamed_lte = inode_unnamed_lte_resolved(inode);
1001         ret = win32_extract_stream(inode, path, NULL, unnamed_lte,
1002                                    security_data);
1003         if (ret)
1004                 goto out;
1005         if (unnamed_lte)
1006                 *completed_bytes_p += wim_resource_size(unnamed_lte);
1007         for (u16 i = 0; i < inode->i_num_ads; i++) {
1008                 const struct wim_ads_entry *ads_entry = &inode->i_ads_entries[i];
1009                 if (ads_entry->stream_name_nbytes != 0) {
1010                         /* Skip special UNIX data entries (see documentation for
1011                          * WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA) */
1012                         if (ads_entry->stream_name_nbytes == WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES
1013                             && !memcmp(ads_entry->stream_name,
1014                                        WIMLIB_UNIX_DATA_TAG_UTF16LE,
1015                                        WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES))
1016                                 continue;
1017                         ret = win32_extract_stream(inode,
1018                                                    path,
1019                                                    ads_entry->stream_name,
1020                                                    ads_entry->lte,
1021                                                    NULL);
1022                         if (ret)
1023                                 break;
1024                         if (ads_entry->lte)
1025                                 *completed_bytes_p += wim_resource_size(ads_entry->lte);
1026                 }
1027         }
1028 out:
1029         return ret;
1030 }
1031
1032 /* Extract a file, directory, reparse point, or hard link to an
1033  * already-extracted file using the Win32 API */
1034 int win32_do_apply_dentry(const mbchar *output_path,
1035                           size_t output_path_nbytes,
1036                           struct wim_dentry *dentry,
1037                           struct apply_args *args)
1038 {
1039         wchar_t *utf16le_path;
1040         size_t utf16le_path_nbytes;
1041         DWORD err;
1042         int ret;
1043         struct wim_inode *inode = dentry->d_inode;
1044
1045         ret = mbs_to_utf16le(output_path, output_path_nbytes,
1046                              &utf16le_path, &utf16le_path_nbytes);
1047         if (ret)
1048                 return ret;
1049
1050         if (inode->i_nlink > 1 && inode->i_extracted_file != NULL) {
1051                 /* Linked file, with another name already extracted.  Create a
1052                  * hard link. */
1053                 DEBUG("Creating hard link \"%ls => %ls\"",
1054                       utf16le_path, inode->i_extracted_file);
1055                 if (!CreateHardLinkW(utf16le_path, inode->i_extracted_file, NULL))
1056                 {
1057                         err = GetLastError();
1058                         ERROR("Can't create hard link \"%ls => %ls\"",
1059                               utf16le_path, inode->i_extracted_file);
1060                         ret = WIMLIB_ERR_LINK;
1061                         win32_error(err);
1062                 }
1063         } else {
1064                 /* Create the file, directory, or reparse point, and extract the
1065                  * data streams. */
1066                 const struct wim_security_data *security_data;
1067                 if (args->extract_flags & WIMLIB_EXTRACT_FLAG_NOACLS)
1068                         security_data = NULL;
1069                 else
1070                         security_data = wim_const_security_data(args->w);
1071
1072                 ret = win32_extract_streams(inode, utf16le_path,
1073                                             &args->progress.extract.completed_bytes,
1074                                             security_data);
1075                 if (ret)
1076                         goto out_free_utf16_path;
1077
1078                 if (inode->i_nlink > 1) {
1079                         /* Save extracted path for a later call to
1080                          * CreateHardLinkW() if this inode has multiple links.
1081                          * */
1082                         inode->i_extracted_file = utf16le_path;
1083                         goto out;
1084                 }
1085         }
1086 out_free_utf16_path:
1087         FREE(utf16le_path);
1088 out:
1089         return ret;
1090 }
1091
1092 /* Set timestamps on an extracted file using the Win32 API */
1093 int
1094 win32_do_apply_dentry_timestamps(const mbchar *output_path,
1095                                  size_t output_path_nbytes,
1096                                  const struct wim_dentry *dentry,
1097                                  const struct apply_args *args)
1098 {
1099         /* Win32 */
1100         wchar_t *utf16le_path;
1101         size_t utf16le_path_nbytes;
1102         DWORD err;
1103         HANDLE h;
1104         int ret;
1105         const struct wim_inode *inode = dentry->d_inode;
1106
1107         ret = mbs_to_utf16le(output_path, output_path_nbytes,
1108                             &utf16le_path, &utf16le_path_nbytes);
1109         if (ret)
1110                 return ret;
1111
1112         DEBUG("Opening \"%s\" to set timestamps", output_path);
1113         h = win32_open_existing_file(utf16le_path, FILE_WRITE_ATTRIBUTES);
1114
1115         if (h == INVALID_HANDLE_VALUE)
1116                 err = GetLastError();
1117         FREE(utf16le_path);
1118         if (h == INVALID_HANDLE_VALUE)
1119                 goto fail;
1120
1121         FILETIME creationTime = {.dwLowDateTime = inode->i_creation_time & 0xffffffff,
1122                                  .dwHighDateTime = inode->i_creation_time >> 32};
1123         FILETIME lastAccessTime = {.dwLowDateTime = inode->i_last_access_time & 0xffffffff,
1124                                   .dwHighDateTime = inode->i_last_access_time >> 32};
1125         FILETIME lastWriteTime = {.dwLowDateTime = inode->i_last_write_time & 0xffffffff,
1126                                   .dwHighDateTime = inode->i_last_write_time >> 32};
1127
1128         DEBUG("Calling SetFileTime() on \"%s\"", output_path);
1129         if (!SetFileTime(h, &creationTime, &lastAccessTime, &lastWriteTime)) {
1130                 err = GetLastError();
1131                 CloseHandle(h);
1132                 goto fail;
1133         }
1134         DEBUG("Closing \"%s\"", output_path);
1135         if (!CloseHandle(h)) {
1136                 err = GetLastError();
1137                 goto fail;
1138         }
1139         goto out;
1140 fail:
1141         /* Only warn if setting timestamps failed. */
1142         WARNING("Can't set timestamps on \"%s\"", output_path);
1143         win32_error(err);
1144 out:
1145         return 0;
1146 }
1147
1148 /* Replacement for POSIX fsync() */
1149 int
1150 fsync(int fd)
1151 {
1152         HANDLE h = (HANDLE)_get_osfhandle(fd);
1153         if (h == INVALID_HANDLE_VALUE) {
1154                 ERROR("Could not get Windows handle for file descriptor");
1155                 win32_error(GetLastError());
1156                 errno = EBADF;
1157                 return -1;
1158         }
1159         if (!FlushFileBuffers(h)) {
1160                 ERROR("Could not flush file buffers to disk");
1161                 win32_error(GetLastError());
1162                 errno = EIO;
1163                 return -1;
1164         }
1165         return 0;
1166 }
1167
1168 /* Use the Win32 API to get the number of processors */
1169 unsigned
1170 win32_get_number_of_processors()
1171 {
1172         SYSTEM_INFO sysinfo;
1173         GetSystemInfo(&sysinfo);
1174         return sysinfo.dwNumberOfProcessors;
1175 }
1176
1177 /* Replacement for POSIX-2008 realpath().  Warning: partial functionality only
1178  * (resolved_path must be NULL).   Also I highly doubt that GetFullPathName
1179  * really does the right thing under all circumstances. */
1180 mbchar *
1181 realpath(const mbchar *path, mbchar *resolved_path)
1182 {
1183         DWORD ret;
1184         wimlib_assert(resolved_path == NULL);
1185
1186         ret = GetFullPathNameA(path, 0, NULL, NULL);
1187         if (!ret)
1188                 goto fail_win32;
1189
1190         resolved_path = MALLOC(ret);
1191         if (!resolved_path)
1192                 goto fail;
1193         ret = GetFullPathNameA(path, ret, resolved_path, NULL);
1194         if (!ret) {
1195                 free(resolved_path);
1196                 goto fail_win32;
1197         }
1198         return resolved_path;
1199 fail_win32:
1200         win32_error(GetLastError());
1201 fail:
1202         return NULL;
1203 }
1204
1205 char *
1206 nl_langinfo(nl_item item)
1207 {
1208         wimlib_assert(item == CODESET);
1209         static char buf[64];
1210         strcpy(buf, "Unknown");
1211         return buf;
1212 }
1213
1214 /* rename() on Windows fails if the destination file exists.  Fix it. */
1215 int
1216 rename_replacement(const char *oldpath, const char *newpath)
1217 {
1218         if (MoveFileExA(oldpath, newpath, MOVEFILE_REPLACE_EXISTING)) {
1219                 return 0;
1220         } else {
1221                 /* As usual, the possible error values are not documented */
1222                 DWORD err = GetLastError();
1223                 ERROR("MoveFileExA(): Can't rename \"%s\" to \"%s\"",
1224                       oldpath, newpath);
1225                 win32_error(err);
1226                 errno = 0;
1227                 return -1;
1228         }
1229 }