blob: 64cab103351c191b1bf37d873448ca5137680676 [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>
Jonas Olssona4d87372019-07-05 19:08:33 +020014
Yves Gerey3e707812018-11-28 16:47:49 +010015#include <cstdint>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000016#include <limits>
jbauch555604a2016-04-26 03:13:22 -070017#include <memory>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000018
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020019#include "rtc_base/checks.h"
20#include "rtc_base/logging.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000021
22// Protect against max macro inclusion.
23#undef max
24
25namespace rtc {
26
27// Base class for RNG implementations.
28class RandomGenerator {
29 public:
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
henrike@webrtc.orgd89b69a2014-11-06 17:23:09 +000035// The OpenSSL RNG.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000036class SecureRandomGenerator : public RandomGenerator {
37 public:
henrike@webrtc.orgd89b69a2014-11-06 17:23:09 +000038 SecureRandomGenerator() {}
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +000039 ~SecureRandomGenerator() override {}
40 bool Init(const void* seed, size_t len) override { return true; }
41 bool Generate(void* buf, size_t len) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000042 return (RAND_bytes(reinterpret_cast<unsigned char*>(buf), len) > 0);
43 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000044};
45
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000046// A test random generator, for predictable output.
47class TestRandomGenerator : public RandomGenerator {
48 public:
Yves Gerey665174f2018-06-19 15:03:05 +020049 TestRandomGenerator() : seed_(7) {}
50 ~TestRandomGenerator() override {}
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +000051 bool Init(const void* seed, size_t len) override { return true; }
52 bool Generate(void* buf, size_t len) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000053 for (size_t i = 0; i < len; ++i) {
Peter Boström0c4e06b2015-10-07 12:23:21 +020054 static_cast<uint8_t*>(buf)[i] = static_cast<uint8_t>(GetRandom());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000055 }
56 return true;
57 }
58
59 private:
60 int GetRandom() {
61 return ((seed_ = seed_ * 214013L + 2531011L) >> 16) & 0x7fff;
62 }
63 int seed_;
64};
65
deadbeef5def7b92015-11-20 11:43:22 -080066namespace {
deadbeef6834fa12015-11-20 09:49:59 -080067
deadbeeffac06552015-11-25 11:26:01 -080068// TODO: Use Base64::Base64Table instead.
69static 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
76static const char kHex[16] = {'0', '1', '2', '3', '4', '5', '6', '7',
77 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
78
79static const char kUuidDigit17[4] = {'8', '9', 'a', 'b'};
80
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000081// This round about way of creating a global RNG is to safe-guard against
82// indeterminant static initialization order.
jbauch555604a2016-04-26 03:13:22 -070083std::unique_ptr<RandomGenerator>& GetGlobalRng() {
Yves Gerey665174f2018-06-19 15:03:05 +020084 static std::unique_ptr<RandomGenerator>& global_rng =
85 *new std::unique_ptr<RandomGenerator>(new SecureRandomGenerator());
Niels Möller14682a32018-05-24 08:54:25 +020086
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000087 return global_rng;
88}
89
90RandomGenerator& Rng() {
91 return *GetGlobalRng();
92}
93
94} // namespace
95
96void SetRandomTestMode(bool test) {
97 if (!test) {
98 GetGlobalRng().reset(new SecureRandomGenerator());
99 } else {
100 GetGlobalRng().reset(new TestRandomGenerator());
101 }
102}
103
104bool InitRandom(int seed) {
105 return InitRandom(reinterpret_cast<const char*>(&seed), sizeof(seed));
106}
107
108bool InitRandom(const char* seed, size_t len) {
109 if (!Rng().Init(seed, len)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100110 RTC_LOG(LS_ERROR) << "Failed to init random generator!";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000111 return false;
112 }
113 return true;
114}
115
116std::string CreateRandomString(size_t len) {
117 std::string str;
jbauch912f46a2016-08-08 16:33:06 -0700118 RTC_CHECK(CreateRandomString(len, &str));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000119 return str;
120}
121
jbauche3eff7c2016-08-08 17:13:33 -0700122static bool CreateRandomString(size_t len,
Yves Gerey665174f2018-06-19 15:03:05 +0200123 const char* table,
124 int table_size,
125 std::string* str) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000126 str->clear();
jbauche3eff7c2016-08-08 17:13:33 -0700127 // Avoid biased modulo division below.
128 if (256 % table_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100129 RTC_LOG(LS_ERROR) << "Table size must divide 256 evenly!";
jbauche3eff7c2016-08-08 17:13:33 -0700130 return false;
131 }
jbauch555604a2016-04-26 03:13:22 -0700132 std::unique_ptr<uint8_t[]> bytes(new uint8_t[len]);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000133 if (!Rng().Generate(bytes.get(), len)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100134 RTC_LOG(LS_ERROR) << "Failed to generate random string!";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000135 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
144bool CreateRandomString(size_t len, std::string* str) {
deadbeeffac06552015-11-25 11:26:01 -0800145 return CreateRandomString(len, kBase64, 64, str);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000146}
147
Yves Gerey665174f2018-06-19 15:03:05 +0200148bool CreateRandomString(size_t len,
149 const std::string& table,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000150 std::string* str) {
Yves Gerey665174f2018-06-19 15:03:05 +0200151 return CreateRandomString(len, table.c_str(), static_cast<int>(table.size()),
152 str);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000153}
154
jbauchcb560652016-08-04 05:20:32 -0700155bool 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
deadbeeffac06552015-11-25 11:26:01 -0800162// 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.
165std::string CreateRandomUuid() {
166 std::string str;
jbauch555604a2016-04-26 03:13:22 -0700167 std::unique_ptr<uint8_t[]> bytes(new uint8_t[31]);
jbauch912f46a2016-08-08 16:33:06 -0700168 RTC_CHECK(Rng().Generate(bytes.get(), 31));
deadbeeffac06552015-11-25 11:26:01 -0800169 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
Peter Boström0c4e06b2015-10-07 12:23:21 +0200194uint32_t CreateRandomId() {
195 uint32_t id;
jbauch912f46a2016-08-08 16:33:06 -0700196 RTC_CHECK(Rng().Generate(&id, sizeof(id)));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000197 return id;
198}
199
Peter Boström0c4e06b2015-10-07 12:23:21 +0200200uint64_t CreateRandomId64() {
201 return static_cast<uint64_t>(CreateRandomId()) << 32 | CreateRandomId();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000202}
203
Peter Boström0c4e06b2015-10-07 12:23:21 +0200204uint32_t CreateRandomNonZeroId() {
205 uint32_t id;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000206 do {
207 id = CreateRandomId();
208 } while (id == 0);
209 return id;
210}
211
212double CreateRandomDouble() {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200213 return CreateRandomId() / (std::numeric_limits<uint32_t>::max() +
214 std::numeric_limits<double>::epsilon());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000215}
216
Qingsi Wang72a43a12018-02-20 16:03:18 -0800217double GetNextMovingAverage(double prev_average, double cur, double ratio) {
218 return (ratio * prev_average + cur) / (ratio + 1);
219}
220
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000221} // namespace rtc