folly: add bser encode/decode for dynamic
[folly.git] / folly / Random.cpp
1 /*
2  * Copyright 2015 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 <unistd.h>
21 #include <sys/time.h>
22 #include <mutex>
23 #include <random>
24 #include <array>
25
26 #include <glog/logging.h>
27 #include <folly/File.h>
28 #include <folly/FileUtil.h>
29 #include <folly/ThreadLocal.h>
30
31 #ifdef _MSC_VER
32 # include <wincrypt.h>
33 #endif
34
35 namespace folly {
36
37 namespace {
38
39 void readRandomDevice(void* data, size_t size) {
40 #ifdef _MSC_VER
41   static std::once_flag flag;
42   static HCRYPTPROV cryptoProv;
43   std::call_once(flag, [&] {
44     PCHECK(CryptAcquireContext(&cryptoProv, nullptr, nullptr,
45                                PROV_RSA_FULL, 0));
46   });
47   CHECK(size <= std::numeric_limits<DWORD>::max());
48   PCHECK(CryptGenRandom(cryptoProv, (DWORD)size, (BYTE*)data));
49 #else
50   // Keep the random device open for the duration of the program.
51   static int randomFd = ::open("/dev/urandom", O_RDONLY);
52   PCHECK(randomFd >= 0);
53   auto bytesRead = readFull(randomFd, data, size);
54   PCHECK(bytesRead >= 0 && size_t(bytesRead) == size);
55 #endif
56 }
57
58 class BufferedRandomDevice {
59  public:
60   static constexpr size_t kDefaultBufferSize = 128;
61
62   explicit BufferedRandomDevice(size_t bufferSize = kDefaultBufferSize);
63
64   void get(void* data, size_t size) {
65     if (LIKELY(size <= remaining())) {
66       memcpy(data, ptr_, size);
67       ptr_ += size;
68     } else {
69       getSlow(static_cast<unsigned char*>(data), size);
70     }
71   }
72
73  private:
74   void getSlow(unsigned char* data, size_t size);
75
76   inline size_t remaining() const {
77     return buffer_.get() + bufferSize_ - ptr_;
78   }
79
80   const size_t bufferSize_;
81   std::unique_ptr<unsigned char[]> buffer_;
82   unsigned char* ptr_;
83 };
84
85 BufferedRandomDevice::BufferedRandomDevice(size_t bufferSize)
86   : bufferSize_(bufferSize),
87     buffer_(new unsigned char[bufferSize]),
88     ptr_(buffer_.get() + bufferSize) {  // refill on first use
89 }
90
91 void BufferedRandomDevice::getSlow(unsigned char* data, size_t size) {
92   DCHECK_GT(size, remaining());
93   if (size >= bufferSize_) {
94     // Just read directly.
95     readRandomDevice(data, size);
96     return;
97   }
98
99   size_t copied = remaining();
100   memcpy(data, ptr_, copied);
101   data += copied;
102   size -= copied;
103
104   // refill
105   readRandomDevice(buffer_.get(), bufferSize_);
106   ptr_ = buffer_.get();
107
108   memcpy(data, ptr_, size);
109   ptr_ += size;
110 }
111
112
113 }  // namespace
114
115 void Random::secureRandom(void* data, size_t size) {
116   static ThreadLocal<BufferedRandomDevice> bufferedRandomDevice;
117   bufferedRandomDevice->get(data, size);
118 }
119
120 class ThreadLocalPRNG::LocalInstancePRNG {
121  public:
122   LocalInstancePRNG() : rng(Random::create()) { }
123
124   Random::DefaultGenerator rng;
125 };
126
127 ThreadLocalPRNG::ThreadLocalPRNG() {
128   static folly::ThreadLocal<ThreadLocalPRNG::LocalInstancePRNG> localInstance;
129   local_ = localInstance.get();
130 }
131
132 uint32_t ThreadLocalPRNG::getImpl(LocalInstancePRNG* local) {
133   return local->rng();
134 }
135
136 }