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