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