summaryrefslogtreecommitdiffstatshomepage
diff options
context:
space:
mode:
authorHenk Vergonet <henk.vergonet@gmail.com>2018-08-07 13:14:00 +0200
committerDamien George <damien@micropython.org>2021-11-17 12:59:38 +1100
commitd11ff0499fe52cfc9443aa6c0cb1620fd3dd1e70 (patch)
tree9ed8221a5f38ce6a0a2d9e0801139b9a865a2450
parent5ed7a748f0f767cdec9da95c289b934adaaecf67 (diff)
downloadmicropython-d11ff0499fe52cfc9443aa6c0cb1620fd3dd1e70.tar.gz
micropython-d11ff0499fe52cfc9443aa6c0cb1620fd3dd1e70.zip
unix/modos: Add support for uos.urandom(n).
Use getrandom function if available, otherwise read from /dev/urandom. Signed-off-by: Henk.Vergonet@gmail.com
-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 5e719c5736..24e5c95b18 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