1 /*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #pragma once
18
19 #include <iomanip>
20 #include <sstream>
21 #include <string>
22 #include <vector>
23
24 namespace android::mediametrics::stringutils {
25
26 // Define a way of printing a vector - this
27 // is used for proto repeated arguments.
28 template <typename T>
29 inline std::ostream & operator<< (std::ostream& s,
30 std::vector<T> const& v) {
31 s << "{ ";
32 for (const auto& e : v) {
33 s << e << " ";
34 }
35 s << "}";
36 return s;
37 }
38
39 /**
40 * fieldPrint is a helper method that logs to a stringstream a sequence of
41 * field names (in a fixed size array) together with a variable number of arg parameters.
42 *
43 * stringstream << field[0] << ":" << arg0 << " ";
44 * stringstream << field[1] << ":" << arg1 << " ";
45 * ...
46 * stringstream << field[N-1] << ":" << arg{N-1} << " ";
47 *
48 * The number of fields must exactly match the (variable) arguments.
49 *
50 * Example:
51 *
52 * const char * const fields[] = { "integer" };
53 * std::stringstream ss;
54 * fieldPrint(ss, fields, int(10));
55 */
56 template <size_t N, typename... Targs>
fieldPrint(std::stringstream & ss,const char * const (& fields)[N],Targs...args)57 void fieldPrint(std::stringstream& ss, const char * const (& fields)[N], Targs... args) {
58 static_assert(N == sizeof...(args)); // guarantee #fields == #args
59 auto fptr = fields; // get a pointer to the base of fields array
60 ((ss << *fptr++ << ":" << args << " "), ...); // (fold expression), send to stringstream.
61 }
62
63 /**
64 * Return string tokens from iterator, separated by spaces and reserved chars.
65 */
66 std::string tokenizer(std::string::const_iterator& it,
67 const std::string::const_iterator& end, const char *reserved);
68
69 /**
70 * Splits flags string based on delimeters (or, whitespace which is removed).
71 */
72 std::vector<std::string> split(const std::string& flags, const char *delim);
73
74 /**
75 * Parses a vector of integers using ',' '{' and '}' as delimeters. Leaves
76 * vector unmodified if the parsing fails.
77 */
78 bool parseVector(const std::string &str, std::vector<int32_t> *vector);
79
80 /**
81 * Parse the devices string and return a vector of device address pairs.
82 *
83 * A failure to parse returns early with the contents that were able to be parsed.
84 */
85 std::vector<std::pair<std::string, std::string>> getDeviceAddressPairs(const std::string &devices);
86
87 /**
88 * Replaces targetChars with replaceChar in string, returns number of chars replaced.
89 */
90 size_t replace(std::string &str, const char *targetChars, const char replaceChar);
91
92 // RFC 1421, 2045, 2152, 4648(4), 4880
93 inline constexpr char Base64Table[] =
94 // 0000000000111111111122222222223333333333444444444455555555556666
95 // 0123456789012345678901234567890123456789012345678901234567890123
96 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
97
98 // RFC 4648(5) URL-safe Base64 encoding
99 inline constexpr char Base64UrlTable[] =
100 // 0000000000111111111122222222223333333333444444444455555555556666
101 // 0123456789012345678901234567890123456789012345678901234567890123
102 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
103
104 // An constexpr struct that transposes/inverts a string conversion table.
105 struct Transpose {
106 // constexpr bug, returning char still means -1 == 0xff, so we use unsigned char.
107 using base_char_t = unsigned char;
108 static inline constexpr base_char_t INVALID_CHAR = 0xff;
109
110 template <size_t N>
TransposeTranspose111 explicit constexpr Transpose(const char(&string)[N]) {
112 for (auto& e : mMap) {
113 e = INVALID_CHAR;
114 }
115 for (size_t i = 0; string[i] != 0; ++i) {
116 mMap[static_cast<size_t>(string[i]) & 0xff] = i;
117 }
118 }
119
120 constexpr base_char_t operator[] (size_t n) const {
121 return n < sizeof(mMap) ? mMap[n] : INVALID_CHAR;
122 }
123
getTranspose124 constexpr const auto& get() const {
125 return mMap;
126 }
127
128 private:
129 base_char_t mMap[256]; // construct an inverse character mapping.
130 };
131
132 // This table is used to convert an input char to a 6 bit (0 - 63) value.
133 // If the input char is not in the Base64Url charset, Transpose::INVALID_CHAR is returned.
134 inline constexpr Transpose InverseBase64UrlTable(Base64UrlTable);
135
136 // Returns true if s consists of only valid Base64Url characters (no padding chars allowed).
isBase64Url(const char * s)137 inline constexpr bool isBase64Url(const char *s) {
138 for (; *s != 0; ++s) {
139 if (InverseBase64UrlTable[(unsigned char)*s] == Transpose::INVALID_CHAR) return false;
140 }
141 return true;
142 }
143
144 // Returns true if s is a valid log session id: exactly 16 Base64Url characters.
145 //
146 // logSessionIds are a web-safe Base64Url RFC 4648(5) encoded string of 16 characters
147 // (representing 96 unique bits 16 * 6).
148 //
149 // The string version is considered the reference representation. However, for ease of
150 // manipulation and comparison, it may be converted to an int128.
151 //
152 // For int128 conversion, some common interpretations exist - for example
153 // (1) the 16 Base64 chars can be converted 6 bits per char to a 96 bit value
154 // (with the most significant 32 bits as zero) as there are only 12 unique bytes worth of data
155 // or (2) the 16 Base64 chars can be used to directly fill the 128 bits of int128 assuming
156 // the 16 chars are 16 bytes, filling the layout of the int128 variable.
157 // Endianness of the data may follow whatever is convenient in the interpretation as long
158 // as it is applied to each such conversion of string to int128 identically.
159 //
isLogSessionId(const char * s)160 inline constexpr bool isLogSessionId(const char *s) {
161 return std::char_traits<std::decay_t<decltype(*s)>>::length(s) == 16 && isBase64Url(s);
162 }
163
164 // Returns either the original string or an empty string if isLogSessionId check fails.
sanitizeLogSessionId(const std::string & string)165 inline std::string sanitizeLogSessionId(const std::string& string) {
166 if (isLogSessionId(string.c_str())) return string;
167 return {}; // if not a logSessionId, return an empty string.
168 }
169
170 inline std::string bytesToString(const std::vector<uint8_t>& bytes, size_t maxSize = SIZE_MAX) {
171 if (bytes.size() == 0) {
172 return "{}";
173 }
174 std::stringstream ss;
175 ss << "{";
176 ss << std::hex << std::setfill('0');
177 maxSize = std::min(maxSize, bytes.size());
178 for (size_t i = 0; i < maxSize; ++i) {
179 ss << " " << std::setw(2) << (int)bytes[i];
180 }
181 if (maxSize != bytes.size()) {
182 ss << " ... }";
183 } else {
184 ss << " }";
185 }
186 return ss.str();
187 }
188
189 /**
190 * Returns true if the string is non-null, not empty, and contains only digits.
191 */
isNumeric(const char * s)192 inline constexpr bool isNumeric(const char *s)
193 {
194 if (s == nullptr || *s == 0) return false;
195 do {
196 if (!isdigit(*s)) return false;
197 } while (*++s != 0);
198 return true; // all digits
199 }
200
201 /**
202 * Extracts out the prefix from the key, returning a pair of prefix, suffix.
203 *
204 * Usually the key is something like:
205 * Prefix.(ID)
206 * where ID is an integer,
207 * or "error" if the id was not returned because of failure,
208 * or "status" if general status.
209 *
210 * Example: audio.track.10 -> prefix = audio.track, suffix = 10
211 * audio.track.error -> prefix = audio.track, suffix = error
212 * audio.track.status -> prefix = audio.track, suffix = status
213 * audio.mute -> prefix = audio.mute, suffix = ""
214 */
215 inline std::pair<std::string /* prefix */,
splitPrefixKey(const std::string & key)216 std::string /* suffix */> splitPrefixKey(const std::string &key)
217 {
218 const size_t split = key.rfind('.');
219 const char* suffix = key.c_str() + split + 1;
220 if (*suffix && (!strcmp(suffix, "error") || !strcmp(suffix, "status") || isNumeric(suffix))) {
221 return { key.substr(0, split), suffix };
222 }
223 return { key, "" };
224 }
225
226 std::pair<std::string /* external statsd */, std::string /* internal */>
227 parseOutputDevicePairs(const std::string& outputDevicePairs);
228
229 std::pair<std::string /* external statsd */, std::string /* internal */>
230 parseInputDevicePairs(const std::string& inputDevicePairs);
231
hasBluetoothOutputDevice(std::string_view devices)232 inline bool hasBluetoothOutputDevice(std::string_view devices) {
233 return devices.find("AUDIO_DEVICE_OUT_BLUETOOTH") != std::string::npos;
234 }
235
236 } // namespace android::mediametrics::stringutils
237