blob: d8ea89f0c2e1203e944c84535c0da053dbacd26b [file] [log] [blame]
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001/*
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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "rtc_base/helpers.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000012
Yves Gerey3e707812018-11-28 16:47:49 +010013#include <openssl/rand.h>
14#include <cstdint>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000015#include <limits>
jbauch555604a2016-04-26 03:13:22 -070016#include <memory>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000017
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020018#include "rtc_base/checks.h"
19#include "rtc_base/logging.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000020
21// Protect against max macro inclusion.
22#undef max
23
24namespace rtc {
25
26// Base class for RNG implementations.
27class RandomGenerator {
28 public:
29 virtual ~RandomGenerator() {}
30 virtual bool Init(const void* seed, size_t len) = 0;
31 virtual bool Generate(void* buf, size_t len) = 0;
32};
33
henrike@webrtc.orgd89b69a2014-11-06 17:23:09 +000034// The OpenSSL RNG.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000035class SecureRandomGenerator : public RandomGenerator {
36 public:
henrike@webrtc.orgd89b69a2014-11-06 17:23:09 +000037 SecureRandomGenerator() {}
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +000038 ~SecureRandomGenerator() override {}
39 bool Init(const void* seed, size_t len) override { return true; }
40 bool Generate(void* buf, size_t len) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000041 return (RAND_bytes(reinterpret_cast<unsigned char*>(buf), len) > 0);
42 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000043};
44
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000045// A test random generator, for predictable output.
46class TestRandomGenerator : public RandomGenerator {
47 public:
Yves Gerey665174f2018-06-19 15:03:05 +020048 TestRandomGenerator() : seed_(7) {}
49 ~TestRandomGenerator() override {}
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +000050 bool Init(const void* seed, size_t len) override { return true; }
51 bool Generate(void* buf, size_t len) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000052 for (size_t i = 0; i < len; ++i) {
Peter Boström0c4e06b2015-10-07 12:23:21 +020053 static_cast<uint8_t*>(buf)[i] = static_cast<uint8_t>(GetRandom());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000054 }
55 return true;
56 }
57
58 private:
59 int GetRandom() {
60 return ((seed_ = seed_ * 214013L + 2531011L) >> 16) & 0x7fff;
61 }
62 int seed_;
63};
64
deadbeef5def7b92015-11-20 11:43:22 -080065namespace {
deadbeef6834fa12015-11-20 09:49:59 -080066
deadbeeffac06552015-11-25 11:26:01 -080067// TODO: Use Base64::Base64Table instead.
68static const char kBase64[64] = {
69 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
70 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
71 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
72 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
73 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'};
74
75static const char kHex[16] = {'0', '1', '2', '3', '4', '5', '6', '7',
76 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
77
78static const char kUuidDigit17[4] = {'8', '9', 'a', 'b'};
79
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000080// This round about way of creating a global RNG is to safe-guard against
81// indeterminant static initialization order.
jbauch555604a2016-04-26 03:13:22 -070082std::unique_ptr<RandomGenerator>& GetGlobalRng() {
Yves Gerey665174f2018-06-19 15:03:05 +020083 static std::unique_ptr<RandomGenerator>& global_rng =
84 *new std::unique_ptr<RandomGenerator>(new SecureRandomGenerator());
Niels Möller14682a32018-05-24 08:54:25 +020085
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000086 return global_rng;
87}
88
89RandomGenerator& Rng() {
90 return *GetGlobalRng();
91}
92
93} // namespace
94
95void SetRandomTestMode(bool test) {
96 if (!test) {
97 GetGlobalRng().reset(new SecureRandomGenerator());
98 } else {
99 GetGlobalRng().reset(new TestRandomGenerator());
100 }
101}
102
103bool InitRandom(int seed) {
104 return InitRandom(reinterpret_cast<const char*>(&seed), sizeof(seed));
105}
106
107bool InitRandom(const char* seed, size_t len) {
108 if (!Rng().Init(seed, len)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100109 RTC_LOG(LS_ERROR) << "Failed to init random generator!";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000110 return false;
111 }
112 return true;
113}
114
115std::string CreateRandomString(size_t len) {
116 std::string str;
jbauch912f46a2016-08-08 16:33:06 -0700117 RTC_CHECK(CreateRandomString(len, &str));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000118 return str;
119}
120
jbauche3eff7c2016-08-08 17:13:33 -0700121static bool CreateRandomString(size_t len,
Yves Gerey665174f2018-06-19 15:03:05 +0200122 const char* table,
123 int table_size,
124 std::string* str) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000125 str->clear();
jbauche3eff7c2016-08-08 17:13:33 -0700126 // Avoid biased modulo division below.
127 if (256 % table_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100128 RTC_LOG(LS_ERROR) << "Table size must divide 256 evenly!";
jbauche3eff7c2016-08-08 17:13:33 -0700129 return false;
130 }
jbauch555604a2016-04-26 03:13:22 -0700131 std::unique_ptr<uint8_t[]> bytes(new uint8_t[len]);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000132 if (!Rng().Generate(bytes.get(), len)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100133 RTC_LOG(LS_ERROR) << "Failed to generate random string!";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000134 return false;
135 }
136 str->reserve(len);
137 for (size_t i = 0; i < len; ++i) {
138 str->push_back(table[bytes[i] % table_size]);
139 }
140 return true;
141}
142
143bool CreateRandomString(size_t len, std::string* str) {
deadbeeffac06552015-11-25 11:26:01 -0800144 return CreateRandomString(len, kBase64, 64, str);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000145}
146
Yves Gerey665174f2018-06-19 15:03:05 +0200147bool CreateRandomString(size_t len,
148 const std::string& table,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000149 std::string* str) {
Yves Gerey665174f2018-06-19 15:03:05 +0200150 return CreateRandomString(len, table.c_str(), static_cast<int>(table.size()),
151 str);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000152}
153
jbauchcb560652016-08-04 05:20:32 -0700154bool CreateRandomData(size_t length, std::string* data) {
155 data->resize(length);
156 // std::string is guaranteed to use contiguous memory in c++11 so we can
157 // safely write directly to it.
158 return Rng().Generate(&data->at(0), length);
159}
160
deadbeeffac06552015-11-25 11:26:01 -0800161// Version 4 UUID is of the form:
162// xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
163// Where 'x' is a hex digit, and 'y' is 8, 9, a or b.
164std::string CreateRandomUuid() {
165 std::string str;
jbauch555604a2016-04-26 03:13:22 -0700166 std::unique_ptr<uint8_t[]> bytes(new uint8_t[31]);
jbauch912f46a2016-08-08 16:33:06 -0700167 RTC_CHECK(Rng().Generate(bytes.get(), 31));
deadbeeffac06552015-11-25 11:26:01 -0800168 str.reserve(36);
169 for (size_t i = 0; i < 8; ++i) {
170 str.push_back(kHex[bytes[i] % 16]);
171 }
172 str.push_back('-');
173 for (size_t i = 8; i < 12; ++i) {
174 str.push_back(kHex[bytes[i] % 16]);
175 }
176 str.push_back('-');
177 str.push_back('4');
178 for (size_t i = 12; i < 15; ++i) {
179 str.push_back(kHex[bytes[i] % 16]);
180 }
181 str.push_back('-');
182 str.push_back(kUuidDigit17[bytes[15] % 4]);
183 for (size_t i = 16; i < 19; ++i) {
184 str.push_back(kHex[bytes[i] % 16]);
185 }
186 str.push_back('-');
187 for (size_t i = 19; i < 31; ++i) {
188 str.push_back(kHex[bytes[i] % 16]);
189 }
190 return str;
191}
192
Peter Boström0c4e06b2015-10-07 12:23:21 +0200193uint32_t CreateRandomId() {
194 uint32_t id;
jbauch912f46a2016-08-08 16:33:06 -0700195 RTC_CHECK(Rng().Generate(&id, sizeof(id)));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000196 return id;
197}
198
Peter Boström0c4e06b2015-10-07 12:23:21 +0200199uint64_t CreateRandomId64() {
200 return static_cast<uint64_t>(CreateRandomId()) << 32 | CreateRandomId();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000201}
202
Peter Boström0c4e06b2015-10-07 12:23:21 +0200203uint32_t CreateRandomNonZeroId() {
204 uint32_t id;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000205 do {
206 id = CreateRandomId();
207 } while (id == 0);
208 return id;
209}
210
211double CreateRandomDouble() {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200212 return CreateRandomId() / (std::numeric_limits<uint32_t>::max() +
213 std::numeric_limits<double>::epsilon());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000214}
215
Qingsi Wang72a43a12018-02-20 16:03:18 -0800216double GetNextMovingAverage(double prev_average, double cur, double ratio) {
217 return (ratio * prev_average + cur) / (ratio + 1);
218}
219
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000220} // namespace rtc