1 // Copyright 2018 Developers of the Rand project.
2 //
3 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4 // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5 // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
6 // option. This file may not be copied, modified, or distributed
7 // except according to those terms.
8 use crate::Error;
9 
10 extern crate std;
11 use std::thread_local;
12 
13 use js_sys::Uint8Array;
14 use wasm_bindgen::prelude::*;
15 
16 // Maximum is 65536 bytes see https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues
17 const BROWSER_CRYPTO_BUFFER_SIZE: usize = 256;
18 
19 enum RngSource {
20     Node(NodeCrypto),
21     Browser(BrowserCrypto, Uint8Array),
22 }
23 
24 // JsValues are always per-thread, so we initialize RngSource for each thread.
25 //   See: https://github.com/rustwasm/wasm-bindgen/pull/955
26 thread_local!(
27     static RNG_SOURCE: Result<RngSource, Error> = getrandom_init();
28 );
29 
getrandom_inner(dest: &mut [u8]) -> Result<(), Error>30 pub(crate) fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
31     RNG_SOURCE.with(|result| {
32         let source = result.as_ref().map_err(|&e| e)?;
33 
34         match source {
35             RngSource::Node(n) => {
36                 if n.random_fill_sync(dest).is_err() {
37                     return Err(Error::NODE_RANDOM_FILL_SYNC);
38                 }
39             }
40             RngSource::Browser(crypto, buf) => {
41                 // getRandomValues does not work with all types of WASM memory,
42                 // so we initially write to browser memory to avoid exceptions.
43                 for chunk in dest.chunks_mut(BROWSER_CRYPTO_BUFFER_SIZE) {
44                     // The chunk can be smaller than buf's length, so we call to
45                     // JS to create a smaller view of buf without allocation.
46                     let sub_buf = buf.subarray(0, chunk.len() as u32);
47 
48                     if crypto.get_random_values(&sub_buf).is_err() {
49                         return Err(Error::WEB_GET_RANDOM_VALUES);
50                     }
51                     sub_buf.copy_to(chunk);
52                 }
53             }
54         };
55         Ok(())
56     })
57 }
58 
getrandom_init() -> Result<RngSource, Error>59 fn getrandom_init() -> Result<RngSource, Error> {
60     if let Ok(self_) = Global::get_self() {
61         // If `self` is defined then we're in a browser somehow (main window
62         // or web worker). We get `self.crypto` (called `msCrypto` on IE), so we
63         // can call `crypto.getRandomValues`. If `crypto` isn't defined, we
64         // assume we're in an older web browser and the OS RNG isn't available.
65 
66         let crypto: BrowserCrypto = match (self_.crypto(), self_.ms_crypto()) {
67             (crypto, _) if !crypto.is_undefined() => crypto,
68             (_, crypto) if !crypto.is_undefined() => crypto,
69             _ => return Err(Error::WEB_CRYPTO),
70         };
71 
72         let buf = Uint8Array::new_with_length(BROWSER_CRYPTO_BUFFER_SIZE as u32);
73         return Ok(RngSource::Browser(crypto, buf));
74     }
75 
76     let crypto = MODULE.require("crypto").map_err(|_| Error::NODE_CRYPTO)?;
77     Ok(RngSource::Node(crypto))
78 }
79 
80 #[wasm_bindgen]
81 extern "C" {
82     type Global;
83     #[wasm_bindgen(getter, catch, static_method_of = Global, js_class = self, js_name = self)]
get_self() -> Result<Self_, JsValue>84     fn get_self() -> Result<Self_, JsValue>;
85 
86     type Self_;
87     #[wasm_bindgen(method, getter, js_name = "msCrypto")]
ms_crypto(me: &Self_) -> BrowserCrypto88     fn ms_crypto(me: &Self_) -> BrowserCrypto;
89     #[wasm_bindgen(method, getter)]
crypto(me: &Self_) -> BrowserCrypto90     fn crypto(me: &Self_) -> BrowserCrypto;
91 
92     type BrowserCrypto;
93     #[wasm_bindgen(method, js_name = getRandomValues, catch)]
get_random_values(me: &BrowserCrypto, buf: &Uint8Array) -> Result<(), JsValue>94     fn get_random_values(me: &BrowserCrypto, buf: &Uint8Array) -> Result<(), JsValue>;
95 
96     #[wasm_bindgen(js_name = module)]
97     static MODULE: NodeModule;
98 
99     type NodeModule;
100     #[wasm_bindgen(method, catch)]
require(this: &NodeModule, s: &str) -> Result<NodeCrypto, JsValue>101     fn require(this: &NodeModule, s: &str) -> Result<NodeCrypto, JsValue>;
102 
103     type NodeCrypto;
104     #[wasm_bindgen(method, js_name = randomFillSync, catch)]
random_fill_sync(crypto: &NodeCrypto, buf: &mut [u8]) -> Result<(), JsValue>105     fn random_fill_sync(crypto: &NodeCrypto, buf: &mut [u8]) -> Result<(), JsValue>;
106 }
107