aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/libs/libc_compat/random
diff options
context:
space:
mode:
authorthegeorg <thegeorg@yandex-team.com>2022-07-27 10:14:03 +0300
committerthegeorg <thegeorg@yandex-team.com>2022-07-27 10:14:03 +0300
commitdda72e831a7b5f7cb932d99db79e2ee8d1a0d520 (patch)
treea4587f408ec33d67cca32cebc3a2170966550176 /contrib/libs/libc_compat/random
parent9762d6d10b478ec2dadd9d91e716738ea937e3a3 (diff)
downloadydb-dda72e831a7b5f7cb932d99db79e2ee8d1a0d520.tar.gz
Provide getrandom() and getentropy() by the means of contrib/libs/libc_compat
Diffstat (limited to 'contrib/libs/libc_compat/random')
-rw-r--r--contrib/libs/libc_compat/random/getentropy.c33
-rw-r--r--contrib/libs/libc_compat/random/getrandom.c7
-rw-r--r--contrib/libs/libc_compat/random/sys/random.h19
3 files changed, 59 insertions, 0 deletions
diff --git a/contrib/libs/libc_compat/random/getentropy.c b/contrib/libs/libc_compat/random/getentropy.c
new file mode 100644
index 0000000000..651ea95f14
--- /dev/null
+++ b/contrib/libs/libc_compat/random/getentropy.c
@@ -0,0 +1,33 @@
+#define _BSD_SOURCE
+#include <unistd.h>
+#include <sys/random.h>
+#include <pthread.h>
+#include <errno.h>
+
+int getentropy(void *buffer, size_t len)
+{
+ int cs, ret = 0;
+ 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;
+}
diff --git a/contrib/libs/libc_compat/random/getrandom.c b/contrib/libs/libc_compat/random/getrandom.c
new file mode 100644
index 0000000000..2184fad710
--- /dev/null
+++ b/contrib/libs/libc_compat/random/getrandom.c
@@ -0,0 +1,7 @@
+#include <sys/random.h>
+#include "syscall.h"
+
+ssize_t getrandom(void *buf, size_t buflen, unsigned flags)
+{
+ return syscall(SYS_getrandom, buf, buflen, flags);
+}
diff --git a/contrib/libs/libc_compat/random/sys/random.h b/contrib/libs/libc_compat/random/sys/random.h
new file mode 100644
index 0000000000..b5b1662c27
--- /dev/null
+++ b/contrib/libs/libc_compat/random/sys/random.h
@@ -0,0 +1,19 @@
+#pragma once
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <sys/types.h>
+
+#define SYS_getrandom 318
+
+#define GRND_NONBLOCK 0x0001
+#define GRND_RANDOM 0x0002
+#define GRND_INSECURE 0x0004
+
+ssize_t getrandom(void* buf, size_t buflen, unsigned int flags);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif