]> wimlib.net Git - wimlib/blob - src/wimboot.c
Various cleanups
[wimlib] / src / wimboot.c
1 /*
2  * wimboot.c
3  *
4  * Support for creating WIMBoot pointer files.
5  *
6  * See http://technet.microsoft.com/en-us/library/dn594399.aspx for general
7  * information about WIMBoot.
8  *
9  * Note that WIMBoot pointer files are actually implemented on top of the
10  * Windows Overlay File System Filter (WOF).  See wof.h for more info.
11  */
12
13 /*
14  * Copyright (C) 2014 Eric Biggers
15  *
16  * This file is free software; you can redistribute it and/or modify it under
17  * the terms of the GNU Lesser General Public License as published by the Free
18  * Software Foundation; either version 3 of the License, or (at your option) any
19  * later version.
20  *
21  * This file is distributed in the hope that it will be useful, but WITHOUT
22  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
23  * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
24  * details.
25  *
26  * You should have received a copy of the GNU Lesser General Public License
27  * along with this file; if not, see http://www.gnu.org/licenses/.
28  */
29
30 #ifdef __WIN32__
31
32 #ifdef HAVE_CONFIG_H
33 #  include "config.h"
34 #endif
35
36 #include "wimlib/win32_common.h"
37
38 #include "wimlib/assert.h"
39 #include "wimlib/blob_table.h"
40 #include "wimlib/error.h"
41 #include "wimlib/util.h"
42 #include "wimlib/wimboot.h"
43 #include "wimlib/win32.h"
44 #include "wimlib/wof.h"
45
46 static HANDLE
47 open_file(const wchar_t *device_name, DWORD desiredAccess)
48 {
49         return CreateFile(device_name, desiredAccess,
50                           FILE_SHARE_VALID_FLAGS, NULL, OPEN_EXISTING,
51                           FILE_FLAG_BACKUP_SEMANTICS, NULL);
52 }
53
54 static BOOL
55 query_device(HANDLE h, DWORD code, void *out, DWORD out_size)
56 {
57         DWORD bytes_returned;
58         return DeviceIoControl(h, code, NULL, 0, out, out_size,
59                                &bytes_returned, NULL);
60 }
61
62 /*
63  * Gets partition and drive information for the specified path.
64  *
65  * @path
66  *      Absolute path which must begin with a drive letter.  For example, if the
67  *      path is D:\install.wim, this function will query information about the
68  *      D: volume.
69  * @part_info_ret
70  *      Partition info is returned here.
71  * @drive_info_ret
72  *      Drive info is returned here.  The contained partition info will not be
73  *      valid.
74  *
75  * Returns 0 on success, or a positive error code on failure.
76  */
77 static int
78 query_partition_and_disk_info(const wchar_t *path,
79                               PARTITION_INFORMATION_EX *part_info,
80                               DRIVE_LAYOUT_INFORMATION_EX *drive_info_ret)
81 {
82         wchar_t vol_name[] = L"\\\\.\\X:";
83         wchar_t disk_name[] = L"\\\\?\\PhysicalDriveXXXXXXXXXX";
84         HANDLE h = INVALID_HANDLE_VALUE;
85         VOLUME_DISK_EXTENTS *extents = NULL;
86         size_t extents_size;
87         DRIVE_LAYOUT_INFORMATION_EX *drive_info = NULL;
88         size_t drive_info_size;
89         int ret;
90
91         wimlib_assert(path[0] != L'\0' && path[1] == L':');
92
93         *(wcschr(vol_name, L'X')) = path[0];
94
95         h = open_file(vol_name, GENERIC_READ);
96         if (h == INVALID_HANDLE_VALUE) {
97                 win32_error(GetLastError(), L"\"%ls\": Can't open volume device",
98                             vol_name);
99                 ret = WIMLIB_ERR_OPEN;
100                 goto out;
101         }
102
103         if (!query_device(h, IOCTL_DISK_GET_PARTITION_INFO_EX,
104                           part_info, sizeof(PARTITION_INFORMATION_EX)))
105         {
106                 win32_error(GetLastError(),
107                             L"\"%ls\": Can't get partition info", vol_name);
108                 ret = WIMLIB_ERR_READ;
109                 goto out;
110         }
111
112         extents_size = sizeof(VOLUME_DISK_EXTENTS);
113         for (;;) {
114                 extents_size += 4 * sizeof(DISK_EXTENT);
115                 extents = MALLOC(extents_size);
116                 if (!extents) {
117                         ret = WIMLIB_ERR_NOMEM;
118                         goto out;
119                 }
120
121                 if (query_device(h, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS,
122                                  extents, extents_size))
123                         break;
124                 if (GetLastError() != ERROR_MORE_DATA) {
125                         win32_error(GetLastError(),
126                                     L"\"%ls\": Can't get volume extent info",
127                                     vol_name);
128                         ret = WIMLIB_ERR_READ;
129                         goto out;
130                 }
131                 FREE(extents);
132         }
133
134         CloseHandle(h);
135         h = INVALID_HANDLE_VALUE;
136
137         if (extents->NumberOfDiskExtents != 1) {
138                 ERROR("\"%ls\": This volume has %"PRIu32" disk extents, "
139                       "but this code is untested for more than 1",
140                       vol_name, (u32)extents->NumberOfDiskExtents);
141                 ret = WIMLIB_ERR_UNSUPPORTED;
142                 goto out;
143         }
144
145         wsprintf(wcschr(disk_name, L'X'), L"%"PRIu32,
146                  extents->Extents[0].DiskNumber);
147
148         h = open_file(disk_name, GENERIC_READ);
149         if (h == INVALID_HANDLE_VALUE) {
150                 win32_error(GetLastError(),
151                             L"\"%ls\": Can't open disk device", disk_name);
152                 ret = WIMLIB_ERR_OPEN;
153                 goto out;
154         }
155
156         drive_info_size = sizeof(DRIVE_LAYOUT_INFORMATION_EX);
157         for (;;) {
158                 drive_info_size += 4 * sizeof(PARTITION_INFORMATION_EX);
159                 drive_info = MALLOC(drive_info_size);
160                 if (!drive_info) {
161                         ret = WIMLIB_ERR_NOMEM;
162                         goto out;
163                 }
164
165                 if (query_device(h, IOCTL_DISK_GET_DRIVE_LAYOUT_EX,
166                                  drive_info, drive_info_size))
167                         break;
168                 if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
169                         win32_error(GetLastError(),
170                                     L"\"%ls\": Can't get disk info", disk_name);
171                         ret = WIMLIB_ERR_READ;
172                         goto out;
173                 }
174                 FREE(drive_info);
175         }
176
177         *drive_info_ret = *drive_info;  /* doesn't include partitions */
178         CloseHandle(h);
179         h = INVALID_HANDLE_VALUE;
180
181         if (drive_info->PartitionStyle != part_info->PartitionStyle) {
182                 ERROR("\"%ls\", \"%ls\": Inconsistent partition table type!",
183                       vol_name, disk_name);
184                 ret = WIMLIB_ERR_UNSUPPORTED;
185                 goto out;
186         }
187
188         if (part_info->PartitionStyle == PARTITION_STYLE_GPT) {
189                 BUILD_BUG_ON(sizeof(part_info->Gpt.PartitionId) !=
190                              sizeof(drive_info->Gpt.DiskId));
191                 if (!memcmp(&part_info->Gpt.PartitionId,
192                             &drive_info->Gpt.DiskId,
193                             sizeof(drive_info->Gpt.DiskId)))
194                 {
195                         ERROR("\"%ls\", \"%ls\": Partition GUID is the "
196                               "same as the disk GUID???", vol_name, disk_name);
197                         ret = WIMLIB_ERR_UNSUPPORTED;
198                         goto out;
199                 }
200         }
201
202         if (part_info->PartitionStyle != PARTITION_STYLE_MBR &&
203             part_info->PartitionStyle != PARTITION_STYLE_GPT)
204         {
205                 ERROR("\"%ls\": Unknown partition style 0x%08"PRIx32,
206                       vol_name, (u32)part_info->PartitionStyle);
207                 ret = WIMLIB_ERR_UNSUPPORTED;
208                 goto out;
209         }
210
211         ret = 0;
212 out:
213         FREE(extents);
214         FREE(drive_info);
215         if (h != INVALID_HANDLE_VALUE)
216                 CloseHandle(h);
217         return ret;
218 }
219
220 /*
221  * Allocate a new WIM data source ID.
222  *
223  * @old_hdr
224  *      Previous WimOverlay.dat contents, or NULL if file did not exist.
225  *
226  * Returns the new data source ID.
227  */
228 static u64
229 alloc_new_data_source_id(const struct WimOverlay_dat_header *old_hdr)
230 {
231         if (!old_hdr)
232                 return 0;
233
234         for (u64 id = 0; ; id++) {
235                 for (u32 i = 0; i < old_hdr->num_entries_1; i++)
236                         if (id == old_hdr->entry_1s[i].data_source_id)
237                                 goto next;
238                 return id;
239         next:
240                 ;
241         }
242 }
243
244 /*
245  * Calculate the size of WimOverlay.dat with one entry added.
246  *
247  * @old_hdr
248  *      Previous WimOverlay.dat contents, or NULL if file did not exist.
249  * @new_entry_2_size
250  *      Size of entry_2 being added.
251  * @size_ret
252  *      Size will be returned here.
253  *
254  * Returns 0 on success, or WIMLIB_ERR_UNSUPPORTED if size overflows 32 bits.
255  */
256 static int
257 calculate_wimoverlay_dat_size(const struct WimOverlay_dat_header *old_hdr,
258                               u32 new_entry_2_size, u32 *size_ret)
259 {
260         u64 size_64;
261         u32 size;
262
263         size_64 = sizeof(struct WimOverlay_dat_header);
264         if (old_hdr) {
265                 for (u32 i = 0; i < old_hdr->num_entries_1; i++) {
266                         size_64 += sizeof(struct WimOverlay_dat_entry_1);
267                         size_64 += old_hdr->entry_1s[i].entry_2_length;
268                 }
269         }
270         size_64 += sizeof(struct WimOverlay_dat_entry_1);
271         size_64 += new_entry_2_size;
272
273         size = size_64;
274         if (size_64 != size)
275                 return WIMLIB_ERR_UNSUPPORTED;
276
277         *size_ret = size;
278         return 0;
279 }
280
281 /*
282  * Writes @size bytes of @contents to the named file @path.
283  *
284  * Returns 0 on success; WIMLIB_ERR_OPEN or WIMLIB_ERR_WRITE on failure.
285  */
286 static int
287 write_wimoverlay_dat(const wchar_t *path, const void *contents, u32 size)
288 {
289         HANDLE h;
290         DWORD bytes_written;
291
292         h = CreateFile(path, GENERIC_WRITE, 0, NULL,
293                        CREATE_ALWAYS, FILE_FLAG_BACKUP_SEMANTICS, NULL);
294         if (h == INVALID_HANDLE_VALUE) {
295                 win32_error(GetLastError(),
296                             L"\"%ls\": Can't open file for writing", path);
297                 return WIMLIB_ERR_OPEN;
298         }
299
300         SetLastError(0);
301         if (!WriteFile(h, contents, size, &bytes_written, NULL) ||
302             bytes_written != size)
303         {
304                 win32_error(GetLastError(),
305                             L"\"%ls\": Can't write file", path);
306                 CloseHandle(h);
307                 return WIMLIB_ERR_WRITE;
308         }
309
310         if (!CloseHandle(h)) {
311                 win32_error(GetLastError(),
312                             L"\"%ls\": Can't close handle", path);
313                 return WIMLIB_ERR_WRITE;
314         }
315
316         return 0;
317 }
318
319 /*
320  * Generates the contents of WimOverlay.dat in memory, with one entry added.
321  *
322  * @buf
323  *      Buffer large enough to hold the new contents.
324  * @old_hdr
325  *      Old contents of WimOverlay.dat, or NULL if it did not exist.
326  * @wim_path
327  *      Absolute path to the WIM file.  It must begin with a drive letter; for
328  *      example, D:\install.wim.
329  * @wim_guid
330  *      GUID of the WIM, from the WIM header.
331  * @image
332  *      Number of the image in the WIM to specify in the new entry.
333  * @new_data_source_id
334  *      Data source ID to use for the new entry.
335  * @part_info
336  *      Partition information for the WIM file.
337  * @disk_info
338  *      Disk information for the WIM file.
339  * @new_entry_2_size
340  *      Size, in bytes, of the new location information structure ('struct
341  *      WimOverlay_dat_entry_2').
342  *
343  * Returns a pointer one past the last byte of @buf filled in.
344  */
345 static u8 *
346 fill_in_wimoverlay_dat(u8 *buf,
347                        const struct WimOverlay_dat_header *old_hdr,
348                        const wchar_t *wim_path,
349                        const u8 wim_guid[WIM_GUID_LEN],
350                        int image,
351                        u64 new_data_source_id,
352                        const PARTITION_INFORMATION_EX *part_info,
353                        const DRIVE_LAYOUT_INFORMATION_EX *disk_info,
354                        u32 new_entry_2_size)
355 {
356         struct WimOverlay_dat_header *new_hdr;
357         struct WimOverlay_dat_entry_1 *new_entry_1;
358         struct WimOverlay_dat_entry_2 *new_entry_2;
359         u32 entry_2_offset;
360         u8 *p = buf;
361
362         new_hdr = (struct WimOverlay_dat_header *)p;
363
364         /* Fill in new header  */
365         new_hdr->magic = WIMOVERLAY_DAT_MAGIC;
366         new_hdr->wim_provider_version = WIM_PROVIDER_CURRENT_VERSION;
367         new_hdr->unknown_0x08 = 0x00000028;
368         new_hdr->num_entries_1 = (old_hdr ? old_hdr->num_entries_1 : 0) + 1;
369         new_hdr->num_entries_2 = (old_hdr ? old_hdr->num_entries_2 : 0) + 1;
370         new_hdr->unknown_0x14 = 0x00000000;
371
372         p += sizeof(struct WimOverlay_dat_header);
373
374         /* Copy WIM-specific information for old entries  */
375         entry_2_offset = sizeof(struct WimOverlay_dat_header) +
376                         (new_hdr->num_entries_1 * sizeof(struct WimOverlay_dat_entry_1));
377         if (old_hdr) {
378                 for (u32 i = 0; i < old_hdr->num_entries_1; i++) {
379                         new_entry_1 = (struct WimOverlay_dat_entry_1 *)p;
380
381                         p = mempcpy(p, &old_hdr->entry_1s[i],
382                                     sizeof(struct WimOverlay_dat_entry_1));
383
384                         new_entry_1->entry_2_offset = entry_2_offset;
385                         entry_2_offset += new_entry_1->entry_2_length;
386                 }
387         }
388
389         /* Generate WIM-specific information for new entry  */
390         new_entry_1 = (struct WimOverlay_dat_entry_1 *)p;
391
392         new_entry_1->data_source_id = new_data_source_id;
393         new_entry_1->entry_2_offset = entry_2_offset;
394         new_entry_1->entry_2_length = new_entry_2_size;
395         new_entry_1->wim_type = WIM_BOOT_NOT_OS_WIM;
396         new_entry_1->wim_index = image;
397         BUILD_BUG_ON(sizeof(new_entry_1->guid) != WIM_GUID_LEN);
398         memcpy(new_entry_1->guid, wim_guid, WIM_GUID_LEN);
399
400         p += sizeof(struct WimOverlay_dat_entry_1);
401
402         /* Copy WIM location information for old entries  */
403         if (old_hdr) {
404                 for (u32 i = 0; i < old_hdr->num_entries_1; i++) {
405                         wimlib_assert(new_hdr->entry_1s[i].entry_2_offset == p - buf);
406                         wimlib_assert(old_hdr->entry_1s[i].entry_2_length ==
407                                       new_hdr->entry_1s[i].entry_2_length);
408                         p = mempcpy(p,
409                                     ((const u8 *)old_hdr + old_hdr->entry_1s[i].entry_2_offset),
410                                     old_hdr->entry_1s[i].entry_2_length);
411                 }
412         }
413
414         /* Generate WIM location information for new entry  */
415         new_entry_2 = (struct WimOverlay_dat_entry_2 *)p;
416
417         new_entry_2->unknown_0x00 = 0x00000000;
418         new_entry_2->unknown_0x04 = 0x00000000;
419         new_entry_2->entry_2_length = new_entry_2_size;
420         new_entry_2->unknown_0x0C = 0x00000000;
421         new_entry_2->unknown_0x10 = 0x00000005;
422         new_entry_2->unknown_0x14 = 0x00000001;
423         new_entry_2->inner_struct_size = new_entry_2_size - 0x14;
424         new_entry_2->unknown_0x1C = 0x00000005;
425         new_entry_2->unknown_0x20 = 0x00000006;
426         new_entry_2->unknown_0x24 = 0x00000000;
427         new_entry_2->unknown_0x28 = 0x00000048;
428         new_entry_2->unknown_0x2C = 0x00000000;
429         new_entry_2->unknown_0x40 = 0x00000000;
430
431         if (part_info->PartitionStyle == PARTITION_STYLE_MBR) {
432                 new_entry_2->partition.mbr.part_start_offset = part_info->StartingOffset.QuadPart;
433                 new_entry_2->partition.mbr.padding = 0;
434                 new_entry_2->partition_table_type = WIMOVERLAY_PARTITION_TYPE_MBR;
435                 new_entry_2->disk.mbr.disk_id = disk_info->Mbr.Signature;
436                 new_entry_2->disk.mbr.padding[0] = 0x00000000;
437                 new_entry_2->disk.mbr.padding[1] = 0x00000000;
438                 new_entry_2->disk.mbr.padding[2] = 0x00000000;
439         } else {
440                 BUILD_BUG_ON(sizeof(new_entry_2->partition.gpt.part_unique_guid) !=
441                              sizeof(part_info->Gpt.PartitionId));
442                 memcpy(new_entry_2->partition.gpt.part_unique_guid,
443                        &part_info->Gpt.PartitionId,
444                        sizeof(part_info->Gpt.PartitionId));
445                 new_entry_2->partition_table_type = WIMOVERLAY_PARTITION_TYPE_GPT;
446
447                 BUILD_BUG_ON(sizeof(new_entry_2->disk.gpt.disk_guid) !=
448                              sizeof(disk_info->Gpt.DiskId));
449                 memcpy(new_entry_2->disk.gpt.disk_guid,
450                        &disk_info->Gpt.DiskId,
451                        sizeof(disk_info->Gpt.DiskId));
452
453                 BUILD_BUG_ON(sizeof(new_entry_2->disk.gpt.disk_guid) !=
454                              sizeof(new_entry_2->partition.gpt.part_unique_guid));
455         }
456         new_entry_2->unknown_0x58[0] = 0x00000000;
457         new_entry_2->unknown_0x58[1] = 0x00000000;
458         new_entry_2->unknown_0x58[2] = 0x00000000;
459         new_entry_2->unknown_0x58[3] = 0x00000000;
460
461         wimlib_assert(wim_path[2] == L'\\');
462         return mempcpy(new_entry_2->wim_file_name,
463                        wim_path + 2,
464                        new_entry_2_size - sizeof(struct WimOverlay_dat_entry_2));
465 }
466
467 /*
468  * Prepares the new contents of WimOverlay.dat in memory, with one entry added.
469  *
470  * @old_hdr
471  *      Old contents of WimOverlay.dat, or NULL if it did not exist.
472  * @wim_path
473  *      Absolute path to the WIM file.  It must begin with a drive letter; for
474  *      example, D:\install.wim.
475  * @wim_guid
476  *      GUID of the WIM, from the WIM header.
477  * @image
478  *      Number of the image in the WIM to specify in the new entry.
479  * @new_contents_ret
480  *      Location into which to return the new contents as a malloc()ed buffer on
481  *      success.
482  * @new_contents_size_ret
483  *      Location into which to return the size, in bytes, of the new contents on
484  *      success.
485  * @new_data_source_id_ret
486  *      Location into which to return the data source ID of the new entry on
487  *      success.
488  *
489  * Returns 0 on success, or a positive error code on failure.
490  */
491 static int
492 prepare_wimoverlay_dat(const struct WimOverlay_dat_header *old_hdr,
493                        const wchar_t *wim_path,
494                        const u8 wim_guid[WIM_GUID_LEN],
495                        int image,
496                        void **new_contents_ret,
497                        u32 *new_contents_size_ret,
498                        u64 *new_data_source_id_ret)
499 {
500         int ret;
501         PARTITION_INFORMATION_EX part_info;
502         DRIVE_LAYOUT_INFORMATION_EX disk_info;
503         u64 new_data_source_id;
504         u32 new_entry_2_size;
505         u32 new_contents_size;
506         u8 *buf;
507         u8 *end;
508
509         ret = query_partition_and_disk_info(wim_path, &part_info, &disk_info);
510         if (ret)
511                 return ret;
512
513         new_data_source_id = alloc_new_data_source_id(old_hdr);
514
515         new_entry_2_size = sizeof(struct WimOverlay_dat_entry_2) +
516                                 ((wcslen(wim_path) - 2 + 1) * sizeof(wchar_t));
517         ret = calculate_wimoverlay_dat_size(old_hdr, new_entry_2_size,
518                                             &new_contents_size);
519         if (ret)
520                 return ret;
521
522         buf = MALLOC(new_contents_size);
523         if (!buf)
524                 return WIMLIB_ERR_NOMEM;
525
526         end = fill_in_wimoverlay_dat(buf, old_hdr, wim_path, wim_guid, image,
527                                      new_data_source_id,
528                                      &part_info, &disk_info, new_entry_2_size);
529
530         wimlib_assert(end - buf == new_contents_size);
531
532         *new_contents_ret = buf;
533         *new_contents_size_ret = new_contents_size;
534         *new_data_source_id_ret = new_data_source_id;
535         return 0;
536 }
537
538 /*
539  * Reads and validates a WimOverlay.dat file.
540  *
541  * @path
542  *      Path to the WimOverlay.dat file, such as
543  *      C:\System Volume Information\WimOverlay.dat
544  * @contents_ret
545  *      Location into which to return the contents as a malloc()ed buffer on
546  *      success.  This can be cast to 'struct WimOverlay_dat_header', and its
547  *      contents are guaranteed to be valid.  Alternatively, if the file does
548  *      not exist, NULL will be returned here.
549  *
550  * Returns 0 on success, or a positive error code on failure.
551  */
552 static int
553 read_wimoverlay_dat(const wchar_t *path, void **contents_ret)
554 {
555         HANDLE h;
556         BY_HANDLE_FILE_INFORMATION info;
557         int ret;
558         void *contents;
559         const struct WimOverlay_dat_header *hdr;
560         DWORD bytes_read;
561         bool already_retried = false;
562
563 retry:
564         h = open_file(path, GENERIC_READ);
565         if (h == INVALID_HANDLE_VALUE) {
566                 DWORD err = GetLastError();
567                 if (err == ERROR_FILE_NOT_FOUND) {
568                         *contents_ret = NULL;
569                         return 0;
570                 }
571                 if (err == ERROR_PATH_NOT_FOUND &&
572                     func_RtlCreateSystemVolumeInformationFolder)
573                 {
574                         wchar_t volume_root_path[] = L"\\??\\X:\\";
575
576                         *(wcschr(volume_root_path, L'X')) = path[0];
577
578                         UNICODE_STRING str = {
579                                 .Length = sizeof(volume_root_path) - sizeof(wchar_t),
580                                 .MaximumLength = sizeof(volume_root_path),
581                                 .Buffer = volume_root_path,
582                         };
583                         NTSTATUS status;
584                         DWORD err2;
585
586                         status = (*func_RtlCreateSystemVolumeInformationFolder)(&str);
587
588                         err2 = (*func_RtlNtStatusToDosError)(status);
589                         if (err2 == ERROR_SUCCESS) {
590                                 if (!already_retried) {
591                                         already_retried = true;
592                                         goto retry;
593                                 }
594                         } else {
595                                 err = err2;
596                         }
597                 }
598                 win32_error(err, L"\"%ls\": Can't open for reading", path);
599                 return WIMLIB_ERR_OPEN;
600         }
601         if (!GetFileInformationByHandle(h, &info)) {
602                 win32_error(GetLastError(), L"\"%ls\": Can't query metadata", path);
603                 CloseHandle(h);
604                 return WIMLIB_ERR_STAT;
605         }
606
607         contents = NULL;
608         if (!info.nFileSizeHigh)
609                 contents = MALLOC(info.nFileSizeLow);
610         if (!contents) {
611                 ERROR("\"%ls\": File is too large to fit into memory", path);
612                 CloseHandle(h);
613                 return WIMLIB_ERR_NOMEM;
614         }
615
616         SetLastError(0);
617         if (!ReadFile(h, contents, info.nFileSizeLow, &bytes_read, NULL) ||
618             bytes_read != info.nFileSizeLow)
619         {
620                 win32_error(GetLastError(), L"\"%ls\": Can't read data", path);
621                 CloseHandle(h);
622                 ret = WIMLIB_ERR_READ;
623                 goto out_free_contents;
624         }
625
626         CloseHandle(h);
627
628         if (info.nFileSizeLow < sizeof(struct WimOverlay_dat_header)) {
629                 ERROR("\"%ls\": File is unexpectedly small (only %"PRIu32" bytes)",
630                       path, (u32)info.nFileSizeLow);
631                 ret = WIMLIB_ERR_UNSUPPORTED;
632                 goto out_free_contents;
633         }
634
635         hdr = (const struct WimOverlay_dat_header *)contents;
636
637         if (hdr->magic != WIMOVERLAY_DAT_MAGIC ||
638             hdr->wim_provider_version != WIM_PROVIDER_CURRENT_VERSION ||
639             hdr->unknown_0x08 != 0x00000028 ||
640             (hdr->num_entries_1 != hdr->num_entries_2) ||
641             hdr->unknown_0x14 != 0x00000000)
642         {
643                 ERROR("\"%ls\": Header contains unexpected data:", path);
644                 if (wimlib_print_errors) {
645                         print_byte_field((const u8 *)hdr,
646                                          sizeof(struct WimOverlay_dat_header),
647                                          wimlib_error_file);
648                         fputc('\n', wimlib_error_file);
649                 }
650                 ret = WIMLIB_ERR_UNSUPPORTED;
651                 goto out_free_contents;
652         }
653
654         if ((u64)hdr->num_entries_1 * sizeof(struct WimOverlay_dat_entry_1) >
655             info.nFileSizeLow - sizeof(struct WimOverlay_dat_header))
656         {
657                 ERROR("\"%ls\": File is unexpectedly small "
658                       "(only %"PRIu32" bytes, but has %"PRIu32" entries)",
659                       path, (u32)info.nFileSizeLow, hdr->num_entries_1);
660                 ret = WIMLIB_ERR_UNSUPPORTED;
661                 goto out_free_contents;
662         }
663
664         for (u32 i = 0; i < hdr->num_entries_1; i++) {
665                 const struct WimOverlay_dat_entry_1 *entry_1;
666                 const struct WimOverlay_dat_entry_2 *entry_2;
667                 u32 wim_file_name_length;
668
669                 entry_1 = &hdr->entry_1s[i];
670
671                 if (((u64)entry_1->entry_2_offset +
672                      (u64)entry_1->entry_2_length) >
673                     info.nFileSizeLow)
674                 {
675                         ERROR("\"%ls\": entry %"PRIu32" (2) "
676                               "(data source ID 0x%016"PRIx64") "
677                               "overflows file",
678                               path, i, entry_1->data_source_id);
679                         ret = WIMLIB_ERR_UNSUPPORTED;
680                         goto out_free_contents;
681                 }
682                 if (entry_1->entry_2_length < sizeof(struct WimOverlay_dat_entry_2)) {
683                         ERROR("\"%ls\": entry %"PRIu32" (2) "
684                               "(data source ID 0x%016"PRIx64") "
685                               "is too short",
686                               path, i, entry_1->data_source_id);
687                         ret = WIMLIB_ERR_UNSUPPORTED;
688                         goto out_free_contents;
689                 }
690
691                 if (entry_1->entry_2_offset % 2 != 0) {
692                         ERROR("\"%ls\": entry %"PRIu32" (2) "
693                               "(data source ID 0x%016"PRIx64") "
694                               "is misaligned",
695                               path, i, entry_1->data_source_id);
696                         ret = WIMLIB_ERR_UNSUPPORTED;
697                         goto out_free_contents;
698                 }
699
700                 entry_2 = (const struct WimOverlay_dat_entry_2 *)
701                                 ((const u8 *)hdr + entry_1->entry_2_offset);
702
703                 wim_file_name_length = entry_1->entry_2_length -
704                                         sizeof(struct WimOverlay_dat_entry_2);
705                 if ((wim_file_name_length < 2 * sizeof(wchar_t)) ||
706                     (wim_file_name_length % sizeof(wchar_t) != 0) ||
707                     (wmemchr(entry_2->wim_file_name, L'\0',
708                              wim_file_name_length / sizeof(wchar_t))
709                      != &entry_2->wim_file_name[wim_file_name_length /
710                                                 sizeof(wchar_t) - 1]))
711                 {
712                         ERROR("\"%ls\": entry %"PRIu32" (2) "
713                               "(data source ID 0x%016"PRIx64") "
714                               "has invalid WIM file name",
715                               path, i, entry_1->data_source_id);
716                         if (wimlib_print_errors) {
717                                 print_byte_field((const u8 *)entry_2->wim_file_name,
718                                                  wim_file_name_length,
719                                                  wimlib_error_file);
720                                 fputc('\n', wimlib_error_file);
721                         }
722                         ret = WIMLIB_ERR_UNSUPPORTED;
723                         goto out_free_contents;
724                 }
725
726                 if (entry_2->unknown_0x00 != 0x00000000 ||
727                     entry_2->unknown_0x04 != 0x00000000 ||
728                     entry_2->unknown_0x0C != 0x00000000 ||
729                     entry_2->entry_2_length != entry_1->entry_2_length ||
730                     entry_2->unknown_0x10 != 0x00000005 ||
731                     entry_2->unknown_0x14 != 0x00000001 ||
732                     entry_2->inner_struct_size != entry_1->entry_2_length - 0x14 ||
733                     entry_2->unknown_0x1C != 0x00000005 ||
734                     entry_2->unknown_0x20 != 0x00000006 ||
735                     entry_2->unknown_0x24 != 0x00000000 ||
736                     entry_2->unknown_0x28 != 0x00000048 ||
737                     entry_2->unknown_0x2C != 0x00000000 ||
738                     entry_2->unknown_0x40 != 0x00000000 ||
739                     (entry_2->partition_table_type != WIMOVERLAY_PARTITION_TYPE_GPT &&
740                      entry_2->partition_table_type != WIMOVERLAY_PARTITION_TYPE_MBR) ||
741                     (entry_2->partition_table_type == WIMOVERLAY_PARTITION_TYPE_MBR &&
742                      entry_2->partition.mbr.padding != 0) ||
743                     (entry_2->partition_table_type == WIMOVERLAY_PARTITION_TYPE_GPT &&
744                      entry_2->partition.mbr.padding == 0) ||
745                     entry_2->unknown_0x58[0] != 0x00000000 ||
746                     entry_2->unknown_0x58[1] != 0x00000000 ||
747                     entry_2->unknown_0x58[2] != 0x00000000 ||
748                     entry_2->unknown_0x58[3] != 0x00000000)
749                 {
750                         ERROR("\"%ls\": entry %"PRIu32" (2) "
751                               "(data source ID 0x%016"PRIx64") "
752                               "contains unexpected data!",
753                               path, i, entry_1->data_source_id);
754                         if (wimlib_print_errors) {
755                                 print_byte_field((const u8 *)entry_2,
756                                                  entry_1->entry_2_length,
757                                                  wimlib_error_file);
758                                 fputc('\n', wimlib_error_file);
759                         }
760                         ret = WIMLIB_ERR_UNSUPPORTED;
761                         goto out_free_contents;
762                 }
763         }
764
765         *contents_ret = contents;
766         return 0;
767
768 out_free_contents:
769         FREE(contents);
770         return ret;
771 }
772
773 /*
774  * Update WimOverlay.dat manually in order to add a WIM data source to the
775  * target volume.
776  *
777  * THIS CODE IS EXPERIMENTAL AS I HAD TO REVERSE ENGINEER THE FILE FORMAT!
778  *
779  * @path
780  *      Target drive.  Must be a letter followed by a colon (e.g. D:).
781  * @wim_path
782  *      Absolute path to the WIM file.  It must begin with a drive letter; for
783  *      example, D:\install.wim.
784  * @wim_guid
785  *      GUID of the WIM, from the WIM header.
786  * @image
787  *      Number of the image in the WIM to specify in the new entry.
788  * @data_source_id_ret
789  *      On success, the allocated data source ID is returned here.
790  */
791 static int
792 update_wimoverlay_manually(const wchar_t *drive, const wchar_t *wim_path,
793                            const u8 wim_guid[WIM_GUID_LEN],
794                            int image, u64 *data_source_id_ret)
795 {
796         wchar_t path_main[] = L"A:\\System Volume Information\\WimOverlay.dat";
797         wchar_t path_backup[] = L"A:\\System Volume Information\\WimOverlay.backup";
798         wchar_t path_wimlib_backup[] = L"A:\\System Volume Information\\WimOverlay.wimlib_backup";
799         wchar_t path_new[] = L"A:\\System Volume Information\\WimOverlay.wimlib_new";
800         void *old_contents;
801         void *new_contents;
802         u32 new_contents_size;
803         u64 new_data_source_id;
804         int ret;
805
806         wimlib_assert(drive[0] != L'\0' &&
807                       drive[1] == L':' &&
808                       drive[2] == L'\0');
809
810         path_main[0]          = drive[0];
811         path_backup[0]        = drive[0];
812         path_wimlib_backup[0] = drive[0];
813         path_new[0]           = drive[0];
814
815         ret = read_wimoverlay_dat(path_main, &old_contents);
816         if (ret)
817                 goto out;
818
819         ret = prepare_wimoverlay_dat(old_contents, wim_path, wim_guid, image,
820                                      &new_contents, &new_contents_size,
821                                      &new_data_source_id);
822         FREE(old_contents);
823         if (ret)
824                 goto out;
825
826         /* Write WimOverlay.wimlib_new  */
827         ret = write_wimoverlay_dat(path_new,
828                                    new_contents, new_contents_size);
829         if (ret)
830                 goto out_free_new_contents;
831
832         /* Write WimOverlay.backup  */
833         ret = write_wimoverlay_dat(path_backup,
834                                    new_contents, new_contents_size);
835         if (ret)
836                 goto out_free_new_contents;
837
838         if (old_contents) {
839                 /* Rename WimOverlay.dat => WimOverlay.wimlib_backup  */
840                 ret = win32_rename_replacement(path_main, path_wimlib_backup);
841                 if (ret) {
842                         ERROR_WITH_ERRNO("Can't rename \"%ls\" => \"%ls\"",
843                                          path_main, path_wimlib_backup);
844                         ret = WIMLIB_ERR_RENAME;
845                         goto out_free_new_contents;
846                 }
847         }
848
849         /* Rename WimOverlay.wimlib_new => WimOverlay.dat  */
850         ret = win32_rename_replacement(path_new, path_main);
851         if (ret) {
852                 ERROR_WITH_ERRNO("Can't rename \"%ls\" => \"%ls\"",
853                                  path_new, path_main);
854                 ret = WIMLIB_ERR_RENAME;
855         }
856 out_free_new_contents:
857         FREE(new_contents);
858 out:
859         if (ret == WIMLIB_ERR_UNSUPPORTED) {
860                 ERROR("Please report to developer ("PACKAGE_BUGREPORT").\n"
861                       "        If possible send the file \"%ls\".\n\n", path_main);
862         }
863         if (ret == 0)
864                 *data_source_id_ret = new_data_source_id;
865         return ret;
866 }
867
868 /* Try to attach an instance of the Windows Overlay File System Filter Driver to
869  * the specified drive (such as C:)  */
870 static bool
871 try_to_attach_wof(const wchar_t *drive)
872 {
873         HMODULE fltlib;
874         bool retval = false;
875
876         /* Use FilterAttach() from Fltlib.dll.  */
877
878         fltlib = LoadLibrary(L"Fltlib.dll");
879
880         if (!fltlib) {
881                 WARNING("Failed to load Fltlib.dll");
882                 return retval;
883         }
884
885         HRESULT (WINAPI *func_FilterAttach)(LPCWSTR lpFilterName,
886                                             LPCWSTR lpVolumeName,
887                                             LPCWSTR lpInstanceName,
888                                             DWORD dwCreatedInstanceNameLength,
889                                             LPWSTR lpCreatedInstanceName);
890
891         func_FilterAttach = (void *)GetProcAddress(fltlib, "FilterAttach");
892
893         if (func_FilterAttach) {
894                 HRESULT res;
895
896                 res = (*func_FilterAttach)(L"WoF", drive, NULL, 0, NULL);
897
898                 if (res == S_OK)
899                         retval = true;
900         } else {
901                 WARNING("FilterAttach() does not exist in Fltlib.dll");
902         }
903
904         FreeLibrary(fltlib);
905
906         return retval;
907 }
908
909 /*
910  * Allocate a WOF data source ID for a WIM file.
911  *
912  * @wim_path
913  *      Absolute path to the WIM file.  This must include a drive letter and use
914  *      backslash path separators.
915  * @wim_guid
916  *      GUID of the WIM, from the WIM header.
917  * @image
918  *      Number of the image in the WIM being applied.
919  * @target
920  *      Path to the target directory.
921  * @data_source_id_ret
922  *      On success, an identifier for the backing WIM file will be returned
923  *      here.
924  *
925  * Returns 0 on success, or a positive error code on failure.
926  */
927 int
928 wimboot_alloc_data_source_id(const wchar_t *wim_path,
929                              const u8 wim_guid[WIM_GUID_LEN],
930                              int image, const wchar_t *target,
931                              u64 *data_source_id_ret, bool *wof_running_ret)
932 {
933         tchar drive_path[7];
934         size_t wim_path_nchars;
935         size_t wim_file_name_length;
936         void *in;
937         size_t insize;
938         struct wof_external_info *wof_info;
939         struct wim_provider_add_overlay_input *wim_info;
940         HANDLE h;
941         u64 data_source_id;
942         DWORD bytes_returned;
943         int ret;
944         const wchar_t *prefix = L"\\??\\";
945         const size_t prefix_nchars = 4;
946         bool tried_to_attach_wof = false;
947
948         ret = win32_get_drive_path(target, drive_path);
949         if (ret)
950                 return ret;
951
952         wimlib_assert(!wcschr(wim_path, L'/'));
953         wimlib_assert(wim_path[0] != L'\0' && wim_path[1] == L':');
954
955         wim_path_nchars = wcslen(wim_path);
956         wim_file_name_length = sizeof(wchar_t) *
957                                (wim_path_nchars + prefix_nchars);
958
959         insize = sizeof(struct wof_external_info) +
960                  sizeof(struct wim_provider_add_overlay_input) +
961                  wim_file_name_length;
962
963         in = MALLOC(insize);
964         if (!in) {
965                 ret = WIMLIB_ERR_NOMEM;
966                 goto out;
967         }
968
969         wof_info = (struct wof_external_info *)in;
970         wof_info->version = WOF_CURRENT_VERSION;
971         wof_info->provider = WOF_PROVIDER_WIM;
972
973         wim_info = (struct wim_provider_add_overlay_input *)(wof_info + 1);
974         wim_info->wim_type = WIM_BOOT_NOT_OS_WIM;
975         wim_info->wim_index = image;
976         wim_info->wim_file_name_offset = offsetof(struct wim_provider_add_overlay_input,
977                                                   wim_file_name);
978         wim_info->wim_file_name_length = wim_file_name_length;
979         wmemcpy(&wim_info->wim_file_name[0], prefix, prefix_nchars);
980         wmemcpy(&wim_info->wim_file_name[prefix_nchars], wim_path, wim_path_nchars);
981
982 retry_ioctl:
983         h = open_file(drive_path, GENERIC_WRITE);
984
985         if (h == INVALID_HANDLE_VALUE) {
986                 win32_error(GetLastError(),
987                             L"Failed to open \"%ls\"", drive_path + 4);
988                 ret = WIMLIB_ERR_OPEN;
989                 goto out_free_in;
990         }
991
992         if (!DeviceIoControl(h, FSCTL_ADD_OVERLAY,
993                              in, insize,
994                              &data_source_id, sizeof(data_source_id),
995                              &bytes_returned, NULL))
996         {
997                 DWORD err = GetLastError();
998                 if (err == ERROR_INVALID_FUNCTION) {
999                         if (!tried_to_attach_wof) {
1000                                 CloseHandle(h);
1001                                 h = INVALID_HANDLE_VALUE;
1002                                 tried_to_attach_wof = true;
1003                                 if (try_to_attach_wof(drive_path + 4))
1004                                         goto retry_ioctl;
1005                         }
1006                         ret = WIMLIB_ERR_UNSUPPORTED;
1007                         goto out_close_handle;
1008                 } else {
1009                         win32_error(err, L"Failed to add overlay source \"%ls\" "
1010                                     "to volume \"%ls\"", wim_path, drive_path + 4);
1011                         ret = WIMLIB_ERR_WIMBOOT;
1012                         goto out_close_handle;
1013                 }
1014         }
1015
1016         if (bytes_returned != sizeof(data_source_id)) {
1017                 ret = WIMLIB_ERR_WIMBOOT;
1018                 ERROR("Unexpected result size when adding "
1019                       "overlay source \"%ls\" to volume \"%ls\"",
1020                       wim_path, drive_path + 4);
1021                 goto out_close_handle;
1022         }
1023
1024         *wof_running_ret = true;
1025         *data_source_id_ret = data_source_id;
1026         ret = 0;
1027
1028 out_close_handle:
1029         CloseHandle(h);
1030 out_free_in:
1031         FREE(in);
1032 out:
1033         if (ret == WIMLIB_ERR_UNSUPPORTED) {
1034         #if 0
1035                 WARNING(
1036                 "The version of Windows you are running does not appear to support\n"
1037                 "        the Windows Overlay File System Filter Driver.  This is normally\n"
1038                 "        available on Windows 8.1 Update 1 or later.  Therefore, wimlib\n"
1039                 "        will attempt to update the WimOverlay.dat file directly.\n");
1040         #else
1041                 WARNING("WOF driver is not available; updating WimOverlay.dat directly.");
1042         #endif
1043                 ret = update_wimoverlay_manually(drive_path + 4, wim_path,
1044                                                  wim_guid, image,
1045                                                  data_source_id_ret);
1046                 *wof_running_ret = false;
1047         }
1048         return ret;
1049 }
1050
1051
1052 /*
1053  * Set WIMBoot information on the specified file.
1054  *
1055  * This turns it into a reparse point that redirects accesses to it, to the
1056  * corresponding resource in the WIM archive.
1057  *
1058  * @h
1059  *      Open handle to the file, with GENERIC_WRITE access.
1060  * @blob
1061  *      The blob for the unnamed data stream of the file.
1062  * @data_source_id
1063  *      Allocated identifier for the WIM data source on the destination volume.
1064  * @blob_table_hash
1065  *      SHA-1 message digest of the WIM's blob table.
1066  * @wof_running
1067  *      %true if the WOF driver appears to be available and working; %false if
1068  *      not.
1069  *
1070  * Returns %true on success, or %false on failure with GetLastError() set.
1071  */
1072 bool
1073 wimboot_set_pointer(HANDLE h,
1074                     const struct blob_descriptor *blob,
1075                     u64 data_source_id,
1076                     const u8 blob_table_hash[SHA1_HASH_SIZE],
1077                     bool wof_running)
1078 {
1079         DWORD bytes_returned;
1080
1081         if (wof_running) {
1082                 /* The WOF driver is running.  We can create the reparse point
1083                  * using FSCTL_SET_EXTERNAL_BACKING.  */
1084                 unsigned int max_retries = 4;
1085                 struct {
1086                         struct wof_external_info wof_info;
1087                         struct wim_provider_external_info wim_info;
1088                 } in;
1089
1090         retry:
1091                 memset(&in, 0, sizeof(in));
1092
1093                 in.wof_info.version = WOF_CURRENT_VERSION;
1094                 in.wof_info.provider = WOF_PROVIDER_WIM;
1095
1096                 in.wim_info.version = WIM_PROVIDER_CURRENT_VERSION;
1097                 in.wim_info.flags = 0;
1098                 in.wim_info.data_source_id = data_source_id;
1099                 copy_hash(in.wim_info.unnamed_data_stream_hash, blob->hash);
1100
1101                 /* blob_table_hash is not necessary  */
1102
1103                 if (!DeviceIoControl(h, FSCTL_SET_EXTERNAL_BACKING,
1104                                      &in, sizeof(in), NULL, 0,
1105                                      &bytes_returned, NULL))
1106                 {
1107                         /* Try to track down sporadic errors  */
1108                         if (wimlib_print_errors) {
1109                                 WARNING("FSCTL_SET_EXTERNAL_BACKING failed (err=%u); data was %zu bytes:",
1110                                         (u32)GetLastError(), sizeof(in));
1111                                 print_byte_field((const u8 *)&in, sizeof(in), wimlib_error_file);
1112                                 putc('\n', wimlib_error_file);
1113                         }
1114                         if (--max_retries) {
1115                                 WARNING("Retrying after 100ms...");
1116                                 Sleep(100);
1117                                 goto retry;
1118                         }
1119                         WARNING("Too many retries; returning failure");
1120                         return false;
1121                 }
1122         } else {
1123
1124                 /* The WOF driver is running.  We need to create the reparse
1125                  * point manually.  */
1126
1127                 struct {
1128                         struct {
1129                                 le32 rptag;
1130                                 le16 rpdatalen;
1131                                 le16 rpreserved;
1132                         } hdr;
1133                         struct wof_external_info wof_info;
1134                         struct wim_provider_rpdata wim_info;
1135                 } in;
1136
1137                 BUILD_BUG_ON(sizeof(in) != 8 +
1138                              sizeof(struct wof_external_info) +
1139                              sizeof(struct wim_provider_rpdata));
1140
1141                 in.hdr.rptag = WIMLIB_REPARSE_TAG_WOF;
1142                 in.hdr.rpdatalen = sizeof(in) - sizeof(in.hdr);
1143                 in.hdr.rpreserved = 0;
1144
1145                 in.wof_info.version = WOF_CURRENT_VERSION;
1146                 in.wof_info.provider = WOF_PROVIDER_WIM;
1147
1148                 in.wim_info.version = 2;
1149                 in.wim_info.flags = 0;
1150                 in.wim_info.data_source_id = data_source_id;
1151                 copy_hash(in.wim_info.unnamed_data_stream_hash, blob->hash);
1152                 copy_hash(in.wim_info.blob_table_hash, blob_table_hash);
1153                 in.wim_info.unnamed_data_stream_size = blob->size;
1154                 in.wim_info.unnamed_data_stream_size_in_wim = blob->rdesc->size_in_wim;
1155                 in.wim_info.unnamed_data_stream_offset_in_wim = blob->rdesc->offset_in_wim;
1156
1157                 if (!DeviceIoControl(h, FSCTL_SET_REPARSE_POINT,
1158                                      &in, sizeof(in), NULL, 0, &bytes_returned, NULL))
1159                         return false;
1160
1161                 /* We also need to create an unnamed data stream of the correct
1162                  * size.  Otherwise the file shows up as zero length.  It can be
1163                  * a sparse stream containing all zeroes; its contents
1164                  * are unimportant.  */
1165                 if (!DeviceIoControl(h, FSCTL_SET_SPARSE, NULL, 0, NULL, 0,
1166                                      &bytes_returned, NULL))
1167                         return false;
1168
1169                 if (!SetFilePointerEx(h,
1170                                       (LARGE_INTEGER){ .QuadPart = blob->size},
1171                                       NULL, FILE_BEGIN))
1172                         return false;
1173
1174                 if (!SetEndOfFile(h))
1175                         return false;
1176         }
1177
1178         return true;
1179 }
1180
1181 #endif /* __WIN32__ */