Win32 apply: Delay setting FILE_ATTRIBUTE_READONLY
[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/error.h"
34 #include "wimlib/lookup_table.h"
35
36 static int
37 win32_start_extract(const wchar_t *path, struct apply_ctx *ctx)
38 {
39         int ret;
40         unsigned vol_flags;
41         bool supports_SetFileShortName;
42
43         ret = win32_get_vol_flags(path, &vol_flags, &supports_SetFileShortName);
44         if (ret)
45                 return ret;
46
47         ctx->supported_features.archive_files = 1;
48         ctx->supported_features.hidden_files = 1;
49         ctx->supported_features.system_files = 1;
50
51         if (vol_flags & FILE_FILE_COMPRESSION)
52                 ctx->supported_features.compressed_files = 1;
53
54         if (vol_flags & FILE_SUPPORTS_ENCRYPTION) {
55                 ctx->supported_features.encrypted_files = 1;
56                 ctx->supported_features.encrypted_directories = 1;
57         }
58
59         ctx->supported_features.not_context_indexed_files = 1;
60
61         if (vol_flags & FILE_SUPPORTS_SPARSE_FILES)
62                 ctx->supported_features.sparse_files = 1;
63
64         if (vol_flags & FILE_NAMED_STREAMS)
65                 ctx->supported_features.named_data_streams = 1;
66
67         if (vol_flags & FILE_SUPPORTS_HARD_LINKS)
68                 ctx->supported_features.hard_links = 1;
69
70         if (vol_flags & FILE_SUPPORTS_REPARSE_POINTS) {
71                 ctx->supported_features.reparse_points = 1;
72                 if (win32func_CreateSymbolicLinkW)
73                         ctx->supported_features.symlink_reparse_points = 1;
74         }
75
76         if (vol_flags & FILE_PERSISTENT_ACLS)
77                 ctx->supported_features.security_descriptors = 1;
78
79         if (supports_SetFileShortName)
80                 ctx->supported_features.short_names = 1;
81         return 0;
82 }
83
84 static int
85 win32_create_file(const wchar_t *path, struct apply_ctx *ctx, u64 *cookie_ret)
86 {
87         HANDLE h;
88
89         h = CreateFile(path, 0, 0, NULL, CREATE_ALWAYS,
90                        FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS, NULL);
91         if (h == INVALID_HANDLE_VALUE)
92                 goto error;
93         CloseHandle(h);
94         return 0;
95
96 error:
97         set_errno_from_GetLastError();
98         return WIMLIB_ERR_OPEN;
99 }
100
101 static int
102 win32_create_directory(const wchar_t *path, struct apply_ctx *ctx,
103                        u64 *cookie_ret)
104 {
105         if (!CreateDirectory(path, NULL))
106                 if (GetLastError() != ERROR_ALREADY_EXISTS)
107                         goto error;
108         return 0;
109
110 error:
111         set_errno_from_GetLastError();
112         return WIMLIB_ERR_MKDIR;
113 }
114
115 static int
116 win32_create_hardlink(const wchar_t *oldpath, const wchar_t *newpath,
117                       struct apply_ctx *ctx)
118 {
119         if (!CreateHardLink(newpath, oldpath, NULL)) {
120                 if (GetLastError() != ERROR_ALREADY_EXISTS)
121                         goto error;
122                 if (!DeleteFile(newpath))
123                         goto error;
124                 if (!CreateHardLink(newpath, oldpath, NULL))
125                         goto error;
126         }
127         return 0;
128
129 error:
130         set_errno_from_GetLastError();
131         return WIMLIB_ERR_LINK;
132 }
133
134 static int
135 win32_create_symlink(const wchar_t *oldpath, const wchar_t *newpath,
136                      struct apply_ctx *ctx)
137 {
138         if (!(*win32func_CreateSymbolicLinkW)(newpath, oldpath, 0)) {
139                 if (GetLastError() != ERROR_ALREADY_EXISTS)
140                         goto error;
141                 if (!DeleteFile(newpath))
142                         goto error;
143                 if (!(*win32func_CreateSymbolicLinkW)(newpath, oldpath, 0))
144                         goto error;
145         }
146         return 0;
147
148 error:
149         set_errno_from_GetLastError();
150         return WIMLIB_ERR_LINK;
151 }
152
153 static int
154 win32_extract_wim_chunk(const void *buf, size_t len, void *arg)
155 {
156         HANDLE h = (HANDLE)arg;
157         DWORD nbytes_written;
158
159         if (unlikely(!WriteFile(h, buf, len, &nbytes_written, NULL)))
160                 goto error;
161         if (unlikely(nbytes_written != len))
162                 goto error;
163         return 0;
164
165 error:
166         set_errno_from_GetLastError();
167         return WIMLIB_ERR_WRITE;
168 }
169
170 static int
171 win32_extract_stream(const wchar_t *path, const wchar_t *stream_name,
172                      size_t stream_name_nchars,
173                      struct wim_lookup_table_entry *lte, struct apply_ctx *ctx)
174 {
175         DWORD creationDisposition = OPEN_EXISTING;
176         wchar_t *stream_path = (wchar_t*)path;
177         HANDLE h;
178         int ret;
179
180         if (stream_name_nchars) {
181                 creationDisposition = CREATE_ALWAYS;
182                 stream_path = alloca(sizeof(wchar_t) *
183                                      (wcslen(path) + 1 +
184                                       wcslen(stream_name) + 1));
185                 swprintf(stream_path, L"%ls:%ls", path, stream_name);
186         }
187
188         h = CreateFile(stream_path, FILE_WRITE_DATA, 0, NULL,
189                        creationDisposition, FILE_FLAG_BACKUP_SEMANTICS |
190                                             FILE_FLAG_OPEN_REPARSE_POINT,
191                        NULL);
192         if (h == INVALID_HANDLE_VALUE)
193                 goto error;
194
195         ret = 0;
196         if (!lte)
197                 goto out_close_handle;
198         ret = extract_wim_resource(lte, wim_resource_size(lte),
199                                    win32_extract_wim_chunk, h);
200 out_close_handle:
201         if (!CloseHandle(h))
202                 goto error;
203         if (ret && !errno)
204                 errno = -1;
205         return ret;
206
207 error:
208         set_errno_from_GetLastError();
209         return WIMLIB_ERR_WRITE;
210 }
211
212 static int
213 win32_extract_unnamed_stream(file_spec_t file,
214                              struct wim_lookup_table_entry *lte,
215                              struct apply_ctx *ctx)
216 {
217         return win32_extract_stream(file.path, NULL, 0, lte, ctx);
218 }
219
220 static int
221 win32_extract_named_stream(file_spec_t file, const wchar_t *stream_name,
222                            size_t stream_name_nchars,
223                            struct wim_lookup_table_entry *lte, struct apply_ctx *ctx)
224 {
225         return win32_extract_stream(file.path, stream_name,
226                                     stream_name_nchars, lte, ctx);
227 }
228
229 struct win32_encrypted_extract_ctx {
230         const struct wim_lookup_table_entry *lte;
231         u64 offset;
232 };
233
234 static DWORD WINAPI
235 win32_encrypted_import_cb(unsigned char *data, void *_import_ctx,
236                           unsigned long *len_p)
237 {
238         struct win32_encrypted_extract_ctx *import_ctx = _import_ctx;
239         unsigned long len = *len_p;
240         const struct wim_lookup_table_entry *lte = import_ctx->lte;
241
242         len = min(len, wim_resource_size(lte) - import_ctx->offset);
243
244         if (read_partial_wim_resource_into_buf(lte, len, import_ctx->offset, data))
245                 return ERROR_READ_FAULT;
246
247         import_ctx->offset += len;
248         *len_p = len;
249         return ERROR_SUCCESS;
250 }
251
252 static int
253 win32_extract_encrypted_stream(file_spec_t file,
254                                struct wim_lookup_table_entry *lte,
255                                struct apply_ctx *ctx)
256 {
257         const tchar *path = file.path;
258         void *file_ctx;
259         DWORD err;
260         int ret;
261         struct win32_encrypted_extract_ctx extract_ctx;
262
263         err = OpenEncryptedFileRaw(path, CREATE_FOR_IMPORT, &file_ctx);
264         if (err != ERROR_SUCCESS) {
265                 errno = win32_error_to_errno(err);
266                 ret = WIMLIB_ERR_OPEN;
267                 goto out;
268         }
269
270         extract_ctx.lte = lte;
271         extract_ctx.offset = 0;
272         err = WriteEncryptedFileRaw(win32_encrypted_import_cb, &extract_ctx,
273                                     file_ctx);
274         if (err != ERROR_SUCCESS) {
275                 errno = win32_error_to_errno(err);
276                 ret = WIMLIB_ERR_WRITE;
277                 goto out_close;
278         }
279
280         ret = 0;
281 out_close:
282         CloseEncryptedFileRaw(file_ctx);
283 out:
284         return ret;
285 }
286
287 static BOOL
288 win32_set_special_file_attributes(const wchar_t *path, u32 attributes)
289 {
290         HANDLE h;
291         DWORD err;
292         USHORT compression_format = COMPRESSION_FORMAT_DEFAULT;
293         DWORD bytes_returned;
294
295         h = CreateFile(path, GENERIC_READ | GENERIC_WRITE, 0, NULL,
296                        OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS |
297                                       FILE_FLAG_OPEN_REPARSE_POINT,
298                        NULL);
299         if (h == INVALID_HANDLE_VALUE)
300                 goto error;
301
302         if (attributes & FILE_ATTRIBUTE_SPARSE_FILE)
303                 if (!DeviceIoControl(h, FSCTL_SET_SPARSE,
304                                      NULL, 0,
305                                      NULL, 0,
306                                      &bytes_returned, NULL))
307                         goto error_close_handle;
308
309         if (attributes & FILE_ATTRIBUTE_COMPRESSED)
310                 if (!DeviceIoControl(h, FSCTL_SET_COMPRESSION,
311                                      &compression_format, sizeof(USHORT),
312                                      NULL, 0,
313                                      &bytes_returned, NULL))
314                         goto error_close_handle;
315
316         if (!CloseHandle(h))
317                 goto error;
318
319         if (attributes & FILE_ATTRIBUTE_ENCRYPTED)
320                 if (!EncryptFile(path))
321                         goto error;
322
323         return TRUE;
324
325 error_close_handle:
326         err = GetLastError();
327         CloseHandle(h);
328         SetLastError(err);
329 error:
330         return FALSE;
331 }
332
333 static int
334 win32_set_file_attributes(const wchar_t *path, u32 attributes,
335                           struct apply_ctx *ctx, unsigned pass)
336 {
337         u32 special_attributes =
338                 FILE_ATTRIBUTE_REPARSE_POINT |
339                 FILE_ATTRIBUTE_DIRECTORY |
340                 FILE_ATTRIBUTE_SPARSE_FILE |
341                 FILE_ATTRIBUTE_COMPRESSED |
342                 FILE_ATTRIBUTE_ENCRYPTED;
343         u32 actual_attributes;
344
345         /* On FAT filesystems we can't set FILE_ATTRIBUTE_READONLY on the
346          * initial pass (when files are created, but data not extracted);
347          * otherwise the system will refuse access to the file even if the
348          * process has SeRestorePrivilege.  */
349         if (pass == 0)
350                 attributes &= ~FILE_ATTRIBUTE_READONLY;
351
352         if (!SetFileAttributes(path, attributes & ~special_attributes))
353                 goto error;
354
355         if (pass != 0)
356                 return 0;
357
358         if (attributes & (FILE_ATTRIBUTE_SPARSE_FILE |
359                           FILE_ATTRIBUTE_ENCRYPTED |
360                           FILE_ATTRIBUTE_COMPRESSED))
361                 if (!win32_set_special_file_attributes(path, attributes))
362                         goto error;
363
364         /* If file is not supposed to be encrypted or compressed, remove
365          * defaulted encrypted or compressed attributes (from creating file in
366          * encrypted or compressed directory).  */
367         actual_attributes = GetFileAttributes(path);
368         if (actual_attributes == INVALID_FILE_ATTRIBUTES)
369                 goto error;
370
371         if ((actual_attributes & FILE_ATTRIBUTE_ENCRYPTED) &&
372             !(attributes & FILE_ATTRIBUTE_ENCRYPTED))
373                 if (!DecryptFile(path, 0))
374                         goto error;
375         if ((actual_attributes & FILE_ATTRIBUTE_COMPRESSED) &&
376             !(attributes & FILE_ATTRIBUTE_COMPRESSED))
377         {
378                 HANDLE h;
379                 DWORD bytes_returned;
380                 USHORT compression_format = COMPRESSION_FORMAT_NONE;
381
382                 h = CreateFile(path, GENERIC_READ | GENERIC_WRITE, 0, NULL,
383                                OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS |
384                                               FILE_FLAG_OPEN_REPARSE_POINT,
385                                NULL);
386                 if (h == INVALID_HANDLE_VALUE)
387                         goto error;
388
389                 if (!DeviceIoControl(h, FSCTL_SET_COMPRESSION,
390                                      &compression_format, sizeof(USHORT),
391                                      NULL, 0,
392                                      &bytes_returned, NULL))
393                 {
394                         DWORD err = GetLastError();
395                         CloseHandle(h);
396                         SetLastError(err);
397                         goto error;
398                 }
399
400                 if (!CloseHandle(h))
401                         goto error;
402         }
403
404         return 0;
405
406 error:
407         set_errno_from_GetLastError();
408         return WIMLIB_ERR_SET_ATTRIBUTES;
409 }
410
411 static int
412 win32_set_reparse_data(const wchar_t *path, const u8 *rpbuf, u16 rpbuflen,
413                        struct apply_ctx *ctx)
414 {
415         HANDLE h;
416         DWORD err;
417         DWORD bytes_returned;
418
419         h = CreateFile(path, GENERIC_WRITE, 0, NULL,
420                        OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS |
421                                       FILE_FLAG_OPEN_REPARSE_POINT,
422                        NULL);
423         if (h == INVALID_HANDLE_VALUE)
424                 goto error;
425
426         if (!DeviceIoControl(h, FSCTL_SET_REPARSE_POINT,
427                              (void*)rpbuf, rpbuflen,
428                              NULL, 0, &bytes_returned, NULL))
429                 goto error_close_handle;
430
431         if (!CloseHandle(h))
432                 goto error;
433
434         return 0;
435
436 error_close_handle:
437         err = GetLastError();
438         CloseHandle(h);
439         SetLastError(err);
440 error:
441         set_errno_from_GetLastError();
442         return WIMLIB_ERR_WRITE; /* XXX: need better error code */
443 }
444
445 static int
446 win32_set_short_name(const wchar_t *path, const wchar_t *short_name,
447                      size_t short_name_nchars, struct apply_ctx *ctx)
448 {
449         HANDLE h;
450         DWORD err;
451
452         h = CreateFile(path, GENERIC_WRITE | DELETE, 0, NULL,
453                        OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS |
454                                       FILE_FLAG_OPEN_REPARSE_POINT,
455                        NULL);
456         if (h == INVALID_HANDLE_VALUE)
457                 goto error;
458
459         if (short_name_nchars) {
460                 if (!SetFileShortName(h, short_name))
461                         goto error_close_handle;
462         } else if (running_on_windows_7_or_later()) {
463                 if (!SetFileShortName(h, L""))
464                         goto error_close_handle;
465         }
466
467         if (!CloseHandle(h))
468                 goto error;
469
470         return 0;
471
472 error_close_handle:
473         err = GetLastError();
474         CloseHandle(h);
475         SetLastError(err);
476 error:
477         set_errno_from_GetLastError();
478         return WIMLIB_ERR_WRITE; /* XXX: need better error code */
479 }
480
481 static int
482 win32_set_security_descriptor(const wchar_t *path, const u8 *desc, size_t desc_size,
483                               struct apply_ctx *ctx)
484 {
485         SECURITY_INFORMATION info;
486
487         info = OWNER_SECURITY_INFORMATION |
488                 GROUP_SECURITY_INFORMATION |
489                 DACL_SECURITY_INFORMATION  |
490                 SACL_SECURITY_INFORMATION;
491 retry:
492         if (!SetFileSecurity(path, info, (PSECURITY_DESCRIPTOR)desc)) {
493                 if (!(ctx->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS) &&
494                     GetLastError() == ERROR_PRIVILEGE_NOT_HELD &&
495                     (info & SACL_SECURITY_INFORMATION))
496                 {
497                         info &= ~SACL_SECURITY_INFORMATION;
498                         goto retry;
499                 }
500                 goto error;
501         }
502         return 0;
503
504 error:
505         set_errno_from_GetLastError();
506         return WIMLIB_ERR_SET_SECURITY;
507 }
508
509 static int
510 win32_set_timestamps(const wchar_t *path, u64 creation_time,
511                      u64 last_write_time, u64 last_access_time,
512                      struct apply_ctx *ctx)
513 {
514         HANDLE h;
515         DWORD err;
516         FILETIME creationTime = {.dwLowDateTime = creation_time & 0xffffffff,
517                                  .dwHighDateTime = creation_time >> 32};
518         FILETIME lastAccessTime = {.dwLowDateTime = last_access_time & 0xffffffff,
519                                   .dwHighDateTime = last_access_time >> 32};
520         FILETIME lastWriteTime = {.dwLowDateTime = last_write_time & 0xffffffff,
521                                   .dwHighDateTime = last_write_time >> 32};
522
523         h = CreateFile(path, FILE_WRITE_ATTRIBUTES, 0, NULL,
524                        OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS |
525                                       FILE_FLAG_OPEN_REPARSE_POINT,
526                        NULL);
527         if (h == INVALID_HANDLE_VALUE)
528                 goto error;
529
530         if (!SetFileTime(h, &creationTime, &lastAccessTime, &lastWriteTime))
531                 goto error_close_handle;
532
533         if (!CloseHandle(h))
534                 goto error;
535
536         return 0;
537
538 error_close_handle:
539         err = GetLastError();
540         CloseHandle(h);
541         SetLastError(err);
542 error:
543         set_errno_from_GetLastError();
544         return WIMLIB_ERR_SET_TIMESTAMPS;
545 }
546
547 const struct apply_operations win32_apply_ops = {
548         .name = L"Win32",
549
550         .target_is_root           = win32_path_is_root_of_drive,
551         .start_extract            = win32_start_extract,
552         .create_file              = win32_create_file,
553         .create_directory         = win32_create_directory,
554         .create_hardlink          = win32_create_hardlink,
555         .create_symlink           = win32_create_symlink,
556         .extract_unnamed_stream   = win32_extract_unnamed_stream,
557         .extract_named_stream     = win32_extract_named_stream,
558         .extract_encrypted_stream = win32_extract_encrypted_stream,
559         .set_file_attributes      = win32_set_file_attributes,
560         .set_reparse_data         = win32_set_reparse_data,
561         .set_short_name           = win32_set_short_name,
562         .set_security_descriptor  = win32_set_security_descriptor,
563         .set_timestamps           = win32_set_timestamps,
564
565         .path_prefix = L"\\\\?\\",
566         .path_prefix_nchars = 4,
567         .path_separator = L'\\',
568         .path_max = 32768,
569
570         .requires_realtarget_in_paths = 1,
571         .realpath_works_on_nonexisting_files = 1,
572         .root_directory_is_special = 1,
573         .requires_final_set_attributes_pass = 1,
574 };
575
576 #endif /* __WIN32__ */