blob: 9b18777b990e42417359c0ffb879833b87dbc742 [file] [log] [blame]
mseaborn@chromium.org056521b2012-05-30 23:26:13 +09001// Copyright (c) 2012 The Chromium Authors. All rights reserved.
mark@chromium.orgb93c0542008-09-30 07:18:01 +09002// 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
deanm@chromium.org2f749ea2009-06-26 19:00:02 +09007#include <errno.h>
mark@chromium.orgb93c0542008-09-30 07:18:01 +09008#include <fcntl.h>
mark@chromium.orgb93c0542008-09-30 07:18:01 +09009#include <unistd.h>
10
phajdan.jr@chromium.org23725932009-04-23 21:38:08 +090011#include "base/file_util.h"
deanm@chromium.org2f749ea2009-06-26 19:00:02 +090012#include "base/lazy_instance.h"
mark@chromium.orgb93c0542008-09-30 07:18:01 +090013#include "base/logging.h"
14
deanm@chromium.org2f749ea2009-06-26 19:00:02 +090015namespace {
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() {
24 fd_ = open("/dev/urandom", O_RDONLY);
brettw@chromium.org5faed3c2011-10-27 06:48:00 +090025 DCHECK_GE(fd_, 0) << "Cannot open /dev/urandom: " << errno;
deanm@chromium.org2f749ea2009-06-26 19:00:02 +090026 }
27
28 ~URandomFd() {
29 close(fd_);
30 }
31
32 int fd() const { return fd_; }
33
34 private:
35 int fd_;
36};
37
rvargas@chromium.org4abdbe82012-12-21 11:59:50 +090038base::LazyInstance<URandomFd>::Leaky g_urandom_fd = LAZY_INSTANCE_INITIALIZER;
deanm@chromium.org2f749ea2009-06-26 19:00:02 +090039
40} // namespace
41
mark@chromium.orgb93c0542008-09-30 07:18:01 +090042namespace base {
43
mniknami@chromium.orgf4331ae2012-08-03 05:22:25 +090044// NOTE: This function must be cryptographically secure. http://crbug.com/140076
deanm@chromium.org48c40ce2008-11-15 08:28:29 +090045uint64 RandUint64() {
mark@chromium.orgb93c0542008-09-30 07:18:01 +090046 uint64 number;
47
deanm@chromium.org2f749ea2009-06-26 19:00:02 +090048 int urandom_fd = g_urandom_fd.Pointer()->fd();
phajdan.jr@chromium.org23725932009-04-23 21:38:08 +090049 bool success = file_util::ReadFromFD(urandom_fd,
50 reinterpret_cast<char*>(&number),
51 sizeof(number));
52 CHECK(success);
mark@chromium.orgb93c0542008-09-30 07:18:01 +090053
54 return number;
55}
56
agl@chromium.orgba637ac2010-03-05 05:18:55 +090057int GetUrandomFD(void) {
58 return g_urandom_fd.Pointer()->fd();
59}
mseaborn@chromium.org056521b2012-05-30 23:26:13 +090060
61} // namespace base