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