// 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.

// +build aix darwin dragonfly freebsd linux netbsd openbsd plan9 solaris

// Unix cryptographically secure pseudorandom number
// generator.

package rand

import (
	
	
	
	
	
	
	
	
	
	
)

const urandomDevice = "/dev/urandom"

// Easy implementation: read from /dev/urandom.
// This is sufficient on Linux, OS X, and FreeBSD.

func init() {
	if runtime.GOOS == "plan9" {
		Reader = newReader(nil)
	} else {
		Reader = &devReader{name: urandomDevice}
	}
}

// A devReader satisfies reads by reading the file named name.
type devReader struct {
	name string
	f    io.Reader
	mu   sync.Mutex
	used int32 // atomic; whether this devReader has been used
}

// altGetRandom if non-nil specifies an OS-specific function to get
// urandom-style randomness.
var altGetRandom func([]byte) (ok bool)

func warnBlocked() {
	println("crypto/rand: blocked for 60 seconds waiting to read random data from the kernel")
}

func ( *devReader) ( []byte) ( int,  error) {
	if atomic.CompareAndSwapInt32(&.used, 0, 1) {
		// First use of randomness. Start timer to warn about
		// being blocked on entropy not being available.
		 := time.AfterFunc(60*time.Second, warnBlocked)
		defer .Stop()
	}
	if altGetRandom != nil && .name == urandomDevice && altGetRandom() {
		return len(), nil
	}
	.mu.Lock()
	defer .mu.Unlock()
	if .f == nil {
		,  := os.Open(.name)
		if  == nil {
			return 0, 
		}
		if runtime.GOOS == "plan9" {
			.f = 
		} else {
			.f = bufio.NewReader(hideAgainReader{})
		}
	}
	return .f.Read()
}

var isEAGAIN func(error) bool // set by eagain.go on unix systems

// hideAgainReader masks EAGAIN reads from /dev/urandom.
// See golang.org/issue/9205
type hideAgainReader struct {
	r io.Reader
}

func ( hideAgainReader) ( []byte) ( int,  error) {
	,  = .r.Read()
	if  != nil && isEAGAIN != nil && isEAGAIN() {
		 = nil
	}
	return
}

// Alternate pseudo-random implementation for use on
// systems without a reliable /dev/urandom.

// newReader returns a new pseudorandom generator that
// seeds itself by reading from entropy. If entropy == nil,
// the generator seeds itself by reading from the system's
// random number generator, typically /dev/random.
// The Read method on the returned reader always returns
// the full amount asked for, or else it returns an error.
//
// The generator uses the X9.31 algorithm with AES-128,
// reseeding after every 1 MB of generated data.
func newReader( io.Reader) io.Reader {
	if  == nil {
		 = &devReader{name: "/dev/random"}
	}
	return &reader{entropy: }
}

type reader struct {
	mu                   sync.Mutex
	budget               int // number of bytes that can be generated
	cipher               cipher.Block
	entropy              io.Reader
	time, seed, dst, key [aes.BlockSize]byte
}

func ( *reader) ( []byte) ( int,  error) {
	.mu.Lock()
	defer .mu.Unlock()
	 = len()

	for len() > 0 {
		if .budget == 0 {
			,  := io.ReadFull(.entropy, .seed[0:])
			if  != nil {
				return  - len(), 
			}
			_,  = io.ReadFull(.entropy, .key[0:])
			if  != nil {
				return  - len(), 
			}
			.cipher,  = aes.NewCipher(.key[0:])
			if  != nil {
				return  - len(), 
			}
			.budget = 1 << 20 // reseed after generating 1MB
		}
		.budget -= aes.BlockSize

		// ANSI X9.31 (== X9.17) algorithm, but using AES in place of 3DES.
		//
		// single block:
		// t = encrypt(time)
		// dst = encrypt(t^seed)
		// seed = encrypt(t^dst)
		 := time.Now().UnixNano()
		binary.BigEndian.PutUint64(.time[:], uint64())
		.cipher.Encrypt(.time[0:], .time[0:])
		for  := 0;  < aes.BlockSize; ++ {
			.dst[] = .time[] ^ .seed[]
		}
		.cipher.Encrypt(.dst[0:], .dst[0:])
		for  := 0;  < aes.BlockSize; ++ {
			.seed[] = .time[] ^ .dst[]
		}
		.cipher.Encrypt(.seed[0:], .seed[0:])

		 := copy(, .dst[0:])
		 = [:]
	}

	return , nil
}