win32_apply.c: Call match_pattern_list() from in_prepopulate_list()
[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 static int
151 win32_start_extract(const wchar_t *path, struct apply_ctx *ctx)
152 {
153         int ret;
154         unsigned vol_flags;
155         bool supports_SetFileShortName;
156         struct win32_apply_private_data *dat = get_private_data(ctx);
157
158         ret = win32_get_vol_flags(path, &vol_flags, &supports_SetFileShortName);
159         if (ret)
160                 goto err;
161
162         ctx->supported_features.archive_files = 1;
163         ctx->supported_features.hidden_files = 1;
164         ctx->supported_features.system_files = 1;
165
166         if (vol_flags & FILE_FILE_COMPRESSION)
167                 ctx->supported_features.compressed_files = 1;
168
169         if (vol_flags & FILE_SUPPORTS_ENCRYPTION) {
170                 ctx->supported_features.encrypted_files = 1;
171                 ctx->supported_features.encrypted_directories = 1;
172         }
173
174         ctx->supported_features.not_context_indexed_files = 1;
175
176         if (vol_flags & FILE_SUPPORTS_SPARSE_FILES)
177                 ctx->supported_features.sparse_files = 1;
178
179         if (vol_flags & FILE_NAMED_STREAMS)
180                 ctx->supported_features.named_data_streams = 1;
181
182         if (vol_flags & FILE_SUPPORTS_HARD_LINKS)
183                 ctx->supported_features.hard_links = 1;
184
185         if (vol_flags & FILE_SUPPORTS_REPARSE_POINTS) {
186                 ctx->supported_features.reparse_points = 1;
187                 if (func_CreateSymbolicLinkW)
188                         ctx->supported_features.symlink_reparse_points = 1;
189         }
190
191         if (vol_flags & FILE_PERSISTENT_ACLS)
192                 ctx->supported_features.security_descriptors = 1;
193
194         if (supports_SetFileShortName)
195                 ctx->supported_features.short_names = 1;
196
197         if (ctx->extract_flags & WIMLIB_EXTRACT_FLAG_WIMBOOT) {
198
199                 ret = load_prepopulate_pats(ctx);
200                 if (ret == WIMLIB_ERR_NOMEM)
201                         goto err;
202
203                 if (!wim_info_get_wimboot(ctx->wim->wim_info,
204                                           ctx->wim->current_image))
205                         WARNING("Image is not marked as WIMBoot compatible!");
206
207
208                 ret = hash_lookup_table(ctx->wim, dat->wim_lookup_table_hash);
209                 if (ret)
210                         goto err;
211
212                 ret = wimboot_alloc_data_source_id(ctx->wim->filename,
213                                                    ctx->wim->hdr.guid,
214                                                    ctx->wim->current_image,
215                                                    path,
216                                                    &dat->data_source_id,
217                                                    &dat->wof_running);
218                 if (ret)
219                         goto err;
220         }
221
222         return 0;
223
224 err:
225         free_prepopulate_pats(dat);
226         return ret;
227 }
228
229 static int
230 win32_finish_extract(struct apply_ctx *ctx)
231 {
232         free_prepopulate_pats(get_private_data(ctx));
233         return 0;
234 }
235
236 /* Delete a non-directory file, working around Windows quirks.  */
237 static BOOL
238 win32_delete_file_wrapper(const wchar_t *path)
239 {
240         DWORD err;
241         DWORD attrib;
242
243         if (DeleteFile(path))
244                 return TRUE;
245
246         err = GetLastError();
247         attrib = GetFileAttributes(path);
248         if ((attrib != INVALID_FILE_ATTRIBUTES) &&
249             (attrib & FILE_ATTRIBUTE_READONLY))
250         {
251                 /* Try again with FILE_ATTRIBUTE_READONLY cleared.  */
252                 attrib &= ~FILE_ATTRIBUTE_READONLY;
253                 if (SetFileAttributes(path, attrib)) {
254                         if (DeleteFile(path))
255                                 return TRUE;
256                         else
257                                 err = GetLastError();
258                 }
259         }
260
261         SetLastError(err);
262         return FALSE;
263 }
264
265
266 /* Create a normal file, overwriting one already present.  */
267 static int
268 win32_create_file(const wchar_t *path, struct apply_ctx *ctx, u64 *cookie_ret)
269 {
270         HANDLE h;
271
272         /* Notes:
273          *
274          * WRITE_OWNER and WRITE_DAC privileges are required for some reason,
275          * even through we're creating a new file.
276          *
277          * FILE_FLAG_OPEN_REPARSE_POINT is required to prevent an existing
278          * reparse point from redirecting the creation of the new file
279          * (potentially to an arbitrary location).
280          *
281          * CREATE_ALWAYS could be used instead of CREATE_NEW.  However, there
282          * are quirks that would need to be handled (e.g. having to set
283          * FILE_ATTRIBUTE_HIDDEN and/or FILE_ATTRIBUTE_SYSTEM if the existing
284          * file had them specified, and/or having to clear
285          * FILE_ATTRIBUTE_READONLY on the existing file).  It's simpler to just
286          * call win32_delete_file_wrapper() to delete the existing file in such
287          * a way that already handles the FILE_ATTRIBUTE_READONLY quirk.
288          */
289 retry:
290         h = CreateFile(path, WRITE_OWNER | WRITE_DAC, 0, NULL, CREATE_NEW,
291                        FILE_FLAG_BACKUP_SEMANTICS |
292                                 FILE_FLAG_OPEN_REPARSE_POINT, NULL);
293         if (h == INVALID_HANDLE_VALUE) {
294                 DWORD err = GetLastError();
295
296                 if (err == ERROR_FILE_EXISTS && win32_delete_file_wrapper(path))
297                         goto retry;
298                 set_errno_from_win32_error(err);
299                 return WIMLIB_ERR_OPEN;
300         }
301         CloseHandle(h);
302         return 0;
303 }
304
305 static int
306 win32_create_directory(const wchar_t *path, struct apply_ctx *ctx,
307                        u64 *cookie_ret)
308 {
309         if (!CreateDirectory(path, NULL))
310                 if (GetLastError() != ERROR_ALREADY_EXISTS)
311                         goto error;
312         return 0;
313
314 error:
315         set_errno_from_GetLastError();
316         return WIMLIB_ERR_MKDIR;
317 }
318
319 static int
320 win32_create_hardlink(const wchar_t *oldpath, const wchar_t *newpath,
321                       struct apply_ctx *ctx)
322 {
323         if (!CreateHardLink(newpath, oldpath, NULL)) {
324                 if (GetLastError() != ERROR_ALREADY_EXISTS)
325                         goto error;
326                 if (!win32_delete_file_wrapper(newpath))
327                         goto error;
328                 if (!CreateHardLink(newpath, oldpath, NULL))
329                         goto error;
330         }
331         return 0;
332
333 error:
334         set_errno_from_GetLastError();
335         return WIMLIB_ERR_LINK;
336 }
337
338 static int
339 win32_create_symlink(const wchar_t *oldpath, const wchar_t *newpath,
340                      struct apply_ctx *ctx)
341 {
342         if (!(*func_CreateSymbolicLinkW)(newpath, oldpath, 0)) {
343                 if (GetLastError() != ERROR_ALREADY_EXISTS)
344                         goto error;
345                 if (!win32_delete_file_wrapper(newpath))
346                         goto error;
347                 if (!(*func_CreateSymbolicLinkW)(newpath, oldpath, 0))
348                         goto error;
349         }
350         return 0;
351
352 error:
353         set_errno_from_GetLastError();
354         return WIMLIB_ERR_LINK;
355 }
356
357 static int
358 win32_extract_wim_chunk(const void *buf, size_t len, void *arg)
359 {
360         HANDLE h = (HANDLE)arg;
361         DWORD nbytes_written;
362
363         if (unlikely(!WriteFile(h, buf, len, &nbytes_written, NULL)))
364                 goto error;
365         if (unlikely(nbytes_written != len))
366                 goto error;
367         return 0;
368
369 error:
370         set_errno_from_GetLastError();
371         return WIMLIB_ERR_WRITE;
372 }
373
374 static int
375 win32_extract_stream(const wchar_t *path, const wchar_t *stream_name,
376                      size_t stream_name_nchars,
377                      struct wim_lookup_table_entry *lte, struct apply_ctx *ctx)
378 {
379         DWORD creationDisposition = OPEN_EXISTING;
380         wchar_t *stream_path = (wchar_t*)path;
381         HANDLE h;
382         int ret;
383
384         if (stream_name_nchars) {
385                 creationDisposition = CREATE_ALWAYS;
386                 stream_path = alloca(sizeof(wchar_t) *
387                                      (wcslen(path) + 1 +
388                                       wcslen(stream_name) + 1));
389                 tsprintf(stream_path, L"%ls:%ls", path, stream_name);
390         }
391
392         h = CreateFile(stream_path, FILE_WRITE_DATA, 0, NULL,
393                        creationDisposition, FILE_FLAG_BACKUP_SEMANTICS |
394                                             FILE_FLAG_OPEN_REPARSE_POINT,
395                        NULL);
396         if (h == INVALID_HANDLE_VALUE) {
397                 set_errno_from_GetLastError();
398                 ret = WIMLIB_ERR_OPEN;
399                 goto out;
400         }
401
402         if (!lte) {
403                 ret = 0;
404                 goto out_close_handle;
405         }
406
407         if (!SetFilePointerEx(h,
408                               (LARGE_INTEGER) { .QuadPart = lte->size},
409                               NULL,
410                               FILE_BEGIN))
411                 goto write_error;
412
413         if (!SetEndOfFile(h))
414                 goto write_error;
415
416         if (!SetFilePointerEx(h,
417                               (LARGE_INTEGER) { .QuadPart = 0},
418                               NULL,
419                               FILE_BEGIN))
420                 goto write_error;
421
422         ret = extract_stream(lte, lte->size, win32_extract_wim_chunk, h);
423         goto out_close_handle;
424
425 write_error:
426         set_errno_from_GetLastError();
427         ret = WIMLIB_ERR_WRITE;
428
429 out_close_handle:
430         if (!CloseHandle(h)) {
431                 if (!ret) {
432                         set_errno_from_GetLastError();
433                         ret = WIMLIB_ERR_WRITE;
434                 }
435         }
436 out:
437         return ret;
438 }
439
440 static int
441 win32_extract_unnamed_stream(file_spec_t file,
442                              struct wim_lookup_table_entry *lte,
443                              struct apply_ctx *ctx,
444                              struct wim_dentry *dentry)
445 {
446         if (ctx->extract_flags & WIMLIB_EXTRACT_FLAG_WIMBOOT
447             && lte
448             && lte->resource_location == RESOURCE_IN_WIM
449             && lte->rspec->wim == ctx->wim
450             && lte->size == lte->rspec->uncompressed_size)
451         {
452                 if (in_prepopulate_list(dentry, ctx)) {
453                         if (ctx->progress_func) {
454                                 union wimlib_progress_info info;
455
456                                 info.wimboot_exclude.path_in_wim = dentry->_full_path;
457                                 info.wimboot_exclude.extraction_path = file.path;
458
459                                 ctx->progress_func(WIMLIB_PROGRESS_MSG_WIMBOOT_EXCLUDE,
460                                                    &info);
461                         }
462                 } else {
463                         const struct win32_apply_private_data *dat;
464
465                         dat = get_private_data(ctx);
466                         return wimboot_set_pointer(file.path, lte,
467                                                    dat->data_source_id,
468                                                    dat->wim_lookup_table_hash,
469                                                    dat->wof_running);
470                 }
471         }
472
473         return win32_extract_stream(file.path, NULL, 0, lte, ctx);
474 }
475
476 static int
477 win32_extract_named_stream(file_spec_t file, const wchar_t *stream_name,
478                            size_t stream_name_nchars,
479                            struct wim_lookup_table_entry *lte, struct apply_ctx *ctx)
480 {
481         return win32_extract_stream(file.path, stream_name,
482                                     stream_name_nchars, lte, ctx);
483 }
484
485 struct win32_encrypted_extract_ctx {
486         const struct wim_lookup_table_entry *lte;
487         u64 offset;
488 };
489
490 static DWORD WINAPI
491 win32_encrypted_import_cb(unsigned char *data, void *_import_ctx,
492                           unsigned long *len_p)
493 {
494         struct win32_encrypted_extract_ctx *import_ctx = _import_ctx;
495         unsigned long len = *len_p;
496         const struct wim_lookup_table_entry *lte = import_ctx->lte;
497
498         len = min(len, lte->size - import_ctx->offset);
499
500         if (read_partial_wim_stream_into_buf(lte, len, import_ctx->offset, data))
501                 return ERROR_READ_FAULT;
502
503         import_ctx->offset += len;
504         *len_p = len;
505         return ERROR_SUCCESS;
506 }
507
508 static int
509 win32_extract_encrypted_stream(const wchar_t *path,
510                                struct wim_lookup_table_entry *lte,
511                                struct apply_ctx *ctx)
512 {
513         void *file_ctx;
514         DWORD err;
515         int ret;
516         struct win32_encrypted_extract_ctx extract_ctx;
517
518         err = OpenEncryptedFileRaw(path, CREATE_FOR_IMPORT, &file_ctx);
519         if (err != ERROR_SUCCESS) {
520                 set_errno_from_win32_error(err);
521                 ret = WIMLIB_ERR_OPEN;
522                 goto out;
523         }
524
525         extract_ctx.lte = lte;
526         extract_ctx.offset = 0;
527         err = WriteEncryptedFileRaw(win32_encrypted_import_cb, &extract_ctx,
528                                     file_ctx);
529         if (err != ERROR_SUCCESS) {
530                 set_errno_from_win32_error(err);
531                 ret = WIMLIB_ERR_WRITE;
532                 goto out_close;
533         }
534
535         ret = 0;
536 out_close:
537         CloseEncryptedFileRaw(file_ctx);
538 out:
539         return ret;
540 }
541
542 static BOOL
543 win32_set_special_file_attributes(const wchar_t *path, u32 attributes)
544 {
545         HANDLE h;
546         DWORD err;
547         USHORT compression_format = COMPRESSION_FORMAT_DEFAULT;
548         DWORD bytes_returned;
549
550         h = win32_open_existing_file(path, GENERIC_READ | GENERIC_WRITE);
551         if (h == INVALID_HANDLE_VALUE)
552                 goto error;
553
554         if (attributes & FILE_ATTRIBUTE_SPARSE_FILE)
555                 if (!DeviceIoControl(h, FSCTL_SET_SPARSE,
556                                      NULL, 0,
557                                      NULL, 0,
558                                      &bytes_returned, NULL))
559                         goto error_close_handle;
560
561         if (attributes & FILE_ATTRIBUTE_COMPRESSED)
562                 if (!DeviceIoControl(h, FSCTL_SET_COMPRESSION,
563                                      &compression_format, sizeof(USHORT),
564                                      NULL, 0,
565                                      &bytes_returned, NULL))
566                         goto error_close_handle;
567
568         if (!CloseHandle(h))
569                 goto error;
570
571         if (attributes & FILE_ATTRIBUTE_ENCRYPTED)
572                 if (!EncryptFile(path))
573                         goto error;
574
575         return TRUE;
576
577 error_close_handle:
578         err = GetLastError();
579         CloseHandle(h);
580         SetLastError(err);
581 error:
582         return FALSE;
583 }
584
585 static int
586 win32_set_file_attributes(const wchar_t *path, u32 attributes,
587                           struct apply_ctx *ctx, unsigned pass)
588 {
589         u32 special_attributes =
590                 FILE_ATTRIBUTE_REPARSE_POINT |
591                 FILE_ATTRIBUTE_DIRECTORY |
592                 FILE_ATTRIBUTE_SPARSE_FILE |
593                 FILE_ATTRIBUTE_COMPRESSED |
594                 FILE_ATTRIBUTE_ENCRYPTED;
595         u32 actual_attributes;
596
597         /* Delay setting FILE_ATTRIBUTE_READONLY on the initial pass (when files
598          * are created, but data not extracted); otherwise the system will
599          * refuse access to the file even if the process has SeRestorePrivilege.
600          */
601         if (pass == 0)
602                 attributes &= ~FILE_ATTRIBUTE_READONLY;
603
604         if (!SetFileAttributes(path, attributes & ~special_attributes))
605                 goto error;
606
607         if (pass != 0)
608                 return 0;
609
610         if (attributes & (FILE_ATTRIBUTE_SPARSE_FILE |
611                           FILE_ATTRIBUTE_ENCRYPTED |
612                           FILE_ATTRIBUTE_COMPRESSED))
613                 if (!win32_set_special_file_attributes(path, attributes))
614                         goto error;
615
616         /* If file is not supposed to be encrypted or compressed, remove
617          * defaulted encrypted or compressed attributes (from creating file in
618          * encrypted or compressed directory).  */
619         actual_attributes = GetFileAttributes(path);
620         if (actual_attributes == INVALID_FILE_ATTRIBUTES)
621                 goto error;
622
623         if ((actual_attributes & FILE_ATTRIBUTE_ENCRYPTED) &&
624             !(attributes & FILE_ATTRIBUTE_ENCRYPTED))
625                 if (!DecryptFile(path, 0))
626                         goto error;
627         if ((actual_attributes & FILE_ATTRIBUTE_COMPRESSED) &&
628             !(attributes & FILE_ATTRIBUTE_COMPRESSED))
629         {
630                 HANDLE h;
631                 DWORD bytes_returned;
632                 USHORT compression_format = COMPRESSION_FORMAT_NONE;
633
634                 h = win32_open_existing_file(path, GENERIC_READ | GENERIC_WRITE);
635                 if (h == INVALID_HANDLE_VALUE)
636                         goto error;
637
638                 if (!DeviceIoControl(h, FSCTL_SET_COMPRESSION,
639                                      &compression_format, sizeof(USHORT),
640                                      NULL, 0,
641                                      &bytes_returned, NULL))
642                 {
643                         DWORD err = GetLastError();
644                         CloseHandle(h);
645                         SetLastError(err);
646                         goto error;
647                 }
648
649                 if (!CloseHandle(h))
650                         goto error;
651         }
652
653         return 0;
654
655 error:
656         set_errno_from_GetLastError();
657         return WIMLIB_ERR_SET_ATTRIBUTES;
658 }
659
660 static int
661 win32_set_reparse_data(const wchar_t *path, const u8 *rpbuf, u16 rpbuflen,
662                        struct apply_ctx *ctx)
663 {
664         HANDLE h;
665         DWORD err;
666         DWORD bytes_returned;
667
668         h = win32_open_existing_file(path, GENERIC_WRITE);
669         if (h == INVALID_HANDLE_VALUE)
670                 goto error;
671
672         if (!DeviceIoControl(h, FSCTL_SET_REPARSE_POINT,
673                              (void*)rpbuf, rpbuflen,
674                              NULL, 0, &bytes_returned, NULL))
675                 goto error_close_handle;
676
677         if (!CloseHandle(h))
678                 goto error;
679
680         return 0;
681
682 error_close_handle:
683         err = GetLastError();
684         CloseHandle(h);
685         SetLastError(err);
686 error:
687         set_errno_from_GetLastError();
688         return WIMLIB_ERR_WRITE; /* XXX: need better error code */
689 }
690
691 static int
692 win32_set_short_name(const wchar_t *path, const wchar_t *short_name,
693                      size_t short_name_nchars, struct apply_ctx *ctx)
694 {
695         HANDLE h;
696         DWORD err;
697
698         h = win32_open_existing_file(path, GENERIC_WRITE | DELETE);
699         if (h == INVALID_HANDLE_VALUE)
700                 goto error;
701
702         if (short_name_nchars) {
703                 if (!SetFileShortName(h, short_name))
704                         goto error_close_handle;
705         } else if (running_on_windows_7_or_later()) {
706                 if (!SetFileShortName(h, L""))
707                         goto error_close_handle;
708         }
709
710         if (!CloseHandle(h))
711                 goto error;
712
713         return 0;
714
715 error_close_handle:
716         err = GetLastError();
717         CloseHandle(h);
718         SetLastError(err);
719 error:
720         set_errno_from_GetLastError();
721         return WIMLIB_ERR_WRITE; /* XXX: need better error code */
722 }
723
724 /*
725  * Set an arbitrary security descriptor on an arbitrary file (or directory),
726  * working around bugs and design flaws in the Windows operating system.
727  *
728  * On success, return 0.  On failure, return WIMLIB_ERR_SET_SECURITY and set
729  * errno.  Note: if WIMLIB_EXTRACT_FLAG_STRICT_ACLS is not set in
730  * ctx->extract_flags, this function succeeds iff any part of the security
731  * descriptor was successfully set.
732  */
733 static int
734 win32_set_security_descriptor(const wchar_t *path, const u8 *desc,
735                               size_t desc_size, struct apply_ctx *ctx)
736 {
737         SECURITY_INFORMATION info;
738         DWORD dwDesiredAccess;
739         HANDLE h;
740         DWORD status;
741         int ret;
742
743         /* We really just want to set entire the security descriptor as-is, but
744          * all available APIs require specifying the specific parts of the
745          * descriptor being set.  Start out by requesting all parts be set.  If
746          * permissions problems are encountered, fall back to omitting some
747          * parts (first the SACL, then the DACL, then the owner), unless the
748          * WIMLIB_EXTRACT_FLAG_STRICT_ACLS flag has been enabled.  */
749         info = OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION |
750                DACL_SECURITY_INFORMATION  | SACL_SECURITY_INFORMATION;
751
752         /* Prefer NtSetSecurityObject() to SetFileSecurity().  SetFileSecurity()
753          * itself necessarily uses NtSetSecurityObject() as the latter is the
754          * underlying system call for setting security information, but
755          * SetFileSecurity() opens the handle with NtCreateFile() without
756          * FILE_OPEN_FILE_BACKUP_INTENT.  Hence, access checks are done and due
757          * to the Windows security model, even a process running as the
758          * Administrator can have access denied.  (Of course, this not mentioned
759          * in the MS "documentation".)  */
760
761         /* Open a handle for NtSetSecurityObject() with as many relevant
762          * access rights as possible.
763          *
764          * We don't know which rights will be actually granted.  It
765          * could be less than what is needed to actually assign the full
766          * security descriptor, especially if the process is running as
767          * a non-Administrator.  However, by default we just do the best
768          * we can, unless WIMLIB_EXTRACT_FLAG_STRICT_ACLS has been
769          * enabled.  The MAXIMUM_ALLOWED access right is seemingly
770          * designed for this use case; however, it does not work
771          * properly in all cases: it can cause CreateFile() to fail with
772          * ERROR_ACCESS_DENIED, even though by definition
773          * MAXIMUM_ALLOWED access only requests access rights that are
774          * *not* denied.  (Needless to say, MS does not document this
775          * bug.)  */
776
777         dwDesiredAccess = WRITE_DAC | WRITE_OWNER | ACCESS_SYSTEM_SECURITY;
778         while ((h = win32_open_existing_file(path,
779                                              dwDesiredAccess)) == INVALID_HANDLE_VALUE)
780         {
781                 DWORD err;
782
783                 err = GetLastError();
784                 if (err == ERROR_ACCESS_DENIED ||
785                     err == ERROR_PRIVILEGE_NOT_HELD)
786                 {
787                         /* Don't increment partial_security_descriptors
788                          * here or check WIMLIB_EXTRACT_FLAG_STRICT_ACLS
789                          * here.  It will be done later if needed; here
790                          * we are just trying to get as many relevant
791                          * access rights as possible.  */
792                         if (dwDesiredAccess & ACCESS_SYSTEM_SECURITY) {
793                                 dwDesiredAccess &= ~ACCESS_SYSTEM_SECURITY;
794                                 continue;
795                         }
796                         if (dwDesiredAccess & WRITE_DAC) {
797                                 dwDesiredAccess &= ~WRITE_DAC;
798                                 continue;
799                         }
800                         if (dwDesiredAccess & WRITE_OWNER) {
801                                 dwDesiredAccess &= ~WRITE_OWNER;
802                                 continue;
803                         }
804                 }
805                 /* Other error, or couldn't open the file even with no
806                  * access rights specified.  Something else must be
807                  * wrong.  */
808                 set_errno_from_win32_error(err);
809                 return WIMLIB_ERR_SET_SECURITY;
810         }
811
812         /* Try setting the security descriptor.  */
813         ret = 0;
814         while (!(NT_SUCCESS(status = (*func_NtSetSecurityObject)(h,
815                                                                  info,
816                                                                  (PSECURITY_DESCRIPTOR)desc))))
817         {
818                 /* Failed to set the requested parts of the security descriptor.
819                  * If the error was permissions-related, try to set fewer parts
820                  * of the security descriptor, unless
821                  * WIMLIB_EXTRACT_FLAG_STRICT_ACLS is enabled.  */
822                 if ((status == STATUS_PRIVILEGE_NOT_HELD ||
823                      status == STATUS_ACCESS_DENIED) &&
824                     !(ctx->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS))
825                 {
826                         if (info & SACL_SECURITY_INFORMATION) {
827                                 info &= ~SACL_SECURITY_INFORMATION;
828                                 ctx->partial_security_descriptors++;
829                                 continue;
830                         }
831                         if (info & DACL_SECURITY_INFORMATION) {
832                                 info &= ~DACL_SECURITY_INFORMATION;
833                                 continue;
834                         }
835                         if (info & OWNER_SECURITY_INFORMATION) {
836                                 info &= ~OWNER_SECURITY_INFORMATION;
837                                 continue;
838                         }
839                         /* Nothing left except GROUP, and if we removed it we
840                          * wouldn't have anything at all.  */
841                 }
842                 /* No part of the security descriptor could be set, or
843                  * WIMLIB_EXTRACT_FLAG_STRICT_ACLS is enabled and the full
844                  * security descriptor could not be set.  */
845                 if (!(info & SACL_SECURITY_INFORMATION))
846                         ctx->partial_security_descriptors--;
847                 set_errno_from_nt_status(status);
848                 ret = WIMLIB_ERR_SET_SECURITY;
849                 break;
850         }
851
852         /* Close handle opened for NtSetSecurityObject().  */
853         CloseHandle(h);
854         return ret;
855 }
856
857 static int
858 win32_set_timestamps(const wchar_t *path, u64 creation_time,
859                      u64 last_write_time, u64 last_access_time,
860                      struct apply_ctx *ctx)
861 {
862         HANDLE h;
863         DWORD err;
864         FILETIME creationTime = {.dwLowDateTime = creation_time & 0xffffffff,
865                                  .dwHighDateTime = creation_time >> 32};
866         FILETIME lastAccessTime = {.dwLowDateTime = last_access_time & 0xffffffff,
867                                   .dwHighDateTime = last_access_time >> 32};
868         FILETIME lastWriteTime = {.dwLowDateTime = last_write_time & 0xffffffff,
869                                   .dwHighDateTime = last_write_time >> 32};
870
871         h = win32_open_existing_file(path, FILE_WRITE_ATTRIBUTES);
872         if (h == INVALID_HANDLE_VALUE)
873                 goto error;
874
875         if (!SetFileTime(h, &creationTime, &lastAccessTime, &lastWriteTime))
876                 goto error_close_handle;
877
878         if (!CloseHandle(h))
879                 goto error;
880
881         return 0;
882
883 error_close_handle:
884         err = GetLastError();
885         CloseHandle(h);
886         SetLastError(err);
887 error:
888         set_errno_from_GetLastError();
889         return WIMLIB_ERR_SET_TIMESTAMPS;
890 }
891
892 const struct apply_operations win32_apply_ops = {
893         .name = L"Win32",
894
895         .target_is_root           = win32_path_is_root_of_drive,
896         .start_extract            = win32_start_extract,
897         .finish_extract           = win32_finish_extract,
898         .abort_extract            = win32_finish_extract,
899         .create_file              = win32_create_file,
900         .create_directory         = win32_create_directory,
901         .create_hardlink          = win32_create_hardlink,
902         .create_symlink           = win32_create_symlink,
903         .extract_unnamed_stream   = win32_extract_unnamed_stream,
904         .extract_named_stream     = win32_extract_named_stream,
905         .extract_encrypted_stream = win32_extract_encrypted_stream,
906         .set_file_attributes      = win32_set_file_attributes,
907         .set_reparse_data         = win32_set_reparse_data,
908         .set_short_name           = win32_set_short_name,
909         .set_security_descriptor  = win32_set_security_descriptor,
910         .set_timestamps           = win32_set_timestamps,
911
912         .path_prefix = L"\\\\?\\",
913         .path_prefix_nchars = 4,
914         .path_separator = L'\\',
915         .path_max = 32768,
916
917         .requires_realtarget_in_paths = 1,
918         .realpath_works_on_nonexisting_files = 1,
919         .root_directory_is_special = 1,
920         .requires_final_set_attributes_pass = 1,
921         .extract_encrypted_stream_creates_file = 1,
922         .requires_short_name_reordering = 1, /* TODO: check if this is really needed  */
923 };
924
925 #endif /* __WIN32__ */