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