]> wimlib.net Git - wimlib/blob - src/resource.c
portability and compression cleanups
[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         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 = fls32(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 _may_alias_attribute aliased_le64_t;
331                 typedef le32 _may_alias_attribute 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 /* Callback for finishing reading a stream while calculating its SHA1 message
1099  * digest.  */
1100 static int
1101 hasher_end_stream(struct wim_lookup_table_entry *lte, int status, void *_ctx)
1102 {
1103         struct hasher_context *ctx = _ctx;
1104         u8 hash[SHA1_HASH_SIZE];
1105         int ret;
1106
1107         if (status) {
1108                 /* Error occurred; the full stream may not have been read.  */
1109                 ret = status;
1110                 goto out_next_cb;
1111         }
1112
1113         /* Retrieve the final SHA1 message digest.  */
1114         sha1_final(hash, &ctx->sha_ctx);
1115
1116         if (lte->unhashed) {
1117                 if (ctx->flags & COMPUTE_MISSING_STREAM_HASHES) {
1118                         /* No SHA1 message digest was previously present for the
1119                          * stream.  Set it to the one just calculated.  */
1120                         DEBUG("Set SHA1 message digest for stream "
1121                               "(size=%"PRIu64").", lte->size);
1122                         copy_hash(lte->hash, hash);
1123                 }
1124         } else {
1125                 if (ctx->flags & VERIFY_STREAM_HASHES) {
1126                         /* The stream already had a SHA1 message digest present.  Verify
1127                          * that it is the same as the calculated value.  */
1128                         if (!hashes_equal(hash, lte->hash)) {
1129                                 if (wimlib_print_errors) {
1130                                         tchar expected_hashstr[SHA1_HASH_SIZE * 2 + 1];
1131                                         tchar actual_hashstr[SHA1_HASH_SIZE * 2 + 1];
1132                                         sprint_hash(lte->hash, expected_hashstr);
1133                                         sprint_hash(hash, actual_hashstr);
1134                                         ERROR("The stream is corrupted!\n"
1135                                               "        (Expected SHA1=%"TS",\n"
1136                                               "              got SHA1=%"TS")",
1137                                               expected_hashstr, actual_hashstr);
1138                                 }
1139                                 ret = WIMLIB_ERR_INVALID_RESOURCE_HASH;
1140                                 errno = EINVAL;
1141                                 goto out_next_cb;
1142                         }
1143                         DEBUG("SHA1 message digest okay for "
1144                               "stream (size=%"PRIu64").", lte->size);
1145                 }
1146         }
1147         ret = 0;
1148 out_next_cb:
1149         if (ctx->cbs.end_stream == NULL)
1150                 return ret;
1151         else
1152                 return (*ctx->cbs.end_stream)(lte, ret, ctx->cbs.end_stream_ctx);
1153 }
1154
1155 static int
1156 read_full_stream_with_cbs(struct wim_lookup_table_entry *lte,
1157                           const struct read_stream_list_callbacks *cbs)
1158 {
1159         int ret;
1160
1161         ret = (*cbs->begin_stream)(lte, cbs->begin_stream_ctx);
1162         if (ret)
1163                 return ret;
1164
1165         ret = read_stream_prefix(lte, lte->size, cbs->consume_chunk,
1166                                  cbs->consume_chunk_ctx);
1167
1168         return (*cbs->end_stream)(lte, ret, cbs->end_stream_ctx);
1169 }
1170
1171 /* Read the full data of the specified stream, passing the data into the
1172  * specified callbacks (all of which are optional) and either checking or
1173  * computing the SHA1 message digest of the stream.  */
1174 static int
1175 read_full_stream_with_sha1(struct wim_lookup_table_entry *lte,
1176                            const struct read_stream_list_callbacks *cbs)
1177 {
1178         struct hasher_context hasher_ctx = {
1179                 .flags = VERIFY_STREAM_HASHES | COMPUTE_MISSING_STREAM_HASHES,
1180                 .cbs = *cbs,
1181         };
1182         struct read_stream_list_callbacks hasher_cbs = {
1183                 .begin_stream           = hasher_begin_stream,
1184                 .begin_stream_ctx       = &hasher_ctx,
1185                 .consume_chunk          = hasher_consume_chunk,
1186                 .consume_chunk_ctx      = &hasher_ctx,
1187                 .end_stream             = hasher_end_stream,
1188                 .end_stream_ctx         = &hasher_ctx,
1189         };
1190         return read_full_stream_with_cbs(lte, &hasher_cbs);
1191 }
1192
1193 static int
1194 read_packed_streams(struct wim_lookup_table_entry *first_stream,
1195                     struct wim_lookup_table_entry *last_stream,
1196                     u64 stream_count,
1197                     size_t list_head_offset,
1198                     const struct read_stream_list_callbacks *sink_cbs)
1199 {
1200         struct data_range *ranges;
1201         bool ranges_malloced;
1202         struct wim_lookup_table_entry *cur_stream;
1203         size_t i;
1204         int ret;
1205         u64 ranges_alloc_size;
1206
1207         DEBUG("Reading %"PRIu64" streams combined in same WIM resource",
1208               stream_count);
1209
1210         /* Setup data ranges array (one range per stream to read); this way
1211          * read_compressed_wim_resource() does not need to be aware of streams.
1212          */
1213
1214         ranges_alloc_size = stream_count * sizeof(ranges[0]);
1215
1216         if (unlikely((size_t)ranges_alloc_size != ranges_alloc_size)) {
1217                 ERROR("Too many streams in one resource!");
1218                 return WIMLIB_ERR_NOMEM;
1219         }
1220         if (likely(ranges_alloc_size <= STACK_MAX)) {
1221                 ranges = alloca(ranges_alloc_size);
1222                 ranges_malloced = false;
1223         } else {
1224                 ranges = MALLOC(ranges_alloc_size);
1225                 if (ranges == NULL) {
1226                         ERROR("Too many streams in one resource!");
1227                         return WIMLIB_ERR_NOMEM;
1228                 }
1229                 ranges_malloced = true;
1230         }
1231
1232         for (i = 0, cur_stream = first_stream;
1233              i < stream_count;
1234              i++, cur_stream = next_stream(cur_stream, list_head_offset))
1235         {
1236                 ranges[i].offset = cur_stream->offset_in_res;
1237                 ranges[i].size = cur_stream->size;
1238         }
1239
1240         struct streamifier_context streamifier_ctx = {
1241                 .cbs                    = *sink_cbs,
1242                 .cur_stream             = first_stream,
1243                 .next_stream            = next_stream(first_stream, list_head_offset),
1244                 .cur_stream_offset      = 0,
1245                 .final_stream           = last_stream,
1246                 .list_head_offset       = list_head_offset,
1247         };
1248
1249         ret = read_compressed_wim_resource(first_stream->rspec,
1250                                            ranges,
1251                                            stream_count,
1252                                            streamifier_cb,
1253                                            &streamifier_ctx);
1254
1255         if (ranges_malloced)
1256                 FREE(ranges);
1257
1258         if (ret) {
1259                 if (streamifier_ctx.cur_stream_offset != 0) {
1260                         ret = (*streamifier_ctx.cbs.end_stream)
1261                                 (streamifier_ctx.cur_stream,
1262                                  ret,
1263                                  streamifier_ctx.cbs.end_stream_ctx);
1264                 }
1265         }
1266         return ret;
1267 }
1268
1269 /*
1270  * Read a list of streams, each of which may be in any supported location (e.g.
1271  * in a WIM or in an external file).  Unlike read_stream_prefix() or the
1272  * functions which call it, this function optimizes the case where multiple
1273  * streams are packed into a single compressed WIM resource and reads them all
1274  * consecutively, only decompressing the data one time.
1275  *
1276  * @stream_list
1277  *      List of streams (represented as `struct wim_lookup_table_entry's) to
1278  *      read.
1279  * @list_head_offset
1280  *      Offset of the `struct list_head' within each `struct
1281  *      wim_lookup_table_entry' that makes up the @stream_list.
1282  * @cbs
1283  *      Callback functions to accept the stream data.
1284  * @flags
1285  *      Bitwise OR of zero or more of the following flags:
1286  *
1287  *      VERIFY_STREAM_HASHES:
1288  *              For all streams being read that have already had SHA1 message
1289  *              digests computed, calculate the SHA1 message digest of the read
1290  *              data and compare it with the previously computed value.  If they
1291  *              do not match, return WIMLIB_ERR_INVALID_RESOURCE_HASH.
1292  *
1293  *      COMPUTE_MISSING_STREAM_HASHES
1294  *              For all streams being read that have not yet had their SHA1
1295  *              message digests computed, calculate and save their SHA1 message
1296  *              digests.
1297  *
1298  *      STREAM_LIST_ALREADY_SORTED
1299  *              @stream_list is already sorted in sequential order for reading.
1300  *
1301  * The callback functions are allowed to delete the current stream from the list
1302  * if necessary.
1303  *
1304  * Returns 0 on success; a nonzero error code on failure.  Failure can occur due
1305  * to an error reading the data or due to an error status being returned by any
1306  * of the callback functions.
1307  */
1308 int
1309 read_stream_list(struct list_head *stream_list,
1310                  size_t list_head_offset,
1311                  const struct read_stream_list_callbacks *cbs,
1312                  int flags)
1313 {
1314         int ret;
1315         struct list_head *cur, *next;
1316         struct wim_lookup_table_entry *lte;
1317         struct hasher_context *hasher_ctx;
1318         struct read_stream_list_callbacks *sink_cbs;
1319
1320         if (!(flags & STREAM_LIST_ALREADY_SORTED)) {
1321                 ret = sort_stream_list_by_sequential_order(stream_list, list_head_offset);
1322                 if (ret)
1323                         return ret;
1324         }
1325
1326         if (flags & (VERIFY_STREAM_HASHES | COMPUTE_MISSING_STREAM_HASHES)) {
1327                 hasher_ctx = alloca(sizeof(*hasher_ctx));
1328                 *hasher_ctx = (struct hasher_context) {
1329                         .flags  = flags,
1330                         .cbs    = *cbs,
1331                 };
1332                 sink_cbs = alloca(sizeof(*sink_cbs));
1333                 *sink_cbs = (struct read_stream_list_callbacks) {
1334                         .begin_stream           = hasher_begin_stream,
1335                         .begin_stream_ctx       = hasher_ctx,
1336                         .consume_chunk          = hasher_consume_chunk,
1337                         .consume_chunk_ctx      = hasher_ctx,
1338                         .end_stream             = hasher_end_stream,
1339                         .end_stream_ctx         = hasher_ctx,
1340                 };
1341         } else {
1342                 sink_cbs = (struct read_stream_list_callbacks*)cbs;
1343         }
1344
1345         for (cur = stream_list->next, next = cur->next;
1346              cur != stream_list;
1347              cur = next, next = cur->next)
1348         {
1349                 lte = (struct wim_lookup_table_entry*)((u8*)cur - list_head_offset);
1350
1351                 if (lte->flags & WIM_RESHDR_FLAG_PACKED_STREAMS &&
1352                     lte->size != lte->rspec->uncompressed_size)
1353                 {
1354
1355                         struct wim_lookup_table_entry *lte_next, *lte_last;
1356                         struct list_head *next2;
1357                         u64 stream_count;
1358
1359                         /* The next stream is a proper sub-sequence of a WIM
1360                          * resource.  See if there are other streams in the same
1361                          * resource that need to be read.  Since
1362                          * sort_stream_list_by_sequential_order() sorted the
1363                          * streams by offset in the WIM, this can be determined
1364                          * by simply scanning forward in the list.  */
1365
1366                         lte_last = lte;
1367                         stream_count = 1;
1368                         for (next2 = next;
1369                              next2 != stream_list
1370                              && (lte_next = (struct wim_lookup_table_entry*)
1371                                                 ((u8*)next2 - list_head_offset),
1372                                  lte_next->resource_location == RESOURCE_IN_WIM
1373                                  && lte_next->rspec == lte->rspec);
1374                              next2 = next2->next)
1375                         {
1376                                 lte_last = lte_next;
1377                                 stream_count++;
1378                         }
1379                         if (stream_count > 1) {
1380                                 /* Reading multiple streams combined into a
1381                                  * single WIM resource.  They are in the stream
1382                                  * list, sorted by offset; @lte specifies the
1383                                  * first stream in the resource that needs to be
1384                                  * read and @lte_last specifies the last stream
1385                                  * in the resource that needs to be read.  */
1386                                 next = next2;
1387                                 ret = read_packed_streams(lte, lte_last,
1388                                                           stream_count,
1389                                                           list_head_offset,
1390                                                           sink_cbs);
1391                                 if (ret)
1392                                         return ret;
1393                                 continue;
1394                         }
1395                 }
1396
1397                 ret = read_full_stream_with_cbs(lte, sink_cbs);
1398                 if (ret && ret != BEGIN_STREAM_STATUS_SKIP_STREAM)
1399                         return ret;
1400         }
1401         return 0;
1402 }
1403
1404 /* Extract the first @size bytes of the specified stream.
1405  *
1406  * If @size specifies the full uncompressed size of the stream, then the SHA1
1407  * message digest of the uncompressed stream is checked while being extracted.
1408  *
1409  * The uncompressed data of the resource is passed in chunks of unspecified size
1410  * to the @extract_chunk function, passing it @extract_chunk_arg.  */
1411 int
1412 extract_stream(struct wim_lookup_table_entry *lte, u64 size,
1413                consume_data_callback_t extract_chunk, void *extract_chunk_arg)
1414 {
1415         wimlib_assert(size <= lte->size);
1416         if (size == lte->size) {
1417                 /* Do SHA1.  */
1418                 struct read_stream_list_callbacks cbs = {
1419                         .consume_chunk          = extract_chunk,
1420                         .consume_chunk_ctx      = extract_chunk_arg,
1421                 };
1422                 return read_full_stream_with_sha1(lte, &cbs);
1423         } else {
1424                 /* Don't do SHA1.  */
1425                 return read_stream_prefix(lte, size, extract_chunk,
1426                                           extract_chunk_arg);
1427         }
1428 }
1429
1430 /* A consume_data_callback_t implementation that writes the chunk of data to a
1431  * file descriptor.  */
1432 static int
1433 extract_chunk_to_fd(const void *chunk, size_t size, void *_fd_p)
1434 {
1435         struct filedes *fd = _fd_p;
1436
1437         int ret = full_write(fd, chunk, size);
1438         if (ret) {
1439                 ERROR_WITH_ERRNO("Error writing to file descriptor");
1440                 return ret;
1441         }
1442         return 0;
1443 }
1444
1445 /* Extract the first @size bytes of the specified stream to the specified file
1446  * descriptor.  */
1447 int
1448 extract_stream_to_fd(struct wim_lookup_table_entry *lte,
1449                      struct filedes *fd, u64 size)
1450 {
1451         return extract_stream(lte, size, extract_chunk_to_fd, fd);
1452 }
1453
1454 /* Extract the full uncompressed contents of the specified stream to the
1455  * specified file descriptor.  */
1456 int
1457 extract_full_stream_to_fd(struct wim_lookup_table_entry *lte,
1458                           struct filedes *fd)
1459 {
1460         return extract_stream_to_fd(lte, fd, lte->size);
1461 }
1462
1463 /* Calculate the SHA1 message digest of a stream and store it in @lte->hash.  */
1464 int
1465 sha1_stream(struct wim_lookup_table_entry *lte)
1466 {
1467         wimlib_assert(lte->unhashed);
1468         struct read_stream_list_callbacks cbs = {
1469         };
1470         return read_full_stream_with_sha1(lte, &cbs);
1471 }
1472
1473 /* Convert a short WIM resource header to a stand-alone WIM resource
1474  * specification.
1475  *
1476  * Note: for packed resources some fields still need to be overridden.
1477  */
1478 void
1479 wim_res_hdr_to_spec(const struct wim_reshdr *reshdr, WIMStruct *wim,
1480                     struct wim_resource_spec *rspec)
1481 {
1482         rspec->wim = wim;
1483         rspec->offset_in_wim = reshdr->offset_in_wim;
1484         rspec->size_in_wim = reshdr->size_in_wim;
1485         rspec->uncompressed_size = reshdr->uncompressed_size;
1486         INIT_LIST_HEAD(&rspec->stream_list);
1487         rspec->flags = reshdr->flags;
1488         rspec->is_pipable = wim_is_pipable(wim);
1489         if (rspec->flags & WIM_RESHDR_FLAG_COMPRESSED) {
1490                 rspec->compression_type = wim->compression_type;
1491                 rspec->chunk_size = wim->chunk_size;
1492         } else {
1493                 rspec->compression_type = WIMLIB_COMPRESSION_TYPE_NONE;
1494                 rspec->chunk_size = 0;
1495         }
1496 }
1497
1498 /* Convert a stand-alone resource specification to a WIM resource header.  */
1499 void
1500 wim_res_spec_to_hdr(const struct wim_resource_spec *rspec,
1501                     struct wim_reshdr *reshdr)
1502 {
1503         reshdr->offset_in_wim     = rspec->offset_in_wim;
1504         reshdr->size_in_wim       = rspec->size_in_wim;
1505         reshdr->flags             = rspec->flags;
1506         reshdr->uncompressed_size = rspec->uncompressed_size;
1507 }
1508
1509 /* Translates a WIM resource header from the on-disk format into an in-memory
1510  * format.  */
1511 void
1512 get_wim_reshdr(const struct wim_reshdr_disk *disk_reshdr,
1513                struct wim_reshdr *reshdr)
1514 {
1515         reshdr->offset_in_wim = le64_to_cpu(disk_reshdr->offset_in_wim);
1516         reshdr->size_in_wim = (((u64)disk_reshdr->size_in_wim[0] <<  0) |
1517                                ((u64)disk_reshdr->size_in_wim[1] <<  8) |
1518                                ((u64)disk_reshdr->size_in_wim[2] << 16) |
1519                                ((u64)disk_reshdr->size_in_wim[3] << 24) |
1520                                ((u64)disk_reshdr->size_in_wim[4] << 32) |
1521                                ((u64)disk_reshdr->size_in_wim[5] << 40) |
1522                                ((u64)disk_reshdr->size_in_wim[6] << 48));
1523         reshdr->uncompressed_size = le64_to_cpu(disk_reshdr->uncompressed_size);
1524         reshdr->flags = disk_reshdr->flags;
1525 }
1526
1527 /* Translates a WIM resource header from an in-memory format into the on-disk
1528  * format.  */
1529 void
1530 put_wim_reshdr(const struct wim_reshdr *reshdr,
1531                struct wim_reshdr_disk *disk_reshdr)
1532 {
1533         disk_reshdr->size_in_wim[0] = reshdr->size_in_wim  >>  0;
1534         disk_reshdr->size_in_wim[1] = reshdr->size_in_wim  >>  8;
1535         disk_reshdr->size_in_wim[2] = reshdr->size_in_wim  >> 16;
1536         disk_reshdr->size_in_wim[3] = reshdr->size_in_wim  >> 24;
1537         disk_reshdr->size_in_wim[4] = reshdr->size_in_wim  >> 32;
1538         disk_reshdr->size_in_wim[5] = reshdr->size_in_wim  >> 40;
1539         disk_reshdr->size_in_wim[6] = reshdr->size_in_wim  >> 48;
1540         disk_reshdr->flags = reshdr->flags;
1541         disk_reshdr->offset_in_wim = cpu_to_le64(reshdr->offset_in_wim);
1542         disk_reshdr->uncompressed_size = cpu_to_le64(reshdr->uncompressed_size);
1543 }