integrity.c: Minor cleanup
[wimlib] / src / integrity.c
1 /*
2  * integrity.c
3  *
4  * WIM files can optionally contain a table of SHA1 message digests at the end,
5  * one digest for each chunk of the file of some specified size (often 10 MB).
6  * This file implements the checking and writing this table.
7  */
8
9 /*
10  * Copyright (C) 2012 Eric Biggers
11  *
12  * This file is part of wimlib, a library for working with WIM files.
13  *
14  * wimlib is free software; you can redistribute it and/or modify it under the
15  * terms of the GNU General Public License as published by the Free
16  * Software Foundation; either version 3 of the License, or (at your option)
17  * any later version.
18  *
19  * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
20  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
21  * A PARTICULAR PURPOSE. See the GNU General Public License for more
22  * details.
23  *
24  * You should have received a copy of the GNU General Public License
25  * along with wimlib; if not, see http://www.gnu.org/licenses/.
26  */
27
28 #include "wimlib_internal.h"
29 #include "io.h"
30 #include "sha1.h"
31
32 /* Size, in bytes, of each SHA1-summed chunk, when wimlib writes integrity
33  * information. */
34 #define INTEGRITY_CHUNK_SIZE 10485760
35
36 /* Only use a different chunk size for compatiblity with an existing integrity
37  * table if the chunk size is between these two numbers. */
38 #define INTEGRITY_MIN_CHUNK_SIZE 4096
39 #define INTEGRITY_MAX_CHUNK_SIZE 134217728
40
41 struct integrity_table {
42         u32 size;
43         u32 num_entries;
44         u32 chunk_size;
45         u8  sha1sums[0][20];
46 };
47
48 static int calculate_chunk_sha1(FILE *fp, size_t this_chunk_size,
49                                 off_t offset, u8 sha1_md[])
50 {
51         int ret;
52         u8 buf[BUFFER_SIZE];
53         SHA_CTX ctx;
54         size_t bytes_remaining;
55         size_t bytes_to_read;
56         size_t bytes_read;
57
58         ret = fseeko(fp, offset, SEEK_SET);
59         if (ret != 0) {
60                 ERROR_WITH_ERRNO("Can't seek to offset "
61                                  "%"PRIu64" in WIM", offset);
62                 return WIMLIB_ERR_READ;
63         }
64         bytes_remaining = this_chunk_size;
65         sha1_init(&ctx);
66         do {
67                 bytes_to_read = min(bytes_remaining, sizeof(buf));
68                 bytes_read = fread(buf, 1, bytes_to_read, fp);
69                 if (bytes_read != bytes_to_read) {
70                         if (feof(fp)) {
71                                 ERROR("Unexpected EOF while calculating "
72                                       "integrity checksums");
73                         } else {
74                                 ERROR_WITH_ERRNO("File stream error while "
75                                                  "calculating integrity "
76                                                  "checksums");
77                         }
78                         return WIMLIB_ERR_READ;
79                 }
80                 sha1_update(&ctx, buf, bytes_read);
81                 bytes_remaining -= bytes_read;
82         } while (bytes_remaining);
83         sha1_final(sha1_md, &ctx);
84         return 0;
85 }
86
87
88 /*
89  * Reads the integrity table from a WIM file.
90  *
91  * @res_entry:
92  *      The resource entry that specifies the location of the integrity table.
93  *      The integrity table must exist (i.e. res_entry->offset must not be 0).
94  *
95  * @fp:
96  *      FILE * to the WIM file, opened for reading.
97  *
98  * @num_checked_bytes:
99  *      Number of bytes of data that should be checked by the integrity table.
100  *
101  * @table ret:
102  *      On success, a pointer to an in-memory structure containing the integrity
103  *      information is written to this location.
104  *
105  * Returns 0 on success; nonzero on failure.  The possible error codes are:
106  *
107  *     * WIMLIB_ERR_INVALID_INTEGRITY_TABLE:  The integrity table is invalid.
108  *     * WIMLIB_ERR_NOMEM:  Could not allocate memory to store the integrity
109  *                          data.
110  *     * WIMLIB_ERR_READ:   Could not read the integrity data from the WIM file.
111  */
112 static int read_integrity_table(const struct resource_entry *res_entry,
113                                 FILE *fp,
114                                 u64 num_checked_bytes,
115                                 struct integrity_table **table_ret)
116 {
117         struct integrity_table *table = NULL;
118         int ret = 0;
119         u64 expected_size;
120         u64 expected_num_entries;
121
122         if (resource_is_compressed(res_entry)) {
123                 ERROR("Didn't expect a compressed integrity table");
124                 return WIMLIB_ERR_INVALID_INTEGRITY_TABLE;
125         }
126
127         if (res_entry->size < 8 || res_entry->size  > 0xffffffff) {
128                 ERROR("Integrity table resource header is invalid");
129                 return WIMLIB_ERR_INVALID_INTEGRITY_TABLE;
130         }
131
132         /* Read the integrity table into memory. */
133         if ((table = MALLOC(res_entry->size)) == NULL) {
134                 ERROR("Can't allocate %"PRIu64" bytes for integrity table",
135                       (u64)res_entry->size);
136                 return WIMLIB_ERR_NOMEM;
137         }
138
139         ret = read_uncompressed_resource(fp, res_entry->offset,
140                                          res_entry->size, (void*)table);
141
142         if (ret != 0) {
143                 ERROR("Failed to read integrity table (size = %u, "
144                       " offset = %"PRIu64")",
145                       (unsigned)res_entry->size, res_entry->offset);
146                 goto out;
147         }
148
149         table->size        = le32_to_cpu(table->size);
150         table->num_entries = le32_to_cpu(table->num_entries);
151         table->chunk_size  = le32_to_cpu(table->chunk_size);
152
153         if (table->size != res_entry->size) {
154                 ERROR("Inconsistent integrity table sizes: Table header says "
155                       "%u bytes but resource entry says %u bytes",
156                       table->size, (unsigned)res_entry->size);
157                 ret = WIMLIB_ERR_INVALID_INTEGRITY_TABLE;
158                 goto out;
159         }
160
161         DEBUG("table->size = %u, table->num_entries = %u, "
162               "table->chunk_size = %u",
163               table->size, table->num_entries, table->chunk_size);
164
165         expected_size = (u64)table->num_entries * SHA1_HASH_SIZE + 12;
166
167         if (table->size != expected_size) {
168                 ERROR("Integrity table is %u bytes, but expected %"PRIu64" "
169                       "bytes to hold %u entries",
170                       table->size, expected_size, table->num_entries);
171                 ret = WIMLIB_ERR_INVALID_INTEGRITY_TABLE;
172                 goto out;
173         }
174
175         if (table->chunk_size == 0) {
176                 ERROR("Cannot use integrity chunk size of 0");
177                 ret = WIMLIB_ERR_INVALID_INTEGRITY_TABLE;
178                 goto out;
179         }
180
181         expected_num_entries = DIV_ROUND_UP(num_checked_bytes, table->chunk_size);
182
183         if (table->num_entries != expected_num_entries) {
184                 ERROR("%"PRIu64" integrity table entries would be required "
185                       "to checksum the %"PRIu64" bytes from the end of the "
186                       "header to the",
187                       expected_num_entries, num_checked_bytes);
188                 ERROR("end of the lookup table with a chunk size of %u, but "
189                       "there were only %u entries",
190                       table->chunk_size, table->num_entries);
191                 ret = WIMLIB_ERR_INVALID_INTEGRITY_TABLE;
192         }
193 out:
194         if (ret == 0)
195                 *table_ret = table;
196         else
197                 FREE(table);
198         return ret;
199 }
200
201 /*
202  * Calculates an integrity table for the data in a file beginning at offset 208
203  * (WIM_HEADER_DISK_SIZE).
204  *
205  * @fp:
206  *      FILE * for the file to be checked, opened for reading.  Does not need to
207  *      be at any specific location in the file.
208  *
209  * @new_check_end:
210  *      Offset of byte after the last byte to be checked.
211  *
212  * @old_table:
213  *      If non-NULL, a pointer to the table containing previously contained
214  *      integrity data for a prefix of this file.
215  *
216  * @old_check_end:
217  *      If @old_table is non-NULL, the byte after the last byte that was checked
218  *      in the old table.  Must be less than or equal to new_check_end.
219  *
220  * @progress_func:
221  *      If non-NULL, a progress function that will be called after every
222  *      calculated chunk.
223  *
224  * @integrity_table_ret:
225  *      On success, a pointer to the calculated integrity table is written into
226  *      this location.
227  *
228  * Returns 0 on success; nonzero on failure.
229  */
230 static int calculate_integrity_table(FILE *fp,
231                                      off_t new_check_end,
232                                      const struct integrity_table *old_table,
233                                      off_t old_check_end,
234                                      wimlib_progress_func_t progress_func,
235                                      struct integrity_table **integrity_table_ret)
236 {
237         int ret = 0;
238         size_t chunk_size = INTEGRITY_CHUNK_SIZE;
239
240         /* If an old table is provided, set the chunk size to be compatible with
241          * the old chunk size, unless the old chunk size was weird. */
242         if (old_table != NULL) {
243                 if (old_table->num_entries == 0 ||
244                     old_table->chunk_size < INTEGRITY_MIN_CHUNK_SIZE ||
245                     old_table->chunk_size > INTEGRITY_MAX_CHUNK_SIZE)
246                         old_table = NULL;
247                 else
248                         chunk_size = old_table->chunk_size;
249         }
250
251
252         u64 old_check_bytes = old_check_end - WIM_HEADER_DISK_SIZE;
253         u64 new_check_bytes = new_check_end - WIM_HEADER_DISK_SIZE;
254
255         u32 old_num_chunks = DIV_ROUND_UP(old_check_bytes, chunk_size);
256         u32 new_num_chunks = DIV_ROUND_UP(new_check_bytes, chunk_size);
257
258         size_t old_last_chunk_size = MODULO_NONZERO(old_check_bytes, chunk_size);
259         size_t new_last_chunk_size = MODULO_NONZERO(new_check_bytes, chunk_size);
260
261         size_t new_table_size = 12 + new_num_chunks * SHA1_HASH_SIZE;
262
263         struct integrity_table *new_table = MALLOC(new_table_size);
264         if (!new_table)
265                 return WIMLIB_ERR_NOMEM;
266         new_table->num_entries = new_num_chunks;
267         new_table->size = new_table_size;
268         new_table->chunk_size = chunk_size;
269
270         u64 offset = WIM_HEADER_DISK_SIZE;
271         union wimlib_progress_info progress;
272
273         if (progress_func) {
274                 progress.integrity.total_bytes      = new_check_bytes;
275                 progress.integrity.total_chunks     = new_num_chunks;
276                 progress.integrity.completed_chunks = 0;
277                 progress.integrity.completed_bytes  = 0;
278                 progress.integrity.chunk_size       = chunk_size;
279                 progress.integrity.filename         = NULL;
280                 progress_func(WIMLIB_PROGRESS_MSG_CALC_INTEGRITY,
281                               &progress);
282         }
283
284         for (u32 i = 0; i < new_num_chunks; i++) {
285                 size_t this_chunk_size;
286                 if (i == new_num_chunks - 1)
287                         this_chunk_size = new_last_chunk_size;
288                 else
289                         this_chunk_size = chunk_size;
290                 if (old_table &&
291                     ((this_chunk_size == chunk_size && i < old_num_chunks - 1) ||
292                       (i == old_num_chunks - 1 && this_chunk_size == old_last_chunk_size)))
293                 {
294                         /* Can use SHA1 message digest from old integrity table
295                          * */
296                         copy_hash(new_table->sha1sums[i], old_table->sha1sums[i]);
297                 } else {
298                         /* Calculate the SHA1 message digest of this chunk */
299                         ret = calculate_chunk_sha1(fp, this_chunk_size,
300                                                    offset, new_table->sha1sums[i]);
301                         if (ret != 0)
302                                 break;
303                 }
304                 offset += this_chunk_size;
305                 if (progress_func) {
306                         progress.integrity.completed_chunks++;
307                         progress.integrity.completed_bytes += this_chunk_size;
308                         progress_func(WIMLIB_PROGRESS_MSG_CALC_INTEGRITY,
309                                       &progress);
310                 }
311         }
312         if (ret == 0)
313                 *integrity_table_ret = new_table;
314         else
315                 FREE(new_table);
316         return ret;
317 }
318
319 /*
320  * Writes a WIM integrity table (a list of SHA1 message digests of raw 10 MiB
321  * chunks of the file).
322  *
323  * This function can optionally re-use entries from an older integrity table.
324  * To do this, make @integrity_res_entry point to the resource entry for the
325  * older table (note: this is an input-output parameter), and set
326  * @old_lookup_table_end to the offset of the byte directly following the last
327  * byte checked by the old table.  If the old integrity table is invalid or
328  * cannot be read, a warning is printed and the integrity information is
329  * re-calculated.
330  *
331  * @fp:
332  *      FILE * to the WIM file, opened read-write, positioned at the location at
333  *      which the integrity table is to be written.
334  *
335  * @integrity_res_entry:
336  *      Resource entry which will be set to point to the integrity table on
337  *      success.  In addition, if @old_lookup_table_end != 0, this initially
338  *      must point to the resource entry for the old integrity table for the
339  *      WIM.
340  *
341  * @new_lookup_table_end:
342  *      The offset of the byte directly following the lookup table in the WIM
343  *      being written.
344  *
345  * @old_lookup_table_end:
346  *      If nonzero, the offset of the byte directly following the old lookup
347  *      table in the WIM.
348  *
349  * @progress_func
350  *      If non-NULL, a progress function that will be called after every
351  *      calculated chunk.
352  *
353  * Returns:
354  *      0 on success, nonzero on failure.  The possible error codes are:
355  *         * WIMLIB_ERR_WRITE:  Could not write the integrity table.
356  *         * WIMLIB_ERR_READ:   Could not read a chunk of data that needed
357  *                              to be checked.
358  */
359 int write_integrity_table(FILE *fp,
360                           struct resource_entry *integrity_res_entry,
361                           off_t new_lookup_table_end,
362                           off_t old_lookup_table_end,
363                           wimlib_progress_func_t progress_func)
364 {
365         struct integrity_table *old_table;
366         struct integrity_table *new_table;
367         int ret;
368         off_t cur_offset;
369         u32 new_table_size;
370
371         wimlib_assert(old_lookup_table_end <= new_lookup_table_end);
372
373         cur_offset = ftello(fp);
374         if (cur_offset == -1)
375                 return WIMLIB_ERR_WRITE;
376
377         if (integrity_res_entry->offset == 0 || old_lookup_table_end == 0) {
378                 old_table = NULL;
379         } else {
380                 ret = read_integrity_table(integrity_res_entry, fp,
381                                            old_lookup_table_end - WIM_HEADER_DISK_SIZE,
382                                            &old_table);
383                 if (ret == WIMLIB_ERR_INVALID_INTEGRITY_TABLE) {
384                         WARNING("Old integrity table is invalid! "
385                                 "Ignoring it");
386                 } else if (ret != 0) {
387                         WARNING("Can't read old integrity table! "
388                                 "Ignoring it");
389                 }
390         }
391
392         ret = calculate_integrity_table(fp, new_lookup_table_end,
393                                         old_table, old_lookup_table_end,
394                                         progress_func, &new_table);
395         if (ret != 0)
396                 goto out_free_old_table;
397
398         new_table_size = new_table->size;
399
400         new_table->size        = cpu_to_le32(new_table->size);
401         new_table->num_entries = cpu_to_le32(new_table->num_entries);
402         new_table->chunk_size  = cpu_to_le32(new_table->chunk_size);
403
404         if (fseeko(fp, cur_offset, SEEK_SET) != 0) {
405                 ERROR_WITH_ERRNO("Failed to seek to byte %"PRIu64" of WIM to "
406                                  "write integrity table", cur_offset);
407                 ret = WIMLIB_ERR_WRITE;
408                 goto out_free_new_table;
409         }
410
411         if (fwrite(new_table, 1, new_table_size, fp) != new_table_size) {
412                 ERROR_WITH_ERRNO("Failed to write WIM integrity table");
413                 ret = WIMLIB_ERR_WRITE;
414         } else {
415                 integrity_res_entry->offset        = cur_offset;
416                 integrity_res_entry->size          = new_table_size;
417                 integrity_res_entry->original_size = new_table_size;
418                 integrity_res_entry->flags         = 0;
419                 ret = 0;
420         }
421 out_free_new_table:
422         FREE(new_table);
423 out_free_old_table:
424         FREE(old_table);
425         return ret;
426 }
427
428 /*
429  * Checks a WIM for consistency with the integrity table.
430  *
431  * @fp:
432  *      FILE * to the WIM file, opened for reading.
433  *
434  * @table:
435  *      The integrity table for the WIM, read into memory.
436  *
437  * @bytes_to_check:
438  *      Number of bytes in the WIM that need to be checked (offset of end of the
439  *      lookup table minus offset of end of the header).
440  *
441  * @progress_func
442  *      If non-NULL, a progress function that will be called after every
443  *      verified chunk.
444  *
445  * Returns:
446  *      > 0 (WIMLIB_ERR_*) on error
447  *      0 (WIM_INTEGRITY_OK) if the integrity was checked successfully and there
448  *      were no inconsistencies.
449  *      -1 (WIM_INTEGRITY_NOT_OK) if the WIM failed the integrity check.
450  */
451 static int verify_integrity(FILE *fp, const char *filename,
452                             const struct integrity_table *table,
453                             u64 bytes_to_check,
454                             wimlib_progress_func_t progress_func)
455 {
456         int ret;
457         u64 offset = WIM_HEADER_DISK_SIZE;
458         u8 sha1_md[SHA1_HASH_SIZE];
459         union wimlib_progress_info progress;
460
461         if (progress_func) {
462                 progress.integrity.total_bytes      = bytes_to_check;
463                 progress.integrity.total_chunks     = table->num_entries;
464                 progress.integrity.completed_chunks = 0;
465                 progress.integrity.completed_bytes  = 0;
466                 progress.integrity.chunk_size       = table->chunk_size;
467                 progress.integrity.filename         = filename;
468                 progress_func(WIMLIB_PROGRESS_MSG_VERIFY_INTEGRITY,
469                               &progress);
470         }
471         for (u32 i = 0; i < table->num_entries; i++) {
472                 size_t this_chunk_size;
473                 if (i == table->num_entries - 1)
474                         this_chunk_size = MODULO_NONZERO(bytes_to_check,
475                                                          table->chunk_size);
476                 else
477                         this_chunk_size = table->chunk_size;
478
479                 ret = calculate_chunk_sha1(fp, this_chunk_size, offset, sha1_md);
480                 if (ret != 0)
481                         return ret;
482
483                 if (!hashes_equal(sha1_md, table->sha1sums[i]))
484                         return WIM_INTEGRITY_NOT_OK;
485
486                 offset += this_chunk_size;
487                 if (progress_func) {
488                         progress.integrity.completed_chunks++;
489                         progress.integrity.completed_bytes += this_chunk_size;
490                         progress_func(WIMLIB_PROGRESS_MSG_VERIFY_INTEGRITY,
491                                       &progress);
492                 }
493         }
494         return WIM_INTEGRITY_OK;
495 }
496
497
498 /*
499  * Verifies the integrity of the WIM by making sure the SHA1 message digests of
500  * ~10 MiB chunks of the WIM match up with the values given in the integrity
501  * table.
502  *
503  * @w:
504  *      The WIM, opened for reading, and with the header already read.
505  *
506  * @progress_func
507  *      If non-NULL, a progress function that will be called after every
508  *      verified chunk.
509  *
510  * Returns:
511  *      > 0 (WIMLIB_ERR_*) on error
512  *      0 (WIM_INTEGRITY_OK) if the integrity was checked successfully and there
513  *      were no inconsistencies.
514  *      -1 (WIM_INTEGRITY_NOT_OK) if the WIM failed the integrity check.
515  *      -2 (WIM_INTEGRITY_NONEXISTENT) if the WIM contains no integrity
516  *      information.
517  */
518 int check_wim_integrity(WIMStruct *w, wimlib_progress_func_t progress_func)
519 {
520         int ret;
521         u64 bytes_to_check;
522         struct integrity_table *table;
523         u64 end_lookup_table_offset;
524
525         if (w->hdr.integrity.offset == 0) {
526                 DEBUG("No integrity information.");
527                 return WIM_INTEGRITY_NONEXISTENT;
528         }
529
530         end_lookup_table_offset = w->hdr.lookup_table_res_entry.offset +
531                                   w->hdr.lookup_table_res_entry.size;
532
533         if (end_lookup_table_offset < WIM_HEADER_DISK_SIZE) {
534                 ERROR("WIM lookup table ends before WIM header ends!");
535                 return WIMLIB_ERR_INVALID_INTEGRITY_TABLE;
536         }
537
538         bytes_to_check = end_lookup_table_offset - WIM_HEADER_DISK_SIZE;
539
540         ret = read_integrity_table(&w->hdr.integrity, w->fp,
541                                    bytes_to_check, &table);
542         if (ret != 0)
543                 return ret;
544         ret = verify_integrity(w->fp, w->filename, table,
545                                bytes_to_check, progress_func);
546         FREE(table);
547         return ret;
548 }