[PATCH 0/3] Small improvements and fixes to urandom.
--- customize/urandom.ml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/customize/urandom.ml b/customize/urandom.ml index 3686f77d2..fd8cc8e8f 100644 --- a/customize/urandom.ml +++ b/customize/urandom.ml @@ -26,7 +26,7 @@ open Unix -let open_urandom_fd () = openfile "/dev/urandom" [O_RDONLY] 0 +let open_urandom_fd () = openfile "/dev/urandom" [O_RDONLY; O_CLOEXEC] 0 let read_byte fd = let b = Bytes.make 1 ' ' in -- 2.13.2
--- customize/urandom.ml | 26 ++++++++++++++------------ 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/customize/urandom.ml b/customize/urandom.ml index fd8cc8e8f..ff5d028d4 100644 --- a/customize/urandom.ml +++ b/customize/urandom.ml @@ -26,13 +26,12 @@ open Unix -let open_urandom_fd () = openfile "/dev/urandom" [O_RDONLY; O_CLOEXEC] 0 +open Std_utils let read_byte fd = let b = Bytes.make 1 ' ' in fun () -> if read fd b 0 1 = 0 then ( - close fd; raise End_of_file ); Char.code (Bytes.unsafe_get b 0) @@ -40,11 +39,12 @@ let read_byte fd = let urandom_bytes n = assert (n > 0); let ret = Bytes.make n ' ' in - let fd = open_urandom_fd () in - for i = 0 to n-1 do - Bytes.unsafe_set ret i (Char.chr (read_byte fd ())) - done; - close fd; + with_openfile "/dev/urandom" [O_RDONLY; O_CLOEXEC] 0 ( + fun fd -> + for i = 0 to n-1 do + Bytes.unsafe_set ret i (Char.chr (read_byte fd ())) + done + ); Bytes.to_string ret (* Return a random number uniformly distributed in [0, upper_bound) @@ -61,9 +61,11 @@ let urandom_uniform n chars = assert (nr_chars > 0); let ret = Bytes.make n ' ' in - let fd = open_urandom_fd () in - for i = 0 to n-1 do - Bytes.unsafe_set ret i (chars.[uniform_random (read_byte fd) nr_chars]) - done; - close fd; + with_openfile "/dev/urandom" [O_RDONLY; O_CLOEXEC] 0 ( + fun fd -> + for i = 0 to n-1 do + Bytes.unsafe_set ret i + (chars.[uniform_random (read_byte fd) nr_chars]) + done + ); Bytes.to_string ret -- 2.13.2
This is an unexpected error, so fail hard instead of leaking End_of_file exception. Nothing that calls into the Urandom module expects or handles End_of_file. --- customize/urandom.ml | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/customize/urandom.ml b/customize/urandom.ml index ff5d028d4..ce0e2cf65 100644 --- a/customize/urandom.ml +++ b/customize/urandom.ml @@ -27,13 +27,14 @@ open Unix open Std_utils +open Tools_utils +open Common_gettext.Gettext let read_byte fd = let b = Bytes.make 1 ' ' in fun () -> - if read fd b 0 1 = 0 then ( - raise End_of_file - ); + if read fd b 0 1 = 0 then + error (f_"unexpected end of file while reading /dev/urandom"); Char.code (Bytes.unsafe_get b 0) let urandom_bytes n = -- 2.13.2
participants (1)
-
Richard W.M. Jones