1// Copyright (c) 2012 The Chromium Authors. All rights reserved.
2// 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
7#include <errno.h>
8#include <fcntl.h>
9#include <unistd.h>
10
11#include "base/files/file_util.h"
12#include "base/lazy_instance.h"
13#include "base/logging.h"
14
15namespace {
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:
23  URandomFd() : fd_(open("/dev/urandom", O_RDONLY)) {
24    DCHECK_GE(fd_, 0) << "Cannot open /dev/urandom: " << errno;
25  }
26
27  ~URandomFd() { close(fd_); }
28
29  int fd() const { return fd_; }
30
31 private:
32  const int fd_;
33};
34
35base::LazyInstance<URandomFd>::Leaky g_urandom_fd = LAZY_INSTANCE_INITIALIZER;
36
37}  // namespace
38
39namespace base {
40
41// NOTE: This function must be cryptographically secure. http://crbug.com/140076
42uint64 RandUint64() {
43  uint64 number;
44  RandBytes(&number, sizeof(number));
45  return number;
46}
47
48void 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
55int GetUrandomFD(void) {
56  return g_urandom_fd.Pointer()->fd();
57}
58
59}  // namespace base
60