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