This commit is contained in:
Jōshin 2018-12-31 09:40:38 -08:00
parent 12ac12a795
commit d79967ef39

69
ent.c
View File

@ -1,59 +1,58 @@
#include <ent/config.h> #include <ent/config.h>
/* ent.h undefs these constants and config.h is #pragma once. */ /* ent.h undefs all constants and config.h is #pragma once. */
#if defined(ENT_GETRANDOM) #if defined(ENT_GETRANDOM)
#define _ENT_GETRANDOM
#define _ENT_IMPL
#define _GNU_SOURCE #define _GNU_SOURCE
#endif
#if defined(ENT_URANDOM)
#define _ENT_URANDOM
#endif
#include <ent/ent.h>
#if defined(_ENT_GETRANDOM) || defined(_ENT_URANDOM)
#include <assert.h>
#include <errno.h>
#include <unistd.h> #include <unistd.h>
#if defined(_ENT_GETRANDOM)
#include <sys/syscall.h> #include <sys/syscall.h>
#elif defined(_ENT_URANDOM) #define ENT_DEFS (void)0
#define ENT_INIT() (void)0
#define ENT_READ(B, L) sysall(SYS_getrandom, B, L, 0)
#define ENT_FINI() (void)0
#elif defined(ENT_URANDOM)
#define _ENT_IMPL
#include <unistd.h>
#include <sys/types.h> #include <sys/types.h>
#include <sys/stat.h> #include <sys/stat.h>
#include <fcntl.h> #include <fcntl.h>
#define ENT_DEFS int fd
#define ENT_INIT() do { \
if ((fd = open("/dev/urandom", O_RDONLY)) < 0) \
return -1; \
} while (0)
#define ENT_READ(B, L) read(fd, B, L)
#define ENT_FINI() (void) close(fd)
#endif #endif
#include <ent/ent.h>
#if defined(_ENT_IMPL)
#include <assert.h>
#include <errno.h>
int int
ent_getentropy(void* buf, size_t len) ent_getentropy(void* buf, size_t len)
{ {
char *cuf = buf; char *cuf = buf;
int ret; int ret;
#if defined(_ENT_URANDOM) ENT_DEFS;
int fd;
#endif
assert(len <= 256); assert(len <= 256);
if (!len) if (!len)
return 0; return 0;
#if defined(_ENT_URANDOM) ENT_INIT();
if ((fd = open("/dev/urandom", O_RDONLY)) < 0) while (len && (ret = ENT_READ(cuf, len)) != 0) {
return -1;
#endif
while (len &&
#if defined(_ENT_GETRANDOM)
(ret = syscall(SYS_getrandom, cuf, len, 0)) != 0
#elif defined(_ENT_URANDOM)
(ret = read(fd, cuf, len)) != 0
#endif
) {
if (ret < 0) { if (ret < 0) {
if (errno == EINTR) if (errno == EINTR)
continue; continue;
@ -62,9 +61,7 @@ ent_getentropy(void* buf, size_t len)
len -= ret; len -= ret;
cuf += ret; cuf += ret;
} }
#if defined(_ENT_URANDOM) ENT_FINI();
(void) close(fd);
#endif
if (!ret) { if (!ret) {
ret = -1; ret = -1;
errno = EIO; errno = EIO;
@ -72,4 +69,4 @@ ent_getentropy(void* buf, size_t len)
return ret < 0 ? ret : 0; return ret < 0 ? ret : 0;
} }
#endif /* _ENT_GETRANDOM || _ENT_URANDOM */ #endif /* _ENT_IMPL */