Initial commit
authorJames Bunton <jamesbunton@delx.net.au>
Fri, 25 Aug 2017 05:25:11 +0000 (15:25 +1000)
committerJames Bunton <jamesbunton@delx.net.au>
Fri, 25 Aug 2017 05:36:17 +0000 (15:36 +1000)
.gitignore [new file with mode: 0644]
Makefile [new file with mode: 0644]
README.md [new file with mode: 0644]
getrandom.c [new file with mode: 0644]

diff --git a/.gitignore b/.gitignore
new file mode 100644 (file)
index 0000000..323b106
--- /dev/null
@@ -0,0 +1 @@
+getrandom.so
diff --git a/Makefile b/Makefile
new file mode 100644 (file)
index 0000000..e1a68c3
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,9 @@
+.PHONY: all clean
+
+all: getrandom.so
+
+clean:
+       rm -f getrandom.so
+
+getrandom.so: getrandom.c
+       $(CC) -Wall -Wextra -shared $< -o $@
diff --git a/README.md b/README.md
new file mode 100644 (file)
index 0000000..7043397
--- /dev/null
+++ b/README.md
@@ -0,0 +1,16 @@
+# linux-getrandom-userspace
+
+## Overview
+
+Since Linux 3.17 there is a system call `getrandom()`. This was added to glibc 2.25.
+
+This library can be used with `LD_PRELOAD` if you're using Linux 3.16 or earlier and need to run an application which requires `getrandom()`.
+
+See [LWN's The long road to getrandom() in glibc](https://lwn.net/Articles/711013/) for more information.
+
+## Usage
+
+```
+make
+LD_PRELOAD="${PWD}/getrandom.so" mail
+```
diff --git a/getrandom.c b/getrandom.c
new file mode 100644 (file)
index 0000000..765294f
--- /dev/null
@@ -0,0 +1,20 @@
+#include <fcntl.h>
+#include <unistd.h>
+#include <sys/random.h>
+
+ssize_t getrandom(void *buf, size_t buflen, unsigned int flags) {
+    char* filename = flags & GRND_RANDOM ? "/dev/random" : "/dev/urandom";
+    int nonblock = flags & GRND_NONBLOCK ? O_NONBLOCK : 0;
+    int oflags = O_CLOEXEC | nonblock;
+
+    int fd = open(filename, oflags);
+    if (fd < 0) {
+        return -1;
+    }
+
+    ssize_t bytes = read(fd, buf, buflen);
+
+    close(fd);
+
+    return bytes;
+}