]> wimlib.net Git - wimlib/blob - src/resource.c
7631dd492309283bb7d8fa72a569004f64ae619d
[wimlib] / src / resource.c
1 /*
2  * resource.c
3  *
4  * Code for reading streams and resources, including compressed WIM resources.
5  */
6
7 /*
8  * Copyright (C) 2012, 2013 Eric Biggers
9  *
10  * This file is part of wimlib, a library for working with WIM files.
11  *
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
15  * version.
16  *
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.
20  *
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/.
23  */
24
25 #ifdef HAVE_CONFIG_H
26 #  include "config.h"
27 #endif
28
29 #include "wimlib.h"
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"
38
39 #ifdef __WIN32__
40 /* for read_win32_file_prefix(), read_win32_encrypted_file_prefix() */
41 #  include "wimlib/win32.h"
42 #endif
43
44 #ifdef WITH_NTFS_3G
45 /* for read_ntfs_file_prefix() */
46 #  include "wimlib/ntfs_3g.h"
47 #endif
48
49 #ifdef HAVE_ALLOCA_H
50 #  include <alloca.h>
51 #endif
52 #include <errno.h>
53 #include <fcntl.h>
54 #include <stdlib.h>
55 #include <unistd.h>
56
57 /*
58  *                         Compressed WIM resources
59  *
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.
68  *
69  * Additional information:
70  *
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.
75  *
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.
78  *
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.
84  *
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.
92  */
93
94
95 struct data_range {
96         u64 offset;
97         u64 size;
98 };
99
100 /*
101  * read_compressed_wim_resource() -
102  *
103  * Read data from a compressed WIM resource.
104  *
105  * @rspec
106  *      Specification of the compressed WIM resource to read from.
107  * @ranges
108  *      Nonoverlapping, nonempty ranges of the uncompressed resource data to
109  *      read, sorted by increasing offset.
110  * @num_ranges
111  *      Number of ranges in @ranges; must be at least 1.
112  * @cb
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.
117  * @cb_ctx
118  *      Parameter to pass to @cb_ctx.
119  *
120  * Possible return values:
121  *
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)
127  *
128  *      or other error code returned by the @cb function.
129  */
130 static int
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,
135                              void * const cb_ctx)
136 {
137         int ret;
138         int errno_save;
139
140         u64 *chunk_offsets = NULL;
141         u8 *ubuf = NULL;
142         void *cbuf = NULL;
143         bool chunk_offsets_malloced = false;
144         bool ubuf_malloced = false;
145         bool cbuf_malloced = false;
146         struct wimlib_decompressor *decompressor = NULL;
147
148         /* Sanity checks  */
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);
160         }
161         for (size_t i = 0; i < num_ranges - 1; i++)
162                 wimlib_assert(ranges[i].offset + ranges[i].size <= ranges[i + 1].offset);
163
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;
167
168         /* Get the file descriptor for the WIM.  */
169         struct filedes * const in_fd = &rspec->wim->in_fd;
170
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);
173
174         /* Determine if the chunk table is in an altenate format.  */
175         const bool alt_chunk_table = (rspec->flags & WIM_RESHDR_FLAG_PACKED_STREAMS)
176                                         && !is_pipe_read;
177
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);
189         }
190
191         if (!is_power_of_2(chunk_size)) {
192                 ERROR("Invalid compressed resource: "
193                       "expected power-of-2 chunk size (got %"PRIu32")",
194                       chunk_size);
195                 ret = WIMLIB_ERR_INVALID_CHUNK_SIZE;
196                 goto out_free_memory;
197         }
198
199         /* Get valid decompressor.  */
200         if (ctype == rspec->wim->decompressor_ctype &&
201             chunk_size == rspec->wim->decompressor_max_block_size)
202         {
203                 /* Cached decompressor.  */
204                 decompressor = rspec->wim->decompressor;
205                 rspec->wim->decompressor_ctype = WIMLIB_COMPRESSION_TYPE_NONE;
206                 rspec->wim->decompressor = NULL;
207         } else {
208                 ret = wimlib_create_decompressor(ctype, chunk_size, NULL,
209                                                  &decompressor);
210                 if (ret)
211                         goto out_free_memory;
212         }
213
214         const u32 chunk_order = bsr32(chunk_size);
215
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;
218
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;
223
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);
228
229         /* Calculate the number of chunk offsets that are needed for the chunks
230          * being read.  */
231         const u64 num_needed_chunk_offsets =
232                 last_needed_chunk - read_start_chunk + 1 +
233                 (last_needed_chunk < num_chunks - 1);
234
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);
240
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,
244                                                           alt_chunk_table);
245
246         /* Calculate the size of the chunk table in bytes.  */
247         const u64 chunk_table_size = num_chunk_entries * chunk_entry_size;
248
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)
253                                   : chunk_table_size;
254
255         if (!is_pipe_read) {
256                 /* Read the needed chunk table entries into memory and use them
257                  * to initialize the chunk_offsets array.  */
258
259                 u64 first_chunk_entry_to_read;
260                 u64 last_chunk_entry_to_read;
261
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;
268                 } else {
269                         /* Here we must account for the fact that the first
270                          * chunk has no explicit chunk table entry.  */
271
272                         if (read_start_chunk == 0)
273                                 first_chunk_entry_to_read = 0;
274                         else
275                                 first_chunk_entry_to_read = read_start_chunk - 1;
276
277                         if (last_needed_chunk == 0)
278                                 last_chunk_entry_to_read = 0;
279                         else
280                                 last_chunk_entry_to_read = last_needed_chunk - 1;
281
282                         if (last_needed_chunk < num_chunks - 1)
283                                 last_chunk_entry_to_read++;
284                 }
285
286                 const u64 num_chunk_entries_to_read =
287                         last_chunk_entry_to_read - first_chunk_entry_to_read + 1;
288
289                 const u64 chunk_offsets_alloc_size =
290                         max(num_chunk_entries_to_read,
291                             num_needed_chunk_offsets) * sizeof(chunk_offsets[0]);
292
293                 if ((size_t)chunk_offsets_alloc_size != chunk_offsets_alloc_size)
294                         goto oom;
295
296                 if (chunk_offsets_alloc_size <= STACK_MAX) {
297                         chunk_offsets = alloca(chunk_offsets_alloc_size);
298                 } else {
299                         chunk_offsets = MALLOC(chunk_offsets_alloc_size);
300                         if (chunk_offsets == NULL)
301                                 goto oom;
302                         chunk_offsets_malloced = true;
303                 }
304
305                 const size_t chunk_table_size_to_read =
306                         num_chunk_entries_to_read * chunk_entry_size;
307
308                 const u64 file_offset_of_needed_chunk_entries =
309                         cur_read_offset
310                         + (first_chunk_entry_to_read * chunk_entry_size)
311                         + (rspec->is_pipable ? (rspec->size_in_wim - chunk_table_size) : 0);
312
313                 void * const chunk_table_data =
314                         (u8*)chunk_offsets +
315                         chunk_offsets_alloc_size -
316                         chunk_table_size_to_read;
317
318                 ret = full_pread(in_fd, chunk_table_data, chunk_table_size_to_read,
319                                  file_offset_of_needed_chunk_entries);
320                 if (ret)
321                         goto read_error;
322
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;
329
330                 if (alt_chunk_table) {
331                         u64 cur_offset = 0;
332                         aliased_le32_t *raw_entries = chunk_table_data;
333
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;
338                                 cur_offset += entry;
339                         }
340                         if (last_needed_chunk < num_chunks - 1)
341                                 *chunk_offsets_p = cur_offset;
342                 } else {
343                         if (read_start_chunk == 0)
344                                 *chunk_offsets_p++ = 0;
345
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]);
350                         } else {
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]);
354                         }
355                 }
356
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);
361                 else
362                         cur_read_offset += chunk_table_size;
363         }
364
365         /* Allocate buffer for holding the uncompressed data of each chunk.  */
366         if (chunk_size <= STACK_MAX) {
367                 ubuf = alloca(chunk_size);
368         } else {
369                 ubuf = MALLOC(chunk_size);
370                 if (ubuf == NULL)
371                         goto oom;
372                 ubuf_malloced = true;
373         }
374
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
378          * uncompressed.  */
379         if (chunk_size - 1 <= STACK_MAX) {
380                 cbuf = alloca(chunk_size - 1);
381         } else {
382                 cbuf = MALLOC(chunk_size - 1);
383                 if (cbuf == NULL)
384                         goto oom;
385                 cbuf_malloced = true;
386         }
387
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;
393
394         /* Read and process each needed chunk.  */
395         for (u64 i = read_start_chunk; i <= last_needed_chunk; i++) {
396
397                 /* Calculate uncompressed size of next chunk.  */
398                 u32 chunk_usize;
399                 if ((i == num_chunks - 1) && (rspec->uncompressed_size & (chunk_size - 1)))
400                         chunk_usize = (rspec->uncompressed_size & (chunk_size - 1));
401                 else
402                         chunk_usize = chunk_size;
403
404                 /* Calculate compressed size of next chunk.  */
405                 u32 chunk_csize;
406                 if (is_pipe_read) {
407                         struct pwm_chunk_hdr chunk_hdr;
408
409                         ret = full_pread(in_fd, &chunk_hdr,
410                                          sizeof(chunk_hdr), cur_read_offset);
411                         if (ret)
412                                 goto read_error;
413                         chunk_csize = le32_to_cpu(chunk_hdr.compressed_size);
414                 } else {
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);
421                         } else {
422                                 chunk_csize = chunk_offsets[i + 1 - read_start_chunk] -
423                                               chunk_offsets[i - read_start_chunk];
424                         }
425                 }
426                 if (chunk_csize == 0 || chunk_csize > chunk_usize) {
427                         ERROR("Invalid chunk size in compressed resource!");
428                         errno = EINVAL;
429                         ret = WIMLIB_ERR_DECOMPRESSION;
430                         goto out_free_memory;
431                 }
432                 if (rspec->is_pipable)
433                         cur_read_offset += sizeof(struct pwm_chunk_hdr);
434
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;
439
440                 if (chunk_end_offset <= cur_range_pos) {
441
442                         /* The next range does not require data in this chunk,
443                          * so skip it.  */
444                         cur_read_offset += chunk_csize;
445                         if (is_pipe_read) {
446                                 u8 dummy;
447
448                                 ret = full_pread(in_fd, &dummy, 1, cur_read_offset - 1);
449                                 if (ret)
450                                         goto read_error;
451                         }
452                 } else {
453
454                         /* Read the chunk and feed data to the callback
455                          * function.  */
456                         u8 *read_buf;
457
458                         if (chunk_csize == chunk_usize)
459                                 read_buf = ubuf;
460                         else
461                                 read_buf = cbuf;
462
463                         ret = full_pread(in_fd,
464                                          read_buf,
465                                          chunk_csize,
466                                          cur_read_offset);
467                         if (ret)
468                                 goto read_error;
469
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,
475                                                         chunk_csize,
476                                                         ubuf,
477                                                         chunk_usize,
478                                                         decompressor);
479                                 if (ret) {
480                                         ERROR("Failed to decompress data!");
481                                         ret = WIMLIB_ERR_DECOMPRESSION;
482                                         errno = EINVAL;
483                                         goto out_free_memory;
484                                 }
485                         }
486                         cur_read_offset += chunk_csize;
487
488                         /* At least one range requires data in this chunk.  */
489                         do {
490                                 size_t start, end, size;
491
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.
496                                  */
497                                 start = cur_range_pos - chunk_start_offset;
498                                 end = min(cur_range_end, chunk_end_offset) - chunk_start_offset;
499                                 size = end - start;
500
501                                 ret = (*cb)(&ubuf[start], size, cb_ctx);
502
503                                 if (ret)
504                                         goto out_free_memory;
505
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;
511                                         } else {
512                                                 cur_range_pos = cur_range->offset;
513                                                 cur_range_end = cur_range->offset + cur_range->size;
514                                         }
515                                 }
516                         } while (cur_range_pos < chunk_end_offset);
517                 }
518         }
519
520         if (is_pipe_read &&
521             last_offset == rspec->uncompressed_size - 1 &&
522             chunk_table_size)
523         {
524                 u8 dummy;
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
528                  * returns.  */
529                 cur_read_offset += chunk_table_size;
530                 ret = full_pread(in_fd, &dummy, 1, cur_read_offset - 1);
531                 if (ret)
532                         goto read_error;
533         }
534         ret = 0;
535
536 out_free_memory:
537         errno_save = errno;
538         if (decompressor) {
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;
543         }
544         if (chunk_offsets_malloced)
545                 FREE(chunk_offsets);
546         if (ubuf_malloced)
547                 FREE(ubuf);
548         if (cbuf_malloced)
549                 FREE(cbuf);
550         errno = errno_save;
551         return ret;
552
553 oom:
554         ERROR("Not enough memory available to read size=%"PRIu64" bytes "
555               "from compressed WIM resource!", last_offset - first_offset + 1);
556         errno = ENOMEM;
557         ret = WIMLIB_ERR_NOMEM;
558         goto out_free_memory;
559
560 read_error:
561         ERROR_WITH_ERRNO("Error reading compressed WIM resource!");
562         goto out_free_memory;
563 }
564
565 static int
566 fill_zeroes(u64 size, consume_data_callback_t cb, void *cb_ctx)
567 {
568         if (unlikely(size)) {
569                 u8 buf[min(size, BUFFER_SIZE)];
570
571                 memset(buf, 0, sizeof(buf));
572
573                 do {
574                         size_t len;
575                         int ret;
576
577                         len = min(size, BUFFER_SIZE);
578                         ret = cb(buf, len, cb_ctx);
579                         if (ret)
580                                 return ret;
581                         size -= len;
582                 } while (size);
583         }
584         return 0;
585 }
586
587 /* Read raw data from a file descriptor at the specified offset, feeding the
588  * data it in chunks into the specified callback function.  */
589 static int
590 read_raw_file_data(struct filedes *in_fd, u64 offset, u64 size,
591                    consume_data_callback_t cb, void *cb_ctx)
592 {
593         u8 buf[BUFFER_SIZE];
594         size_t bytes_to_read;
595         int ret;
596
597         while (size) {
598                 bytes_to_read = min(sizeof(buf), size);
599                 ret = full_pread(in_fd, buf, bytes_to_read, offset);
600                 if (ret) {
601                         ERROR_WITH_ERRNO("Read error");
602                         return ret;
603                 }
604                 ret = cb(buf, bytes_to_read, cb_ctx);
605                 if (ret)
606                         return ret;
607                 size -= bytes_to_read;
608                 offset += bytes_to_read;
609         }
610         return 0;
611 }
612
613 /* A consume_data_callback_t implementation that simply concatenates all chunks
614  * into a buffer.  */
615 static int
616 bufferer_cb(const void *chunk, size_t size, void *_ctx)
617 {
618         u8 **buf_p = _ctx;
619
620         *buf_p = mempcpy(*buf_p, chunk, size);
621         return 0;
622 }
623
624 /*
625  * read_partial_wim_resource()-
626  *
627  * Read a range of data from an uncompressed or compressed resource in a WIM
628  * file.
629  *
630  * @rspec
631  *      Specification of the WIM resource to read from.
632  * @offset
633  *      Offset within the uncompressed resource at which to start reading.
634  * @size
635  *      Number of bytes to read.
636  * @cb
637  *      Callback function to feed the data being read.  Each call provides the
638  *      next chunk of the requested data, uncompressed.  Each chunk will be of
639  *      nonzero size and will not cross range boundaries, but otherwise will be
640  *      of unspecified size.
641  * @cb_ctx
642  *      Parameter to pass to @cb_ctx.
643  *
644  * Return values:
645  *      WIMLIB_ERR_SUCCESS (0)
646  *      WIMLIB_ERR_READ                   (errno set)
647  *      WIMLIB_ERR_UNEXPECTED_END_OF_FILE (errno set to 0)
648  *      WIMLIB_ERR_NOMEM                  (errno set to ENOMEM)
649  *      WIMLIB_ERR_DECOMPRESSION          (errno set to EINVAL)
650  *
651  *      or other error code returned by the @cb function.
652  */
653 static int
654 read_partial_wim_resource(const struct wim_resource_spec *rspec,
655                           u64 offset, u64 size,
656                           consume_data_callback_t cb, void *cb_ctx)
657 {
658         /* Sanity checks.  */
659         wimlib_assert(offset + size >= offset);
660         wimlib_assert(offset + size <= rspec->uncompressed_size);
661
662         DEBUG("Reading %"PRIu64" @ %"PRIu64" from WIM resource  "
663               "%"PRIu64" => %"PRIu64" @ %"PRIu64,
664               size, offset, rspec->uncompressed_size,
665               rspec->size_in_wim, rspec->offset_in_wim);
666
667         /* Trivial case.  */
668         if (size == 0)
669                 return 0;
670
671         if (resource_is_compressed(rspec)) {
672                 struct data_range range = {
673                         .offset = offset,
674                         .size = size,
675                 };
676                 return read_compressed_wim_resource(rspec, &range, 1,
677                                                     cb, cb_ctx);
678         } else {
679                 /* Reading uncompressed resource.  For completeness, handle the
680                  * weird case where size_in_wim < uncompressed_size.  */
681
682                 u64 read_size;
683                 u64 zeroes_size;
684                 int ret;
685
686                 if (likely(offset + size <= rspec->size_in_wim) ||
687                     rspec->is_pipable)
688                 {
689                         read_size = size;
690                         zeroes_size = 0;
691                 } else {
692                         if (offset >= rspec->size_in_wim) {
693                                 read_size = 0;
694                                 zeroes_size = size;
695                         } else {
696                                 read_size = rspec->size_in_wim - offset;
697                                 zeroes_size = offset + size - rspec->size_in_wim;
698                         }
699                 }
700
701                 ret = read_raw_file_data(&rspec->wim->in_fd,
702                                          rspec->offset_in_wim + offset,
703                                          read_size,
704                                          cb,
705                                          cb_ctx);
706                 if (ret)
707                         return ret;
708
709                 return fill_zeroes(zeroes_size, cb, cb_ctx);
710         }
711 }
712
713 /* Read the specified range of uncompressed data from the specified stream,
714  * which must be located into a WIM file, into the specified buffer.  */
715 int
716 read_partial_wim_stream_into_buf(const struct wim_lookup_table_entry *lte,
717                                  size_t size, u64 offset, void *_buf)
718 {
719         u8 *buf = _buf;
720
721         wimlib_assert(lte->resource_location == RESOURCE_IN_WIM);
722
723         return read_partial_wim_resource(lte->rspec,
724                                          lte->offset_in_res + offset,
725                                          size,
726                                          bufferer_cb,
727                                          &buf);
728 }
729
730 /* A consume_data_callback_t implementation that simply ignores the data
731  * received.  */
732 static int
733 skip_chunk_cb(const void *chunk, size_t size, void *_ctx)
734 {
735         return 0;
736 }
737
738 /* Skip over the data of the specified stream, which must correspond to a full
739  * WIM resource.  */
740 int
741 skip_wim_stream(struct wim_lookup_table_entry *lte)
742 {
743         wimlib_assert(lte->resource_location == RESOURCE_IN_WIM);
744         wimlib_assert(!(lte->flags & WIM_RESHDR_FLAG_PACKED_STREAMS));
745         DEBUG("Skipping stream (size=%"PRIu64")", lte->size);
746         return read_partial_wim_resource(lte->rspec,
747                                          0,
748                                          lte->rspec->uncompressed_size,
749                                          skip_chunk_cb,
750                                          NULL);
751 }
752
753 static int
754 read_wim_stream_prefix(const struct wim_lookup_table_entry *lte, u64 size,
755                        consume_data_callback_t cb, void *cb_ctx)
756 {
757         return read_partial_wim_resource(lte->rspec, lte->offset_in_res, size,
758                                          cb, cb_ctx);
759 }
760
761 /* This function handles reading stream data that is located in an external
762  * file,  such as a file that has been added to the WIM image through execution
763  * of a wimlib_add_command.
764  *
765  * This assumes the file can be accessed using the standard POSIX open(),
766  * read(), and close().  On Windows this will not necessarily be the case (since
767  * the file may need FILE_FLAG_BACKUP_SEMANTICS to be opened, or the file may be
768  * encrypted), so Windows uses its own code for its equivalent case.  */
769 static int
770 read_file_on_disk_prefix(const struct wim_lookup_table_entry *lte, u64 size,
771                          consume_data_callback_t cb, void *cb_ctx)
772 {
773         int ret;
774         int raw_fd;
775         struct filedes fd;
776
777         wimlib_assert(size <= lte->size);
778
779         DEBUG("Reading %"PRIu64" bytes from \"%"TS"\"", size, lte->file_on_disk);
780
781         raw_fd = topen(lte->file_on_disk, O_BINARY | O_RDONLY);
782         if (raw_fd < 0) {
783                 ERROR_WITH_ERRNO("Can't open \"%"TS"\"", lte->file_on_disk);
784                 return WIMLIB_ERR_OPEN;
785         }
786         filedes_init(&fd, raw_fd);
787         ret = read_raw_file_data(&fd, 0, size, cb, cb_ctx);
788         filedes_close(&fd);
789         return ret;
790 }
791
792 /* This function handles the trivial case of reading stream data that is, in
793  * fact, already located in an in-memory buffer.  */
794 static int
795 read_buffer_prefix(const struct wim_lookup_table_entry *lte,
796                    u64 size, consume_data_callback_t cb, void *cb_ctx)
797 {
798         wimlib_assert(size <= lte->size);
799         return (*cb)(lte->attached_buffer, size, cb_ctx);
800 }
801
802 typedef int (*read_stream_prefix_handler_t)(const struct wim_lookup_table_entry *lte,
803                                             u64 size,
804                                             consume_data_callback_t cb,
805                                             void *cb_ctx);
806
807 /*
808  * read_stream_prefix()-
809  *
810  * Reads the first @size bytes from a generic "stream", which may be located in
811  * any one of several locations, such as in a WIM file (compressed or
812  * uncompressed), in an external file, or directly in an in-memory buffer.
813  *
814  * This function feeds the data to a callback function @cb in chunks of
815  * unspecified size.
816  *
817  * Returns 0 on success; nonzero on error.  A nonzero value will be returned if
818  * the stream data cannot be successfully read (for a number of different
819  * reasons, depending on the stream location), or if @cb returned nonzero in
820  * which case that error code will be returned.
821  */
822 static int
823 read_stream_prefix(const struct wim_lookup_table_entry *lte, u64 size,
824                    consume_data_callback_t cb, void *cb_ctx)
825 {
826         static const read_stream_prefix_handler_t handlers[] = {
827                 [RESOURCE_IN_WIM]             = read_wim_stream_prefix,
828                 [RESOURCE_IN_FILE_ON_DISK]    = read_file_on_disk_prefix,
829                 [RESOURCE_IN_ATTACHED_BUFFER] = read_buffer_prefix,
830         #ifdef WITH_FUSE
831                 [RESOURCE_IN_STAGING_FILE]    = read_file_on_disk_prefix,
832         #endif
833         #ifdef WITH_NTFS_3G
834                 [RESOURCE_IN_NTFS_VOLUME]     = read_ntfs_file_prefix,
835         #endif
836         #ifdef __WIN32__
837                 [RESOURCE_IN_WINNT_FILE_ON_DISK] = read_winnt_file_prefix,
838                 [RESOURCE_WIN32_ENCRYPTED]    = read_win32_encrypted_file_prefix,
839         #endif
840         };
841         wimlib_assert(lte->resource_location < ARRAY_LEN(handlers)
842                       && handlers[lte->resource_location] != NULL);
843         return handlers[lte->resource_location](lte, size, cb, cb_ctx);
844 }
845
846 /* Read the full uncompressed data of the specified stream into the specified
847  * buffer, which must have space for at least lte->size bytes.  */
848 int
849 read_full_stream_into_buf(const struct wim_lookup_table_entry *lte, void *_buf)
850 {
851         u8 *buf = _buf;
852         return read_stream_prefix(lte, lte->size, bufferer_cb, &buf);
853 }
854
855 /* Retrieve the full uncompressed data of the specified stream.  A buffer large
856  * enough hold the data is allocated and returned in @buf_ret.  */
857 int
858 read_full_stream_into_alloc_buf(const struct wim_lookup_table_entry *lte,
859                                 void **buf_ret)
860 {
861         int ret;
862         void *buf;
863
864         if ((size_t)lte->size != lte->size) {
865                 ERROR("Can't read %"PRIu64" byte stream into "
866                       "memory", lte->size);
867                 return WIMLIB_ERR_NOMEM;
868         }
869
870         buf = MALLOC(lte->size);
871         if (buf == NULL)
872                 return WIMLIB_ERR_NOMEM;
873
874         ret = read_full_stream_into_buf(lte, buf);
875         if (ret) {
876                 FREE(buf);
877                 return ret;
878         }
879
880         *buf_ret = buf;
881         return 0;
882 }
883
884 /* Retrieve the full uncompressed data of the specified WIM resource.  A buffer
885  * large enough hold the data is allocated and returned in @buf_ret.  */
886 static int
887 wim_resource_spec_to_data(struct wim_resource_spec *rspec, void **buf_ret)
888 {
889         int ret;
890         struct wim_lookup_table_entry *lte;
891
892         lte = new_lookup_table_entry();
893         if (lte == NULL)
894                 return WIMLIB_ERR_NOMEM;
895
896         lte_bind_wim_resource_spec(lte, rspec);
897         lte->flags = rspec->flags;
898         lte->size = rspec->uncompressed_size;
899         lte->offset_in_res = 0;
900
901         ret = read_full_stream_into_alloc_buf(lte, buf_ret);
902
903         lte_unbind_wim_resource_spec(lte);
904         free_lookup_table_entry(lte);
905         return ret;
906 }
907
908 /* Retrieve the full uncompressed data of a WIM resource specified as a raw
909  * `wim_reshdr' and the corresponding WIM file.  A large enough hold the data is
910  * allocated and returned in @buf_ret.  */
911 int
912 wim_reshdr_to_data(const struct wim_reshdr *reshdr, WIMStruct *wim, void **buf_ret)
913 {
914         DEBUG("offset_in_wim=%"PRIu64", size_in_wim=%"PRIu64", "
915               "uncompressed_size=%"PRIu64,
916               reshdr->offset_in_wim, reshdr->size_in_wim,
917               reshdr->uncompressed_size);
918
919         struct wim_resource_spec rspec;
920         wim_res_hdr_to_spec(reshdr, wim, &rspec);
921         return wim_resource_spec_to_data(&rspec, buf_ret);
922 }
923
924 int
925 wim_reshdr_to_hash(const struct wim_reshdr *reshdr, WIMStruct *wim,
926                    u8 hash[SHA1_HASH_SIZE])
927 {
928         struct wim_resource_spec rspec;
929         int ret;
930         struct wim_lookup_table_entry *lte;
931
932         wim_res_hdr_to_spec(reshdr, wim, &rspec);
933
934         lte = new_lookup_table_entry();
935         if (lte == NULL)
936                 return WIMLIB_ERR_NOMEM;
937
938         lte_bind_wim_resource_spec(lte, &rspec);
939         lte->flags = rspec.flags;
940         lte->size = rspec.uncompressed_size;
941         lte->offset_in_res = 0;
942         lte->unhashed = 1;
943
944         ret = sha1_stream(lte);
945
946         lte_unbind_wim_resource_spec(lte);
947         copy_hash(hash, lte->hash);
948         free_lookup_table_entry(lte);
949         return ret;
950 }
951
952 struct streamifier_context {
953         struct read_stream_list_callbacks cbs;
954         struct wim_lookup_table_entry *cur_stream;
955         struct wim_lookup_table_entry *next_stream;
956         u64 cur_stream_offset;
957         struct wim_lookup_table_entry *final_stream;
958         size_t list_head_offset;
959 };
960
961 static struct wim_lookup_table_entry *
962 next_stream(struct wim_lookup_table_entry *lte, size_t list_head_offset)
963 {
964         struct list_head *cur;
965
966         cur = (struct list_head*)((u8*)lte + list_head_offset);
967
968         return (struct wim_lookup_table_entry*)((u8*)cur->next - list_head_offset);
969 }
970
971 /* A consume_data_callback_t implementation that translates raw resource data
972  * into streams, calling the begin_stream, consume_chunk, and end_stream
973  * callback functions as appropriate.  */
974 static int
975 streamifier_cb(const void *chunk, size_t size, void *_ctx)
976 {
977         struct streamifier_context *ctx = _ctx;
978         int ret;
979
980         DEBUG("%zu bytes passed to streamifier", size);
981
982         wimlib_assert(ctx->cur_stream != NULL);
983         wimlib_assert(size <= ctx->cur_stream->size - ctx->cur_stream_offset);
984
985         if (ctx->cur_stream_offset == 0) {
986                 u32 flags;
987
988                 /* Starting a new stream.  */
989                 DEBUG("Begin new stream (size=%"PRIu64").",
990                       ctx->cur_stream->size);
991
992                 flags = BEGIN_STREAM_FLAG_PARTIAL_RESOURCE;
993                 if (size == ctx->cur_stream->size)
994                         flags |= BEGIN_STREAM_FLAG_WHOLE_STREAM;
995                 ret = (*ctx->cbs.begin_stream)(ctx->cur_stream,
996                                                flags,
997                                                ctx->cbs.begin_stream_ctx);
998                 if (ret)
999                         return ret;
1000         }
1001
1002         /* Consume the chunk.  */
1003         ret = (*ctx->cbs.consume_chunk)(chunk, size,
1004                                         ctx->cbs.consume_chunk_ctx);
1005         ctx->cur_stream_offset += size;
1006         if (ret)
1007                 return ret;
1008
1009         if (ctx->cur_stream_offset == ctx->cur_stream->size) {
1010                 /* Finished reading all the data for a stream.  */
1011
1012                 ctx->cur_stream_offset = 0;
1013
1014                 DEBUG("End stream (size=%"PRIu64").", ctx->cur_stream->size);
1015                 ret = (*ctx->cbs.end_stream)(ctx->cur_stream, 0,
1016                                              ctx->cbs.end_stream_ctx);
1017                 if (ret)
1018                         return ret;
1019
1020                 /* Advance to next stream.  */
1021                 ctx->cur_stream = ctx->next_stream;
1022                 if (ctx->cur_stream != NULL) {
1023                         if (ctx->cur_stream != ctx->final_stream)
1024                                 ctx->next_stream = next_stream(ctx->cur_stream,
1025                                                                ctx->list_head_offset);
1026                         else
1027                                 ctx->next_stream = NULL;
1028                 }
1029         }
1030         return 0;
1031 }
1032
1033 struct hasher_context {
1034         SHA_CTX sha_ctx;
1035         int flags;
1036         struct read_stream_list_callbacks cbs;
1037 };
1038
1039 /* Callback for starting to read a stream while calculating its SHA1 message
1040  * digest.  */
1041 static int
1042 hasher_begin_stream(struct wim_lookup_table_entry *lte, u32 flags,
1043                     void *_ctx)
1044 {
1045         struct hasher_context *ctx = _ctx;
1046
1047         sha1_init(&ctx->sha_ctx);
1048
1049         if (ctx->cbs.begin_stream == NULL)
1050                 return 0;
1051         else
1052                 return (*ctx->cbs.begin_stream)(lte, flags,
1053                                                 ctx->cbs.begin_stream_ctx);
1054 }
1055
1056 /* A consume_data_callback_t implementation that continues calculating the SHA1
1057  * message digest of the stream being read, then optionally passes the data on
1058  * to another consume_data_callback_t implementation.  This allows checking the
1059  * SHA1 message digest of a stream being extracted, for example.  */
1060 static int
1061 hasher_consume_chunk(const void *chunk, size_t size, void *_ctx)
1062 {
1063         struct hasher_context *ctx = _ctx;
1064
1065         sha1_update(&ctx->sha_ctx, chunk, size);
1066         if (ctx->cbs.consume_chunk == NULL)
1067                 return 0;
1068         else
1069                 return (*ctx->cbs.consume_chunk)(chunk, size, ctx->cbs.consume_chunk_ctx);
1070 }
1071
1072 static void
1073 get_sha1_string(const u8 md[SHA1_HASH_SIZE], tchar *str)
1074 {
1075         for (size_t i = 0; i < SHA1_HASH_SIZE; i++)
1076                 str += tsprintf(str, T("%02x"), md[i]);
1077 }
1078
1079 /* Callback for finishing reading a stream while calculating its SHA1 message
1080  * digest.  */
1081 static int
1082 hasher_end_stream(struct wim_lookup_table_entry *lte, int status, void *_ctx)
1083 {
1084         struct hasher_context *ctx = _ctx;
1085         u8 hash[SHA1_HASH_SIZE];
1086         int ret;
1087
1088         if (status) {
1089                 /* Error occurred; the full stream may not have been read.  */
1090                 ret = status;
1091                 goto out_next_cb;
1092         }
1093
1094         /* Retrieve the final SHA1 message digest.  */
1095         sha1_final(hash, &ctx->sha_ctx);
1096
1097         if (lte->unhashed) {
1098                 if (ctx->flags & COMPUTE_MISSING_STREAM_HASHES) {
1099                         /* No SHA1 message digest was previously present for the
1100                          * stream.  Set it to the one just calculated.  */
1101                         DEBUG("Set SHA1 message digest for stream "
1102                               "(size=%"PRIu64").", lte->size);
1103                         copy_hash(lte->hash, hash);
1104                 }
1105         } else {
1106                 if (ctx->flags & VERIFY_STREAM_HASHES) {
1107                         /* The stream already had a SHA1 message digest present.  Verify
1108                          * that it is the same as the calculated value.  */
1109                         if (!hashes_equal(hash, lte->hash)) {
1110                                 if (wimlib_print_errors) {
1111                                         tchar expected_hashstr[SHA1_HASH_SIZE * 2 + 1];
1112                                         tchar actual_hashstr[SHA1_HASH_SIZE * 2 + 1];
1113                                         get_sha1_string(lte->hash, expected_hashstr);
1114                                         get_sha1_string(hash, actual_hashstr);
1115                                         ERROR("The stream is corrupted!\n"
1116                                               "        (Expected SHA1=%"TS",\n"
1117                                               "              got SHA1=%"TS")",
1118                                               expected_hashstr, actual_hashstr);
1119                                 }
1120                                 ret = WIMLIB_ERR_INVALID_RESOURCE_HASH;
1121                                 errno = EINVAL;
1122                                 goto out_next_cb;
1123                         }
1124                         DEBUG("SHA1 message digest okay for "
1125                               "stream (size=%"PRIu64").", lte->size);
1126                 }
1127         }
1128         ret = 0;
1129 out_next_cb:
1130         if (ctx->cbs.end_stream == NULL)
1131                 return ret;
1132         else
1133                 return (*ctx->cbs.end_stream)(lte, ret, ctx->cbs.end_stream_ctx);
1134 }
1135
1136 static int
1137 read_full_stream_with_cbs(struct wim_lookup_table_entry *lte,
1138                           const struct read_stream_list_callbacks *cbs)
1139 {
1140         int ret;
1141
1142         ret = (*cbs->begin_stream)(lte, 0, cbs->begin_stream_ctx);
1143         if (ret)
1144                 return ret;
1145
1146         ret = read_stream_prefix(lte, lte->size, cbs->consume_chunk,
1147                                  cbs->consume_chunk_ctx);
1148
1149         return (*cbs->end_stream)(lte, ret, cbs->end_stream_ctx);
1150 }
1151
1152 /* Read the full data of the specified stream, passing the data into the
1153  * specified callbacks (all of which are optional) and either checking or
1154  * computing the SHA1 message digest of the stream.  */
1155 static int
1156 read_full_stream_with_sha1(struct wim_lookup_table_entry *lte,
1157                            const struct read_stream_list_callbacks *cbs)
1158 {
1159         struct hasher_context hasher_ctx = {
1160                 .flags = VERIFY_STREAM_HASHES | COMPUTE_MISSING_STREAM_HASHES,
1161                 .cbs = *cbs,
1162         };
1163         struct read_stream_list_callbacks hasher_cbs = {
1164                 .begin_stream           = hasher_begin_stream,
1165                 .begin_stream_ctx       = &hasher_ctx,
1166                 .consume_chunk          = hasher_consume_chunk,
1167                 .consume_chunk_ctx      = &hasher_ctx,
1168                 .end_stream             = hasher_end_stream,
1169                 .end_stream_ctx         = &hasher_ctx,
1170         };
1171         return read_full_stream_with_cbs(lte, &hasher_cbs);
1172 }
1173
1174 static int
1175 read_packed_streams(struct wim_lookup_table_entry *first_stream,
1176                     struct wim_lookup_table_entry *last_stream,
1177                     u64 stream_count,
1178                     size_t list_head_offset,
1179                     const struct read_stream_list_callbacks *sink_cbs)
1180 {
1181         struct data_range *ranges;
1182         bool ranges_malloced;
1183         struct wim_lookup_table_entry *cur_stream;
1184         size_t i;
1185         int ret;
1186         u64 ranges_alloc_size;
1187
1188         DEBUG("Reading %"PRIu64" streams combined in same WIM resource",
1189               stream_count);
1190
1191         /* Setup data ranges array (one range per stream to read); this way
1192          * read_compressed_wim_resource() does not need to be aware of streams.
1193          */
1194
1195         ranges_alloc_size = stream_count * sizeof(ranges[0]);
1196
1197         if (unlikely((size_t)ranges_alloc_size != ranges_alloc_size)) {
1198                 ERROR("Too many streams in one resource!");
1199                 return WIMLIB_ERR_NOMEM;
1200         }
1201         if (likely(ranges_alloc_size <= STACK_MAX)) {
1202                 ranges = alloca(ranges_alloc_size);
1203                 ranges_malloced = false;
1204         } else {
1205                 ranges = MALLOC(ranges_alloc_size);
1206                 if (ranges == NULL) {
1207                         ERROR("Too many streams in one resource!");
1208                         return WIMLIB_ERR_NOMEM;
1209                 }
1210                 ranges_malloced = true;
1211         }
1212
1213         for (i = 0, cur_stream = first_stream;
1214              i < stream_count;
1215              i++, cur_stream = next_stream(cur_stream, list_head_offset))
1216         {
1217                 ranges[i].offset = cur_stream->offset_in_res;
1218                 ranges[i].size = cur_stream->size;
1219         }
1220
1221         struct streamifier_context streamifier_ctx = {
1222                 .cbs                    = *sink_cbs,
1223                 .cur_stream             = first_stream,
1224                 .next_stream            = next_stream(first_stream, list_head_offset),
1225                 .cur_stream_offset      = 0,
1226                 .final_stream           = last_stream,
1227                 .list_head_offset       = list_head_offset,
1228         };
1229
1230         ret = read_compressed_wim_resource(first_stream->rspec,
1231                                            ranges,
1232                                            stream_count,
1233                                            streamifier_cb,
1234                                            &streamifier_ctx);
1235
1236         if (ranges_malloced)
1237                 FREE(ranges);
1238
1239         if (ret) {
1240                 if (streamifier_ctx.cur_stream_offset != 0) {
1241                         ret = (*streamifier_ctx.cbs.end_stream)
1242                                 (streamifier_ctx.cur_stream,
1243                                  ret,
1244                                  streamifier_ctx.cbs.end_stream_ctx);
1245                 }
1246         }
1247         return ret;
1248 }
1249
1250 /*
1251  * Read a list of streams, each of which may be in any supported location (e.g.
1252  * in a WIM or in an external file).  Unlike read_stream_prefix() or the
1253  * functions which call it, this function optimizes the case where multiple
1254  * streams are packed into a single compressed WIM resource and reads them all
1255  * consecutively, only decompressing the data one time.
1256  *
1257  * @stream_list
1258  *      List of streams (represented as `struct wim_lookup_table_entry's) to
1259  *      read.
1260  * @list_head_offset
1261  *      Offset of the `struct list_head' within each `struct
1262  *      wim_lookup_table_entry' that makes up the @stream_list.
1263  * @cbs
1264  *      Callback functions to accept the stream data.
1265  * @flags
1266  *      Bitwise OR of zero or more of the following flags:
1267  *
1268  *      VERIFY_STREAM_HASHES:
1269  *              For all streams being read that have already had SHA1 message
1270  *              digests computed, calculate the SHA1 message digest of the read
1271  *              data and compare it with the previously computed value.  If they
1272  *              do not match, return WIMLIB_ERR_INVALID_RESOURCE_HASH.
1273  *
1274  *      COMPUTE_MISSING_STREAM_HASHES
1275  *              For all streams being read that have not yet had their SHA1
1276  *              message digests computed, calculate and save their SHA1 message
1277  *              digests.
1278  *
1279  *      STREAM_LIST_ALREADY_SORTED
1280  *              @stream_list is already sorted in sequential order for reading.
1281  *
1282  * The callback functions are allowed to delete the current stream from the list
1283  * if necessary.
1284  *
1285  * Returns 0 on success; a nonzero error code on failure.  Failure can occur due
1286  * to an error reading the data or due to an error status being returned by any
1287  * of the callback functions.
1288  */
1289 int
1290 read_stream_list(struct list_head *stream_list,
1291                  size_t list_head_offset,
1292                  const struct read_stream_list_callbacks *cbs,
1293                  int flags)
1294 {
1295         int ret;
1296         struct list_head *cur, *next;
1297         struct wim_lookup_table_entry *lte;
1298         struct hasher_context *hasher_ctx;
1299         struct read_stream_list_callbacks *sink_cbs;
1300
1301         if (!(flags & STREAM_LIST_ALREADY_SORTED)) {
1302                 ret = sort_stream_list_by_sequential_order(stream_list, list_head_offset);
1303                 if (ret)
1304                         return ret;
1305         }
1306
1307         if (flags & (VERIFY_STREAM_HASHES | COMPUTE_MISSING_STREAM_HASHES)) {
1308                 hasher_ctx = alloca(sizeof(*hasher_ctx));
1309                 *hasher_ctx = (struct hasher_context) {
1310                         .flags  = flags,
1311                         .cbs    = *cbs,
1312                 };
1313                 sink_cbs = alloca(sizeof(*sink_cbs));
1314                 *sink_cbs = (struct read_stream_list_callbacks) {
1315                         .begin_stream           = hasher_begin_stream,
1316                         .begin_stream_ctx       = hasher_ctx,
1317                         .consume_chunk          = hasher_consume_chunk,
1318                         .consume_chunk_ctx      = hasher_ctx,
1319                         .end_stream             = hasher_end_stream,
1320                         .end_stream_ctx         = hasher_ctx,
1321                 };
1322         } else {
1323                 sink_cbs = (struct read_stream_list_callbacks*)cbs;
1324         }
1325
1326         for (cur = stream_list->next, next = cur->next;
1327              cur != stream_list;
1328              cur = next, next = cur->next)
1329         {
1330                 lte = (struct wim_lookup_table_entry*)((u8*)cur - list_head_offset);
1331
1332                 if (lte->flags & WIM_RESHDR_FLAG_PACKED_STREAMS &&
1333                     lte->size != lte->rspec->uncompressed_size)
1334                 {
1335
1336                         struct wim_lookup_table_entry *lte_next, *lte_last;
1337                         struct list_head *next2;
1338                         u64 stream_count;
1339
1340                         /* The next stream is a proper sub-sequence of a WIM
1341                          * resource.  See if there are other streams in the same
1342                          * resource that need to be read.  Since
1343                          * sort_stream_list_by_sequential_order() sorted the
1344                          * streams by offset in the WIM, this can be determined
1345                          * by simply scanning forward in the list.  */
1346
1347                         lte_last = lte;
1348                         stream_count = 1;
1349                         for (next2 = next;
1350                              next2 != stream_list
1351                              && (lte_next = (struct wim_lookup_table_entry*)
1352                                                 ((u8*)next2 - list_head_offset),
1353                                  lte_next->resource_location == RESOURCE_IN_WIM
1354                                  && lte_next->rspec == lte->rspec);
1355                              next2 = next2->next)
1356                         {
1357                                 lte_last = lte_next;
1358                                 stream_count++;
1359                         }
1360                         if (stream_count > 1) {
1361                                 /* Reading multiple streams combined into a
1362                                  * single WIM resource.  They are in the stream
1363                                  * list, sorted by offset; @lte specifies the
1364                                  * first stream in the resource that needs to be
1365                                  * read and @lte_last specifies the last stream
1366                                  * in the resource that needs to be read.  */
1367                                 next = next2;
1368                                 ret = read_packed_streams(lte, lte_last,
1369                                                           stream_count,
1370                                                           list_head_offset,
1371                                                           sink_cbs);
1372                                 if (ret)
1373                                         return ret;
1374                                 continue;
1375                         }
1376                 }
1377
1378                 ret = read_full_stream_with_cbs(lte, sink_cbs);
1379                 if (ret && ret != BEGIN_STREAM_STATUS_SKIP_STREAM)
1380                         return ret;
1381         }
1382         return 0;
1383 }
1384
1385 /* Extract the first @size bytes of the specified stream.
1386  *
1387  * If @size specifies the full uncompressed size of the stream, then the SHA1
1388  * message digest of the uncompressed stream is checked while being extracted.
1389  *
1390  * The uncompressed data of the resource is passed in chunks of unspecified size
1391  * to the @extract_chunk function, passing it @extract_chunk_arg.  */
1392 int
1393 extract_stream(struct wim_lookup_table_entry *lte, u64 size,
1394                consume_data_callback_t extract_chunk, void *extract_chunk_arg)
1395 {
1396         wimlib_assert(size <= lte->size);
1397         if (size == lte->size) {
1398                 /* Do SHA1.  */
1399                 struct read_stream_list_callbacks cbs = {
1400                         .consume_chunk          = extract_chunk,
1401                         .consume_chunk_ctx      = extract_chunk_arg,
1402                 };
1403                 return read_full_stream_with_sha1(lte, &cbs);
1404         } else {
1405                 /* Don't do SHA1.  */
1406                 return read_stream_prefix(lte, size, extract_chunk,
1407                                           extract_chunk_arg);
1408         }
1409 }
1410
1411 /* A consume_data_callback_t implementation that writes the chunk of data to a
1412  * file descriptor.  */
1413 int
1414 extract_chunk_to_fd(const void *chunk, size_t size, void *_fd_p)
1415 {
1416         struct filedes *fd = _fd_p;
1417
1418         int ret = full_write(fd, chunk, size);
1419         if (ret) {
1420                 ERROR_WITH_ERRNO("Error writing to file descriptor");
1421                 return ret;
1422         }
1423         return 0;
1424 }
1425
1426 /* Extract the first @size bytes of the specified stream to the specified file
1427  * descriptor.  */
1428 int
1429 extract_stream_to_fd(struct wim_lookup_table_entry *lte,
1430                      struct filedes *fd, u64 size)
1431 {
1432         return extract_stream(lte, size, extract_chunk_to_fd, fd);
1433 }
1434
1435 /* Extract the full uncompressed contents of the specified stream to the
1436  * specified file descriptor.  */
1437 int
1438 extract_full_stream_to_fd(struct wim_lookup_table_entry *lte,
1439                           struct filedes *fd)
1440 {
1441         return extract_stream_to_fd(lte, fd, lte->size);
1442 }
1443
1444 /* Calculate the SHA1 message digest of a stream and store it in @lte->hash.  */
1445 int
1446 sha1_stream(struct wim_lookup_table_entry *lte)
1447 {
1448         wimlib_assert(lte->unhashed);
1449         struct read_stream_list_callbacks cbs = {
1450         };
1451         return read_full_stream_with_sha1(lte, &cbs);
1452 }
1453
1454 /* Convert a short WIM resource header to a stand-alone WIM resource
1455  * specification.
1456  *
1457  * Note: for packed resources some fields still need to be overridden.
1458  */
1459 void
1460 wim_res_hdr_to_spec(const struct wim_reshdr *reshdr, WIMStruct *wim,
1461                     struct wim_resource_spec *rspec)
1462 {
1463         rspec->wim = wim;
1464         rspec->offset_in_wim = reshdr->offset_in_wim;
1465         rspec->size_in_wim = reshdr->size_in_wim;
1466         rspec->uncompressed_size = reshdr->uncompressed_size;
1467         INIT_LIST_HEAD(&rspec->stream_list);
1468         rspec->flags = reshdr->flags;
1469         rspec->is_pipable = wim_is_pipable(wim);
1470         if (rspec->flags & WIM_RESHDR_FLAG_COMPRESSED) {
1471                 rspec->compression_type = wim->compression_type;
1472                 rspec->chunk_size = wim->chunk_size;
1473         } else {
1474                 rspec->compression_type = WIMLIB_COMPRESSION_TYPE_NONE;
1475                 rspec->chunk_size = 0;
1476         }
1477 }
1478
1479 /* Convert a stand-alone resource specification to a WIM resource header.  */
1480 void
1481 wim_res_spec_to_hdr(const struct wim_resource_spec *rspec,
1482                     struct wim_reshdr *reshdr)
1483 {
1484         reshdr->offset_in_wim     = rspec->offset_in_wim;
1485         reshdr->size_in_wim       = rspec->size_in_wim;
1486         reshdr->flags             = rspec->flags;
1487         reshdr->uncompressed_size = rspec->uncompressed_size;
1488 }
1489
1490 /* Translates a WIM resource header from the on-disk format into an in-memory
1491  * format.  */
1492 void
1493 get_wim_reshdr(const struct wim_reshdr_disk *disk_reshdr,
1494                struct wim_reshdr *reshdr)
1495 {
1496         reshdr->offset_in_wim = le64_to_cpu(disk_reshdr->offset_in_wim);
1497         reshdr->size_in_wim = (((u64)disk_reshdr->size_in_wim[0] <<  0) |
1498                                ((u64)disk_reshdr->size_in_wim[1] <<  8) |
1499                                ((u64)disk_reshdr->size_in_wim[2] << 16) |
1500                                ((u64)disk_reshdr->size_in_wim[3] << 24) |
1501                                ((u64)disk_reshdr->size_in_wim[4] << 32) |
1502                                ((u64)disk_reshdr->size_in_wim[5] << 40) |
1503                                ((u64)disk_reshdr->size_in_wim[6] << 48));
1504         reshdr->uncompressed_size = le64_to_cpu(disk_reshdr->uncompressed_size);
1505         reshdr->flags = disk_reshdr->flags;
1506 }
1507
1508 /* Translates a WIM resource header from an in-memory format into the on-disk
1509  * format.  */
1510 void
1511 put_wim_reshdr(const struct wim_reshdr *reshdr,
1512                struct wim_reshdr_disk *disk_reshdr)
1513 {
1514         disk_reshdr->size_in_wim[0] = reshdr->size_in_wim  >>  0;
1515         disk_reshdr->size_in_wim[1] = reshdr->size_in_wim  >>  8;
1516         disk_reshdr->size_in_wim[2] = reshdr->size_in_wim  >> 16;
1517         disk_reshdr->size_in_wim[3] = reshdr->size_in_wim  >> 24;
1518         disk_reshdr->size_in_wim[4] = reshdr->size_in_wim  >> 32;
1519         disk_reshdr->size_in_wim[5] = reshdr->size_in_wim  >> 40;
1520         disk_reshdr->size_in_wim[6] = reshdr->size_in_wim  >> 48;
1521         disk_reshdr->flags = reshdr->flags;
1522         disk_reshdr->offset_in_wim = cpu_to_le64(reshdr->offset_in_wim);
1523         disk_reshdr->uncompressed_size = cpu_to_le64(reshdr->uncompressed_size);
1524 }