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