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