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