libcruft-util/rand/system_linux.cpp

63 lines
1.4 KiB
C++
Raw Normal View History

/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Copyright 2019 Danny Robson <danny@nerdcruft.net>
*/
#include "system_linux.hpp"
#include "../posix/except.hpp"
#include "../io.hpp"
#include <sys/ioctl.h>
#include <linux/random.h>
using cruft::rand::linux::device;
///////////////////////////////////////////////////////////////////////////////
static std::string const& default_source (void)
{
static std::string const s_path = "/dev/urandom";
return s_path;
}
//-----------------------------------------------------------------------------
device::device ():
device (default_source ())
{ ; }
//-----------------------------------------------------------------------------
device::device (std::string const &token)
: m_fd (token, O_RDONLY | O_BINARY)
{ ; }
///////////////////////////////////////////////////////////////////////////////
device::result_type
device::operator() (void)
{
result_type res;
cruft::read (m_fd, cruft::make_byte_view<u08> (res));
return res;
}
///////////////////////////////////////////////////////////////////////////////
double
device::entropy () const noexcept
{
int val;
cruft::posix::error::try_code (
ioctl (m_fd.native (), RNDGETENTCNT, &val)
);
return val < 0 ? 0. : double (val);
}