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