diff --git a/ent.c b/ent.c index fee4cd674..70e595a19 100644 --- a/ent.c +++ b/ent.c @@ -1,59 +1,58 @@ #include -/* 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) -#define _ENT_GETRANDOM + +#define _ENT_IMPL #define _GNU_SOURCE -#endif - -#if defined(ENT_URANDOM) -#define _ENT_URANDOM -#endif - -#include - -#if defined(_ENT_GETRANDOM) || defined(_ENT_URANDOM) - -#include -#include #include - -#if defined(_ENT_GETRANDOM) - #include -#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 #include #include #include +#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 + +#include + +#if defined(_ENT_IMPL) + +#include +#include + + int ent_getentropy(void* buf, size_t len) { char *cuf = buf; int ret; -#if defined(_ENT_URANDOM) - int fd; -#endif + ENT_DEFS; assert(len <= 256); if (!len) return 0; -#if defined(_ENT_URANDOM) - if ((fd = open("/dev/urandom", O_RDONLY)) < 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 - ) { + ENT_INIT(); + while (len && (ret = ENT_READ(cuf, len)) != 0) { if (ret < 0) { if (errno == EINTR) continue; @@ -62,9 +61,7 @@ ent_getentropy(void* buf, size_t len) len -= ret; cuf += ret; } -#if defined(_ENT_URANDOM) - (void) close(fd); -#endif + ENT_FINI(); if (!ret) { ret = -1; errno = EIO; @@ -72,4 +69,4 @@ ent_getentropy(void* buf, size_t len) return ret < 0 ? ret : 0; } -#endif /* _ENT_GETRANDOM || _ENT_URANDOM */ +#endif /* _ENT_IMPL */