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