1 /* boost uuid/detail/random_provider_posix implementation
3 * Copyright Jens Maurer 2000
4 * Copyright 2007 Andy Tompkins.
5 * Copyright Steven Watanabe 2010-2011
6 * Copyright 2017 James E. King III
8 * Distributed under the Boost Software License, Version 1.0. (See
9 * accompanying file LICENSE_1_0.txt or copy at
10 * https://www.boost.org/LICENSE_1_0.txt)
15 #include <boost/config.hpp>
16 #include <boost/core/ignore_unused.hpp>
17 #include <boost/move/core.hpp>
18 #include <boost/throw_exception.hpp>
19 #include <boost/uuid/entropy_error.hpp>
22 #include <fcntl.h> // open
24 #include <sys/types.h>
25 #if defined(BOOST_HAS_UNISTD_H)
29 #ifndef BOOST_UUID_RANDOM_PROVIDER_POSIX_IMPL_CLOSE
30 #define BOOST_UUID_RANDOM_PROVIDER_POSIX_IMPL_CLOSE ::close
32 #ifndef BOOST_UUID_RANDOM_PROVIDER_POSIX_IMPL_OPEN
33 #define BOOST_UUID_RANDOM_PROVIDER_POSIX_IMPL_OPEN ::open
35 #ifndef BOOST_UUID_RANDOM_PROVIDER_POSIX_IMPL_READ
36 #define BOOST_UUID_RANDOM_PROVIDER_POSIX_IMPL_READ ::read
43 class random_provider_base
45 BOOST_MOVABLE_BUT_NOT_COPYABLE(random_provider_base)
48 random_provider_base()
52 #if defined(O_CLOEXEC)
55 fd_ = BOOST_UUID_RANDOM_PROVIDER_POSIX_IMPL_OPEN("/dev/urandom", flags);
57 if (BOOST_UNLIKELY(-1 == fd_))
60 BOOST_THROW_EXCEPTION(entropy_error(err, "open /dev/urandom"));
64 random_provider_base(BOOST_RV_REF(random_provider_base) that) BOOST_NOEXCEPT : fd_(that.fd_)
69 random_provider_base& operator= (BOOST_RV_REF(random_provider_base) that) BOOST_NOEXCEPT
77 ~random_provider_base() BOOST_NOEXCEPT
82 //! Obtain entropy and place it into a memory location
83 //! \param[in] buf the location to write entropy
84 //! \param[in] siz the number of bytes to acquire
85 void get_random_bytes(void *buf, std::size_t siz)
87 std::size_t offset = 0;
90 ssize_t sz = BOOST_UUID_RANDOM_PROVIDER_POSIX_IMPL_READ(
91 fd_, static_cast<char *>(buf) + offset, siz - offset);
93 if (BOOST_UNLIKELY(sz < 0))
98 BOOST_THROW_EXCEPTION(entropy_error(err, "read"));
106 void destroy() BOOST_NOEXCEPT
110 boost::ignore_unused(BOOST_UUID_RANDOM_PROVIDER_POSIX_IMPL_CLOSE(fd_));