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