From c72bbb0a5ba526e9ae1806e672709d7e95f15709 Mon Sep 17 00:00:00 2001 From: Juan RP Date: Fri, 3 Apr 2009 12:10:28 +0200 Subject: [PATCH] Add func that returns a malloc'ed buffer with the hash string of a file. --HG-- extra : convert_revision : 66d886c413e0a909ccd678fe1ebdda44ab6fef8a --- include/util.h | 1 + lib/util.c | 38 ++++++++++++++++++++++++++------------ 2 files changed, 27 insertions(+), 12 deletions(-) diff --git a/include/util.h b/include/util.h index 894e454cee3..e932f062829 100644 --- a/include/util.h +++ b/include/util.h @@ -28,6 +28,7 @@ /* From lib/util.c */ char * xbps_append_full_path(bool, const char *, const char *); +char * xbps_get_file_hash(const char *); int xbps_check_file_hash(const char *, const char *); int xbps_check_pkg_file_hash(prop_dictionary_t, const char *); int xbps_check_is_installed_pkg(const char *); diff --git a/lib/util.c b/lib/util.c index 034f02851eb..38737196678 100644 --- a/lib/util.c +++ b/lib/util.c @@ -37,29 +37,43 @@ static const char *rootdir; static int flags; -int -xbps_check_file_hash(const char *path, const char *sha256) +char * +xbps_get_file_hash(const char *file) { SHA256_CTX ctx; - const char *res; + char *hash; uint8_t buf[BUFSIZ * 20], digest[SHA256_DIGEST_LENGTH * 2 + 1]; ssize_t bytes; - int fd, rv = 0; + int fd; - if ((fd = open(path, O_RDONLY)) == -1) - return errno; + if ((fd = open(file, O_RDONLY)) == -1) + return NULL; SHA256_Init(&ctx); while ((bytes = read(fd, buf, sizeof(buf))) > 0) SHA256_Update(&ctx, buf, (size_t)bytes); - res = SHA256_End(&ctx, digest); - - if (strcmp(sha256, res)) - rv = ERANGE; - + hash = strdup(SHA256_End(&ctx, digest)); (void)close(fd); - return rv; + return hash; +} + +int +xbps_check_file_hash(const char *path, const char *sha256) +{ + char *res; + + res = xbps_get_file_hash(path); + if (res == NULL) + return errno; + + if (strcmp(sha256, res)) { + free(res); + return ERANGE; + } + free(res); + + return 0; } int