Move code from win32_common.c to win32_apply.c
[wimlib] / src / win32_apply.c
1 /*
2  * win32_apply.c - Windows-specific code for applying files from a WIM image.
3  */
4
5 /*
6  * Copyright (C) 2013, 2014 Eric Biggers
7  *
8  * This file is part of wimlib, a library for working with WIM files.
9  *
10  * wimlib is free software; you can redistribute it and/or modify it under the
11  * terms of the GNU General Public License as published by the Free
12  * Software Foundation; either version 3 of the License, or (at your option)
13  * any later version.
14  *
15  * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
16  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
17  * A PARTICULAR PURPOSE. See the GNU General Public License for more
18  * details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with wimlib; if not, see http://www.gnu.org/licenses/.
22  */
23
24 #ifdef __WIN32__
25
26 #ifdef HAVE_CONFIG_H
27 #  include "config.h"
28 #endif
29
30 #include "wimlib/win32_common.h"
31
32 #include "wimlib/apply.h"
33 #include "wimlib/capture.h" /* for mangle_pat() and match_pattern_list()  */
34 #include "wimlib/dentry.h"
35 #include "wimlib/error.h"
36 #include "wimlib/lookup_table.h"
37 #include "wimlib/resource.h"
38 #include "wimlib/textfile.h"
39 #include "wimlib/xml.h"
40 #include "wimlib/wim.h"
41 #include "wimlib/wimboot.h"
42
43 struct win32_apply_private_data {
44         u64 data_source_id;
45         struct string_set *prepopulate_pats;
46         void *mem_prepopulate_pats;
47         u8 wim_lookup_table_hash[SHA1_HASH_SIZE];
48         bool wof_running;
49 };
50
51 static struct win32_apply_private_data *
52 get_private_data(struct apply_ctx *ctx)
53 {
54         BUILD_BUG_ON(sizeof(ctx->private) < sizeof(struct win32_apply_private_data));
55         return (struct win32_apply_private_data *)(ctx->private);
56 }
57
58 static void
59 free_prepopulate_pats(struct win32_apply_private_data *dat)
60 {
61         if (dat->prepopulate_pats) {
62                 FREE(dat->prepopulate_pats->strings);
63                 FREE(dat->prepopulate_pats);
64                 dat->prepopulate_pats = NULL;
65         }
66
67         if (dat->mem_prepopulate_pats) {
68                 FREE(dat->mem_prepopulate_pats);
69                 dat->mem_prepopulate_pats = NULL;
70         }
71 }
72
73 static int
74 load_prepopulate_pats(struct apply_ctx *ctx)
75 {
76         int ret;
77         struct wim_dentry *dentry;
78         struct wim_lookup_table_entry *lte;
79         struct string_set *s;
80         const tchar *path = WIMLIB_WIM_PATH_SEPARATOR_STRING T("Windows")
81                             WIMLIB_WIM_PATH_SEPARATOR_STRING T("System32")
82                             WIMLIB_WIM_PATH_SEPARATOR_STRING T("WimBootCompress.ini");
83         void *buf;
84         void *mem;
85         struct text_file_section sec;
86         struct win32_apply_private_data *dat = get_private_data(ctx);
87
88         dentry = get_dentry(ctx->wim, path, WIMLIB_CASE_INSENSITIVE);
89         if (!dentry ||
90             (dentry->d_inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
91                                               FILE_ATTRIBUTE_REPARSE_POINT |
92                                               FILE_ATTRIBUTE_ENCRYPTED)) ||
93             !(lte = inode_unnamed_lte(dentry->d_inode, ctx->wim->lookup_table)))
94         {
95                 WARNING("%"TS" does not exist in WIM image!", path);
96                 return WIMLIB_ERR_PATH_DOES_NOT_EXIST;
97         }
98
99         ret = read_full_stream_into_alloc_buf(lte, &buf);
100         if (ret)
101                 return ret;
102
103         s = CALLOC(1, sizeof(struct string_set));
104         if (!s) {
105                 FREE(buf);
106                 return WIMLIB_ERR_NOMEM;
107         }
108
109         sec.name = T("PrepopulateList");
110         sec.strings = s;
111
112         ret = do_load_text_file(path, buf, lte->size, &mem, &sec, 1,
113                                 LOAD_TEXT_FILE_REMOVE_QUOTES |
114                                         LOAD_TEXT_FILE_NO_WARNINGS,
115                                 mangle_pat);
116         BUILD_BUG_ON(OS_PREFERRED_PATH_SEPARATOR != WIM_PATH_SEPARATOR);
117         FREE(buf);
118         if (ret) {
119                 FREE(s);
120                 return ret;
121         }
122         dat->prepopulate_pats = s;
123         dat->mem_prepopulate_pats = mem;
124         return 0;
125 }
126
127 static bool
128 in_prepopulate_list(struct wim_dentry *dentry, struct apply_ctx *ctx)
129 {
130         struct string_set *pats;
131         const tchar *path;
132
133         pats = get_private_data(ctx)->prepopulate_pats;
134         if (!pats || !pats->num_strings)
135                 return false;
136
137         path = dentry_full_path(dentry);
138         if (!path)
139                 return false;
140
141         return match_pattern_list(path, tstrlen(path), pats);
142 }
143
144 static int
145 hash_lookup_table(WIMStruct *wim, u8 hash[SHA1_HASH_SIZE])
146 {
147         return wim_reshdr_to_hash(&wim->hdr.lookup_table_reshdr, wim, hash);
148 }
149
150 /* Given a Windows-style path, return the number of characters of the prefix
151  * that specify the path to the root directory of a drive, or return 0 if the
152  * drive is relative (or at least on the current drive, in the case of
153  * absolute-but-not-really-absolute paths like \Windows\System32) */
154 static size_t
155 win32_path_drive_spec_len(const wchar_t *path)
156 {
157         size_t n = 0;
158
159         if (!wcsncmp(path, L"\\\\?\\", 4)) {
160                 /* \\?\-prefixed path.  Check for following drive letter and
161                  * path separator. */
162                 if (path[4] != L'\0' && path[5] == L':' &&
163                     is_any_path_separator(path[6]))
164                         n = 7;
165         } else {
166                 /* Not a \\?\-prefixed path.  Check for an initial drive letter
167                  * and path separator. */
168                 if (path[0] != L'\0' && path[1] == L':' &&
169                     is_any_path_separator(path[2]))
170                         n = 3;
171         }
172         /* Include any additional path separators.*/
173         if (n > 0)
174                 while (is_any_path_separator(path[n]))
175                         n++;
176         return n;
177 }
178
179 static bool
180 win32_path_is_root_of_drive(const wchar_t *path)
181 {
182         size_t drive_spec_len;
183         wchar_t full_path[32768];
184         DWORD ret;
185
186         ret = GetFullPathName(path, ARRAY_LEN(full_path), full_path, NULL);
187         if (ret > 0 && ret < ARRAY_LEN(full_path))
188                 path = full_path;
189
190         /* Explicit drive letter and path separator? */
191         drive_spec_len = win32_path_drive_spec_len(path);
192         if (drive_spec_len > 0 && path[drive_spec_len] == L'\0')
193                 return true;
194
195         /* All path separators? */
196         for (const wchar_t *p = path; *p != L'\0'; p++)
197                 if (!is_any_path_separator(*p))
198                         return false;
199         return true;
200 }
201
202 /* Given a path, which may not yet exist, get a set of flags that describe the
203  * features of the volume the path is on. */
204 static int
205 win32_get_vol_flags(const wchar_t *path, unsigned *vol_flags_ret,
206                     bool *supports_SetFileShortName_ret)
207 {
208         wchar_t *volume;
209         BOOL bret;
210         DWORD vol_flags;
211         size_t drive_spec_len;
212         wchar_t filesystem_name[MAX_PATH + 1];
213
214         if (supports_SetFileShortName_ret)
215                 *supports_SetFileShortName_ret = false;
216
217         drive_spec_len = win32_path_drive_spec_len(path);
218
219         if (drive_spec_len == 0)
220                 if (path[0] != L'\0' && path[1] == L':') /* Drive-relative path? */
221                         drive_spec_len = 2;
222
223         if (drive_spec_len == 0) {
224                 /* Path does not start with a drive letter; use the volume of
225                  * the current working directory. */
226                 volume = NULL;
227         } else {
228                 /* Path starts with a drive letter (or \\?\ followed by a drive
229                  * letter); use it. */
230                 volume = alloca((drive_spec_len + 2) * sizeof(wchar_t));
231                 wmemcpy(volume, path, drive_spec_len);
232                 /* Add trailing backslash in case this was a drive-relative
233                  * path. */
234                 volume[drive_spec_len] = L'\\';
235                 volume[drive_spec_len + 1] = L'\0';
236         }
237         bret = GetVolumeInformation(
238                         volume,                         /* lpRootPathName */
239                         NULL,                           /* lpVolumeNameBuffer */
240                         0,                              /* nVolumeNameSize */
241                         NULL,                           /* lpVolumeSerialNumber */
242                         NULL,                           /* lpMaximumComponentLength */
243                         &vol_flags,                     /* lpFileSystemFlags */
244                         filesystem_name,                /* lpFileSystemNameBuffer */
245                         ARRAY_LEN(filesystem_name));    /* nFileSystemNameSize */
246         if (!bret) {
247                 set_errno_from_GetLastError();
248                 WARNING_WITH_ERRNO("Failed to get volume information for "
249                                    "path \"%ls\"", path);
250                 vol_flags = 0xffffffff;
251                 goto out;
252         }
253
254         if (wcsstr(filesystem_name, L"NTFS")) {
255                 /* FILE_SUPPORTS_HARD_LINKS is only supported on Windows 7 and later.
256                  * Force it on anyway if filesystem is NTFS.  */
257                 vol_flags |= FILE_SUPPORTS_HARD_LINKS;
258
259                 if (supports_SetFileShortName_ret)
260                         *supports_SetFileShortName_ret = true;
261         }
262
263 out:
264         DEBUG("using vol_flags = %x", vol_flags);
265         *vol_flags_ret = vol_flags;
266         return 0;
267 }
268
269 static int
270 win32_start_extract(const wchar_t *path, struct apply_ctx *ctx)
271 {
272         int ret;
273         unsigned vol_flags;
274         bool supports_SetFileShortName;
275         struct win32_apply_private_data *dat = get_private_data(ctx);
276
277         ret = win32_get_vol_flags(path, &vol_flags, &supports_SetFileShortName);
278         if (ret)
279                 goto err;
280
281         ctx->supported_features.archive_files = 1;
282         ctx->supported_features.hidden_files = 1;
283         ctx->supported_features.system_files = 1;
284
285         if (vol_flags & FILE_FILE_COMPRESSION)
286                 ctx->supported_features.compressed_files = 1;
287
288         if (vol_flags & FILE_SUPPORTS_ENCRYPTION) {
289                 ctx->supported_features.encrypted_files = 1;
290                 ctx->supported_features.encrypted_directories = 1;
291         }
292
293         ctx->supported_features.not_context_indexed_files = 1;
294
295         if (vol_flags & FILE_SUPPORTS_SPARSE_FILES)
296                 ctx->supported_features.sparse_files = 1;
297
298         if (vol_flags & FILE_NAMED_STREAMS)
299                 ctx->supported_features.named_data_streams = 1;
300
301         if (vol_flags & FILE_SUPPORTS_HARD_LINKS)
302                 ctx->supported_features.hard_links = 1;
303
304         if (vol_flags & FILE_SUPPORTS_REPARSE_POINTS) {
305                 ctx->supported_features.reparse_points = 1;
306                 if (func_CreateSymbolicLinkW)
307                         ctx->supported_features.symlink_reparse_points = 1;
308         }
309
310         if (vol_flags & FILE_PERSISTENT_ACLS)
311                 ctx->supported_features.security_descriptors = 1;
312
313         if (supports_SetFileShortName)
314                 ctx->supported_features.short_names = 1;
315
316         if (ctx->extract_flags & WIMLIB_EXTRACT_FLAG_WIMBOOT) {
317
318                 ret = load_prepopulate_pats(ctx);
319                 if (ret == WIMLIB_ERR_NOMEM)
320                         goto err;
321
322                 if (!wim_info_get_wimboot(ctx->wim->wim_info,
323                                           ctx->wim->current_image))
324                         WARNING("Image is not marked as WIMBoot compatible!");
325
326
327                 ret = hash_lookup_table(ctx->wim, dat->wim_lookup_table_hash);
328                 if (ret)
329                         goto err;
330
331                 ret = wimboot_alloc_data_source_id(ctx->wim->filename,
332                                                    ctx->wim->hdr.guid,
333                                                    ctx->wim->current_image,
334                                                    path,
335                                                    &dat->data_source_id,
336                                                    &dat->wof_running);
337                 if (ret)
338                         goto err;
339         }
340
341         return 0;
342
343 err:
344         free_prepopulate_pats(dat);
345         return ret;
346 }
347
348 static int
349 win32_finish_extract(struct apply_ctx *ctx)
350 {
351         free_prepopulate_pats(get_private_data(ctx));
352         return 0;
353 }
354
355 /* Delete a non-directory file, working around Windows quirks.  */
356 static BOOL
357 win32_delete_file_wrapper(const wchar_t *path)
358 {
359         DWORD err;
360         DWORD attrib;
361
362         if (DeleteFile(path))
363                 return TRUE;
364
365         err = GetLastError();
366         attrib = GetFileAttributes(path);
367         if ((attrib != INVALID_FILE_ATTRIBUTES) &&
368             (attrib & FILE_ATTRIBUTE_READONLY))
369         {
370                 /* Try again with FILE_ATTRIBUTE_READONLY cleared.  */
371                 attrib &= ~FILE_ATTRIBUTE_READONLY;
372                 if (SetFileAttributes(path, attrib)) {
373                         if (DeleteFile(path))
374                                 return TRUE;
375                         else
376                                 err = GetLastError();
377                 }
378         }
379
380         SetLastError(err);
381         return FALSE;
382 }
383
384
385 /* Create a normal file, overwriting one already present.  */
386 static int
387 win32_create_file(const wchar_t *path, struct apply_ctx *ctx, u64 *cookie_ret)
388 {
389         HANDLE h;
390
391         /* Notes:
392          *
393          * WRITE_OWNER and WRITE_DAC privileges are required for some reason,
394          * even through we're creating a new file.
395          *
396          * FILE_FLAG_OPEN_REPARSE_POINT is required to prevent an existing
397          * reparse point from redirecting the creation of the new file
398          * (potentially to an arbitrary location).
399          *
400          * CREATE_ALWAYS could be used instead of CREATE_NEW.  However, there
401          * are quirks that would need to be handled (e.g. having to set
402          * FILE_ATTRIBUTE_HIDDEN and/or FILE_ATTRIBUTE_SYSTEM if the existing
403          * file had them specified, and/or having to clear
404          * FILE_ATTRIBUTE_READONLY on the existing file).  It's simpler to just
405          * call win32_delete_file_wrapper() to delete the existing file in such
406          * a way that already handles the FILE_ATTRIBUTE_READONLY quirk.
407          */
408 retry:
409         h = CreateFile(path, WRITE_OWNER | WRITE_DAC, 0, NULL, CREATE_NEW,
410                        FILE_FLAG_BACKUP_SEMANTICS |
411                                 FILE_FLAG_OPEN_REPARSE_POINT, NULL);
412         if (h == INVALID_HANDLE_VALUE) {
413                 DWORD err = GetLastError();
414
415                 if (err == ERROR_FILE_EXISTS && win32_delete_file_wrapper(path))
416                         goto retry;
417                 set_errno_from_win32_error(err);
418                 return WIMLIB_ERR_OPEN;
419         }
420         CloseHandle(h);
421         return 0;
422 }
423
424 static int
425 win32_create_directory(const wchar_t *path, struct apply_ctx *ctx,
426                        u64 *cookie_ret)
427 {
428         if (!CreateDirectory(path, NULL))
429                 if (GetLastError() != ERROR_ALREADY_EXISTS)
430                         goto error;
431         return 0;
432
433 error:
434         set_errno_from_GetLastError();
435         return WIMLIB_ERR_MKDIR;
436 }
437
438 static int
439 win32_create_hardlink(const wchar_t *oldpath, const wchar_t *newpath,
440                       struct apply_ctx *ctx)
441 {
442         if (!CreateHardLink(newpath, oldpath, NULL)) {
443                 if (GetLastError() != ERROR_ALREADY_EXISTS)
444                         goto error;
445                 if (!win32_delete_file_wrapper(newpath))
446                         goto error;
447                 if (!CreateHardLink(newpath, oldpath, NULL))
448                         goto error;
449         }
450         return 0;
451
452 error:
453         set_errno_from_GetLastError();
454         return WIMLIB_ERR_LINK;
455 }
456
457 static int
458 win32_create_symlink(const wchar_t *oldpath, const wchar_t *newpath,
459                      struct apply_ctx *ctx)
460 {
461         if (!(*func_CreateSymbolicLinkW)(newpath, oldpath, 0)) {
462                 if (GetLastError() != ERROR_ALREADY_EXISTS)
463                         goto error;
464                 if (!win32_delete_file_wrapper(newpath))
465                         goto error;
466                 if (!(*func_CreateSymbolicLinkW)(newpath, oldpath, 0))
467                         goto error;
468         }
469         return 0;
470
471 error:
472         set_errno_from_GetLastError();
473         return WIMLIB_ERR_LINK;
474 }
475
476 static int
477 win32_extract_wim_chunk(const void *buf, size_t len, void *arg)
478 {
479         HANDLE h = (HANDLE)arg;
480         DWORD nbytes_written;
481
482         if (unlikely(!WriteFile(h, buf, len, &nbytes_written, NULL)))
483                 goto error;
484         if (unlikely(nbytes_written != len))
485                 goto error;
486         return 0;
487
488 error:
489         set_errno_from_GetLastError();
490         return WIMLIB_ERR_WRITE;
491 }
492
493 static int
494 win32_extract_stream(const wchar_t *path, const wchar_t *stream_name,
495                      size_t stream_name_nchars,
496                      struct wim_lookup_table_entry *lte, struct apply_ctx *ctx)
497 {
498         DWORD creationDisposition = OPEN_EXISTING;
499         wchar_t *stream_path = (wchar_t*)path;
500         HANDLE h;
501         int ret;
502
503         if (stream_name_nchars) {
504                 creationDisposition = CREATE_ALWAYS;
505                 stream_path = alloca(sizeof(wchar_t) *
506                                      (wcslen(path) + 1 +
507                                       wcslen(stream_name) + 1));
508                 tsprintf(stream_path, L"%ls:%ls", path, stream_name);
509         }
510
511         h = CreateFile(stream_path, FILE_WRITE_DATA, 0, NULL,
512                        creationDisposition, FILE_FLAG_BACKUP_SEMANTICS |
513                                             FILE_FLAG_OPEN_REPARSE_POINT,
514                        NULL);
515         if (h == INVALID_HANDLE_VALUE) {
516                 set_errno_from_GetLastError();
517                 ret = WIMLIB_ERR_OPEN;
518                 goto out;
519         }
520
521         if (!lte) {
522                 ret = 0;
523                 goto out_close_handle;
524         }
525
526         if (!SetFilePointerEx(h,
527                               (LARGE_INTEGER) { .QuadPart = lte->size},
528                               NULL,
529                               FILE_BEGIN))
530                 goto write_error;
531
532         if (!SetEndOfFile(h))
533                 goto write_error;
534
535         if (!SetFilePointerEx(h,
536                               (LARGE_INTEGER) { .QuadPart = 0},
537                               NULL,
538                               FILE_BEGIN))
539                 goto write_error;
540
541         ret = extract_stream(lte, lte->size, win32_extract_wim_chunk, h);
542         goto out_close_handle;
543
544 write_error:
545         set_errno_from_GetLastError();
546         ret = WIMLIB_ERR_WRITE;
547
548 out_close_handle:
549         if (!CloseHandle(h)) {
550                 if (!ret) {
551                         set_errno_from_GetLastError();
552                         ret = WIMLIB_ERR_WRITE;
553                 }
554         }
555 out:
556         return ret;
557 }
558
559 static int
560 win32_extract_unnamed_stream(file_spec_t file,
561                              struct wim_lookup_table_entry *lte,
562                              struct apply_ctx *ctx,
563                              struct wim_dentry *dentry)
564 {
565         if (ctx->extract_flags & WIMLIB_EXTRACT_FLAG_WIMBOOT
566             && lte
567             && lte->resource_location == RESOURCE_IN_WIM
568             && lte->rspec->wim == ctx->wim
569             && lte->size == lte->rspec->uncompressed_size)
570         {
571                 if (in_prepopulate_list(dentry, ctx)) {
572                         if (ctx->progress_func) {
573                                 union wimlib_progress_info info;
574
575                                 info.wimboot_exclude.path_in_wim = dentry->_full_path;
576                                 info.wimboot_exclude.extraction_path = file.path;
577
578                                 ctx->progress_func(WIMLIB_PROGRESS_MSG_WIMBOOT_EXCLUDE,
579                                                    &info);
580                         }
581                 } else {
582                         const struct win32_apply_private_data *dat;
583
584                         dat = get_private_data(ctx);
585                         return wimboot_set_pointer(file.path, lte,
586                                                    dat->data_source_id,
587                                                    dat->wim_lookup_table_hash,
588                                                    dat->wof_running);
589                 }
590         }
591
592         return win32_extract_stream(file.path, NULL, 0, lte, ctx);
593 }
594
595 static int
596 win32_extract_named_stream(file_spec_t file, const wchar_t *stream_name,
597                            size_t stream_name_nchars,
598                            struct wim_lookup_table_entry *lte, struct apply_ctx *ctx)
599 {
600         return win32_extract_stream(file.path, stream_name,
601                                     stream_name_nchars, lte, ctx);
602 }
603
604 struct win32_encrypted_extract_ctx {
605         const struct wim_lookup_table_entry *lte;
606         u64 offset;
607 };
608
609 static DWORD WINAPI
610 win32_encrypted_import_cb(unsigned char *data, void *_import_ctx,
611                           unsigned long *len_p)
612 {
613         struct win32_encrypted_extract_ctx *import_ctx = _import_ctx;
614         unsigned long len = *len_p;
615         const struct wim_lookup_table_entry *lte = import_ctx->lte;
616
617         len = min(len, lte->size - import_ctx->offset);
618
619         if (read_partial_wim_stream_into_buf(lte, len, import_ctx->offset, data))
620                 return ERROR_READ_FAULT;
621
622         import_ctx->offset += len;
623         *len_p = len;
624         return ERROR_SUCCESS;
625 }
626
627 static int
628 win32_extract_encrypted_stream(const wchar_t *path,
629                                struct wim_lookup_table_entry *lte,
630                                struct apply_ctx *ctx)
631 {
632         void *file_ctx;
633         DWORD err;
634         int ret;
635         struct win32_encrypted_extract_ctx extract_ctx;
636
637         err = OpenEncryptedFileRaw(path, CREATE_FOR_IMPORT, &file_ctx);
638         if (err != ERROR_SUCCESS) {
639                 set_errno_from_win32_error(err);
640                 ret = WIMLIB_ERR_OPEN;
641                 goto out;
642         }
643
644         extract_ctx.lte = lte;
645         extract_ctx.offset = 0;
646         err = WriteEncryptedFileRaw(win32_encrypted_import_cb, &extract_ctx,
647                                     file_ctx);
648         if (err != ERROR_SUCCESS) {
649                 set_errno_from_win32_error(err);
650                 ret = WIMLIB_ERR_WRITE;
651                 goto out_close;
652         }
653
654         ret = 0;
655 out_close:
656         CloseEncryptedFileRaw(file_ctx);
657 out:
658         return ret;
659 }
660
661 static BOOL
662 win32_set_special_file_attributes(const wchar_t *path, u32 attributes)
663 {
664         HANDLE h;
665         DWORD err;
666         USHORT compression_format = COMPRESSION_FORMAT_DEFAULT;
667         DWORD bytes_returned;
668
669         h = win32_open_existing_file(path, GENERIC_READ | GENERIC_WRITE);
670         if (h == INVALID_HANDLE_VALUE)
671                 goto error;
672
673         if (attributes & FILE_ATTRIBUTE_SPARSE_FILE)
674                 if (!DeviceIoControl(h, FSCTL_SET_SPARSE,
675                                      NULL, 0,
676                                      NULL, 0,
677                                      &bytes_returned, NULL))
678                         goto error_close_handle;
679
680         if (attributes & FILE_ATTRIBUTE_COMPRESSED)
681                 if (!DeviceIoControl(h, FSCTL_SET_COMPRESSION,
682                                      &compression_format, sizeof(USHORT),
683                                      NULL, 0,
684                                      &bytes_returned, NULL))
685                         goto error_close_handle;
686
687         if (!CloseHandle(h))
688                 goto error;
689
690         if (attributes & FILE_ATTRIBUTE_ENCRYPTED)
691                 if (!EncryptFile(path))
692                         goto error;
693
694         return TRUE;
695
696 error_close_handle:
697         err = GetLastError();
698         CloseHandle(h);
699         SetLastError(err);
700 error:
701         return FALSE;
702 }
703
704 static int
705 win32_set_file_attributes(const wchar_t *path, u32 attributes,
706                           struct apply_ctx *ctx, unsigned pass)
707 {
708         u32 special_attributes =
709                 FILE_ATTRIBUTE_REPARSE_POINT |
710                 FILE_ATTRIBUTE_DIRECTORY |
711                 FILE_ATTRIBUTE_SPARSE_FILE |
712                 FILE_ATTRIBUTE_COMPRESSED |
713                 FILE_ATTRIBUTE_ENCRYPTED;
714         u32 actual_attributes;
715
716         /* Delay setting FILE_ATTRIBUTE_READONLY on the initial pass (when files
717          * are created, but data not extracted); otherwise the system will
718          * refuse access to the file even if the process has SeRestorePrivilege.
719          */
720         if (pass == 0)
721                 attributes &= ~FILE_ATTRIBUTE_READONLY;
722
723         if (!SetFileAttributes(path, attributes & ~special_attributes))
724                 goto error;
725
726         if (pass != 0)
727                 return 0;
728
729         if (attributes & (FILE_ATTRIBUTE_SPARSE_FILE |
730                           FILE_ATTRIBUTE_ENCRYPTED |
731                           FILE_ATTRIBUTE_COMPRESSED))
732                 if (!win32_set_special_file_attributes(path, attributes))
733                         goto error;
734
735         /* If file is not supposed to be encrypted or compressed, remove
736          * defaulted encrypted or compressed attributes (from creating file in
737          * encrypted or compressed directory).  */
738         actual_attributes = GetFileAttributes(path);
739         if (actual_attributes == INVALID_FILE_ATTRIBUTES)
740                 goto error;
741
742         if ((actual_attributes & FILE_ATTRIBUTE_ENCRYPTED) &&
743             !(attributes & FILE_ATTRIBUTE_ENCRYPTED))
744                 if (!DecryptFile(path, 0))
745                         goto error;
746         if ((actual_attributes & FILE_ATTRIBUTE_COMPRESSED) &&
747             !(attributes & FILE_ATTRIBUTE_COMPRESSED))
748         {
749                 HANDLE h;
750                 DWORD bytes_returned;
751                 USHORT compression_format = COMPRESSION_FORMAT_NONE;
752
753                 h = win32_open_existing_file(path, GENERIC_READ | GENERIC_WRITE);
754                 if (h == INVALID_HANDLE_VALUE)
755                         goto error;
756
757                 if (!DeviceIoControl(h, FSCTL_SET_COMPRESSION,
758                                      &compression_format, sizeof(USHORT),
759                                      NULL, 0,
760                                      &bytes_returned, NULL))
761                 {
762                         DWORD err = GetLastError();
763                         CloseHandle(h);
764                         SetLastError(err);
765                         goto error;
766                 }
767
768                 if (!CloseHandle(h))
769                         goto error;
770         }
771
772         return 0;
773
774 error:
775         set_errno_from_GetLastError();
776         return WIMLIB_ERR_SET_ATTRIBUTES;
777 }
778
779 static int
780 win32_set_reparse_data(const wchar_t *path, const u8 *rpbuf, u16 rpbuflen,
781                        struct apply_ctx *ctx)
782 {
783         HANDLE h;
784         DWORD err;
785         DWORD bytes_returned;
786
787         h = win32_open_existing_file(path, GENERIC_WRITE);
788         if (h == INVALID_HANDLE_VALUE)
789                 goto error;
790
791         if (!DeviceIoControl(h, FSCTL_SET_REPARSE_POINT,
792                              (void*)rpbuf, rpbuflen,
793                              NULL, 0, &bytes_returned, NULL))
794                 goto error_close_handle;
795
796         if (!CloseHandle(h))
797                 goto error;
798
799         return 0;
800
801 error_close_handle:
802         err = GetLastError();
803         CloseHandle(h);
804         SetLastError(err);
805 error:
806         set_errno_from_GetLastError();
807         return WIMLIB_ERR_WRITE; /* XXX: need better error code */
808 }
809
810 static int
811 win32_set_short_name(const wchar_t *path, const wchar_t *short_name,
812                      size_t short_name_nchars, struct apply_ctx *ctx)
813 {
814         HANDLE h;
815         DWORD err;
816
817         h = win32_open_existing_file(path, GENERIC_WRITE | DELETE);
818         if (h == INVALID_HANDLE_VALUE)
819                 goto error;
820
821         if (short_name_nchars) {
822                 if (!SetFileShortName(h, short_name))
823                         goto error_close_handle;
824         } else if (running_on_windows_7_or_later()) {
825                 if (!SetFileShortName(h, L""))
826                         goto error_close_handle;
827         }
828
829         if (!CloseHandle(h))
830                 goto error;
831
832         return 0;
833
834 error_close_handle:
835         err = GetLastError();
836         CloseHandle(h);
837         SetLastError(err);
838 error:
839         set_errno_from_GetLastError();
840         return WIMLIB_ERR_WRITE; /* XXX: need better error code */
841 }
842
843 /*
844  * Set an arbitrary security descriptor on an arbitrary file (or directory),
845  * working around bugs and design flaws in the Windows operating system.
846  *
847  * On success, return 0.  On failure, return WIMLIB_ERR_SET_SECURITY and set
848  * errno.  Note: if WIMLIB_EXTRACT_FLAG_STRICT_ACLS is not set in
849  * ctx->extract_flags, this function succeeds iff any part of the security
850  * descriptor was successfully set.
851  */
852 static int
853 win32_set_security_descriptor(const wchar_t *path, const u8 *desc,
854                               size_t desc_size, struct apply_ctx *ctx)
855 {
856         SECURITY_INFORMATION info;
857         DWORD dwDesiredAccess;
858         HANDLE h;
859         DWORD status;
860         int ret;
861
862         /* We really just want to set entire the security descriptor as-is, but
863          * all available APIs require specifying the specific parts of the
864          * descriptor being set.  Start out by requesting all parts be set.  If
865          * permissions problems are encountered, fall back to omitting some
866          * parts (first the SACL, then the DACL, then the owner), unless the
867          * WIMLIB_EXTRACT_FLAG_STRICT_ACLS flag has been enabled.  */
868         info = OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION |
869                DACL_SECURITY_INFORMATION  | SACL_SECURITY_INFORMATION;
870
871         /* Prefer NtSetSecurityObject() to SetFileSecurity().  SetFileSecurity()
872          * itself necessarily uses NtSetSecurityObject() as the latter is the
873          * underlying system call for setting security information, but
874          * SetFileSecurity() opens the handle with NtCreateFile() without
875          * FILE_OPEN_FILE_BACKUP_INTENT.  Hence, access checks are done and due
876          * to the Windows security model, even a process running as the
877          * Administrator can have access denied.  (Of course, this not mentioned
878          * in the MS "documentation".)  */
879
880         /* Open a handle for NtSetSecurityObject() with as many relevant
881          * access rights as possible.
882          *
883          * We don't know which rights will be actually granted.  It
884          * could be less than what is needed to actually assign the full
885          * security descriptor, especially if the process is running as
886          * a non-Administrator.  However, by default we just do the best
887          * we can, unless WIMLIB_EXTRACT_FLAG_STRICT_ACLS has been
888          * enabled.  The MAXIMUM_ALLOWED access right is seemingly
889          * designed for this use case; however, it does not work
890          * properly in all cases: it can cause CreateFile() to fail with
891          * ERROR_ACCESS_DENIED, even though by definition
892          * MAXIMUM_ALLOWED access only requests access rights that are
893          * *not* denied.  (Needless to say, MS does not document this
894          * bug.)  */
895
896         dwDesiredAccess = WRITE_DAC | WRITE_OWNER | ACCESS_SYSTEM_SECURITY;
897         while ((h = win32_open_existing_file(path,
898                                              dwDesiredAccess)) == INVALID_HANDLE_VALUE)
899         {
900                 DWORD err;
901
902                 err = GetLastError();
903                 if (err == ERROR_ACCESS_DENIED ||
904                     err == ERROR_PRIVILEGE_NOT_HELD)
905                 {
906                         /* Don't increment partial_security_descriptors
907                          * here or check WIMLIB_EXTRACT_FLAG_STRICT_ACLS
908                          * here.  It will be done later if needed; here
909                          * we are just trying to get as many relevant
910                          * access rights as possible.  */
911                         if (dwDesiredAccess & ACCESS_SYSTEM_SECURITY) {
912                                 dwDesiredAccess &= ~ACCESS_SYSTEM_SECURITY;
913                                 continue;
914                         }
915                         if (dwDesiredAccess & WRITE_DAC) {
916                                 dwDesiredAccess &= ~WRITE_DAC;
917                                 continue;
918                         }
919                         if (dwDesiredAccess & WRITE_OWNER) {
920                                 dwDesiredAccess &= ~WRITE_OWNER;
921                                 continue;
922                         }
923                 }
924                 /* Other error, or couldn't open the file even with no
925                  * access rights specified.  Something else must be
926                  * wrong.  */
927                 set_errno_from_win32_error(err);
928                 return WIMLIB_ERR_SET_SECURITY;
929         }
930
931         /* Try setting the security descriptor.  */
932         ret = 0;
933         while (!(NT_SUCCESS(status = (*func_NtSetSecurityObject)(h,
934                                                                  info,
935                                                                  (PSECURITY_DESCRIPTOR)desc))))
936         {
937                 /* Failed to set the requested parts of the security descriptor.
938                  * If the error was permissions-related, try to set fewer parts
939                  * of the security descriptor, unless
940                  * WIMLIB_EXTRACT_FLAG_STRICT_ACLS is enabled.  */
941                 if ((status == STATUS_PRIVILEGE_NOT_HELD ||
942                      status == STATUS_ACCESS_DENIED) &&
943                     !(ctx->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS))
944                 {
945                         if (info & SACL_SECURITY_INFORMATION) {
946                                 info &= ~SACL_SECURITY_INFORMATION;
947                                 ctx->partial_security_descriptors++;
948                                 continue;
949                         }
950                         if (info & DACL_SECURITY_INFORMATION) {
951                                 info &= ~DACL_SECURITY_INFORMATION;
952                                 continue;
953                         }
954                         if (info & OWNER_SECURITY_INFORMATION) {
955                                 info &= ~OWNER_SECURITY_INFORMATION;
956                                 continue;
957                         }
958                         /* Nothing left except GROUP, and if we removed it we
959                          * wouldn't have anything at all.  */
960                 }
961                 /* No part of the security descriptor could be set, or
962                  * WIMLIB_EXTRACT_FLAG_STRICT_ACLS is enabled and the full
963                  * security descriptor could not be set.  */
964                 if (!(info & SACL_SECURITY_INFORMATION))
965                         ctx->partial_security_descriptors--;
966                 set_errno_from_nt_status(status);
967                 ret = WIMLIB_ERR_SET_SECURITY;
968                 break;
969         }
970
971         /* Close handle opened for NtSetSecurityObject().  */
972         CloseHandle(h);
973         return ret;
974 }
975
976 static int
977 win32_set_timestamps(const wchar_t *path, u64 creation_time,
978                      u64 last_write_time, u64 last_access_time,
979                      struct apply_ctx *ctx)
980 {
981         HANDLE h;
982         DWORD err;
983         FILETIME creationTime = {.dwLowDateTime = creation_time & 0xffffffff,
984                                  .dwHighDateTime = creation_time >> 32};
985         FILETIME lastAccessTime = {.dwLowDateTime = last_access_time & 0xffffffff,
986                                   .dwHighDateTime = last_access_time >> 32};
987         FILETIME lastWriteTime = {.dwLowDateTime = last_write_time & 0xffffffff,
988                                   .dwHighDateTime = last_write_time >> 32};
989
990         h = win32_open_existing_file(path, FILE_WRITE_ATTRIBUTES);
991         if (h == INVALID_HANDLE_VALUE)
992                 goto error;
993
994         if (!SetFileTime(h, &creationTime, &lastAccessTime, &lastWriteTime))
995                 goto error_close_handle;
996
997         if (!CloseHandle(h))
998                 goto error;
999
1000         return 0;
1001
1002 error_close_handle:
1003         err = GetLastError();
1004         CloseHandle(h);
1005         SetLastError(err);
1006 error:
1007         set_errno_from_GetLastError();
1008         return WIMLIB_ERR_SET_TIMESTAMPS;
1009 }
1010
1011 const struct apply_operations win32_apply_ops = {
1012         .name = L"Win32",
1013
1014         .target_is_root           = win32_path_is_root_of_drive,
1015         .start_extract            = win32_start_extract,
1016         .finish_extract           = win32_finish_extract,
1017         .abort_extract            = win32_finish_extract,
1018         .create_file              = win32_create_file,
1019         .create_directory         = win32_create_directory,
1020         .create_hardlink          = win32_create_hardlink,
1021         .create_symlink           = win32_create_symlink,
1022         .extract_unnamed_stream   = win32_extract_unnamed_stream,
1023         .extract_named_stream     = win32_extract_named_stream,
1024         .extract_encrypted_stream = win32_extract_encrypted_stream,
1025         .set_file_attributes      = win32_set_file_attributes,
1026         .set_reparse_data         = win32_set_reparse_data,
1027         .set_short_name           = win32_set_short_name,
1028         .set_security_descriptor  = win32_set_security_descriptor,
1029         .set_timestamps           = win32_set_timestamps,
1030
1031         .path_prefix = L"\\\\?\\",
1032         .path_prefix_nchars = 4,
1033         .path_separator = L'\\',
1034         .path_max = 32768,
1035
1036         .requires_realtarget_in_paths = 1,
1037         .realpath_works_on_nonexisting_files = 1,
1038         .root_directory_is_special = 1,
1039         .requires_final_set_attributes_pass = 1,
1040         .extract_encrypted_stream_creates_file = 1,
1041         .requires_short_name_reordering = 1, /* TODO: check if this is really needed  */
1042 };
1043
1044 #endif /* __WIN32__ */