csum-file: introduce checksum_valid()
Introduce a new function which checks the validity of a file's trailing checksum. This is similar to hashfd_check(), but different since it is intended to be used by callers who aren't writing the same data (like `git index-pack --verify`), but who instead want to validate the integrity of data that they are reading. Rewrite the first of two callers which could benefit from this new function in pack-check.c. Subsequent callers will be added in the following patches. Helped-by: Jeff King <peff@peff.net> Signed-off-by: Jeff King <peff@peff.net> Signed-off-by: Taylor Blau <me@ttaylorr.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>
Taylor Blau committed
Jun 23, 2021 at 14:39 UTC
f9221e2cf5049805d9151b3db6a5eef07b1cc92e
3 files changed
+20
-10
csum-file.c
+16
@@ -187,3 +187,19 @@ uint32_t crc32_end(struct hashfile *f)
187
f->do_crc = 0;
188
return f->crc32;
189
}
190
+
191
+int hashfile_checksum_valid(const unsigned char *data, size_t total_len)
192
+{
193
+ unsigned char got[GIT_MAX_RAWSZ];
194
+ git_hash_ctx ctx;
195
+ size_t data_len = total_len - the_hash_algo->rawsz;
196
+
197
+ if (total_len < the_hash_algo->rawsz)
198
+ return 0; /* say "too short"? */
199
+
200
+ the_hash_algo->init_fn(&ctx);
201
+ the_hash_algo->update_fn(&ctx, data, data_len);
202
+ the_hash_algo->final_fn(got, &ctx);
203
+
204
+ return hasheq(got, data + data_len);
205
+}
csum-file.h
+3
@@ -42,6 +42,9 @@ void hashflush(struct hashfile *f);
42
void crc32_begin(struct hashfile *);
43
uint32_t crc32_end(struct hashfile *);
44
45
+/* Verify checksum validity while reading. Returns non-zero on success. */
46
+int hashfile_checksum_valid(const unsigned char *data, size_t len);
47
+
48
/*
49
* Returns the total number of bytes fed to the hashfile so far (including ones
50
* that have not been written out to the descriptor yet).
pack-check.c
+1
-10
@@ -164,22 +164,13 @@ static int verify_packfile(struct repository *r,
164
165
int verify_pack_index(struct packed_git *p)
166
{
167
- size_t len;
168
- const unsigned char *index_base;
169
- git_hash_ctx ctx;
170
- unsigned char hash[GIT_MAX_RAWSZ];
167
int err = 0;
168
169
if (open_pack_index(p))
170
return error("packfile %s index not opened", p->pack_name);
175
- index_base = p->index_data;
176
- len = p->index_size - the_hash_algo->rawsz;
171
172
/* Verify SHA1 sum of the index file */
179
- the_hash_algo->init_fn(&ctx);
180
- the_hash_algo->update_fn(&ctx, index_base, len);
181
- the_hash_algo->final_fn(hash, &ctx);
182
- if (!hasheq(hash, index_base + len))
173
+ if (!hashfile_checksum_valid(p->index_data, p->index_size))
174
err = error("Packfile index for %s hash mismatch",
175
p->pack_name);
176
return err;