blob: e62aaf87b21c34cba3d9722217db2261390a017c [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"
19#include "rtc_base/basictypes.h"
20#include "rtc_base/checks.h"
21#include "rtc_base/logging.h"
22#include "rtc_base/timeutils.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000023
24// Protect against max macro inclusion.
25#undef max
26
27namespace rtc {
28
29// Base class for RNG implementations.
30class RandomGenerator {
31 public:
32 virtual ~RandomGenerator() {}
33 virtual bool Init(const void* seed, size_t len) = 0;
34 virtual bool Generate(void* buf, size_t len) = 0;
35};
36
henrike@webrtc.orgd89b69a2014-11-06 17:23:09 +000037// The OpenSSL RNG.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000038class SecureRandomGenerator : public RandomGenerator {
39 public:
henrike@webrtc.orgd89b69a2014-11-06 17:23:09 +000040 SecureRandomGenerator() {}
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +000041 ~SecureRandomGenerator() override {}
42 bool Init(const void* seed, size_t len) override { return true; }
43 bool Generate(void* buf, size_t len) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000044 return (RAND_bytes(reinterpret_cast<unsigned char*>(buf), len) > 0);
45 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000046};
47
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000048// A test random generator, for predictable output.
49class TestRandomGenerator : public RandomGenerator {
50 public:
51 TestRandomGenerator() : seed_(7) {
52 }
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +000053 ~TestRandomGenerator() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000054 }
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +000055 bool Init(const void* seed, size_t len) override { return true; }
56 bool Generate(void* buf, size_t len) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000057 for (size_t i = 0; i < len; ++i) {
Peter Boström0c4e06b2015-10-07 12:23:21 +020058 static_cast<uint8_t*>(buf)[i] = static_cast<uint8_t>(GetRandom());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000059 }
60 return true;
61 }
62
63 private:
64 int GetRandom() {
65 return ((seed_ = seed_ * 214013L + 2531011L) >> 16) & 0x7fff;
66 }
67 int seed_;
68};
69
deadbeef5def7b92015-11-20 11:43:22 -080070namespace {
deadbeef6834fa12015-11-20 09:49:59 -080071
deadbeeffac06552015-11-25 11:26:01 -080072// TODO: Use Base64::Base64Table instead.
73static const char kBase64[64] = {
74 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
75 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
76 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
77 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
78 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'};
79
80static const char kHex[16] = {'0', '1', '2', '3', '4', '5', '6', '7',
81 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
82
83static const char kUuidDigit17[4] = {'8', '9', 'a', 'b'};
84
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000085// This round about way of creating a global RNG is to safe-guard against
86// indeterminant static initialization order.
jbauch555604a2016-04-26 03:13:22 -070087std::unique_ptr<RandomGenerator>& GetGlobalRng() {
88 RTC_DEFINE_STATIC_LOCAL(std::unique_ptr<RandomGenerator>, global_rng,
Andrew MacDonald469c2c02015-05-22 17:50:26 -070089 (new SecureRandomGenerator()));
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)) {
113 LOG(LS_ERROR) << "Failed to init random generator!";
114 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) {
131 LOG(LS_ERROR) << "Table size must divide 256 evenly!";
132 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)) {
136 LOG(LS_ERROR) << "Failed to generate random string!";
137 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
218} // namespace rtc