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