random-util: add crypto_random_bytes_allocate_iovec()

Just a simple helper that allocates some memory, initializes it
randomly, and places this in a struct iovec.
This commit is contained in:
Lennart Poettering
2024-06-15 12:43:37 +01:00
committed by Luca Boccassi
parent 3b2e99ed8c
commit 4d6222b6a4
4 changed files with 23 additions and 13 deletions
+19
View File
@@ -21,6 +21,7 @@
#include "fd-util.h"
#include "fileio.h"
#include "io-util.h"
#include "iovec-util.h"
#include "missing_random.h"
#include "missing_syscall.h"
#include "missing_threads.h"
@@ -164,6 +165,24 @@ int crypto_random_bytes(void *p, size_t n) {
return loop_read_exact(fd, p, n, false);
}
int crypto_random_bytes_allocate_iovec(size_t n, struct iovec *ret) {
_cleanup_free_ void *p = NULL;
int r;
assert(ret);
p = malloc(MAX(n, 1U));
if (!p)
return -ENOMEM;
r = crypto_random_bytes(p, n);
if (r < 0)
return r;
*ret = IOVEC_MAKE(TAKE_PTR(p), n);
return 0;
}
size_t random_pool_size(void) {
_cleanup_free_ char *s = NULL;
int r;
+2
View File
@@ -4,9 +4,11 @@
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <sys/uio.h>
void random_bytes(void *p, size_t n); /* Returns random bytes suitable for most uses, but may be insecure sometimes. */
int crypto_random_bytes(void *p, size_t n); /* Returns secure random bytes after waiting for the RNG to initialize. */
int crypto_random_bytes_allocate_iovec(size_t n, struct iovec *ret);
static inline uint64_t random_u64(void) {
uint64_t u;