aboutsummaryrefslogtreecommitdiffstats
path: root/sum_fd.c
diff options
context:
space:
mode:
authorMattias Andrée <maandree@kth.se>2019-02-10 20:21:19 +0100
committerMattias Andrée <maandree@kth.se>2019-02-10 20:21:19 +0100
commited0296b9055713df0d910e4e7528ffe6fc539514 (patch)
tree8cbf8ecc9b6352257d6bc4946ff75cb8a4b484c0 /sum_fd.c
downloadlibsha1-ed0296b9055713df0d910e4e7528ffe6fc539514.tar.gz
libsha1-ed0296b9055713df0d910e4e7528ffe6fc539514.tar.bz2
libsha1-ed0296b9055713df0d910e4e7528ffe6fc539514.tar.xz
First commit
Signed-off-by: Mattias Andrée <maandree@kth.se>
Diffstat (limited to 'sum_fd.c')
-rw-r--r--sum_fd.c45
1 files changed, 45 insertions, 0 deletions
diff --git a/sum_fd.c b/sum_fd.c
new file mode 100644
index 0000000..bc2761d
--- /dev/null
+++ b/sum_fd.c
@@ -0,0 +1,45 @@
+/* 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
+libsha1_sum_fd(int fd, enum libsha1_algorithm algorithm, void *restrict hashsum)
+{
+ struct libsha1_state state;
+ ssize_t r;
+ struct stat attr;
+ size_t blksize = 4096;
+ char *restrict chunk;
+
+ if (libsha1_init(&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;
+ }
+ libsha1_update(&state, chunk, (size_t)r * 8);
+ }
+
+ libsha1_digest(&state, NULL, 0, hashsum);
+ return 0;
+}