summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--ports/unix/modos.c25
1 files changed, 25 insertions, 0 deletions
diff --git a/ports/unix/modos.c b/ports/unix/modos.c
index 5e719c573..24e5c95b1 100644
--- a/ports/unix/modos.c
+++ b/ports/unix/modos.c
@@ -27,6 +27,7 @@
#include <sys/types.h>
#include <sys/stat.h>
+#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <stdio.h>
@@ -49,6 +50,29 @@
#define USE_STATFS 1
#endif
+#if defined(__GLIBC__) && defined(__GLIBC_PREREQ)
+#if __GLIBC_PREREQ(2, 25)
+#include <sys/random.h>
+#define _HAVE_GETRANDOM
+#endif
+#endif
+
+STATIC mp_obj_t mod_os_urandom(mp_obj_t num) {
+ mp_int_t n = mp_obj_get_int(num);
+ vstr_t vstr;
+ vstr_init_len(&vstr, n);
+ #ifdef _HAVE_GETRANDOM
+ RAISE_ERRNO(getrandom(vstr.buf, n, 0), errno);
+ #else
+ int fd = open("/dev/urandom", O_RDONLY);
+ RAISE_ERRNO(fd, errno);
+ RAISE_ERRNO(read(fd, vstr.buf, n), errno);
+ close(fd);
+ #endif
+ return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
+}
+STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_os_urandom_obj, mod_os_urandom);
+
STATIC mp_obj_t mod_os_stat(mp_obj_t path_in) {
struct stat sb;
const char *path = mp_obj_str_get_str(path_in);
@@ -309,6 +333,7 @@ STATIC const mp_rom_map_elem_t mp_module_os_globals_table[] = {
{ MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_uos) },
{ MP_ROM_QSTR(MP_QSTR_errno), MP_ROM_PTR(&mod_os_errno_obj) },
{ MP_ROM_QSTR(MP_QSTR_stat), MP_ROM_PTR(&mod_os_stat_obj) },
+ { MP_ROM_QSTR(MP_QSTR_urandom), MP_ROM_PTR(&mod_os_urandom_obj) },
#if MICROPY_PY_OS_STATVFS
{ MP_ROM_QSTR(MP_QSTR_statvfs), MP_ROM_PTR(&mod_os_statvfs_obj) },
#endif