diff --git a/include/meson.build b/include/meson.build index 996c9b9e3..bddb11f05 100644 --- a/include/meson.build +++ b/include/meson.build @@ -137,6 +137,7 @@ conf_data.set('HAVE_SYS_UTSNAME_H', cc.has_header('sys/utsname.h') ? '1' : false conf_data.set('HAVE_SYS_SYSMACROS_H', cc.has_header('sys/sysmacros.h') ? '1' : false) conf_data.set('HAVE_ARC4RANDOM_BUF', cc.has_function('arc4random_buf', dependencies: libbsd_dep) ? '1' : false) +conf_data.set('HAVE_GETRANDOM', cc.has_function('getrandom', prefix: '#include ') ? '1' : false) conf_data.set('HAVE_BACKTRACE', cc.has_function('backtrace') ? '1' : false) conf_data.set('HAVE_CBRT', cc.has_function('cbrt') ? '1' : false) conf_data.set('HAVE_EPOLL_CREATE1', cc.has_function('epoll_create1',dependencies:epoll_dep, prefix:'#include') ? '1' : false) diff --git a/os/auth.c b/os/auth.c index 71871ef40..1c4fc70d7 100644 --- a/os/auth.c +++ b/os/auth.c @@ -45,6 +45,9 @@ from The Open Group. #include #endif #include /* for arc4random_buf() */ +#ifdef HAVE_GETRANDOM +#include /* for getrandom() */ +#endif #include "os/auth.h" diff --git a/os/osdep.h b/os/osdep.h index 64f368431..c95b39226 100644 --- a/os/osdep.h +++ b/os/osdep.h @@ -88,12 +88,25 @@ extern Bool NewOutputPending; #ifndef HAVE_ARC4RANDOM_BUF static inline void arc4random_buf(void *buf, size_t nbytes) { + ssize_t ret; + int pos = 0; +#ifdef HAVE_GETRANDOM + while (pos < len) { + ret = getrandom(buf + pos, len - pos, 0); + if (ret <= 0) { + if (ret < 0 && errno == EINTR) + continue; + FatalError("Cannot read random data via getrandom(): %s\n", + strerror(errno)); + } + pos += ret; + } +#else int fd = open("/dev/urandom", O_RDONLY); if (fd < 0) FatalError("Cannot open /dev/urandom for random data generation\n"); - int pos = 0; while (pos < nbytes) { - int ret = read(fd, (unsigned char*)buf + pos, nbytes - pos); + ret = read(fd, (unsigned char*)buf + pos, nbytes - pos); if (ret <= 0) { if (ret < 0 && errno == EINTR) continue; @@ -103,6 +116,7 @@ static inline void arc4random_buf(void *buf, size_t nbytes) pos += ret; } close(fd); +#endif } #endif /* HAVE_ARC4RANDOM_BUF */