You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

221 lines
6.1 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  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. #include "rtc_base/helpers.h"
  11. #include <openssl/rand.h>
  12. #include <cstdint>
  13. #include <limits>
  14. #include <memory>
  15. #include "rtc_base/checks.h"
  16. #include "rtc_base/logging.h"
  17. // Protect against max macro inclusion.
  18. #undef max
  19. namespace rtc {
  20. // Base class for RNG implementations.
  21. class RandomGenerator {
  22. public:
  23. virtual ~RandomGenerator() {}
  24. virtual bool Init(const void* seed, size_t len) = 0;
  25. virtual bool Generate(void* buf, size_t len) = 0;
  26. };
  27. // The OpenSSL RNG.
  28. class SecureRandomGenerator : public RandomGenerator {
  29. public:
  30. SecureRandomGenerator() {}
  31. ~SecureRandomGenerator() override {}
  32. bool Init(const void* seed, size_t len) override { return true; }
  33. bool Generate(void* buf, size_t len) override {
  34. return (RAND_bytes(reinterpret_cast<unsigned char*>(buf), len) > 0);
  35. }
  36. };
  37. // A test random generator, for predictable output.
  38. class TestRandomGenerator : public RandomGenerator {
  39. public:
  40. TestRandomGenerator() : seed_(7) {}
  41. ~TestRandomGenerator() override {}
  42. bool Init(const void* seed, size_t len) override { return true; }
  43. bool Generate(void* buf, size_t len) override {
  44. for (size_t i = 0; i < len; ++i) {
  45. static_cast<uint8_t*>(buf)[i] = static_cast<uint8_t>(GetRandom());
  46. }
  47. return true;
  48. }
  49. private:
  50. int GetRandom() {
  51. return ((seed_ = seed_ * 214013L + 2531011L) >> 16) & 0x7fff;
  52. }
  53. int seed_;
  54. };
  55. namespace {
  56. // TODO: Use Base64::Base64Table instead.
  57. static const char kBase64[64] = {
  58. 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
  59. 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
  60. 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
  61. 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
  62. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'};
  63. static const char kHex[16] = {'0', '1', '2', '3', '4', '5', '6', '7',
  64. '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
  65. static const char kUuidDigit17[4] = {'8', '9', 'a', 'b'};
  66. // This round about way of creating a global RNG is to safe-guard against
  67. // indeterminant static initialization order.
  68. std::unique_ptr<RandomGenerator>& GetGlobalRng() {
  69. static std::unique_ptr<RandomGenerator>& global_rng =
  70. *new std::unique_ptr<RandomGenerator>(new SecureRandomGenerator());
  71. return global_rng;
  72. }
  73. RandomGenerator& Rng() {
  74. return *GetGlobalRng();
  75. }
  76. } // namespace
  77. void SetRandomTestMode(bool test) {
  78. if (!test) {
  79. GetGlobalRng().reset(new SecureRandomGenerator());
  80. } else {
  81. GetGlobalRng().reset(new TestRandomGenerator());
  82. }
  83. }
  84. bool InitRandom(int seed) {
  85. return InitRandom(reinterpret_cast<const char*>(&seed), sizeof(seed));
  86. }
  87. bool InitRandom(const char* seed, size_t len) {
  88. if (!Rng().Init(seed, len)) {
  89. RTC_LOG(LS_ERROR) << "Failed to init random generator!";
  90. return false;
  91. }
  92. return true;
  93. }
  94. std::string CreateRandomString(size_t len) {
  95. std::string str;
  96. RTC_CHECK(CreateRandomString(len, &str));
  97. return str;
  98. }
  99. static bool CreateRandomString(size_t len,
  100. const char* table,
  101. int table_size,
  102. std::string* str) {
  103. str->clear();
  104. // Avoid biased modulo division below.
  105. if (256 % table_size) {
  106. RTC_LOG(LS_ERROR) << "Table size must divide 256 evenly!";
  107. return false;
  108. }
  109. std::unique_ptr<uint8_t[]> bytes(new uint8_t[len]);
  110. if (!Rng().Generate(bytes.get(), len)) {
  111. RTC_LOG(LS_ERROR) << "Failed to generate random string!";
  112. return false;
  113. }
  114. str->reserve(len);
  115. for (size_t i = 0; i < len; ++i) {
  116. str->push_back(table[bytes[i] % table_size]);
  117. }
  118. return true;
  119. }
  120. bool CreateRandomString(size_t len, std::string* str) {
  121. return CreateRandomString(len, kBase64, 64, str);
  122. }
  123. bool CreateRandomString(size_t len,
  124. const std::string& table,
  125. std::string* str) {
  126. return CreateRandomString(len, table.c_str(), static_cast<int>(table.size()),
  127. str);
  128. }
  129. bool CreateRandomData(size_t length, std::string* data) {
  130. data->resize(length);
  131. // std::string is guaranteed to use contiguous memory in c++11 so we can
  132. // safely write directly to it.
  133. return Rng().Generate(&data->at(0), length);
  134. }
  135. // Version 4 UUID is of the form:
  136. // xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
  137. // Where 'x' is a hex digit, and 'y' is 8, 9, a or b.
  138. std::string CreateRandomUuid() {
  139. std::string str;
  140. std::unique_ptr<uint8_t[]> bytes(new uint8_t[31]);
  141. RTC_CHECK(Rng().Generate(bytes.get(), 31));
  142. str.reserve(36);
  143. for (size_t i = 0; i < 8; ++i) {
  144. str.push_back(kHex[bytes[i] % 16]);
  145. }
  146. str.push_back('-');
  147. for (size_t i = 8; i < 12; ++i) {
  148. str.push_back(kHex[bytes[i] % 16]);
  149. }
  150. str.push_back('-');
  151. str.push_back('4');
  152. for (size_t i = 12; i < 15; ++i) {
  153. str.push_back(kHex[bytes[i] % 16]);
  154. }
  155. str.push_back('-');
  156. str.push_back(kUuidDigit17[bytes[15] % 4]);
  157. for (size_t i = 16; i < 19; ++i) {
  158. str.push_back(kHex[bytes[i] % 16]);
  159. }
  160. str.push_back('-');
  161. for (size_t i = 19; i < 31; ++i) {
  162. str.push_back(kHex[bytes[i] % 16]);
  163. }
  164. return str;
  165. }
  166. uint32_t CreateRandomId() {
  167. uint32_t id;
  168. RTC_CHECK(Rng().Generate(&id, sizeof(id)));
  169. return id;
  170. }
  171. uint64_t CreateRandomId64() {
  172. return static_cast<uint64_t>(CreateRandomId()) << 32 | CreateRandomId();
  173. }
  174. uint32_t CreateRandomNonZeroId() {
  175. uint32_t id;
  176. do {
  177. id = CreateRandomId();
  178. } while (id == 0);
  179. return id;
  180. }
  181. double CreateRandomDouble() {
  182. return CreateRandomId() / (std::numeric_limits<uint32_t>::max() +
  183. std::numeric_limits<double>::epsilon());
  184. }
  185. double GetNextMovingAverage(double prev_average, double cur, double ratio) {
  186. return (ratio * prev_average + cur) / (ratio + 1);
  187. }
  188. } // namespace rtc