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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
|
/*
* Reader of /dev/random and company
* (C) 1999-2009,2013 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include <botan/internal/dev_random.h>
#include <sys/types.h>
#include <sys/select.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
namespace Botan {
/**
Device_EntropySource constructor
Open a file descriptor to each (available) device in fsnames
*/
Device_EntropySource::Device_EntropySource(const std::vector<std::string>& fsnames)
{
#ifndef O_NONBLOCK
#define O_NONBLOCK 0
#endif
#ifndef O_NOCTTY
#define O_NOCTTY 0
#endif
const int flags = O_RDONLY | O_NONBLOCK | O_NOCTTY;
for(auto fsname : fsnames)
{
fd_type fd = ::open(fsname.c_str(), flags);
if(fd >= 0 && fd < FD_SETSIZE)
m_devices.push_back(fd);
else if(fd >= 0)
::close(fd);
}
}
/**
Device_EntropySource destructor: close all open devices
*/
Device_EntropySource::~Device_EntropySource()
{
for(size_t i = 0; i != m_devices.size(); ++i)
::close(m_devices[i]);
}
/**
* Gather entropy from a RNG device
*/
void Device_EntropySource::poll(Entropy_Accumulator& accum)
{
if(m_devices.empty())
return;
fd_type max_fd = m_devices[0];
fd_set read_set;
FD_ZERO(&read_set);
for(size_t i = 0; i != m_devices.size(); ++i)
{
FD_SET(m_devices[i], &read_set);
max_fd = std::max(m_devices[i], max_fd);
}
struct ::timeval timeout;
timeout.tv_sec = (BOTAN_SYSTEM_RNG_POLL_TIMEOUT_MS / 1000);
timeout.tv_usec = (BOTAN_SYSTEM_RNG_POLL_TIMEOUT_MS % 1000) * 1000;
if(::select(max_fd + 1, &read_set, nullptr, nullptr, &timeout) < 0)
return;
secure_vector<byte>& buf = accum.get_io_buf(BOTAN_SYSTEM_RNG_POLL_REQUEST);
for(size_t i = 0; i != m_devices.size(); ++i)
{
if(FD_ISSET(m_devices[i], &read_set))
{
const ssize_t got = ::read(m_devices[i], buf.data(), buf.size());
if(got > 0)
accum.add(buf.data(), got, BOTAN_ENTROPY_ESTIMATE_STRONG_RNG);
}
}
}
}
|