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