make Range::size() constexpr
[folly.git] / folly / Random.cpp
1 /*
2  * Copyright 2016 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <folly/Random.h>
18
19 #include <atomic>
20 #include <mutex>
21 #include <random>
22 #include <array>
23
24 #include <glog/logging.h>
25 #include <folly/CallOnce.h>
26 #include <folly/File.h>
27 #include <folly/FileUtil.h>
28 #include <folly/ThreadLocal.h>
29 #include <folly/portability/SysTime.h>
30 #include <folly/portability/Unistd.h>
31
32 #ifdef _MSC_VER
33 # include <wincrypt.h>
34 #endif
35
36 namespace folly {
37
38 namespace {
39
40 void readRandomDevice(void* data, size_t size) {
41 #ifdef _MSC_VER
42   static folly::once_flag flag;
43   static HCRYPTPROV cryptoProv;
44   folly::call_once(flag, [&] {
45     PCHECK(CryptAcquireContext(&cryptoProv, nullptr, nullptr,
46                                PROV_RSA_FULL, 0));
47   });
48   CHECK(size <= std::numeric_limits<DWORD>::max());
49   PCHECK(CryptGenRandom(cryptoProv, (DWORD)size, (BYTE*)data));
50 #else
51   // Keep the random device open for the duration of the program.
52   static int randomFd = ::open("/dev/urandom", O_RDONLY);
53   PCHECK(randomFd >= 0);
54   auto bytesRead = readFull(randomFd, data, size);
55   PCHECK(bytesRead >= 0 && size_t(bytesRead) == size);
56 #endif
57 }
58
59 class BufferedRandomDevice {
60  public:
61   static constexpr size_t kDefaultBufferSize = 128;
62
63   explicit BufferedRandomDevice(size_t bufferSize = kDefaultBufferSize);
64
65   void get(void* data, size_t size) {
66     if (LIKELY(size <= remaining())) {
67       memcpy(data, ptr_, size);
68       ptr_ += size;
69     } else {
70       getSlow(static_cast<unsigned char*>(data), size);
71     }
72   }
73
74  private:
75   void getSlow(unsigned char* data, size_t size);
76
77   inline size_t remaining() const {
78     return buffer_.get() + bufferSize_ - ptr_;
79   }
80
81   const size_t bufferSize_;
82   std::unique_ptr<unsigned char[]> buffer_;
83   unsigned char* ptr_;
84 };
85
86 BufferedRandomDevice::BufferedRandomDevice(size_t bufferSize)
87   : bufferSize_(bufferSize),
88     buffer_(new unsigned char[bufferSize]),
89     ptr_(buffer_.get() + bufferSize) {  // refill on first use
90 }
91
92 void BufferedRandomDevice::getSlow(unsigned char* data, size_t size) {
93   DCHECK_GT(size, remaining());
94   if (size >= bufferSize_) {
95     // Just read directly.
96     readRandomDevice(data, size);
97     return;
98   }
99
100   size_t copied = remaining();
101   memcpy(data, ptr_, copied);
102   data += copied;
103   size -= copied;
104
105   // refill
106   readRandomDevice(buffer_.get(), bufferSize_);
107   ptr_ = buffer_.get();
108
109   memcpy(data, ptr_, size);
110   ptr_ += size;
111 }
112
113
114 }  // namespace
115
116 void Random::secureRandom(void* data, size_t size) {
117   static ThreadLocal<BufferedRandomDevice> bufferedRandomDevice;
118   bufferedRandomDevice->get(data, size);
119 }
120
121 class ThreadLocalPRNG::LocalInstancePRNG {
122  public:
123   LocalInstancePRNG() : rng(Random::create()) { }
124
125   Random::DefaultGenerator rng;
126 };
127
128 ThreadLocalPRNG::ThreadLocalPRNG() {
129   static folly::ThreadLocal<ThreadLocalPRNG::LocalInstancePRNG> localInstance;
130   local_ = localInstance.get();
131 }
132
133 uint32_t ThreadLocalPRNG::getImpl(LocalInstancePRNG* local) {
134   return local->rng();
135 }
136
137 }