File: random_urandom.go

package info (click to toggle)
golang-github-u-root-uio 0.0~git20240224.d2acac8-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental, forky, sid
  • size: 276 kB
  • sloc: sh: 25; makefile: 2
file content (60 lines) | stat: -rw-r--r-- 1,241 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// Copyright 2019 the u-root 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 aix || darwin || dragonfly || freebsd || nacl || netbsd || openbsd || solaris || linux
// +build aix darwin dragonfly freebsd nacl netbsd openbsd solaris linux

package rand

import (
	"context"
	"fmt"
	"sync"
	"syscall"

	"golang.org/x/sys/unix"
)

// urandomReader is a contextReader.
type urandomReader struct {
	once sync.Once

	// fd is expected to be non-blocking.
	fd int
}

func (r *urandomReader) init() error {
	var realErr error
	r.once.Do(func() {
		fd, err := unix.Open("/dev/urandom", unix.O_RDONLY, 0)
		if err != nil {
			realErr = fmt.Errorf("open(/dev/urandom): %v", err)
			return
		}
		r.fd = fd
	})
	return realErr
}

// ReadContext implements a cancelable read from /dev/urandom.
func (r *urandomReader) ReadContext(ctx context.Context, b []byte) (int, error) {
	if err := r.init(); err != nil {
		return 0, err
	}
	for {
		n, err := unix.Read(r.fd, b)
		if err == nil {
			return n, nil
		}
		select {
		case <-ctx.Done():
			return 0, ctx.Err()

		default:
			if err != syscall.EAGAIN && err != syscall.EINTR {
				return n, err
			}
		}
	}
}