1 /*
2 * Copyright 2004 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11 #include "rtc_base/helpers.h"
12
13 #include <openssl/rand.h>
14
15 #include <cstdint>
16 #include <limits>
17 #include <memory>
18
19 #include "rtc_base/checks.h"
20 #include "rtc_base/logging.h"
21
22 // Protect against max macro inclusion.
23 #undef max
24
25 namespace rtc {
26
27 // Base class for RNG implementations.
28 class RandomGenerator {
29 public:
~RandomGenerator()30 virtual ~RandomGenerator() {}
31 virtual bool Init(const void* seed, size_t len) = 0;
32 virtual bool Generate(void* buf, size_t len) = 0;
33 };
34
35 // The OpenSSL RNG.
36 class SecureRandomGenerator : public RandomGenerator {
37 public:
SecureRandomGenerator()38 SecureRandomGenerator() {}
~SecureRandomGenerator()39 ~SecureRandomGenerator() override {}
Init(const void * seed,size_t len)40 bool Init(const void* seed, size_t len) override { return true; }
Generate(void * buf,size_t len)41 bool Generate(void* buf, size_t len) override {
42 return (RAND_bytes(reinterpret_cast<unsigned char*>(buf), len) > 0);
43 }
44 };
45
46 // A test random generator, for predictable output.
47 class TestRandomGenerator : public RandomGenerator {
48 public:
TestRandomGenerator()49 TestRandomGenerator() : seed_(7) {}
~TestRandomGenerator()50 ~TestRandomGenerator() override {}
Init(const void * seed,size_t len)51 bool Init(const void* seed, size_t len) override { return true; }
Generate(void * buf,size_t len)52 bool Generate(void* buf, size_t len) override {
53 for (size_t i = 0; i < len; ++i) {
54 static_cast<uint8_t*>(buf)[i] = static_cast<uint8_t>(GetRandom());
55 }
56 return true;
57 }
58
59 private:
GetRandom()60 int GetRandom() {
61 return ((seed_ = seed_ * 214013L + 2531011L) >> 16) & 0x7fff;
62 }
63 int seed_;
64 };
65
66 namespace {
67
68 // TODO: Use Base64::Base64Table instead.
69 static const char kBase64[64] = {
70 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
71 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
72 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
73 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
74 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'};
75
76 static const char kHex[16] = {'0', '1', '2', '3', '4', '5', '6', '7',
77 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
78
79 static const char kUuidDigit17[4] = {'8', '9', 'a', 'b'};
80
81 // This round about way of creating a global RNG is to safe-guard against
82 // indeterminant static initialization order.
GetGlobalRng()83 std::unique_ptr<RandomGenerator>& GetGlobalRng() {
84 static std::unique_ptr<RandomGenerator>& global_rng =
85 *new std::unique_ptr<RandomGenerator>(new SecureRandomGenerator());
86
87 return global_rng;
88 }
89
Rng()90 RandomGenerator& Rng() {
91 return *GetGlobalRng();
92 }
93
94 } // namespace
95
SetRandomTestMode(bool test)96 void SetRandomTestMode(bool test) {
97 if (!test) {
98 GetGlobalRng().reset(new SecureRandomGenerator());
99 } else {
100 GetGlobalRng().reset(new TestRandomGenerator());
101 }
102 }
103
InitRandom(int seed)104 bool InitRandom(int seed) {
105 return InitRandom(reinterpret_cast<const char*>(&seed), sizeof(seed));
106 }
107
InitRandom(const char * seed,size_t len)108 bool InitRandom(const char* seed, size_t len) {
109 if (!Rng().Init(seed, len)) {
110 RTC_LOG(LS_ERROR) << "Failed to init random generator!";
111 return false;
112 }
113 return true;
114 }
115
CreateRandomString(size_t len)116 std::string CreateRandomString(size_t len) {
117 std::string str;
118 RTC_CHECK(CreateRandomString(len, &str));
119 return str;
120 }
121
CreateRandomString(size_t len,const char * table,int table_size,std::string * str)122 static bool CreateRandomString(size_t len,
123 const char* table,
124 int table_size,
125 std::string* str) {
126 str->clear();
127 // Avoid biased modulo division below.
128 if (256 % table_size) {
129 RTC_LOG(LS_ERROR) << "Table size must divide 256 evenly!";
130 return false;
131 }
132 std::unique_ptr<uint8_t[]> bytes(new uint8_t[len]);
133 if (!Rng().Generate(bytes.get(), len)) {
134 RTC_LOG(LS_ERROR) << "Failed to generate random string!";
135 return false;
136 }
137 str->reserve(len);
138 for (size_t i = 0; i < len; ++i) {
139 str->push_back(table[bytes[i] % table_size]);
140 }
141 return true;
142 }
143
CreateRandomString(size_t len,std::string * str)144 bool CreateRandomString(size_t len, std::string* str) {
145 return CreateRandomString(len, kBase64, 64, str);
146 }
147
CreateRandomString(size_t len,const std::string & table,std::string * str)148 bool CreateRandomString(size_t len,
149 const std::string& table,
150 std::string* str) {
151 return CreateRandomString(len, table.c_str(), static_cast<int>(table.size()),
152 str);
153 }
154
CreateRandomData(size_t length,std::string * data)155 bool CreateRandomData(size_t length, std::string* data) {
156 data->resize(length);
157 // std::string is guaranteed to use contiguous memory in c++11 so we can
158 // safely write directly to it.
159 return Rng().Generate(&data->at(0), length);
160 }
161
162 // Version 4 UUID is of the form:
163 // xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
164 // Where 'x' is a hex digit, and 'y' is 8, 9, a or b.
CreateRandomUuid()165 std::string CreateRandomUuid() {
166 std::string str;
167 std::unique_ptr<uint8_t[]> bytes(new uint8_t[31]);
168 RTC_CHECK(Rng().Generate(bytes.get(), 31));
169 str.reserve(36);
170 for (size_t i = 0; i < 8; ++i) {
171 str.push_back(kHex[bytes[i] % 16]);
172 }
173 str.push_back('-');
174 for (size_t i = 8; i < 12; ++i) {
175 str.push_back(kHex[bytes[i] % 16]);
176 }
177 str.push_back('-');
178 str.push_back('4');
179 for (size_t i = 12; i < 15; ++i) {
180 str.push_back(kHex[bytes[i] % 16]);
181 }
182 str.push_back('-');
183 str.push_back(kUuidDigit17[bytes[15] % 4]);
184 for (size_t i = 16; i < 19; ++i) {
185 str.push_back(kHex[bytes[i] % 16]);
186 }
187 str.push_back('-');
188 for (size_t i = 19; i < 31; ++i) {
189 str.push_back(kHex[bytes[i] % 16]);
190 }
191 return str;
192 }
193
CreateRandomId()194 uint32_t CreateRandomId() {
195 uint32_t id;
196 RTC_CHECK(Rng().Generate(&id, sizeof(id)));
197 return id;
198 }
199
CreateRandomId64()200 uint64_t CreateRandomId64() {
201 return static_cast<uint64_t>(CreateRandomId()) << 32 | CreateRandomId();
202 }
203
CreateRandomNonZeroId()204 uint32_t CreateRandomNonZeroId() {
205 uint32_t id;
206 do {
207 id = CreateRandomId();
208 } while (id == 0);
209 return id;
210 }
211
CreateRandomDouble()212 double CreateRandomDouble() {
213 return CreateRandomId() / (std::numeric_limits<uint32_t>::max() +
214 std::numeric_limits<double>::epsilon());
215 }
216
GetNextMovingAverage(double prev_average,double cur,double ratio)217 double GetNextMovingAverage(double prev_average, double cur, double ratio) {
218 return (ratio * prev_average + cur) / (ratio + 1);
219 }
220
221 } // namespace rtc
222