Add func that returns a malloc'ed buffer with the hash string of a file.

--HG--
extra : convert_revision : 66d886c413e0a909ccd678fe1ebdda44ab6fef8a
This commit is contained in:
Juan RP 2009-04-03 12:10:28 +02:00
parent cb21ca090c
commit c72bbb0a5b
2 changed files with 27 additions and 12 deletions

View File

@ -28,6 +28,7 @@
/* From lib/util.c */ /* From lib/util.c */
char * xbps_append_full_path(bool, const char *, const char *); 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_file_hash(const char *, const char *);
int xbps_check_pkg_file_hash(prop_dictionary_t, const char *); int xbps_check_pkg_file_hash(prop_dictionary_t, const char *);
int xbps_check_is_installed_pkg(const char *); int xbps_check_is_installed_pkg(const char *);

View File

@ -37,29 +37,43 @@
static const char *rootdir; static const char *rootdir;
static int flags; static int flags;
int char *
xbps_check_file_hash(const char *path, const char *sha256) xbps_get_file_hash(const char *file)
{ {
SHA256_CTX ctx; SHA256_CTX ctx;
const char *res; char *hash;
uint8_t buf[BUFSIZ * 20], digest[SHA256_DIGEST_LENGTH * 2 + 1]; uint8_t buf[BUFSIZ * 20], digest[SHA256_DIGEST_LENGTH * 2 + 1];
ssize_t bytes; ssize_t bytes;
int fd, rv = 0; int fd;
if ((fd = open(path, O_RDONLY)) == -1) if ((fd = open(file, O_RDONLY)) == -1)
return errno; return NULL;
SHA256_Init(&ctx); SHA256_Init(&ctx);
while ((bytes = read(fd, buf, sizeof(buf))) > 0) while ((bytes = read(fd, buf, sizeof(buf))) > 0)
SHA256_Update(&ctx, buf, (size_t)bytes); SHA256_Update(&ctx, buf, (size_t)bytes);
res = SHA256_End(&ctx, digest); hash = strdup(SHA256_End(&ctx, digest));
if (strcmp(sha256, res))
rv = ERANGE;
(void)close(fd); (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 int