inet.af/netstack@v0.0.0-20220214151720-7585b01ddccf/rand/rand_linux.go (about) 1 // Copyright 2018 The gVisor Authors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 // Package rand implements a cryptographically secure pseudorandom number 16 // generator. 17 package rand 18 19 import ( 20 "bufio" 21 "crypto/rand" 22 "io" 23 24 "golang.org/x/sys/unix" 25 "inet.af/netstack/sync" 26 ) 27 28 // reader implements an io.Reader that returns pseudorandom bytes. 29 type reader struct { 30 once sync.Once 31 useGetrandom bool 32 } 33 34 // Read implements io.Reader.Read. 35 func (r *reader) Read(p []byte) (int, error) { 36 r.once.Do(func() { 37 _, err := unix.Getrandom(p, 0) 38 if err != unix.ENOSYS { 39 r.useGetrandom = true 40 } 41 }) 42 43 if r.useGetrandom { 44 return unix.Getrandom(p, 0) 45 } 46 return rand.Read(p) 47 } 48 49 // bufferedReader implements a threadsafe buffered io.Reader. 50 type bufferedReader struct { 51 mu sync.Mutex 52 r *bufio.Reader 53 } 54 55 // Read implements io.Reader.Read. 56 func (b *bufferedReader) Read(p []byte) (int, error) { 57 b.mu.Lock() 58 n, err := b.r.Read(p) 59 b.mu.Unlock() 60 return n, err 61 } 62 63 // Reader is the default reader. 64 var Reader io.Reader = &bufferedReader{r: bufio.NewReader(&reader{})} 65 66 // Read reads from the default reader. 67 func Read(b []byte) (int, error) { 68 return io.ReadFull(Reader, b) 69 } 70 71 // Init can be called to make sure /dev/urandom is pre-opened on kernels that 72 // do not support getrandom(2). 73 func Init() error { 74 p := make([]byte, 1) 75 _, err := Read(p) 76 return err 77 }