summaryrefslogtreecommitdiffstats
path: root/src/crypto/rand/rand_unix.go
diff options
context:
space:
mode:
authorDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-16 19:23:18 +0000
committerDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-16 19:23:18 +0000
commit43a123c1ae6613b3efeed291fa552ecd909d3acf (patch)
treefd92518b7024bc74031f78a1cf9e454b65e73665 /src/crypto/rand/rand_unix.go
parentInitial commit. (diff)
downloadgolang-1.20-43a123c1ae6613b3efeed291fa552ecd909d3acf.tar.xz
golang-1.20-43a123c1ae6613b3efeed291fa552ecd909d3acf.zip
Adding upstream version 1.20.14.upstream/1.20.14upstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'src/crypto/rand/rand_unix.go')
-rw-r--r--src/crypto/rand/rand_unix.go87
1 files changed, 87 insertions, 0 deletions
diff --git a/src/crypto/rand/rand_unix.go b/src/crypto/rand/rand_unix.go
new file mode 100644
index 0000000..40fce36
--- /dev/null
+++ b/src/crypto/rand/rand_unix.go
@@ -0,0 +1,87 @@
+// Copyright 2010 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+//go:build unix
+
+// Unix cryptographically secure pseudorandom number
+// generator.
+
+package rand
+
+import (
+ "crypto/internal/boring"
+ "errors"
+ "io"
+ "os"
+ "sync"
+ "sync/atomic"
+ "syscall"
+ "time"
+)
+
+const urandomDevice = "/dev/urandom"
+
+func init() {
+ if boring.Enabled {
+ Reader = boring.RandReader
+ return
+ }
+ Reader = &reader{}
+}
+
+// A reader satisfies reads by reading from urandomDevice
+type reader struct {
+ f io.Reader
+ mu sync.Mutex
+ used atomic.Uint32 // Atomic: 0 - never used, 1 - used, but f == nil, 2 - used, and f != nil
+}
+
+// altGetRandom if non-nil specifies an OS-specific function to get
+// urandom-style randomness.
+var altGetRandom func([]byte) (err error)
+
+func warnBlocked() {
+ println("crypto/rand: blocked for 60 seconds waiting to read random data from the kernel")
+}
+
+func (r *reader) Read(b []byte) (n int, err error) {
+ boring.Unreachable()
+ if r.used.CompareAndSwap(0, 1) {
+ // First use of randomness. Start timer to warn about
+ // being blocked on entropy not being available.
+ t := time.AfterFunc(time.Minute, warnBlocked)
+ defer t.Stop()
+ }
+ if altGetRandom != nil && altGetRandom(b) == nil {
+ return len(b), nil
+ }
+ if r.used.Load() != 2 {
+ r.mu.Lock()
+ if r.used.Load() != 2 {
+ f, err := os.Open(urandomDevice)
+ if err != nil {
+ r.mu.Unlock()
+ return 0, err
+ }
+ r.f = hideAgainReader{f}
+ r.used.Store(2)
+ }
+ r.mu.Unlock()
+ }
+ return io.ReadFull(r.f, b)
+}
+
+// hideAgainReader masks EAGAIN reads from /dev/urandom.
+// See golang.org/issue/9205
+type hideAgainReader struct {
+ r io.Reader
+}
+
+func (hr hideAgainReader) Read(p []byte) (n int, err error) {
+ n, err = hr.r.Read(p)
+ if errors.Is(err, syscall.EAGAIN) {
+ err = nil
+ }
+ return
+}