More robust read loop

This commit is contained in:
Jōshin 2018-12-27 11:06:22 -08:00
parent f1b44b42a9
commit 30390fa180

27
ent.c
View File

@ -1,6 +1,7 @@
#include <ent/ent.h>
#if defined(ENT_USE_URANDOM)
#if defined(ENT_URANDOM)
#include <assert.h>
#include <fcntl.h>
#include <sys/types.h>
@ -8,20 +9,30 @@
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;
}
close(fd);
return 0;
len -= ret;
buf += ret;
}
(void) close(fd);
if (ret == 0) {
ret = -1;
errno = EIO;
}
return ret < 0 ? ret : 0;
}
#endif /* ENT_USE_URANDOM */