blob: 0a72a20d6420961e75aabf82f06fff41ca5e1dc1 [file] [log] [blame]
[email protected]ead8c1fa2012-05-30 14:26:131// Copyright (c) 2012 The Chromium Authors. All rights reserved.
[email protected]05f9b682008-09-29 22:18:012// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "base/rand_util.h"
6
[email protected]09e5f47a2009-06-26 10:00:027#include <errno.h>
[email protected]05f9b682008-09-29 22:18:018#include <fcntl.h>
[email protected]05f9b682008-09-29 22:18:019#include <unistd.h>
10
[email protected]45301492009-04-23 12:38:0811#include "base/file_util.h"
[email protected]09e5f47a2009-06-26 10:00:0212#include "base/lazy_instance.h"
[email protected]05f9b682008-09-29 22:18:0113#include "base/logging.h"
14
[email protected]09e5f47a2009-06-26 10:00:0215namespace {
16
17// We keep the file descriptor for /dev/urandom around so we don't need to
18// reopen it (which is expensive), and since we may not even be able to reopen
19// it if we are later put in a sandbox. This class wraps the file descriptor so
20// we can use LazyInstance to handle opening it on the first access.
21class URandomFd {
22 public:
[email protected]c910c5a2014-01-23 02:14:2823 URandomFd() : fd_(open("/dev/urandom", O_RDONLY)) {
[email protected]a42d4632011-10-26 21:48:0024 DCHECK_GE(fd_, 0) << "Cannot open /dev/urandom: " << errno;
[email protected]09e5f47a2009-06-26 10:00:0225 }
26
[email protected]c910c5a2014-01-23 02:14:2827 ~URandomFd() { close(fd_); }
[email protected]09e5f47a2009-06-26 10:00:0228
29 int fd() const { return fd_; }
30
31 private:
[email protected]c910c5a2014-01-23 02:14:2832 const int fd_;
[email protected]09e5f47a2009-06-26 10:00:0233};
34
[email protected]6ecc0962012-12-21 02:59:5035base::LazyInstance<URandomFd>::Leaky g_urandom_fd = LAZY_INSTANCE_INITIALIZER;
[email protected]09e5f47a2009-06-26 10:00:0236
37} // namespace
38
[email protected]05f9b682008-09-29 22:18:0139namespace base {
40
[email protected]9b205782012-08-02 20:22:2541// NOTE: This function must be cryptographically secure. http://crbug.com/140076
[email protected]ba990122008-11-14 23:28:2942uint64 RandUint64() {
[email protected]05f9b682008-09-29 22:18:0143 uint64 number;
[email protected]c910c5a2014-01-23 02:14:2844 RandBytes(&number, sizeof(number));
[email protected]05f9b682008-09-29 22:18:0145 return number;
46}
47
[email protected]c910c5a2014-01-23 02:14:2848void RandBytes(void* output, size_t output_length) {
49 const int urandom_fd = g_urandom_fd.Pointer()->fd();
50 const bool success =
51 ReadFromFD(urandom_fd, static_cast<char*>(output), output_length);
52 CHECK(success);
53}
54
[email protected]1d87fad2010-03-04 20:18:5555int GetUrandomFD(void) {
56 return g_urandom_fd.Pointer()->fd();
57}
[email protected]ead8c1fa2012-05-30 14:26:1358
59} // namespace base