blob: 300204aea93d5b292103bbe30657cc0c22986fdb [file] [log] [blame]
Harald Welte468b6432014-09-11 13:05:51 +08001/*
2 * (C) 2011 by Harald Welte <laforge@gnumonks.org>
3 * (C) 2011 by Sylvain Munaut <tnt@246tNt.com>
4 * (C) 2014 by Nils O. SelÄsdal <noselasd@fiane.dyndns.org>
5 *
6 * All Rights Reserved
7 *
Harald Weltee08da972017-11-13 01:00:26 +09008 * SPDX-License-Identifier: GPL-2.0+
9 *
Harald Welte468b6432014-09-11 13:05:51 +080010 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23 *
24 */
25
Harald Welted284cd92010-03-01 21:58:31 +010026
Harald Weltefebe83c2017-10-03 17:41:59 +080027#include <stdbool.h>
Harald Welted284cd92010-03-01 21:58:31 +010028#include <string.h>
29#include <stdint.h>
30#include <errno.h>
Harald Welteb59f9352010-03-25 11:37:04 +080031#include <stdio.h>
Pau Espin Pedrol45735022017-06-18 14:05:24 +020032#include <inttypes.h>
Neels Hofmeyr87c3afb2020-09-30 21:47:47 +000033#include <limits.h>
Harald Welted284cd92010-03-01 21:58:31 +010034
Pablo Neira Ayuso83419342011-03-22 16:36:13 +010035#include <osmocom/core/utils.h>
Harald Welte9709b2e2016-04-25 18:47:53 +020036#include <osmocom/core/bit64gen.h>
37
Harald Welted284cd92010-03-01 21:58:31 +010038
Harald Welte8598f182011-08-17 14:19:27 +020039/*! \addtogroup utils
40 * @{
Neels Hofmeyr87e45502017-06-20 00:17:59 +020041 * various utility routines
Neels Hofmeyr17518fe2017-06-20 04:35:06 +020042 *
43 * \file utils.c */
Harald Welte8598f182011-08-17 14:19:27 +020044
Harald Welte171ef822019-03-28 10:49:05 +010045static __thread char namebuf[255];
Pau Espin Pedrola37f58e2019-08-01 18:11:41 +020046/* shared by osmo_str_tolower() and osmo_str_toupper() */
47static __thread char capsbuf[128];
Harald Welte8598f182011-08-17 14:19:27 +020048
Neels Hofmeyr87e45502017-06-20 00:17:59 +020049/*! get human-readable string for given value
Harald Welte8598f182011-08-17 14:19:27 +020050 * \param[in] vs Array of value_string tuples
51 * \param[in] val Value to be converted
52 * \returns pointer to human-readable string
Neels Hofmeyr8a3c83e2016-06-13 13:16:58 +020053 *
54 * If val is found in vs, the array's string entry is returned. Otherwise, an
55 * "unknown" string containing the actual value is composed in a static buffer
56 * that is reused across invocations.
Harald Welte8598f182011-08-17 14:19:27 +020057 */
Harald Welted284cd92010-03-01 21:58:31 +010058const char *get_value_string(const struct value_string *vs, uint32_t val)
59{
Neels Hofmeyr8d6dcd92016-06-06 18:05:23 +020060 const char *str = get_value_string_or_null(vs, val);
61 if (str)
62 return str;
63
Pau Espin Pedrol45735022017-06-18 14:05:24 +020064 snprintf(namebuf, sizeof(namebuf), "unknown 0x%"PRIx32, val);
Neels Hofmeyr8d6dcd92016-06-06 18:05:23 +020065 namebuf[sizeof(namebuf) - 1] = '\0';
66 return namebuf;
67}
68
Neels Hofmeyr87e45502017-06-20 00:17:59 +020069/*! get human-readable string or NULL for given value
Neels Hofmeyr8d6dcd92016-06-06 18:05:23 +020070 * \param[in] vs Array of value_string tuples
71 * \param[in] val Value to be converted
72 * \returns pointer to human-readable string or NULL if val is not found
73 */
74const char *get_value_string_or_null(const struct value_string *vs,
75 uint32_t val)
76{
Harald Welted284cd92010-03-01 21:58:31 +010077 int i;
78
Neels Hofmeyra0331ed2019-02-11 21:24:40 +010079 if (!vs)
80 return NULL;
81
Harald Welted284cd92010-03-01 21:58:31 +010082 for (i = 0;; i++) {
83 if (vs[i].value == 0 && vs[i].str == NULL)
84 break;
85 if (vs[i].value == val)
86 return vs[i].str;
87 }
Harald Welteb59f9352010-03-25 11:37:04 +080088
Neels Hofmeyr8d6dcd92016-06-06 18:05:23 +020089 return NULL;
Harald Welted284cd92010-03-01 21:58:31 +010090}
91
Neels Hofmeyr87e45502017-06-20 00:17:59 +020092/*! get numeric value for given human-readable string
Harald Welte8598f182011-08-17 14:19:27 +020093 * \param[in] vs Array of value_string tuples
94 * \param[in] str human-readable string
95 * \returns numeric value (>0) or negative numer in case of error
96 */
Harald Welted284cd92010-03-01 21:58:31 +010097int get_string_value(const struct value_string *vs, const char *str)
98{
99 int i;
100
101 for (i = 0;; i++) {
102 if (vs[i].value == 0 && vs[i].str == NULL)
103 break;
104 if (!strcasecmp(vs[i].str, str))
105 return vs[i].value;
106 }
107 return -EINVAL;
108}
Harald Weltea73e2f92010-03-04 10:50:32 +0100109
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200110/*! Convert BCD-encoded digit into printable character
Harald Welte8598f182011-08-17 14:19:27 +0200111 * \param[in] bcd A single BCD-encoded digit
112 * \returns single printable character
113 */
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200114char osmo_bcd2char(uint8_t bcd)
Harald Weltea73e2f92010-03-04 10:50:32 +0100115{
116 if (bcd < 0xa)
117 return '0' + bcd;
118 else
119 return 'A' + (bcd - 0xa);
120}
121
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200122/*! Convert number in ASCII to BCD value
Harald Weltede6e4982012-12-06 21:25:27 +0100123 * \param[in] c ASCII character
124 * \returns BCD encoded value of character
125 */
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200126uint8_t osmo_char2bcd(char c)
Harald Weltea73e2f92010-03-04 10:50:32 +0100127{
Harald Weltefa8983d2017-10-27 16:52:59 +0200128 if (c >= '0' && c <= '9')
129 return c - 0x30;
130 else if (c >= 'A' && c <= 'F')
131 return 0xa + (c - 'A');
132 else if (c >= 'a' && c <= 'f')
133 return 0xa + (c - 'a');
134 else
135 return 0;
Harald Weltea73e2f92010-03-04 10:50:32 +0100136}
Harald Welte3eba9912010-07-30 10:37:29 +0200137
Neels Hofmeyr7079e692018-12-05 21:02:36 +0100138/*! Convert BCD to string.
139 * The given nibble offsets are interpreted in BCD order, i.e. nibble 0 is bcd[0] & 0xf, nibble 1 is bcd[0] >> 4, nibble
140 * 3 is bcd[1] & 0xf, etc..
141 * \param[out] dst Output string buffer, is always nul terminated when dst_size > 0.
142 * \param[in] dst_size sizeof() the output string buffer.
143 * \param[in] bcd Binary coded data buffer.
144 * \param[in] start_nibble Offset to start from, in nibbles, typically 1 to skip the first nibble.
Neels Hofmeyr48b2de02018-12-11 02:13:57 +0100145 * \param[in] end_nibble Offset to stop before, in nibbles, e.g. sizeof(bcd)*2 - (bcd[0] & GSM_MI_ODD? 0:1).
Neels Hofmeyr7079e692018-12-05 21:02:36 +0100146 * \param[in] allow_hex If false, return error if there are digits other than 0-9. If true, return those as [A-F].
147 * \returns The strlen that would be written if the output buffer is large enough, excluding nul byte (like
148 * snprintf()), or -EINVAL if allow_hex is false and a digit > 9 is encountered. On -EINVAL, the conversion is
149 * still completed as if allow_hex were passed as true. Return -ENOMEM if dst is NULL or dst_size is zero.
150 * If end_nibble <= start_nibble, write an empty string to dst and return 0.
151 */
152int osmo_bcd2str(char *dst, size_t dst_size, const uint8_t *bcd, int start_nibble, int end_nibble, bool allow_hex)
153{
154 char *dst_end = dst + dst_size - 1;
155 int nibble_i;
156 int rc = 0;
157
Neels Hofmeyr0b6a8c82020-06-12 16:34:20 +0200158 if (!dst || dst_size < 1 || start_nibble < 0)
Neels Hofmeyr7079e692018-12-05 21:02:36 +0100159 return -ENOMEM;
160
161 for (nibble_i = start_nibble; nibble_i < end_nibble && dst < dst_end; nibble_i++, dst++) {
162 uint8_t nibble = bcd[nibble_i >> 1];
163 if ((nibble_i & 1))
164 nibble >>= 4;
165 nibble &= 0xf;
166
167 if (!allow_hex && nibble > 9)
168 rc = -EINVAL;
169
170 *dst = osmo_bcd2char(nibble);
171 }
172 *dst = '\0';
173
174 if (rc < 0)
175 return rc;
176 return OSMO_MAX(0, end_nibble - start_nibble);
177}
178
Neels Hofmeyr83025bf2020-05-26 02:45:23 +0200179/*! Convert string to BCD.
180 * The given nibble offsets are interpreted in BCD order, i.e. nibble 0 is bcd[0] & 0x0f, nibble 1 is bcd[0] & 0xf0, nibble
181 * 3 is bcd[1] & 0x0f, etc..
182 * \param[out] dst Output BCD buffer.
183 * \param[in] dst_size sizeof() the output string buffer.
184 * \param[in] digits String containing decimal or hexadecimal digits in upper or lower case.
185 * \param[in] start_nibble Offset to start from, in nibbles, typically 1 to skip the first (MI type) nibble.
186 * \param[in] end_nibble Negative to write all digits found in str, followed by 0xf nibbles to fill any started octet.
187 * If >= 0, stop before this offset in nibbles, e.g. to get default behavior, pass
188 * start_nibble + strlen(str) + ((start_nibble + strlen(str)) & 1? 1 : 0) + 1.
189 * \param[in] allow_hex If false, return error if there are hexadecimal digits (A-F). If true, write those to
190 * BCD.
191 * \returns The buffer size in octets that is used to place all bcd digits (including the skipped nibbles
192 * from 'start_nibble' and rounded up to full octets); -EINVAL on invalid digits;
193 * -ENOMEM if dst is NULL, if dst_size is too small to contain all nibbles, or if start_nibble is negative.
194 */
195int osmo_str2bcd(uint8_t *dst, size_t dst_size, const char *digits, int start_nibble, int end_nibble, bool allow_hex)
196{
197 const char *digit = digits;
198 int nibble_i;
199
200 if (!dst || !dst_size || start_nibble < 0)
201 return -ENOMEM;
202
203 if (end_nibble < 0) {
204 end_nibble = start_nibble + strlen(digits);
205 /* If the last octet is not complete, add another filler nibble */
206 if (end_nibble & 1)
207 end_nibble++;
208 }
209 if ((end_nibble / 2) > dst_size)
210 return -ENOMEM;
211
212 for (nibble_i = start_nibble; nibble_i < end_nibble; nibble_i++) {
213 uint8_t nibble = 0xf;
214 int octet = nibble_i >> 1;
215 if (*digit) {
216 char c = *digit;
217 digit++;
218 if (c >= '0' && c <= '9')
219 nibble = c - '0';
220 else if (allow_hex && c >= 'A' && c <= 'F')
221 nibble = 0xa + (c - 'A');
222 else if (allow_hex && c >= 'a' && c <= 'f')
223 nibble = 0xa + (c - 'a');
224 else
225 return -EINVAL;
226 }
227 nibble &= 0xf;
228 if ((nibble_i & 1))
229 dst[octet] = (nibble << 4) | (dst[octet] & 0x0f);
230 else
231 dst[octet] = (dst[octet] & 0xf0) | nibble;
232 }
233
234 /* floor(float(end_nibble) / 2) */
235 return end_nibble / 2;
236}
237
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200238/*! Parse a string containing hexadecimal digits
Harald Weltede6e4982012-12-06 21:25:27 +0100239 * \param[in] str string containing ASCII encoded hexadecimal digits
240 * \param[out] b output buffer
241 * \param[in] max_len maximum space in output buffer
Neels Hofmeyr3de7b052015-09-23 23:16:53 +0200242 * \returns number of parsed octets, or -1 on error
Harald Weltede6e4982012-12-06 21:25:27 +0100243 */
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200244int osmo_hexparse(const char *str, uint8_t *b, int max_len)
Harald Welte3eba9912010-07-30 10:37:29 +0200245
246{
Neels Hofmeyr437ed4a2017-02-14 15:54:31 +0100247 char c;
248 uint8_t v;
249 const char *strpos;
250 unsigned int nibblepos = 0;
Harald Welte3eba9912010-07-30 10:37:29 +0200251
252 memset(b, 0x00, max_len);
253
Neels Hofmeyr437ed4a2017-02-14 15:54:31 +0100254 for (strpos = str; (c = *strpos); strpos++) {
255 /* skip whitespace */
256 if (c == ' ' || c == '\t' || c == '\n' || c == '\r')
257 continue;
258
259 /* If the buffer is too small, error out */
260 if (nibblepos >= (max_len << 1))
261 return -1;
262
Harald Welte3eba9912010-07-30 10:37:29 +0200263 if (c >= '0' && c <= '9')
264 v = c - '0';
265 else if (c >= 'a' && c <= 'f')
266 v = 10 + (c - 'a');
267 else if (c >= 'A' && c <= 'F')
268 v = 10 + (c - 'A');
269 else
270 return -1;
Neels Hofmeyr437ed4a2017-02-14 15:54:31 +0100271
272 b[nibblepos >> 1] |= v << (nibblepos & 1 ? 0 : 4);
273 nibblepos ++;
Harald Welte3eba9912010-07-30 10:37:29 +0200274 }
275
Neels Hofmeyr437ed4a2017-02-14 15:54:31 +0100276 /* In case of uneven amount of digits, the last byte is not complete
277 * and that's an error. */
278 if (nibblepos & 1)
279 return -1;
280
281 return nibblepos >> 1;
Harald Welte3eba9912010-07-30 10:37:29 +0200282}
Harald Welte40481e82010-07-30 11:40:32 +0200283
Harald Welte171ef822019-03-28 10:49:05 +0100284static __thread char hexd_buff[4096];
Nils O. SelÄsdal32447022014-01-02 14:04:43 +0100285static const char hex_chars[] = "0123456789abcdef";
Harald Welte40481e82010-07-30 11:40:32 +0200286
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100287/*! Convert binary sequence to hexadecimal ASCII string.
288 * \param[out] out_buf Output buffer to write the resulting string to.
289 * \param[in] out_buf_size sizeof(out_buf).
290 * \param[in] buf Input buffer, pointer to sequence of bytes.
291 * \param[in] len Length of input buf in number of bytes.
292 * \param[in] delim String to separate each byte; NULL or "" for no delim.
293 * \param[in] delim_after_last If true, end the string in delim (true: "1a:ef:d9:", false: "1a:ef:d9");
294 * if out_buf has insufficient space, the string will always end in a delim.
295 * \returns out_buf, containing a zero-terminated string, or "" (empty string) if out_buf == NULL or out_buf_size < 1.
296 *
297 * This function will print a sequence of bytes as hexadecimal numbers, adding one delim between each byte (e.g. for
298 * delim passed as ":", return a string like "1a:ef:d9").
299 *
300 * The delim_after_last argument exists to be able to exactly show the original osmo_hexdump() behavior, which always
301 * ends the string with a delimiter.
302 */
303const char *osmo_hexdump_buf(char *out_buf, size_t out_buf_size, const unsigned char *buf, int len, const char *delim,
304 bool delim_after_last)
Harald Welte40481e82010-07-30 11:40:32 +0200305{
306 int i;
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100307 char *cur = out_buf;
308 size_t delim_len;
Harald Welte40481e82010-07-30 11:40:32 +0200309
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100310 if (!out_buf || !out_buf_size)
311 return "";
312
313 delim = delim ? : "";
314 delim_len = strlen(delim);
315
Harald Welte40481e82010-07-30 11:40:32 +0200316 for (i = 0; i < len; i++) {
Nils O. SelÄsdal32447022014-01-02 14:04:43 +0100317 const char *delimp = delim;
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100318 int len_remain = out_buf_size - (cur - out_buf) - 1;
319 if (len_remain < (2 + delim_len)
320 && !(!delim_after_last && i == (len - 1) && len_remain >= 2))
Holger Hans Peter Freyther128d9e22011-07-15 16:07:23 +0200321 break;
Nils O. SelÄsdal32447022014-01-02 14:04:43 +0100322
323 *cur++ = hex_chars[buf[i] >> 4];
324 *cur++ = hex_chars[buf[i] & 0xf];
325
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100326 if (i == (len - 1) && !delim_after_last)
327 break;
328
Nils O. SelÄsdal32447022014-01-02 14:04:43 +0100329 while (len_remain > 1 && *delimp) {
330 *cur++ = *delimp++;
331 len_remain--;
332 }
Harald Welte40481e82010-07-30 11:40:32 +0200333 }
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100334 *cur = '\0';
335 return out_buf;
Harald Welte40481e82010-07-30 11:40:32 +0200336}
Harald Weltedee47cd2010-07-30 11:43:30 +0200337
Harald Welte4a62eda2019-03-18 18:27:00 +0100338/*! Convert a sequence of unpacked bits to ASCII string, in user-supplied buffer.
339 * \param[out] buf caller-provided output string buffer
340 * \param[out] buf_len size of buf in bytes
Harald Welte8598f182011-08-17 14:19:27 +0200341 * \param[in] bits A sequence of unpacked bits
342 * \param[in] len Length of bits
Neels Hofmeyrdd7b6f92019-11-20 21:32:29 +0100343 * \return The output buffer (buf).
Harald Welte8598f182011-08-17 14:19:27 +0200344 */
Harald Welte4a62eda2019-03-18 18:27:00 +0100345char *osmo_ubit_dump_buf(char *buf, size_t buf_len, const uint8_t *bits, unsigned int len)
Harald Welte3d0ac5e2011-02-08 16:55:03 +0100346{
347 int i;
348
Harald Welte4a62eda2019-03-18 18:27:00 +0100349 if (len > buf_len-1)
350 len = buf_len-1;
351 memset(buf, 0, buf_len);
Harald Welte3d0ac5e2011-02-08 16:55:03 +0100352
353 for (i = 0; i < len; i++) {
354 char outch;
355 switch (bits[i]) {
356 case 0:
357 outch = '0';
358 break;
359 case 0xff:
360 outch = '?';
361 break;
362 case 1:
363 outch = '1';
364 break;
365 default:
366 outch = 'E';
367 break;
368 }
Harald Welte4a62eda2019-03-18 18:27:00 +0100369 buf[i] = outch;
Harald Welte3d0ac5e2011-02-08 16:55:03 +0100370 }
Harald Welte4a62eda2019-03-18 18:27:00 +0100371 buf[buf_len-1] = 0;
372 return buf;
373}
374
375/*! Convert a sequence of unpacked bits to ASCII string, in static buffer.
376 * \param[in] bits A sequence of unpacked bits
377 * \param[in] len Length of bits
378 * \returns string representation in static buffer.
379 */
380char *osmo_ubit_dump(const uint8_t *bits, unsigned int len)
381{
382 return osmo_ubit_dump_buf(hexd_buff, sizeof(hexd_buff), bits, len);
Harald Welte3d0ac5e2011-02-08 16:55:03 +0100383}
384
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200385/*! Convert binary sequence to hexadecimal ASCII string
Harald Welte8598f182011-08-17 14:19:27 +0200386 * \param[in] buf pointer to sequence of bytes
387 * \param[in] len length of buf in number of bytes
388 * \returns pointer to zero-terminated string
389 *
390 * This function will print a sequence of bytes as hexadecimal numbers,
391 * adding one space character between each byte (e.g. "1a ef d9")
Harald Welte096a6662017-10-16 14:33:11 +0200392 *
393 * The maximum size of the output buffer is 4096 bytes, i.e. the maximum
394 * number of input bytes that can be printed in one call is 1365!
Harald Welte8598f182011-08-17 14:19:27 +0200395 */
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200396char *osmo_hexdump(const unsigned char *buf, int len)
Harald Weltedee47cd2010-07-30 11:43:30 +0200397{
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100398 osmo_hexdump_buf(hexd_buff, sizeof(hexd_buff), buf, len, " ", true);
399 return hexd_buff;
Harald Weltedee47cd2010-07-30 11:43:30 +0200400}
401
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200402/*! Convert binary sequence to hexadecimal ASCII string
Harald Welte179f3572019-03-18 18:38:47 +0100403 * \param[in] ctx talloc context from where to allocate the output string
404 * \param[in] buf pointer to sequence of bytes
405 * \param[in] len length of buf in number of bytes
406 * \returns pointer to zero-terminated string
407 *
408 * This function will print a sequence of bytes as hexadecimal numbers,
409 * adding one space character between each byte (e.g. "1a ef d9")
Harald Welte179f3572019-03-18 18:38:47 +0100410 */
411char *osmo_hexdump_c(const void *ctx, const unsigned char *buf, int len)
412{
Vadim Yanitskiy4f619c22019-04-12 21:48:07 +0700413 size_t hexd_buff_len = len * 3 + 1;
414 char *hexd_buff = talloc_size(ctx, hexd_buff_len);
Harald Welte179f3572019-03-18 18:38:47 +0100415 if (!hexd_buff)
416 return NULL;
Vadim Yanitskiy4f619c22019-04-12 21:48:07 +0700417 osmo_hexdump_buf(hexd_buff, hexd_buff_len, buf, len, " ", true);
Harald Welte179f3572019-03-18 18:38:47 +0100418 return hexd_buff;
419}
420
421/*! Convert binary sequence to hexadecimal ASCII string
Harald Welte8598f182011-08-17 14:19:27 +0200422 * \param[in] buf pointer to sequence of bytes
423 * \param[in] len length of buf in number of bytes
424 * \returns pointer to zero-terminated string
425 *
426 * This function will print a sequence of bytes as hexadecimal numbers,
427 * without any space character between each byte (e.g. "1aefd9")
Harald Welte096a6662017-10-16 14:33:11 +0200428 *
429 * The maximum size of the output buffer is 4096 bytes, i.e. the maximum
430 * number of input bytes that can be printed in one call is 2048!
Harald Welte8598f182011-08-17 14:19:27 +0200431 */
Sylvain Munautff23d242011-11-10 23:03:18 +0100432char *osmo_hexdump_nospc(const unsigned char *buf, int len)
Harald Weltedee47cd2010-07-30 11:43:30 +0200433{
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100434 osmo_hexdump_buf(hexd_buff, sizeof(hexd_buff), buf, len, "", true);
435 return hexd_buff;
Harald Weltedee47cd2010-07-30 11:43:30 +0200436}
Harald Welte28222962011-02-18 20:37:04 +0100437
Harald Welte179f3572019-03-18 18:38:47 +0100438/*! Convert binary sequence to hexadecimal ASCII string
439 * \param[in] ctx talloc context from where to allocate the output string
440 * \param[in] buf pointer to sequence of bytes
441 * \param[in] len length of buf in number of bytes
442 * \returns pointer to zero-terminated string
443 *
444 * This function will print a sequence of bytes as hexadecimal numbers,
445 * without any space character between each byte (e.g. "1aefd9")
Harald Welte179f3572019-03-18 18:38:47 +0100446 */
447char *osmo_hexdump_nospc_c(const void *ctx, const unsigned char *buf, int len)
448{
Vadim Yanitskiy4f619c22019-04-12 21:48:07 +0700449 size_t hexd_buff_len = len * 2 + 1;
450 char *hexd_buff = talloc_size(ctx, hexd_buff_len);
Harald Welte179f3572019-03-18 18:38:47 +0100451 if (!hexd_buff)
452 return NULL;
Vadim Yanitskiy4f619c22019-04-12 21:48:07 +0700453 osmo_hexdump_buf(hexd_buff, hexd_buff_len, buf, len, "", true);
Harald Welte179f3572019-03-18 18:38:47 +0100454 return hexd_buff;
455}
456
457
Holger Hans Peter Freyther9a1a5a12015-04-11 19:26:55 +0200458/* Compat with previous typo to preserve abi */
Sylvain Munaute55ae3a2011-11-11 23:06:55 +0100459char *osmo_osmo_hexdump_nospc(const unsigned char *buf, int len)
Holger Hans Peter Freyther9a1a5a12015-04-11 19:26:55 +0200460#if defined(__MACH__) && defined(__APPLE__)
461 ;
462#else
Sylvain Munaut17af41d2011-11-19 22:30:39 +0100463 __attribute__((weak, alias("osmo_hexdump_nospc")));
Holger Hans Peter Freyther9a1a5a12015-04-11 19:26:55 +0200464#endif
Sylvain Munaute55ae3a2011-11-11 23:06:55 +0100465
Harald Welte28222962011-02-18 20:37:04 +0100466#include "../config.h"
467#ifdef HAVE_CTYPE_H
468#include <ctype.h>
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200469/*! Convert an entire string to lower case
Harald Welte8598f182011-08-17 14:19:27 +0200470 * \param[out] out output string, caller-allocated
471 * \param[in] in input string
472 */
Harald Welte28222962011-02-18 20:37:04 +0100473void osmo_str2lower(char *out, const char *in)
474{
475 unsigned int i;
476
477 for (i = 0; i < strlen(in); i++)
Pau Espin Pedrol399a6f02017-06-18 14:07:37 +0200478 out[i] = tolower((const unsigned char)in[i]);
Harald Welte28222962011-02-18 20:37:04 +0100479 out[strlen(in)] = '\0';
480}
481
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200482/*! Convert an entire string to upper case
Harald Welte8598f182011-08-17 14:19:27 +0200483 * \param[out] out output string, caller-allocated
484 * \param[in] in input string
485 */
Harald Welte28222962011-02-18 20:37:04 +0100486void osmo_str2upper(char *out, const char *in)
487{
488 unsigned int i;
489
490 for (i = 0; i < strlen(in); i++)
Pau Espin Pedrol399a6f02017-06-18 14:07:37 +0200491 out[i] = toupper((const unsigned char)in[i]);
Harald Welte28222962011-02-18 20:37:04 +0100492 out[strlen(in)] = '\0';
493}
494#endif /* HAVE_CTYPE_H */
Harald Welte8598f182011-08-17 14:19:27 +0200495
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200496/*! Wishful thinking to generate a constant time compare
Harald Welte9709b2e2016-04-25 18:47:53 +0200497 * \param[in] exp Expected data
498 * \param[in] rel Comparison value
499 * \param[in] count Number of bytes to compare
500 * \returns 1 in case \a exp equals \a rel; zero otherwise
501 *
502 * Compare count bytes of exp to rel. Return 0 if they are identical, 1
503 * otherwise. Do not return a mismatch on the first mismatching byte,
504 * but always compare all bytes, regardless. The idea is that the amount of
505 * matching bytes cannot be inferred from the time the comparison took. */
506int osmo_constant_time_cmp(const uint8_t *exp, const uint8_t *rel, const int count)
507{
508 int x = 0, i;
509
510 for (i = 0; i < count; ++i)
511 x |= exp[i] ^ rel[i];
512
513 /* if x is zero, all data was identical */
514 return x? 1 : 0;
515}
516
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200517/*! Generic retrieval of 1..8 bytes as big-endian uint64_t
Harald Welte9709b2e2016-04-25 18:47:53 +0200518 * \param[in] data Input data as byte-array
519 * \param[in] data_len Length of \a data in octets
520 * \returns uint64_t of \a data interpreted as big-endian
521 *
522 * This is like osmo_load64be_ext, except that if data_len is less than
523 * sizeof(uint64_t), the data is interpreted as the least significant bytes
524 * (osmo_load64be_ext loads them as the most significant bytes into the
525 * returned uint64_t). In this way, any integer size up to 64 bits can be
526 * decoded conveniently by using sizeof(), without the need to call specific
527 * numbered functions (osmo_load16, 32, ...). */
528uint64_t osmo_decode_big_endian(const uint8_t *data, size_t data_len)
529{
530 uint64_t value = 0;
531
532 while (data_len > 0) {
533 value = (value << 8) + *data;
534 data += 1;
535 data_len -= 1;
536 }
537
538 return value;
539}
540
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200541/*! Generic big-endian encoding of big endian number up to 64bit
Harald Welte9709b2e2016-04-25 18:47:53 +0200542 * \param[in] value unsigned integer value to be stored
Pau Espin Pedrolc29d5132020-09-21 17:09:31 +0200543 * \param[in] data_len number of octets
Harald Welte9709b2e2016-04-25 18:47:53 +0200544 * \returns static buffer containing big-endian stored value
545 *
546 * This is like osmo_store64be_ext, except that this returns a static buffer of
547 * the result (for convenience, but not threadsafe). If data_len is less than
548 * sizeof(uint64_t), only the least significant bytes of value are encoded. */
549uint8_t *osmo_encode_big_endian(uint64_t value, size_t data_len)
550{
Harald Welte171ef822019-03-28 10:49:05 +0100551 static __thread uint8_t buf[sizeof(uint64_t)];
Harald Welte9709b2e2016-04-25 18:47:53 +0200552 OSMO_ASSERT(data_len <= ARRAY_SIZE(buf));
553 osmo_store64be_ext(value, buf, data_len);
554 return buf;
555}
Harald Welteaeecc482016-11-26 10:41:40 +0100556
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200557/*! Copy a C-string into a sized buffer
Harald Welteaeecc482016-11-26 10:41:40 +0100558 * \param[in] src source string
559 * \param[out] dst destination string
Neels Hofmeyrdf83ece2017-01-13 13:55:43 +0100560 * \param[in] siz size of the \a dst buffer
561 * \returns length of \a src
Harald Welteaeecc482016-11-26 10:41:40 +0100562 *
Neels Hofmeyrdf83ece2017-01-13 13:55:43 +0100563 * Copy at most \a siz bytes from \a src to \a dst, ensuring that the result is
564 * NUL terminated. The NUL character is included in \a siz, i.e. passing the
565 * actual sizeof(*dst) is correct.
Neels Hofmeyrff65d242019-11-19 00:21:14 +0100566 *
567 * Note, a similar function that also limits the input buffer size is osmo_print_n().
Harald Welteaeecc482016-11-26 10:41:40 +0100568 */
569size_t osmo_strlcpy(char *dst, const char *src, size_t siz)
570{
Neels Hofmeyrbcf9f232017-10-25 04:16:45 +0200571 size_t ret = src ? strlen(src) : 0;
Harald Welteaeecc482016-11-26 10:41:40 +0100572
573 if (siz) {
Pau Espin Pedrol53fbc672020-09-21 17:13:30 +0200574 size_t len = OSMO_MIN(siz - 1, ret);
Pau Espin Pedrolc29d5132020-09-21 17:09:31 +0200575 if (len)
Neels Hofmeyrebd3cdd2017-11-18 23:07:38 +0100576 memcpy(dst, src, len);
Harald Welteaeecc482016-11-26 10:41:40 +0100577 dst[len] = '\0';
578 }
579 return ret;
580}
Neels Hofmeyr0aeda1b2017-01-13 14:16:02 +0100581
Neels Hofmeyr06356fd2019-11-19 01:38:10 +0100582/*! Find first occurence of a char in a size limited string.
583 * Like strchr() but with a buffer size limit.
584 * \param[in] str String buffer to examine.
585 * \param[in] str_size sizeof(str).
586 * \param[in] c Character to look for.
587 * \return Pointer to the matched char, or NULL if not found.
588 */
589const char *osmo_strnchr(const char *str, size_t str_size, char c)
590{
591 const char *end = str + str_size;
592 const char *pos;
593 if (!str)
594 return NULL;
595 for (pos = str; pos < end; pos++) {
596 if (c == *pos)
597 return pos;
598 if (!*pos)
599 return NULL;
600 }
601 return NULL;
602}
603
Neels Hofmeyr4335bad2017-10-07 04:39:14 +0200604/*! Validate that a given string is a hex string within given size limits.
605 * Note that each hex digit amounts to a nibble, so if checking for a hex
606 * string to result in N bytes, pass amount of digits as 2*N.
607 * \param str A nul-terminated string to validate, or NULL.
608 * \param min_digits least permitted amount of digits.
609 * \param max_digits most permitted amount of digits.
610 * \param require_even if true, require an even amount of digits.
611 * \returns true when the hex_str contains only hexadecimal digits (no
612 * whitespace) and matches the requested length; also true
613 * when min_digits <= 0 and str is NULL.
614 */
615bool osmo_is_hexstr(const char *str, int min_digits, int max_digits,
616 bool require_even)
617{
618 int len;
619 /* Use unsigned char * to avoid a compiler warning of
620 * "error: array subscript has type 'char' [-Werror=char-subscripts]" */
621 const unsigned char *pos = (const unsigned char*)str;
622 if (!pos)
623 return min_digits < 1;
624 for (len = 0; *pos && len < max_digits; len++, pos++)
625 if (!isxdigit(*pos))
626 return false;
627 if (len < min_digits)
628 return false;
629 /* With not too many digits, we should have reached *str == nul */
630 if (*pos)
631 return false;
632 if (require_even && (len & 1))
633 return false;
Harald Weltefebe83c2017-10-03 17:41:59 +0800634
635 return true;
636}
637
Neels Hofmeyrb480b742019-04-11 06:58:44 +0200638static const char osmo_identifier_illegal_chars[] = "., {}[]()<>|~\\^`'\"?=;/+*&%$#!";
639
Harald Weltefebe83c2017-10-03 17:41:59 +0800640/*! Determine if a given identifier is valid, i.e. doesn't contain illegal chars
641 * \param[in] str String to validate
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100642 * \param[in] sep_chars Permitted separation characters between identifiers.
643 * \returns true in case \a str contains only valid identifiers and sep_chars, false otherwise
Harald Weltefebe83c2017-10-03 17:41:59 +0800644 */
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100645bool osmo_separated_identifiers_valid(const char *str, const char *sep_chars)
Harald Weltefebe83c2017-10-03 17:41:59 +0800646{
647 /* characters that are illegal in names */
Harald Weltefebe83c2017-10-03 17:41:59 +0800648 unsigned int i;
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100649 size_t len;
Harald Weltefebe83c2017-10-03 17:41:59 +0800650
651 /* an empty string is not a valid identifier */
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100652 if (!str || (len = strlen(str)) == 0)
Harald Weltefebe83c2017-10-03 17:41:59 +0800653 return false;
654
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100655 for (i = 0; i < len; i++) {
656 if (sep_chars && strchr(sep_chars, str[i]))
657 continue;
Harald Weltefebe83c2017-10-03 17:41:59 +0800658 /* check for 7-bit ASCII */
659 if (str[i] & 0x80)
660 return false;
Neels Hofmeyre5a2bdb2017-12-16 04:54:37 +0100661 if (!isprint((int)str[i]))
662 return false;
Harald Weltefebe83c2017-10-03 17:41:59 +0800663 /* check for some explicit reserved control characters */
Neels Hofmeyrb480b742019-04-11 06:58:44 +0200664 if (strchr(osmo_identifier_illegal_chars, str[i]))
Harald Weltefebe83c2017-10-03 17:41:59 +0800665 return false;
666 }
667
Neels Hofmeyr4335bad2017-10-07 04:39:14 +0200668 return true;
669}
670
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100671/*! Determine if a given identifier is valid, i.e. doesn't contain illegal chars
672 * \param[in] str String to validate
673 * \returns true in case \a str contains valid identifier, false otherwise
674 */
675bool osmo_identifier_valid(const char *str)
676{
677 return osmo_separated_identifiers_valid(str, NULL);
678}
679
Neels Hofmeyrb480b742019-04-11 06:58:44 +0200680/*! Replace characters in the given string buffer so that it is guaranteed to pass osmo_separated_identifiers_valid().
681 * To guarantee passing osmo_separated_identifiers_valid(), replace_with must not itself be an illegal character. If in
682 * doubt, use '-'.
683 * \param[inout] str Identifier to sanitize, must be nul terminated and in a writable buffer.
Neels Hofmeyr5aa421f2021-07-07 23:50:29 +0200684 * \param[in] sep_chars Additional characters that are to be replaced besides osmo_identifier_illegal_chars.
Neels Hofmeyrb480b742019-04-11 06:58:44 +0200685 * \param[in] replace_with Replace any illegal characters with this character.
686 */
687void osmo_identifier_sanitize_buf(char *str, const char *sep_chars, char replace_with)
688{
689 char *pos;
690 if (!str)
691 return;
692 for (pos = str; *pos; pos++) {
693 if (strchr(osmo_identifier_illegal_chars, *pos)
694 || (sep_chars && strchr(sep_chars, *pos)))
695 *pos = replace_with;
696 }
697}
698
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100699/*! Like osmo_escape_str_buf2, but with unusual ordering of arguments, and may sometimes return string constants instead
700 * of writing to buf for error cases or empty input.
701 * Most *_buf() functions have the buffer and size as first arguments, here the arguments are last.
702 * In particular, this function signature doesn't work with OSMO_STRBUF_APPEND_NOLEN().
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100703 * \param[in] str A string that may contain any characters.
704 * \param[in] len Pass -1 to print until nul char, or >= 0 to force a length.
705 * \param[inout] buf string buffer to write escaped characters to.
706 * \param[in] bufsize size of \a buf.
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100707 * \returns buf containing an escaped representation, possibly truncated,
708 * or "(null)" if str == NULL, or "(error)" in case of errors.
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100709 */
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100710const char *osmo_escape_str_buf(const char *str, int in_len, char *buf, size_t bufsize)
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100711{
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100712 if (!str)
713 return "(null)";
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100714 if (!buf || !bufsize)
715 return "(error)";
716 return osmo_escape_str_buf2(buf, bufsize, str, in_len);
717}
718
719/*! Copy N characters to a buffer with a function signature useful for OSMO_STRBUF_APPEND().
720 * Similarly to snprintf(), the result is always nul terminated (except if buf is NULL or bufsize is 0).
721 * \param[out] buf Target buffer.
722 * \param[in] bufsize sizeof(buf).
723 * \param[in] str String to copy.
724 * \param[in] n Maximum number of non-nul characters to copy.
725 * \return Number of characters that would be written if bufsize were large enough excluding '\0' (like snprintf()).
726 */
727int osmo_print_n(char *buf, size_t bufsize, const char *str, size_t n)
728{
729 size_t write_n;
730
731 if (!str)
732 str = "";
733
734 n = strnlen(str, n);
735
736 if (!buf || !bufsize)
737 return n;
738 write_n = n;
739 if (write_n >= bufsize)
740 write_n = bufsize - 1;
741 if (write_n)
742 strncpy(buf, str, write_n);
743 buf[write_n] = '\0';
744
745 return n;
746}
747
748/*! Return the string with all non-printable characters escaped.
Neels Hofmeyrc36e2e42019-11-20 21:57:32 +0100749 * This internal function is the implementation for all osmo_escape_str* and osmo_quote_str* API versions.
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100750 * It provides both the legacy (non C compatible) escaping, as well as C compatible string constant syntax,
751 * and it provides a return value of characters-needed, to allow producing un-truncated strings in all cases.
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100752 * \param[out] buf string buffer to write escaped characters to.
753 * \param[in] bufsize sizeof(buf).
754 * \param[in] str A string that may contain any characters.
755 * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length (also past nul chars).
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100756 * \param[in] legacy_format If false, return C compatible string constants ("\x0f"), if true the legacy
757 * escaping format ("\15"). The legacy format also escapes as "\a\b\f\v", while
758 * the non-legacy format also escapes those as "\xNN" sequences.
Neels Hofmeyrc36e2e42019-11-20 21:57:32 +0100759 * \return Number of characters that would be written if bufsize were large enough excluding '\0' (like snprintf()).
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100760 */
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100761static size_t _osmo_escape_str_buf(char *buf, size_t bufsize, const char *str, int in_len, bool legacy_format)
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100762{
763 struct osmo_strbuf sb = { .buf = buf, .len = bufsize };
764 int in_pos = 0;
765 int next_unprintable = 0;
766
767 if (!str)
768 in_len = 0;
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100769
770 if (in_len < 0)
771 in_len = strlen(str);
772
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100773 /* Make sure of '\0' termination */
774 if (!in_len)
775 OSMO_STRBUF_PRINTF(sb, "%s", "");
776
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100777 while (in_pos < in_len) {
778 for (next_unprintable = in_pos;
779 next_unprintable < in_len && isprint((int)str[next_unprintable])
780 && str[next_unprintable] != '"'
781 && str[next_unprintable] != '\\';
782 next_unprintable++);
783
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100784 OSMO_STRBUF_APPEND(sb, osmo_print_n, &str[in_pos], next_unprintable - in_pos);
785 in_pos = next_unprintable;
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100786
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100787 if (in_pos == in_len)
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100788 goto done;
789
790 switch (str[next_unprintable]) {
791#define BACKSLASH_CASE(c, repr) \
792 case c: \
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100793 OSMO_STRBUF_PRINTF(sb, "\\%c", repr); \
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100794 break
795
796 BACKSLASH_CASE('\n', 'n');
797 BACKSLASH_CASE('\r', 'r');
798 BACKSLASH_CASE('\t', 't');
799 BACKSLASH_CASE('\0', '0');
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100800 BACKSLASH_CASE('\\', '\\');
801 BACKSLASH_CASE('"', '"');
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100802
803 default:
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100804 if (legacy_format) {
805 switch (str[next_unprintable]) {
806 BACKSLASH_CASE('\a', 'a');
807 BACKSLASH_CASE('\b', 'b');
808 BACKSLASH_CASE('\v', 'v');
809 BACKSLASH_CASE('\f', 'f');
810 default:
811 OSMO_STRBUF_PRINTF(sb, "\\%u", (unsigned char)str[in_pos]);
812 break;
813 }
814 break;
815 }
816
817 OSMO_STRBUF_PRINTF(sb, "\\x%02x", (unsigned char)str[in_pos]);
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100818 break;
819 }
820 in_pos ++;
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100821#undef BACKSLASH_CASE
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100822 }
823
824done:
Neels Hofmeyrc36e2e42019-11-20 21:57:32 +0100825 return sb.chars_needed;
826}
827
828/*! Return the string with all non-printable characters escaped.
829 * \param[out] buf string buffer to write escaped characters to.
830 * \param[in] bufsize sizeof(buf).
831 * \param[in] str A string that may contain any characters.
832 * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length (also past nul chars).
833 * \return The output buffer (buf).
834 */
835char *osmo_escape_str_buf2(char *buf, size_t bufsize, const char *str, int in_len)
836{
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100837 _osmo_escape_str_buf(buf, bufsize, str, in_len, true);
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100838 return buf;
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100839}
840
841/*! Return the string with all non-printable characters escaped.
842 * Call osmo_escape_str_buf() with a static buffer.
843 * \param[in] str A string that may contain any characters.
844 * \param[in] len Pass -1 to print until nul char, or >= 0 to force a length.
845 * \returns buf containing an escaped representation, possibly truncated, or str itself.
846 */
847const char *osmo_escape_str(const char *str, int in_len)
848{
849 return osmo_escape_str_buf(str, in_len, namebuf, sizeof(namebuf));
850}
851
Harald Welte179f3572019-03-18 18:38:47 +0100852/*! Return the string with all non-printable characters escaped, in dynamically-allocated buffer.
853 * \param[in] str A string that may contain any characters.
854 * \param[in] len Pass -1 to print until nul char, or >= 0 to force a length.
855 * \returns dynamically-allocated output buffer, containing an escaped representation
856 */
857char *osmo_escape_str_c(const void *ctx, const char *str, int in_len)
858{
Neels Hofmeyrc36e2e42019-11-20 21:57:32 +0100859 /* The string will be at least as long as in_len, but some characters might need escaping.
860 * These extra bytes should catch most usual escaping situations, avoiding a second run in OSMO_NAME_C_IMPL. */
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100861 OSMO_NAME_C_IMPL(ctx, in_len + 16, "ERROR", _osmo_escape_str_buf, str, in_len, true);
Neels Hofmeyrc36e2e42019-11-20 21:57:32 +0100862}
863
864/*! Return a quoted and escaped representation of the string.
865 * This internal function is the implementation for all osmo_quote_str* API versions.
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100866 * It provides both the legacy (non C compatible) escaping, as well as C compatible string constant syntax,
867 * and it provides a return value of characters-needed, to allow producing un-truncated strings in all cases.
Neels Hofmeyrc36e2e42019-11-20 21:57:32 +0100868 * \param[out] buf string buffer to write escaped characters to.
869 * \param[in] bufsize sizeof(buf).
870 * \param[in] str A string that may contain any characters.
871 * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length (also past nul chars).
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100872 * \param[in] legacy_format If false, return C compatible string constants ("\x0f"), if true the legacy
873 * escaping format ("\15"). The legacy format also escapes as "\a\b\f\v", while
874 * the non-legacy format also escapes those as "\xNN" sequences.
Neels Hofmeyrc36e2e42019-11-20 21:57:32 +0100875 * \return Number of characters that would be written if bufsize were large enough excluding '\0' (like snprintf()).
876 */
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100877static size_t _osmo_quote_str_buf(char *buf, size_t bufsize, const char *str, int in_len, bool legacy_format)
Neels Hofmeyrc36e2e42019-11-20 21:57:32 +0100878{
879 struct osmo_strbuf sb = { .buf = buf, .len = bufsize };
880 if (!str)
881 OSMO_STRBUF_PRINTF(sb, "NULL");
882 else {
883 OSMO_STRBUF_PRINTF(sb, "\"");
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100884 OSMO_STRBUF_APPEND(sb, _osmo_escape_str_buf, str, in_len, legacy_format);
Neels Hofmeyrc36e2e42019-11-20 21:57:32 +0100885 OSMO_STRBUF_PRINTF(sb, "\"");
886 }
887 return sb.chars_needed;
Harald Welte179f3572019-03-18 18:38:47 +0100888}
889
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100890/*! Like osmo_escape_str_buf2(), but returns double-quotes around a string, or "NULL" for a NULL string.
Neels Hofmeyr04eb56f2018-04-09 00:41:28 +0200891 * This allows passing any char* value and get its C representation as string.
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100892 * The function signature is suitable for OSMO_STRBUF_APPEND_NOLEN().
893 * \param[out] buf string buffer to write escaped characters to.
894 * \param[in] bufsize sizeof(buf).
895 * \param[in] str A string that may contain any characters.
896 * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length.
Neels Hofmeyrdd7b6f92019-11-20 21:32:29 +0100897 * \return The output buffer (buf).
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100898 */
899char *osmo_quote_str_buf2(char *buf, size_t bufsize, const char *str, int in_len)
900{
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100901 _osmo_quote_str_buf(buf, bufsize, str, in_len, true);
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100902 return buf;
903}
904
905/*! Like osmo_quote_str_buf2, but with unusual ordering of arguments, and may sometimes return string constants instead
906 * of writing to buf for error cases or empty input.
907 * Most *_buf() functions have the buffer and size as first arguments, here the arguments are last.
908 * In particular, this function signature doesn't work with OSMO_STRBUF_APPEND_NOLEN().
Neels Hofmeyr04eb56f2018-04-09 00:41:28 +0200909 * \param[in] str A string that may contain any characters.
Neels Hofmeyr03e75532018-09-07 03:12:05 +0200910 * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length.
911 * \returns buf containing a quoted and escaped representation, possibly truncated.
Neels Hofmeyr04eb56f2018-04-09 00:41:28 +0200912 */
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100913const char *osmo_quote_str_buf(const char *str, int in_len, char *buf, size_t bufsize)
Neels Hofmeyr04eb56f2018-04-09 00:41:28 +0200914{
Neels Hofmeyr04eb56f2018-04-09 00:41:28 +0200915 if (!str)
916 return "NULL";
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100917 if (!buf || !bufsize)
918 return "(error)";
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100919 _osmo_quote_str_buf(buf, bufsize, str, in_len, true);
Neels Hofmeyr04eb56f2018-04-09 00:41:28 +0200920 return buf;
921}
922
Neels Hofmeyr03e75532018-09-07 03:12:05 +0200923/*! Like osmo_quote_str_buf() but returns the result in a static buffer.
924 * The static buffer is shared with get_value_string() and osmo_escape_str().
925 * \param[in] str A string that may contain any characters.
926 * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length.
927 * \returns static buffer containing a quoted and escaped representation, possibly truncated.
928 */
Neels Hofmeyr04eb56f2018-04-09 00:41:28 +0200929const char *osmo_quote_str(const char *str, int in_len)
930{
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100931 _osmo_quote_str_buf(namebuf, sizeof(namebuf), str, in_len, true);
Neels Hofmeyrc36e2e42019-11-20 21:57:32 +0100932 return namebuf;
Neels Hofmeyr04eb56f2018-04-09 00:41:28 +0200933}
934
Harald Welte179f3572019-03-18 18:38:47 +0100935/*! Like osmo_quote_str_buf() but returns the result in a dynamically-allocated buffer.
Harald Welte179f3572019-03-18 18:38:47 +0100936 * \param[in] str A string that may contain any characters.
937 * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length.
938 * \returns dynamically-allocated buffer containing a quoted and escaped representation.
939 */
940char *osmo_quote_str_c(const void *ctx, const char *str, int in_len)
941{
Neels Hofmeyrc36e2e42019-11-20 21:57:32 +0100942 /* The string will be at least as long as in_len, but some characters might need escaping.
943 * These extra bytes should catch most usual escaping situations, avoiding a second run in OSMO_NAME_C_IMPL. */
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100944 OSMO_NAME_C_IMPL(ctx, in_len + 16, "ERROR", _osmo_quote_str_buf, str, in_len, true);
945}
946
947/*! Return the string with all non-printable characters escaped.
948 * In contrast to osmo_escape_str_buf2(), this returns the needed buffer size suitable for OSMO_STRBUF_APPEND(), and
949 * this escapes characters in a way compatible with C string constant syntax.
950 * \param[out] buf string buffer to write escaped characters to.
951 * \param[in] bufsize sizeof(buf).
952 * \param[in] str A string that may contain any characters.
953 * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length (also past nul chars).
954 * \return Number of characters that would be written if bufsize were large enough excluding '\0' (like snprintf()).
955 */
956size_t osmo_escape_cstr_buf(char *buf, size_t bufsize, const char *str, int in_len)
957{
958 return _osmo_escape_str_buf(buf, bufsize, str, in_len, false);
959}
960
961/*! Return the string with all non-printable characters escaped, in dynamically-allocated buffer.
962 * In contrast to osmo_escape_str_c(), this escapes characters in a way compatible with C string constant syntax, and
963 * allocates sufficient memory in all cases.
964 * \param[in] str A string that may contain any characters.
965 * \param[in] len Pass -1 to print until nul char, or >= 0 to force a length.
966 * \returns dynamically-allocated buffer, containing an escaped representation.
967 */
968char *osmo_escape_cstr_c(void *ctx, const char *str, int in_len)
969{
970 /* The string will be at least as long as in_len, but some characters might need escaping.
971 * These extra bytes should catch most usual escaping situations, avoiding a second run in OSMO_NAME_C_IMPL. */
972 OSMO_NAME_C_IMPL(ctx, in_len + 16, "ERROR", _osmo_escape_str_buf, str, in_len, false);
973}
974
975/*! Like osmo_escape_str_buf2(), but returns double-quotes around a string, or "NULL" for a NULL string.
976 * This allows passing any char* value and get its C representation as string.
977 * The function signature is suitable for OSMO_STRBUF_APPEND_NOLEN().
978 * In contrast to osmo_escape_str_buf2(), this returns the needed buffer size suitable for OSMO_STRBUF_APPEND(), and
979 * this escapes characters in a way compatible with C string constant syntax.
980 * \param[out] buf string buffer to write escaped characters to.
981 * \param[in] bufsize sizeof(buf).
982 * \param[in] str A string that may contain any characters.
983 * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length.
984 * \return Number of characters that would be written if bufsize were large enough excluding '\0' (like snprintf()).
985 */
986size_t osmo_quote_cstr_buf(char *buf, size_t bufsize, const char *str, int in_len)
987{
988 return _osmo_quote_str_buf(buf, bufsize, str, in_len, false);
989}
990
991/*! Return the string quoted and with all non-printable characters escaped, in dynamically-allocated buffer.
992 * In contrast to osmo_quote_str_c(), this escapes characters in a way compatible with C string constant syntax, and
993 * allocates sufficient memory in all cases.
994 * \param[in] str A string that may contain any characters.
995 * \param[in] len Pass -1 to print until nul char, or >= 0 to force a length.
996 * \returns dynamically-allocated buffer, containing a quoted and escaped representation.
997 */
998char *osmo_quote_cstr_c(void *ctx, const char *str, int in_len)
999{
1000 /* The string will be at least as long as in_len plus two quotes, but some characters might need escaping.
1001 * These extra bytes should catch most usual escaping situations, avoiding a second run in OSMO_NAME_C_IMPL. */
1002 OSMO_NAME_C_IMPL(ctx, in_len + 16, "ERROR", _osmo_quote_str_buf, str, in_len, false);
Harald Welte179f3572019-03-18 18:38:47 +01001003}
1004
Harald Welte15a5f8d2018-06-06 16:58:17 +02001005/*! perform an integer square root operation on unsigned 32bit integer.
1006 * This implementation is taken from "Hacker's Delight" Figure 11-1 "Integer square root, Newton's
1007 * method", which can also be found at http://www.hackersdelight.org/hdcodetxt/isqrt.c.txt */
1008uint32_t osmo_isqrt32(uint32_t x)
1009{
1010 uint32_t x1;
1011 int s, g0, g1;
1012
1013 if (x <= 1)
1014 return x;
1015
1016 s = 1;
1017 x1 = x - 1;
1018 if (x1 > 0xffff) {
1019 s = s + 8;
1020 x1 = x1 >> 16;
1021 }
1022 if (x1 > 0xff) {
1023 s = s + 4;
1024 x1 = x1 >> 8;
1025 }
1026 if (x1 > 0xf) {
1027 s = s + 2;
1028 x1 = x1 >> 4;
1029 }
1030 if (x1 > 0x3) {
1031 s = s + 1;
1032 }
1033
1034 g0 = 1 << s; /* g0 = 2**s */
1035 g1 = (g0 + (x >> s)) >> 1; /* g1 = (g0 + x/g0)/2 */
1036
1037 /* converges after four to five divisions for arguments up to 16,785,407 */
1038 while (g1 < g0) {
1039 g0 = g1;
1040 g1 = (g0 + (x/g0)) >> 1;
1041 }
1042 return g0;
1043}
1044
Neels Hofmeyr7c749892018-09-07 03:01:38 +02001045/*! Convert a string to lowercase, while checking buffer size boundaries.
1046 * The result written to \a dest is guaranteed to be nul terminated if \a dest_len > 0.
1047 * If dest == src, the string is converted in-place, if necessary truncated at dest_len - 1 characters
1048 * length as well as nul terminated.
1049 * Note: similar osmo_str2lower(), but safe to use for src strings of arbitrary length.
1050 * \param[out] dest Target buffer to write lowercase string.
1051 * \param[in] dest_len Maximum buffer size of dest (e.g. sizeof(dest)).
1052 * \param[in] src String to convert to lowercase.
1053 * \returns Length of \a src, like osmo_strlcpy(), but if \a dest == \a src at most \a dest_len - 1.
1054 */
1055size_t osmo_str_tolower_buf(char *dest, size_t dest_len, const char *src)
1056{
1057 size_t rc;
1058 if (dest == src) {
1059 if (dest_len < 1)
1060 return 0;
1061 dest[dest_len - 1] = '\0';
1062 rc = strlen(dest);
1063 } else {
1064 if (dest_len < 1)
1065 return strlen(src);
1066 rc = osmo_strlcpy(dest, src, dest_len);
1067 }
1068 for (; *dest; dest++)
1069 *dest = tolower(*dest);
1070 return rc;
1071}
1072
1073/*! Convert a string to lowercase, using a static buffer.
1074 * The resulting string may be truncated if the internally used static buffer is shorter than src.
1075 * The internal buffer is at least 128 bytes long, i.e. guaranteed to hold at least 127 characters and a
Pau Espin Pedrola37f58e2019-08-01 18:11:41 +02001076 * terminating nul. The static buffer returned is shared with osmo_str_toupper().
Neels Hofmeyr7c749892018-09-07 03:01:38 +02001077 * See also osmo_str_tolower_buf().
1078 * \param[in] src String to convert to lowercase.
1079 * \returns Resulting lowercase string in a static buffer, always nul terminated.
1080 */
1081const char *osmo_str_tolower(const char *src)
1082{
Pau Espin Pedrola37f58e2019-08-01 18:11:41 +02001083 osmo_str_tolower_buf(capsbuf, sizeof(capsbuf), src);
1084 return capsbuf;
Neels Hofmeyr7c749892018-09-07 03:01:38 +02001085}
1086
Harald Welte179f3572019-03-18 18:38:47 +01001087/*! Convert a string to lowercase, dynamically allocating the output from given talloc context
1088 * See also osmo_str_tolower_buf().
1089 * \param[in] ctx talloc context from where to allocate the output string
1090 * \param[in] src String to convert to lowercase.
1091 * \returns Resulting lowercase string in a dynamically allocated buffer, always nul terminated.
1092 */
1093char *osmo_str_tolower_c(const void *ctx, const char *src)
1094{
Vadim Yanitskiy4f619c22019-04-12 21:48:07 +07001095 size_t buf_len = strlen(src) + 1;
1096 char *buf = talloc_size(ctx, buf_len);
Harald Welte179f3572019-03-18 18:38:47 +01001097 if (!buf)
1098 return NULL;
Vadim Yanitskiy4f619c22019-04-12 21:48:07 +07001099 osmo_str_tolower_buf(buf, buf_len, src);
Harald Welte179f3572019-03-18 18:38:47 +01001100 return buf;
1101}
1102
Neels Hofmeyr7c749892018-09-07 03:01:38 +02001103/*! Convert a string to uppercase, while checking buffer size boundaries.
1104 * The result written to \a dest is guaranteed to be nul terminated if \a dest_len > 0.
1105 * If dest == src, the string is converted in-place, if necessary truncated at dest_len - 1 characters
1106 * length as well as nul terminated.
1107 * Note: similar osmo_str2upper(), but safe to use for src strings of arbitrary length.
1108 * \param[out] dest Target buffer to write uppercase string.
1109 * \param[in] dest_len Maximum buffer size of dest (e.g. sizeof(dest)).
1110 * \param[in] src String to convert to uppercase.
1111 * \returns Length of \a src, like osmo_strlcpy(), but if \a dest == \a src at most \a dest_len - 1.
1112 */
1113size_t osmo_str_toupper_buf(char *dest, size_t dest_len, const char *src)
1114{
1115 size_t rc;
1116 if (dest == src) {
1117 if (dest_len < 1)
1118 return 0;
1119 dest[dest_len - 1] = '\0';
1120 rc = strlen(dest);
1121 } else {
1122 if (dest_len < 1)
1123 return strlen(src);
1124 rc = osmo_strlcpy(dest, src, dest_len);
1125 }
1126 for (; *dest; dest++)
1127 *dest = toupper(*dest);
1128 return rc;
1129}
1130
1131/*! Convert a string to uppercase, using a static buffer.
1132 * The resulting string may be truncated if the internally used static buffer is shorter than src.
1133 * The internal buffer is at least 128 bytes long, i.e. guaranteed to hold at least 127 characters and a
Pau Espin Pedrola37f58e2019-08-01 18:11:41 +02001134 * terminating nul. The static buffer returned is shared with osmo_str_tolower().
Neels Hofmeyr7c749892018-09-07 03:01:38 +02001135 * See also osmo_str_toupper_buf().
1136 * \param[in] src String to convert to uppercase.
1137 * \returns Resulting uppercase string in a static buffer, always nul terminated.
1138 */
1139const char *osmo_str_toupper(const char *src)
1140{
Pau Espin Pedrola37f58e2019-08-01 18:11:41 +02001141 osmo_str_toupper_buf(capsbuf, sizeof(capsbuf), src);
1142 return capsbuf;
Neels Hofmeyr7c749892018-09-07 03:01:38 +02001143}
1144
Harald Welte179f3572019-03-18 18:38:47 +01001145/*! Convert a string to uppercase, dynamically allocating the output from given talloc context
1146 * See also osmo_str_tolower_buf().
1147 * \param[in] ctx talloc context from where to allocate the output string
1148 * \param[in] src String to convert to uppercase.
1149 * \returns Resulting uppercase string in a dynamically allocated buffer, always nul terminated.
1150 */
1151char *osmo_str_toupper_c(const void *ctx, const char *src)
1152{
Vadim Yanitskiy4f619c22019-04-12 21:48:07 +07001153 size_t buf_len = strlen(src) + 1;
1154 char *buf = talloc_size(ctx, buf_len);
Harald Welte179f3572019-03-18 18:38:47 +01001155 if (!buf)
1156 return NULL;
Vadim Yanitskiy4f619c22019-04-12 21:48:07 +07001157 osmo_str_toupper_buf(buf, buf_len, src);
Harald Welte179f3572019-03-18 18:38:47 +01001158 return buf;
1159}
1160
Oliver Smith894be2d2019-01-11 13:13:37 +01001161/*! Calculate the Luhn checksum (as used for IMEIs).
1162 * \param[in] in Input digits in ASCII string representation.
1163 * \param[in] in_len Count of digits to use for the input (14 for IMEI).
1164 * \returns checksum char (e.g. '3'); negative on error
1165 */
Vadim Yanitskiyd9fc6042019-06-12 15:49:03 +07001166char osmo_luhn(const char* in, int in_len)
Oliver Smith894be2d2019-01-11 13:13:37 +01001167{
1168 int i, sum = 0;
1169
1170 /* All input must be numbers */
1171 for (i = 0; i < in_len; i++) {
KĂ©vin Redon1af2cd52019-05-23 19:00:19 +02001172 if (!isdigit((unsigned char)in[i]))
Oliver Smith894be2d2019-01-11 13:13:37 +01001173 return -EINVAL;
1174 }
1175
1176 /* Double every second digit and add it to sum */
1177 for (i = in_len - 1; i >= 0; i -= 2) {
1178 int dbl = (in[i] - '0') * 2;
1179 if (dbl > 9)
1180 dbl -= 9;
1181 sum += dbl;
1182 }
1183
1184 /* Add other digits to sum */
1185 for (i = in_len - 2; i >= 0; i -= 2)
1186 sum += in[i] - '0';
1187
1188 /* Final checksum */
1189 return (sum * 9) % 10 + '0';
1190}
1191
Neels Hofmeyrd79ccc62019-03-07 23:08:40 +01001192/*! Compare start of a string.
1193 * This is an optimisation of 'strstr(str, startswith_str) == str' because it doesn't search through the entire string.
1194 * \param str (Longer) string to compare.
1195 * \param startswith_str (Shorter) string to compare with the start of str.
1196 * \return true iff the first characters of str fully match startswith_str or startswith_str is empty. */
1197bool osmo_str_startswith(const char *str, const char *startswith_str)
1198{
1199 if (!startswith_str || !*startswith_str)
1200 return true;
1201 if (!str)
1202 return false;
1203 return strncmp(str, startswith_str, strlen(startswith_str)) == 0;
1204}
1205
Neels Hofmeyr87c3afb2020-09-30 21:47:47 +00001206/*! Convert a string of a floating point number to a signed int, with a decimal factor (fixed-point precision).
1207 * For example, with precision=3, convert "-1.23" to -1230. In other words, the float value is multiplied by
1208 * 10 to-the-power-of precision to obtain the returned integer.
1209 * The usable range of digits is -INT64_MAX .. INT64_MAX -- note, not INT64_MIN! The value of INT64_MIN is excluded to
1210 * reduce implementation complexity. See also utils_test.c.
Neels Hofmeyr6d744982020-10-08 13:09:49 +02001211 * The advantage over using sscanf("%f") is guaranteed precision: float or double types may apply rounding in the
1212 * conversion result. osmo_float_str_to_int() and osmo_int_to_float_str_buf() guarantee true results when converting
1213 * back and forth between string and int.
Neels Hofmeyr87c3afb2020-09-30 21:47:47 +00001214 * \param[out] val Returned integer value.
1215 * \param[in] str String of a float, like '-12.345'.
Neels Hofmeyr87c3afb2020-09-30 21:47:47 +00001216 * \param[in] precision Fixed-point precision, or * \returns 0 on success, negative on error.
1217 */
1218int osmo_float_str_to_int(int64_t *val, const char *str, unsigned int precision)
1219{
1220 const char *point;
1221 char *endptr;
1222 const char *p;
1223 int64_t sign = 1;
1224 int64_t integer = 0;
1225 int64_t decimal = 0;
1226 int64_t precision_factor;
1227 int64_t integer_max;
1228 int64_t decimal_max;
1229 int i;
1230
1231 OSMO_ASSERT(val);
1232 *val = 0;
1233
1234 if (!str)
1235 return -EINVAL;
1236 if (str[0] == '-') {
1237 str = str + 1;
1238 sign = -1;
1239 } else if (str[0] == '+') {
1240 str = str + 1;
1241 }
1242 if (!str[0])
1243 return -EINVAL;
1244
1245 /* Validate entire string as purely digits and at most one decimal dot. If not doing this here in advance,
1246 * parsing digits might stop early because of precision cut-off and miss validation of input data. */
1247 point = NULL;
1248 for (p = str; *p; p++) {
1249 if (*p == '.') {
1250 if (point)
1251 return -EINVAL;
1252 point = p;
Eric79f29032021-11-19 12:58:39 +01001253 } else if (!isdigit((unsigned char)*p))
Neels Hofmeyr87c3afb2020-09-30 21:47:47 +00001254 return -EINVAL;
1255 }
1256
1257 /* Parse integer part if there is one. If the string starts with a point, there's nothing to parse for the
1258 * integer part. */
1259 if (!point || point > str) {
1260 errno = 0;
1261 integer = strtoll(str, &endptr, 10);
Harald Weltecb11a602020-10-09 10:08:44 +02001262 if ((errno == ERANGE && (integer == LLONG_MAX || integer == LLONG_MIN))
Neels Hofmeyr87c3afb2020-09-30 21:47:47 +00001263 || (errno != 0 && integer == 0))
1264 return -ERANGE;
1265
1266 if ((point && endptr != point)
1267 || (!point && *endptr))
1268 return -EINVAL;
1269 }
1270
1271 /* Parse the fractional part if there is any, and if the precision is nonzero (if we even care about fractional
1272 * digits) */
1273 if (precision && point && point[1] != '\0') {
1274 /* limit the number of digits parsed to 'precision'.
1275 * If 'precision' is larger than the 19 digits representable in int64_t, skip some, to pick up lower
1276 * magnitude digits. */
1277 unsigned int skip_digits = (precision < 20) ? 0 : precision - 20;
1278 char decimal_str[precision + 1];
1279 osmo_strlcpy(decimal_str, point+1, precision+1);
1280
1281 /* fill with zeros to make exactly 'precision' digits */
1282 for (i = strlen(decimal_str); i < precision; i++)
1283 decimal_str[i] = '0';
1284 decimal_str[precision] = '\0';
1285
1286 for (i = 0; i < skip_digits; i++) {
1287 /* When skipping digits because precision > nr-of-digits-in-int64_t, they must be zero;
1288 * if there is a nonzero digit above the precision, it's -ERANGE. */
1289 if (decimal_str[i] != '0')
1290 return -ERANGE;
1291 }
1292 errno = 0;
1293 decimal = strtoll(decimal_str + skip_digits, &endptr, 10);
Harald Weltecb11a602020-10-09 10:08:44 +02001294 if ((errno == ERANGE && (decimal == LLONG_MAX || decimal == LLONG_MIN))
Neels Hofmeyr87c3afb2020-09-30 21:47:47 +00001295 || (errno != 0 && decimal == 0))
1296 return -ERANGE;
1297
1298 if (*endptr)
1299 return -EINVAL;
1300 }
1301
1302 if (precision > 18) {
1303 /* Special case of returning more digits than fit in int64_t range, e.g.
1304 * osmo_float_str_to_int("0.0000000012345678901234567", precision=25) -> 12345678901234567. */
1305 precision_factor = 0;
1306 integer_max = 0;
1307 decimal_max = INT64_MAX;
1308 } else {
1309 /* Do not surpass the resulting int64_t range. Depending on the amount of precision, the integer part
1310 * and decimal part have specific ranges they must comply to. */
1311 precision_factor = 1;
1312 for (i = 0; i < precision; i++)
1313 precision_factor *= 10;
1314 integer_max = INT64_MAX / precision_factor;
1315 if (integer == integer_max)
1316 decimal_max = INT64_MAX % precision_factor;
1317 else
1318 decimal_max = INT64_MAX;
1319 }
1320
1321 if (integer > integer_max)
1322 return -ERANGE;
1323 if (decimal > decimal_max)
1324 return -ERANGE;
1325
1326 *val = sign * (integer * precision_factor + decimal);
1327 return 0;
1328}
1329
Neels Hofmeyr6d744982020-10-08 13:09:49 +02001330/*! Convert an integer to a floating point string using a decimal quotient (fixed-point precision).
Neels Hofmeyr87c3afb2020-09-30 21:47:47 +00001331 * For example, with precision = 3, convert -1230 to "-1.23".
Neels Hofmeyr6d744982020-10-08 13:09:49 +02001332 * The usable range of digits is -INT64_MAX .. INT64_MAX -- note, not INT64_MIN! The value of INT64_MIN is excluded to
1333 * reduce implementation complexity. See also utils_test.c.
1334 * The advantage over using printf("%.6g") is guaranteed precision: float or double types may apply rounding in the
1335 * conversion result. osmo_float_str_to_int() and osmo_int_to_float_str_buf() guarantee true results when converting
1336 * back and forth between string and int.
1337 * The resulting string omits trailing zeros in the fractional part (like "%g" would) but never applies rounding.
Neels Hofmeyr87c3afb2020-09-30 21:47:47 +00001338 * \param[out] buf Buffer to write string to.
1339 * \param[in] buflen sizeof(buf).
1340 * \param[in] val Value to convert to float.
1341 * \returns number of chars that would be written, like snprintf().
1342 */
1343int osmo_int_to_float_str_buf(char *buf, size_t buflen, int64_t val, unsigned int precision)
1344{
1345 struct osmo_strbuf sb = { .buf = buf, .len = buflen };
1346 unsigned int i;
1347 unsigned int w;
1348 int64_t precision_factor;
1349 if (val < 0) {
1350 OSMO_STRBUF_PRINTF(sb, "-");
1351 if (val == INT64_MIN) {
1352 OSMO_STRBUF_PRINTF(sb, "ERR");
1353 return sb.chars_needed;
1354 }
1355 val = -val;
1356 }
1357
1358 if (precision > 18) {
1359 /* Special case of returning more digits than fit in int64_t range, e.g.
1360 * osmo_int_to_float_str(12345678901234567, precision=25) -> "0.0000000012345678901234567". */
1361 if (!val) {
1362 OSMO_STRBUF_PRINTF(sb, "0");
1363 return sb.chars_needed;
1364 }
1365 OSMO_STRBUF_PRINTF(sb, "0.");
1366 for (i = 19; i < precision; i++)
1367 OSMO_STRBUF_PRINTF(sb, "0");
1368 precision = 19;
1369 } else {
1370 precision_factor = 1;
1371 for (i = 0; i < precision; i++)
1372 precision_factor *= 10;
1373
1374 OSMO_STRBUF_PRINTF(sb, "%" PRId64, val / precision_factor);
1375 val %= precision_factor;
1376 if (!val)
1377 return sb.chars_needed;
1378 OSMO_STRBUF_PRINTF(sb, ".");
1379 }
1380
1381 /* print fractional part, skip trailing zeros */
1382 w = precision;
1383 while (!(val % 10)) {
1384 val /= 10;
1385 w--;
1386 }
1387 OSMO_STRBUF_PRINTF(sb, "%0*" PRId64, w, val);
1388 return sb.chars_needed;
1389}
1390
1391/*! Convert an integer with a factor of a million to a floating point string.
1392 * For example, convert -1230000 to "-1.23".
1393 * \param[in] ctx Talloc ctx to allocate string buffer from.
1394 * \param[in] val Value to convert to float.
1395 * \returns resulting string, dynamically allocated.
1396 */
1397char *osmo_int_to_float_str_c(void *ctx, int64_t val, unsigned int precision)
1398{
1399 OSMO_NAME_C_IMPL(ctx, 16, "ERROR", osmo_int_to_float_str_buf, val, precision)
1400}
1401
Neels Hofmeyr47773342021-09-05 18:48:31 +02001402/*! Convert a string of a number to int64_t, including all common strtoll() validity checks.
1403 * It's not so trivial to call strtoll() and properly verify that the input string was indeed a valid number string.
1404 * \param[out] result Buffer for the resulting integer number, or NULL if the caller is only interested in the
1405 * validation result (returned rc).
1406 * \param[in] str The string to convert.
1407 * \param[in] base The integer base, i.e. 10 for decimal numbers or 16 for hexadecimal, as in strtoll().
1408 * \param[in] min_val The smallest valid number expected in the string.
1409 * \param[in] max_val The largest valid number expected in the string.
1410 * \return 0 on success, -EOVERFLOW if the number in the string exceeds int64_t, -ENOTSUPP if the base is not supported,
1411 * -ERANGE if the converted number exceeds the range [min_val..max_val] but is still within int64_t range, -E2BIG if
1412 * surplus characters follow after the number, -EINVAL if the string does not contain a number. In case of -ERANGE and
1413 * -E2BIG, the converted number is still accurately returned in result. In case of -EOVERFLOW, the returned value is
1414 * clamped to INT64_MIN..INT64_MAX.
1415 */
1416int osmo_str_to_int64(int64_t *result, const char *str, int base, int64_t min_val, int64_t max_val)
1417{
1418 long long int val;
1419 char *endptr;
1420 if (result)
1421 *result = 0;
1422 if (!str || !*str)
1423 return -EINVAL;
1424 errno = 0;
1425 val = strtoll(str, &endptr, base);
1426 /* In case the number string exceeds long long int range, strtoll() clamps the returned value to LLONG_MIN or
1427 * LLONG_MAX. Make sure of the same here with respect to int64_t. */
1428 if (val < INT64_MIN) {
1429 if (result)
1430 *result = INT64_MIN;
1431 return -ERANGE;
1432 }
1433 if (val > INT64_MAX) {
1434 if (result)
1435 *result = INT64_MAX;
1436 return -ERANGE;
1437 }
1438 if (result)
1439 *result = (int64_t)val;
1440 switch (errno) {
1441 case 0:
1442 break;
1443 case ERANGE:
1444 return -EOVERFLOW;
1445 default:
1446 case EINVAL:
1447 return -ENOTSUP;
1448 }
1449 if (!endptr || *endptr) {
1450 /* No chars were converted */
1451 if (endptr == str)
1452 return -EINVAL;
1453 /* Or there are surplus chars after the converted number */
1454 return -E2BIG;
1455 }
1456 if (val < min_val || val > max_val)
1457 return -ERANGE;
1458 return 0;
1459}
1460
1461/*! Convert a string of a number to int, including all common strtoll() validity checks.
1462 * Same as osmo_str_to_int64() but using the plain int data type.
1463 * \param[out] result Buffer for the resulting integer number, or NULL if the caller is only interested in the
1464 * validation result (returned rc).
1465 * \param[in] str The string to convert.
1466 * \param[in] base The integer base, i.e. 10 for decimal numbers or 16 for hexadecimal, as in strtoll().
1467 * \param[in] min_val The smallest valid number expected in the string.
1468 * \param[in] max_val The largest valid number expected in the string.
1469 * \return 0 on success, -EOVERFLOW if the number in the string exceeds int range, -ENOTSUPP if the base is not supported,
1470 * -ERANGE if the converted number exceeds the range [min_val..max_val] but is still within int range, -E2BIG if
1471 * surplus characters follow after the number, -EINVAL if the string does not contain a number. In case of -ERANGE and
1472 * -E2BIG, the converted number is still accurately returned in result. In case of -EOVERFLOW, the returned value is
1473 * clamped to INT_MIN..INT_MAX.
1474 */
1475int osmo_str_to_int(int *result, const char *str, int base, int min_val, int max_val)
1476{
1477 int64_t val;
1478 int rc = osmo_str_to_int64(&val, str, base, min_val, max_val);
1479 /* In case the number string exceeds long long int range, strtoll() clamps the returned value to LLONG_MIN or
1480 * LLONG_MAX. Make sure of the same here with respect to int. */
1481 if (val < INT_MIN) {
1482 if (result)
1483 *result = INT_MIN;
1484 return -EOVERFLOW;
1485 }
1486 if (val > INT_MAX) {
1487 if (result)
1488 *result = INT_MAX;
1489 return -EOVERFLOW;
1490 }
1491 if (result)
1492 *result = (int)val;
1493 return rc;
1494}
1495
Vadim Yanitskiyc5497192021-06-07 16:30:28 +02001496/*! Replace a string using talloc and release its prior content (if any).
1497 * This is a format string capable equivalent of osmo_talloc_replace_string().
1498 * \param[in] ctx Talloc context to use for allocation.
1499 * \param[out] dst Pointer to string, will be updated with ptr to new string.
1500 * \param[in] fmt Format string that will be copied to newly allocated string. */
1501void osmo_talloc_replace_string_fmt(void *ctx, char **dst, const char *fmt, ...)
1502{
1503 char *name = NULL;
1504
1505 if (fmt != NULL) {
1506 va_list ap;
1507
1508 va_start(ap, fmt);
1509 name = talloc_vasprintf(ctx, fmt, ap);
1510 va_end(ap);
1511 }
1512
1513 talloc_free(*dst);
1514 *dst = name;
1515}
1516
Neels Hofmeyr0aeda1b2017-01-13 14:16:02 +01001517/*! @} */