wimlib_vmsg(): Use correct error string buffer length
[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 /* Create a normal file, overwriting one already present.  */
85 static int
86 win32_create_file(const wchar_t *path, struct apply_ctx *ctx, u64 *cookie_ret)
87 {
88         HANDLE h;
89         unsigned retry_count = 0;
90         DWORD dwFlagsAndAttributes = FILE_FLAG_BACKUP_SEMANTICS;
91
92 retry:
93         /* WRITE_OWNER and WRITE_DAC privileges are required for some reason,
94          * even through we're creating a new file.  */
95         h = CreateFile(path, WRITE_OWNER | WRITE_DAC, 0, NULL,
96                        CREATE_ALWAYS, dwFlagsAndAttributes, NULL);
97         if (h == INVALID_HANDLE_VALUE) {
98                 /* File couldn't be created.  */
99                 DWORD err = GetLastError();
100                 if (err == ERROR_ACCESS_DENIED && retry_count == 0) {
101
102                         /* Access denied error for the first time.  Try
103                          * adjusting file attributes.  */
104
105                         /* Get attributes of the existing file.  */
106                         DWORD attribs = GetFileAttributes(path);
107                         if (attribs != INVALID_FILE_ATTRIBUTES &&
108                             (attribs & (FILE_ATTRIBUTE_HIDDEN |
109                                         FILE_ATTRIBUTE_SYSTEM |
110                                         FILE_ATTRIBUTE_READONLY)))
111                         {
112                                 /* If the existing file has
113                                  * FILE_ATTRIBUTE_HIDDEN and/or
114                                  * FILE_ATTRIBUTE_SYSTEM, they must be set in
115                                  * the call to CreateFile().  This is true even
116                                  * when FILE_ATTRIBUTE_NORMAL was not specified,
117                                  * contrary to the MS "documentation".  */
118                                 dwFlagsAndAttributes |= (attribs &
119                                                          (FILE_ATTRIBUTE_HIDDEN |
120                                                           FILE_ATTRIBUTE_SYSTEM));
121                                 /* If the existing file has
122                                  * FILE_ATTRIBUTE_READONLY, it must be cleared
123                                  * before attempting to create a new file over
124                                  * it.  This is true even when the process has
125                                  * the SE_RESTORE_NAME privilege and requested
126                                  * the FILE_FLAG_BACKUP_SEMANTICS flag to
127                                  * CreateFile().  */
128                                 if (attribs & FILE_ATTRIBUTE_READONLY) {
129                                         SetFileAttributes(path,
130                                                           attribs & ~FILE_ATTRIBUTE_READONLY);
131                                 }
132                                 retry_count++;
133                                 goto retry;
134                         }
135                 }
136                 set_errno_from_win32_error(err);
137                 return WIMLIB_ERR_OPEN;
138         }
139         CloseHandle(h);
140         return 0;
141 }
142
143 static int
144 win32_create_directory(const wchar_t *path, struct apply_ctx *ctx,
145                        u64 *cookie_ret)
146 {
147         if (!CreateDirectory(path, NULL))
148                 if (GetLastError() != ERROR_ALREADY_EXISTS)
149                         goto error;
150         return 0;
151
152 error:
153         set_errno_from_GetLastError();
154         return WIMLIB_ERR_MKDIR;
155 }
156
157 static int
158 win32_create_hardlink(const wchar_t *oldpath, const wchar_t *newpath,
159                       struct apply_ctx *ctx)
160 {
161         if (!CreateHardLink(newpath, oldpath, NULL)) {
162                 if (GetLastError() != ERROR_ALREADY_EXISTS)
163                         goto error;
164                 if (!DeleteFile(newpath))
165                         goto error;
166                 if (!CreateHardLink(newpath, oldpath, NULL))
167                         goto error;
168         }
169         return 0;
170
171 error:
172         set_errno_from_GetLastError();
173         return WIMLIB_ERR_LINK;
174 }
175
176 static int
177 win32_create_symlink(const wchar_t *oldpath, const wchar_t *newpath,
178                      struct apply_ctx *ctx)
179 {
180         if (!(*win32func_CreateSymbolicLinkW)(newpath, oldpath, 0)) {
181                 if (GetLastError() != ERROR_ALREADY_EXISTS)
182                         goto error;
183                 if (!DeleteFile(newpath))
184                         goto error;
185                 if (!(*win32func_CreateSymbolicLinkW)(newpath, oldpath, 0))
186                         goto error;
187         }
188         return 0;
189
190 error:
191         set_errno_from_GetLastError();
192         return WIMLIB_ERR_LINK;
193 }
194
195 static int
196 win32_extract_wim_chunk(const void *buf, size_t len, void *arg)
197 {
198         HANDLE h = (HANDLE)arg;
199         DWORD nbytes_written;
200
201         if (unlikely(!WriteFile(h, buf, len, &nbytes_written, NULL)))
202                 goto error;
203         if (unlikely(nbytes_written != len))
204                 goto error;
205         return 0;
206
207 error:
208         set_errno_from_GetLastError();
209         return WIMLIB_ERR_WRITE;
210 }
211
212 static int
213 win32_extract_stream(const wchar_t *path, const wchar_t *stream_name,
214                      size_t stream_name_nchars,
215                      struct wim_lookup_table_entry *lte, struct apply_ctx *ctx)
216 {
217         DWORD creationDisposition = OPEN_EXISTING;
218         wchar_t *stream_path = (wchar_t*)path;
219         HANDLE h;
220         int ret;
221
222         if (stream_name_nchars) {
223                 creationDisposition = CREATE_ALWAYS;
224                 stream_path = alloca(sizeof(wchar_t) *
225                                      (wcslen(path) + 1 +
226                                       wcslen(stream_name) + 1));
227                 tsprintf(stream_path, L"%ls:%ls", path, stream_name);
228         }
229
230         h = CreateFile(stream_path, FILE_WRITE_DATA, 0, NULL,
231                        creationDisposition, FILE_FLAG_BACKUP_SEMANTICS |
232                                             FILE_FLAG_OPEN_REPARSE_POINT,
233                        NULL);
234         if (h == INVALID_HANDLE_VALUE)
235                 goto error;
236
237         ret = 0;
238         if (!lte)
239                 goto out_close_handle;
240         ret = extract_stream(lte, lte->size, win32_extract_wim_chunk, h);
241 out_close_handle:
242         if (!CloseHandle(h))
243                 goto error;
244         if (ret && !errno)
245                 errno = -1;
246         return ret;
247
248 error:
249         set_errno_from_GetLastError();
250         return WIMLIB_ERR_WRITE;
251 }
252
253 static int
254 win32_extract_unnamed_stream(file_spec_t file,
255                              struct wim_lookup_table_entry *lte,
256                              struct apply_ctx *ctx)
257 {
258         return win32_extract_stream(file.path, NULL, 0, lte, ctx);
259 }
260
261 static int
262 win32_extract_named_stream(file_spec_t file, const wchar_t *stream_name,
263                            size_t stream_name_nchars,
264                            struct wim_lookup_table_entry *lte, struct apply_ctx *ctx)
265 {
266         return win32_extract_stream(file.path, stream_name,
267                                     stream_name_nchars, lte, ctx);
268 }
269
270 struct win32_encrypted_extract_ctx {
271         const struct wim_lookup_table_entry *lte;
272         u64 offset;
273 };
274
275 static DWORD WINAPI
276 win32_encrypted_import_cb(unsigned char *data, void *_import_ctx,
277                           unsigned long *len_p)
278 {
279         struct win32_encrypted_extract_ctx *import_ctx = _import_ctx;
280         unsigned long len = *len_p;
281         const struct wim_lookup_table_entry *lte = import_ctx->lte;
282
283         len = min(len, lte->size - import_ctx->offset);
284
285         if (read_partial_wim_stream_into_buf(lte, len, import_ctx->offset, data))
286                 return ERROR_READ_FAULT;
287
288         import_ctx->offset += len;
289         *len_p = len;
290         return ERROR_SUCCESS;
291 }
292
293 static int
294 win32_extract_encrypted_stream(const wchar_t *path,
295                                struct wim_lookup_table_entry *lte,
296                                struct apply_ctx *ctx)
297 {
298         void *file_ctx;
299         DWORD err;
300         int ret;
301         struct win32_encrypted_extract_ctx extract_ctx;
302
303         err = OpenEncryptedFileRaw(path, CREATE_FOR_IMPORT, &file_ctx);
304         if (err != ERROR_SUCCESS) {
305                 set_errno_from_win32_error(err);
306                 ret = WIMLIB_ERR_OPEN;
307                 goto out;
308         }
309
310         extract_ctx.lte = lte;
311         extract_ctx.offset = 0;
312         err = WriteEncryptedFileRaw(win32_encrypted_import_cb, &extract_ctx,
313                                     file_ctx);
314         if (err != ERROR_SUCCESS) {
315                 set_errno_from_win32_error(err);
316                 ret = WIMLIB_ERR_WRITE;
317                 goto out_close;
318         }
319
320         ret = 0;
321 out_close:
322         CloseEncryptedFileRaw(file_ctx);
323 out:
324         return ret;
325 }
326
327 static BOOL
328 win32_set_special_file_attributes(const wchar_t *path, u32 attributes)
329 {
330         HANDLE h;
331         DWORD err;
332         USHORT compression_format = COMPRESSION_FORMAT_DEFAULT;
333         DWORD bytes_returned;
334
335         h = win32_open_existing_file(path, GENERIC_READ | GENERIC_WRITE);
336         if (h == INVALID_HANDLE_VALUE)
337                 goto error;
338
339         if (attributes & FILE_ATTRIBUTE_SPARSE_FILE)
340                 if (!DeviceIoControl(h, FSCTL_SET_SPARSE,
341                                      NULL, 0,
342                                      NULL, 0,
343                                      &bytes_returned, NULL))
344                         goto error_close_handle;
345
346         if (attributes & FILE_ATTRIBUTE_COMPRESSED)
347                 if (!DeviceIoControl(h, FSCTL_SET_COMPRESSION,
348                                      &compression_format, sizeof(USHORT),
349                                      NULL, 0,
350                                      &bytes_returned, NULL))
351                         goto error_close_handle;
352
353         if (!CloseHandle(h))
354                 goto error;
355
356         if (attributes & FILE_ATTRIBUTE_ENCRYPTED)
357                 if (!EncryptFile(path))
358                         goto error;
359
360         return TRUE;
361
362 error_close_handle:
363         err = GetLastError();
364         CloseHandle(h);
365         SetLastError(err);
366 error:
367         return FALSE;
368 }
369
370 static int
371 win32_set_file_attributes(const wchar_t *path, u32 attributes,
372                           struct apply_ctx *ctx, unsigned pass)
373 {
374         u32 special_attributes =
375                 FILE_ATTRIBUTE_REPARSE_POINT |
376                 FILE_ATTRIBUTE_DIRECTORY |
377                 FILE_ATTRIBUTE_SPARSE_FILE |
378                 FILE_ATTRIBUTE_COMPRESSED |
379                 FILE_ATTRIBUTE_ENCRYPTED;
380         u32 actual_attributes;
381
382         /* Delay setting FILE_ATTRIBUTE_READONLY on the initial pass (when files
383          * are created, but data not extracted); otherwise the system will
384          * refuse access to the file even if the process has SeRestorePrivilege.
385          */
386         if (pass == 0)
387                 attributes &= ~FILE_ATTRIBUTE_READONLY;
388
389         if (!SetFileAttributes(path, attributes & ~special_attributes))
390                 goto error;
391
392         if (pass != 0)
393                 return 0;
394
395         if (attributes & (FILE_ATTRIBUTE_SPARSE_FILE |
396                           FILE_ATTRIBUTE_ENCRYPTED |
397                           FILE_ATTRIBUTE_COMPRESSED))
398                 if (!win32_set_special_file_attributes(path, attributes))
399                         goto error;
400
401         /* If file is not supposed to be encrypted or compressed, remove
402          * defaulted encrypted or compressed attributes (from creating file in
403          * encrypted or compressed directory).  */
404         actual_attributes = GetFileAttributes(path);
405         if (actual_attributes == INVALID_FILE_ATTRIBUTES)
406                 goto error;
407
408         if ((actual_attributes & FILE_ATTRIBUTE_ENCRYPTED) &&
409             !(attributes & FILE_ATTRIBUTE_ENCRYPTED))
410                 if (!DecryptFile(path, 0))
411                         goto error;
412         if ((actual_attributes & FILE_ATTRIBUTE_COMPRESSED) &&
413             !(attributes & FILE_ATTRIBUTE_COMPRESSED))
414         {
415                 HANDLE h;
416                 DWORD bytes_returned;
417                 USHORT compression_format = COMPRESSION_FORMAT_NONE;
418
419                 h = win32_open_existing_file(path, GENERIC_READ | GENERIC_WRITE);
420                 if (h == INVALID_HANDLE_VALUE)
421                         goto error;
422
423                 if (!DeviceIoControl(h, FSCTL_SET_COMPRESSION,
424                                      &compression_format, sizeof(USHORT),
425                                      NULL, 0,
426                                      &bytes_returned, NULL))
427                 {
428                         DWORD err = GetLastError();
429                         CloseHandle(h);
430                         SetLastError(err);
431                         goto error;
432                 }
433
434                 if (!CloseHandle(h))
435                         goto error;
436         }
437
438         return 0;
439
440 error:
441         set_errno_from_GetLastError();
442         return WIMLIB_ERR_SET_ATTRIBUTES;
443 }
444
445 static int
446 win32_set_reparse_data(const wchar_t *path, const u8 *rpbuf, u16 rpbuflen,
447                        struct apply_ctx *ctx)
448 {
449         HANDLE h;
450         DWORD err;
451         DWORD bytes_returned;
452
453         h = win32_open_existing_file(path, GENERIC_WRITE);
454         if (h == INVALID_HANDLE_VALUE)
455                 goto error;
456
457         if (!DeviceIoControl(h, FSCTL_SET_REPARSE_POINT,
458                              (void*)rpbuf, rpbuflen,
459                              NULL, 0, &bytes_returned, NULL))
460                 goto error_close_handle;
461
462         if (!CloseHandle(h))
463                 goto error;
464
465         return 0;
466
467 error_close_handle:
468         err = GetLastError();
469         CloseHandle(h);
470         SetLastError(err);
471 error:
472         set_errno_from_GetLastError();
473         return WIMLIB_ERR_WRITE; /* XXX: need better error code */
474 }
475
476 static int
477 win32_set_short_name(const wchar_t *path, const wchar_t *short_name,
478                      size_t short_name_nchars, struct apply_ctx *ctx)
479 {
480         HANDLE h;
481         DWORD err;
482
483         h = win32_open_existing_file(path, GENERIC_WRITE | DELETE);
484         if (h == INVALID_HANDLE_VALUE)
485                 goto error;
486
487         if (short_name_nchars) {
488                 if (!SetFileShortName(h, short_name))
489                         goto error_close_handle;
490         } else if (running_on_windows_7_or_later()) {
491                 if (!SetFileShortName(h, L""))
492                         goto error_close_handle;
493         }
494
495         if (!CloseHandle(h))
496                 goto error;
497
498         return 0;
499
500 error_close_handle:
501         err = GetLastError();
502         CloseHandle(h);
503         SetLastError(err);
504 error:
505         set_errno_from_GetLastError();
506         return WIMLIB_ERR_WRITE; /* XXX: need better error code */
507 }
508
509 static DWORD
510 do_win32_set_security_descriptor(HANDLE h, const wchar_t *path,
511                                  SECURITY_INFORMATION info,
512                                  PSECURITY_DESCRIPTOR desc)
513 {
514 #ifdef WITH_NTDLL
515         if (func_NtSetSecurityObject) {
516                 return (*func_RtlNtStatusToDosError)(
517                                 (*func_NtSetSecurityObject)(h, info, desc));
518         }
519 #endif
520         if (SetFileSecurity(path, info, desc))
521                 return ERROR_SUCCESS;
522         else
523                 return GetLastError();
524 }
525
526 static int
527 win32_set_security_descriptor(const wchar_t *path, const u8 *desc,
528                               size_t desc_size, struct apply_ctx *ctx)
529 {
530         SECURITY_INFORMATION info;
531         HANDLE h;
532         DWORD err;
533         int ret;
534
535         info = OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION |
536                DACL_SECURITY_INFORMATION  | SACL_SECURITY_INFORMATION;
537         h = INVALID_HANDLE_VALUE;
538
539 #ifdef WITH_NTDLL
540         if (func_NtSetSecurityObject) {
541                 h = win32_open_existing_file(path, MAXIMUM_ALLOWED);
542                 if (h == INVALID_HANDLE_VALUE) {
543                         set_errno_from_GetLastError();
544                         ERROR_WITH_ERRNO("Can't open %ls", path);
545                         return WIMLIB_ERR_SET_SECURITY;
546                 }
547         }
548 #endif
549
550         for (;;) {
551                 err = do_win32_set_security_descriptor(h, path, info,
552                                                        (PSECURITY_DESCRIPTOR)desc);
553                 if (err == ERROR_SUCCESS) {
554                         ret = 0;
555                         break;
556                 }
557                 if ((err == ERROR_PRIVILEGE_NOT_HELD ||
558                      err == ERROR_ACCESS_DENIED) &&
559                     !(ctx->extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS))
560                 {
561                         if (info & SACL_SECURITY_INFORMATION) {
562                                 info &= ~SACL_SECURITY_INFORMATION;
563                                 ctx->partial_security_descriptors++;
564                                 continue;
565                         }
566                         if (info & DACL_SECURITY_INFORMATION) {
567                                 info &= ~DACL_SECURITY_INFORMATION;
568                                 continue;
569                         }
570                         if (info & OWNER_SECURITY_INFORMATION) {
571                                 info &= ~OWNER_SECURITY_INFORMATION;
572                                 continue;
573                         }
574                         ctx->partial_security_descriptors--;
575                         ctx->no_security_descriptors++;
576                         ret = 0;
577                         break;
578                 }
579                 set_errno_from_win32_error(err);
580                 ret = WIMLIB_ERR_SET_SECURITY;
581                 break;
582         }
583 #ifdef WITH_NTDLL
584         if (func_NtSetSecurityObject)
585                 CloseHandle(h);
586 #endif
587         return ret;
588 }
589
590 static int
591 win32_set_timestamps(const wchar_t *path, u64 creation_time,
592                      u64 last_write_time, u64 last_access_time,
593                      struct apply_ctx *ctx)
594 {
595         HANDLE h;
596         DWORD err;
597         FILETIME creationTime = {.dwLowDateTime = creation_time & 0xffffffff,
598                                  .dwHighDateTime = creation_time >> 32};
599         FILETIME lastAccessTime = {.dwLowDateTime = last_access_time & 0xffffffff,
600                                   .dwHighDateTime = last_access_time >> 32};
601         FILETIME lastWriteTime = {.dwLowDateTime = last_write_time & 0xffffffff,
602                                   .dwHighDateTime = last_write_time >> 32};
603
604         h = win32_open_existing_file(path, FILE_WRITE_ATTRIBUTES);
605         if (h == INVALID_HANDLE_VALUE)
606                 goto error;
607
608         if (!SetFileTime(h, &creationTime, &lastAccessTime, &lastWriteTime))
609                 goto error_close_handle;
610
611         if (!CloseHandle(h))
612                 goto error;
613
614         return 0;
615
616 error_close_handle:
617         err = GetLastError();
618         CloseHandle(h);
619         SetLastError(err);
620 error:
621         set_errno_from_GetLastError();
622         return WIMLIB_ERR_SET_TIMESTAMPS;
623 }
624
625 const struct apply_operations win32_apply_ops = {
626         .name = L"Win32",
627
628         .target_is_root           = win32_path_is_root_of_drive,
629         .start_extract            = win32_start_extract,
630         .create_file              = win32_create_file,
631         .create_directory         = win32_create_directory,
632         .create_hardlink          = win32_create_hardlink,
633         .create_symlink           = win32_create_symlink,
634         .extract_unnamed_stream   = win32_extract_unnamed_stream,
635         .extract_named_stream     = win32_extract_named_stream,
636         .extract_encrypted_stream = win32_extract_encrypted_stream,
637         .set_file_attributes      = win32_set_file_attributes,
638         .set_reparse_data         = win32_set_reparse_data,
639         .set_short_name           = win32_set_short_name,
640         .set_security_descriptor  = win32_set_security_descriptor,
641         .set_timestamps           = win32_set_timestamps,
642
643         .path_prefix = L"\\\\?\\",
644         .path_prefix_nchars = 4,
645         .path_separator = L'\\',
646         .path_max = 32768,
647
648         .requires_realtarget_in_paths = 1,
649         .realpath_works_on_nonexisting_files = 1,
650         .root_directory_is_special = 1,
651         .requires_final_set_attributes_pass = 1,
652         .extract_encrypted_stream_creates_file = 1,
653         .requires_short_name_reordering = 1, /* TODO: check if this is really needed  */
654 };
655
656 #endif /* __WIN32__ */