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