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