4 * Code for reading blobs and resources, including compressed WIM resources.
8 * Copyright (C) 2012, 2013, 2015 Eric Biggers
10 * This file is free software; you can redistribute it and/or modify it under
11 * the terms of the GNU Lesser General Public License as published by the Free
12 * Software Foundation; either version 3 of the License, or (at your option) any
15 * This file is distributed in the hope that it will be useful, but WITHOUT
16 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
17 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
20 * You should have received a copy of the GNU Lesser General Public License
21 * along with this file; if not, see http://www.gnu.org/licenses/.
32 #include "wimlib/alloca.h"
33 #include "wimlib/assert.h"
34 #include "wimlib/bitops.h"
35 #include "wimlib/blob_table.h"
36 #include "wimlib/endianness.h"
37 #include "wimlib/error.h"
38 #include "wimlib/file_io.h"
39 #include "wimlib/ntfs_3g.h"
40 #include "wimlib/resource.h"
41 #include "wimlib/sha1.h"
42 #include "wimlib/wim.h"
43 #include "wimlib/win32.h"
46 * Compressed WIM resources
48 * A compressed resource in a WIM consists of a sequence of chunks. Each chunk
49 * decompresses to the same size except possibly for the last, which
50 * decompresses to the remaining size. Chunks that did not compress to less
51 * than their original size are stored uncompressed.
53 * We support three variations on this resource format, independently of the
54 * compression type and chunk size which can vary as well:
56 * - Original resource format: immediately before the compressed chunks, the
57 * "chunk table" provides the offset, in bytes relative to the end of the
58 * chunk table, of the start of each compressed chunk, except for the first
59 * chunk which is omitted as it always has an offset of 0. Chunk table
60 * entries are 32-bit for resources <= 4 GiB uncompressed and 64-bit for
61 * resources > 4 GiB uncompressed.
63 * - Solid resource format (distinguished by the use of WIM_RESHDR_FLAG_SOLID
64 * instead of WIM_RESHDR_FLAG_COMPRESSED): similar to the original format, but
65 * the resource begins with a 16-byte header which specifies the uncompressed
66 * size of the resource, the compression type, and the chunk size. (In the
67 * original format, these values were instead determined from outside the
68 * resource itself, from the blob table and the WIM file header.) In addition,
69 * in this format the entries in the chunk table contain compressed chunk
70 * sizes rather than offsets. As a consequence of this, the chunk table
71 * entries are always 32-bit and there is an entry for chunk 0.
73 * - Pipable resource format (wimlib extension; all resources in a pipable WIM
74 * have this format): similar to the original format, but the chunk table is
75 * at the end of the resource rather than the beginning, and each compressed
76 * chunk is prefixed with its compressed size as a 32-bit integer. This
77 * format allows a resource to be written without rewinding.
87 * Read data from a compressed WIM resource.
90 * Description of the compressed WIM resource to read from.
92 * Nonoverlapping, nonempty ranges of the uncompressed resource data to
93 * read, sorted by increasing offset.
95 * Number of ranges in @ranges; must be at least 1.
97 * Structure which provides the consume_chunk() callback to feed the data
98 * being read. Each call provides the next chunk of the requested data,
99 * uncompressed. Each chunk will be nonempty and will not cross range
100 * boundaries but otherwise will be of unspecified size.
102 * Possible return values:
104 * WIMLIB_ERR_SUCCESS (0)
105 * WIMLIB_ERR_READ (errno set)
106 * WIMLIB_ERR_UNEXPECTED_END_OF_FILE (errno set to EINVAL)
107 * WIMLIB_ERR_NOMEM (errno set to ENOMEM)
108 * WIMLIB_ERR_DECOMPRESSION (errno set to EINVAL)
109 * WIMLIB_ERR_INVALID_CHUNK_SIZE (errno set to EINVAL)
111 * or other error code returned by the cbs->consume_chunk() function.
114 read_compressed_wim_resource(const struct wim_resource_descriptor * const rdesc,
115 const struct data_range * const ranges,
116 const size_t num_ranges,
117 const struct read_blob_callbacks *cbs)
120 u64 *chunk_offsets = NULL;
123 bool chunk_offsets_malloced = false;
124 bool ubuf_malloced = false;
125 bool cbuf_malloced = false;
126 struct wimlib_decompressor *decompressor = NULL;
129 wimlib_assert(num_ranges != 0);
130 for (size_t i = 0; i < num_ranges; i++) {
131 wimlib_assert(ranges[i].offset + ranges[i].size > ranges[i].offset &&
132 ranges[i].offset + ranges[i].size <= rdesc->uncompressed_size);
134 for (size_t i = 0; i < num_ranges - 1; i++)
135 wimlib_assert(ranges[i].offset + ranges[i].size <= ranges[i + 1].offset);
137 /* Get the offsets of the first and last bytes of the read. */
138 const u64 first_offset = ranges[0].offset;
139 const u64 last_offset = ranges[num_ranges - 1].offset + ranges[num_ranges - 1].size - 1;
141 /* Get the file descriptor for the WIM. */
142 struct filedes * const in_fd = &rdesc->wim->in_fd;
144 /* Determine if we're reading a pipable resource from a pipe or not. */
145 const bool is_pipe_read = (rdesc->is_pipable && !filedes_is_seekable(in_fd));
147 /* Determine if the chunk table is in an alternate format. */
148 const bool alt_chunk_table = (rdesc->flags & WIM_RESHDR_FLAG_SOLID)
151 /* Get the maximum size of uncompressed chunks in this resource, which
152 * we require be a power of 2. */
153 u64 cur_read_offset = rdesc->offset_in_wim;
154 int ctype = rdesc->compression_type;
155 u32 chunk_size = rdesc->chunk_size;
156 if (alt_chunk_table) {
157 /* Alternate chunk table format. Its header specifies the chunk
158 * size and compression format. Note: it could be read here;
159 * however, the relevant data was already loaded into @rdesc by
160 * read_blob_table(). */
161 cur_read_offset += sizeof(struct alt_chunk_table_header_disk);
164 if (unlikely(!is_power_of_2(chunk_size))) {
165 ERROR("Invalid compressed resource: "
166 "expected power-of-2 chunk size (got %"PRIu32")",
168 ret = WIMLIB_ERR_INVALID_CHUNK_SIZE;
173 /* Get valid decompressor. */
174 if (likely(ctype == rdesc->wim->decompressor_ctype &&
175 chunk_size == rdesc->wim->decompressor_max_block_size))
177 /* Cached decompressor. */
178 decompressor = rdesc->wim->decompressor;
179 rdesc->wim->decompressor_ctype = WIMLIB_COMPRESSION_TYPE_NONE;
180 rdesc->wim->decompressor = NULL;
182 ret = wimlib_create_decompressor(ctype, chunk_size,
185 if (ret != WIMLIB_ERR_NOMEM)
191 const u32 chunk_order = fls32(chunk_size);
193 /* Calculate the total number of chunks the resource is divided into. */
194 const u64 num_chunks = (rdesc->uncompressed_size + chunk_size - 1) >> chunk_order;
196 /* Calculate the 0-based indices of the first and last chunks containing
197 * data that needs to be passed to the callback. */
198 const u64 first_needed_chunk = first_offset >> chunk_order;
199 const u64 last_needed_chunk = last_offset >> chunk_order;
201 /* Calculate the 0-based index of the first chunk that actually needs to
202 * be read. This is normally first_needed_chunk, but for pipe reads we
203 * must always start from the 0th chunk. */
204 const u64 read_start_chunk = (is_pipe_read ? 0 : first_needed_chunk);
206 /* Calculate the number of chunk offsets that are needed for the chunks
208 const u64 num_needed_chunk_offsets =
209 last_needed_chunk - read_start_chunk + 1 +
210 (last_needed_chunk < num_chunks - 1);
212 /* Calculate the number of entries in the chunk table. Normally, it's
213 * one less than the number of chunks, since the first chunk has no
214 * entry. But in the alternate chunk table format, the chunk entries
215 * contain chunk sizes, not offsets, and there is one per chunk. */
216 const u64 num_chunk_entries = (alt_chunk_table ? num_chunks : num_chunks - 1);
218 /* Set the size of each chunk table entry based on the resource's
219 * uncompressed size. */
220 const u64 chunk_entry_size = get_chunk_entry_size(rdesc->uncompressed_size,
223 /* Calculate the size of the chunk table in bytes. */
224 const u64 chunk_table_size = num_chunk_entries * chunk_entry_size;
226 /* Calculate the size of the chunk table in bytes, including the header
227 * in the case of the alternate chunk table format. */
228 const u64 chunk_table_full_size =
229 (alt_chunk_table) ? chunk_table_size + sizeof(struct alt_chunk_table_header_disk)
233 /* Read the needed chunk table entries into memory and use them
234 * to initialize the chunk_offsets array. */
236 u64 first_chunk_entry_to_read;
237 u64 last_chunk_entry_to_read;
239 if (alt_chunk_table) {
240 /* The alternate chunk table contains chunk sizes, not
241 * offsets, so we always must read all preceding entries
242 * in order to determine offsets. */
243 first_chunk_entry_to_read = 0;
244 last_chunk_entry_to_read = last_needed_chunk;
246 /* Here we must account for the fact that the first
247 * chunk has no explicit chunk table entry. */
249 if (read_start_chunk == 0)
250 first_chunk_entry_to_read = 0;
252 first_chunk_entry_to_read = read_start_chunk - 1;
254 if (last_needed_chunk == 0)
255 last_chunk_entry_to_read = 0;
257 last_chunk_entry_to_read = last_needed_chunk - 1;
259 if (last_needed_chunk < num_chunks - 1)
260 last_chunk_entry_to_read++;
263 const u64 num_chunk_entries_to_read =
264 last_chunk_entry_to_read - first_chunk_entry_to_read + 1;
266 const u64 chunk_offsets_alloc_size =
267 max(num_chunk_entries_to_read,
268 num_needed_chunk_offsets) * sizeof(chunk_offsets[0]);
270 if (unlikely((size_t)chunk_offsets_alloc_size != chunk_offsets_alloc_size)) {
275 if (likely(chunk_offsets_alloc_size <= STACK_MAX)) {
276 chunk_offsets = alloca(chunk_offsets_alloc_size);
278 chunk_offsets = MALLOC(chunk_offsets_alloc_size);
279 if (unlikely(!chunk_offsets))
281 chunk_offsets_malloced = true;
284 const size_t chunk_table_size_to_read =
285 num_chunk_entries_to_read * chunk_entry_size;
287 const u64 file_offset_of_needed_chunk_entries =
289 + (first_chunk_entry_to_read * chunk_entry_size)
290 + (rdesc->is_pipable ? (rdesc->size_in_wim - chunk_table_size) : 0);
292 void * const chunk_table_data =
294 chunk_offsets_alloc_size -
295 chunk_table_size_to_read;
297 ret = full_pread(in_fd, chunk_table_data, chunk_table_size_to_read,
298 file_offset_of_needed_chunk_entries);
302 /* Now fill in chunk_offsets from the entries we have read in
303 * chunk_tab_data. We break aliasing rules here to avoid having
304 * to allocate yet another array. */
305 typedef le64 _may_alias_attribute aliased_le64_t;
306 typedef le32 _may_alias_attribute aliased_le32_t;
307 u64 * chunk_offsets_p = chunk_offsets;
309 if (alt_chunk_table) {
311 aliased_le32_t *raw_entries = chunk_table_data;
313 for (size_t i = 0; i < num_chunk_entries_to_read; i++) {
314 u32 entry = le32_to_cpu(raw_entries[i]);
315 if (i >= read_start_chunk)
316 *chunk_offsets_p++ = cur_offset;
319 if (last_needed_chunk < num_chunks - 1)
320 *chunk_offsets_p = cur_offset;
322 if (read_start_chunk == 0)
323 *chunk_offsets_p++ = 0;
325 if (chunk_entry_size == 4) {
326 aliased_le32_t *raw_entries = chunk_table_data;
327 for (size_t i = 0; i < num_chunk_entries_to_read; i++)
328 *chunk_offsets_p++ = le32_to_cpu(raw_entries[i]);
330 aliased_le64_t *raw_entries = chunk_table_data;
331 for (size_t i = 0; i < num_chunk_entries_to_read; i++)
332 *chunk_offsets_p++ = le64_to_cpu(raw_entries[i]);
336 /* Set offset to beginning of first chunk to read. */
337 cur_read_offset += chunk_offsets[0];
338 if (rdesc->is_pipable)
339 cur_read_offset += read_start_chunk * sizeof(struct pwm_chunk_hdr);
341 cur_read_offset += chunk_table_size;
344 /* Allocate buffer for holding the uncompressed data of each chunk. */
345 if (chunk_size <= STACK_MAX) {
346 ubuf = alloca(chunk_size);
348 ubuf = MALLOC(chunk_size);
351 ubuf_malloced = true;
354 /* Allocate a temporary buffer for reading compressed chunks, each of
355 * which can be at most @chunk_size - 1 bytes. This excludes compressed
356 * chunks that are a full @chunk_size bytes, which are actually stored
358 if (chunk_size - 1 <= STACK_MAX) {
359 cbuf = alloca(chunk_size - 1);
361 cbuf = MALLOC(chunk_size - 1);
364 cbuf_malloced = true;
367 /* Set current data range. */
368 const struct data_range *cur_range = ranges;
369 const struct data_range * const end_range = &ranges[num_ranges];
370 u64 cur_range_pos = cur_range->offset;
371 u64 cur_range_end = cur_range->offset + cur_range->size;
373 /* Read and process each needed chunk. */
374 for (u64 i = read_start_chunk; i <= last_needed_chunk; i++) {
376 /* Calculate uncompressed size of next chunk. */
378 if ((i == num_chunks - 1) && (rdesc->uncompressed_size & (chunk_size - 1)))
379 chunk_usize = (rdesc->uncompressed_size & (chunk_size - 1));
381 chunk_usize = chunk_size;
383 /* Calculate compressed size of next chunk. */
386 struct pwm_chunk_hdr chunk_hdr;
388 ret = full_pread(in_fd, &chunk_hdr,
389 sizeof(chunk_hdr), cur_read_offset);
392 chunk_csize = le32_to_cpu(chunk_hdr.compressed_size);
394 if (i == num_chunks - 1) {
395 chunk_csize = rdesc->size_in_wim -
396 chunk_table_full_size -
397 chunk_offsets[i - read_start_chunk];
398 if (rdesc->is_pipable)
399 chunk_csize -= num_chunks * sizeof(struct pwm_chunk_hdr);
401 chunk_csize = chunk_offsets[i + 1 - read_start_chunk] -
402 chunk_offsets[i - read_start_chunk];
405 if (unlikely(chunk_csize == 0 || chunk_csize > chunk_usize)) {
406 ERROR("Invalid chunk size in compressed resource!");
408 ret = WIMLIB_ERR_DECOMPRESSION;
411 if (rdesc->is_pipable)
412 cur_read_offset += sizeof(struct pwm_chunk_hdr);
414 /* Offsets in the uncompressed resource at which this chunk
415 * starts and ends. */
416 const u64 chunk_start_offset = i << chunk_order;
417 const u64 chunk_end_offset = chunk_start_offset + chunk_usize;
419 if (chunk_end_offset <= cur_range_pos) {
421 /* The next range does not require data in this chunk,
423 cur_read_offset += chunk_csize;
427 ret = full_pread(in_fd, &dummy, 1, cur_read_offset - 1);
433 /* Read the chunk and feed data to the callback
437 if (chunk_csize == chunk_usize)
442 ret = full_pread(in_fd,
449 if (read_buf == cbuf) {
450 ret = wimlib_decompress(cbuf,
456 ERROR("Failed to decompress data!");
457 ret = WIMLIB_ERR_DECOMPRESSION;
462 cur_read_offset += chunk_csize;
464 /* At least one range requires data in this chunk. */
466 size_t start, end, size;
468 /* Calculate how many bytes of data should be
469 * sent to the callback function, taking into
470 * account that data sent to the callback
471 * function must not overlap range boundaries.
473 start = cur_range_pos - chunk_start_offset;
474 end = min(cur_range_end, chunk_end_offset) - chunk_start_offset;
477 ret = call_consume_chunk(&ubuf[start], size, cbs);
481 cur_range_pos += size;
482 if (cur_range_pos == cur_range_end) {
483 /* Advance to next range. */
484 if (++cur_range == end_range) {
485 cur_range_pos = ~0ULL;
487 cur_range_pos = cur_range->offset;
488 cur_range_end = cur_range->offset + cur_range->size;
491 } while (cur_range_pos < chunk_end_offset);
496 last_offset == rdesc->uncompressed_size - 1 &&
500 /* If reading a pipable resource from a pipe and the full data
501 * was requested, skip the chunk table at the end so that the
502 * file descriptor is fully clear of the resource after this
504 cur_read_offset += chunk_table_size;
505 ret = full_pread(in_fd, &dummy, 1, cur_read_offset - 1);
513 wimlib_free_decompressor(rdesc->wim->decompressor);
514 rdesc->wim->decompressor = decompressor;
515 rdesc->wim->decompressor_ctype = ctype;
516 rdesc->wim->decompressor_max_block_size = chunk_size;
518 if (chunk_offsets_malloced)
527 ERROR("Out of memory while reading compressed WIM resource");
528 ret = WIMLIB_ERR_NOMEM;
532 ERROR_WITH_ERRNO("Error reading data from WIM file");
536 /* Read raw data from a file descriptor at the specified offset, feeding the
537 * data in nonempty chunks into the cbs->consume_chunk() function. */
539 read_raw_file_data(struct filedes *in_fd, u64 offset, u64 size,
540 const struct read_blob_callbacks *cbs,
541 const tchar *filename)
544 size_t bytes_to_read;
548 bytes_to_read = min(sizeof(buf), size);
549 ret = full_pread(in_fd, buf, bytes_to_read, offset);
552 ret = call_consume_chunk(buf, bytes_to_read, cbs);
555 size -= bytes_to_read;
556 offset += bytes_to_read;
562 ERROR_WITH_ERRNO("Error reading data from WIM file");
563 } else if (ret == WIMLIB_ERR_UNEXPECTED_END_OF_FILE) {
564 ERROR("\"%"TS"\": File was concurrently truncated", filename);
565 ret = WIMLIB_ERR_CONCURRENT_MODIFICATION_DETECTED;
567 ERROR_WITH_ERRNO("\"%"TS"\": Error reading data", filename);
572 /* A consume_chunk() implementation that simply concatenates all chunks into an
573 * in-memory buffer. */
575 bufferer_cb(const void *chunk, size_t size, void *_ctx)
579 *buf_p = mempcpy(*buf_p, chunk, size);
584 * Read @size bytes at @offset in the WIM resource described by @rdesc and feed
585 * the data into the @cbs->consume_chunk callback function.
587 * @offset and @size are assumed to have already been validated against the
588 * resource's uncompressed size.
590 * Returns 0 on success; or the first nonzero value returned by the callback
591 * function; or a nonzero wimlib error code with errno set as well.
594 read_partial_wim_resource(const struct wim_resource_descriptor *rdesc,
595 const u64 offset, const u64 size,
596 const struct read_blob_callbacks *cbs)
598 if (rdesc->flags & (WIM_RESHDR_FLAG_COMPRESSED |
599 WIM_RESHDR_FLAG_SOLID))
601 /* Compressed resource */
604 struct data_range range = {
608 return read_compressed_wim_resource(rdesc, &range, 1, cbs);
611 /* Uncompressed resource */
612 return read_raw_file_data(&rdesc->wim->in_fd,
613 rdesc->offset_in_wim + offset,
617 /* Read the specified range of uncompressed data from the specified blob, which
618 * must be located in a WIM file, into the specified buffer. */
620 read_partial_wim_blob_into_buf(const struct blob_descriptor *blob,
621 u64 offset, size_t size, void *buf)
623 struct read_blob_callbacks cbs = {
624 .consume_chunk = bufferer_cb,
627 return read_partial_wim_resource(blob->rdesc,
628 blob->offset_in_res + offset,
633 /* Skip over the data of the specified WIM resource. */
635 skip_wim_resource(const struct wim_resource_descriptor *rdesc)
637 struct read_blob_callbacks cbs = {
639 return read_partial_wim_resource(rdesc, 0,
640 rdesc->uncompressed_size, &cbs);
644 read_wim_blob_prefix(const struct blob_descriptor *blob, u64 size,
645 const struct read_blob_callbacks *cbs)
647 return read_partial_wim_resource(blob->rdesc, blob->offset_in_res,
651 /* This function handles reading blob data that is located in an external file,
652 * such as a file that has been added to the WIM image through execution of a
653 * wimlib_add_command.
655 * This assumes the file can be accessed using the standard POSIX open(),
656 * read(), and close(). On Windows this will not necessarily be the case (since
657 * the file may need FILE_FLAG_BACKUP_SEMANTICS to be opened, or the file may be
658 * encrypted), so Windows uses its own code for its equivalent case. */
660 read_file_on_disk_prefix(const struct blob_descriptor *blob, u64 size,
661 const struct read_blob_callbacks *cbs)
667 raw_fd = topen(blob->file_on_disk, O_BINARY | O_RDONLY);
668 if (unlikely(raw_fd < 0)) {
669 ERROR_WITH_ERRNO("Can't open \"%"TS"\"", blob->file_on_disk);
670 return WIMLIB_ERR_OPEN;
672 filedes_init(&fd, raw_fd);
673 ret = read_raw_file_data(&fd, 0, size, cbs, blob->file_on_disk);
680 read_staging_file_prefix(const struct blob_descriptor *blob, u64 size,
681 const struct read_blob_callbacks *cbs)
687 raw_fd = openat(blob->staging_dir_fd, blob->staging_file_name,
688 O_RDONLY | O_NOFOLLOW);
689 if (unlikely(raw_fd < 0)) {
690 ERROR_WITH_ERRNO("Can't open staging file \"%s\"",
691 blob->staging_file_name);
692 return WIMLIB_ERR_OPEN;
694 filedes_init(&fd, raw_fd);
695 ret = read_raw_file_data(&fd, 0, size, cbs, blob->staging_file_name);
701 /* This function handles the trivial case of reading blob data that is, in fact,
702 * already located in an in-memory buffer. */
704 read_buffer_prefix(const struct blob_descriptor *blob,
705 u64 size, const struct read_blob_callbacks *cbs)
709 return call_consume_chunk(blob->attached_buffer, size, cbs);
712 typedef int (*read_blob_prefix_handler_t)(const struct blob_descriptor *blob,
714 const struct read_blob_callbacks *cbs);
717 * Read the first @size bytes from a generic "blob", which may be located in any
718 * one of several locations, such as in a WIM resource (possibly compressed), in
719 * an external file, or directly in an in-memory buffer. The blob data will be
720 * fed to the cbs->consume_chunk() callback function in chunks that are nonempty
721 * but otherwise are of unspecified size.
723 * Returns 0 on success; nonzero on error. A nonzero value will be returned if
724 * the blob data cannot be successfully read (for a number of different reasons,
725 * depending on the blob location), or if cbs->consume_chunk() returned nonzero
726 * in which case that error code will be returned.
729 read_blob_prefix(const struct blob_descriptor *blob, u64 size,
730 const struct read_blob_callbacks *cbs)
732 static const read_blob_prefix_handler_t handlers[] = {
733 [BLOB_IN_WIM] = read_wim_blob_prefix,
734 [BLOB_IN_FILE_ON_DISK] = read_file_on_disk_prefix,
735 [BLOB_IN_ATTACHED_BUFFER] = read_buffer_prefix,
737 [BLOB_IN_STAGING_FILE] = read_staging_file_prefix,
740 [BLOB_IN_NTFS_VOLUME] = read_ntfs_attribute_prefix,
743 [BLOB_IN_WINNT_FILE_ON_DISK] = read_winnt_stream_prefix,
744 [BLOB_WIN32_ENCRYPTED] = read_win32_encrypted_file_prefix,
747 wimlib_assert(blob->blob_location < ARRAY_LEN(handlers)
748 && handlers[blob->blob_location] != NULL);
749 wimlib_assert(size <= blob->size);
750 return handlers[blob->blob_location](blob, size, cbs);
753 /* Read the full data of the specified blob, passing the data into the specified
754 * callbacks (all of which are optional). */
756 read_blob_with_cbs(struct blob_descriptor *blob,
757 const struct read_blob_callbacks *cbs)
761 ret = call_begin_blob(blob, cbs);
765 ret = read_blob_prefix(blob, blob->size, cbs);
767 return call_end_blob(blob, ret, cbs);
770 /* Read the full uncompressed data of the specified blob into the specified
771 * buffer, which must have space for at least blob->size bytes. The SHA-1
772 * message digest is *not* checked. */
774 read_blob_into_buf(const struct blob_descriptor *blob, void *buf)
776 struct read_blob_callbacks cbs = {
777 .consume_chunk = bufferer_cb,
780 return read_blob_prefix(blob, blob->size, &cbs);
783 /* Retrieve the full uncompressed data of the specified blob. A buffer large
784 * enough hold the data is allocated and returned in @buf_ret. The SHA-1
785 * message digest is *not* checked. */
787 read_blob_into_alloc_buf(const struct blob_descriptor *blob, void **buf_ret)
792 if (unlikely((size_t)blob->size != blob->size)) {
793 ERROR("Can't read %"PRIu64" byte blob into memory", blob->size);
794 return WIMLIB_ERR_NOMEM;
797 buf = MALLOC(blob->size);
799 return WIMLIB_ERR_NOMEM;
801 ret = read_blob_into_buf(blob, buf);
811 /* Retrieve the full uncompressed data of a WIM resource specified as a raw
812 * `wim_reshdr' and the corresponding WIM file. A buffer large enough hold the
813 * data is allocated and returned in @buf_ret. */
815 wim_reshdr_to_data(const struct wim_reshdr *reshdr, WIMStruct *wim,
818 struct wim_resource_descriptor rdesc;
819 struct blob_descriptor blob;
821 wim_reshdr_to_desc_and_blob(reshdr, wim, &rdesc, &blob);
823 return read_blob_into_alloc_buf(&blob, buf_ret);
826 /* Calculate the SHA-1 message digest of the uncompressed data of the specified
829 wim_reshdr_to_hash(const struct wim_reshdr *reshdr, WIMStruct *wim,
830 u8 hash[SHA1_HASH_SIZE])
832 struct wim_resource_descriptor rdesc;
833 struct blob_descriptor blob;
836 wim_reshdr_to_desc_and_blob(reshdr, wim, &rdesc, &blob);
839 ret = sha1_blob(&blob);
843 copy_hash(hash, blob.hash);
847 struct blobifier_context {
848 struct read_blob_callbacks cbs;
849 struct blob_descriptor *cur_blob;
850 struct blob_descriptor *next_blob;
852 struct blob_descriptor *final_blob;
853 size_t list_head_offset;
856 static struct blob_descriptor *
857 next_blob(struct blob_descriptor *blob, size_t list_head_offset)
859 struct list_head *cur;
861 cur = (struct list_head*)((u8*)blob + list_head_offset);
863 return (struct blob_descriptor*)((u8*)cur->next - list_head_offset);
866 /* A consume_chunk() implementation that translates raw resource data into
867 * blobs, calling the begin_blob, consume_chunk, and end_blob callbacks as
870 blobifier_cb(const void *chunk, size_t size, void *_ctx)
872 struct blobifier_context *ctx = _ctx;
875 wimlib_assert(ctx->cur_blob != NULL);
876 wimlib_assert(size <= ctx->cur_blob->size - ctx->cur_blob_offset);
878 if (ctx->cur_blob_offset == 0) {
879 /* Starting a new blob. */
880 ret = call_begin_blob(ctx->cur_blob, &ctx->cbs);
885 ctx->cur_blob_offset += size;
887 ret = call_consume_chunk(chunk, size, &ctx->cbs);
891 if (ctx->cur_blob_offset == ctx->cur_blob->size) {
892 /* Finished reading all the data for a blob. */
894 ctx->cur_blob_offset = 0;
896 ret = call_end_blob(ctx->cur_blob, 0, &ctx->cbs);
900 /* Advance to next blob. */
901 ctx->cur_blob = ctx->next_blob;
902 if (ctx->cur_blob != NULL) {
903 if (ctx->cur_blob != ctx->final_blob)
904 ctx->next_blob = next_blob(ctx->cur_blob,
905 ctx->list_head_offset);
907 ctx->next_blob = NULL;
913 struct hasher_context {
916 struct read_blob_callbacks cbs;
919 /* Callback for starting to read a blob while calculating its SHA-1 message
922 hasher_begin_blob(struct blob_descriptor *blob, void *_ctx)
924 struct hasher_context *ctx = _ctx;
926 sha1_init(&ctx->sha_ctx);
928 return call_begin_blob(blob, &ctx->cbs);
931 /* A consume_chunk() implementation that continues calculating the SHA-1 message
932 * digest of the blob being read, then optionally passes the data on to another
933 * consume_chunk() implementation. This allows checking the SHA-1 message
934 * digest of a blob being extracted, for example. */
936 hasher_consume_chunk(const void *chunk, size_t size, void *_ctx)
938 struct hasher_context *ctx = _ctx;
940 sha1_update(&ctx->sha_ctx, chunk, size);
942 return call_consume_chunk(chunk, size, &ctx->cbs);
946 report_sha1_mismatch_error(const struct blob_descriptor *blob,
947 const u8 actual_hash[SHA1_HASH_SIZE])
949 tchar expected_hashstr[SHA1_HASH_SIZE * 2 + 1];
950 tchar actual_hashstr[SHA1_HASH_SIZE * 2 + 1];
952 wimlib_assert(blob->blob_location != BLOB_NONEXISTENT);
953 wimlib_assert(blob->blob_location != BLOB_IN_ATTACHED_BUFFER);
955 sprint_hash(blob->hash, expected_hashstr);
956 sprint_hash(actual_hash, actual_hashstr);
958 if (blob_is_in_file(blob)) {
959 ERROR("A file was concurrently modified!\n"
961 " Expected SHA-1: %"TS"\n"
962 " Actual SHA-1: %"TS"\n",
963 blob->file_on_disk, expected_hashstr, actual_hashstr);
964 return WIMLIB_ERR_CONCURRENT_MODIFICATION_DETECTED;
965 } else if (blob->blob_location == BLOB_IN_WIM) {
966 const struct wim_resource_descriptor *rdesc = blob->rdesc;
967 ERROR("A WIM resource is corrupted!\n"
968 " WIM file: \"%"TS"\"\n"
969 " Blob uncompressed size: %"PRIu64"\n"
970 " Resource offset in WIM: %"PRIu64"\n"
971 " Resource uncompressed size: %"PRIu64"\n"
972 " Resource size in WIM: %"PRIu64"\n"
973 " Resource flags: 0x%x%"TS"\n"
974 " Resource compression type: %"TS"\n"
975 " Resource compression chunk size: %"PRIu32"\n"
976 " Expected SHA-1: %"TS"\n"
977 " Actual SHA-1: %"TS"\n",
978 rdesc->wim->filename,
980 rdesc->offset_in_wim,
981 rdesc->uncompressed_size,
983 (unsigned int)rdesc->flags,
984 (rdesc->is_pipable ? T(", pipable") : T("")),
985 wimlib_get_compression_type_string(
986 rdesc->compression_type),
988 expected_hashstr, actual_hashstr);
989 return WIMLIB_ERR_INVALID_RESOURCE_HASH;
991 ERROR("File data was concurrently modified!\n"
993 " Expected SHA-1: %"TS"\n"
994 " Actual SHA-1: %"TS"\n",
995 (int)blob->blob_location,
996 expected_hashstr, actual_hashstr);
997 return WIMLIB_ERR_CONCURRENT_MODIFICATION_DETECTED;
1001 /* Callback for finishing reading a blob while calculating its SHA-1 message
1004 hasher_end_blob(struct blob_descriptor *blob, int status, void *_ctx)
1006 struct hasher_context *ctx = _ctx;
1007 u8 hash[SHA1_HASH_SIZE];
1010 if (unlikely(status)) {
1011 /* Error occurred; the full blob may not have been read. */
1016 /* Retrieve the final SHA-1 message digest. */
1017 sha1_final(hash, &ctx->sha_ctx);
1019 /* Set the SHA-1 message digest of the blob, or compare the calculated
1020 * value with stored value. */
1021 if (blob->unhashed) {
1022 if (ctx->flags & COMPUTE_MISSING_BLOB_HASHES)
1023 copy_hash(blob->hash, hash);
1024 } else if ((ctx->flags & VERIFY_BLOB_HASHES) &&
1025 unlikely(!hashes_equal(hash, blob->hash)))
1027 ret = report_sha1_mismatch_error(blob, hash);
1032 return call_end_blob(blob, ret, &ctx->cbs);
1035 /* Read the full data of the specified blob, passing the data into the specified
1036 * callbacks (all of which are optional) and either checking or computing the
1037 * SHA-1 message digest of the blob. */
1039 read_blob_with_sha1(struct blob_descriptor *blob,
1040 const struct read_blob_callbacks *cbs)
1042 struct hasher_context hasher_ctx = {
1043 .flags = VERIFY_BLOB_HASHES | COMPUTE_MISSING_BLOB_HASHES,
1046 struct read_blob_callbacks hasher_cbs = {
1047 .begin_blob = hasher_begin_blob,
1048 .consume_chunk = hasher_consume_chunk,
1049 .end_blob = hasher_end_blob,
1052 return read_blob_with_cbs(blob, &hasher_cbs);
1056 read_blobs_in_solid_resource(struct blob_descriptor *first_blob,
1057 struct blob_descriptor *last_blob,
1059 size_t list_head_offset,
1060 const struct read_blob_callbacks *sink_cbs)
1062 struct data_range *ranges;
1063 bool ranges_malloced;
1064 struct blob_descriptor *cur_blob;
1067 u64 ranges_alloc_size;
1069 /* Setup data ranges array (one range per blob to read); this way
1070 * read_compressed_wim_resource() does not need to be aware of blobs.
1073 ranges_alloc_size = (u64)blob_count * sizeof(ranges[0]);
1075 if (unlikely((size_t)ranges_alloc_size != ranges_alloc_size))
1078 if (ranges_alloc_size <= STACK_MAX) {
1079 ranges = alloca(ranges_alloc_size);
1080 ranges_malloced = false;
1082 ranges = MALLOC(ranges_alloc_size);
1083 if (unlikely(!ranges))
1085 ranges_malloced = true;
1088 for (i = 0, cur_blob = first_blob;
1090 i++, cur_blob = next_blob(cur_blob, list_head_offset))
1092 ranges[i].offset = cur_blob->offset_in_res;
1093 ranges[i].size = cur_blob->size;
1096 struct blobifier_context blobifier_ctx = {
1098 .cur_blob = first_blob,
1099 .next_blob = next_blob(first_blob, list_head_offset),
1100 .cur_blob_offset = 0,
1101 .final_blob = last_blob,
1102 .list_head_offset = list_head_offset,
1104 struct read_blob_callbacks cbs = {
1105 .consume_chunk = blobifier_cb,
1106 .ctx = &blobifier_ctx,
1109 ret = read_compressed_wim_resource(first_blob->rdesc, ranges,
1112 if (ranges_malloced)
1115 if (unlikely(ret && blobifier_ctx.cur_blob_offset != 0)) {
1116 ret = call_end_blob(blobifier_ctx.cur_blob, ret,
1117 &blobifier_ctx.cbs);
1122 ERROR("Too many blobs in one resource!");
1123 return WIMLIB_ERR_NOMEM;
1127 * Read a list of blobs, each of which may be in any supported location (e.g.
1128 * in a WIM or in an external file). This function optimizes the case where
1129 * multiple blobs are combined into a single solid compressed WIM resource by
1130 * reading the blobs in sequential order, only decompressing the solid resource
1134 * List of blobs to read.
1136 * Offset of the `struct list_head' within each `struct blob_descriptor'
1137 * that makes up the @blob_list.
1139 * Callback functions to accept the blob data.
1141 * Bitwise OR of zero or more of the following flags:
1143 * VERIFY_BLOB_HASHES:
1144 * For all blobs being read that have already had SHA-1 message
1145 * digests computed, calculate the SHA-1 message digest of the read
1146 * data and compare it with the previously computed value. If they
1147 * do not match, return WIMLIB_ERR_INVALID_RESOURCE_HASH.
1149 * COMPUTE_MISSING_BLOB_HASHES
1150 * For all blobs being read that have not yet had their SHA-1
1151 * message digests computed, calculate and save their SHA-1 message
1154 * BLOB_LIST_ALREADY_SORTED
1155 * @blob_list is already sorted in sequential order for reading.
1157 * The callback functions are allowed to delete the current blob from the list
1160 * Returns 0 on success; a nonzero error code on failure. Failure can occur due
1161 * to an error reading the data or due to an error status being returned by any
1162 * of the callback functions.
1165 read_blob_list(struct list_head *blob_list, size_t list_head_offset,
1166 const struct read_blob_callbacks *cbs, int flags)
1169 struct list_head *cur, *next;
1170 struct blob_descriptor *blob;
1171 struct hasher_context *hasher_ctx;
1172 struct read_blob_callbacks *sink_cbs;
1174 if (!(flags & BLOB_LIST_ALREADY_SORTED)) {
1175 ret = sort_blob_list_by_sequential_order(blob_list,
1181 if (flags & (VERIFY_BLOB_HASHES | COMPUTE_MISSING_BLOB_HASHES)) {
1182 hasher_ctx = alloca(sizeof(*hasher_ctx));
1183 *hasher_ctx = (struct hasher_context) {
1187 sink_cbs = alloca(sizeof(*sink_cbs));
1188 *sink_cbs = (struct read_blob_callbacks) {
1189 .begin_blob = hasher_begin_blob,
1190 .consume_chunk = hasher_consume_chunk,
1191 .end_blob = hasher_end_blob,
1195 sink_cbs = (struct read_blob_callbacks *)cbs;
1198 for (cur = blob_list->next, next = cur->next;
1200 cur = next, next = cur->next)
1202 blob = (struct blob_descriptor*)((u8*)cur - list_head_offset);
1204 if (blob->blob_location == BLOB_IN_WIM &&
1205 blob->size != blob->rdesc->uncompressed_size)
1207 struct blob_descriptor *blob_next, *blob_last;
1208 struct list_head *next2;
1211 /* The next blob is a proper sub-sequence of a WIM
1212 * resource. See if there are other blobs in the same
1213 * resource that need to be read. Since
1214 * sort_blob_list_by_sequential_order() sorted the blobs
1215 * by offset in the WIM, this can be determined by
1216 * simply scanning forward in the list. */
1222 && (blob_next = (struct blob_descriptor*)
1223 ((u8*)next2 - list_head_offset),
1224 blob_next->blob_location == BLOB_IN_WIM
1225 && blob_next->rdesc == blob->rdesc);
1226 next2 = next2->next)
1228 blob_last = blob_next;
1231 if (blob_count > 1) {
1232 /* Reading multiple blobs combined into a single
1233 * WIM resource. They are in the blob list,
1234 * sorted by offset; @blob specifies the first
1235 * blob in the resource that needs to be read
1236 * and @blob_last specifies the last blob in the
1237 * resource that needs to be read. */
1239 ret = read_blobs_in_solid_resource(blob, blob_last,
1249 ret = read_blob_with_cbs(blob, sink_cbs);
1250 if (unlikely(ret && ret != BEGIN_BLOB_STATUS_SKIP_BLOB))
1257 extract_chunk_to_fd(const void *chunk, size_t size, void *_fd)
1259 struct filedes *fd = _fd;
1260 int ret = full_write(fd, chunk, size);
1262 ERROR_WITH_ERRNO("Error writing to file descriptor");
1266 /* Extract the first @size bytes of the specified blob to the specified file
1267 * descriptor. This does *not* check the SHA-1 message digest. */
1269 extract_blob_prefix_to_fd(struct blob_descriptor *blob, u64 size,
1272 struct read_blob_callbacks cbs = {
1273 .consume_chunk = extract_chunk_to_fd,
1276 return read_blob_prefix(blob, size, &cbs);
1279 /* Extract the full uncompressed contents of the specified blob to the specified
1280 * file descriptor. This checks the SHA-1 message digest. */
1282 extract_blob_to_fd(struct blob_descriptor *blob, struct filedes *fd)
1284 struct read_blob_callbacks cbs = {
1285 .consume_chunk = extract_chunk_to_fd,
1288 return read_blob_with_sha1(blob, &cbs);
1291 /* Calculate the SHA-1 message digest of a blob and store it in @blob->hash. */
1293 sha1_blob(struct blob_descriptor *blob)
1295 struct read_blob_callbacks cbs = {
1297 return read_blob_with_sha1(blob, &cbs);
1301 * Convert a short WIM resource header to a stand-alone WIM resource descriptor.
1303 * Note: for solid resources some fields still need to be overridden.
1306 wim_reshdr_to_desc(const struct wim_reshdr *reshdr, WIMStruct *wim,
1307 struct wim_resource_descriptor *rdesc)
1310 rdesc->offset_in_wim = reshdr->offset_in_wim;
1311 rdesc->size_in_wim = reshdr->size_in_wim;
1312 rdesc->uncompressed_size = reshdr->uncompressed_size;
1313 INIT_LIST_HEAD(&rdesc->blob_list);
1314 rdesc->flags = reshdr->flags;
1315 rdesc->is_pipable = wim_is_pipable(wim);
1316 if (rdesc->flags & WIM_RESHDR_FLAG_COMPRESSED) {
1317 rdesc->compression_type = wim->compression_type;
1318 rdesc->chunk_size = wim->chunk_size;
1320 rdesc->compression_type = WIMLIB_COMPRESSION_TYPE_NONE;
1321 rdesc->chunk_size = 0;
1326 * Convert the short WIM resource header @reshdr to a stand-alone WIM resource
1327 * descriptor @rdesc, then set @blob to consist of that entire resource. This
1328 * should only be used for non-solid resources!
1331 wim_reshdr_to_desc_and_blob(const struct wim_reshdr *reshdr, WIMStruct *wim,
1332 struct wim_resource_descriptor *rdesc,
1333 struct blob_descriptor *blob)
1335 wim_reshdr_to_desc(reshdr, wim, rdesc);
1336 blob->size = rdesc->uncompressed_size;
1337 blob_set_is_located_in_wim_resource(blob, rdesc, 0);
1340 /* Import a WIM resource header from the on-disk format. */
1342 get_wim_reshdr(const struct wim_reshdr_disk *disk_reshdr,
1343 struct wim_reshdr *reshdr)
1345 reshdr->offset_in_wim = le64_to_cpu(disk_reshdr->offset_in_wim);
1346 reshdr->size_in_wim = (((u64)disk_reshdr->size_in_wim[0] << 0) |
1347 ((u64)disk_reshdr->size_in_wim[1] << 8) |
1348 ((u64)disk_reshdr->size_in_wim[2] << 16) |
1349 ((u64)disk_reshdr->size_in_wim[3] << 24) |
1350 ((u64)disk_reshdr->size_in_wim[4] << 32) |
1351 ((u64)disk_reshdr->size_in_wim[5] << 40) |
1352 ((u64)disk_reshdr->size_in_wim[6] << 48));
1353 reshdr->uncompressed_size = le64_to_cpu(disk_reshdr->uncompressed_size);
1354 reshdr->flags = disk_reshdr->flags;
1357 /* Export a WIM resource header to the on-disk format. */
1359 put_wim_reshdr(const struct wim_reshdr *reshdr,
1360 struct wim_reshdr_disk *disk_reshdr)
1362 disk_reshdr->size_in_wim[0] = reshdr->size_in_wim >> 0;
1363 disk_reshdr->size_in_wim[1] = reshdr->size_in_wim >> 8;
1364 disk_reshdr->size_in_wim[2] = reshdr->size_in_wim >> 16;
1365 disk_reshdr->size_in_wim[3] = reshdr->size_in_wim >> 24;
1366 disk_reshdr->size_in_wim[4] = reshdr->size_in_wim >> 32;
1367 disk_reshdr->size_in_wim[5] = reshdr->size_in_wim >> 40;
1368 disk_reshdr->size_in_wim[6] = reshdr->size_in_wim >> 48;
1369 disk_reshdr->flags = reshdr->flags;
1370 disk_reshdr->offset_in_wim = cpu_to_le64(reshdr->offset_in_wim);
1371 disk_reshdr->uncompressed_size = cpu_to_le64(reshdr->uncompressed_size);