Skip to content

Commit d11ff04

Browse files
hveghdpgeorge
authored andcommitted
unix/modos: Add support for uos.urandom(n).
Use getrandom function if available, otherwise read from /dev/urandom. Signed-off-by: [email protected]
1 parent 5ed7a74 commit d11ff04

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

ports/unix/modos.c

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727

2828
#include <sys/types.h>
2929
#include <sys/stat.h>
30+
#include <fcntl.h>
3031
#include <unistd.h>
3132
#include <errno.h>
3233
#include <stdio.h>
@@ -49,6 +50,29 @@
4950
#define USE_STATFS 1
5051
#endif
5152

53+
#if defined(__GLIBC__) && defined(__GLIBC_PREREQ)
54+
#if __GLIBC_PREREQ(2, 25)
55+
#include <sys/random.h>
56+
#define _HAVE_GETRANDOM
57+
#endif
58+
#endif
59+
60+
STATIC mp_obj_t mod_os_urandom(mp_obj_t num) {
61+
mp_int_t n = mp_obj_get_int(num);
62+
vstr_t vstr;
63+
vstr_init_len(&vstr, n);
64+
#ifdef _HAVE_GETRANDOM
65+
RAISE_ERRNO(getrandom(vstr.buf, n, 0), errno);
66+
#else
67+
int fd = open("/dev/urandom", O_RDONLY);
68+
RAISE_ERRNO(fd, errno);
69+
RAISE_ERRNO(read(fd, vstr.buf, n), errno);
70+
close(fd);
71+
#endif
72+
return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
73+
}
74+
STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_os_urandom_obj, mod_os_urandom);
75+
5276
STATIC mp_obj_t mod_os_stat(mp_obj_t path_in) {
5377
struct stat sb;
5478
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[] = {
309333
{ MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_uos) },
310334
{ MP_ROM_QSTR(MP_QSTR_errno), MP_ROM_PTR(&mod_os_errno_obj) },
311335
{ MP_ROM_QSTR(MP_QSTR_stat), MP_ROM_PTR(&mod_os_stat_obj) },
336+
{ MP_ROM_QSTR(MP_QSTR_urandom), MP_ROM_PTR(&mod_os_urandom_obj) },
312337
#if MICROPY_PY_OS_STATVFS
313338
{ MP_ROM_QSTR(MP_QSTR_statvfs), MP_ROM_PTR(&mod_os_statvfs_obj) },
314339
#endif

0 commit comments

Comments
 (0)