blob: aa6a6aea187f3e8e4f33b9788315264514fe0d0b [file] [log] [blame]
henrike@webrtc.org47be73b2014-05-13 18:00:261/*
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 "webrtc/base/helpers.h"
12
13#include <limits>
jbauch1286d0e2016-04-26 10:13:2214#include <memory>
henrike@webrtc.org47be73b2014-05-13 18:00:2615
henrike@webrtc.org47be73b2014-05-13 18:00:2616#include <openssl/rand.h>
henrike@webrtc.org47be73b2014-05-13 18:00:2617
18#include "webrtc/base/base64.h"
19#include "webrtc/base/basictypes.h"
jbauch3d134c12016-08-08 23:33:0620#include "webrtc/base/checks.h"
henrike@webrtc.org47be73b2014-05-13 18:00:2621#include "webrtc/base/logging.h"
henrike@webrtc.org47be73b2014-05-13 18:00:2622#include "webrtc/base/timeutils.h"
23
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.orga031c172014-11-06 17:23:0937// The OpenSSL RNG.
henrike@webrtc.org47be73b2014-05-13 18:00:2638class SecureRandomGenerator : public RandomGenerator {
39 public:
henrike@webrtc.orga031c172014-11-06 17:23:0940 SecureRandomGenerator() {}
kwiberg@webrtc.org786b6342015-03-09 22:21:5341 ~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.org47be73b2014-05-13 18:00:2644 return (RAND_bytes(reinterpret_cast<unsigned char*>(buf), len) > 0);
45 }
henrike@webrtc.org47be73b2014-05-13 18:00:2646};
47
henrike@webrtc.org47be73b2014-05-13 18:00:2648// A test random generator, for predictable output.
49class TestRandomGenerator : public RandomGenerator {
50 public:
51 TestRandomGenerator() : seed_(7) {
52 }
kwiberg@webrtc.org786b6342015-03-09 22:21:5353 ~TestRandomGenerator() override {
henrike@webrtc.org47be73b2014-05-13 18:00:2654 }
kwiberg@webrtc.org786b6342015-03-09 22:21:5355 bool Init(const void* seed, size_t len) override { return true; }
56 bool Generate(void* buf, size_t len) override {
henrike@webrtc.org47be73b2014-05-13 18:00:2657 for (size_t i = 0; i < len; ++i) {
Peter Boström07e22e62015-10-07 10:23:2158 static_cast<uint8_t*>(buf)[i] = static_cast<uint8_t>(GetRandom());
henrike@webrtc.org47be73b2014-05-13 18:00:2659 }
60 return true;
61 }
62
63 private:
64 int GetRandom() {
65 return ((seed_ = seed_ * 214013L + 2531011L) >> 16) & 0x7fff;
66 }
67 int seed_;
68};
69
deadbeef697d03b2015-11-20 19:43:2270namespace {
deadbeefecbf8f52015-11-20 17:49:5971
deadbeefad95edd2015-11-25 19:26:0172// 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.org47be73b2014-05-13 18:00:2685// This round about way of creating a global RNG is to safe-guard against
86// indeterminant static initialization order.
jbauch1286d0e2016-04-26 10:13:2287std::unique_ptr<RandomGenerator>& GetGlobalRng() {
88 RTC_DEFINE_STATIC_LOCAL(std::unique_ptr<RandomGenerator>, global_rng,
Andrew MacDonald0a666142015-05-23 00:50:2689 (new SecureRandomGenerator()));
henrike@webrtc.org47be73b2014-05-13 18:00:2690 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;
jbauch3d134c12016-08-08 23:33:06121 RTC_CHECK(CreateRandomString(len, &str));
henrike@webrtc.org47be73b2014-05-13 18:00:26122 return str;
123}
124
jbauchfd00d952016-08-09 00:13:33125static bool CreateRandomString(size_t len,
henrike@webrtc.org47be73b2014-05-13 18:00:26126 const char* table, int table_size,
127 std::string* str) {
128 str->clear();
jbauchfd00d952016-08-09 00:13:33129 // Avoid biased modulo division below.
130 if (256 % table_size) {
131 LOG(LS_ERROR) << "Table size must divide 256 evenly!";
132 return false;
133 }
jbauch1286d0e2016-04-26 10:13:22134 std::unique_ptr<uint8_t[]> bytes(new uint8_t[len]);
henrike@webrtc.org47be73b2014-05-13 18:00:26135 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) {
deadbeefad95edd2015-11-25 19:26:01147 return CreateRandomString(len, kBase64, 64, str);
henrike@webrtc.org47be73b2014-05-13 18:00:26148}
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
jbauch4443dc42016-08-04 12:20:32156bool 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
deadbeefad95edd2015-11-25 19:26:01163// 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;
jbauch1286d0e2016-04-26 10:13:22168 std::unique_ptr<uint8_t[]> bytes(new uint8_t[31]);
jbauch3d134c12016-08-08 23:33:06169 RTC_CHECK(Rng().Generate(bytes.get(), 31));
deadbeefad95edd2015-11-25 19:26:01170 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öm07e22e62015-10-07 10:23:21195uint32_t CreateRandomId() {
196 uint32_t id;
jbauch3d134c12016-08-08 23:33:06197 RTC_CHECK(Rng().Generate(&id, sizeof(id)));
henrike@webrtc.org47be73b2014-05-13 18:00:26198 return id;
199}
200
Peter Boström07e22e62015-10-07 10:23:21201uint64_t CreateRandomId64() {
202 return static_cast<uint64_t>(CreateRandomId()) << 32 | CreateRandomId();
henrike@webrtc.org47be73b2014-05-13 18:00:26203}
204
Peter Boström07e22e62015-10-07 10:23:21205uint32_t CreateRandomNonZeroId() {
206 uint32_t id;
henrike@webrtc.org47be73b2014-05-13 18:00:26207 do {
208 id = CreateRandomId();
209 } while (id == 0);
210 return id;
211}
212
213double CreateRandomDouble() {
Peter Boström07e22e62015-10-07 10:23:21214 return CreateRandomId() / (std::numeric_limits<uint32_t>::max() +
215 std::numeric_limits<double>::epsilon());
henrike@webrtc.org47be73b2014-05-13 18:00:26216}
217
218} // namespace rtc