X-Git-Url: https://git.librecmc.org/?p=oweals%2Fopkg-lede.git;a=blobdiff_plain;f=libopkg%2Ffile_util.c;h=b867df76a2b0a23dc29a51c40a42f5b0f7ccec9a;hp=fad4178901f8f9aa47961d2131acfeaa27501830;hb=edf1b1964b565726a0b0f730b109e4491c7929b9;hpb=733d8409723a397b4ced39ea7aaab8bc8b4af5d9 diff --git a/libopkg/file_util.c b/libopkg/file_util.c index fad4178..b867df7 100644 --- a/libopkg/file_util.c +++ b/libopkg/file_util.c @@ -25,6 +25,10 @@ #include "libbb/libbb.h" #undef strlen +#if defined HAVE_SHA256 +#include "sha256.h" +#endif + int file_exists(const char *file_name) { int err; @@ -79,7 +83,7 @@ char *file_read_line_alloc(FILE *file) strcat(line, buf); } else { line_size = buf_len + 1; - line = strdup(buf); + line = xstrdup(buf); } if (buf[buf_len - 1] == '\n') { break; @@ -146,21 +150,24 @@ char *file_md5sum_alloc(const char *file_name) md5sum_hex = calloc(1, md5sum_hex_len + 1); if (md5sum_hex == NULL) { fprintf(stderr, "%s: out of memory\n", __FUNCTION__); - return strdup(""); + return NULL; } file = fopen(file_name, "r"); if (file == NULL) { fprintf(stderr, "%s: Failed to open file %s: %s\n", __FUNCTION__, file_name, strerror(errno)); - return strdup(""); + free(md5sum_hex); + return NULL; } err = md5_stream(file, md5sum_bin); if (err) { fprintf(stderr, "%s: ERROR computing md5sum for %s: %s\n", __FUNCTION__, file_name, strerror(err)); - return strdup(""); + fclose(file); + free(md5sum_hex); + return NULL; } fclose(file); @@ -175,3 +182,57 @@ char *file_md5sum_alloc(const char *file_name) return md5sum_hex; } +#ifdef HAVE_SHA256 +char *file_sha256sum_alloc(const char *file_name) +{ + static const int sha256sum_bin_len = 32; + static const int sha256sum_hex_len = 64; + + static const unsigned char bin2hex[16] = { + '0', '1', '2', '3', + '4', '5', '6', '7', + '8', '9', 'a', 'b', + 'c', 'd', 'e', 'f' + }; + + int i, err; + FILE *file; + char *sha256sum_hex; + unsigned char sha256sum_bin[sha256sum_bin_len]; + + sha256sum_hex = calloc(1, sha256sum_hex_len + 1); + if (sha256sum_hex == NULL) { + fprintf(stderr, "%s: out of memory\n", __FUNCTION__); + return NULL; + } + + file = fopen(file_name, "r"); + if (file == NULL) { + fprintf(stderr, "%s: Failed to open file %s: %s\n", + __FUNCTION__, file_name, strerror(errno)); + free(sha256sum_hex); + return NULL; + } + + err = sha256_stream(file, sha256sum_bin); + if (err) { + fprintf(stderr, "%s: ERROR computing sha256sum for %s: %s\n", + __FUNCTION__, file_name, strerror(err)); + fclose(file); + free(sha256sum_hex); + return NULL; + } + + fclose(file); + + for (i=0; i < sha256sum_bin_len; i++) { + sha256sum_hex[i*2] = bin2hex[sha256sum_bin[i] >> 4]; + sha256sum_hex[i*2+1] = bin2hex[sha256sum_bin[i] & 0xf]; + } + + sha256sum_hex[sha256sum_hex_len] = '\0'; + + return sha256sum_hex; +} + +#endif