4 * Code for reading streams and resources, including compressed WIM resources.
8 * Copyright (C) 2012, 2013 Eric Biggers
10 * This file is part of wimlib, a library for working with WIM files.
12 * wimlib is free software; you can redistribute it and/or modify it under the
13 * terms of the GNU General Public License as published by the Free Software
14 * Foundation; either version 3 of the License, or (at your option) any later
17 * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
18 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
19 * A PARTICULAR PURPOSE. See the GNU General Public License for more details.
21 * You should have received a copy of the GNU General Public License along with
22 * wimlib; if not, see http://www.gnu.org/licenses/.
30 #include "wimlib/assert.h"
31 #include "wimlib/endianness.h"
32 #include "wimlib/error.h"
33 #include "wimlib/file_io.h"
34 #include "wimlib/lookup_table.h"
35 #include "wimlib/resource.h"
36 #include "wimlib/sha1.h"
37 #include "wimlib/wim.h"
40 /* for read_win32_file_prefix(), read_win32_encrypted_file_prefix() */
41 # include "wimlib/win32.h"
45 /* for read_ntfs_file_prefix() */
46 # include "wimlib/ntfs_3g.h"
58 * Compressed WIM resources
60 * A compressed resource in a WIM consists of a number of compressed chunks,
61 * each of which decompresses to a fixed chunk size (given in the WIM header;
62 * usually 32768) except possibly the last, which always decompresses to any
63 * remaining bytes. In addition, immediately before the chunks, a table (the
64 * "chunk table") provides the offset, in bytes relative to the end of the chunk
65 * table, of the start of each compressed chunk, except for the first chunk
66 * which is omitted as it always has an offset of 0. Therefore, a compressed
67 * resource with N chunks will have a chunk table with N - 1 entries.
69 * Additional information:
71 * - Entries in the chunk table are 4 bytes each, except if the uncompressed
72 * size of the resource is greater than 4 GiB, in which case the entries in
73 * the chunk table are 8 bytes each. In either case, the entries are unsigned
74 * little-endian integers.
76 * - The chunk table is included in the compressed size of the resource provided
77 * in the corresponding entry in the WIM's stream lookup table.
79 * - The compressed size of a chunk is never greater than the uncompressed size.
80 * From the compressor's point of view, chunks that would have compressed to a
81 * size greater than or equal to their original size are in fact stored
82 * uncompressed. From the decompresser's point of view, chunks with
83 * compressed size equal to their uncompressed size are in fact uncompressed.
85 * Furthermore, wimlib supports its own "pipable" WIM format, and for this the
86 * structure of compressed resources was modified to allow piped reading and
87 * writing. To make sequential writing possible, the chunk table is placed
88 * after the chunks rather than before the chunks, and to make sequential
89 * reading possible, each chunk is prefixed with a 4-byte header giving its
90 * compressed size as a 32-bit, unsigned, little-endian integer. Otherwise the
91 * details are the same.
101 * read_compressed_wim_resource() -
103 * Read data from a compressed WIM resource.
106 * Specification of the compressed WIM resource to read from.
108 * Nonoverlapping, nonempty ranges of the uncompressed resource data to
109 * read, sorted by increasing offset.
111 * Number of ranges in @ranges; must be at least 1.
113 * Callback function to feed the data being read. Each call provides the
114 * next chunk of the requested data, uncompressed. Each chunk will be of
115 * nonzero size and will not cross range boundaries, but otherwise will be
116 * of unspecified size.
118 * Parameter to pass to @cb_ctx.
120 * Possible return values:
122 * WIMLIB_ERR_SUCCESS (0)
123 * WIMLIB_ERR_READ (errno set)
124 * WIMLIB_ERR_UNEXPECTED_END_OF_FILE (errno set to 0)
125 * WIMLIB_ERR_NOMEM (errno set to ENOMEM)
126 * WIMLIB_ERR_DECOMPRESSION (errno set to EINVAL)
128 * or other error code returned by the @cb function.
131 read_compressed_wim_resource(const struct wim_resource_spec * const rspec,
132 const struct data_range * const ranges,
133 const size_t num_ranges,
134 const consume_data_callback_t cb,
140 u64 *chunk_offsets = NULL;
143 bool chunk_offsets_malloced = false;
144 bool ubuf_malloced = false;
145 bool cbuf_malloced = false;
146 struct wimlib_decompressor *decompressor = NULL;
149 wimlib_assert(rspec != NULL);
150 wimlib_assert(resource_is_compressed(rspec));
151 wimlib_assert(cb != NULL);
152 wimlib_assert(num_ranges != 0);
153 for (size_t i = 0; i < num_ranges; i++) {
154 DEBUG("Range %zu/%zu: %"PRIu64"@+%"PRIu64" / %"PRIu64,
155 i + 1, num_ranges, ranges[i].size, ranges[i].offset,
156 rspec->uncompressed_size);
157 wimlib_assert(ranges[i].size != 0);
158 wimlib_assert(ranges[i].offset + ranges[i].size >= ranges[i].size);
159 wimlib_assert(ranges[i].offset + ranges[i].size <= rspec->uncompressed_size);
161 for (size_t i = 0; i < num_ranges - 1; i++)
162 wimlib_assert(ranges[i].offset + ranges[i].size <= ranges[i + 1].offset);
164 /* Get the offsets of the first and last bytes of the read. */
165 const u64 first_offset = ranges[0].offset;
166 const u64 last_offset = ranges[num_ranges - 1].offset + ranges[num_ranges - 1].size - 1;
168 /* Get the file descriptor for the WIM. */
169 struct filedes * const in_fd = &rspec->wim->in_fd;
171 /* Determine if we're reading a pipable resource from a pipe or not. */
172 const bool is_pipe_read = !filedes_is_seekable(in_fd);
174 /* Determine if the chunk table is in an altenate format. */
175 const bool alt_chunk_table = (rspec->flags & WIM_RESHDR_FLAG_PACKED_STREAMS)
178 /* Get the maximum size of uncompressed chunks in this resource, which
179 * we require be a power of 2. */
180 u64 cur_read_offset = rspec->offset_in_wim;
181 int ctype = rspec->compression_type;
182 u32 chunk_size = rspec->chunk_size;
183 if (alt_chunk_table) {
184 /* Alternate chunk table format. Its header specifies the chunk
185 * size and compression format. Note: it could be read here;
186 * however, the relevant data was already loaded into @rspec by
187 * read_wim_lookup_table(). */
188 cur_read_offset += sizeof(struct alt_chunk_table_header_disk);
191 if (!is_power_of_2(chunk_size)) {
192 ERROR("Invalid compressed resource: "
193 "expected power-of-2 chunk size (got %"PRIu32")",
195 ret = WIMLIB_ERR_INVALID_CHUNK_SIZE;
196 goto out_free_memory;
199 /* Get valid decompressor. */
200 if (ctype == rspec->wim->decompressor_ctype &&
201 chunk_size == rspec->wim->decompressor_max_block_size)
203 /* Cached decompressor. */
204 decompressor = rspec->wim->decompressor;
205 rspec->wim->decompressor_ctype = WIMLIB_COMPRESSION_TYPE_NONE;
206 rspec->wim->decompressor = NULL;
208 ret = wimlib_create_decompressor(ctype, chunk_size, NULL,
211 goto out_free_memory;
214 const u32 chunk_order = bsr32(chunk_size);
216 /* Calculate the total number of chunks the resource is divided into. */
217 const u64 num_chunks = (rspec->uncompressed_size + chunk_size - 1) >> chunk_order;
219 /* Calculate the 0-based indices of the first and last chunks containing
220 * data that needs to be passed to the callback. */
221 const u64 first_needed_chunk = first_offset >> chunk_order;
222 const u64 last_needed_chunk = last_offset >> chunk_order;
224 /* Calculate the 0-based index of the first chunk that actually needs to
225 * be read. This is normally first_needed_chunk, but for pipe reads we
226 * must always start from the 0th chunk. */
227 const u64 read_start_chunk = (is_pipe_read ? 0 : first_needed_chunk);
229 /* Calculate the number of chunk offsets that are needed for the chunks
231 const u64 num_needed_chunk_offsets =
232 last_needed_chunk - read_start_chunk + 1 +
233 (last_needed_chunk < num_chunks - 1);
235 /* Calculate the number of entries in the chunk table. Normally, it's
236 * one less than the number of chunks, since the first chunk has no
237 * entry. But in the alternate chunk table format, the chunk entries
238 * contain chunk sizes, not offsets, and there is one per chunk. */
239 const u64 num_chunk_entries = (alt_chunk_table ? num_chunks : num_chunks - 1);
241 /* Set the size of each chunk table entry based on the resource's
242 * uncompressed size. */
243 const u64 chunk_entry_size = get_chunk_entry_size(rspec->uncompressed_size,
246 /* Calculate the size of the chunk table in bytes. */
247 const u64 chunk_table_size = num_chunk_entries * chunk_entry_size;
249 /* Calculate the size of the chunk table in bytes, including the header
250 * in the case of the alternate chunk table format. */
251 const u64 chunk_table_full_size =
252 (alt_chunk_table) ? chunk_table_size + sizeof(struct alt_chunk_table_header_disk)
256 /* Read the needed chunk table entries into memory and use them
257 * to initialize the chunk_offsets array. */
259 u64 first_chunk_entry_to_read;
260 u64 last_chunk_entry_to_read;
262 if (alt_chunk_table) {
263 /* The alternate chunk table contains chunk sizes, not
264 * offsets, so we always must read all preceding entries
265 * in order to determine offsets. */
266 first_chunk_entry_to_read = 0;
267 last_chunk_entry_to_read = last_needed_chunk;
269 /* Here we must account for the fact that the first
270 * chunk has no explicit chunk table entry. */
272 if (read_start_chunk == 0)
273 first_chunk_entry_to_read = 0;
275 first_chunk_entry_to_read = read_start_chunk - 1;
277 if (last_needed_chunk == 0)
278 last_chunk_entry_to_read = 0;
280 last_chunk_entry_to_read = last_needed_chunk - 1;
282 if (last_needed_chunk < num_chunks - 1)
283 last_chunk_entry_to_read++;
286 const u64 num_chunk_entries_to_read =
287 last_chunk_entry_to_read - first_chunk_entry_to_read + 1;
289 const u64 chunk_offsets_alloc_size =
290 max(num_chunk_entries_to_read,
291 num_needed_chunk_offsets) * sizeof(chunk_offsets[0]);
293 if ((size_t)chunk_offsets_alloc_size != chunk_offsets_alloc_size)
296 if (chunk_offsets_alloc_size <= STACK_MAX) {
297 chunk_offsets = alloca(chunk_offsets_alloc_size);
299 chunk_offsets = MALLOC(chunk_offsets_alloc_size);
300 if (chunk_offsets == NULL)
302 chunk_offsets_malloced = true;
305 const size_t chunk_table_size_to_read =
306 num_chunk_entries_to_read * chunk_entry_size;
308 const u64 file_offset_of_needed_chunk_entries =
310 + (first_chunk_entry_to_read * chunk_entry_size)
311 + (rspec->is_pipable ? (rspec->size_in_wim - chunk_table_size) : 0);
313 void * const chunk_table_data =
315 chunk_offsets_alloc_size -
316 chunk_table_size_to_read;
318 ret = full_pread(in_fd, chunk_table_data, chunk_table_size_to_read,
319 file_offset_of_needed_chunk_entries);
323 /* Now fill in chunk_offsets from the entries we have read in
324 * chunk_tab_data. We break aliasing rules here to avoid having
325 * to allocate yet another array. */
326 typedef le64 __attribute__((may_alias)) aliased_le64_t;
327 typedef le32 __attribute__((may_alias)) aliased_le32_t;
328 u64 * chunk_offsets_p = chunk_offsets;
330 if (alt_chunk_table) {
332 aliased_le32_t *raw_entries = chunk_table_data;
334 for (size_t i = 0; i < num_chunk_entries_to_read; i++) {
335 u32 entry = le32_to_cpu(raw_entries[i]);
336 if (i >= read_start_chunk)
337 *chunk_offsets_p++ = cur_offset;
340 if (last_needed_chunk < num_chunks - 1)
341 *chunk_offsets_p = cur_offset;
343 if (read_start_chunk == 0)
344 *chunk_offsets_p++ = 0;
346 if (chunk_entry_size == 4) {
347 aliased_le32_t *raw_entries = chunk_table_data;
348 for (size_t i = 0; i < num_chunk_entries_to_read; i++)
349 *chunk_offsets_p++ = le32_to_cpu(raw_entries[i]);
351 aliased_le64_t *raw_entries = chunk_table_data;
352 for (size_t i = 0; i < num_chunk_entries_to_read; i++)
353 *chunk_offsets_p++ = le64_to_cpu(raw_entries[i]);
357 /* Set offset to beginning of first chunk to read. */
358 cur_read_offset += chunk_offsets[0];
359 if (rspec->is_pipable)
360 cur_read_offset += read_start_chunk * sizeof(struct pwm_chunk_hdr);
362 cur_read_offset += chunk_table_size;
365 /* Allocate buffer for holding the uncompressed data of each chunk. */
366 if (chunk_size <= STACK_MAX) {
367 ubuf = alloca(chunk_size);
369 ubuf = MALLOC(chunk_size);
372 ubuf_malloced = true;
375 /* Allocate a temporary buffer for reading compressed chunks, each of
376 * which can be at most @chunk_size - 1 bytes. This excludes compressed
377 * chunks that are a full @chunk_size bytes, which are actually stored
379 if (chunk_size - 1 <= STACK_MAX) {
380 cbuf = alloca(chunk_size - 1);
382 cbuf = MALLOC(chunk_size - 1);
385 cbuf_malloced = true;
388 /* Set current data range. */
389 const struct data_range *cur_range = ranges;
390 const struct data_range * const end_range = &ranges[num_ranges];
391 u64 cur_range_pos = cur_range->offset;
392 u64 cur_range_end = cur_range->offset + cur_range->size;
394 /* Read and process each needed chunk. */
395 for (u64 i = read_start_chunk; i <= last_needed_chunk; i++) {
397 /* Calculate uncompressed size of next chunk. */
399 if ((i == num_chunks - 1) && (rspec->uncompressed_size & (chunk_size - 1)))
400 chunk_usize = (rspec->uncompressed_size & (chunk_size - 1));
402 chunk_usize = chunk_size;
404 /* Calculate compressed size of next chunk. */
407 struct pwm_chunk_hdr chunk_hdr;
409 ret = full_pread(in_fd, &chunk_hdr,
410 sizeof(chunk_hdr), cur_read_offset);
413 chunk_csize = le32_to_cpu(chunk_hdr.compressed_size);
415 if (i == num_chunks - 1) {
416 chunk_csize = rspec->size_in_wim -
417 chunk_table_full_size -
418 chunk_offsets[i - read_start_chunk];
419 if (rspec->is_pipable)
420 chunk_csize -= num_chunks * sizeof(struct pwm_chunk_hdr);
422 chunk_csize = chunk_offsets[i + 1 - read_start_chunk] -
423 chunk_offsets[i - read_start_chunk];
426 if (chunk_csize == 0 || chunk_csize > chunk_usize) {
427 ERROR("Invalid chunk size in compressed resource!");
429 ret = WIMLIB_ERR_DECOMPRESSION;
430 goto out_free_memory;
432 if (rspec->is_pipable)
433 cur_read_offset += sizeof(struct pwm_chunk_hdr);
435 /* Offsets in the uncompressed resource at which this chunk
436 * starts and ends. */
437 const u64 chunk_start_offset = i << chunk_order;
438 const u64 chunk_end_offset = chunk_start_offset + chunk_usize;
440 if (chunk_end_offset <= cur_range_pos) {
442 /* The next range does not require data in this chunk,
444 cur_read_offset += chunk_csize;
448 ret = full_pread(in_fd, &dummy, 1, cur_read_offset - 1);
454 /* Read the chunk and feed data to the callback
458 if (chunk_csize == chunk_usize)
463 ret = full_pread(in_fd,
470 if (read_buf == cbuf) {
471 DEBUG("Decompressing chunk %"PRIu64" "
472 "(csize=%"PRIu32" usize=%"PRIu32")",
473 i, chunk_csize, chunk_usize);
474 ret = wimlib_decompress(cbuf,
480 ERROR("Failed to decompress data!");
481 ret = WIMLIB_ERR_DECOMPRESSION;
483 goto out_free_memory;
486 cur_read_offset += chunk_csize;
488 /* At least one range requires data in this chunk. */
490 size_t start, end, size;
492 /* Calculate how many bytes of data should be
493 * sent to the callback function, taking into
494 * account that data sent to the callback
495 * function must not overlap range boundaries.
497 start = cur_range_pos - chunk_start_offset;
498 end = min(cur_range_end, chunk_end_offset) - chunk_start_offset;
501 ret = (*cb)(&ubuf[start], size, cb_ctx);
504 goto out_free_memory;
506 cur_range_pos += size;
507 if (cur_range_pos == cur_range_end) {
508 /* Advance to next range. */
509 if (++cur_range == end_range) {
510 cur_range_pos = ~0ULL;
512 cur_range_pos = cur_range->offset;
513 cur_range_end = cur_range->offset + cur_range->size;
516 } while (cur_range_pos < chunk_end_offset);
521 last_offset == rspec->uncompressed_size - 1 &&
525 /* If reading a pipable resource from a pipe and the full data
526 * was requested, skip the chunk table at the end so that the
527 * file descriptor is fully clear of the resource after this
529 cur_read_offset += chunk_table_size;
530 ret = full_pread(in_fd, &dummy, 1, cur_read_offset - 1);
539 wimlib_free_decompressor(rspec->wim->decompressor);
540 rspec->wim->decompressor = decompressor;
541 rspec->wim->decompressor_ctype = ctype;
542 rspec->wim->decompressor_max_block_size = chunk_size;
544 if (chunk_offsets_malloced)
554 ERROR("Not enough memory available to read size=%"PRIu64" bytes "
555 "from compressed WIM resource!", last_offset - first_offset + 1);
557 ret = WIMLIB_ERR_NOMEM;
558 goto out_free_memory;
561 ERROR_WITH_ERRNO("Error reading compressed WIM resource!");
562 goto out_free_memory;
565 /* Read raw data from a file descriptor at the specified offset, feeding the
566 * data it in chunks into the specified callback function. */
568 read_raw_file_data(struct filedes *in_fd, u64 offset, u64 size,
569 consume_data_callback_t cb, void *cb_ctx)
572 size_t bytes_to_read;
576 bytes_to_read = min(sizeof(buf), size);
577 ret = full_pread(in_fd, buf, bytes_to_read, offset);
579 ERROR_WITH_ERRNO("Read error");
582 ret = cb(buf, bytes_to_read, cb_ctx);
585 size -= bytes_to_read;
586 offset += bytes_to_read;
591 /* A consume_data_callback_t implementation that simply concatenates all chunks
594 bufferer_cb(const void *chunk, size_t size, void *_ctx)
598 *buf_p = mempcpy(*buf_p, chunk, size);
603 * read_partial_wim_resource()-
605 * Read a range of data from an uncompressed or compressed resource in a WIM
609 * Specification of the WIM resource to read from.
611 * Offset within the uncompressed resource at which to start reading.
613 * Number of bytes to read.
615 * Callback function to feed the data being read. Each call provides the
616 * next chunk of the requested data, uncompressed. Each chunk will be of
617 * nonzero size and will not cross range boundaries, but otherwise will be
618 * of unspecified size.
620 * Parameter to pass to @cb_ctx.
623 * WIMLIB_ERR_SUCCESS (0)
624 * WIMLIB_ERR_READ (errno set)
625 * WIMLIB_ERR_UNEXPECTED_END_OF_FILE (errno set to 0)
626 * WIMLIB_ERR_NOMEM (errno set to ENOMEM)
627 * WIMLIB_ERR_DECOMPRESSION (errno set to EINVAL)
629 * or other error code returned by the @cb function.
632 read_partial_wim_resource(const struct wim_resource_spec *rspec,
633 u64 offset, u64 size,
634 consume_data_callback_t cb, void *cb_ctx)
637 wimlib_assert(offset + size >= offset);
638 wimlib_assert(offset + size <= rspec->uncompressed_size);
640 DEBUG("Reading %"PRIu64" @ %"PRIu64" from WIM resource "
641 "%"PRIu64" => %"PRIu64" @ %"PRIu64,
642 size, offset, rspec->uncompressed_size,
643 rspec->size_in_wim, rspec->offset_in_wim);
649 if (resource_is_compressed(rspec)) {
650 struct data_range range = {
654 return read_compressed_wim_resource(rspec, &range, 1,
657 return read_raw_file_data(&rspec->wim->in_fd,
658 rspec->offset_in_wim + offset,
665 /* Read the specified range of uncompressed data from the specified stream,
666 * which must be located into a WIM file, into the specified buffer. */
668 read_partial_wim_stream_into_buf(const struct wim_lookup_table_entry *lte,
669 size_t size, u64 offset, void *_buf)
673 wimlib_assert(lte->resource_location == RESOURCE_IN_WIM);
675 return read_partial_wim_resource(lte->rspec,
676 lte->offset_in_res + offset,
682 /* A consume_data_callback_t implementation that simply ignores the data
685 skip_chunk_cb(const void *chunk, size_t size, void *_ctx)
690 /* Skip over the data of the specified stream, which must correspond to a full
693 skip_wim_stream(struct wim_lookup_table_entry *lte)
695 wimlib_assert(lte->resource_location == RESOURCE_IN_WIM);
696 wimlib_assert(!(lte->flags & WIM_RESHDR_FLAG_PACKED_STREAMS));
697 DEBUG("Skipping stream (size=%"PRIu64")", lte->size);
698 return read_partial_wim_resource(lte->rspec,
700 lte->rspec->uncompressed_size,
706 read_wim_stream_prefix(const struct wim_lookup_table_entry *lte, u64 size,
707 consume_data_callback_t cb, void *cb_ctx)
709 return read_partial_wim_resource(lte->rspec, lte->offset_in_res, size,
714 /* This function handles reading stream data that is located in an external
715 * file, such as a file that has been added to the WIM image through execution
716 * of a wimlib_add_command.
718 * This assumes the file can be accessed using the standard POSIX open(),
719 * read(), and close(). On Windows this will not necessarily be the case (since
720 * the file may need FILE_FLAG_BACKUP_SEMANTICS to be opened, or the file may be
721 * encrypted), so Windows uses its own code for its equivalent case. */
723 read_file_on_disk_prefix(const struct wim_lookup_table_entry *lte, u64 size,
724 consume_data_callback_t cb, void *cb_ctx)
730 wimlib_assert(size <= lte->size);
732 DEBUG("Reading %"PRIu64" bytes from \"%"TS"\"", size, lte->file_on_disk);
734 raw_fd = open(lte->file_on_disk, O_BINARY | O_RDONLY);
736 ERROR_WITH_ERRNO("Can't open \"%"TS"\"", lte->file_on_disk);
737 return WIMLIB_ERR_OPEN;
739 filedes_init(&fd, raw_fd);
740 ret = read_raw_file_data(&fd, 0, size, cb, cb_ctx);
744 #endif /* !__WIN32__ */
746 /* This function handles the trivial case of reading stream data that is, in
747 * fact, already located in an in-memory buffer. */
749 read_buffer_prefix(const struct wim_lookup_table_entry *lte,
750 u64 size, consume_data_callback_t cb, void *cb_ctx)
752 wimlib_assert(size <= lte->size);
753 return (*cb)(lte->attached_buffer, size, cb_ctx);
756 typedef int (*read_stream_prefix_handler_t)(const struct wim_lookup_table_entry *lte,
758 consume_data_callback_t cb,
762 * read_stream_prefix()-
764 * Reads the first @size bytes from a generic "stream", which may be located in
765 * any one of several locations, such as in a WIM file (compressed or
766 * uncompressed), in an external file, or directly in an in-memory buffer.
768 * This function feeds the data to a callback function @cb in chunks of
771 * Returns 0 on success; nonzero on error. A nonzero value will be returned if
772 * the stream data cannot be successfully read (for a number of different
773 * reasons, depending on the stream location), or if @cb returned nonzero in
774 * which case that error code will be returned.
777 read_stream_prefix(const struct wim_lookup_table_entry *lte, u64 size,
778 consume_data_callback_t cb, void *cb_ctx)
780 static const read_stream_prefix_handler_t handlers[] = {
781 [RESOURCE_IN_WIM] = read_wim_stream_prefix,
783 [RESOURCE_IN_FILE_ON_DISK] = read_win32_file_prefix,
785 [RESOURCE_IN_FILE_ON_DISK] = read_file_on_disk_prefix,
787 [RESOURCE_IN_ATTACHED_BUFFER] = read_buffer_prefix,
789 [RESOURCE_IN_STAGING_FILE] = read_file_on_disk_prefix,
792 [RESOURCE_IN_NTFS_VOLUME] = read_ntfs_file_prefix,
795 [RESOURCE_WIN32_ENCRYPTED] = read_win32_encrypted_file_prefix,
798 wimlib_assert(lte->resource_location < ARRAY_LEN(handlers)
799 && handlers[lte->resource_location] != NULL);
800 return handlers[lte->resource_location](lte, size, cb, cb_ctx);
803 /* Read the full uncompressed data of the specified stream into the specified
804 * buffer, which must have space for at least lte->size bytes. */
806 read_full_stream_into_buf(const struct wim_lookup_table_entry *lte, void *_buf)
809 return read_stream_prefix(lte, lte->size, bufferer_cb, &buf);
812 /* Retrieve the full uncompressed data of the specified stream. A buffer large
813 * enough hold the data is allocated and returned in @buf_ret. */
815 read_full_stream_into_alloc_buf(const struct wim_lookup_table_entry *lte,
821 if ((size_t)lte->size != lte->size) {
822 ERROR("Can't read %"PRIu64" byte stream into "
823 "memory", lte->size);
824 return WIMLIB_ERR_NOMEM;
827 buf = MALLOC(lte->size);
829 return WIMLIB_ERR_NOMEM;
831 ret = read_full_stream_into_buf(lte, buf);
841 /* Retrieve the full uncompressed data of the specified WIM resource. A buffer
842 * large enough hold the data is allocated and returned in @buf_ret. */
844 wim_resource_spec_to_data(struct wim_resource_spec *rspec, void **buf_ret)
847 struct wim_lookup_table_entry *lte;
849 lte = new_lookup_table_entry();
851 return WIMLIB_ERR_NOMEM;
853 lte_bind_wim_resource_spec(lte, rspec);
854 lte->flags = rspec->flags;
855 lte->size = rspec->uncompressed_size;
856 lte->offset_in_res = 0;
858 ret = read_full_stream_into_alloc_buf(lte, buf_ret);
860 lte_unbind_wim_resource_spec(lte);
861 free_lookup_table_entry(lte);
865 /* Retrieve the full uncompressed data of a WIM resource specified as a raw
866 * `wim_reshdr' and the corresponding WIM file. A large enough hold the data is
867 * allocated and returned in @buf_ret. */
869 wim_reshdr_to_data(const struct wim_reshdr *reshdr, WIMStruct *wim, void **buf_ret)
871 DEBUG("offset_in_wim=%"PRIu64", size_in_wim=%"PRIu64", "
872 "uncompressed_size=%"PRIu64,
873 reshdr->offset_in_wim, reshdr->size_in_wim,
874 reshdr->uncompressed_size);
876 struct wim_resource_spec rspec;
877 wim_res_hdr_to_spec(reshdr, wim, &rspec);
878 return wim_resource_spec_to_data(&rspec, buf_ret);
882 wim_reshdr_to_hash(const struct wim_reshdr *reshdr, WIMStruct *wim,
883 u8 hash[SHA1_HASH_SIZE])
885 struct wim_resource_spec rspec;
887 struct wim_lookup_table_entry *lte;
889 wim_res_hdr_to_spec(reshdr, wim, &rspec);
891 lte = new_lookup_table_entry();
893 return WIMLIB_ERR_NOMEM;
895 lte_bind_wim_resource_spec(lte, &rspec);
896 lte->flags = rspec.flags;
897 lte->size = rspec.uncompressed_size;
898 lte->offset_in_res = 0;
901 ret = sha1_stream(lte);
903 lte_unbind_wim_resource_spec(lte);
904 copy_hash(hash, lte->hash);
905 free_lookup_table_entry(lte);
909 struct streamifier_context {
910 struct read_stream_list_callbacks cbs;
911 struct wim_lookup_table_entry *cur_stream;
912 struct wim_lookup_table_entry *next_stream;
913 u64 cur_stream_offset;
914 struct wim_lookup_table_entry *final_stream;
915 size_t list_head_offset;
918 static struct wim_lookup_table_entry *
919 next_stream(struct wim_lookup_table_entry *lte, size_t list_head_offset)
921 struct list_head *cur;
923 cur = (struct list_head*)((u8*)lte + list_head_offset);
925 return (struct wim_lookup_table_entry*)((u8*)cur->next - list_head_offset);
928 /* A consume_data_callback_t implementation that translates raw resource data
929 * into streams, calling the begin_stream, consume_chunk, and end_stream
930 * callback functions as appropriate. */
932 streamifier_cb(const void *chunk, size_t size, void *_ctx)
934 struct streamifier_context *ctx = _ctx;
937 DEBUG("%zu bytes passed to streamifier", size);
939 wimlib_assert(ctx->cur_stream != NULL);
940 wimlib_assert(size <= ctx->cur_stream->size - ctx->cur_stream_offset);
942 if (ctx->cur_stream_offset == 0) {
943 /* Starting a new stream. */
944 DEBUG("Begin new stream (size=%"PRIu64").",
945 ctx->cur_stream->size);
946 ret = (*ctx->cbs.begin_stream)(ctx->cur_stream, true,
947 ctx->cbs.begin_stream_ctx);
952 /* Consume the chunk. */
953 ret = (*ctx->cbs.consume_chunk)(chunk, size,
954 ctx->cbs.consume_chunk_ctx);
957 ctx->cur_stream_offset += size;
959 if (ctx->cur_stream_offset == ctx->cur_stream->size) {
960 /* Finished reading all the data for a stream. */
962 ctx->cur_stream_offset = 0;
964 DEBUG("End stream (size=%"PRIu64").", ctx->cur_stream->size);
965 ret = (*ctx->cbs.end_stream)(ctx->cur_stream, 0,
966 ctx->cbs.end_stream_ctx);
970 /* Advance to next stream. */
971 ctx->cur_stream = ctx->next_stream;
972 if (ctx->cur_stream != NULL) {
973 if (ctx->cur_stream != ctx->final_stream)
974 ctx->next_stream = next_stream(ctx->cur_stream,
975 ctx->list_head_offset);
977 ctx->next_stream = NULL;
983 struct hasher_context {
986 struct read_stream_list_callbacks cbs;
989 /* Callback for starting to read a stream while calculating its SHA1 message
992 hasher_begin_stream(struct wim_lookup_table_entry *lte, bool is_partial_res,
995 struct hasher_context *ctx = _ctx;
997 sha1_init(&ctx->sha_ctx);
999 if (ctx->cbs.begin_stream == NULL)
1002 return (*ctx->cbs.begin_stream)(lte, is_partial_res,
1003 ctx->cbs.begin_stream_ctx);
1006 /* A consume_data_callback_t implementation that continues calculating the SHA1
1007 * message digest of the stream being read, then optionally passes the data on
1008 * to another consume_data_callback_t implementation. This allows checking the
1009 * SHA1 message digest of a stream being extracted, for example. */
1011 hasher_consume_chunk(const void *chunk, size_t size, void *_ctx)
1013 struct hasher_context *ctx = _ctx;
1015 sha1_update(&ctx->sha_ctx, chunk, size);
1016 if (ctx->cbs.consume_chunk == NULL)
1019 return (*ctx->cbs.consume_chunk)(chunk, size, ctx->cbs.consume_chunk_ctx);
1023 get_sha1_string(const u8 md[SHA1_HASH_SIZE], tchar *str)
1025 for (size_t i = 0; i < SHA1_HASH_SIZE; i++)
1026 str += tsprintf(str, T("%02x"), md[i]);
1029 /* Callback for finishing reading a stream while calculating its SHA1 message
1032 hasher_end_stream(struct wim_lookup_table_entry *lte, int status, void *_ctx)
1034 struct hasher_context *ctx = _ctx;
1035 u8 hash[SHA1_HASH_SIZE];
1039 /* Error occurred; the full stream may not have been read. */
1044 /* Retrieve the final SHA1 message digest. */
1045 sha1_final(hash, &ctx->sha_ctx);
1047 if (lte->unhashed) {
1048 if (ctx->flags & COMPUTE_MISSING_STREAM_HASHES) {
1049 /* No SHA1 message digest was previously present for the
1050 * stream. Set it to the one just calculated. */
1051 DEBUG("Set SHA1 message digest for stream "
1052 "(size=%"PRIu64").", lte->size);
1053 copy_hash(lte->hash, hash);
1056 if (ctx->flags & VERIFY_STREAM_HASHES) {
1057 /* The stream already had a SHA1 message digest present. Verify
1058 * that it is the same as the calculated value. */
1059 if (!hashes_equal(hash, lte->hash)) {
1060 if (wimlib_print_errors) {
1061 tchar expected_hashstr[SHA1_HASH_SIZE * 2 + 1];
1062 tchar actual_hashstr[SHA1_HASH_SIZE * 2 + 1];
1063 get_sha1_string(lte->hash, expected_hashstr);
1064 get_sha1_string(hash, actual_hashstr);
1065 ERROR("The stream is corrupted!\n"
1066 " (Expected SHA1=%"TS",\n"
1068 expected_hashstr, actual_hashstr);
1070 ret = WIMLIB_ERR_INVALID_RESOURCE_HASH;
1074 DEBUG("SHA1 message digest okay for "
1075 "stream (size=%"PRIu64").", lte->size);
1080 if (ctx->cbs.end_stream == NULL)
1083 return (*ctx->cbs.end_stream)(lte, ret, ctx->cbs.end_stream_ctx);
1087 read_full_stream_with_cbs(struct wim_lookup_table_entry *lte,
1088 const struct read_stream_list_callbacks *cbs)
1092 ret = (*cbs->begin_stream)(lte, false, cbs->begin_stream_ctx);
1096 ret = read_stream_prefix(lte, lte->size, cbs->consume_chunk,
1097 cbs->consume_chunk_ctx);
1099 return (*cbs->end_stream)(lte, ret, cbs->end_stream_ctx);
1102 /* Read the full data of the specified stream, passing the data into the
1103 * specified callbacks (all of which are optional) and either checking or
1104 * computing the SHA1 message digest of the stream. */
1106 read_full_stream_with_sha1(struct wim_lookup_table_entry *lte,
1107 const struct read_stream_list_callbacks *cbs)
1109 struct hasher_context hasher_ctx = {
1110 .flags = VERIFY_STREAM_HASHES | COMPUTE_MISSING_STREAM_HASHES,
1113 struct read_stream_list_callbacks hasher_cbs = {
1114 .begin_stream = hasher_begin_stream,
1115 .begin_stream_ctx = &hasher_ctx,
1116 .consume_chunk = hasher_consume_chunk,
1117 .consume_chunk_ctx = &hasher_ctx,
1118 .end_stream = hasher_end_stream,
1119 .end_stream_ctx = &hasher_ctx,
1122 return read_full_stream_with_cbs(lte, &hasher_cbs);
1126 read_packed_streams(struct wim_lookup_table_entry *first_stream,
1127 struct wim_lookup_table_entry *last_stream,
1129 size_t list_head_offset,
1130 const struct read_stream_list_callbacks *sink_cbs)
1132 struct data_range *ranges;
1133 bool ranges_malloced;
1134 struct wim_lookup_table_entry *cur_stream;
1137 u64 ranges_alloc_size;
1139 DEBUG("Reading %"PRIu64" streams combined in same WIM resource",
1142 /* Setup data ranges array (one range per stream to read); this way
1143 * read_compressed_wim_resource() does not need to be aware of streams.
1146 ranges_alloc_size = stream_count * sizeof(ranges[0]);
1148 if (unlikely((size_t)ranges_alloc_size != ranges_alloc_size)) {
1149 ERROR("Too many streams in one resource!");
1150 return WIMLIB_ERR_NOMEM;
1152 if (likely(ranges_alloc_size <= STACK_MAX)) {
1153 ranges = alloca(ranges_alloc_size);
1154 ranges_malloced = false;
1156 ranges = MALLOC(ranges_alloc_size);
1157 if (ranges == NULL) {
1158 ERROR("Too many streams in one resource!");
1159 return WIMLIB_ERR_NOMEM;
1161 ranges_malloced = true;
1164 for (i = 0, cur_stream = first_stream;
1166 i++, cur_stream = next_stream(cur_stream, list_head_offset))
1168 ranges[i].offset = cur_stream->offset_in_res;
1169 ranges[i].size = cur_stream->size;
1172 struct streamifier_context streamifier_ctx = {
1174 .cur_stream = first_stream,
1175 .next_stream = next_stream(first_stream, list_head_offset),
1176 .cur_stream_offset = 0,
1177 .final_stream = last_stream,
1178 .list_head_offset = list_head_offset,
1181 ret = read_compressed_wim_resource(first_stream->rspec,
1187 if (ranges_malloced)
1191 if (streamifier_ctx.cur_stream_offset != 0) {
1192 ret = (*streamifier_ctx.cbs.end_stream)
1193 (streamifier_ctx.cur_stream,
1195 streamifier_ctx.cbs.end_stream_ctx);
1202 * Read a list of streams, each of which may be in any supported location (e.g.
1203 * in a WIM or in an external file). Unlike read_stream_prefix() or the
1204 * functions which call it, this function optimizes the case where multiple
1205 * streams are packed into a single compressed WIM resource and reads them all
1206 * consecutively, only decompressing the data one time.
1209 * List of streams (represented as `struct wim_lookup_table_entry's) to
1212 * Offset of the `struct list_head' within each `struct
1213 * wim_lookup_table_entry' that makes up the @stream_list.
1215 * Callback functions to accept the stream data.
1217 * Bitwise OR of zero or more of the following flags:
1219 * VERIFY_STREAM_HASHES:
1220 * For all streams being read that have already had SHA1 message
1221 * digests computed, calculate the SHA1 message digest of the read
1222 * data and compare it with the previously computed value. If they
1223 * do not match, return WIMLIB_ERR_INVALID_RESOURCE_HASH.
1225 * COMPUTE_MISSING_STREAM_HASHES
1226 * For all streams being read that have not yet had their SHA1
1227 * message digests computed, calculate and save their SHA1 message
1230 * STREAM_LIST_ALREADY_SORTED
1231 * @stream_list is already sorted in sequential order for reading.
1233 * The callback functions are allowed to delete the current stream from the list
1236 * Returns 0 on success; a nonzero error code on failure. Failure can occur due
1237 * to an error reading the data or due to an error status being returned by any
1238 * of the callback functions.
1241 read_stream_list(struct list_head *stream_list,
1242 size_t list_head_offset,
1243 const struct read_stream_list_callbacks *cbs,
1247 struct list_head *cur, *next;
1248 struct wim_lookup_table_entry *lte;
1249 struct hasher_context *hasher_ctx;
1250 struct read_stream_list_callbacks *sink_cbs;
1252 if (!(flags & STREAM_LIST_ALREADY_SORTED)) {
1253 ret = sort_stream_list_by_sequential_order(stream_list, list_head_offset);
1258 if (flags & (VERIFY_STREAM_HASHES | COMPUTE_MISSING_STREAM_HASHES)) {
1259 hasher_ctx = alloca(sizeof(*hasher_ctx));
1260 *hasher_ctx = (struct hasher_context) {
1264 sink_cbs = alloca(sizeof(*sink_cbs));
1265 *sink_cbs = (struct read_stream_list_callbacks) {
1266 .begin_stream = hasher_begin_stream,
1267 .begin_stream_ctx = hasher_ctx,
1268 .consume_chunk = hasher_consume_chunk,
1269 .consume_chunk_ctx = hasher_ctx,
1270 .end_stream = hasher_end_stream,
1271 .end_stream_ctx = hasher_ctx,
1274 sink_cbs = (struct read_stream_list_callbacks*)cbs;
1277 for (cur = stream_list->next, next = cur->next;
1279 cur = next, next = cur->next)
1281 lte = (struct wim_lookup_table_entry*)((u8*)cur - list_head_offset);
1283 if (lte->flags & WIM_RESHDR_FLAG_PACKED_STREAMS &&
1284 lte->size != lte->rspec->uncompressed_size)
1287 struct wim_lookup_table_entry *lte_next, *lte_last;
1288 struct list_head *next2;
1291 /* The next stream is a proper sub-sequence of a WIM
1292 * resource. See if there are other streams in the same
1293 * resource that need to be read. Since
1294 * sort_stream_list_by_sequential_order() sorted the
1295 * streams by offset in the WIM, this can be determined
1296 * by simply scanning forward in the list. */
1301 next2 != stream_list
1302 && (lte_next = (struct wim_lookup_table_entry*)
1303 ((u8*)next2 - list_head_offset),
1304 lte_next->resource_location == RESOURCE_IN_WIM
1305 && lte_next->rspec == lte->rspec);
1306 next2 = next2->next)
1308 lte_last = lte_next;
1311 if (stream_count > 1) {
1312 /* Reading multiple streams combined into a
1313 * single WIM resource. They are in the stream
1314 * list, sorted by offset; @lte specifies the
1315 * first stream in the resource that needs to be
1316 * read and @lte_last specifies the last stream
1317 * in the resource that needs to be read. */
1319 ret = read_packed_streams(lte, lte_last,
1329 ret = read_full_stream_with_cbs(lte, sink_cbs);
1330 if (ret && ret != BEGIN_STREAM_STATUS_SKIP_STREAM)
1336 /* Extract the first @size bytes of the specified stream.
1338 * If @size specifies the full uncompressed size of the stream, then the SHA1
1339 * message digest of the uncompressed stream is checked while being extracted.
1341 * The uncompressed data of the resource is passed in chunks of unspecified size
1342 * to the @extract_chunk function, passing it @extract_chunk_arg. */
1344 extract_stream(struct wim_lookup_table_entry *lte, u64 size,
1345 consume_data_callback_t extract_chunk, void *extract_chunk_arg)
1347 wimlib_assert(size <= lte->size);
1348 if (size == lte->size) {
1350 struct read_stream_list_callbacks cbs = {
1351 .consume_chunk = extract_chunk,
1352 .consume_chunk_ctx = extract_chunk_arg,
1354 return read_full_stream_with_sha1(lte, &cbs);
1356 /* Don't do SHA1. */
1357 return read_stream_prefix(lte, size, extract_chunk,
1362 /* A consume_data_callback_t implementation that writes the chunk of data to a
1363 * file descriptor. */
1365 extract_chunk_to_fd(const void *chunk, size_t size, void *_fd_p)
1367 struct filedes *fd = _fd_p;
1369 int ret = full_write(fd, chunk, size);
1371 ERROR_WITH_ERRNO("Error writing to file descriptor");
1377 /* Extract the first @size bytes of the specified stream to the specified file
1380 extract_stream_to_fd(struct wim_lookup_table_entry *lte,
1381 struct filedes *fd, u64 size)
1383 return extract_stream(lte, size, extract_chunk_to_fd, fd);
1386 /* Extract the full uncompressed contents of the specified stream to the
1387 * specified file descriptor. */
1389 extract_full_stream_to_fd(struct wim_lookup_table_entry *lte,
1392 return extract_stream_to_fd(lte, fd, lte->size);
1395 /* Calculate the SHA1 message digest of a stream and store it in @lte->hash. */
1397 sha1_stream(struct wim_lookup_table_entry *lte)
1399 wimlib_assert(lte->unhashed);
1400 struct read_stream_list_callbacks cbs = {
1402 return read_full_stream_with_sha1(lte, &cbs);
1405 /* Convert a short WIM resource header to a stand-alone WIM resource
1408 * Note: for packed resources some fields still need to be overridden.
1411 wim_res_hdr_to_spec(const struct wim_reshdr *reshdr, WIMStruct *wim,
1412 struct wim_resource_spec *rspec)
1415 rspec->offset_in_wim = reshdr->offset_in_wim;
1416 rspec->size_in_wim = reshdr->size_in_wim;
1417 rspec->uncompressed_size = reshdr->uncompressed_size;
1418 INIT_LIST_HEAD(&rspec->stream_list);
1419 rspec->flags = reshdr->flags;
1420 rspec->is_pipable = wim_is_pipable(wim);
1421 if (rspec->flags & WIM_RESHDR_FLAG_COMPRESSED) {
1422 rspec->compression_type = wim->compression_type;
1423 rspec->chunk_size = wim->chunk_size;
1425 rspec->compression_type = WIMLIB_COMPRESSION_TYPE_NONE;
1426 rspec->chunk_size = 0;
1430 /* Convert a stand-alone resource specification to a WIM resource header. */
1432 wim_res_spec_to_hdr(const struct wim_resource_spec *rspec,
1433 struct wim_reshdr *reshdr)
1435 reshdr->offset_in_wim = rspec->offset_in_wim;
1436 reshdr->size_in_wim = rspec->size_in_wim;
1437 reshdr->flags = rspec->flags;
1438 reshdr->uncompressed_size = rspec->uncompressed_size;
1441 /* Translates a WIM resource header from the on-disk format into an in-memory
1444 get_wim_reshdr(const struct wim_reshdr_disk *disk_reshdr,
1445 struct wim_reshdr *reshdr)
1447 reshdr->offset_in_wim = le64_to_cpu(disk_reshdr->offset_in_wim);
1448 reshdr->size_in_wim = (((u64)disk_reshdr->size_in_wim[0] << 0) |
1449 ((u64)disk_reshdr->size_in_wim[1] << 8) |
1450 ((u64)disk_reshdr->size_in_wim[2] << 16) |
1451 ((u64)disk_reshdr->size_in_wim[3] << 24) |
1452 ((u64)disk_reshdr->size_in_wim[4] << 32) |
1453 ((u64)disk_reshdr->size_in_wim[5] << 40) |
1454 ((u64)disk_reshdr->size_in_wim[6] << 48));
1455 reshdr->uncompressed_size = le64_to_cpu(disk_reshdr->uncompressed_size);
1456 reshdr->flags = disk_reshdr->flags;
1459 /* Translates a WIM resource header from an in-memory format into the on-disk
1462 put_wim_reshdr(const struct wim_reshdr *reshdr,
1463 struct wim_reshdr_disk *disk_reshdr)
1465 disk_reshdr->size_in_wim[0] = reshdr->size_in_wim >> 0;
1466 disk_reshdr->size_in_wim[1] = reshdr->size_in_wim >> 8;
1467 disk_reshdr->size_in_wim[2] = reshdr->size_in_wim >> 16;
1468 disk_reshdr->size_in_wim[3] = reshdr->size_in_wim >> 24;
1469 disk_reshdr->size_in_wim[4] = reshdr->size_in_wim >> 32;
1470 disk_reshdr->size_in_wim[5] = reshdr->size_in_wim >> 40;
1471 disk_reshdr->size_in_wim[6] = reshdr->size_in_wim >> 48;
1472 disk_reshdr->flags = reshdr->flags;
1473 disk_reshdr->offset_in_wim = cpu_to_le64(reshdr->offset_in_wim);
1474 disk_reshdr->uncompressed_size = cpu_to_le64(reshdr->uncompressed_size);