blob: 89cf609d1daa7fad3cb8e6110a92c40917c01d07 [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
13#include <limits>
jbauch555604a2016-04-26 03:13:22 -070014#include <memory>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000015
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000016#include <openssl/rand.h>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000017
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020018#include "rtc_base/base64.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020019#include "rtc_base/checks.h"
20#include "rtc_base/logging.h"
21#include "rtc_base/timeutils.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000022
23// Protect against max macro inclusion.
24#undef max
25
26namespace rtc {
27
28// Base class for RNG implementations.
29class RandomGenerator {
30 public:
31 virtual ~RandomGenerator() {}
32 virtual bool Init(const void* seed, size_t len) = 0;
33 virtual bool Generate(void* buf, size_t len) = 0;
34};
35
henrike@webrtc.orgd89b69a2014-11-06 17:23:09 +000036// The OpenSSL RNG.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000037class SecureRandomGenerator : public RandomGenerator {
38 public:
henrike@webrtc.orgd89b69a2014-11-06 17:23:09 +000039 SecureRandomGenerator() {}
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +000040 ~SecureRandomGenerator() override {}
41 bool Init(const void* seed, size_t len) override { return true; }
42 bool Generate(void* buf, size_t len) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000043 return (RAND_bytes(reinterpret_cast<unsigned char*>(buf), len) > 0);
44 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000045};
46
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000047// A test random generator, for predictable output.
48class TestRandomGenerator : public RandomGenerator {
49 public:
50 TestRandomGenerator() : seed_(7) {
51 }
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +000052 ~TestRandomGenerator() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000053 }
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +000054 bool Init(const void* seed, size_t len) override { return true; }
55 bool Generate(void* buf, size_t len) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000056 for (size_t i = 0; i < len; ++i) {
Peter Boström0c4e06b2015-10-07 12:23:21 +020057 static_cast<uint8_t*>(buf)[i] = static_cast<uint8_t>(GetRandom());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000058 }
59 return true;
60 }
61
62 private:
63 int GetRandom() {
64 return ((seed_ = seed_ * 214013L + 2531011L) >> 16) & 0x7fff;
65 }
66 int seed_;
67};
68
deadbeef5def7b92015-11-20 11:43:22 -080069namespace {
deadbeef6834fa12015-11-20 09:49:59 -080070
deadbeeffac06552015-11-25 11:26:01 -080071// TODO: Use Base64::Base64Table instead.
72static const char kBase64[64] = {
73 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
74 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
75 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
76 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
77 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'};
78
79static const char kHex[16] = {'0', '1', '2', '3', '4', '5', '6', '7',
80 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
81
82static const char kUuidDigit17[4] = {'8', '9', 'a', 'b'};
83
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000084// This round about way of creating a global RNG is to safe-guard against
85// indeterminant static initialization order.
jbauch555604a2016-04-26 03:13:22 -070086std::unique_ptr<RandomGenerator>& GetGlobalRng() {
Niels Möller14682a32018-05-24 08:54:25 +020087 static std::unique_ptr<RandomGenerator>& global_rng
88 = *new std::unique_ptr<RandomGenerator>(new SecureRandomGenerator());
89
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000090 return global_rng;
91}
92
93RandomGenerator& Rng() {
94 return *GetGlobalRng();
95}
96
97} // namespace
98
99void SetRandomTestMode(bool test) {
100 if (!test) {
101 GetGlobalRng().reset(new SecureRandomGenerator());
102 } else {
103 GetGlobalRng().reset(new TestRandomGenerator());
104 }
105}
106
107bool InitRandom(int seed) {
108 return InitRandom(reinterpret_cast<const char*>(&seed), sizeof(seed));
109}
110
111bool InitRandom(const char* seed, size_t len) {
112 if (!Rng().Init(seed, len)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100113 RTC_LOG(LS_ERROR) << "Failed to init random generator!";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000114 return false;
115 }
116 return true;
117}
118
119std::string CreateRandomString(size_t len) {
120 std::string str;
jbauch912f46a2016-08-08 16:33:06 -0700121 RTC_CHECK(CreateRandomString(len, &str));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000122 return str;
123}
124
jbauche3eff7c2016-08-08 17:13:33 -0700125static bool CreateRandomString(size_t len,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000126 const char* table, int table_size,
127 std::string* str) {
128 str->clear();
jbauche3eff7c2016-08-08 17:13:33 -0700129 // Avoid biased modulo division below.
130 if (256 % table_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100131 RTC_LOG(LS_ERROR) << "Table size must divide 256 evenly!";
jbauche3eff7c2016-08-08 17:13:33 -0700132 return false;
133 }
jbauch555604a2016-04-26 03:13:22 -0700134 std::unique_ptr<uint8_t[]> bytes(new uint8_t[len]);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000135 if (!Rng().Generate(bytes.get(), len)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100136 RTC_LOG(LS_ERROR) << "Failed to generate random string!";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000137 return false;
138 }
139 str->reserve(len);
140 for (size_t i = 0; i < len; ++i) {
141 str->push_back(table[bytes[i] % table_size]);
142 }
143 return true;
144}
145
146bool CreateRandomString(size_t len, std::string* str) {
deadbeeffac06552015-11-25 11:26:01 -0800147 return CreateRandomString(len, kBase64, 64, str);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000148}
149
150bool CreateRandomString(size_t len, const std::string& table,
151 std::string* str) {
152 return CreateRandomString(len, table.c_str(),
153 static_cast<int>(table.size()), str);
154}
155
jbauchcb560652016-08-04 05:20:32 -0700156bool CreateRandomData(size_t length, std::string* data) {
157 data->resize(length);
158 // std::string is guaranteed to use contiguous memory in c++11 so we can
159 // safely write directly to it.
160 return Rng().Generate(&data->at(0), length);
161}
162
deadbeeffac06552015-11-25 11:26:01 -0800163// Version 4 UUID is of the form:
164// xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
165// Where 'x' is a hex digit, and 'y' is 8, 9, a or b.
166std::string CreateRandomUuid() {
167 std::string str;
jbauch555604a2016-04-26 03:13:22 -0700168 std::unique_ptr<uint8_t[]> bytes(new uint8_t[31]);
jbauch912f46a2016-08-08 16:33:06 -0700169 RTC_CHECK(Rng().Generate(bytes.get(), 31));
deadbeeffac06552015-11-25 11:26:01 -0800170 str.reserve(36);
171 for (size_t i = 0; i < 8; ++i) {
172 str.push_back(kHex[bytes[i] % 16]);
173 }
174 str.push_back('-');
175 for (size_t i = 8; i < 12; ++i) {
176 str.push_back(kHex[bytes[i] % 16]);
177 }
178 str.push_back('-');
179 str.push_back('4');
180 for (size_t i = 12; i < 15; ++i) {
181 str.push_back(kHex[bytes[i] % 16]);
182 }
183 str.push_back('-');
184 str.push_back(kUuidDigit17[bytes[15] % 4]);
185 for (size_t i = 16; i < 19; ++i) {
186 str.push_back(kHex[bytes[i] % 16]);
187 }
188 str.push_back('-');
189 for (size_t i = 19; i < 31; ++i) {
190 str.push_back(kHex[bytes[i] % 16]);
191 }
192 return str;
193}
194
Peter Boström0c4e06b2015-10-07 12:23:21 +0200195uint32_t CreateRandomId() {
196 uint32_t id;
jbauch912f46a2016-08-08 16:33:06 -0700197 RTC_CHECK(Rng().Generate(&id, sizeof(id)));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000198 return id;
199}
200
Peter Boström0c4e06b2015-10-07 12:23:21 +0200201uint64_t CreateRandomId64() {
202 return static_cast<uint64_t>(CreateRandomId()) << 32 | CreateRandomId();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000203}
204
Peter Boström0c4e06b2015-10-07 12:23:21 +0200205uint32_t CreateRandomNonZeroId() {
206 uint32_t id;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000207 do {
208 id = CreateRandomId();
209 } while (id == 0);
210 return id;
211}
212
213double CreateRandomDouble() {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200214 return CreateRandomId() / (std::numeric_limits<uint32_t>::max() +
215 std::numeric_limits<double>::epsilon());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000216}
217
Qingsi Wang72a43a12018-02-20 16:03:18 -0800218double GetNextMovingAverage(double prev_average, double cur, double ratio) {
219 return (ratio * prev_average + cur) / (ratio + 1);
220}
221
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000222} // namespace rtc