]> wimlib.net Git - wimlib/blob - src/win32_apply.c
c78683b75f618ed867a2643bbffa54eb451ad2be
[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             && !in_prepopulate_list(dentry, ctx))
436         {
437                 const struct win32_apply_private_data *dat;
438
439                 dat = get_private_data(ctx);
440                 return wimboot_set_pointer(file.path, lte,
441                                            dat->data_source_id,
442                                            dat->wim_lookup_table_hash,
443                                            dat->wof_running);
444         }
445
446         return win32_extract_stream(file.path, NULL, 0, lte, ctx);
447 }
448
449 static int
450 win32_extract_named_stream(file_spec_t file, const wchar_t *stream_name,
451                            size_t stream_name_nchars,
452                            struct wim_lookup_table_entry *lte, struct apply_ctx *ctx)
453 {
454         return win32_extract_stream(file.path, stream_name,
455                                     stream_name_nchars, lte, ctx);
456 }
457
458 struct win32_encrypted_extract_ctx {
459         const struct wim_lookup_table_entry *lte;
460         u64 offset;
461 };
462
463 static DWORD WINAPI
464 win32_encrypted_import_cb(unsigned char *data, void *_import_ctx,
465                           unsigned long *len_p)
466 {
467         struct win32_encrypted_extract_ctx *import_ctx = _import_ctx;
468         unsigned long len = *len_p;
469         const struct wim_lookup_table_entry *lte = import_ctx->lte;
470
471         len = min(len, lte->size - import_ctx->offset);
472
473         if (read_partial_wim_stream_into_buf(lte, len, import_ctx->offset, data))
474                 return ERROR_READ_FAULT;
475
476         import_ctx->offset += len;
477         *len_p = len;
478         return ERROR_SUCCESS;
479 }
480
481 static int
482 win32_extract_encrypted_stream(const wchar_t *path,
483                                struct wim_lookup_table_entry *lte,
484                                struct apply_ctx *ctx)
485 {
486         void *file_ctx;
487         DWORD err;
488         int ret;
489         struct win32_encrypted_extract_ctx extract_ctx;
490
491         err = OpenEncryptedFileRaw(path, CREATE_FOR_IMPORT, &file_ctx);
492         if (err != ERROR_SUCCESS) {
493                 set_errno_from_win32_error(err);
494                 ret = WIMLIB_ERR_OPEN;
495                 goto out;
496         }
497
498         extract_ctx.lte = lte;
499         extract_ctx.offset = 0;
500         err = WriteEncryptedFileRaw(win32_encrypted_import_cb, &extract_ctx,
501                                     file_ctx);
502         if (err != ERROR_SUCCESS) {
503                 set_errno_from_win32_error(err);
504                 ret = WIMLIB_ERR_WRITE;
505                 goto out_close;
506         }
507
508         ret = 0;
509 out_close:
510         CloseEncryptedFileRaw(file_ctx);
511 out:
512         return ret;
513 }
514
515 static BOOL
516 win32_set_special_file_attributes(const wchar_t *path, u32 attributes)
517 {
518         HANDLE h;
519         DWORD err;
520         USHORT compression_format = COMPRESSION_FORMAT_DEFAULT;
521         DWORD bytes_returned;
522
523         h = win32_open_existing_file(path, GENERIC_READ | GENERIC_WRITE);
524         if (h == INVALID_HANDLE_VALUE)
525                 goto error;
526
527         if (attributes & FILE_ATTRIBUTE_SPARSE_FILE)
528                 if (!DeviceIoControl(h, FSCTL_SET_SPARSE,
529                                      NULL, 0,
530                                      NULL, 0,
531                                      &bytes_returned, NULL))
532                         goto error_close_handle;
533
534         if (attributes & FILE_ATTRIBUTE_COMPRESSED)
535                 if (!DeviceIoControl(h, FSCTL_SET_COMPRESSION,
536                                      &compression_format, sizeof(USHORT),
537                                      NULL, 0,
538                                      &bytes_returned, NULL))
539                         goto error_close_handle;
540
541         if (!CloseHandle(h))
542                 goto error;
543
544         if (attributes & FILE_ATTRIBUTE_ENCRYPTED)
545                 if (!EncryptFile(path))
546                         goto error;
547
548         return TRUE;
549
550 error_close_handle:
551         err = GetLastError();
552         CloseHandle(h);
553         SetLastError(err);
554 error:
555         return FALSE;
556 }
557
558 static int
559 win32_set_file_attributes(const wchar_t *path, u32 attributes,
560                           struct apply_ctx *ctx, unsigned pass)
561 {
562         u32 special_attributes =
563                 FILE_ATTRIBUTE_REPARSE_POINT |
564                 FILE_ATTRIBUTE_DIRECTORY |
565                 FILE_ATTRIBUTE_SPARSE_FILE |
566                 FILE_ATTRIBUTE_COMPRESSED |
567                 FILE_ATTRIBUTE_ENCRYPTED;
568         u32 actual_attributes;
569
570         /* Delay setting FILE_ATTRIBUTE_READONLY on the initial pass (when files
571          * are created, but data not extracted); otherwise the system will
572          * refuse access to the file even if the process has SeRestorePrivilege.
573          */
574         if (pass == 0)
575                 attributes &= ~FILE_ATTRIBUTE_READONLY;
576
577         if (!SetFileAttributes(path, attributes & ~special_attributes))
578                 goto error;
579
580         if (pass != 0)
581                 return 0;
582
583         if (attributes & (FILE_ATTRIBUTE_SPARSE_FILE |
584                           FILE_ATTRIBUTE_ENCRYPTED |
585                           FILE_ATTRIBUTE_COMPRESSED))
586                 if (!win32_set_special_file_attributes(path, attributes))
587                         goto error;
588
589         /* If file is not supposed to be encrypted or compressed, remove
590          * defaulted encrypted or compressed attributes (from creating file in
591          * encrypted or compressed directory).  */
592         actual_attributes = GetFileAttributes(path);
593         if (actual_attributes == INVALID_FILE_ATTRIBUTES)
594                 goto error;
595
596         if ((actual_attributes & FILE_ATTRIBUTE_ENCRYPTED) &&
597             !(attributes & FILE_ATTRIBUTE_ENCRYPTED))
598                 if (!DecryptFile(path, 0))
599                         goto error;
600         if ((actual_attributes & FILE_ATTRIBUTE_COMPRESSED) &&
601             !(attributes & FILE_ATTRIBUTE_COMPRESSED))
602         {
603                 HANDLE h;
604                 DWORD bytes_returned;
605                 USHORT compression_format = COMPRESSION_FORMAT_NONE;
606
607                 h = win32_open_existing_file(path, GENERIC_READ | GENERIC_WRITE);
608                 if (h == INVALID_HANDLE_VALUE)
609                         goto error;
610
611                 if (!DeviceIoControl(h, FSCTL_SET_COMPRESSION,
612                                      &compression_format, sizeof(USHORT),
613                                      NULL, 0,
614                                      &bytes_returned, NULL))
615                 {
616                         DWORD err = GetLastError();
617                         CloseHandle(h);
618                         SetLastError(err);
619                         goto error;
620                 }
621
622                 if (!CloseHandle(h))
623                         goto error;
624         }
625
626         return 0;
627
628 error:
629         set_errno_from_GetLastError();
630         return WIMLIB_ERR_SET_ATTRIBUTES;
631 }
632
633 static int
634 win32_set_reparse_data(const wchar_t *path, const u8 *rpbuf, u16 rpbuflen,
635                        struct apply_ctx *ctx)
636 {
637         HANDLE h;
638         DWORD err;
639         DWORD bytes_returned;
640
641         h = win32_open_existing_file(path, GENERIC_WRITE);
642         if (h == INVALID_HANDLE_VALUE)
643                 goto error;
644
645         if (!DeviceIoControl(h, FSCTL_SET_REPARSE_POINT,
646                              (void*)rpbuf, rpbuflen,
647                              NULL, 0, &bytes_returned, NULL))
648                 goto error_close_handle;
649
650         if (!CloseHandle(h))
651                 goto error;
652
653         return 0;
654
655 error_close_handle:
656         err = GetLastError();
657         CloseHandle(h);
658         SetLastError(err);
659 error:
660         set_errno_from_GetLastError();
661         return WIMLIB_ERR_WRITE; /* XXX: need better error code */
662 }
663
664 static int
665 win32_set_short_name(const wchar_t *path, const wchar_t *short_name,
666                      size_t short_name_nchars, struct apply_ctx *ctx)
667 {
668         HANDLE h;
669         DWORD err;
670
671         h = win32_open_existing_file(path, GENERIC_WRITE | DELETE);
672         if (h == INVALID_HANDLE_VALUE)
673                 goto error;
674
675         if (short_name_nchars) {
676                 if (!SetFileShortName(h, short_name))
677                         goto error_close_handle;
678         } else if (running_on_windows_7_or_later()) {
679                 if (!SetFileShortName(h, L""))
680                         goto error_close_handle;
681         }
682
683         if (!CloseHandle(h))
684                 goto error;
685
686         return 0;
687
688 error_close_handle:
689         err = GetLastError();
690         CloseHandle(h);
691         SetLastError(err);
692 error:
693         set_errno_from_GetLastError();
694         return WIMLIB_ERR_WRITE; /* XXX: need better error code */
695 }
696
697 static DWORD
698 do_win32_set_security_descriptor(HANDLE h, const wchar_t *path,
699                                  SECURITY_INFORMATION info,
700                                  PSECURITY_DESCRIPTOR desc)
701 {
702 #ifdef WITH_NTDLL
703         if (func_NtSetSecurityObject) {
704                 return (*func_RtlNtStatusToDosError)(
705                                 (*func_NtSetSecurityObject)(h, info, desc));
706         }
707 #endif
708         if (SetFileSecurity(path, info, desc))
709                 return ERROR_SUCCESS;
710         else
711                 return GetLastError();
712 }
713
714 /*
715  * Set an arbitrary security descriptor on an arbitrary file (or directory),
716  * working around bugs and design flaws in the Windows operating system.
717  *
718  * On success, return 0.  On failure, return WIMLIB_ERR_SET_SECURITY and set
719  * errno.  Note: if WIMLIB_EXTRACT_FLAG_STRICT_ACLS is not set in
720  * ctx->extract_flags, this function succeeds iff any part of the security
721  * descriptor was successfully set.
722  */
723 static int
724 win32_set_security_descriptor(const wchar_t *path, const u8 *desc,
725                               size_t desc_size, struct apply_ctx *ctx)
726 {
727         SECURITY_INFORMATION info;
728         HANDLE h;
729         int ret;
730
731         /* We really just want to set entire the security descriptor as-is, but
732          * all available APIs require specifying the specific parts of the
733          * descriptor being set.  Start out by requesting all parts be set.  If
734          * permissions problems are encountered, fall back to omitting some
735          * parts (first the SACL, then the DACL, then the owner), unless the
736          * WIMLIB_EXTRACT_FLAG_STRICT_ACLS flag has been enabled.  */
737         info = OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION |
738                DACL_SECURITY_INFORMATION  | SACL_SECURITY_INFORMATION;
739
740         h = INVALID_HANDLE_VALUE;
741
742         /* Prefer NtSetSecurityObject() to SetFileSecurity().  SetFileSecurity()
743          * itself necessarily uses NtSetSecurityObject() as the latter is the
744          * underlying system call for setting security information, but
745          * SetFileSecurity() opens the handle with NtCreateFile() without
746          * FILE_OPEN_FILE_BACKUP_INTENT.  Hence, access checks are done and due
747          * to the Windows security model, even a process running as the
748          * Administrator can have access denied.  (Of course, this not mentioned
749          * in the MS "documentation".)  */
750
751 #ifdef WITH_NTDLL
752         if (func_NtSetSecurityObject) {
753                 DWORD dwDesiredAccess;
754
755                 /* Open a handle for NtSetSecurityObject() with as many relevant
756                  * access rights as possible.
757                  *
758                  * We don't know which rights will be actually granted.  It
759                  * could be less than what is needed to actually assign the full
760                  * security descriptor, especially if the process is running as
761                  * a non-Administrator.  However, by default we just do the best
762                  * we can, unless WIMLIB_EXTRACT_FLAG_STRICT_ACLS has been
763                  * enabled.  The MAXIMUM_ALLOWED access right is seemingly
764                  * designed for this use case; however, it does not work
765                  * properly in all cases: it can cause CreateFile() to fail with
766                  * ERROR_ACCESS_DENIED, even though by definition
767                  * MAXIMUM_ALLOWED access only requests access rights that are
768                  * *not* denied.  (Needless to say, MS does not document this
769                  * bug.)  */
770
771                 dwDesiredAccess = WRITE_DAC |
772                                   WRITE_OWNER |
773                                   ACCESS_SYSTEM_SECURITY;
774                 for (;;) {
775                         DWORD err;
776
777                         h = win32_open_existing_file(path, dwDesiredAccess);
778                         if (h != INVALID_HANDLE_VALUE)
779                                 break;
780                         err = GetLastError();
781                         if (err == ERROR_ACCESS_DENIED ||
782                             err == ERROR_PRIVILEGE_NOT_HELD)
783                         {
784                                 /* Don't increment partial_security_descriptors
785                                  * here or check WIMLIB_EXTRACT_FLAG_STRICT_ACLS
786                                  * here.  It will be done later if needed; here
787                                  * we are just trying to get as many relevant
788                                  * access rights as possible.  */
789                                 if (dwDesiredAccess & ACCESS_SYSTEM_SECURITY) {
790                                         dwDesiredAccess &= ~ACCESS_SYSTEM_SECURITY;
791                                         continue;
792                                 }
793                                 if (dwDesiredAccess & WRITE_DAC) {
794                                         dwDesiredAccess &= ~WRITE_DAC;
795                                         continue;
796                                 }
797                                 if (dwDesiredAccess & WRITE_OWNER) {
798                                         dwDesiredAccess &= ~WRITE_OWNER;
799                                         continue;
800                                 }
801                         }
802                         /* Other error, or couldn't open the file even with no
803                          * access rights specified.  Something else must be
804                          * wrong.  */
805                         set_errno_from_win32_error(err);
806                         return WIMLIB_ERR_SET_SECURITY;
807                 }
808         }
809 #endif
810
811         /* Try setting the security descriptor.  */
812         for (;;) {
813                 DWORD err;
814
815                 err = do_win32_set_security_descriptor(h, path, info,
816                                                        (PSECURITY_DESCRIPTOR)desc);
817                 if (err == ERROR_SUCCESS) {
818                         ret = 0;
819                         break;
820                 }
821
822                 /* Failed to set the requested parts of the security descriptor.
823                  * If the error was permissions-related, try to set fewer parts
824                  * of the security descriptor, unless
825                  * WIMLIB_EXTRACT_FLAG_STRICT_ACLS is enabled.  */
826                 if ((err == ERROR_PRIVILEGE_NOT_HELD ||
827                      err == ERROR_ACCESS_DENIED) &&
828                     !(ctx->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS))
829                 {
830                         if (info & SACL_SECURITY_INFORMATION) {
831                                 info &= ~SACL_SECURITY_INFORMATION;
832                                 ctx->partial_security_descriptors++;
833                                 continue;
834                         }
835                         if (info & DACL_SECURITY_INFORMATION) {
836                                 info &= ~DACL_SECURITY_INFORMATION;
837                                 continue;
838                         }
839                         if (info & OWNER_SECURITY_INFORMATION) {
840                                 info &= ~OWNER_SECURITY_INFORMATION;
841                                 continue;
842                         }
843                         /* Nothing left except GROUP, and if we removed it we
844                          * wouldn't have anything at all.  */
845                 }
846                 /* No part of the security descriptor could be set, or
847                  * WIMLIB_EXTRACT_FLAG_STRICT_ACLS is enabled and the full
848                  * security descriptor could not be set.  */
849                 if (!(info & SACL_SECURITY_INFORMATION))
850                         ctx->partial_security_descriptors--;
851                 set_errno_from_win32_error(err);
852                 ret = WIMLIB_ERR_SET_SECURITY;
853                 break;
854         }
855
856         /* Close handle opened for NtSetSecurityObject().  */
857 #ifdef WITH_NTDLL
858         if (func_NtSetSecurityObject)
859                 CloseHandle(h);
860 #endif
861         return ret;
862 }
863
864 static int
865 win32_set_timestamps(const wchar_t *path, u64 creation_time,
866                      u64 last_write_time, u64 last_access_time,
867                      struct apply_ctx *ctx)
868 {
869         HANDLE h;
870         DWORD err;
871         FILETIME creationTime = {.dwLowDateTime = creation_time & 0xffffffff,
872                                  .dwHighDateTime = creation_time >> 32};
873         FILETIME lastAccessTime = {.dwLowDateTime = last_access_time & 0xffffffff,
874                                   .dwHighDateTime = last_access_time >> 32};
875         FILETIME lastWriteTime = {.dwLowDateTime = last_write_time & 0xffffffff,
876                                   .dwHighDateTime = last_write_time >> 32};
877
878         h = win32_open_existing_file(path, FILE_WRITE_ATTRIBUTES);
879         if (h == INVALID_HANDLE_VALUE)
880                 goto error;
881
882         if (!SetFileTime(h, &creationTime, &lastAccessTime, &lastWriteTime))
883                 goto error_close_handle;
884
885         if (!CloseHandle(h))
886                 goto error;
887
888         return 0;
889
890 error_close_handle:
891         err = GetLastError();
892         CloseHandle(h);
893         SetLastError(err);
894 error:
895         set_errno_from_GetLastError();
896         return WIMLIB_ERR_SET_TIMESTAMPS;
897 }
898
899 const struct apply_operations win32_apply_ops = {
900         .name = L"Win32",
901
902         .target_is_root           = win32_path_is_root_of_drive,
903         .start_extract            = win32_start_extract,
904         .finish_extract           = win32_finish_extract,
905         .abort_extract            = win32_finish_extract,
906         .create_file              = win32_create_file,
907         .create_directory         = win32_create_directory,
908         .create_hardlink          = win32_create_hardlink,
909         .create_symlink           = win32_create_symlink,
910         .extract_unnamed_stream   = win32_extract_unnamed_stream,
911         .extract_named_stream     = win32_extract_named_stream,
912         .extract_encrypted_stream = win32_extract_encrypted_stream,
913         .set_file_attributes      = win32_set_file_attributes,
914         .set_reparse_data         = win32_set_reparse_data,
915         .set_short_name           = win32_set_short_name,
916         .set_security_descriptor  = win32_set_security_descriptor,
917         .set_timestamps           = win32_set_timestamps,
918
919         .path_prefix = L"\\\\?\\",
920         .path_prefix_nchars = 4,
921         .path_separator = L'\\',
922         .path_max = 32768,
923
924         .requires_realtarget_in_paths = 1,
925         .realpath_works_on_nonexisting_files = 1,
926         .root_directory_is_special = 1,
927         .requires_final_set_attributes_pass = 1,
928         .extract_encrypted_stream_creates_file = 1,
929         .requires_short_name_reordering = 1, /* TODO: check if this is really needed  */
930 };
931
932 #endif /* __WIN32__ */