From 635bbec22163da21305d77a1ddbca9d531a5cefa Mon Sep 17 00:00:00 2001 From: EuAndreh Date: Tue, 16 Apr 2024 09:21:40 -0300 Subject: src/random.c: Add temporary buffer so we do not mess with "addr" --- src/random.c | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/src/random.c b/src/random.c index 8c3eda3..648ec9f 100644 --- a/src/random.c +++ b/src/random.c @@ -2,9 +2,9 @@ #include #include -#include #include #include +#include #include #include "logerr.h" @@ -12,25 +12,41 @@ #include "random.h" +/// A temporary buffer is used to avoid writing to `addr` while having an error +/// when calling `fclose(3)`; int urandom_bytes(const size_t n, uint8_t (*const addr)[]) { int rc = -1; + uint8_t *temp = NULL; FILE *f = NULL; + temp = malloc(n); + if (temp == NULL) { + logerr("malloc(...): %s\n", strerror(errno)); + goto out; + } + f = fopen("/dev/urandom", "r"); if (f == NULL) { logerr("fopen(...): %s\n", strerror(errno)); goto out; } - const size_t read_count = fread(addr, 1, n, f); + const size_t read_count = fread(temp, 1, n, f); if (ferror(f)) { logerr("fread(...), n, f): %s\n", strerror(errno)); goto out; } assert(read_count == n); + if (fclose(f)) { + logerr("fclose(...): %s\n", strerror(errno)); + goto out; + } + f = NULL; + + memcpy(addr, temp, n); rc = 0; out: if (f != NULL) { @@ -39,5 +55,8 @@ out: rc = -1; } } + if (temp != NULL) { + free(temp); + } return rc; } -- cgit v1.2.3