summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorEuAndreh <eu@euandre.org>2024-04-16 09:21:40 -0300
committerEuAndreh <eu@euandre.org>2024-04-16 09:21:40 -0300
commit635bbec22163da21305d77a1ddbca9d531a5cefa (patch)
tree5c5313eb4a1265a0b8139f835286cdc89ef3e4ec
parentOrganaze imports (diff)
downloadpindaiba-635bbec22163da21305d77a1ddbca9d531a5cefa.tar.gz
pindaiba-635bbec22163da21305d77a1ddbca9d531a5cefa.tar.xz
src/random.c: Add temporary buffer so we do not mess with "addr"
-rw-r--r--src/random.c23
1 files 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 <assert.h>
#include <errno.h>
-#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
+#include <stdlib.h>
#include <string.h>
#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;
}