summaryrefslogtreecommitdiff
path: root/src/random.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/random.c')
-rw-r--r--src/random.c109
1 files changed, 16 insertions, 93 deletions
diff --git a/src/random.c b/src/random.c
index b409e6a..0382b3e 100644
--- a/src/random.c
+++ b/src/random.c
@@ -1,141 +1,64 @@
-#include "config.h"
+#include <s.h>
#include <assert.h>
#include <errno.h>
-#include <stdint.h>
#include <stdio.h>
-#include <stdlib.h>
#include <string.h>
#include "logerr.h"
-#include "util.h"
#include "random.h"
-struct Random {
- FILE *const file_handle;
-};
+static FILE *
+FRANDOM = NULL;
int
-urandom_bytes(const size_t n, uint8_t (*const addr)[]) {
+random_init(void) {
int rc = -1;
- uint8_t *ret = NULL;
- FILE *f = NULL;
-
- ret = malloc(n);
- if (ret == NULL) {
- logerr("malloc(): %s", strerror(errno));
- goto out;
- }
-
- f = fopen("/dev/urandom", "r");
- if (f == NULL) {
+ FRANDOM = fopen("/dev/urandom", "r");
+ if (FRANDOM == NULL) {
logerr("fopen(): %s", strerror(errno));
goto out;
}
- const size_t read_count = fread(ret, 1U, n, f);
- if (ferror(f)) {
- logerr("fread(): %s", strerror(errno));
- goto out;
- }
- assert(read_count == n);
-
- if (fclose(f)) {
- logerr("fclose(): %s", strerror(errno));
- goto out;
- }
- f = NULL;
-
- memcpy(addr, ret, n);
rc = 0;
out:
- if (f != NULL) {
- if (fclose(f)) {
- logerr("fclose(): %s", strerror(errno));
- rc = -1;
- }
- }
- if (ret != NULL) {
- freeit((void *)&ret);
- }
return rc;
}
int
-random_generate(
- const struct Random *const r,
- const size_t length,
- uint8_t (*const out)[]
-) {
+random_end(void) {
int rc = -1;
- const size_t read_count = fread(out, 1U, length, r->file_handle);
- if (ferror(r->file_handle)) {
- logerr("fread(): %s", strerror(errno));
+ if (fclose(FRANDOM)) {
+ logerr("fclose(): %s", strerror(errno));
goto out;
}
- assert(read_count == length);
rc = 0;
out:
+ FRANDOM = NULL;
return rc;
}
int
-random_new(const struct Random **const out) {
+random_bytes(const size_t length, u8 (*const out)[]) {
int rc = -1;
- const struct Random *ret = NULL;
- FILE *f = NULL;
-
- ret = malloc(sizeof(*ret));
- if (ret == NULL) {
- logerr("malloc(): %s", strerror(errno));
- goto out;
- }
-
- f = fopen("/dev/urandom", "r");
- if (f == NULL) {
- logerr("fopen(): %s", strerror(errno));
- goto out;
- }
-
- memcpy((void *)ret, &(struct Random) {
- .file_handle = f,
- }, sizeof(*ret));
- *out = ret;
- rc = 0;
-out:
- if (rc) {
- random_free(&ret);
- }
- return rc;
-}
-
-int
-random_free(const struct Random **const r) {
- if (r == NULL) {
- return 0;
- }
-
- if (*r == NULL) {
- return 0;
- }
-
- int rc = -1;
- if (fclose((*r)->file_handle)) {
- logerr("fclose(): %s", strerror(errno));
+ assert(FRANDOM != NULL);
+ const size_t read_count = fread(out, 1U, length, FRANDOM);
+ if (ferror(FRANDOM)) {
+ logerr("fread(): %s", strerror(errno));
goto out;
}
+ assert(read_count == length);
rc = 0;
out:
- freeit((void *)r);
return rc;
}