]> wimlib.net Git - wimlib/blob - src/resource.c
Use LGPLv3+ for src/*.c
[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 free software; you can redistribute it and/or modify it under
11  * the terms of the GNU Lesser General Public License as published by the Free
12  * Software Foundation; either version 3 of the License, or (at your option) any
13  * later version.
14  *
15  * This file is distributed in the hope that it will be useful, but WITHOUT
16  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
17  * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
18  * details.
19  *
20  * You should have received a copy of the GNU Lesser General Public License
21  * along with this file; if not, see http://www.gnu.org/licenses/.
22  */
23
24 #ifdef HAVE_CONFIG_H
25 #  include "config.h"
26 #endif
27
28 #include "wimlib/assert.h"
29 #include "wimlib/endianness.h"
30 #include "wimlib/error.h"
31 #include "wimlib/file_io.h"
32 #include "wimlib/lookup_table.h"
33 #include "wimlib/resource.h"
34 #include "wimlib/sha1.h"
35 #include "wimlib/wim.h"
36
37 #ifdef __WIN32__
38 /* for read_winnt_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         u8 *ubuf = NULL;
141         void *cbuf = NULL;
142         bool chunk_offsets_malloced = false;
143         bool ubuf_malloced = false;
144         bool cbuf_malloced = false;
145         struct wimlib_decompressor *decompressor = NULL;
146
147         /* Sanity checks  */
148         wimlib_assert(rspec != NULL);
149         wimlib_assert(resource_is_compressed(rspec));
150         wimlib_assert(cb != NULL);
151         wimlib_assert(num_ranges != 0);
152         for (size_t i = 0; i < num_ranges; i++) {
153                 DEBUG("Range %zu/%zu: %"PRIu64"@+%"PRIu64" / %"PRIu64,
154                       i + 1, num_ranges, ranges[i].size, ranges[i].offset,
155                       rspec->uncompressed_size);
156                 wimlib_assert(ranges[i].size != 0);
157                 wimlib_assert(ranges[i].offset + ranges[i].size >= ranges[i].size);
158                 wimlib_assert(ranges[i].offset + ranges[i].size <= rspec->uncompressed_size);
159         }
160         for (size_t i = 0; i < num_ranges - 1; i++)
161                 wimlib_assert(ranges[i].offset + ranges[i].size <= ranges[i + 1].offset);
162
163         /* Get the offsets of the first and last bytes of the read.  */
164         const u64 first_offset = ranges[0].offset;
165         const u64 last_offset = ranges[num_ranges - 1].offset + ranges[num_ranges - 1].size - 1;
166
167         /* Get the file descriptor for the WIM.  */
168         struct filedes * const in_fd = &rspec->wim->in_fd;
169
170         /* Determine if we're reading a pipable resource from a pipe or not.  */
171         const bool is_pipe_read = (rspec->is_pipable && !filedes_is_seekable(in_fd));
172
173         /* Determine if the chunk table is in an alternate format.  */
174         const bool alt_chunk_table = (rspec->flags & WIM_RESHDR_FLAG_PACKED_STREAMS)
175                                         && !is_pipe_read;
176
177         /* Get the maximum size of uncompressed chunks in this resource, which
178          * we require be a power of 2.  */
179         u64 cur_read_offset = rspec->offset_in_wim;
180         int ctype = rspec->compression_type;
181         u32 chunk_size = rspec->chunk_size;
182         if (alt_chunk_table) {
183                 /* Alternate chunk table format.  Its header specifies the chunk
184                  * size and compression format.  Note: it could be read here;
185                  * however, the relevant data was already loaded into @rspec by
186                  * read_wim_lookup_table().  */
187                 cur_read_offset += sizeof(struct alt_chunk_table_header_disk);
188         }
189
190         if (!is_power_of_2(chunk_size)) {
191                 ERROR("Invalid compressed resource: "
192                       "expected power-of-2 chunk size (got %"PRIu32")",
193                       chunk_size);
194                 ret = WIMLIB_ERR_INVALID_CHUNK_SIZE;
195                 errno = EINVAL;
196                 goto out_free_memory;
197         }
198
199         /* Get valid decompressor.  */
200         if (ctype == rspec->wim->decompressor_ctype &&
201             chunk_size == rspec->wim->decompressor_max_block_size)
202         {
203                 /* Cached decompressor.  */
204                 decompressor = rspec->wim->decompressor;
205                 rspec->wim->decompressor_ctype = WIMLIB_COMPRESSION_TYPE_NONE;
206                 rspec->wim->decompressor = NULL;
207         } else {
208                 ret = wimlib_create_decompressor(ctype, chunk_size,
209                                                  &decompressor);
210                 if (ret) {
211                         if (ret != WIMLIB_ERR_NOMEM)
212                                 errno = EINVAL;
213                         goto out_free_memory;
214                 }
215         }
216
217         const u32 chunk_order = bsr32(chunk_size);
218
219         /* Calculate the total number of chunks the resource is divided into.  */
220         const u64 num_chunks = (rspec->uncompressed_size + chunk_size - 1) >> chunk_order;
221
222         /* Calculate the 0-based indices of the first and last chunks containing
223          * data that needs to be passed to the callback.  */
224         const u64 first_needed_chunk = first_offset >> chunk_order;
225         const u64 last_needed_chunk = last_offset >> chunk_order;
226
227         /* Calculate the 0-based index of the first chunk that actually needs to
228          * be read.  This is normally first_needed_chunk, but for pipe reads we
229          * must always start from the 0th chunk.  */
230         const u64 read_start_chunk = (is_pipe_read ? 0 : first_needed_chunk);
231
232         /* Calculate the number of chunk offsets that are needed for the chunks
233          * being read.  */
234         const u64 num_needed_chunk_offsets =
235                 last_needed_chunk - read_start_chunk + 1 +
236                 (last_needed_chunk < num_chunks - 1);
237
238         /* Calculate the number of entries in the chunk table.  Normally, it's
239          * one less than the number of chunks, since the first chunk has no
240          * entry.  But in the alternate chunk table format, the chunk entries
241          * contain chunk sizes, not offsets, and there is one per chunk.  */
242         const u64 num_chunk_entries = (alt_chunk_table ? num_chunks : num_chunks - 1);
243
244         /* Set the size of each chunk table entry based on the resource's
245          * uncompressed size.  */
246         const u64 chunk_entry_size = get_chunk_entry_size(rspec->uncompressed_size,
247                                                           alt_chunk_table);
248
249         /* Calculate the size of the chunk table in bytes.  */
250         const u64 chunk_table_size = num_chunk_entries * chunk_entry_size;
251
252         /* Calculate the size of the chunk table in bytes, including the header
253          * in the case of the alternate chunk table format.  */
254         const u64 chunk_table_full_size =
255                 (alt_chunk_table) ? chunk_table_size + sizeof(struct alt_chunk_table_header_disk)
256                                   : chunk_table_size;
257
258         if (!is_pipe_read) {
259                 /* Read the needed chunk table entries into memory and use them
260                  * to initialize the chunk_offsets array.  */
261
262                 u64 first_chunk_entry_to_read;
263                 u64 last_chunk_entry_to_read;
264
265                 if (alt_chunk_table) {
266                         /* The alternate chunk table contains chunk sizes, not
267                          * offsets, so we always must read all preceding entries
268                          * in order to determine offsets.  */
269                         first_chunk_entry_to_read = 0;
270                         last_chunk_entry_to_read = last_needed_chunk;
271                 } else {
272                         /* Here we must account for the fact that the first
273                          * chunk has no explicit chunk table entry.  */
274
275                         if (read_start_chunk == 0)
276                                 first_chunk_entry_to_read = 0;
277                         else
278                                 first_chunk_entry_to_read = read_start_chunk - 1;
279
280                         if (last_needed_chunk == 0)
281                                 last_chunk_entry_to_read = 0;
282                         else
283                                 last_chunk_entry_to_read = last_needed_chunk - 1;
284
285                         if (last_needed_chunk < num_chunks - 1)
286                                 last_chunk_entry_to_read++;
287                 }
288
289                 const u64 num_chunk_entries_to_read =
290                         last_chunk_entry_to_read - first_chunk_entry_to_read + 1;
291
292                 const u64 chunk_offsets_alloc_size =
293                         max(num_chunk_entries_to_read,
294                             num_needed_chunk_offsets) * sizeof(chunk_offsets[0]);
295
296                 if ((size_t)chunk_offsets_alloc_size != chunk_offsets_alloc_size)
297                         goto oom;
298
299                 if (chunk_offsets_alloc_size <= STACK_MAX) {
300                         chunk_offsets = alloca(chunk_offsets_alloc_size);
301                 } else {
302                         chunk_offsets = MALLOC(chunk_offsets_alloc_size);
303                         if (chunk_offsets == NULL)
304                                 goto oom;
305                         chunk_offsets_malloced = true;
306                 }
307
308                 const size_t chunk_table_size_to_read =
309                         num_chunk_entries_to_read * chunk_entry_size;
310
311                 const u64 file_offset_of_needed_chunk_entries =
312                         cur_read_offset
313                         + (first_chunk_entry_to_read * chunk_entry_size)
314                         + (rspec->is_pipable ? (rspec->size_in_wim - chunk_table_size) : 0);
315
316                 void * const chunk_table_data =
317                         (u8*)chunk_offsets +
318                         chunk_offsets_alloc_size -
319                         chunk_table_size_to_read;
320
321                 ret = full_pread(in_fd, chunk_table_data, chunk_table_size_to_read,
322                                  file_offset_of_needed_chunk_entries);
323                 if (ret)
324                         goto read_error;
325
326                 /* Now fill in chunk_offsets from the entries we have read in
327                  * chunk_tab_data.  We break aliasing rules here to avoid having
328                  * to allocate yet another array.  */
329                 typedef le64 __attribute__((may_alias)) aliased_le64_t;
330                 typedef le32 __attribute__((may_alias)) aliased_le32_t;
331                 u64 * chunk_offsets_p = chunk_offsets;
332
333                 if (alt_chunk_table) {
334                         u64 cur_offset = 0;
335                         aliased_le32_t *raw_entries = chunk_table_data;
336
337                         for (size_t i = 0; i < num_chunk_entries_to_read; i++) {
338                                 u32 entry = le32_to_cpu(raw_entries[i]);
339                                 if (i >= read_start_chunk)
340                                         *chunk_offsets_p++ = cur_offset;
341                                 cur_offset += entry;
342                         }
343                         if (last_needed_chunk < num_chunks - 1)
344                                 *chunk_offsets_p = cur_offset;
345                 } else {
346                         if (read_start_chunk == 0)
347                                 *chunk_offsets_p++ = 0;
348
349                         if (chunk_entry_size == 4) {
350                                 aliased_le32_t *raw_entries = chunk_table_data;
351                                 for (size_t i = 0; i < num_chunk_entries_to_read; i++)
352                                         *chunk_offsets_p++ = le32_to_cpu(raw_entries[i]);
353                         } else {
354                                 aliased_le64_t *raw_entries = chunk_table_data;
355                                 for (size_t i = 0; i < num_chunk_entries_to_read; i++)
356                                         *chunk_offsets_p++ = le64_to_cpu(raw_entries[i]);
357                         }
358                 }
359
360                 /* Set offset to beginning of first chunk to read.  */
361                 cur_read_offset += chunk_offsets[0];
362                 if (rspec->is_pipable)
363                         cur_read_offset += read_start_chunk * sizeof(struct pwm_chunk_hdr);
364                 else
365                         cur_read_offset += chunk_table_size;
366         }
367
368         /* Allocate buffer for holding the uncompressed data of each chunk.  */
369         if (chunk_size <= STACK_MAX) {
370                 _ubuf = alloca(chunk_size + 15);
371         } else {
372                 _ubuf = MALLOC(chunk_size + 15);
373                 if (_ubuf == NULL)
374                         goto oom;
375                 ubuf_malloced = true;
376         }
377         ubuf = (u8 *)(((uintptr_t)_ubuf + 15) & ~15);
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
1019                 /* Starting a new stream.  */
1020                 DEBUG("Begin new stream (size=%"PRIu64").",
1021                       ctx->cur_stream->size);
1022
1023                 ret = (*ctx->cbs.begin_stream)(ctx->cur_stream,
1024                                                ctx->cbs.begin_stream_ctx);
1025                 if (ret)
1026                         return ret;
1027         }
1028
1029         /* Consume the chunk.  */
1030         ret = (*ctx->cbs.consume_chunk)(chunk, size,
1031                                         ctx->cbs.consume_chunk_ctx);
1032         ctx->cur_stream_offset += size;
1033         if (ret)
1034                 return ret;
1035
1036         if (ctx->cur_stream_offset == ctx->cur_stream->size) {
1037                 /* Finished reading all the data for a stream.  */
1038
1039                 ctx->cur_stream_offset = 0;
1040
1041                 DEBUG("End stream (size=%"PRIu64").", ctx->cur_stream->size);
1042                 ret = (*ctx->cbs.end_stream)(ctx->cur_stream, 0,
1043                                              ctx->cbs.end_stream_ctx);
1044                 if (ret)
1045                         return ret;
1046
1047                 /* Advance to next stream.  */
1048                 ctx->cur_stream = ctx->next_stream;
1049                 if (ctx->cur_stream != NULL) {
1050                         if (ctx->cur_stream != ctx->final_stream)
1051                                 ctx->next_stream = next_stream(ctx->cur_stream,
1052                                                                ctx->list_head_offset);
1053                         else
1054                                 ctx->next_stream = NULL;
1055                 }
1056         }
1057         return 0;
1058 }
1059
1060 struct hasher_context {
1061         SHA_CTX sha_ctx;
1062         int flags;
1063         struct read_stream_list_callbacks cbs;
1064 };
1065
1066 /* Callback for starting to read a stream while calculating its SHA1 message
1067  * digest.  */
1068 static int
1069 hasher_begin_stream(struct wim_lookup_table_entry *lte, void *_ctx)
1070 {
1071         struct hasher_context *ctx = _ctx;
1072
1073         sha1_init(&ctx->sha_ctx);
1074
1075         if (ctx->cbs.begin_stream == NULL)
1076                 return 0;
1077         else
1078                 return (*ctx->cbs.begin_stream)(lte, ctx->cbs.begin_stream_ctx);
1079 }
1080
1081 /* A consume_data_callback_t implementation that continues calculating the SHA1
1082  * message digest of the stream being read, then optionally passes the data on
1083  * to another consume_data_callback_t implementation.  This allows checking the
1084  * SHA1 message digest of a stream being extracted, for example.  */
1085 static int
1086 hasher_consume_chunk(const void *chunk, size_t size, void *_ctx)
1087 {
1088         struct hasher_context *ctx = _ctx;
1089
1090         sha1_update(&ctx->sha_ctx, chunk, size);
1091         if (ctx->cbs.consume_chunk == NULL)
1092                 return 0;
1093         else
1094                 return (*ctx->cbs.consume_chunk)(chunk, size, ctx->cbs.consume_chunk_ctx);
1095 }
1096
1097 /* Callback for finishing reading a stream while calculating its SHA1 message
1098  * digest.  */
1099 static int
1100 hasher_end_stream(struct wim_lookup_table_entry *lte, int status, void *_ctx)
1101 {
1102         struct hasher_context *ctx = _ctx;
1103         u8 hash[SHA1_HASH_SIZE];
1104         int ret;
1105
1106         if (status) {
1107                 /* Error occurred; the full stream may not have been read.  */
1108                 ret = status;
1109                 goto out_next_cb;
1110         }
1111
1112         /* Retrieve the final SHA1 message digest.  */
1113         sha1_final(hash, &ctx->sha_ctx);
1114
1115         if (lte->unhashed) {
1116                 if (ctx->flags & COMPUTE_MISSING_STREAM_HASHES) {
1117                         /* No SHA1 message digest was previously present for the
1118                          * stream.  Set it to the one just calculated.  */
1119                         DEBUG("Set SHA1 message digest for stream "
1120                               "(size=%"PRIu64").", lte->size);
1121                         copy_hash(lte->hash, hash);
1122                 }
1123         } else {
1124                 if (ctx->flags & VERIFY_STREAM_HASHES) {
1125                         /* The stream already had a SHA1 message digest present.  Verify
1126                          * that it is the same as the calculated value.  */
1127                         if (!hashes_equal(hash, lte->hash)) {
1128                                 if (wimlib_print_errors) {
1129                                         tchar expected_hashstr[SHA1_HASH_SIZE * 2 + 1];
1130                                         tchar actual_hashstr[SHA1_HASH_SIZE * 2 + 1];
1131                                         sprint_hash(lte->hash, expected_hashstr);
1132                                         sprint_hash(hash, actual_hashstr);
1133                                         ERROR("The stream is corrupted!\n"
1134                                               "        (Expected SHA1=%"TS",\n"
1135                                               "              got SHA1=%"TS")",
1136                                               expected_hashstr, actual_hashstr);
1137                                 }
1138                                 ret = WIMLIB_ERR_INVALID_RESOURCE_HASH;
1139                                 errno = EINVAL;
1140                                 goto out_next_cb;
1141                         }
1142                         DEBUG("SHA1 message digest okay for "
1143                               "stream (size=%"PRIu64").", lte->size);
1144                 }
1145         }
1146         ret = 0;
1147 out_next_cb:
1148         if (ctx->cbs.end_stream == NULL)
1149                 return ret;
1150         else
1151                 return (*ctx->cbs.end_stream)(lte, ret, ctx->cbs.end_stream_ctx);
1152 }
1153
1154 static int
1155 read_full_stream_with_cbs(struct wim_lookup_table_entry *lte,
1156                           const struct read_stream_list_callbacks *cbs)
1157 {
1158         int ret;
1159
1160         ret = (*cbs->begin_stream)(lte, cbs->begin_stream_ctx);
1161         if (ret)
1162                 return ret;
1163
1164         ret = read_stream_prefix(lte, lte->size, cbs->consume_chunk,
1165                                  cbs->consume_chunk_ctx);
1166
1167         return (*cbs->end_stream)(lte, ret, cbs->end_stream_ctx);
1168 }
1169
1170 /* Read the full data of the specified stream, passing the data into the
1171  * specified callbacks (all of which are optional) and either checking or
1172  * computing the SHA1 message digest of the stream.  */
1173 static int
1174 read_full_stream_with_sha1(struct wim_lookup_table_entry *lte,
1175                            const struct read_stream_list_callbacks *cbs)
1176 {
1177         struct hasher_context hasher_ctx = {
1178                 .flags = VERIFY_STREAM_HASHES | COMPUTE_MISSING_STREAM_HASHES,
1179                 .cbs = *cbs,
1180         };
1181         struct read_stream_list_callbacks hasher_cbs = {
1182                 .begin_stream           = hasher_begin_stream,
1183                 .begin_stream_ctx       = &hasher_ctx,
1184                 .consume_chunk          = hasher_consume_chunk,
1185                 .consume_chunk_ctx      = &hasher_ctx,
1186                 .end_stream             = hasher_end_stream,
1187                 .end_stream_ctx         = &hasher_ctx,
1188         };
1189         return read_full_stream_with_cbs(lte, &hasher_cbs);
1190 }
1191
1192 static int
1193 read_packed_streams(struct wim_lookup_table_entry *first_stream,
1194                     struct wim_lookup_table_entry *last_stream,
1195                     u64 stream_count,
1196                     size_t list_head_offset,
1197                     const struct read_stream_list_callbacks *sink_cbs)
1198 {
1199         struct data_range *ranges;
1200         bool ranges_malloced;
1201         struct wim_lookup_table_entry *cur_stream;
1202         size_t i;
1203         int ret;
1204         u64 ranges_alloc_size;
1205
1206         DEBUG("Reading %"PRIu64" streams combined in same WIM resource",
1207               stream_count);
1208
1209         /* Setup data ranges array (one range per stream to read); this way
1210          * read_compressed_wim_resource() does not need to be aware of streams.
1211          */
1212
1213         ranges_alloc_size = stream_count * sizeof(ranges[0]);
1214
1215         if (unlikely((size_t)ranges_alloc_size != ranges_alloc_size)) {
1216                 ERROR("Too many streams in one resource!");
1217                 return WIMLIB_ERR_NOMEM;
1218         }
1219         if (likely(ranges_alloc_size <= STACK_MAX)) {
1220                 ranges = alloca(ranges_alloc_size);
1221                 ranges_malloced = false;
1222         } else {
1223                 ranges = MALLOC(ranges_alloc_size);
1224                 if (ranges == NULL) {
1225                         ERROR("Too many streams in one resource!");
1226                         return WIMLIB_ERR_NOMEM;
1227                 }
1228                 ranges_malloced = true;
1229         }
1230
1231         for (i = 0, cur_stream = first_stream;
1232              i < stream_count;
1233              i++, cur_stream = next_stream(cur_stream, list_head_offset))
1234         {
1235                 ranges[i].offset = cur_stream->offset_in_res;
1236                 ranges[i].size = cur_stream->size;
1237         }
1238
1239         struct streamifier_context streamifier_ctx = {
1240                 .cbs                    = *sink_cbs,
1241                 .cur_stream             = first_stream,
1242                 .next_stream            = next_stream(first_stream, list_head_offset),
1243                 .cur_stream_offset      = 0,
1244                 .final_stream           = last_stream,
1245                 .list_head_offset       = list_head_offset,
1246         };
1247
1248         ret = read_compressed_wim_resource(first_stream->rspec,
1249                                            ranges,
1250                                            stream_count,
1251                                            streamifier_cb,
1252                                            &streamifier_ctx);
1253
1254         if (ranges_malloced)
1255                 FREE(ranges);
1256
1257         if (ret) {
1258                 if (streamifier_ctx.cur_stream_offset != 0) {
1259                         ret = (*streamifier_ctx.cbs.end_stream)
1260                                 (streamifier_ctx.cur_stream,
1261                                  ret,
1262                                  streamifier_ctx.cbs.end_stream_ctx);
1263                 }
1264         }
1265         return ret;
1266 }
1267
1268 /*
1269  * Read a list of streams, each of which may be in any supported location (e.g.
1270  * in a WIM or in an external file).  Unlike read_stream_prefix() or the
1271  * functions which call it, this function optimizes the case where multiple
1272  * streams are packed into a single compressed WIM resource and reads them all
1273  * consecutively, only decompressing the data one time.
1274  *
1275  * @stream_list
1276  *      List of streams (represented as `struct wim_lookup_table_entry's) to
1277  *      read.
1278  * @list_head_offset
1279  *      Offset of the `struct list_head' within each `struct
1280  *      wim_lookup_table_entry' that makes up the @stream_list.
1281  * @cbs
1282  *      Callback functions to accept the stream data.
1283  * @flags
1284  *      Bitwise OR of zero or more of the following flags:
1285  *
1286  *      VERIFY_STREAM_HASHES:
1287  *              For all streams being read that have already had SHA1 message
1288  *              digests computed, calculate the SHA1 message digest of the read
1289  *              data and compare it with the previously computed value.  If they
1290  *              do not match, return WIMLIB_ERR_INVALID_RESOURCE_HASH.
1291  *
1292  *      COMPUTE_MISSING_STREAM_HASHES
1293  *              For all streams being read that have not yet had their SHA1
1294  *              message digests computed, calculate and save their SHA1 message
1295  *              digests.
1296  *
1297  *      STREAM_LIST_ALREADY_SORTED
1298  *              @stream_list is already sorted in sequential order for reading.
1299  *
1300  * The callback functions are allowed to delete the current stream from the list
1301  * if necessary.
1302  *
1303  * Returns 0 on success; a nonzero error code on failure.  Failure can occur due
1304  * to an error reading the data or due to an error status being returned by any
1305  * of the callback functions.
1306  */
1307 int
1308 read_stream_list(struct list_head *stream_list,
1309                  size_t list_head_offset,
1310                  const struct read_stream_list_callbacks *cbs,
1311                  int flags)
1312 {
1313         int ret;
1314         struct list_head *cur, *next;
1315         struct wim_lookup_table_entry *lte;
1316         struct hasher_context *hasher_ctx;
1317         struct read_stream_list_callbacks *sink_cbs;
1318
1319         if (!(flags & STREAM_LIST_ALREADY_SORTED)) {
1320                 ret = sort_stream_list_by_sequential_order(stream_list, list_head_offset);
1321                 if (ret)
1322                         return ret;
1323         }
1324
1325         if (flags & (VERIFY_STREAM_HASHES | COMPUTE_MISSING_STREAM_HASHES)) {
1326                 hasher_ctx = alloca(sizeof(*hasher_ctx));
1327                 *hasher_ctx = (struct hasher_context) {
1328                         .flags  = flags,
1329                         .cbs    = *cbs,
1330                 };
1331                 sink_cbs = alloca(sizeof(*sink_cbs));
1332                 *sink_cbs = (struct read_stream_list_callbacks) {
1333                         .begin_stream           = hasher_begin_stream,
1334                         .begin_stream_ctx       = hasher_ctx,
1335                         .consume_chunk          = hasher_consume_chunk,
1336                         .consume_chunk_ctx      = hasher_ctx,
1337                         .end_stream             = hasher_end_stream,
1338                         .end_stream_ctx         = hasher_ctx,
1339                 };
1340         } else {
1341                 sink_cbs = (struct read_stream_list_callbacks*)cbs;
1342         }
1343
1344         for (cur = stream_list->next, next = cur->next;
1345              cur != stream_list;
1346              cur = next, next = cur->next)
1347         {
1348                 lte = (struct wim_lookup_table_entry*)((u8*)cur - list_head_offset);
1349
1350                 if (lte->flags & WIM_RESHDR_FLAG_PACKED_STREAMS &&
1351                     lte->size != lte->rspec->uncompressed_size)
1352                 {
1353
1354                         struct wim_lookup_table_entry *lte_next, *lte_last;
1355                         struct list_head *next2;
1356                         u64 stream_count;
1357
1358                         /* The next stream is a proper sub-sequence of a WIM
1359                          * resource.  See if there are other streams in the same
1360                          * resource that need to be read.  Since
1361                          * sort_stream_list_by_sequential_order() sorted the
1362                          * streams by offset in the WIM, this can be determined
1363                          * by simply scanning forward in the list.  */
1364
1365                         lte_last = lte;
1366                         stream_count = 1;
1367                         for (next2 = next;
1368                              next2 != stream_list
1369                              && (lte_next = (struct wim_lookup_table_entry*)
1370                                                 ((u8*)next2 - list_head_offset),
1371                                  lte_next->resource_location == RESOURCE_IN_WIM
1372                                  && lte_next->rspec == lte->rspec);
1373                              next2 = next2->next)
1374                         {
1375                                 lte_last = lte_next;
1376                                 stream_count++;
1377                         }
1378                         if (stream_count > 1) {
1379                                 /* Reading multiple streams combined into a
1380                                  * single WIM resource.  They are in the stream
1381                                  * list, sorted by offset; @lte specifies the
1382                                  * first stream in the resource that needs to be
1383                                  * read and @lte_last specifies the last stream
1384                                  * in the resource that needs to be read.  */
1385                                 next = next2;
1386                                 ret = read_packed_streams(lte, lte_last,
1387                                                           stream_count,
1388                                                           list_head_offset,
1389                                                           sink_cbs);
1390                                 if (ret)
1391                                         return ret;
1392                                 continue;
1393                         }
1394                 }
1395
1396                 ret = read_full_stream_with_cbs(lte, sink_cbs);
1397                 if (ret && ret != BEGIN_STREAM_STATUS_SKIP_STREAM)
1398                         return ret;
1399         }
1400         return 0;
1401 }
1402
1403 /* Extract the first @size bytes of the specified stream.
1404  *
1405  * If @size specifies the full uncompressed size of the stream, then the SHA1
1406  * message digest of the uncompressed stream is checked while being extracted.
1407  *
1408  * The uncompressed data of the resource is passed in chunks of unspecified size
1409  * to the @extract_chunk function, passing it @extract_chunk_arg.  */
1410 int
1411 extract_stream(struct wim_lookup_table_entry *lte, u64 size,
1412                consume_data_callback_t extract_chunk, void *extract_chunk_arg)
1413 {
1414         wimlib_assert(size <= lte->size);
1415         if (size == lte->size) {
1416                 /* Do SHA1.  */
1417                 struct read_stream_list_callbacks cbs = {
1418                         .consume_chunk          = extract_chunk,
1419                         .consume_chunk_ctx      = extract_chunk_arg,
1420                 };
1421                 return read_full_stream_with_sha1(lte, &cbs);
1422         } else {
1423                 /* Don't do SHA1.  */
1424                 return read_stream_prefix(lte, size, extract_chunk,
1425                                           extract_chunk_arg);
1426         }
1427 }
1428
1429 /* A consume_data_callback_t implementation that writes the chunk of data to a
1430  * file descriptor.  */
1431 static int
1432 extract_chunk_to_fd(const void *chunk, size_t size, void *_fd_p)
1433 {
1434         struct filedes *fd = _fd_p;
1435
1436         int ret = full_write(fd, chunk, size);
1437         if (ret) {
1438                 ERROR_WITH_ERRNO("Error writing to file descriptor");
1439                 return ret;
1440         }
1441         return 0;
1442 }
1443
1444 /* Extract the first @size bytes of the specified stream to the specified file
1445  * descriptor.  */
1446 int
1447 extract_stream_to_fd(struct wim_lookup_table_entry *lte,
1448                      struct filedes *fd, u64 size)
1449 {
1450         return extract_stream(lte, size, extract_chunk_to_fd, fd);
1451 }
1452
1453 /* Extract the full uncompressed contents of the specified stream to the
1454  * specified file descriptor.  */
1455 int
1456 extract_full_stream_to_fd(struct wim_lookup_table_entry *lte,
1457                           struct filedes *fd)
1458 {
1459         return extract_stream_to_fd(lte, fd, lte->size);
1460 }
1461
1462 /* Calculate the SHA1 message digest of a stream and store it in @lte->hash.  */
1463 int
1464 sha1_stream(struct wim_lookup_table_entry *lte)
1465 {
1466         wimlib_assert(lte->unhashed);
1467         struct read_stream_list_callbacks cbs = {
1468         };
1469         return read_full_stream_with_sha1(lte, &cbs);
1470 }
1471
1472 /* Convert a short WIM resource header to a stand-alone WIM resource
1473  * specification.
1474  *
1475  * Note: for packed resources some fields still need to be overridden.
1476  */
1477 void
1478 wim_res_hdr_to_spec(const struct wim_reshdr *reshdr, WIMStruct *wim,
1479                     struct wim_resource_spec *rspec)
1480 {
1481         rspec->wim = wim;
1482         rspec->offset_in_wim = reshdr->offset_in_wim;
1483         rspec->size_in_wim = reshdr->size_in_wim;
1484         rspec->uncompressed_size = reshdr->uncompressed_size;
1485         INIT_LIST_HEAD(&rspec->stream_list);
1486         rspec->flags = reshdr->flags;
1487         rspec->is_pipable = wim_is_pipable(wim);
1488         if (rspec->flags & WIM_RESHDR_FLAG_COMPRESSED) {
1489                 rspec->compression_type = wim->compression_type;
1490                 rspec->chunk_size = wim->chunk_size;
1491         } else {
1492                 rspec->compression_type = WIMLIB_COMPRESSION_TYPE_NONE;
1493                 rspec->chunk_size = 0;
1494         }
1495 }
1496
1497 /* Convert a stand-alone resource specification to a WIM resource header.  */
1498 void
1499 wim_res_spec_to_hdr(const struct wim_resource_spec *rspec,
1500                     struct wim_reshdr *reshdr)
1501 {
1502         reshdr->offset_in_wim     = rspec->offset_in_wim;
1503         reshdr->size_in_wim       = rspec->size_in_wim;
1504         reshdr->flags             = rspec->flags;
1505         reshdr->uncompressed_size = rspec->uncompressed_size;
1506 }
1507
1508 /* Translates a WIM resource header from the on-disk format into an in-memory
1509  * format.  */
1510 void
1511 get_wim_reshdr(const struct wim_reshdr_disk *disk_reshdr,
1512                struct wim_reshdr *reshdr)
1513 {
1514         reshdr->offset_in_wim = le64_to_cpu(disk_reshdr->offset_in_wim);
1515         reshdr->size_in_wim = (((u64)disk_reshdr->size_in_wim[0] <<  0) |
1516                                ((u64)disk_reshdr->size_in_wim[1] <<  8) |
1517                                ((u64)disk_reshdr->size_in_wim[2] << 16) |
1518                                ((u64)disk_reshdr->size_in_wim[3] << 24) |
1519                                ((u64)disk_reshdr->size_in_wim[4] << 32) |
1520                                ((u64)disk_reshdr->size_in_wim[5] << 40) |
1521                                ((u64)disk_reshdr->size_in_wim[6] << 48));
1522         reshdr->uncompressed_size = le64_to_cpu(disk_reshdr->uncompressed_size);
1523         reshdr->flags = disk_reshdr->flags;
1524 }
1525
1526 /* Translates a WIM resource header from an in-memory format into the on-disk
1527  * format.  */
1528 void
1529 put_wim_reshdr(const struct wim_reshdr *reshdr,
1530                struct wim_reshdr_disk *disk_reshdr)
1531 {
1532         disk_reshdr->size_in_wim[0] = reshdr->size_in_wim  >>  0;
1533         disk_reshdr->size_in_wim[1] = reshdr->size_in_wim  >>  8;
1534         disk_reshdr->size_in_wim[2] = reshdr->size_in_wim  >> 16;
1535         disk_reshdr->size_in_wim[3] = reshdr->size_in_wim  >> 24;
1536         disk_reshdr->size_in_wim[4] = reshdr->size_in_wim  >> 32;
1537         disk_reshdr->size_in_wim[5] = reshdr->size_in_wim  >> 40;
1538         disk_reshdr->size_in_wim[6] = reshdr->size_in_wim  >> 48;
1539         disk_reshdr->flags = reshdr->flags;
1540         disk_reshdr->offset_in_wim = cpu_to_le64(reshdr->offset_in_wim);
1541         disk_reshdr->uncompressed_size = cpu_to_le64(reshdr->uncompressed_size);
1542 }