about summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/misc/getentropy.c31
1 files changed, 31 insertions, 0 deletions
diff --git a/src/misc/getentropy.c b/src/misc/getentropy.c
new file mode 100644
index 00000000..4c61ae26
--- /dev/null
+++ b/src/misc/getentropy.c
@@ -0,0 +1,31 @@
+#include <sys/random.h>
+#include <pthread.h>
+#include <errno.h>
+
+int getentropy(void *buffer, size_t len)
+{
+	int cs, ret;
+	char *pos = buffer;
+
+	if (len > 256) {
+		errno = EIO;
+		return -1;
+	}
+
+	pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cs);
+
+	while (len) {
+		ret = getrandom(pos, len, 0);
+		if (ret < 0) {
+			if (errno == EINTR) continue;
+			else break;
+		}
+		pos += ret;
+		len -= ret;
+		ret = 0;
+	}
+
+	pthread_setcancelstate(cs, 0);
+
+	return ret;
+}