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