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