From 30390fa180f9f3502086ed851393482b64421e8e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C5=8Dshin?= Date: Thu, 27 Dec 2018 11:06:22 -0800 Subject: [PATCH] More robust read loop --- ent.c | 35 +++++++++++++++++++++++------------ 1 file changed, 23 insertions(+), 12 deletions(-) diff --git a/ent.c b/ent.c index 7ac88b286..522960bca 100644 --- a/ent.c +++ b/ent.c @@ -1,27 +1,38 @@ #include -#if defined(ENT_USE_URANDOM) -# include -# include -# include -# include +#if defined(ENT_URANDOM) + +#include +#include +#include +#include int -ent_getentropy(void* buf, size_t buflen) +ent_getentropy(void* buf, size_t len) { int fd; + ssize_t ret; - assert(buflen <= 256); + assert(len <= 256); if (-1 == (fd = open("/dev/urandom", O_RDONLY))) { return -1; } - if (buflen != read(fd, buf, buflen)) { - (void) close(fd); - return -1; + while (len != 0 && (ret = read(fd, buf, len)) != 0) { + if (ret == -1) { + if (errno == EINTR) + continue; + break; + } + len -= ret; + buf += ret; } - close(fd); - return 0; + (void) close(fd); + if (ret == 0) { + ret = -1; + errno = EIO; + } + return ret < 0 ? ret : 0; } #endif /* ENT_USE_URANDOM */