blob: 1ec940d02b8e58435c23aa78f4f4e945e1a57508 [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 *
Harald Welte468b6432014-09-11 13:05:51 +080020 */
21
Harald Welted284cd92010-03-01 21:58:31 +010022
Harald Weltefebe83c2017-10-03 17:41:59 +080023#include <stdbool.h>
Harald Welted284cd92010-03-01 21:58:31 +010024#include <string.h>
25#include <stdint.h>
26#include <errno.h>
Harald Welteb59f9352010-03-25 11:37:04 +080027#include <stdio.h>
Pau Espin Pedrol45735022017-06-18 14:05:24 +020028#include <inttypes.h>
Neels Hofmeyr87c3afb2020-09-30 21:47:47 +000029#include <limits.h>
Harald Welted284cd92010-03-01 21:58:31 +010030
Pablo Neira Ayuso83419342011-03-22 16:36:13 +010031#include <osmocom/core/utils.h>
Harald Welte9709b2e2016-04-25 18:47:53 +020032#include <osmocom/core/bit64gen.h>
33
Harald Welted284cd92010-03-01 21:58:31 +010034
Harald Welte8598f182011-08-17 14:19:27 +020035/*! \addtogroup utils
36 * @{
Neels Hofmeyr87e45502017-06-20 00:17:59 +020037 * various utility routines
Neels Hofmeyr17518fe2017-06-20 04:35:06 +020038 *
39 * \file utils.c */
Harald Welte8598f182011-08-17 14:19:27 +020040
Harald Welte171ef822019-03-28 10:49:05 +010041static __thread char namebuf[255];
Pau Espin Pedrola37f58e2019-08-01 18:11:41 +020042/* shared by osmo_str_tolower() and osmo_str_toupper() */
43static __thread char capsbuf[128];
Harald Welte8598f182011-08-17 14:19:27 +020044
Neels Hofmeyr87e45502017-06-20 00:17:59 +020045/*! get human-readable string for given value
Harald Welte8598f182011-08-17 14:19:27 +020046 * \param[in] vs Array of value_string tuples
47 * \param[in] val Value to be converted
48 * \returns pointer to human-readable string
Neels Hofmeyr8a3c83e2016-06-13 13:16:58 +020049 *
50 * If val is found in vs, the array's string entry is returned. Otherwise, an
51 * "unknown" string containing the actual value is composed in a static buffer
52 * that is reused across invocations.
Harald Welte8598f182011-08-17 14:19:27 +020053 */
Harald Welted284cd92010-03-01 21:58:31 +010054const char *get_value_string(const struct value_string *vs, uint32_t val)
55{
Neels Hofmeyr8d6dcd92016-06-06 18:05:23 +020056 const char *str = get_value_string_or_null(vs, val);
57 if (str)
58 return str;
59
Pau Espin Pedrol45735022017-06-18 14:05:24 +020060 snprintf(namebuf, sizeof(namebuf), "unknown 0x%"PRIx32, val);
Neels Hofmeyr8d6dcd92016-06-06 18:05:23 +020061 namebuf[sizeof(namebuf) - 1] = '\0';
62 return namebuf;
63}
64
Neels Hofmeyr87e45502017-06-20 00:17:59 +020065/*! get human-readable string or NULL for given value
Neels Hofmeyr8d6dcd92016-06-06 18:05:23 +020066 * \param[in] vs Array of value_string tuples
67 * \param[in] val Value to be converted
68 * \returns pointer to human-readable string or NULL if val is not found
69 */
70const char *get_value_string_or_null(const struct value_string *vs,
71 uint32_t val)
72{
Harald Welted284cd92010-03-01 21:58:31 +010073 int i;
74
Neels Hofmeyra0331ed2019-02-11 21:24:40 +010075 if (!vs)
76 return NULL;
77
Harald Welted284cd92010-03-01 21:58:31 +010078 for (i = 0;; i++) {
79 if (vs[i].value == 0 && vs[i].str == NULL)
80 break;
81 if (vs[i].value == val)
82 return vs[i].str;
83 }
Harald Welteb59f9352010-03-25 11:37:04 +080084
Neels Hofmeyr8d6dcd92016-06-06 18:05:23 +020085 return NULL;
Harald Welted284cd92010-03-01 21:58:31 +010086}
87
Neels Hofmeyr87e45502017-06-20 00:17:59 +020088/*! get numeric value for given human-readable string
Harald Welte8598f182011-08-17 14:19:27 +020089 * \param[in] vs Array of value_string tuples
90 * \param[in] str human-readable string
91 * \returns numeric value (>0) or negative numer in case of error
92 */
Harald Welted284cd92010-03-01 21:58:31 +010093int get_string_value(const struct value_string *vs, const char *str)
94{
95 int i;
96
97 for (i = 0;; i++) {
98 if (vs[i].value == 0 && vs[i].str == NULL)
99 break;
100 if (!strcasecmp(vs[i].str, str))
101 return vs[i].value;
102 }
103 return -EINVAL;
104}
Harald Weltea73e2f92010-03-04 10:50:32 +0100105
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200106/*! Convert BCD-encoded digit into printable character
Harald Welte8598f182011-08-17 14:19:27 +0200107 * \param[in] bcd A single BCD-encoded digit
108 * \returns single printable character
109 */
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200110char osmo_bcd2char(uint8_t bcd)
Harald Weltea73e2f92010-03-04 10:50:32 +0100111{
112 if (bcd < 0xa)
113 return '0' + bcd;
114 else
115 return 'A' + (bcd - 0xa);
116}
117
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200118/*! Convert number in ASCII to BCD value
Harald Weltede6e4982012-12-06 21:25:27 +0100119 * \param[in] c ASCII character
120 * \returns BCD encoded value of character
121 */
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200122uint8_t osmo_char2bcd(char c)
Harald Weltea73e2f92010-03-04 10:50:32 +0100123{
Harald Weltefa8983d2017-10-27 16:52:59 +0200124 if (c >= '0' && c <= '9')
125 return c - 0x30;
126 else if (c >= 'A' && c <= 'F')
127 return 0xa + (c - 'A');
128 else if (c >= 'a' && c <= 'f')
129 return 0xa + (c - 'a');
130 else
131 return 0;
Harald Weltea73e2f92010-03-04 10:50:32 +0100132}
Harald Welte3eba9912010-07-30 10:37:29 +0200133
Neels Hofmeyr7079e692018-12-05 21:02:36 +0100134/*! Convert BCD to string.
135 * The given nibble offsets are interpreted in BCD order, i.e. nibble 0 is bcd[0] & 0xf, nibble 1 is bcd[0] >> 4, nibble
136 * 3 is bcd[1] & 0xf, etc..
137 * \param[out] dst Output string buffer, is always nul terminated when dst_size > 0.
138 * \param[in] dst_size sizeof() the output string buffer.
139 * \param[in] bcd Binary coded data buffer.
140 * \param[in] start_nibble Offset to start from, in nibbles, typically 1 to skip the first nibble.
Neels Hofmeyr48b2de02018-12-11 02:13:57 +0100141 * \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 +0100142 * \param[in] allow_hex If false, return error if there are digits other than 0-9. If true, return those as [A-F].
143 * \returns The strlen that would be written if the output buffer is large enough, excluding nul byte (like
144 * snprintf()), or -EINVAL if allow_hex is false and a digit > 9 is encountered. On -EINVAL, the conversion is
145 * still completed as if allow_hex were passed as true. Return -ENOMEM if dst is NULL or dst_size is zero.
146 * If end_nibble <= start_nibble, write an empty string to dst and return 0.
147 */
148int osmo_bcd2str(char *dst, size_t dst_size, const uint8_t *bcd, int start_nibble, int end_nibble, bool allow_hex)
149{
Vadim Yanitskiy5ce01312023-12-31 15:18:20 +0700150 char *dst_end;
Neels Hofmeyr7079e692018-12-05 21:02:36 +0100151 int nibble_i;
152 int rc = 0;
153
Neels Hofmeyr0b6a8c82020-06-12 16:34:20 +0200154 if (!dst || dst_size < 1 || start_nibble < 0)
Neels Hofmeyr7079e692018-12-05 21:02:36 +0100155 return -ENOMEM;
156
Vadim Yanitskiy5ce01312023-12-31 15:18:20 +0700157 dst_end = dst + dst_size - 1;
158
Neels Hofmeyr7079e692018-12-05 21:02:36 +0100159 for (nibble_i = start_nibble; nibble_i < end_nibble && dst < dst_end; nibble_i++, dst++) {
160 uint8_t nibble = bcd[nibble_i >> 1];
161 if ((nibble_i & 1))
162 nibble >>= 4;
163 nibble &= 0xf;
164
165 if (!allow_hex && nibble > 9)
166 rc = -EINVAL;
167
168 *dst = osmo_bcd2char(nibble);
169 }
170 *dst = '\0';
171
172 if (rc < 0)
173 return rc;
174 return OSMO_MAX(0, end_nibble - start_nibble);
175}
176
Neels Hofmeyr83025bf2020-05-26 02:45:23 +0200177/*! Convert string to BCD.
178 * The given nibble offsets are interpreted in BCD order, i.e. nibble 0 is bcd[0] & 0x0f, nibble 1 is bcd[0] & 0xf0, nibble
179 * 3 is bcd[1] & 0x0f, etc..
180 * \param[out] dst Output BCD buffer.
181 * \param[in] dst_size sizeof() the output string buffer.
182 * \param[in] digits String containing decimal or hexadecimal digits in upper or lower case.
183 * \param[in] start_nibble Offset to start from, in nibbles, typically 1 to skip the first (MI type) nibble.
184 * \param[in] end_nibble Negative to write all digits found in str, followed by 0xf nibbles to fill any started octet.
185 * If >= 0, stop before this offset in nibbles, e.g. to get default behavior, pass
186 * start_nibble + strlen(str) + ((start_nibble + strlen(str)) & 1? 1 : 0) + 1.
187 * \param[in] allow_hex If false, return error if there are hexadecimal digits (A-F). If true, write those to
188 * BCD.
189 * \returns The buffer size in octets that is used to place all bcd digits (including the skipped nibbles
190 * from 'start_nibble' and rounded up to full octets); -EINVAL on invalid digits;
191 * -ENOMEM if dst is NULL, if dst_size is too small to contain all nibbles, or if start_nibble is negative.
192 */
193int osmo_str2bcd(uint8_t *dst, size_t dst_size, const char *digits, int start_nibble, int end_nibble, bool allow_hex)
194{
195 const char *digit = digits;
196 int nibble_i;
197
198 if (!dst || !dst_size || start_nibble < 0)
199 return -ENOMEM;
200
201 if (end_nibble < 0) {
202 end_nibble = start_nibble + strlen(digits);
203 /* If the last octet is not complete, add another filler nibble */
204 if (end_nibble & 1)
205 end_nibble++;
206 }
Harald Welte7d6166a2022-01-09 11:57:01 +0100207 if ((unsigned int) (end_nibble / 2) > dst_size)
Neels Hofmeyr83025bf2020-05-26 02:45:23 +0200208 return -ENOMEM;
209
210 for (nibble_i = start_nibble; nibble_i < end_nibble; nibble_i++) {
211 uint8_t nibble = 0xf;
212 int octet = nibble_i >> 1;
213 if (*digit) {
214 char c = *digit;
215 digit++;
216 if (c >= '0' && c <= '9')
217 nibble = c - '0';
218 else if (allow_hex && c >= 'A' && c <= 'F')
219 nibble = 0xa + (c - 'A');
220 else if (allow_hex && c >= 'a' && c <= 'f')
221 nibble = 0xa + (c - 'a');
222 else
223 return -EINVAL;
224 }
225 nibble &= 0xf;
226 if ((nibble_i & 1))
227 dst[octet] = (nibble << 4) | (dst[octet] & 0x0f);
228 else
229 dst[octet] = (dst[octet] & 0xf0) | nibble;
230 }
231
232 /* floor(float(end_nibble) / 2) */
233 return end_nibble / 2;
234}
235
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200236/*! Parse a string containing hexadecimal digits
Harald Weltede6e4982012-12-06 21:25:27 +0100237 * \param[in] str string containing ASCII encoded hexadecimal digits
238 * \param[out] b output buffer
239 * \param[in] max_len maximum space in output buffer
Neels Hofmeyr3de7b052015-09-23 23:16:53 +0200240 * \returns number of parsed octets, or -1 on error
Harald Weltede6e4982012-12-06 21:25:27 +0100241 */
Harald Welte7d6166a2022-01-09 11:57:01 +0100242int osmo_hexparse(const char *str, uint8_t *b, unsigned int max_len)
Harald Welte3eba9912010-07-30 10:37:29 +0200243
244{
Neels Hofmeyr437ed4a2017-02-14 15:54:31 +0100245 char c;
246 uint8_t v;
247 const char *strpos;
248 unsigned int nibblepos = 0;
Harald Welte3eba9912010-07-30 10:37:29 +0200249
250 memset(b, 0x00, max_len);
251
Neels Hofmeyr437ed4a2017-02-14 15:54:31 +0100252 for (strpos = str; (c = *strpos); strpos++) {
253 /* skip whitespace */
254 if (c == ' ' || c == '\t' || c == '\n' || c == '\r')
255 continue;
256
257 /* If the buffer is too small, error out */
258 if (nibblepos >= (max_len << 1))
259 return -1;
260
Harald Welte3eba9912010-07-30 10:37:29 +0200261 if (c >= '0' && c <= '9')
262 v = c - '0';
263 else if (c >= 'a' && c <= 'f')
264 v = 10 + (c - 'a');
265 else if (c >= 'A' && c <= 'F')
266 v = 10 + (c - 'A');
267 else
268 return -1;
Neels Hofmeyr437ed4a2017-02-14 15:54:31 +0100269
270 b[nibblepos >> 1] |= v << (nibblepos & 1 ? 0 : 4);
271 nibblepos ++;
Harald Welte3eba9912010-07-30 10:37:29 +0200272 }
273
Neels Hofmeyr437ed4a2017-02-14 15:54:31 +0100274 /* In case of uneven amount of digits, the last byte is not complete
275 * and that's an error. */
276 if (nibblepos & 1)
277 return -1;
278
279 return nibblepos >> 1;
Harald Welte3eba9912010-07-30 10:37:29 +0200280}
Harald Welte40481e82010-07-30 11:40:32 +0200281
Harald Welte171ef822019-03-28 10:49:05 +0100282static __thread char hexd_buff[4096];
Nils O. SelÄsdal32447022014-01-02 14:04:43 +0100283static const char hex_chars[] = "0123456789abcdef";
Harald Welte40481e82010-07-30 11:40:32 +0200284
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100285/*! Convert binary sequence to hexadecimal ASCII string.
286 * \param[out] out_buf Output buffer to write the resulting string to.
287 * \param[in] out_buf_size sizeof(out_buf).
288 * \param[in] buf Input buffer, pointer to sequence of bytes.
289 * \param[in] len Length of input buf in number of bytes.
290 * \param[in] delim String to separate each byte; NULL or "" for no delim.
291 * \param[in] delim_after_last If true, end the string in delim (true: "1a:ef:d9:", false: "1a:ef:d9");
292 * if out_buf has insufficient space, the string will always end in a delim.
293 * \returns out_buf, containing a zero-terminated string, or "" (empty string) if out_buf == NULL or out_buf_size < 1.
294 *
295 * This function will print a sequence of bytes as hexadecimal numbers, adding one delim between each byte (e.g. for
296 * delim passed as ":", return a string like "1a:ef:d9").
297 *
298 * The delim_after_last argument exists to be able to exactly show the original osmo_hexdump() behavior, which always
299 * ends the string with a delimiter.
300 */
301const char *osmo_hexdump_buf(char *out_buf, size_t out_buf_size, const unsigned char *buf, int len, const char *delim,
302 bool delim_after_last)
Harald Welte40481e82010-07-30 11:40:32 +0200303{
304 int i;
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100305 char *cur = out_buf;
306 size_t delim_len;
Harald Welte40481e82010-07-30 11:40:32 +0200307
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100308 if (!out_buf || !out_buf_size)
309 return "";
310
311 delim = delim ? : "";
312 delim_len = strlen(delim);
313
Harald Welte40481e82010-07-30 11:40:32 +0200314 for (i = 0; i < len; i++) {
Nils O. SelÄsdal32447022014-01-02 14:04:43 +0100315 const char *delimp = delim;
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100316 int len_remain = out_buf_size - (cur - out_buf) - 1;
Harald Welte7d6166a2022-01-09 11:57:01 +0100317 if (len_remain < (int) (2 + delim_len)
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100318 && !(!delim_after_last && i == (len - 1) && len_remain >= 2))
Holger Hans Peter Freyther128d9e22011-07-15 16:07:23 +0200319 break;
Nils O. SelÄsdal32447022014-01-02 14:04:43 +0100320
321 *cur++ = hex_chars[buf[i] >> 4];
322 *cur++ = hex_chars[buf[i] & 0xf];
323
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100324 if (i == (len - 1) && !delim_after_last)
325 break;
326
Nils O. SelÄsdal32447022014-01-02 14:04:43 +0100327 while (len_remain > 1 && *delimp) {
328 *cur++ = *delimp++;
329 len_remain--;
330 }
Harald Welte40481e82010-07-30 11:40:32 +0200331 }
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100332 *cur = '\0';
333 return out_buf;
Harald Welte40481e82010-07-30 11:40:32 +0200334}
Harald Weltedee47cd2010-07-30 11:43:30 +0200335
Harald Welte4a62eda2019-03-18 18:27:00 +0100336/*! Convert a sequence of unpacked bits to ASCII string, in user-supplied buffer.
337 * \param[out] buf caller-provided output string buffer
338 * \param[out] buf_len size of buf in bytes
Harald Welte8598f182011-08-17 14:19:27 +0200339 * \param[in] bits A sequence of unpacked bits
340 * \param[in] len Length of bits
Neels Hofmeyrdd7b6f92019-11-20 21:32:29 +0100341 * \return The output buffer (buf).
Harald Welte8598f182011-08-17 14:19:27 +0200342 */
Harald Welte4a62eda2019-03-18 18:27:00 +0100343char *osmo_ubit_dump_buf(char *buf, size_t buf_len, const uint8_t *bits, unsigned int len)
Harald Welte3d0ac5e2011-02-08 16:55:03 +0100344{
Harald Welte7d6166a2022-01-09 11:57:01 +0100345 unsigned int i;
Harald Welte3d0ac5e2011-02-08 16:55:03 +0100346
Harald Welte4a62eda2019-03-18 18:27:00 +0100347 if (len > buf_len-1)
348 len = buf_len-1;
349 memset(buf, 0, buf_len);
Harald Welte3d0ac5e2011-02-08 16:55:03 +0100350
351 for (i = 0; i < len; i++) {
352 char outch;
353 switch (bits[i]) {
354 case 0:
355 outch = '0';
356 break;
357 case 0xff:
358 outch = '?';
359 break;
360 case 1:
361 outch = '1';
362 break;
363 default:
364 outch = 'E';
365 break;
366 }
Harald Welte4a62eda2019-03-18 18:27:00 +0100367 buf[i] = outch;
Harald Welte3d0ac5e2011-02-08 16:55:03 +0100368 }
Harald Welte4a62eda2019-03-18 18:27:00 +0100369 buf[buf_len-1] = 0;
370 return buf;
371}
372
373/*! Convert a sequence of unpacked bits to ASCII string, in static buffer.
374 * \param[in] bits A sequence of unpacked bits
375 * \param[in] len Length of bits
376 * \returns string representation in static buffer.
377 */
378char *osmo_ubit_dump(const uint8_t *bits, unsigned int len)
379{
380 return osmo_ubit_dump_buf(hexd_buff, sizeof(hexd_buff), bits, len);
Harald Welte3d0ac5e2011-02-08 16:55:03 +0100381}
382
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200383/*! Convert binary sequence to hexadecimal ASCII string
Harald Welte8598f182011-08-17 14:19:27 +0200384 * \param[in] buf pointer to sequence of bytes
385 * \param[in] len length of buf in number of bytes
386 * \returns pointer to zero-terminated string
387 *
388 * This function will print a sequence of bytes as hexadecimal numbers,
389 * adding one space character between each byte (e.g. "1a ef d9")
Harald Welte096a6662017-10-16 14:33:11 +0200390 *
391 * The maximum size of the output buffer is 4096 bytes, i.e. the maximum
392 * number of input bytes that can be printed in one call is 1365!
Harald Welte8598f182011-08-17 14:19:27 +0200393 */
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200394char *osmo_hexdump(const unsigned char *buf, int len)
Harald Weltedee47cd2010-07-30 11:43:30 +0200395{
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100396 osmo_hexdump_buf(hexd_buff, sizeof(hexd_buff), buf, len, " ", true);
397 return hexd_buff;
Harald Weltedee47cd2010-07-30 11:43:30 +0200398}
399
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200400/*! Convert binary sequence to hexadecimal ASCII string
Harald Welte179f3572019-03-18 18:38:47 +0100401 * \param[in] ctx talloc context from where to allocate the output string
402 * \param[in] buf pointer to sequence of bytes
403 * \param[in] len length of buf in number of bytes
404 * \returns pointer to zero-terminated string
405 *
406 * This function will print a sequence of bytes as hexadecimal numbers,
407 * adding one space character between each byte (e.g. "1a ef d9")
Harald Welte179f3572019-03-18 18:38:47 +0100408 */
409char *osmo_hexdump_c(const void *ctx, const unsigned char *buf, int len)
410{
Vadim Yanitskiy4f619c22019-04-12 21:48:07 +0700411 size_t hexd_buff_len = len * 3 + 1;
412 char *hexd_buff = talloc_size(ctx, hexd_buff_len);
Harald Welte179f3572019-03-18 18:38:47 +0100413 if (!hexd_buff)
414 return NULL;
Vadim Yanitskiy4f619c22019-04-12 21:48:07 +0700415 osmo_hexdump_buf(hexd_buff, hexd_buff_len, buf, len, " ", true);
Harald Welte179f3572019-03-18 18:38:47 +0100416 return hexd_buff;
417}
418
419/*! Convert binary sequence to hexadecimal ASCII string
Harald Welte8598f182011-08-17 14:19:27 +0200420 * \param[in] buf pointer to sequence of bytes
421 * \param[in] len length of buf in number of bytes
422 * \returns pointer to zero-terminated string
423 *
424 * This function will print a sequence of bytes as hexadecimal numbers,
425 * without any space character between each byte (e.g. "1aefd9")
Harald Welte096a6662017-10-16 14:33:11 +0200426 *
427 * The maximum size of the output buffer is 4096 bytes, i.e. the maximum
428 * number of input bytes that can be printed in one call is 2048!
Harald Welte8598f182011-08-17 14:19:27 +0200429 */
Sylvain Munautff23d242011-11-10 23:03:18 +0100430char *osmo_hexdump_nospc(const unsigned char *buf, int len)
Harald Weltedee47cd2010-07-30 11:43:30 +0200431{
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100432 osmo_hexdump_buf(hexd_buff, sizeof(hexd_buff), buf, len, "", true);
433 return hexd_buff;
Harald Weltedee47cd2010-07-30 11:43:30 +0200434}
Harald Welte28222962011-02-18 20:37:04 +0100435
Harald Welte179f3572019-03-18 18:38:47 +0100436/*! Convert binary sequence to hexadecimal ASCII string
437 * \param[in] ctx talloc context from where to allocate the output string
438 * \param[in] buf pointer to sequence of bytes
439 * \param[in] len length of buf in number of bytes
440 * \returns pointer to zero-terminated string
441 *
442 * This function will print a sequence of bytes as hexadecimal numbers,
443 * without any space character between each byte (e.g. "1aefd9")
Harald Welte179f3572019-03-18 18:38:47 +0100444 */
445char *osmo_hexdump_nospc_c(const void *ctx, const unsigned char *buf, int len)
446{
Vadim Yanitskiy4f619c22019-04-12 21:48:07 +0700447 size_t hexd_buff_len = len * 2 + 1;
448 char *hexd_buff = talloc_size(ctx, hexd_buff_len);
Harald Welte179f3572019-03-18 18:38:47 +0100449 if (!hexd_buff)
450 return NULL;
Vadim Yanitskiy4f619c22019-04-12 21:48:07 +0700451 osmo_hexdump_buf(hexd_buff, hexd_buff_len, buf, len, "", true);
Harald Welte179f3572019-03-18 18:38:47 +0100452 return hexd_buff;
453}
454
455
Holger Hans Peter Freyther9a1a5a12015-04-11 19:26:55 +0200456/* Compat with previous typo to preserve abi */
Sylvain Munaute55ae3a2011-11-11 23:06:55 +0100457char *osmo_osmo_hexdump_nospc(const unsigned char *buf, int len)
Holger Hans Peter Freyther9a1a5a12015-04-11 19:26:55 +0200458#if defined(__MACH__) && defined(__APPLE__)
459 ;
460#else
Sylvain Munaut17af41d2011-11-19 22:30:39 +0100461 __attribute__((weak, alias("osmo_hexdump_nospc")));
Holger Hans Peter Freyther9a1a5a12015-04-11 19:26:55 +0200462#endif
Sylvain Munaute55ae3a2011-11-11 23:06:55 +0100463
Pau Espin Pedrol88955fb2023-01-18 18:54:00 +0100464#include "config.h"
Harald Welte28222962011-02-18 20:37:04 +0100465#ifdef HAVE_CTYPE_H
466#include <ctype.h>
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200467/*! Convert an entire string to lower case
Harald Welte8598f182011-08-17 14:19:27 +0200468 * \param[out] out output string, caller-allocated
469 * \param[in] in input string
470 */
Harald Welte28222962011-02-18 20:37:04 +0100471void osmo_str2lower(char *out, const char *in)
472{
473 unsigned int i;
474
475 for (i = 0; i < strlen(in); i++)
Pau Espin Pedrol399a6f02017-06-18 14:07:37 +0200476 out[i] = tolower((const unsigned char)in[i]);
Harald Welte28222962011-02-18 20:37:04 +0100477 out[strlen(in)] = '\0';
478}
479
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200480/*! Convert an entire string to upper case
Harald Welte8598f182011-08-17 14:19:27 +0200481 * \param[out] out output string, caller-allocated
482 * \param[in] in input string
483 */
Harald Welte28222962011-02-18 20:37:04 +0100484void osmo_str2upper(char *out, const char *in)
485{
486 unsigned int i;
487
488 for (i = 0; i < strlen(in); i++)
Pau Espin Pedrol399a6f02017-06-18 14:07:37 +0200489 out[i] = toupper((const unsigned char)in[i]);
Harald Welte28222962011-02-18 20:37:04 +0100490 out[strlen(in)] = '\0';
491}
492#endif /* HAVE_CTYPE_H */
Harald Welte8598f182011-08-17 14:19:27 +0200493
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200494/*! Wishful thinking to generate a constant time compare
Harald Welte9709b2e2016-04-25 18:47:53 +0200495 * \param[in] exp Expected data
496 * \param[in] rel Comparison value
497 * \param[in] count Number of bytes to compare
498 * \returns 1 in case \a exp equals \a rel; zero otherwise
499 *
500 * Compare count bytes of exp to rel. Return 0 if they are identical, 1
501 * otherwise. Do not return a mismatch on the first mismatching byte,
502 * but always compare all bytes, regardless. The idea is that the amount of
503 * matching bytes cannot be inferred from the time the comparison took. */
504int osmo_constant_time_cmp(const uint8_t *exp, const uint8_t *rel, const int count)
505{
506 int x = 0, i;
507
508 for (i = 0; i < count; ++i)
509 x |= exp[i] ^ rel[i];
510
511 /* if x is zero, all data was identical */
512 return x? 1 : 0;
513}
514
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200515/*! Generic retrieval of 1..8 bytes as big-endian uint64_t
Harald Welte9709b2e2016-04-25 18:47:53 +0200516 * \param[in] data Input data as byte-array
517 * \param[in] data_len Length of \a data in octets
518 * \returns uint64_t of \a data interpreted as big-endian
519 *
520 * This is like osmo_load64be_ext, except that if data_len is less than
521 * sizeof(uint64_t), the data is interpreted as the least significant bytes
522 * (osmo_load64be_ext loads them as the most significant bytes into the
523 * returned uint64_t). In this way, any integer size up to 64 bits can be
524 * decoded conveniently by using sizeof(), without the need to call specific
525 * numbered functions (osmo_load16, 32, ...). */
526uint64_t osmo_decode_big_endian(const uint8_t *data, size_t data_len)
527{
528 uint64_t value = 0;
529
530 while (data_len > 0) {
531 value = (value << 8) + *data;
532 data += 1;
533 data_len -= 1;
534 }
535
536 return value;
537}
538
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200539/*! Generic big-endian encoding of big endian number up to 64bit
Harald Welte9709b2e2016-04-25 18:47:53 +0200540 * \param[in] value unsigned integer value to be stored
Pau Espin Pedrolc29d5132020-09-21 17:09:31 +0200541 * \param[in] data_len number of octets
Harald Welte9709b2e2016-04-25 18:47:53 +0200542 * \returns static buffer containing big-endian stored value
543 *
544 * This is like osmo_store64be_ext, except that this returns a static buffer of
545 * the result (for convenience, but not threadsafe). If data_len is less than
546 * sizeof(uint64_t), only the least significant bytes of value are encoded. */
547uint8_t *osmo_encode_big_endian(uint64_t value, size_t data_len)
548{
Harald Welte171ef822019-03-28 10:49:05 +0100549 static __thread uint8_t buf[sizeof(uint64_t)];
Harald Welte9709b2e2016-04-25 18:47:53 +0200550 OSMO_ASSERT(data_len <= ARRAY_SIZE(buf));
551 osmo_store64be_ext(value, buf, data_len);
552 return buf;
553}
Harald Welteaeecc482016-11-26 10:41:40 +0100554
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200555/*! Copy a C-string into a sized buffer
Harald Welteaeecc482016-11-26 10:41:40 +0100556 * \param[in] src source string
557 * \param[out] dst destination string
Neels Hofmeyrdf83ece2017-01-13 13:55:43 +0100558 * \param[in] siz size of the \a dst buffer
559 * \returns length of \a src
Harald Welteaeecc482016-11-26 10:41:40 +0100560 *
Neels Hofmeyrdf83ece2017-01-13 13:55:43 +0100561 * Copy at most \a siz bytes from \a src to \a dst, ensuring that the result is
562 * NUL terminated. The NUL character is included in \a siz, i.e. passing the
563 * actual sizeof(*dst) is correct.
Neels Hofmeyrff65d242019-11-19 00:21:14 +0100564 *
565 * Note, a similar function that also limits the input buffer size is osmo_print_n().
Harald Welteaeecc482016-11-26 10:41:40 +0100566 */
567size_t osmo_strlcpy(char *dst, const char *src, size_t siz)
568{
Neels Hofmeyrbcf9f232017-10-25 04:16:45 +0200569 size_t ret = src ? strlen(src) : 0;
Harald Welteaeecc482016-11-26 10:41:40 +0100570
571 if (siz) {
Pau Espin Pedrol53fbc672020-09-21 17:13:30 +0200572 size_t len = OSMO_MIN(siz - 1, ret);
Pau Espin Pedrolc29d5132020-09-21 17:09:31 +0200573 if (len)
Neels Hofmeyrebd3cdd2017-11-18 23:07:38 +0100574 memcpy(dst, src, len);
Harald Welteaeecc482016-11-26 10:41:40 +0100575 dst[len] = '\0';
576 }
577 return ret;
578}
Neels Hofmeyr0aeda1b2017-01-13 14:16:02 +0100579
Neels Hofmeyr06356fd2019-11-19 01:38:10 +0100580/*! Find first occurence of a char in a size limited string.
581 * Like strchr() but with a buffer size limit.
582 * \param[in] str String buffer to examine.
583 * \param[in] str_size sizeof(str).
584 * \param[in] c Character to look for.
585 * \return Pointer to the matched char, or NULL if not found.
586 */
587const char *osmo_strnchr(const char *str, size_t str_size, char c)
588{
589 const char *end = str + str_size;
590 const char *pos;
591 if (!str)
592 return NULL;
593 for (pos = str; pos < end; pos++) {
594 if (c == *pos)
595 return pos;
596 if (!*pos)
597 return NULL;
598 }
599 return NULL;
600}
601
Neels Hofmeyr4335bad2017-10-07 04:39:14 +0200602/*! Validate that a given string is a hex string within given size limits.
603 * Note that each hex digit amounts to a nibble, so if checking for a hex
604 * string to result in N bytes, pass amount of digits as 2*N.
605 * \param str A nul-terminated string to validate, or NULL.
606 * \param min_digits least permitted amount of digits.
607 * \param max_digits most permitted amount of digits.
608 * \param require_even if true, require an even amount of digits.
609 * \returns true when the hex_str contains only hexadecimal digits (no
610 * whitespace) and matches the requested length; also true
611 * when min_digits <= 0 and str is NULL.
612 */
613bool osmo_is_hexstr(const char *str, int min_digits, int max_digits,
614 bool require_even)
615{
616 int len;
617 /* Use unsigned char * to avoid a compiler warning of
618 * "error: array subscript has type 'char' [-Werror=char-subscripts]" */
619 const unsigned char *pos = (const unsigned char*)str;
620 if (!pos)
621 return min_digits < 1;
622 for (len = 0; *pos && len < max_digits; len++, pos++)
623 if (!isxdigit(*pos))
624 return false;
625 if (len < min_digits)
626 return false;
627 /* With not too many digits, we should have reached *str == nul */
628 if (*pos)
629 return false;
630 if (require_even && (len & 1))
631 return false;
Harald Weltefebe83c2017-10-03 17:41:59 +0800632
633 return true;
634}
635
Neels Hofmeyrb480b742019-04-11 06:58:44 +0200636static const char osmo_identifier_illegal_chars[] = "., {}[]()<>|~\\^`'\"?=;/+*&%$#!";
637
Harald Weltefebe83c2017-10-03 17:41:59 +0800638/*! Determine if a given identifier is valid, i.e. doesn't contain illegal chars
639 * \param[in] str String to validate
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100640 * \param[in] sep_chars Permitted separation characters between identifiers.
641 * \returns true in case \a str contains only valid identifiers and sep_chars, false otherwise
Harald Weltefebe83c2017-10-03 17:41:59 +0800642 */
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100643bool osmo_separated_identifiers_valid(const char *str, const char *sep_chars)
Harald Weltefebe83c2017-10-03 17:41:59 +0800644{
645 /* characters that are illegal in names */
Harald Weltefebe83c2017-10-03 17:41:59 +0800646 unsigned int i;
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100647 size_t len;
Harald Weltefebe83c2017-10-03 17:41:59 +0800648
649 /* an empty string is not a valid identifier */
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100650 if (!str || (len = strlen(str)) == 0)
Harald Weltefebe83c2017-10-03 17:41:59 +0800651 return false;
652
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100653 for (i = 0; i < len; i++) {
654 if (sep_chars && strchr(sep_chars, str[i]))
655 continue;
Harald Weltefebe83c2017-10-03 17:41:59 +0800656 /* check for 7-bit ASCII */
657 if (str[i] & 0x80)
658 return false;
Neels Hofmeyre5a2bdb2017-12-16 04:54:37 +0100659 if (!isprint((int)str[i]))
660 return false;
Harald Weltefebe83c2017-10-03 17:41:59 +0800661 /* check for some explicit reserved control characters */
Neels Hofmeyrb480b742019-04-11 06:58:44 +0200662 if (strchr(osmo_identifier_illegal_chars, str[i]))
Harald Weltefebe83c2017-10-03 17:41:59 +0800663 return false;
664 }
665
Neels Hofmeyr4335bad2017-10-07 04:39:14 +0200666 return true;
667}
668
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100669/*! Determine if a given identifier is valid, i.e. doesn't contain illegal chars
670 * \param[in] str String to validate
671 * \returns true in case \a str contains valid identifier, false otherwise
672 */
673bool osmo_identifier_valid(const char *str)
674{
675 return osmo_separated_identifiers_valid(str, NULL);
676}
677
Neels Hofmeyrb480b742019-04-11 06:58:44 +0200678/*! Replace characters in the given string buffer so that it is guaranteed to pass osmo_separated_identifiers_valid().
679 * To guarantee passing osmo_separated_identifiers_valid(), replace_with must not itself be an illegal character. If in
680 * doubt, use '-'.
681 * \param[inout] str Identifier to sanitize, must be nul terminated and in a writable buffer.
Neels Hofmeyr5aa421f2021-07-07 23:50:29 +0200682 * \param[in] sep_chars Additional characters that are to be replaced besides osmo_identifier_illegal_chars.
Neels Hofmeyrb480b742019-04-11 06:58:44 +0200683 * \param[in] replace_with Replace any illegal characters with this character.
684 */
685void osmo_identifier_sanitize_buf(char *str, const char *sep_chars, char replace_with)
686{
687 char *pos;
688 if (!str)
689 return;
690 for (pos = str; *pos; pos++) {
691 if (strchr(osmo_identifier_illegal_chars, *pos)
692 || (sep_chars && strchr(sep_chars, *pos)))
693 *pos = replace_with;
694 }
695}
696
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100697/*! Like osmo_escape_str_buf2, but with unusual ordering of arguments, and may sometimes return string constants instead
698 * of writing to buf for error cases or empty input.
699 * Most *_buf() functions have the buffer and size as first arguments, here the arguments are last.
700 * In particular, this function signature doesn't work with OSMO_STRBUF_APPEND_NOLEN().
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100701 * \param[in] str A string that may contain any characters.
702 * \param[in] len Pass -1 to print until nul char, or >= 0 to force a length.
703 * \param[inout] buf string buffer to write escaped characters to.
704 * \param[in] bufsize size of \a buf.
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100705 * \returns buf containing an escaped representation, possibly truncated,
706 * or "(null)" if str == NULL, or "(error)" in case of errors.
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100707 */
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100708const char *osmo_escape_str_buf(const char *str, int in_len, char *buf, size_t bufsize)
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100709{
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100710 if (!str)
711 return "(null)";
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100712 if (!buf || !bufsize)
713 return "(error)";
714 return osmo_escape_str_buf2(buf, bufsize, str, in_len);
715}
716
717/*! Copy N characters to a buffer with a function signature useful for OSMO_STRBUF_APPEND().
718 * Similarly to snprintf(), the result is always nul terminated (except if buf is NULL or bufsize is 0).
719 * \param[out] buf Target buffer.
720 * \param[in] bufsize sizeof(buf).
721 * \param[in] str String to copy.
722 * \param[in] n Maximum number of non-nul characters to copy.
723 * \return Number of characters that would be written if bufsize were large enough excluding '\0' (like snprintf()).
724 */
725int osmo_print_n(char *buf, size_t bufsize, const char *str, size_t n)
726{
727 size_t write_n;
728
729 if (!str)
730 str = "";
731
732 n = strnlen(str, n);
733
734 if (!buf || !bufsize)
735 return n;
736 write_n = n;
737 if (write_n >= bufsize)
738 write_n = bufsize - 1;
739 if (write_n)
740 strncpy(buf, str, write_n);
741 buf[write_n] = '\0';
742
743 return n;
744}
745
746/*! Return the string with all non-printable characters escaped.
Neels Hofmeyrc36e2e42019-11-20 21:57:32 +0100747 * This internal function is the implementation for all osmo_escape_str* and osmo_quote_str* API versions.
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100748 * It provides both the legacy (non C compatible) escaping, as well as C compatible string constant syntax,
749 * 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 +0100750 * \param[out] buf string buffer to write escaped characters to.
751 * \param[in] bufsize sizeof(buf).
752 * \param[in] str A string that may contain any characters.
753 * \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 +0100754 * \param[in] legacy_format If false, return C compatible string constants ("\x0f"), if true the legacy
755 * escaping format ("\15"). The legacy format also escapes as "\a\b\f\v", while
756 * the non-legacy format also escapes those as "\xNN" sequences.
Neels Hofmeyrc36e2e42019-11-20 21:57:32 +0100757 * \return Number of characters that would be written if bufsize were large enough excluding '\0' (like snprintf()).
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100758 */
Neels Hofmeyr16337352022-01-31 15:56:02 +0100759static int _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 +0100760{
761 struct osmo_strbuf sb = { .buf = buf, .len = bufsize };
762 int in_pos = 0;
763 int next_unprintable = 0;
764
765 if (!str)
766 in_len = 0;
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100767
768 if (in_len < 0)
769 in_len = strlen(str);
770
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100771 /* Make sure of '\0' termination */
772 if (!in_len)
773 OSMO_STRBUF_PRINTF(sb, "%s", "");
774
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100775 while (in_pos < in_len) {
776 for (next_unprintable = in_pos;
777 next_unprintable < in_len && isprint((int)str[next_unprintable])
778 && str[next_unprintable] != '"'
779 && str[next_unprintable] != '\\';
780 next_unprintable++);
781
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100782 OSMO_STRBUF_APPEND(sb, osmo_print_n, &str[in_pos], next_unprintable - in_pos);
783 in_pos = next_unprintable;
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100784
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100785 if (in_pos == in_len)
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100786 goto done;
787
788 switch (str[next_unprintable]) {
789#define BACKSLASH_CASE(c, repr) \
790 case c: \
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100791 OSMO_STRBUF_PRINTF(sb, "\\%c", repr); \
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100792 break
793
794 BACKSLASH_CASE('\n', 'n');
795 BACKSLASH_CASE('\r', 'r');
796 BACKSLASH_CASE('\t', 't');
797 BACKSLASH_CASE('\0', '0');
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100798 BACKSLASH_CASE('\\', '\\');
799 BACKSLASH_CASE('"', '"');
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100800
801 default:
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100802 if (legacy_format) {
803 switch (str[next_unprintable]) {
804 BACKSLASH_CASE('\a', 'a');
805 BACKSLASH_CASE('\b', 'b');
806 BACKSLASH_CASE('\v', 'v');
807 BACKSLASH_CASE('\f', 'f');
808 default:
809 OSMO_STRBUF_PRINTF(sb, "\\%u", (unsigned char)str[in_pos]);
810 break;
811 }
812 break;
813 }
814
815 OSMO_STRBUF_PRINTF(sb, "\\x%02x", (unsigned char)str[in_pos]);
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100816 break;
817 }
818 in_pos ++;
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100819#undef BACKSLASH_CASE
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100820 }
821
822done:
Neels Hofmeyrc36e2e42019-11-20 21:57:32 +0100823 return sb.chars_needed;
824}
825
826/*! Return the string with all non-printable characters escaped.
827 * \param[out] buf string buffer to write escaped characters to.
828 * \param[in] bufsize sizeof(buf).
829 * \param[in] str A string that may contain any characters.
830 * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length (also past nul chars).
Neels Hofmeyr16337352022-01-31 15:56:02 +0100831 * \return Number of characters that would be written if bufsize were large enough excluding '\0' (like snprintf()).
832 */
833int osmo_escape_str_buf3(char *buf, size_t bufsize, const char *str, int in_len)
834{
835 return _osmo_escape_str_buf(buf, bufsize, str, in_len, false);
836}
837
838/*! Return the string with all non-printable characters escaped.
839 * \param[out] buf string buffer to write escaped characters to.
840 * \param[in] bufsize sizeof(buf).
841 * \param[in] str A string that may contain any characters.
842 * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length (also past nul chars).
Neels Hofmeyrc36e2e42019-11-20 21:57:32 +0100843 * \return The output buffer (buf).
844 */
845char *osmo_escape_str_buf2(char *buf, size_t bufsize, const char *str, int in_len)
846{
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100847 _osmo_escape_str_buf(buf, bufsize, str, in_len, true);
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100848 return buf;
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100849}
850
851/*! Return the string with all non-printable characters escaped.
852 * Call osmo_escape_str_buf() with a static 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 buf containing an escaped representation, possibly truncated, or str itself.
856 */
857const char *osmo_escape_str(const char *str, int in_len)
858{
859 return osmo_escape_str_buf(str, in_len, namebuf, sizeof(namebuf));
860}
861
Harald Welte179f3572019-03-18 18:38:47 +0100862/*! Return the string with all non-printable characters escaped, in dynamically-allocated buffer.
863 * \param[in] str A string that may contain any characters.
864 * \param[in] len Pass -1 to print until nul char, or >= 0 to force a length.
865 * \returns dynamically-allocated output buffer, containing an escaped representation
866 */
867char *osmo_escape_str_c(const void *ctx, const char *str, int in_len)
868{
Neels Hofmeyrc36e2e42019-11-20 21:57:32 +0100869 /* The string will be at least as long as in_len, but some characters might need escaping.
870 * 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 +0100871 OSMO_NAME_C_IMPL(ctx, in_len + 16, "ERROR", _osmo_escape_str_buf, str, in_len, true);
Neels Hofmeyrc36e2e42019-11-20 21:57:32 +0100872}
873
874/*! Return a quoted and escaped representation of the string.
875 * This internal function is the implementation for all osmo_quote_str* API versions.
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100876 * It provides both the legacy (non C compatible) escaping, as well as C compatible string constant syntax,
877 * 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 +0100878 * \param[out] buf string buffer to write escaped characters to.
879 * \param[in] bufsize sizeof(buf).
880 * \param[in] str A string that may contain any characters.
881 * \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 +0100882 * \param[in] legacy_format If false, return C compatible string constants ("\x0f"), if true the legacy
883 * escaping format ("\15"). The legacy format also escapes as "\a\b\f\v", while
884 * the non-legacy format also escapes those as "\xNN" sequences.
Neels Hofmeyrc36e2e42019-11-20 21:57:32 +0100885 * \return Number of characters that would be written if bufsize were large enough excluding '\0' (like snprintf()).
886 */
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100887static 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 +0100888{
889 struct osmo_strbuf sb = { .buf = buf, .len = bufsize };
890 if (!str)
891 OSMO_STRBUF_PRINTF(sb, "NULL");
892 else {
893 OSMO_STRBUF_PRINTF(sb, "\"");
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100894 OSMO_STRBUF_APPEND(sb, _osmo_escape_str_buf, str, in_len, legacy_format);
Neels Hofmeyrc36e2e42019-11-20 21:57:32 +0100895 OSMO_STRBUF_PRINTF(sb, "\"");
896 }
897 return sb.chars_needed;
Harald Welte179f3572019-03-18 18:38:47 +0100898}
899
Neels Hofmeyr16337352022-01-31 15:56:02 +0100900/*! Like osmo_escape_str_buf3(), but returns double-quotes around a string, or "NULL" for a NULL string.
901 * This allows passing any char* value and get its C representation as string.
902 * The function signature is suitable for OSMO_STRBUF_APPEND_NOLEN().
903 * \param[out] buf string buffer to write escaped characters to.
904 * \param[in] bufsize sizeof(buf).
905 * \param[in] str A string that may contain any characters.
906 * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length.
907 * \return Number of characters that would be written if bufsize were large enough excluding '\0' (like snprintf()).
908 */
909int osmo_quote_str_buf3(char *buf, size_t bufsize, const char *str, int in_len)
910{
911 return _osmo_quote_str_buf(buf, bufsize, str, in_len, false);
912}
913
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100914/*! 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 +0200915 * This allows passing any char* value and get its C representation as string.
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100916 * The function signature is suitable for OSMO_STRBUF_APPEND_NOLEN().
917 * \param[out] buf string buffer to write escaped characters to.
918 * \param[in] bufsize sizeof(buf).
919 * \param[in] str A string that may contain any characters.
920 * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length.
Neels Hofmeyrdd7b6f92019-11-20 21:32:29 +0100921 * \return The output buffer (buf).
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100922 */
923char *osmo_quote_str_buf2(char *buf, size_t bufsize, const char *str, int in_len)
924{
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100925 _osmo_quote_str_buf(buf, bufsize, str, in_len, true);
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100926 return buf;
927}
928
929/*! Like osmo_quote_str_buf2, but with unusual ordering of arguments, and may sometimes return string constants instead
930 * of writing to buf for error cases or empty input.
931 * Most *_buf() functions have the buffer and size as first arguments, here the arguments are last.
932 * In particular, this function signature doesn't work with OSMO_STRBUF_APPEND_NOLEN().
Neels Hofmeyr04eb56f2018-04-09 00:41:28 +0200933 * \param[in] str A string that may contain any characters.
Neels Hofmeyr03e75532018-09-07 03:12:05 +0200934 * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length.
935 * \returns buf containing a quoted and escaped representation, possibly truncated.
Neels Hofmeyr04eb56f2018-04-09 00:41:28 +0200936 */
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100937const char *osmo_quote_str_buf(const char *str, int in_len, char *buf, size_t bufsize)
Neels Hofmeyr04eb56f2018-04-09 00:41:28 +0200938{
Neels Hofmeyr04eb56f2018-04-09 00:41:28 +0200939 if (!str)
940 return "NULL";
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100941 if (!buf || !bufsize)
942 return "(error)";
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100943 _osmo_quote_str_buf(buf, bufsize, str, in_len, true);
Neels Hofmeyr04eb56f2018-04-09 00:41:28 +0200944 return buf;
945}
946
Neels Hofmeyr03e75532018-09-07 03:12:05 +0200947/*! Like osmo_quote_str_buf() but returns the result in a static buffer.
948 * The static buffer is shared with get_value_string() and osmo_escape_str().
949 * \param[in] str A string that may contain any characters.
950 * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length.
951 * \returns static buffer containing a quoted and escaped representation, possibly truncated.
952 */
Neels Hofmeyr04eb56f2018-04-09 00:41:28 +0200953const char *osmo_quote_str(const char *str, int in_len)
954{
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100955 _osmo_quote_str_buf(namebuf, sizeof(namebuf), str, in_len, true);
Neels Hofmeyrc36e2e42019-11-20 21:57:32 +0100956 return namebuf;
Neels Hofmeyr04eb56f2018-04-09 00:41:28 +0200957}
958
Harald Welte179f3572019-03-18 18:38:47 +0100959/*! Like osmo_quote_str_buf() but returns the result in a dynamically-allocated buffer.
Harald Welte179f3572019-03-18 18:38:47 +0100960 * \param[in] str A string that may contain any characters.
961 * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length.
962 * \returns dynamically-allocated buffer containing a quoted and escaped representation.
963 */
964char *osmo_quote_str_c(const void *ctx, const char *str, int in_len)
965{
Neels Hofmeyrc36e2e42019-11-20 21:57:32 +0100966 /* The string will be at least as long as in_len, but some characters might need escaping.
967 * 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 +0100968 OSMO_NAME_C_IMPL(ctx, in_len + 16, "ERROR", _osmo_quote_str_buf, str, in_len, true);
969}
970
971/*! Return the string with all non-printable characters escaped.
972 * In contrast to osmo_escape_str_buf2(), this returns the needed buffer size suitable for OSMO_STRBUF_APPEND(), and
973 * this escapes characters in a way compatible with C string constant syntax.
974 * \param[out] buf string buffer to write escaped characters to.
975 * \param[in] bufsize sizeof(buf).
976 * \param[in] str A string that may contain any characters.
977 * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length (also past nul chars).
978 * \return Number of characters that would be written if bufsize were large enough excluding '\0' (like snprintf()).
979 */
980size_t osmo_escape_cstr_buf(char *buf, size_t bufsize, const char *str, int in_len)
981{
982 return _osmo_escape_str_buf(buf, bufsize, str, in_len, false);
983}
984
985/*! Return the string with all non-printable characters escaped, in dynamically-allocated buffer.
986 * In contrast to osmo_escape_str_c(), this escapes characters in a way compatible with C string constant syntax, and
987 * allocates sufficient memory in all cases.
988 * \param[in] str A string that may contain any characters.
989 * \param[in] len Pass -1 to print until nul char, or >= 0 to force a length.
990 * \returns dynamically-allocated buffer, containing an escaped representation.
991 */
992char *osmo_escape_cstr_c(void *ctx, const char *str, int in_len)
993{
994 /* The string will be at least as long as in_len, but some characters might need escaping.
995 * These extra bytes should catch most usual escaping situations, avoiding a second run in OSMO_NAME_C_IMPL. */
996 OSMO_NAME_C_IMPL(ctx, in_len + 16, "ERROR", _osmo_escape_str_buf, str, in_len, false);
997}
998
999/*! Like osmo_escape_str_buf2(), but returns double-quotes around a string, or "NULL" for a NULL string.
1000 * This allows passing any char* value and get its C representation as string.
1001 * The function signature is suitable for OSMO_STRBUF_APPEND_NOLEN().
1002 * In contrast to osmo_escape_str_buf2(), this returns the needed buffer size suitable for OSMO_STRBUF_APPEND(), and
1003 * this escapes characters in a way compatible with C string constant syntax.
1004 * \param[out] buf string buffer to write escaped characters to.
1005 * \param[in] bufsize sizeof(buf).
1006 * \param[in] str A string that may contain any characters.
1007 * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length.
1008 * \return Number of characters that would be written if bufsize were large enough excluding '\0' (like snprintf()).
1009 */
1010size_t osmo_quote_cstr_buf(char *buf, size_t bufsize, const char *str, int in_len)
1011{
1012 return _osmo_quote_str_buf(buf, bufsize, str, in_len, false);
1013}
1014
1015/*! Return the string quoted and with all non-printable characters escaped, in dynamically-allocated buffer.
1016 * In contrast to osmo_quote_str_c(), this escapes characters in a way compatible with C string constant syntax, and
1017 * allocates sufficient memory in all cases.
1018 * \param[in] str A string that may contain any characters.
1019 * \param[in] len Pass -1 to print until nul char, or >= 0 to force a length.
1020 * \returns dynamically-allocated buffer, containing a quoted and escaped representation.
1021 */
1022char *osmo_quote_cstr_c(void *ctx, const char *str, int in_len)
1023{
1024 /* The string will be at least as long as in_len plus two quotes, but some characters might need escaping.
1025 * These extra bytes should catch most usual escaping situations, avoiding a second run in OSMO_NAME_C_IMPL. */
1026 OSMO_NAME_C_IMPL(ctx, in_len + 16, "ERROR", _osmo_quote_str_buf, str, in_len, false);
Harald Welte179f3572019-03-18 18:38:47 +01001027}
1028
Harald Welte15a5f8d2018-06-06 16:58:17 +02001029/*! perform an integer square root operation on unsigned 32bit integer.
1030 * This implementation is taken from "Hacker's Delight" Figure 11-1 "Integer square root, Newton's
1031 * method", which can also be found at http://www.hackersdelight.org/hdcodetxt/isqrt.c.txt */
1032uint32_t osmo_isqrt32(uint32_t x)
1033{
1034 uint32_t x1;
1035 int s, g0, g1;
1036
1037 if (x <= 1)
1038 return x;
1039
1040 s = 1;
1041 x1 = x - 1;
1042 if (x1 > 0xffff) {
1043 s = s + 8;
1044 x1 = x1 >> 16;
1045 }
1046 if (x1 > 0xff) {
1047 s = s + 4;
1048 x1 = x1 >> 8;
1049 }
1050 if (x1 > 0xf) {
1051 s = s + 2;
1052 x1 = x1 >> 4;
1053 }
1054 if (x1 > 0x3) {
1055 s = s + 1;
1056 }
1057
1058 g0 = 1 << s; /* g0 = 2**s */
1059 g1 = (g0 + (x >> s)) >> 1; /* g1 = (g0 + x/g0)/2 */
1060
1061 /* converges after four to five divisions for arguments up to 16,785,407 */
1062 while (g1 < g0) {
1063 g0 = g1;
1064 g1 = (g0 + (x/g0)) >> 1;
1065 }
1066 return g0;
1067}
1068
Neels Hofmeyr7c749892018-09-07 03:01:38 +02001069/*! Convert a string to lowercase, while checking buffer size boundaries.
1070 * The result written to \a dest is guaranteed to be nul terminated if \a dest_len > 0.
1071 * If dest == src, the string is converted in-place, if necessary truncated at dest_len - 1 characters
1072 * length as well as nul terminated.
1073 * Note: similar osmo_str2lower(), but safe to use for src strings of arbitrary length.
1074 * \param[out] dest Target buffer to write lowercase string.
1075 * \param[in] dest_len Maximum buffer size of dest (e.g. sizeof(dest)).
1076 * \param[in] src String to convert to lowercase.
1077 * \returns Length of \a src, like osmo_strlcpy(), but if \a dest == \a src at most \a dest_len - 1.
1078 */
1079size_t osmo_str_tolower_buf(char *dest, size_t dest_len, const char *src)
1080{
1081 size_t rc;
1082 if (dest == src) {
1083 if (dest_len < 1)
1084 return 0;
1085 dest[dest_len - 1] = '\0';
1086 rc = strlen(dest);
1087 } else {
1088 if (dest_len < 1)
1089 return strlen(src);
1090 rc = osmo_strlcpy(dest, src, dest_len);
1091 }
1092 for (; *dest; dest++)
1093 *dest = tolower(*dest);
1094 return rc;
1095}
1096
1097/*! Convert a string to lowercase, using a static buffer.
1098 * The resulting string may be truncated if the internally used static buffer is shorter than src.
1099 * 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 +02001100 * terminating nul. The static buffer returned is shared with osmo_str_toupper().
Neels Hofmeyr7c749892018-09-07 03:01:38 +02001101 * See also osmo_str_tolower_buf().
1102 * \param[in] src String to convert to lowercase.
1103 * \returns Resulting lowercase string in a static buffer, always nul terminated.
1104 */
1105const char *osmo_str_tolower(const char *src)
1106{
Pau Espin Pedrola37f58e2019-08-01 18:11:41 +02001107 osmo_str_tolower_buf(capsbuf, sizeof(capsbuf), src);
1108 return capsbuf;
Neels Hofmeyr7c749892018-09-07 03:01:38 +02001109}
1110
Harald Welte179f3572019-03-18 18:38:47 +01001111/*! Convert a string to lowercase, dynamically allocating the output from given talloc context
1112 * See also osmo_str_tolower_buf().
1113 * \param[in] ctx talloc context from where to allocate the output string
1114 * \param[in] src String to convert to lowercase.
1115 * \returns Resulting lowercase string in a dynamically allocated buffer, always nul terminated.
1116 */
1117char *osmo_str_tolower_c(const void *ctx, const char *src)
1118{
Vadim Yanitskiy4f619c22019-04-12 21:48:07 +07001119 size_t buf_len = strlen(src) + 1;
1120 char *buf = talloc_size(ctx, buf_len);
Harald Welte179f3572019-03-18 18:38:47 +01001121 if (!buf)
1122 return NULL;
Vadim Yanitskiy4f619c22019-04-12 21:48:07 +07001123 osmo_str_tolower_buf(buf, buf_len, src);
Harald Welte179f3572019-03-18 18:38:47 +01001124 return buf;
1125}
1126
Neels Hofmeyr7c749892018-09-07 03:01:38 +02001127/*! Convert a string to uppercase, while checking buffer size boundaries.
1128 * The result written to \a dest is guaranteed to be nul terminated if \a dest_len > 0.
1129 * If dest == src, the string is converted in-place, if necessary truncated at dest_len - 1 characters
1130 * length as well as nul terminated.
1131 * Note: similar osmo_str2upper(), but safe to use for src strings of arbitrary length.
1132 * \param[out] dest Target buffer to write uppercase string.
1133 * \param[in] dest_len Maximum buffer size of dest (e.g. sizeof(dest)).
1134 * \param[in] src String to convert to uppercase.
1135 * \returns Length of \a src, like osmo_strlcpy(), but if \a dest == \a src at most \a dest_len - 1.
1136 */
1137size_t osmo_str_toupper_buf(char *dest, size_t dest_len, const char *src)
1138{
1139 size_t rc;
1140 if (dest == src) {
1141 if (dest_len < 1)
1142 return 0;
1143 dest[dest_len - 1] = '\0';
1144 rc = strlen(dest);
1145 } else {
1146 if (dest_len < 1)
1147 return strlen(src);
1148 rc = osmo_strlcpy(dest, src, dest_len);
1149 }
1150 for (; *dest; dest++)
1151 *dest = toupper(*dest);
1152 return rc;
1153}
1154
1155/*! Convert a string to uppercase, using a static buffer.
1156 * The resulting string may be truncated if the internally used static buffer is shorter than src.
1157 * 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 +02001158 * terminating nul. The static buffer returned is shared with osmo_str_tolower().
Neels Hofmeyr7c749892018-09-07 03:01:38 +02001159 * See also osmo_str_toupper_buf().
1160 * \param[in] src String to convert to uppercase.
1161 * \returns Resulting uppercase string in a static buffer, always nul terminated.
1162 */
1163const char *osmo_str_toupper(const char *src)
1164{
Pau Espin Pedrola37f58e2019-08-01 18:11:41 +02001165 osmo_str_toupper_buf(capsbuf, sizeof(capsbuf), src);
1166 return capsbuf;
Neels Hofmeyr7c749892018-09-07 03:01:38 +02001167}
1168
Harald Welte179f3572019-03-18 18:38:47 +01001169/*! Convert a string to uppercase, dynamically allocating the output from given talloc context
1170 * See also osmo_str_tolower_buf().
1171 * \param[in] ctx talloc context from where to allocate the output string
1172 * \param[in] src String to convert to uppercase.
1173 * \returns Resulting uppercase string in a dynamically allocated buffer, always nul terminated.
1174 */
1175char *osmo_str_toupper_c(const void *ctx, const char *src)
1176{
Vadim Yanitskiy4f619c22019-04-12 21:48:07 +07001177 size_t buf_len = strlen(src) + 1;
1178 char *buf = talloc_size(ctx, buf_len);
Harald Welte179f3572019-03-18 18:38:47 +01001179 if (!buf)
1180 return NULL;
Vadim Yanitskiy4f619c22019-04-12 21:48:07 +07001181 osmo_str_toupper_buf(buf, buf_len, src);
Harald Welte179f3572019-03-18 18:38:47 +01001182 return buf;
1183}
1184
Oliver Smith894be2d2019-01-11 13:13:37 +01001185/*! Calculate the Luhn checksum (as used for IMEIs).
1186 * \param[in] in Input digits in ASCII string representation.
1187 * \param[in] in_len Count of digits to use for the input (14 for IMEI).
1188 * \returns checksum char (e.g. '3'); negative on error
1189 */
Vadim Yanitskiyd9fc6042019-06-12 15:49:03 +07001190char osmo_luhn(const char* in, int in_len)
Oliver Smith894be2d2019-01-11 13:13:37 +01001191{
1192 int i, sum = 0;
1193
1194 /* All input must be numbers */
1195 for (i = 0; i < in_len; i++) {
KĂ©vin Redon1af2cd52019-05-23 19:00:19 +02001196 if (!isdigit((unsigned char)in[i]))
Oliver Smith894be2d2019-01-11 13:13:37 +01001197 return -EINVAL;
1198 }
1199
1200 /* Double every second digit and add it to sum */
1201 for (i = in_len - 1; i >= 0; i -= 2) {
1202 int dbl = (in[i] - '0') * 2;
1203 if (dbl > 9)
1204 dbl -= 9;
1205 sum += dbl;
1206 }
1207
1208 /* Add other digits to sum */
1209 for (i = in_len - 2; i >= 0; i -= 2)
1210 sum += in[i] - '0';
1211
1212 /* Final checksum */
1213 return (sum * 9) % 10 + '0';
1214}
1215
Neels Hofmeyrd511a9d2023-12-04 07:48:55 +01001216/*! Remove up to N chars from the end of an osmo_strbuf.
1217 * |--char-count---| - - chars_needed - - |
1218 * |<---------drop----------|
1219 */
1220void osmo_strbuf_drop_tail(struct osmo_strbuf *sb, size_t n_chars)
1221{
1222 size_t drop_n;
1223 if (sb->pos <= sb->buf)
1224 return;
1225 drop_n = OSMO_MIN(sb->chars_needed, n_chars);
1226 sb->chars_needed -= drop_n;
1227 /* chars_needed was reduced by n_chars, which may have been entirely behind the end of a full buffer, within the
1228 * hypothetical chars_needed. Modify the buffer tail pos only if the buffer is not or longer full now. */
1229 if (sb->chars_needed >= OSMO_STRBUF_CHAR_COUNT(*sb))
1230 return;
1231 sb->pos = sb->buf + sb->chars_needed;
1232 *sb->pos = '\0';
1233}
1234
1235/*! Let osmo_strbuf know that n_chars characters (excluding nul) were written to the end of the buffer.
1236 * If sb is nonempty, the n_chars are assumed to have been written to sb->pos. If sb is still empty and pos == NULL, the
1237 * n_chars are assumed to have been written to the start of the buffer.
1238 * Advance sb->pos and sb->chars_needed by at most n_chars, or up to sb->len - 1.
1239 * Ensure nul termination. */
1240void osmo_strbuf_added_tail(struct osmo_strbuf *sb, size_t n_chars)
1241{
1242 /* On init of an osmo_strbuf, sb->pos == NULL, which is defined as semantically identical to pointing at the
1243 * start of the buffer. A caller may just write to the buffer and call osmo_strbuf_added_tail(), in which case
1244 * still pos == NULL. pos != NULL happens as soon as the first OSMO_STRBUF_*() API has acted on the strbuf. */
1245 if (!sb->pos)
1246 sb->pos = sb->buf;
1247 sb->chars_needed += n_chars;
1248 /* first get remaining space, not counting trailing nul; but safeguard against empty buffer */
1249 size_t n_added = OSMO_STRBUF_REMAIN(*sb);
1250 if (n_added)
1251 n_added--;
1252 /* do not add more than fit in sb->len, still ensuring nul termination */
1253 n_added = OSMO_MIN(n_added, n_chars);
1254 if (n_added)
1255 sb->pos += n_added;
1256 /* when a strbuf is full, sb->pos may point after the final nul, so nul terminate only when pos is valid. */
1257 if (sb->pos < sb->buf + sb->len)
1258 *sb->pos = '\0';
1259}
1260
Neels Hofmeyrd79ccc62019-03-07 23:08:40 +01001261/*! Compare start of a string.
1262 * This is an optimisation of 'strstr(str, startswith_str) == str' because it doesn't search through the entire string.
1263 * \param str (Longer) string to compare.
1264 * \param startswith_str (Shorter) string to compare with the start of str.
1265 * \return true iff the first characters of str fully match startswith_str or startswith_str is empty. */
1266bool osmo_str_startswith(const char *str, const char *startswith_str)
1267{
1268 if (!startswith_str || !*startswith_str)
1269 return true;
1270 if (!str)
1271 return false;
1272 return strncmp(str, startswith_str, strlen(startswith_str)) == 0;
1273}
1274
Neels Hofmeyr87c3afb2020-09-30 21:47:47 +00001275/*! Convert a string of a floating point number to a signed int, with a decimal factor (fixed-point precision).
1276 * For example, with precision=3, convert "-1.23" to -1230. In other words, the float value is multiplied by
1277 * 10 to-the-power-of precision to obtain the returned integer.
1278 * The usable range of digits is -INT64_MAX .. INT64_MAX -- note, not INT64_MIN! The value of INT64_MIN is excluded to
1279 * reduce implementation complexity. See also utils_test.c.
Neels Hofmeyr6d744982020-10-08 13:09:49 +02001280 * The advantage over using sscanf("%f") is guaranteed precision: float or double types may apply rounding in the
1281 * conversion result. osmo_float_str_to_int() and osmo_int_to_float_str_buf() guarantee true results when converting
1282 * back and forth between string and int.
Neels Hofmeyr87c3afb2020-09-30 21:47:47 +00001283 * \param[out] val Returned integer value.
1284 * \param[in] str String of a float, like '-12.345'.
Neels Hofmeyr87c3afb2020-09-30 21:47:47 +00001285 * \param[in] precision Fixed-point precision, or * \returns 0 on success, negative on error.
1286 */
1287int osmo_float_str_to_int(int64_t *val, const char *str, unsigned int precision)
1288{
1289 const char *point;
1290 char *endptr;
1291 const char *p;
1292 int64_t sign = 1;
1293 int64_t integer = 0;
1294 int64_t decimal = 0;
1295 int64_t precision_factor;
1296 int64_t integer_max;
1297 int64_t decimal_max;
Harald Welte7d6166a2022-01-09 11:57:01 +01001298 unsigned int i;
Neels Hofmeyr87c3afb2020-09-30 21:47:47 +00001299
1300 OSMO_ASSERT(val);
1301 *val = 0;
1302
1303 if (!str)
1304 return -EINVAL;
1305 if (str[0] == '-') {
1306 str = str + 1;
1307 sign = -1;
1308 } else if (str[0] == '+') {
1309 str = str + 1;
1310 }
1311 if (!str[0])
1312 return -EINVAL;
1313
1314 /* Validate entire string as purely digits and at most one decimal dot. If not doing this here in advance,
1315 * parsing digits might stop early because of precision cut-off and miss validation of input data. */
1316 point = NULL;
1317 for (p = str; *p; p++) {
1318 if (*p == '.') {
1319 if (point)
1320 return -EINVAL;
1321 point = p;
Eric79f29032021-11-19 12:58:39 +01001322 } else if (!isdigit((unsigned char)*p))
Neels Hofmeyr87c3afb2020-09-30 21:47:47 +00001323 return -EINVAL;
1324 }
1325
1326 /* Parse integer part if there is one. If the string starts with a point, there's nothing to parse for the
1327 * integer part. */
1328 if (!point || point > str) {
1329 errno = 0;
1330 integer = strtoll(str, &endptr, 10);
Harald Weltecb11a602020-10-09 10:08:44 +02001331 if ((errno == ERANGE && (integer == LLONG_MAX || integer == LLONG_MIN))
Neels Hofmeyr87c3afb2020-09-30 21:47:47 +00001332 || (errno != 0 && integer == 0))
1333 return -ERANGE;
1334
1335 if ((point && endptr != point)
1336 || (!point && *endptr))
1337 return -EINVAL;
1338 }
1339
1340 /* Parse the fractional part if there is any, and if the precision is nonzero (if we even care about fractional
1341 * digits) */
1342 if (precision && point && point[1] != '\0') {
1343 /* limit the number of digits parsed to 'precision'.
1344 * If 'precision' is larger than the 19 digits representable in int64_t, skip some, to pick up lower
1345 * magnitude digits. */
1346 unsigned int skip_digits = (precision < 20) ? 0 : precision - 20;
1347 char decimal_str[precision + 1];
1348 osmo_strlcpy(decimal_str, point+1, precision+1);
1349
1350 /* fill with zeros to make exactly 'precision' digits */
1351 for (i = strlen(decimal_str); i < precision; i++)
1352 decimal_str[i] = '0';
1353 decimal_str[precision] = '\0';
1354
1355 for (i = 0; i < skip_digits; i++) {
1356 /* When skipping digits because precision > nr-of-digits-in-int64_t, they must be zero;
1357 * if there is a nonzero digit above the precision, it's -ERANGE. */
1358 if (decimal_str[i] != '0')
1359 return -ERANGE;
1360 }
1361 errno = 0;
1362 decimal = strtoll(decimal_str + skip_digits, &endptr, 10);
Harald Weltecb11a602020-10-09 10:08:44 +02001363 if ((errno == ERANGE && (decimal == LLONG_MAX || decimal == LLONG_MIN))
Neels Hofmeyr87c3afb2020-09-30 21:47:47 +00001364 || (errno != 0 && decimal == 0))
1365 return -ERANGE;
1366
1367 if (*endptr)
1368 return -EINVAL;
1369 }
1370
1371 if (precision > 18) {
1372 /* Special case of returning more digits than fit in int64_t range, e.g.
1373 * osmo_float_str_to_int("0.0000000012345678901234567", precision=25) -> 12345678901234567. */
1374 precision_factor = 0;
1375 integer_max = 0;
1376 decimal_max = INT64_MAX;
1377 } else {
1378 /* Do not surpass the resulting int64_t range. Depending on the amount of precision, the integer part
1379 * and decimal part have specific ranges they must comply to. */
1380 precision_factor = 1;
1381 for (i = 0; i < precision; i++)
1382 precision_factor *= 10;
1383 integer_max = INT64_MAX / precision_factor;
1384 if (integer == integer_max)
1385 decimal_max = INT64_MAX % precision_factor;
1386 else
1387 decimal_max = INT64_MAX;
1388 }
1389
1390 if (integer > integer_max)
1391 return -ERANGE;
1392 if (decimal > decimal_max)
1393 return -ERANGE;
1394
1395 *val = sign * (integer * precision_factor + decimal);
1396 return 0;
1397}
1398
Neels Hofmeyr6d744982020-10-08 13:09:49 +02001399/*! Convert an integer to a floating point string using a decimal quotient (fixed-point precision).
Neels Hofmeyr87c3afb2020-09-30 21:47:47 +00001400 * For example, with precision = 3, convert -1230 to "-1.23".
Neels Hofmeyr6d744982020-10-08 13:09:49 +02001401 * The usable range of digits is -INT64_MAX .. INT64_MAX -- note, not INT64_MIN! The value of INT64_MIN is excluded to
1402 * reduce implementation complexity. See also utils_test.c.
1403 * The advantage over using printf("%.6g") is guaranteed precision: float or double types may apply rounding in the
1404 * conversion result. osmo_float_str_to_int() and osmo_int_to_float_str_buf() guarantee true results when converting
1405 * back and forth between string and int.
1406 * The resulting string omits trailing zeros in the fractional part (like "%g" would) but never applies rounding.
Neels Hofmeyr87c3afb2020-09-30 21:47:47 +00001407 * \param[out] buf Buffer to write string to.
1408 * \param[in] buflen sizeof(buf).
1409 * \param[in] val Value to convert to float.
1410 * \returns number of chars that would be written, like snprintf().
1411 */
1412int osmo_int_to_float_str_buf(char *buf, size_t buflen, int64_t val, unsigned int precision)
1413{
1414 struct osmo_strbuf sb = { .buf = buf, .len = buflen };
1415 unsigned int i;
1416 unsigned int w;
1417 int64_t precision_factor;
1418 if (val < 0) {
1419 OSMO_STRBUF_PRINTF(sb, "-");
1420 if (val == INT64_MIN) {
1421 OSMO_STRBUF_PRINTF(sb, "ERR");
1422 return sb.chars_needed;
1423 }
1424 val = -val;
1425 }
1426
1427 if (precision > 18) {
1428 /* Special case of returning more digits than fit in int64_t range, e.g.
1429 * osmo_int_to_float_str(12345678901234567, precision=25) -> "0.0000000012345678901234567". */
1430 if (!val) {
1431 OSMO_STRBUF_PRINTF(sb, "0");
1432 return sb.chars_needed;
1433 }
1434 OSMO_STRBUF_PRINTF(sb, "0.");
1435 for (i = 19; i < precision; i++)
1436 OSMO_STRBUF_PRINTF(sb, "0");
1437 precision = 19;
1438 } else {
1439 precision_factor = 1;
1440 for (i = 0; i < precision; i++)
1441 precision_factor *= 10;
1442
1443 OSMO_STRBUF_PRINTF(sb, "%" PRId64, val / precision_factor);
1444 val %= precision_factor;
1445 if (!val)
1446 return sb.chars_needed;
1447 OSMO_STRBUF_PRINTF(sb, ".");
1448 }
1449
1450 /* print fractional part, skip trailing zeros */
1451 w = precision;
1452 while (!(val % 10)) {
1453 val /= 10;
1454 w--;
1455 }
1456 OSMO_STRBUF_PRINTF(sb, "%0*" PRId64, w, val);
1457 return sb.chars_needed;
1458}
1459
1460/*! Convert an integer with a factor of a million to a floating point string.
1461 * For example, convert -1230000 to "-1.23".
1462 * \param[in] ctx Talloc ctx to allocate string buffer from.
1463 * \param[in] val Value to convert to float.
1464 * \returns resulting string, dynamically allocated.
1465 */
1466char *osmo_int_to_float_str_c(void *ctx, int64_t val, unsigned int precision)
1467{
1468 OSMO_NAME_C_IMPL(ctx, 16, "ERROR", osmo_int_to_float_str_buf, val, precision)
1469}
1470
Neels Hofmeyr47773342021-09-05 18:48:31 +02001471/*! Convert a string of a number to int64_t, including all common strtoll() validity checks.
1472 * It's not so trivial to call strtoll() and properly verify that the input string was indeed a valid number string.
1473 * \param[out] result Buffer for the resulting integer number, or NULL if the caller is only interested in the
1474 * validation result (returned rc).
1475 * \param[in] str The string to convert.
1476 * \param[in] base The integer base, i.e. 10 for decimal numbers or 16 for hexadecimal, as in strtoll().
1477 * \param[in] min_val The smallest valid number expected in the string.
1478 * \param[in] max_val The largest valid number expected in the string.
1479 * \return 0 on success, -EOVERFLOW if the number in the string exceeds int64_t, -ENOTSUPP if the base is not supported,
1480 * -ERANGE if the converted number exceeds the range [min_val..max_val] but is still within int64_t range, -E2BIG if
1481 * surplus characters follow after the number, -EINVAL if the string does not contain a number. In case of -ERANGE and
1482 * -E2BIG, the converted number is still accurately returned in result. In case of -EOVERFLOW, the returned value is
1483 * clamped to INT64_MIN..INT64_MAX.
1484 */
1485int osmo_str_to_int64(int64_t *result, const char *str, int base, int64_t min_val, int64_t max_val)
1486{
1487 long long int val;
1488 char *endptr;
1489 if (result)
1490 *result = 0;
1491 if (!str || !*str)
1492 return -EINVAL;
1493 errno = 0;
1494 val = strtoll(str, &endptr, base);
1495 /* In case the number string exceeds long long int range, strtoll() clamps the returned value to LLONG_MIN or
1496 * LLONG_MAX. Make sure of the same here with respect to int64_t. */
1497 if (val < INT64_MIN) {
1498 if (result)
1499 *result = INT64_MIN;
1500 return -ERANGE;
1501 }
1502 if (val > INT64_MAX) {
1503 if (result)
1504 *result = INT64_MAX;
1505 return -ERANGE;
1506 }
1507 if (result)
1508 *result = (int64_t)val;
1509 switch (errno) {
1510 case 0:
1511 break;
1512 case ERANGE:
1513 return -EOVERFLOW;
1514 default:
1515 case EINVAL:
1516 return -ENOTSUP;
1517 }
1518 if (!endptr || *endptr) {
1519 /* No chars were converted */
1520 if (endptr == str)
1521 return -EINVAL;
1522 /* Or there are surplus chars after the converted number */
1523 return -E2BIG;
1524 }
1525 if (val < min_val || val > max_val)
1526 return -ERANGE;
1527 return 0;
1528}
1529
1530/*! Convert a string of a number to int, including all common strtoll() validity checks.
1531 * Same as osmo_str_to_int64() but using the plain int data type.
1532 * \param[out] result Buffer for the resulting integer number, or NULL if the caller is only interested in the
1533 * validation result (returned rc).
1534 * \param[in] str The string to convert.
1535 * \param[in] base The integer base, i.e. 10 for decimal numbers or 16 for hexadecimal, as in strtoll().
1536 * \param[in] min_val The smallest valid number expected in the string.
1537 * \param[in] max_val The largest valid number expected in the string.
1538 * \return 0 on success, -EOVERFLOW if the number in the string exceeds int range, -ENOTSUPP if the base is not supported,
1539 * -ERANGE if the converted number exceeds the range [min_val..max_val] but is still within int range, -E2BIG if
1540 * surplus characters follow after the number, -EINVAL if the string does not contain a number. In case of -ERANGE and
1541 * -E2BIG, the converted number is still accurately returned in result. In case of -EOVERFLOW, the returned value is
1542 * clamped to INT_MIN..INT_MAX.
1543 */
1544int osmo_str_to_int(int *result, const char *str, int base, int min_val, int max_val)
1545{
1546 int64_t val;
1547 int rc = osmo_str_to_int64(&val, str, base, min_val, max_val);
1548 /* In case the number string exceeds long long int range, strtoll() clamps the returned value to LLONG_MIN or
1549 * LLONG_MAX. Make sure of the same here with respect to int. */
1550 if (val < INT_MIN) {
1551 if (result)
1552 *result = INT_MIN;
1553 return -EOVERFLOW;
1554 }
1555 if (val > INT_MAX) {
1556 if (result)
1557 *result = INT_MAX;
1558 return -EOVERFLOW;
1559 }
1560 if (result)
1561 *result = (int)val;
1562 return rc;
1563}
1564
Vadim Yanitskiyc5497192021-06-07 16:30:28 +02001565/*! Replace a string using talloc and release its prior content (if any).
1566 * This is a format string capable equivalent of osmo_talloc_replace_string().
1567 * \param[in] ctx Talloc context to use for allocation.
1568 * \param[out] dst Pointer to string, will be updated with ptr to new string.
1569 * \param[in] fmt Format string that will be copied to newly allocated string. */
1570void osmo_talloc_replace_string_fmt(void *ctx, char **dst, const char *fmt, ...)
1571{
1572 char *name = NULL;
1573
1574 if (fmt != NULL) {
1575 va_list ap;
1576
1577 va_start(ap, fmt);
1578 name = talloc_vasprintf(ctx, fmt, ap);
1579 va_end(ap);
1580 }
1581
1582 talloc_free(*dst);
1583 *dst = name;
1584}
1585
Neels Hofmeyr0aeda1b2017-01-13 14:16:02 +01001586/*! @} */