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