]> wimlib.net Git - wimlib/blob - src/resource.c
f37b8958300e6cd024a8882f559ed0d043781926
[wimlib] / src / resource.c
1 /*
2  * resource.c
3  *
4  * Read uncompressed and compressed metadata and file resources from a WIM file.
5  */
6
7 /*
8  * Copyright (C) 2012, 2013 Eric Biggers
9  *
10  * This file is part of wimlib, a library for working with WIM files.
11  *
12  * wimlib is free software; you can redistribute it and/or modify it under the
13  * terms of the GNU General Public License as published by the Free Software
14  * Foundation; either version 3 of the License, or (at your option) any later
15  * version.
16  *
17  * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
18  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
19  * A PARTICULAR PURPOSE. See the GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License along with
22  * wimlib; if not, see http://www.gnu.org/licenses/.
23  */
24
25 #ifdef HAVE_CONFIG_H
26 #  include "config.h"
27 #endif
28
29 #include "wimlib.h"
30 #include "wimlib/dentry.h"
31 #include "wimlib/endianness.h"
32 #include "wimlib/error.h"
33 #include "wimlib/file_io.h"
34 #include "wimlib/lookup_table.h"
35 #include "wimlib/resource.h"
36 #include "wimlib/sha1.h"
37
38 #ifdef __WIN32__
39 /* for read_win32_file_prefix(), read_win32_encrypted_file_prefix() */
40 #  include "wimlib/win32.h"
41 #endif
42
43 #ifdef WITH_NTFS_3G
44 /* for read_ntfs_file_prefix() */
45 #  include "wimlib/ntfs_3g.h"
46 #endif
47
48 #ifdef HAVE_ALLOCA_H
49 #  include <alloca.h>
50 #endif
51 #include <errno.h>
52 #include <fcntl.h>
53 #include <stdarg.h>
54 #include <stdlib.h>
55 #include <unistd.h>
56
57 /*
58  * Reads all or part of a compressed WIM resource.
59  *
60  * Returns zero on success, nonzero on failure.
61  */
62 static int
63 read_compressed_resource(int in_fd,
64                          u64 resource_compressed_size,
65                          u64 resource_uncompressed_size,
66                          u64 resource_offset,
67                          int resource_ctype,
68                          u64 len,
69                          u64 offset,
70                          consume_data_callback_t cb,
71                          void *ctx_or_buf)
72 {
73         int ret;
74
75         /* Trivial case */
76         if (len == 0)
77                 return 0;
78
79         int (*decompress)(const void *, unsigned, void *, unsigned);
80         /* Set the appropriate decompress function. */
81         if (resource_ctype == WIMLIB_COMPRESSION_TYPE_LZX)
82                 decompress = wimlib_lzx_decompress;
83         else
84                 decompress = wimlib_xpress_decompress;
85
86         /* The structure of a compressed resource consists of a table of chunk
87          * offsets followed by the chunks themselves.  Each chunk consists of
88          * compressed data, and there is one chunk for each WIM_CHUNK_SIZE =
89          * 32768 bytes of the uncompressed file, with the last chunk having any
90          * remaining bytes.
91          *
92          * The chunk offsets are measured relative to the end of the chunk
93          * table.  The first chunk is omitted from the table in the WIM file
94          * because its offset is implicitly given by the fact that it directly
95          * follows the chunk table and therefore must have an offset of 0.
96          */
97
98         /* Calculate how many chunks the resource consists of in its entirety.
99          * */
100         u64 num_chunks = DIV_ROUND_UP(resource_uncompressed_size, WIM_CHUNK_SIZE);
101
102         /* As mentioned, the first chunk has no entry in the chunk table. */
103         u64 num_chunk_entries = num_chunks - 1;
104
105
106         /* The index of the chunk that the read starts at. */
107         u64 start_chunk = offset / WIM_CHUNK_SIZE;
108         /* The byte offset at which the read starts, within the start chunk. */
109         u64 start_chunk_offset = offset % WIM_CHUNK_SIZE;
110
111         /* The index of the chunk that contains the last byte of the read. */
112         u64 end_chunk   = (offset + len - 1) / WIM_CHUNK_SIZE;
113         /* The byte offset of the last byte of the read, within the end chunk */
114         u64 end_chunk_offset = (offset + len - 1) % WIM_CHUNK_SIZE;
115
116         /* Number of chunks that are actually needed to read the requested part
117          * of the file. */
118         u64 num_needed_chunks = end_chunk - start_chunk + 1;
119
120         /* If the end chunk is not the last chunk, an extra chunk entry is
121          * needed because we need to know the offset of the chunk after the last
122          * chunk read to figure out the size of the last read chunk. */
123         if (end_chunk != num_chunks - 1)
124                 num_needed_chunks++;
125
126         /* According to M$'s documentation, if the uncompressed size of
127          * the file is greater than 4 GB, the chunk entries are 8-byte
128          * integers.  Otherwise, they are 4-byte integers. */
129         u64 chunk_entry_size = (resource_uncompressed_size >
130                                 (u64)1 << 32) ?  8 : 4;
131
132         /* Size of the full chunk table in the WIM file. */
133         u64 chunk_table_size = chunk_entry_size * num_chunk_entries;
134
135         /* Allocate the chunk table.  It will only contain offsets for the
136          * chunks that are actually needed for this read. */
137         u64 *chunk_offsets;
138         bool chunk_offsets_malloced;
139         if (num_needed_chunks < 1024) {
140                 chunk_offsets = alloca(num_needed_chunks * sizeof(u64));
141                 chunk_offsets_malloced = false;
142         } else {
143                 chunk_offsets = malloc(num_needed_chunks * sizeof(u64));
144                 if (!chunk_offsets) {
145                         ERROR("Failed to allocate chunk table "
146                               "with %"PRIu64" entries", num_needed_chunks);
147                         return WIMLIB_ERR_NOMEM;
148                 }
149                 chunk_offsets_malloced = true;
150         }
151
152         /* Set the implicit offset of the first chunk if it is included in the
153          * needed chunks.
154          *
155          * Note: M$'s documentation includes a picture that shows the first
156          * chunk starting right after the chunk entry table, labeled as offset
157          * 0x10.  However, in the actual file format, the offset is measured
158          * from the end of the chunk entry table, so the first chunk has an
159          * offset of 0. */
160         if (start_chunk == 0)
161                 chunk_offsets[0] = 0;
162
163
164         /* Read the needed chunk offsets from the table in the WIM file. */
165
166         /* Index, in the WIM file, of the first needed entry in the
167          * chunk table. */
168         u64 start_table_idx = (start_chunk == 0) ? 0 : start_chunk - 1;
169
170         /* Number of entries we need to actually read from the chunk
171          * table (excludes the implicit first chunk). */
172         u64 num_needed_chunk_entries = (start_chunk == 0) ?
173                                 num_needed_chunks - 1 : num_needed_chunks;
174
175         /* Skip over unneeded chunk table entries. */
176         u64 file_offset_of_needed_chunk_entries = resource_offset +
177                                 start_table_idx * chunk_entry_size;
178
179         /* Allocate a buffer into which to read the raw chunk entries. */
180         void *chunk_tab_buf;
181         bool chunk_tab_buf_malloced = false;
182
183         /* Number of bytes we need to read from the chunk table. */
184         size_t size = num_needed_chunk_entries * chunk_entry_size;
185         if ((u64)size != num_needed_chunk_entries * chunk_entry_size) {
186                 ERROR("Compressed read request too large to fit into memory!");
187                 ret = WIMLIB_ERR_NOMEM;
188                 goto out;
189         }
190
191         if (size < 4096) {
192                 chunk_tab_buf = alloca(size);
193         } else {
194                 chunk_tab_buf = malloc(size);
195                 if (!chunk_tab_buf) {
196                         ERROR("Failed to allocate chunk table buffer of "
197                               "size %zu bytes", size);
198                         ret = WIMLIB_ERR_NOMEM;
199                         goto out;
200                 }
201                 chunk_tab_buf_malloced = true;
202         }
203
204         if (full_pread(in_fd, chunk_tab_buf, size,
205                        file_offset_of_needed_chunk_entries) != size)
206                 goto read_error;
207
208         /* Now fill in chunk_offsets from the entries we have read in
209          * chunk_tab_buf. */
210
211         u64 *chunk_tab_p = chunk_offsets;
212         if (start_chunk == 0)
213                 chunk_tab_p++;
214
215         if (chunk_entry_size == 4) {
216                 le32 *entries = (le32*)chunk_tab_buf;
217                 while (num_needed_chunk_entries--)
218                         *chunk_tab_p++ = le32_to_cpu(*entries++);
219         } else {
220                 le64 *entries = (le64*)chunk_tab_buf;
221                 while (num_needed_chunk_entries--)
222                         *chunk_tab_p++ = le64_to_cpu(*entries++);
223         }
224
225         /* Done reading the chunk table now.  Now calculate the file offset for
226          * the first byte of compressed data we need to read. */
227
228         u64 cur_read_offset = resource_offset + chunk_table_size + chunk_offsets[0];
229
230         /* Pointer to current position in the output buffer for uncompressed
231          * data.  Alternatively, if using a callback function, we repeatedly
232          * fill a temporary buffer to feed data into the callback function.  */
233         u8 *out_p;
234         if (cb)
235                 out_p = alloca(WIM_CHUNK_SIZE);
236         else
237                 out_p = ctx_or_buf;
238
239         /* Buffer for compressed data.  While most compressed chunks will have a
240          * size much less than WIM_CHUNK_SIZE, WIM_CHUNK_SIZE - 1 is the maximum
241          * size in the worst-case.  This assumption is valid only if chunks that
242          * happen to compress to more than the uncompressed size (i.e. a
243          * sequence of random bytes) are always stored uncompressed. But this seems
244          * to be the case in M$'s WIM files, even though it is undocumented. */
245         void *compressed_buf = alloca(WIM_CHUNK_SIZE - 1);
246
247         /* Decompress all the chunks. */
248         for (u64 i = start_chunk; i <= end_chunk; i++) {
249
250                 /* Calculate the sizes of the compressed chunk and of the
251                  * uncompressed chunk. */
252                 unsigned compressed_chunk_size;
253                 unsigned uncompressed_chunk_size;
254                 if (i != num_chunks - 1) {
255                         /* All the chunks except the last one in the resource
256                          * expand to WIM_CHUNK_SIZE uncompressed, and the amount
257                          * of compressed data for the chunk is given by the
258                          * difference of offsets in the chunk offset table. */
259                         compressed_chunk_size = chunk_offsets[i + 1 - start_chunk] -
260                                                 chunk_offsets[i - start_chunk];
261                         uncompressed_chunk_size = WIM_CHUNK_SIZE;
262                 } else {
263                         /* The last compressed chunk consists of the remaining
264                          * bytes in the file resource, and the last uncompressed
265                          * chunk has size equal to however many bytes are left-
266                          * that is, the remainder of the uncompressed size when
267                          * divided by WIM_CHUNK_SIZE.
268                          *
269                          * Note that the resource_compressed_size includes the
270                          * chunk table, so the size of it must be subtracted. */
271                         compressed_chunk_size = resource_compressed_size -
272                                                 chunk_table_size -
273                                                 chunk_offsets[i - start_chunk];
274
275                         uncompressed_chunk_size = resource_uncompressed_size %
276                                                                 WIM_CHUNK_SIZE;
277
278                         /* If the remainder is 0, the last chunk actually
279                          * uncompresses to a full WIM_CHUNK_SIZE bytes. */
280                         if (uncompressed_chunk_size == 0)
281                                 uncompressed_chunk_size = WIM_CHUNK_SIZE;
282                 }
283
284                 /* Figure out how much of this chunk we actually need to read */
285                 u64 start_offset;
286                 if (i == start_chunk)
287                         start_offset = start_chunk_offset;
288                 else
289                         start_offset = 0;
290                 u64 end_offset;
291                 if (i == end_chunk)
292                         end_offset = end_chunk_offset;
293                 else
294                         end_offset = WIM_CHUNK_SIZE - 1;
295
296                 unsigned partial_chunk_size = end_offset + 1 - start_offset;
297                 bool is_partial_chunk = (partial_chunk_size != uncompressed_chunk_size);
298
299                 /* This is undocumented, but chunks can be uncompressed.  This
300                  * appears to always be the case when the compressed chunk size
301                  * is equal to the uncompressed chunk size. */
302                 if (compressed_chunk_size == uncompressed_chunk_size) {
303                         /* Uncompressed chunk */
304                         if (full_pread(in_fd,
305                                        cb ? out_p + start_offset : out_p,
306                                        partial_chunk_size,
307                                        cur_read_offset + start_offset) != partial_chunk_size)
308                         {
309                                 goto read_error;
310                         }
311                 } else {
312                         /* Compressed chunk */
313
314                         /* Read the compressed data into compressed_buf. */
315                         if (full_pread(in_fd,
316                                        compressed_buf,
317                                        compressed_chunk_size,
318                                        cur_read_offset) != compressed_chunk_size)
319                         {
320                                 goto read_error;
321                         }
322
323                         /* For partial chunks and when writing directly to a
324                          * buffer, we must buffer the uncompressed data because
325                          * we don't need all of it. */
326                         if (is_partial_chunk && !cb) {
327                                 u8 uncompressed_buf[uncompressed_chunk_size];
328
329                                 ret = decompress(compressed_buf,
330                                                  compressed_chunk_size,
331                                                  uncompressed_buf,
332                                                  uncompressed_chunk_size);
333                                 if (ret) {
334                                         ret = WIMLIB_ERR_DECOMPRESSION;
335                                         goto out;
336                                 }
337                                 memcpy(out_p, uncompressed_buf + start_offset,
338                                        partial_chunk_size);
339                         } else {
340                                 ret = decompress(compressed_buf,
341                                                  compressed_chunk_size,
342                                                  out_p,
343                                                  uncompressed_chunk_size);
344                                 if (ret) {
345                                         ret = WIMLIB_ERR_DECOMPRESSION;
346                                         goto out;
347                                 }
348                         }
349                 }
350                 if (cb) {
351                         /* Feed the data to the callback function */
352                         ret = cb(out_p + start_offset,
353                                  partial_chunk_size, ctx_or_buf);
354                         if (ret)
355                                 goto out;
356                 } else {
357                         /* No callback function provided; we are writing
358                          * directly to a buffer.  Advance the pointer into this
359                          * buffer by the number of uncompressed bytes that were
360                          * written.  */
361                         out_p += partial_chunk_size;
362                 }
363                 cur_read_offset += compressed_chunk_size;
364         }
365
366         ret = 0;
367 out:
368         if (chunk_offsets_malloced)
369                 FREE(chunk_offsets);
370         if (chunk_tab_buf_malloced)
371                 FREE(chunk_tab_buf);
372         return ret;
373
374 read_error:
375         ERROR_WITH_ERRNO("Error reading compressed file resource");
376         ret = WIMLIB_ERR_READ;
377         goto out;
378 }
379
380 /* Translates a WIM resource entry from the on-disk format to an in-memory
381  * format. */
382 void
383 get_resource_entry(const struct resource_entry_disk *disk_entry,
384                    struct resource_entry *entry)
385 {
386         /* Note: disk_entry may not be 8 byte aligned--- in that case, the
387          * offset and original_size members will be unaligned.  (This should be
388          * okay since `struct resource_entry_disk' is declared as packed.) */
389
390         /* Read the size and flags into a bitfield portably... */
391         entry->size = (((u64)disk_entry->size[0] <<  0) |
392                        ((u64)disk_entry->size[1] <<  8) |
393                        ((u64)disk_entry->size[2] << 16) |
394                        ((u64)disk_entry->size[3] << 24) |
395                        ((u64)disk_entry->size[4] << 32) |
396                        ((u64)disk_entry->size[5] << 40) |
397                        ((u64)disk_entry->size[6] << 48));
398         entry->flags = disk_entry->flags;
399         entry->offset = le64_to_cpu(disk_entry->offset);
400         entry->original_size = le64_to_cpu(disk_entry->original_size);
401
402         /* offset and original_size are truncated to 62 bits to avoid possible
403          * overflows, when converting to a signed 64-bit integer (off_t) or when
404          * adding size or original_size.  This is okay since no one would ever
405          * actually have a WIM bigger than 4611686018427387903 bytes... */
406         if (entry->offset & 0xc000000000000000ULL) {
407                 WARNING("Truncating offset in resource entry");
408                 entry->offset &= 0x3fffffffffffffffULL;
409         }
410         if (entry->original_size & 0xc000000000000000ULL) {
411                 WARNING("Truncating original_size in resource entry");
412                 entry->original_size &= 0x3fffffffffffffffULL;
413         }
414 }
415
416 /* Translates a WIM resource entry from an in-memory format into the on-disk
417  * format. */
418 void
419 put_resource_entry(const struct resource_entry *entry,
420                    struct resource_entry_disk *disk_entry)
421 {
422         /* Note: disk_entry may not be 8 byte aligned--- in that case, the
423          * offset and original_size members will be unaligned.  (This should be
424          * okay since `struct resource_entry_disk' is declared as packed.) */
425         u64 size = entry->size;
426
427         disk_entry->size[0] = size >>  0;
428         disk_entry->size[1] = size >>  8;
429         disk_entry->size[2] = size >> 16;
430         disk_entry->size[3] = size >> 24;
431         disk_entry->size[4] = size >> 32;
432         disk_entry->size[5] = size >> 40;
433         disk_entry->size[6] = size >> 48;
434         disk_entry->flags = entry->flags;
435         disk_entry->offset = cpu_to_le64(entry->offset);
436         disk_entry->original_size = cpu_to_le64(entry->original_size);
437 }
438
439 static int
440 read_partial_wim_resource(const struct wim_lookup_table_entry *lte,
441                           u64 size,
442                           consume_data_callback_t cb,
443                           void *ctx_or_buf,
444                           int flags,
445                           u64 offset)
446 {
447         WIMStruct *wim;
448         int in_fd;
449         int ret;
450
451         wimlib_assert(lte->resource_location == RESOURCE_IN_WIM);
452
453         wim = lte->wim;
454         in_fd = wim->in_fd;
455
456         if (lte->resource_entry.flags & WIM_RESHDR_FLAG_COMPRESSED &&
457             !(flags & WIMLIB_RESOURCE_FLAG_RAW))
458         {
459                 ret = read_compressed_resource(in_fd,
460                                                lte->resource_entry.size,
461                                                lte->resource_entry.original_size,
462                                                lte->resource_entry.offset,
463                                                wimlib_get_compression_type(wim),
464                                                size,
465                                                offset,
466                                                cb,
467                                                ctx_or_buf);
468         } else {
469                 offset += lte->resource_entry.offset;
470                 if (cb) {
471                         /* Send data to callback function */
472                         u8 buf[min(WIM_CHUNK_SIZE, size)];
473                         while (size) {
474                                 size_t bytes_to_read = min(WIM_CHUNK_SIZE, size);
475                                 size_t bytes_read = full_pread(in_fd, buf,
476                                                                bytes_to_read, offset);
477                                 if (bytes_read != bytes_to_read)
478                                         goto read_error;
479                                 ret = cb(buf, bytes_read, ctx_or_buf);
480                                 if (ret)
481                                         goto out;
482                                 size -= bytes_read;
483                                 offset += bytes_read;
484                         }
485                 } else {
486                         /* Send data directly to a buffer */
487                         if (full_pread(in_fd, ctx_or_buf, size, offset) != size)
488                                 goto read_error;
489                 }
490                 ret = 0;
491         }
492         goto out;
493 read_error:
494         ERROR_WITH_ERRNO("Error reading data from WIM");
495         ret = WIMLIB_ERR_READ;
496 out:
497         if (ret) {
498                 if (errno == 0)
499                         errno = EIO;
500         }
501         return ret;
502 }
503
504
505 int
506 read_partial_wim_resource_into_buf(const struct wim_lookup_table_entry *lte,
507                                    size_t size, u64 offset, void *buf)
508 {
509         return read_partial_wim_resource(lte, size, NULL, buf, 0, offset);
510 }
511
512 static int
513 read_wim_resource_prefix(const struct wim_lookup_table_entry *lte,
514                          u64 size,
515                          consume_data_callback_t cb,
516                          void *ctx_or_buf,
517                          int flags)
518 {
519         return read_partial_wim_resource(lte, size, cb, ctx_or_buf, flags, 0);
520 }
521
522
523 #ifndef __WIN32__
524 static int
525 read_file_on_disk_prefix(const struct wim_lookup_table_entry *lte,
526                          u64 size,
527                          consume_data_callback_t cb,
528                          void *ctx_or_buf,
529                          int _ignored_flags)
530 {
531         const tchar *filename = lte->file_on_disk;
532         int ret;
533         int fd;
534         size_t bytes_read;
535
536         fd = open(filename, O_RDONLY);
537         if (fd < 0) {
538                 ERROR_WITH_ERRNO("Can't open \"%"TS"\"", filename);
539                 return WIMLIB_ERR_OPEN;
540         }
541         if (cb) {
542                 /* Send data to callback function */
543                 u8 buf[min(WIM_CHUNK_SIZE, size)];
544                 size_t bytes_to_read;
545                 while (size) {
546                         bytes_to_read = min(WIM_CHUNK_SIZE, size);
547                         bytes_read = full_read(fd, buf, bytes_to_read);
548                         if (bytes_read != bytes_to_read)
549                                 goto read_error;
550                         ret = cb(buf, bytes_read, ctx_or_buf);
551                         if (ret)
552                                 goto out_close;
553                         size -= bytes_read;
554                 }
555         } else {
556                 /* Send data directly to a buffer */
557                 bytes_read = full_read(fd, ctx_or_buf, size);
558                 if (bytes_read != size)
559                         goto read_error;
560         }
561         ret = 0;
562         goto out_close;
563 read_error:
564         ERROR_WITH_ERRNO("Error reading \"%"TS"\"", filename);
565         ret = WIMLIB_ERR_READ;
566 out_close:
567         close(fd);
568         return ret;
569 }
570 #endif /* !__WIN32__ */
571
572 static int
573 read_buffer_prefix(const struct wim_lookup_table_entry *lte,
574                    u64 size, consume_data_callback_t cb,
575                    void *ctx_or_buf, int _ignored_flags)
576 {
577         const void *inbuf = lte->attached_buffer;
578         int ret;
579
580         if (cb) {
581                 while (size) {
582                         size_t chunk_size = min(WIM_CHUNK_SIZE, size);
583                         ret = cb(inbuf, chunk_size, ctx_or_buf);
584                         if (ret)
585                                 return ret;
586                         size -= chunk_size;
587                         inbuf += chunk_size;
588                 }
589         } else {
590                 memcpy(ctx_or_buf, inbuf, size);
591         }
592         return 0;
593 }
594
595 typedef int (*read_resource_prefix_handler_t)(const struct wim_lookup_table_entry *lte,
596                                               u64 size,
597                                               consume_data_callback_t cb,
598                                               void *ctx_or_buf,
599                                               int flags);
600
601 /*
602  * Read the first @size bytes from a generic "resource", which may be located in
603  * the WIM (compressed or uncompressed), in an external file, or directly in an
604  * in-memory buffer.
605  *
606  * Feed the data either to a callback function (cb != NULL, passing it
607  * ctx_or_buf), or write it directly into a buffer (cb == NULL, ctx_or_buf
608  * specifies the buffer, which must have room for @size bytes).
609  *
610  * When using a callback function, it is called with chunks up to 32768 bytes in
611  * size until the resource is exhausted.
612  *
613  * If the resource is located in a WIM file, @flags can be:
614  *   * WIMLIB_RESOURCE_FLAG_RAW if the raw compressed data is to be supplied
615  *     instead of the uncompressed data.
616  * Otherwise, the @flags are ignored.
617  */
618 int
619 read_resource_prefix(const struct wim_lookup_table_entry *lte,
620                      u64 size, consume_data_callback_t cb, void *ctx_or_buf,
621                      int flags)
622 {
623         static const read_resource_prefix_handler_t handlers[] = {
624                 [RESOURCE_IN_WIM]             = read_wim_resource_prefix,
625         #ifndef __WIN32__
626                 [RESOURCE_IN_FILE_ON_DISK]    = read_file_on_disk_prefix,
627         #endif
628                 [RESOURCE_IN_ATTACHED_BUFFER] = read_buffer_prefix,
629         #ifdef WITH_FUSE
630                 [RESOURCE_IN_STAGING_FILE]    = read_file_on_disk_prefix,
631         #endif
632         #ifdef WITH_NTFS_3G
633                 [RESOURCE_IN_NTFS_VOLUME]     = read_ntfs_file_prefix,
634         #endif
635         #ifdef __WIN32__
636                 [RESOURCE_WIN32]              = read_win32_file_prefix,
637                 [RESOURCE_WIN32_ENCRYPTED]    = read_win32_encrypted_file_prefix,
638         #endif
639         };
640         wimlib_assert(lte->resource_location < ARRAY_LEN(handlers)
641                       && handlers[lte->resource_location] != NULL);
642         return handlers[lte->resource_location](lte, size, cb, ctx_or_buf, flags);
643 }
644
645 int
646 read_full_resource_into_buf(const struct wim_lookup_table_entry *lte,
647                             void *buf)
648 {
649         return read_resource_prefix(lte, wim_resource_size(lte), NULL, buf, 0);
650 }
651
652 struct extract_ctx {
653         SHA_CTX sha_ctx;
654         consume_data_callback_t extract_chunk;
655         void *extract_chunk_arg;
656 };
657
658 static int
659 extract_chunk_sha1_wrapper(const void *chunk, size_t chunk_size,
660                            void *_ctx)
661 {
662         struct extract_ctx *ctx = _ctx;
663
664         sha1_update(&ctx->sha_ctx, chunk, chunk_size);
665         return ctx->extract_chunk(chunk, chunk_size, ctx->extract_chunk_arg);
666 }
667
668 /* Extracts the first @size bytes of a WIM resource to somewhere.  In the
669  * process, the SHA1 message digest of the resource is checked if the full
670  * resource is being extracted.
671  *
672  * @extract_chunk is a function that is called to extract each chunk of the
673  * resource. */
674 int
675 extract_wim_resource(const struct wim_lookup_table_entry *lte,
676                      u64 size,
677                      consume_data_callback_t extract_chunk,
678                      void *extract_chunk_arg)
679 {
680         int ret;
681         if (size == wim_resource_size(lte)) {
682                 /* Do SHA1 */
683                 struct extract_ctx ctx;
684                 ctx.extract_chunk = extract_chunk;
685                 ctx.extract_chunk_arg = extract_chunk_arg;
686                 sha1_init(&ctx.sha_ctx);
687                 ret = read_resource_prefix(lte, size,
688                                            extract_chunk_sha1_wrapper,
689                                            &ctx, 0);
690                 if (ret == 0) {
691                         u8 hash[SHA1_HASH_SIZE];
692                         sha1_final(hash, &ctx.sha_ctx);
693                         if (!hashes_equal(hash, lte->hash)) {
694                                 if (wimlib_print_errors) {
695                                         ERROR("Invalid SHA1 message digest "
696                                               "on the following WIM resource:");
697                                         print_lookup_table_entry(lte, stderr);
698                                         if (lte->resource_location == RESOURCE_IN_WIM)
699                                                 ERROR("The WIM file appears to be corrupt!");
700                                 }
701                                 ret = WIMLIB_ERR_INVALID_RESOURCE_HASH;
702                         }
703                 }
704         } else {
705                 /* Don't do SHA1 */
706                 ret = read_resource_prefix(lte, size, extract_chunk,
707                                            extract_chunk_arg, 0);
708         }
709         return ret;
710 }
711
712 static int
713 extract_wim_chunk_to_fd(const void *buf, size_t len, void *_fd_p)
714 {
715         int fd = *(int*)_fd_p;
716         ssize_t ret = full_write(fd, buf, len);
717         if (ret < len) {
718                 ERROR_WITH_ERRNO("Error writing to file descriptor");
719                 return WIMLIB_ERR_WRITE;
720         } else {
721                 return 0;
722         }
723 }
724
725 int
726 extract_wim_resource_to_fd(const struct wim_lookup_table_entry *lte,
727                            int fd, u64 size)
728 {
729         return extract_wim_resource(lte, size, extract_wim_chunk_to_fd, &fd);
730 }
731
732
733 static int
734 sha1_chunk(const void *buf, size_t len, void *ctx)
735 {
736         sha1_update(ctx, buf, len);
737         return 0;
738 }
739
740 /* Calculate the SHA1 message digest of a stream. */
741 int
742 sha1_resource(struct wim_lookup_table_entry *lte)
743 {
744         int ret;
745         SHA_CTX sha_ctx;
746
747         sha1_init(&sha_ctx);
748         ret = read_resource_prefix(lte, wim_resource_size(lte),
749                                    sha1_chunk, &sha_ctx, 0);
750         if (ret == 0)
751                 sha1_final(lte->hash, &sha_ctx);
752         return ret;
753 }
754
755 /*
756  * Copies the file resource specified by the lookup table entry @lte from the
757  * input WIM to the output WIM that has its FILE * given by
758  * ((WIMStruct*)wim)->out_fp.
759  *
760  * The output_resource_entry, out_refcnt, and part_number fields of @lte are
761  * updated.
762  *
763  * (This function is confusing and should be refactored somehow.)
764  */
765 int
766 copy_resource(struct wim_lookup_table_entry *lte, void *wim)
767 {
768         WIMStruct *w = wim;
769         int ret;
770
771         ret = write_wim_resource(lte, w->out_fd,
772                                  wim_resource_compression_type(lte),
773                                  &lte->output_resource_entry, 0);
774         if (ret == 0) {
775                 lte->out_refcnt = lte->refcnt;
776                 lte->part_number = w->hdr.part_number;
777         }
778         return ret;
779 }