patch 9.1.0518: initialize the random buffer can be improved
Problem: initialize the random buffer can be improved
Solution: refactor init_srand() function, move machine-specific parts to
os_mswin and os_unix, implement a fallback for Windows 10 and
later (LemonBoy)
closes: #15125
Signed-off-by: LemonBoy <thatlemon@gmail.com>
Signed-off-by: Christian Brabandt <cb@256bit.org>
diff --git a/src/os_unix.c b/src/os_unix.c
index d155142..b7da552 100644
--- a/src/os_unix.c
+++ b/src/os_unix.c
@@ -7722,6 +7722,34 @@
}
#endif // FEAT_SYSMOUSE
+/*
+ * Fill the buffer 'buf' with 'len' random bytes.
+ * Returns FAIL if the OS PRNG is not available or something went wrong.
+ */
+ int
+mch_get_random(char_u *buf, int len)
+{
+ static int dev_urandom_state = NOTDONE;
+
+ if (dev_urandom_state == FAIL)
+ return FAIL;
+
+ int fd = open("/dev/urandom", O_RDONLY);
+
+ // Attempt reading /dev/urandom.
+ if (fd == -1)
+ dev_urandom_state = FAIL;
+ else if (read(fd, buf, len) == len)
+ dev_urandom_state = OK;
+ else
+ {
+ dev_urandom_state = FAIL;
+ close(fd);
+ }
+
+ return dev_urandom_state;
+}
+
#if defined(FEAT_LIBCALL) || defined(PROTO)
typedef char_u * (*STRPROCSTR)(char_u *);
typedef char_u * (*INTPROCSTR)(int);