#include "config.h" #include #include #include #include #include #include #include "logerr.h" #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(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) { if (fclose(f)) { logerr("fclose(...): %s\n", strerror(errno)); rc = -1; } } if (temp != NULL) { free(temp); } return rc; }