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