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