diff options
author | Mattias Andrée <maandree@kth.se> | 2019-02-09 18:20:57 +0100 |
---|---|---|
committer | Mattias Andrée <maandree@kth.se> | 2019-02-09 18:20:57 +0100 |
commit | 242430d5e52cf8ee49dcd1701cf134e7454910c6 (patch) | |
tree | e3238ce604ffb0d80a4e122cd40d5807372f187f /sum_fd.c | |
parent | Merge pull request #2 from maaku/no-trailing-comma (diff) | |
download | libsha2-242430d5e52cf8ee49dcd1701cf134e7454910c6.tar.gz libsha2-242430d5e52cf8ee49dcd1701cf134e7454910c6.tar.bz2 libsha2-242430d5e52cf8ee49dcd1701cf134e7454910c6.tar.xz |
Change license to ISC and reorganise
Signed-off-by: Mattias Andrée <maandree@kth.se>
Diffstat (limited to 'sum_fd.c')
-rw-r--r-- | sum_fd.c | 46 |
1 files changed, 46 insertions, 0 deletions
diff --git a/sum_fd.c b/sum_fd.c new file mode 100644 index 0000000..381a634 --- /dev/null +++ b/sum_fd.c @@ -0,0 +1,46 @@ +/* See LICENSE file for copyright and license details. */ +#include "common.h" + + +/** + * Calculate the checksum for a file, + * the content of the file is assumed non-sensitive + * + * @param fd The file descriptor of the file + * @param algorithm The hashing algorithm + * @param hashsum Output buffer for the hash + * @return Zero on success, -1 on error + */ +int +libsha2_sum_fd(int fd, enum libsha2_algorithm algorithm, char *restrict hashsum) +{ + struct libsha2_state state; + ssize_t r; + struct stat attr; + size_t blksize = 4096; + char *restrict chunk; + + if (libsha2_state_initialise(&state, algorithm) < 0) + return -1; + + if (fstat(fd, &attr) == 0 && attr.st_blksize > 0) + blksize = (size_t)(attr.st_blksize); + + chunk = alloca(blksize); + + for (;;) { + r = read(fd, chunk, blksize); + if (r <= 0) { + if (!r) + break; + if (errno == EINTR) + continue; + return -1; + } + libsha2_update(&state, chunk, (size_t)r); + } + + libsha2_digest(&state, NULL, 0, hashsum); + return 0; +} + |