summaryrefslogtreecommitdiff
path: root/src/shared
diff options
context:
space:
mode:
Diffstat (limited to 'src/shared')
-rw-r--r--src/shared/missing.h15
-rw-r--r--src/shared/util.c25
2 files changed, 39 insertions, 1 deletions
diff --git a/src/shared/missing.h b/src/shared/missing.h
index bb4f8f23a8..5b87e23eec 100644
--- a/src/shared/missing.h
+++ b/src/shared/missing.h
@@ -140,6 +140,21 @@ static inline int memfd_create(const char *name, unsigned int flags) {
}
#endif
+#ifndef __NR_getrandom
+# if defined __x86_64__
+# define __NR_getrandom 278
+# else
+# warning "__NR_getrandom unknown for your architecture"
+# define __NR_getrandom 0xffffffff
+# endif
+#endif
+
+#if !HAVE_DECL_GETRANDOM
+static inline int getrandom(void *buffer, size_t count, unsigned flags) {
+ return syscall(__NR_getrandom, buffer, count, flags);
+}
+#endif
+
#ifndef BTRFS_IOCTL_MAGIC
#define BTRFS_IOCTL_MAGIC 0x94
#endif
diff --git a/src/shared/util.c b/src/shared/util.c
index 4143f6d643..ceafba86af 100644
--- a/src/shared/util.c
+++ b/src/shared/util.c
@@ -2466,14 +2466,37 @@ char* dirname_malloc(const char *path) {
}
int dev_urandom(void *p, size_t n) {
- _cleanup_close_ int fd;
+ static int have_syscall = -1;
+ int r, fd;
ssize_t k;
+ /* Use the syscall unless we know we don't have it, or when
+ * the requested size is too large for it. */
+ if (have_syscall != 0 || (size_t) (int) n != n) {
+ r = getrandom(p, n, 0);
+ if (r == (int) n) {
+ have_syscall = true;
+ return 0;
+ }
+
+ if (r < 0) {
+ if (errno == ENOSYS)
+ /* we lack the syscall, continue with reading from /dev/urandom */
+ have_syscall = false;
+ else
+ return -errno;
+ } else
+ /* too short read? */
+ return -EIO;
+ }
+
fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
if (fd < 0)
return errno == ENOENT ? -ENOSYS : -errno;
k = loop_read(fd, p, n, true);
+ safe_close(fd);
+
if (k < 0)
return (int) k;
if ((size_t) k != n)