blob: bec4b75eddaa9ab99db27eb119254ef130a150f0 [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{
150 char *dst_end = dst + dst_size - 1;
151 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
157 for (nibble_i = start_nibble; nibble_i < end_nibble && dst < dst_end; nibble_i++, dst++) {
158 uint8_t nibble = bcd[nibble_i >> 1];
159 if ((nibble_i & 1))
160 nibble >>= 4;
161 nibble &= 0xf;
162
163 if (!allow_hex && nibble > 9)
164 rc = -EINVAL;
165
166 *dst = osmo_bcd2char(nibble);
167 }
168 *dst = '\0';
169
170 if (rc < 0)
171 return rc;
172 return OSMO_MAX(0, end_nibble - start_nibble);
173}
174
Neels Hofmeyr83025bf2020-05-26 02:45:23 +0200175/*! Convert string to BCD.
176 * The given nibble offsets are interpreted in BCD order, i.e. nibble 0 is bcd[0] & 0x0f, nibble 1 is bcd[0] & 0xf0, nibble
177 * 3 is bcd[1] & 0x0f, etc..
178 * \param[out] dst Output BCD buffer.
179 * \param[in] dst_size sizeof() the output string buffer.
180 * \param[in] digits String containing decimal or hexadecimal digits in upper or lower case.
181 * \param[in] start_nibble Offset to start from, in nibbles, typically 1 to skip the first (MI type) nibble.
182 * \param[in] end_nibble Negative to write all digits found in str, followed by 0xf nibbles to fill any started octet.
183 * If >= 0, stop before this offset in nibbles, e.g. to get default behavior, pass
184 * start_nibble + strlen(str) + ((start_nibble + strlen(str)) & 1? 1 : 0) + 1.
185 * \param[in] allow_hex If false, return error if there are hexadecimal digits (A-F). If true, write those to
186 * BCD.
187 * \returns The buffer size in octets that is used to place all bcd digits (including the skipped nibbles
188 * from 'start_nibble' and rounded up to full octets); -EINVAL on invalid digits;
189 * -ENOMEM if dst is NULL, if dst_size is too small to contain all nibbles, or if start_nibble is negative.
190 */
191int osmo_str2bcd(uint8_t *dst, size_t dst_size, const char *digits, int start_nibble, int end_nibble, bool allow_hex)
192{
193 const char *digit = digits;
194 int nibble_i;
195
196 if (!dst || !dst_size || start_nibble < 0)
197 return -ENOMEM;
198
199 if (end_nibble < 0) {
200 end_nibble = start_nibble + strlen(digits);
201 /* If the last octet is not complete, add another filler nibble */
202 if (end_nibble & 1)
203 end_nibble++;
204 }
205 if ((end_nibble / 2) > dst_size)
206 return -ENOMEM;
207
208 for (nibble_i = start_nibble; nibble_i < end_nibble; nibble_i++) {
209 uint8_t nibble = 0xf;
210 int octet = nibble_i >> 1;
211 if (*digit) {
212 char c = *digit;
213 digit++;
214 if (c >= '0' && c <= '9')
215 nibble = c - '0';
216 else if (allow_hex && c >= 'A' && c <= 'F')
217 nibble = 0xa + (c - 'A');
218 else if (allow_hex && c >= 'a' && c <= 'f')
219 nibble = 0xa + (c - 'a');
220 else
221 return -EINVAL;
222 }
223 nibble &= 0xf;
224 if ((nibble_i & 1))
225 dst[octet] = (nibble << 4) | (dst[octet] & 0x0f);
226 else
227 dst[octet] = (dst[octet] & 0xf0) | nibble;
228 }
229
230 /* floor(float(end_nibble) / 2) */
231 return end_nibble / 2;
232}
233
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200234/*! Parse a string containing hexadecimal digits
Harald Weltede6e4982012-12-06 21:25:27 +0100235 * \param[in] str string containing ASCII encoded hexadecimal digits
236 * \param[out] b output buffer
237 * \param[in] max_len maximum space in output buffer
Neels Hofmeyr3de7b052015-09-23 23:16:53 +0200238 * \returns number of parsed octets, or -1 on error
Harald Weltede6e4982012-12-06 21:25:27 +0100239 */
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200240int osmo_hexparse(const char *str, uint8_t *b, int max_len)
Harald Welte3eba9912010-07-30 10:37:29 +0200241
242{
Neels Hofmeyr437ed4a2017-02-14 15:54:31 +0100243 char c;
244 uint8_t v;
245 const char *strpos;
246 unsigned int nibblepos = 0;
Harald Welte3eba9912010-07-30 10:37:29 +0200247
248 memset(b, 0x00, max_len);
249
Neels Hofmeyr437ed4a2017-02-14 15:54:31 +0100250 for (strpos = str; (c = *strpos); strpos++) {
251 /* skip whitespace */
252 if (c == ' ' || c == '\t' || c == '\n' || c == '\r')
253 continue;
254
255 /* If the buffer is too small, error out */
256 if (nibblepos >= (max_len << 1))
257 return -1;
258
Harald Welte3eba9912010-07-30 10:37:29 +0200259 if (c >= '0' && c <= '9')
260 v = c - '0';
261 else if (c >= 'a' && c <= 'f')
262 v = 10 + (c - 'a');
263 else if (c >= 'A' && c <= 'F')
264 v = 10 + (c - 'A');
265 else
266 return -1;
Neels Hofmeyr437ed4a2017-02-14 15:54:31 +0100267
268 b[nibblepos >> 1] |= v << (nibblepos & 1 ? 0 : 4);
269 nibblepos ++;
Harald Welte3eba9912010-07-30 10:37:29 +0200270 }
271
Neels Hofmeyr437ed4a2017-02-14 15:54:31 +0100272 /* In case of uneven amount of digits, the last byte is not complete
273 * and that's an error. */
274 if (nibblepos & 1)
275 return -1;
276
277 return nibblepos >> 1;
Harald Welte3eba9912010-07-30 10:37:29 +0200278}
Harald Welte40481e82010-07-30 11:40:32 +0200279
Harald Welte171ef822019-03-28 10:49:05 +0100280static __thread char hexd_buff[4096];
Nils O. SelÄsdal32447022014-01-02 14:04:43 +0100281static const char hex_chars[] = "0123456789abcdef";
Harald Welte40481e82010-07-30 11:40:32 +0200282
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100283/*! Convert binary sequence to hexadecimal ASCII string.
284 * \param[out] out_buf Output buffer to write the resulting string to.
285 * \param[in] out_buf_size sizeof(out_buf).
286 * \param[in] buf Input buffer, pointer to sequence of bytes.
287 * \param[in] len Length of input buf in number of bytes.
288 * \param[in] delim String to separate each byte; NULL or "" for no delim.
289 * \param[in] delim_after_last If true, end the string in delim (true: "1a:ef:d9:", false: "1a:ef:d9");
290 * if out_buf has insufficient space, the string will always end in a delim.
291 * \returns out_buf, containing a zero-terminated string, or "" (empty string) if out_buf == NULL or out_buf_size < 1.
292 *
293 * This function will print a sequence of bytes as hexadecimal numbers, adding one delim between each byte (e.g. for
294 * delim passed as ":", return a string like "1a:ef:d9").
295 *
296 * The delim_after_last argument exists to be able to exactly show the original osmo_hexdump() behavior, which always
297 * ends the string with a delimiter.
298 */
299const char *osmo_hexdump_buf(char *out_buf, size_t out_buf_size, const unsigned char *buf, int len, const char *delim,
300 bool delim_after_last)
Harald Welte40481e82010-07-30 11:40:32 +0200301{
302 int i;
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100303 char *cur = out_buf;
304 size_t delim_len;
Harald Welte40481e82010-07-30 11:40:32 +0200305
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100306 if (!out_buf || !out_buf_size)
307 return "";
308
309 delim = delim ? : "";
310 delim_len = strlen(delim);
311
Harald Welte40481e82010-07-30 11:40:32 +0200312 for (i = 0; i < len; i++) {
Nils O. SelÄsdal32447022014-01-02 14:04:43 +0100313 const char *delimp = delim;
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100314 int len_remain = out_buf_size - (cur - out_buf) - 1;
315 if (len_remain < (2 + delim_len)
316 && !(!delim_after_last && i == (len - 1) && len_remain >= 2))
Holger Hans Peter Freyther128d9e22011-07-15 16:07:23 +0200317 break;
Nils O. SelÄsdal32447022014-01-02 14:04:43 +0100318
319 *cur++ = hex_chars[buf[i] >> 4];
320 *cur++ = hex_chars[buf[i] & 0xf];
321
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100322 if (i == (len - 1) && !delim_after_last)
323 break;
324
Nils O. SelÄsdal32447022014-01-02 14:04:43 +0100325 while (len_remain > 1 && *delimp) {
326 *cur++ = *delimp++;
327 len_remain--;
328 }
Harald Welte40481e82010-07-30 11:40:32 +0200329 }
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100330 *cur = '\0';
331 return out_buf;
Harald Welte40481e82010-07-30 11:40:32 +0200332}
Harald Weltedee47cd2010-07-30 11:43:30 +0200333
Harald Welte4a62eda2019-03-18 18:27:00 +0100334/*! Convert a sequence of unpacked bits to ASCII string, in user-supplied buffer.
335 * \param[out] buf caller-provided output string buffer
336 * \param[out] buf_len size of buf in bytes
Harald Welte8598f182011-08-17 14:19:27 +0200337 * \param[in] bits A sequence of unpacked bits
338 * \param[in] len Length of bits
Neels Hofmeyrdd7b6f92019-11-20 21:32:29 +0100339 * \return The output buffer (buf).
Harald Welte8598f182011-08-17 14:19:27 +0200340 */
Harald Welte4a62eda2019-03-18 18:27:00 +0100341char *osmo_ubit_dump_buf(char *buf, size_t buf_len, const uint8_t *bits, unsigned int len)
Harald Welte3d0ac5e2011-02-08 16:55:03 +0100342{
343 int i;
344
Harald Welte4a62eda2019-03-18 18:27:00 +0100345 if (len > buf_len-1)
346 len = buf_len-1;
347 memset(buf, 0, buf_len);
Harald Welte3d0ac5e2011-02-08 16:55:03 +0100348
349 for (i = 0; i < len; i++) {
350 char outch;
351 switch (bits[i]) {
352 case 0:
353 outch = '0';
354 break;
355 case 0xff:
356 outch = '?';
357 break;
358 case 1:
359 outch = '1';
360 break;
361 default:
362 outch = 'E';
363 break;
364 }
Harald Welte4a62eda2019-03-18 18:27:00 +0100365 buf[i] = outch;
Harald Welte3d0ac5e2011-02-08 16:55:03 +0100366 }
Harald Welte4a62eda2019-03-18 18:27:00 +0100367 buf[buf_len-1] = 0;
368 return buf;
369}
370
371/*! Convert a sequence of unpacked bits to ASCII string, in static buffer.
372 * \param[in] bits A sequence of unpacked bits
373 * \param[in] len Length of bits
374 * \returns string representation in static buffer.
375 */
376char *osmo_ubit_dump(const uint8_t *bits, unsigned int len)
377{
378 return osmo_ubit_dump_buf(hexd_buff, sizeof(hexd_buff), bits, len);
Harald Welte3d0ac5e2011-02-08 16:55:03 +0100379}
380
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200381/*! Convert binary sequence to hexadecimal ASCII string
Harald Welte8598f182011-08-17 14:19:27 +0200382 * \param[in] buf pointer to sequence of bytes
383 * \param[in] len length of buf in number of bytes
384 * \returns pointer to zero-terminated string
385 *
386 * This function will print a sequence of bytes as hexadecimal numbers,
387 * adding one space character between each byte (e.g. "1a ef d9")
Harald Welte096a6662017-10-16 14:33:11 +0200388 *
389 * The maximum size of the output buffer is 4096 bytes, i.e. the maximum
390 * number of input bytes that can be printed in one call is 1365!
Harald Welte8598f182011-08-17 14:19:27 +0200391 */
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200392char *osmo_hexdump(const unsigned char *buf, int len)
Harald Weltedee47cd2010-07-30 11:43:30 +0200393{
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100394 osmo_hexdump_buf(hexd_buff, sizeof(hexd_buff), buf, len, " ", true);
395 return hexd_buff;
Harald Weltedee47cd2010-07-30 11:43:30 +0200396}
397
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200398/*! Convert binary sequence to hexadecimal ASCII string
Harald Welte179f3572019-03-18 18:38:47 +0100399 * \param[in] ctx talloc context from where to allocate the output string
400 * \param[in] buf pointer to sequence of bytes
401 * \param[in] len length of buf in number of bytes
402 * \returns pointer to zero-terminated string
403 *
404 * This function will print a sequence of bytes as hexadecimal numbers,
405 * adding one space character between each byte (e.g. "1a ef d9")
Harald Welte179f3572019-03-18 18:38:47 +0100406 */
407char *osmo_hexdump_c(const void *ctx, const unsigned char *buf, int len)
408{
Vadim Yanitskiy4f619c22019-04-12 21:48:07 +0700409 size_t hexd_buff_len = len * 3 + 1;
410 char *hexd_buff = talloc_size(ctx, hexd_buff_len);
Harald Welte179f3572019-03-18 18:38:47 +0100411 if (!hexd_buff)
412 return NULL;
Vadim Yanitskiy4f619c22019-04-12 21:48:07 +0700413 osmo_hexdump_buf(hexd_buff, hexd_buff_len, buf, len, " ", true);
Harald Welte179f3572019-03-18 18:38:47 +0100414 return hexd_buff;
415}
416
417/*! Convert binary sequence to hexadecimal ASCII string
Harald Welte8598f182011-08-17 14:19:27 +0200418 * \param[in] buf pointer to sequence of bytes
419 * \param[in] len length of buf in number of bytes
420 * \returns pointer to zero-terminated string
421 *
422 * This function will print a sequence of bytes as hexadecimal numbers,
423 * without any space character between each byte (e.g. "1aefd9")
Harald Welte096a6662017-10-16 14:33:11 +0200424 *
425 * The maximum size of the output buffer is 4096 bytes, i.e. the maximum
426 * number of input bytes that can be printed in one call is 2048!
Harald Welte8598f182011-08-17 14:19:27 +0200427 */
Sylvain Munautff23d242011-11-10 23:03:18 +0100428char *osmo_hexdump_nospc(const unsigned char *buf, int len)
Harald Weltedee47cd2010-07-30 11:43:30 +0200429{
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100430 osmo_hexdump_buf(hexd_buff, sizeof(hexd_buff), buf, len, "", true);
431 return hexd_buff;
Harald Weltedee47cd2010-07-30 11:43:30 +0200432}
Harald Welte28222962011-02-18 20:37:04 +0100433
Harald Welte179f3572019-03-18 18:38:47 +0100434/*! Convert binary sequence to hexadecimal ASCII string
435 * \param[in] ctx talloc context from where to allocate the output string
436 * \param[in] buf pointer to sequence of bytes
437 * \param[in] len length of buf in number of bytes
438 * \returns pointer to zero-terminated string
439 *
440 * This function will print a sequence of bytes as hexadecimal numbers,
441 * without any space character between each byte (e.g. "1aefd9")
Harald Welte179f3572019-03-18 18:38:47 +0100442 */
443char *osmo_hexdump_nospc_c(const void *ctx, const unsigned char *buf, int len)
444{
Vadim Yanitskiy4f619c22019-04-12 21:48:07 +0700445 size_t hexd_buff_len = len * 2 + 1;
446 char *hexd_buff = talloc_size(ctx, hexd_buff_len);
Harald Welte179f3572019-03-18 18:38:47 +0100447 if (!hexd_buff)
448 return NULL;
Vadim Yanitskiy4f619c22019-04-12 21:48:07 +0700449 osmo_hexdump_buf(hexd_buff, hexd_buff_len, buf, len, "", true);
Harald Welte179f3572019-03-18 18:38:47 +0100450 return hexd_buff;
451}
452
453
Holger Hans Peter Freyther9a1a5a12015-04-11 19:26:55 +0200454/* Compat with previous typo to preserve abi */
Sylvain Munaute55ae3a2011-11-11 23:06:55 +0100455char *osmo_osmo_hexdump_nospc(const unsigned char *buf, int len)
Holger Hans Peter Freyther9a1a5a12015-04-11 19:26:55 +0200456#if defined(__MACH__) && defined(__APPLE__)
457 ;
458#else
Sylvain Munaut17af41d2011-11-19 22:30:39 +0100459 __attribute__((weak, alias("osmo_hexdump_nospc")));
Holger Hans Peter Freyther9a1a5a12015-04-11 19:26:55 +0200460#endif
Sylvain Munaute55ae3a2011-11-11 23:06:55 +0100461
Harald Welte28222962011-02-18 20:37:04 +0100462#include "../config.h"
463#ifdef HAVE_CTYPE_H
464#include <ctype.h>
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200465/*! Convert an entire string to lower case
Harald Welte8598f182011-08-17 14:19:27 +0200466 * \param[out] out output string, caller-allocated
467 * \param[in] in input string
468 */
Harald Welte28222962011-02-18 20:37:04 +0100469void osmo_str2lower(char *out, const char *in)
470{
471 unsigned int i;
472
473 for (i = 0; i < strlen(in); i++)
Pau Espin Pedrol399a6f02017-06-18 14:07:37 +0200474 out[i] = tolower((const unsigned char)in[i]);
Harald Welte28222962011-02-18 20:37:04 +0100475 out[strlen(in)] = '\0';
476}
477
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200478/*! Convert an entire string to upper case
Harald Welte8598f182011-08-17 14:19:27 +0200479 * \param[out] out output string, caller-allocated
480 * \param[in] in input string
481 */
Harald Welte28222962011-02-18 20:37:04 +0100482void osmo_str2upper(char *out, const char *in)
483{
484 unsigned int i;
485
486 for (i = 0; i < strlen(in); i++)
Pau Espin Pedrol399a6f02017-06-18 14:07:37 +0200487 out[i] = toupper((const unsigned char)in[i]);
Harald Welte28222962011-02-18 20:37:04 +0100488 out[strlen(in)] = '\0';
489}
490#endif /* HAVE_CTYPE_H */
Harald Welte8598f182011-08-17 14:19:27 +0200491
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200492/*! Wishful thinking to generate a constant time compare
Harald Welte9709b2e2016-04-25 18:47:53 +0200493 * \param[in] exp Expected data
494 * \param[in] rel Comparison value
495 * \param[in] count Number of bytes to compare
496 * \returns 1 in case \a exp equals \a rel; zero otherwise
497 *
498 * Compare count bytes of exp to rel. Return 0 if they are identical, 1
499 * otherwise. Do not return a mismatch on the first mismatching byte,
500 * but always compare all bytes, regardless. The idea is that the amount of
501 * matching bytes cannot be inferred from the time the comparison took. */
502int osmo_constant_time_cmp(const uint8_t *exp, const uint8_t *rel, const int count)
503{
504 int x = 0, i;
505
506 for (i = 0; i < count; ++i)
507 x |= exp[i] ^ rel[i];
508
509 /* if x is zero, all data was identical */
510 return x? 1 : 0;
511}
512
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200513/*! Generic retrieval of 1..8 bytes as big-endian uint64_t
Harald Welte9709b2e2016-04-25 18:47:53 +0200514 * \param[in] data Input data as byte-array
515 * \param[in] data_len Length of \a data in octets
516 * \returns uint64_t of \a data interpreted as big-endian
517 *
518 * This is like osmo_load64be_ext, except that if data_len is less than
519 * sizeof(uint64_t), the data is interpreted as the least significant bytes
520 * (osmo_load64be_ext loads them as the most significant bytes into the
521 * returned uint64_t). In this way, any integer size up to 64 bits can be
522 * decoded conveniently by using sizeof(), without the need to call specific
523 * numbered functions (osmo_load16, 32, ...). */
524uint64_t osmo_decode_big_endian(const uint8_t *data, size_t data_len)
525{
526 uint64_t value = 0;
527
528 while (data_len > 0) {
529 value = (value << 8) + *data;
530 data += 1;
531 data_len -= 1;
532 }
533
534 return value;
535}
536
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200537/*! Generic big-endian encoding of big endian number up to 64bit
Harald Welte9709b2e2016-04-25 18:47:53 +0200538 * \param[in] value unsigned integer value to be stored
Pau Espin Pedrolc29d5132020-09-21 17:09:31 +0200539 * \param[in] data_len number of octets
Harald Welte9709b2e2016-04-25 18:47:53 +0200540 * \returns static buffer containing big-endian stored value
541 *
542 * This is like osmo_store64be_ext, except that this returns a static buffer of
543 * the result (for convenience, but not threadsafe). If data_len is less than
544 * sizeof(uint64_t), only the least significant bytes of value are encoded. */
545uint8_t *osmo_encode_big_endian(uint64_t value, size_t data_len)
546{
Harald Welte171ef822019-03-28 10:49:05 +0100547 static __thread uint8_t buf[sizeof(uint64_t)];
Harald Welte9709b2e2016-04-25 18:47:53 +0200548 OSMO_ASSERT(data_len <= ARRAY_SIZE(buf));
549 osmo_store64be_ext(value, buf, data_len);
550 return buf;
551}
Harald Welteaeecc482016-11-26 10:41:40 +0100552
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200553/*! Copy a C-string into a sized buffer
Harald Welteaeecc482016-11-26 10:41:40 +0100554 * \param[in] src source string
555 * \param[out] dst destination string
Neels Hofmeyrdf83ece2017-01-13 13:55:43 +0100556 * \param[in] siz size of the \a dst buffer
557 * \returns length of \a src
Harald Welteaeecc482016-11-26 10:41:40 +0100558 *
Neels Hofmeyrdf83ece2017-01-13 13:55:43 +0100559 * Copy at most \a siz bytes from \a src to \a dst, ensuring that the result is
560 * NUL terminated. The NUL character is included in \a siz, i.e. passing the
561 * actual sizeof(*dst) is correct.
Neels Hofmeyrff65d242019-11-19 00:21:14 +0100562 *
563 * Note, a similar function that also limits the input buffer size is osmo_print_n().
Harald Welteaeecc482016-11-26 10:41:40 +0100564 */
565size_t osmo_strlcpy(char *dst, const char *src, size_t siz)
566{
Neels Hofmeyrbcf9f232017-10-25 04:16:45 +0200567 size_t ret = src ? strlen(src) : 0;
Harald Welteaeecc482016-11-26 10:41:40 +0100568
569 if (siz) {
Pau Espin Pedrol53fbc672020-09-21 17:13:30 +0200570 size_t len = OSMO_MIN(siz - 1, ret);
Pau Espin Pedrolc29d5132020-09-21 17:09:31 +0200571 if (len)
Neels Hofmeyrebd3cdd2017-11-18 23:07:38 +0100572 memcpy(dst, src, len);
Harald Welteaeecc482016-11-26 10:41:40 +0100573 dst[len] = '\0';
574 }
575 return ret;
576}
Neels Hofmeyr0aeda1b2017-01-13 14:16:02 +0100577
Neels Hofmeyr06356fd2019-11-19 01:38:10 +0100578/*! Find first occurence of a char in a size limited string.
579 * Like strchr() but with a buffer size limit.
580 * \param[in] str String buffer to examine.
581 * \param[in] str_size sizeof(str).
582 * \param[in] c Character to look for.
583 * \return Pointer to the matched char, or NULL if not found.
584 */
585const char *osmo_strnchr(const char *str, size_t str_size, char c)
586{
587 const char *end = str + str_size;
588 const char *pos;
589 if (!str)
590 return NULL;
591 for (pos = str; pos < end; pos++) {
592 if (c == *pos)
593 return pos;
594 if (!*pos)
595 return NULL;
596 }
597 return NULL;
598}
599
Neels Hofmeyr4335bad2017-10-07 04:39:14 +0200600/*! Validate that a given string is a hex string within given size limits.
601 * Note that each hex digit amounts to a nibble, so if checking for a hex
602 * string to result in N bytes, pass amount of digits as 2*N.
603 * \param str A nul-terminated string to validate, or NULL.
604 * \param min_digits least permitted amount of digits.
605 * \param max_digits most permitted amount of digits.
606 * \param require_even if true, require an even amount of digits.
607 * \returns true when the hex_str contains only hexadecimal digits (no
608 * whitespace) and matches the requested length; also true
609 * when min_digits <= 0 and str is NULL.
610 */
611bool osmo_is_hexstr(const char *str, int min_digits, int max_digits,
612 bool require_even)
613{
614 int len;
615 /* Use unsigned char * to avoid a compiler warning of
616 * "error: array subscript has type 'char' [-Werror=char-subscripts]" */
617 const unsigned char *pos = (const unsigned char*)str;
618 if (!pos)
619 return min_digits < 1;
620 for (len = 0; *pos && len < max_digits; len++, pos++)
621 if (!isxdigit(*pos))
622 return false;
623 if (len < min_digits)
624 return false;
625 /* With not too many digits, we should have reached *str == nul */
626 if (*pos)
627 return false;
628 if (require_even && (len & 1))
629 return false;
Harald Weltefebe83c2017-10-03 17:41:59 +0800630
631 return true;
632}
633
Neels Hofmeyrb480b742019-04-11 06:58:44 +0200634static const char osmo_identifier_illegal_chars[] = "., {}[]()<>|~\\^`'\"?=;/+*&%$#!";
635
Harald Weltefebe83c2017-10-03 17:41:59 +0800636/*! Determine if a given identifier is valid, i.e. doesn't contain illegal chars
637 * \param[in] str String to validate
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100638 * \param[in] sep_chars Permitted separation characters between identifiers.
639 * \returns true in case \a str contains only valid identifiers and sep_chars, false otherwise
Harald Weltefebe83c2017-10-03 17:41:59 +0800640 */
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100641bool osmo_separated_identifiers_valid(const char *str, const char *sep_chars)
Harald Weltefebe83c2017-10-03 17:41:59 +0800642{
643 /* characters that are illegal in names */
Harald Weltefebe83c2017-10-03 17:41:59 +0800644 unsigned int i;
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100645 size_t len;
Harald Weltefebe83c2017-10-03 17:41:59 +0800646
647 /* an empty string is not a valid identifier */
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100648 if (!str || (len = strlen(str)) == 0)
Harald Weltefebe83c2017-10-03 17:41:59 +0800649 return false;
650
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100651 for (i = 0; i < len; i++) {
652 if (sep_chars && strchr(sep_chars, str[i]))
653 continue;
Harald Weltefebe83c2017-10-03 17:41:59 +0800654 /* check for 7-bit ASCII */
655 if (str[i] & 0x80)
656 return false;
Neels Hofmeyre5a2bdb2017-12-16 04:54:37 +0100657 if (!isprint((int)str[i]))
658 return false;
Harald Weltefebe83c2017-10-03 17:41:59 +0800659 /* check for some explicit reserved control characters */
Neels Hofmeyrb480b742019-04-11 06:58:44 +0200660 if (strchr(osmo_identifier_illegal_chars, str[i]))
Harald Weltefebe83c2017-10-03 17:41:59 +0800661 return false;
662 }
663
Neels Hofmeyr4335bad2017-10-07 04:39:14 +0200664 return true;
665}
666
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100667/*! Determine if a given identifier is valid, i.e. doesn't contain illegal chars
668 * \param[in] str String to validate
669 * \returns true in case \a str contains valid identifier, false otherwise
670 */
671bool osmo_identifier_valid(const char *str)
672{
673 return osmo_separated_identifiers_valid(str, NULL);
674}
675
Neels Hofmeyrb480b742019-04-11 06:58:44 +0200676/*! Replace characters in the given string buffer so that it is guaranteed to pass osmo_separated_identifiers_valid().
677 * To guarantee passing osmo_separated_identifiers_valid(), replace_with must not itself be an illegal character. If in
678 * doubt, use '-'.
679 * \param[inout] str Identifier to sanitize, must be nul terminated and in a writable buffer.
Neels Hofmeyr5aa421f2021-07-07 23:50:29 +0200680 * \param[in] sep_chars Additional characters that are to be replaced besides osmo_identifier_illegal_chars.
Neels Hofmeyrb480b742019-04-11 06:58:44 +0200681 * \param[in] replace_with Replace any illegal characters with this character.
682 */
683void osmo_identifier_sanitize_buf(char *str, const char *sep_chars, char replace_with)
684{
685 char *pos;
686 if (!str)
687 return;
688 for (pos = str; *pos; pos++) {
689 if (strchr(osmo_identifier_illegal_chars, *pos)
690 || (sep_chars && strchr(sep_chars, *pos)))
691 *pos = replace_with;
692 }
693}
694
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100695/*! Like osmo_escape_str_buf2, but with unusual ordering of arguments, and may sometimes return string constants instead
696 * of writing to buf for error cases or empty input.
697 * Most *_buf() functions have the buffer and size as first arguments, here the arguments are last.
698 * In particular, this function signature doesn't work with OSMO_STRBUF_APPEND_NOLEN().
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100699 * \param[in] str A string that may contain any characters.
700 * \param[in] len Pass -1 to print until nul char, or >= 0 to force a length.
701 * \param[inout] buf string buffer to write escaped characters to.
702 * \param[in] bufsize size of \a buf.
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100703 * \returns buf containing an escaped representation, possibly truncated,
704 * or "(null)" if str == NULL, or "(error)" in case of errors.
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100705 */
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100706const char *osmo_escape_str_buf(const char *str, int in_len, char *buf, size_t bufsize)
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100707{
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100708 if (!str)
709 return "(null)";
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100710 if (!buf || !bufsize)
711 return "(error)";
712 return osmo_escape_str_buf2(buf, bufsize, str, in_len);
713}
714
715/*! Copy N characters to a buffer with a function signature useful for OSMO_STRBUF_APPEND().
716 * Similarly to snprintf(), the result is always nul terminated (except if buf is NULL or bufsize is 0).
717 * \param[out] buf Target buffer.
718 * \param[in] bufsize sizeof(buf).
719 * \param[in] str String to copy.
720 * \param[in] n Maximum number of non-nul characters to copy.
721 * \return Number of characters that would be written if bufsize were large enough excluding '\0' (like snprintf()).
722 */
723int osmo_print_n(char *buf, size_t bufsize, const char *str, size_t n)
724{
725 size_t write_n;
726
727 if (!str)
728 str = "";
729
730 n = strnlen(str, n);
731
732 if (!buf || !bufsize)
733 return n;
734 write_n = n;
735 if (write_n >= bufsize)
736 write_n = bufsize - 1;
737 if (write_n)
738 strncpy(buf, str, write_n);
739 buf[write_n] = '\0';
740
741 return n;
742}
743
744/*! Return the string with all non-printable characters escaped.
Neels Hofmeyrc36e2e42019-11-20 21:57:32 +0100745 * This internal function is the implementation for all osmo_escape_str* and osmo_quote_str* API versions.
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100746 * It provides both the legacy (non C compatible) escaping, as well as C compatible string constant syntax,
747 * 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 +0100748 * \param[out] buf string buffer to write escaped characters to.
749 * \param[in] bufsize sizeof(buf).
750 * \param[in] str A string that may contain any characters.
751 * \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 +0100752 * \param[in] legacy_format If false, return C compatible string constants ("\x0f"), if true the legacy
753 * escaping format ("\15"). The legacy format also escapes as "\a\b\f\v", while
754 * the non-legacy format also escapes those as "\xNN" sequences.
Neels Hofmeyrc36e2e42019-11-20 21:57:32 +0100755 * \return Number of characters that would be written if bufsize were large enough excluding '\0' (like snprintf()).
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100756 */
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100757static 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 +0100758{
759 struct osmo_strbuf sb = { .buf = buf, .len = bufsize };
760 int in_pos = 0;
761 int next_unprintable = 0;
762
763 if (!str)
764 in_len = 0;
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100765
766 if (in_len < 0)
767 in_len = strlen(str);
768
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100769 /* Make sure of '\0' termination */
770 if (!in_len)
771 OSMO_STRBUF_PRINTF(sb, "%s", "");
772
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100773 while (in_pos < in_len) {
774 for (next_unprintable = in_pos;
775 next_unprintable < in_len && isprint((int)str[next_unprintable])
776 && str[next_unprintable] != '"'
777 && str[next_unprintable] != '\\';
778 next_unprintable++);
779
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100780 OSMO_STRBUF_APPEND(sb, osmo_print_n, &str[in_pos], next_unprintable - in_pos);
781 in_pos = next_unprintable;
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100782
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100783 if (in_pos == in_len)
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100784 goto done;
785
786 switch (str[next_unprintable]) {
787#define BACKSLASH_CASE(c, repr) \
788 case c: \
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100789 OSMO_STRBUF_PRINTF(sb, "\\%c", repr); \
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100790 break
791
792 BACKSLASH_CASE('\n', 'n');
793 BACKSLASH_CASE('\r', 'r');
794 BACKSLASH_CASE('\t', 't');
795 BACKSLASH_CASE('\0', '0');
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100796 BACKSLASH_CASE('\\', '\\');
797 BACKSLASH_CASE('"', '"');
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100798
799 default:
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100800 if (legacy_format) {
801 switch (str[next_unprintable]) {
802 BACKSLASH_CASE('\a', 'a');
803 BACKSLASH_CASE('\b', 'b');
804 BACKSLASH_CASE('\v', 'v');
805 BACKSLASH_CASE('\f', 'f');
806 default:
807 OSMO_STRBUF_PRINTF(sb, "\\%u", (unsigned char)str[in_pos]);
808 break;
809 }
810 break;
811 }
812
813 OSMO_STRBUF_PRINTF(sb, "\\x%02x", (unsigned char)str[in_pos]);
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100814 break;
815 }
816 in_pos ++;
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100817#undef BACKSLASH_CASE
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100818 }
819
820done:
Neels Hofmeyrc36e2e42019-11-20 21:57:32 +0100821 return sb.chars_needed;
822}
823
824/*! Return the string with all non-printable characters escaped.
825 * \param[out] buf string buffer to write escaped characters to.
826 * \param[in] bufsize sizeof(buf).
827 * \param[in] str A string that may contain any characters.
828 * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length (also past nul chars).
829 * \return The output buffer (buf).
830 */
831char *osmo_escape_str_buf2(char *buf, size_t bufsize, const char *str, int in_len)
832{
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100833 _osmo_escape_str_buf(buf, bufsize, str, in_len, true);
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100834 return buf;
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100835}
836
837/*! Return the string with all non-printable characters escaped.
838 * Call osmo_escape_str_buf() with a static buffer.
839 * \param[in] str A string that may contain any characters.
840 * \param[in] len Pass -1 to print until nul char, or >= 0 to force a length.
841 * \returns buf containing an escaped representation, possibly truncated, or str itself.
842 */
843const char *osmo_escape_str(const char *str, int in_len)
844{
845 return osmo_escape_str_buf(str, in_len, namebuf, sizeof(namebuf));
846}
847
Harald Welte179f3572019-03-18 18:38:47 +0100848/*! Return the string with all non-printable characters escaped, in dynamically-allocated buffer.
849 * \param[in] str A string that may contain any characters.
850 * \param[in] len Pass -1 to print until nul char, or >= 0 to force a length.
851 * \returns dynamically-allocated output buffer, containing an escaped representation
852 */
853char *osmo_escape_str_c(const void *ctx, const char *str, int in_len)
854{
Neels Hofmeyrc36e2e42019-11-20 21:57:32 +0100855 /* The string will be at least as long as in_len, but some characters might need escaping.
856 * 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 +0100857 OSMO_NAME_C_IMPL(ctx, in_len + 16, "ERROR", _osmo_escape_str_buf, str, in_len, true);
Neels Hofmeyrc36e2e42019-11-20 21:57:32 +0100858}
859
860/*! Return a quoted and escaped representation of the string.
861 * This internal function is the implementation for all osmo_quote_str* API versions.
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100862 * It provides both the legacy (non C compatible) escaping, as well as C compatible string constant syntax,
863 * 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 +0100864 * \param[out] buf string buffer to write escaped characters to.
865 * \param[in] bufsize sizeof(buf).
866 * \param[in] str A string that may contain any characters.
867 * \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 +0100868 * \param[in] legacy_format If false, return C compatible string constants ("\x0f"), if true the legacy
869 * escaping format ("\15"). The legacy format also escapes as "\a\b\f\v", while
870 * the non-legacy format also escapes those as "\xNN" sequences.
Neels Hofmeyrc36e2e42019-11-20 21:57:32 +0100871 * \return Number of characters that would be written if bufsize were large enough excluding '\0' (like snprintf()).
872 */
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100873static 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 +0100874{
875 struct osmo_strbuf sb = { .buf = buf, .len = bufsize };
876 if (!str)
877 OSMO_STRBUF_PRINTF(sb, "NULL");
878 else {
879 OSMO_STRBUF_PRINTF(sb, "\"");
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100880 OSMO_STRBUF_APPEND(sb, _osmo_escape_str_buf, str, in_len, legacy_format);
Neels Hofmeyrc36e2e42019-11-20 21:57:32 +0100881 OSMO_STRBUF_PRINTF(sb, "\"");
882 }
883 return sb.chars_needed;
Harald Welte179f3572019-03-18 18:38:47 +0100884}
885
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100886/*! 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 +0200887 * This allows passing any char* value and get its C representation as string.
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100888 * The function signature is suitable for OSMO_STRBUF_APPEND_NOLEN().
889 * \param[out] buf string buffer to write escaped characters to.
890 * \param[in] bufsize sizeof(buf).
891 * \param[in] str A string that may contain any characters.
892 * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length.
Neels Hofmeyrdd7b6f92019-11-20 21:32:29 +0100893 * \return The output buffer (buf).
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100894 */
895char *osmo_quote_str_buf2(char *buf, size_t bufsize, const char *str, int in_len)
896{
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100897 _osmo_quote_str_buf(buf, bufsize, str, in_len, true);
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100898 return buf;
899}
900
901/*! Like osmo_quote_str_buf2, but with unusual ordering of arguments, and may sometimes return string constants instead
902 * of writing to buf for error cases or empty input.
903 * Most *_buf() functions have the buffer and size as first arguments, here the arguments are last.
904 * In particular, this function signature doesn't work with OSMO_STRBUF_APPEND_NOLEN().
Neels Hofmeyr04eb56f2018-04-09 00:41:28 +0200905 * \param[in] str A string that may contain any characters.
Neels Hofmeyr03e75532018-09-07 03:12:05 +0200906 * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length.
907 * \returns buf containing a quoted and escaped representation, possibly truncated.
Neels Hofmeyr04eb56f2018-04-09 00:41:28 +0200908 */
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100909const char *osmo_quote_str_buf(const char *str, int in_len, char *buf, size_t bufsize)
Neels Hofmeyr04eb56f2018-04-09 00:41:28 +0200910{
Neels Hofmeyr04eb56f2018-04-09 00:41:28 +0200911 if (!str)
912 return "NULL";
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100913 if (!buf || !bufsize)
914 return "(error)";
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100915 _osmo_quote_str_buf(buf, bufsize, str, in_len, true);
Neels Hofmeyr04eb56f2018-04-09 00:41:28 +0200916 return buf;
917}
918
Neels Hofmeyr03e75532018-09-07 03:12:05 +0200919/*! Like osmo_quote_str_buf() but returns the result in a static buffer.
920 * The static buffer is shared with get_value_string() and osmo_escape_str().
921 * \param[in] str A string that may contain any characters.
922 * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length.
923 * \returns static buffer containing a quoted and escaped representation, possibly truncated.
924 */
Neels Hofmeyr04eb56f2018-04-09 00:41:28 +0200925const char *osmo_quote_str(const char *str, int in_len)
926{
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100927 _osmo_quote_str_buf(namebuf, sizeof(namebuf), str, in_len, true);
Neels Hofmeyrc36e2e42019-11-20 21:57:32 +0100928 return namebuf;
Neels Hofmeyr04eb56f2018-04-09 00:41:28 +0200929}
930
Harald Welte179f3572019-03-18 18:38:47 +0100931/*! Like osmo_quote_str_buf() but returns the result in a dynamically-allocated buffer.
Harald Welte179f3572019-03-18 18:38:47 +0100932 * \param[in] str A string that may contain any characters.
933 * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length.
934 * \returns dynamically-allocated buffer containing a quoted and escaped representation.
935 */
936char *osmo_quote_str_c(const void *ctx, const char *str, int in_len)
937{
Neels Hofmeyrc36e2e42019-11-20 21:57:32 +0100938 /* The string will be at least as long as in_len, but some characters might need escaping.
939 * 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 +0100940 OSMO_NAME_C_IMPL(ctx, in_len + 16, "ERROR", _osmo_quote_str_buf, str, in_len, true);
941}
942
943/*! Return the string with all non-printable characters escaped.
944 * In contrast to osmo_escape_str_buf2(), this returns the needed buffer size suitable for OSMO_STRBUF_APPEND(), and
945 * this escapes characters in a way compatible with C string constant syntax.
946 * \param[out] buf string buffer to write escaped characters to.
947 * \param[in] bufsize sizeof(buf).
948 * \param[in] str A string that may contain any characters.
949 * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length (also past nul chars).
950 * \return Number of characters that would be written if bufsize were large enough excluding '\0' (like snprintf()).
951 */
952size_t osmo_escape_cstr_buf(char *buf, size_t bufsize, const char *str, int in_len)
953{
954 return _osmo_escape_str_buf(buf, bufsize, str, in_len, false);
955}
956
957/*! Return the string with all non-printable characters escaped, in dynamically-allocated buffer.
958 * In contrast to osmo_escape_str_c(), this escapes characters in a way compatible with C string constant syntax, and
959 * allocates sufficient memory in all cases.
960 * \param[in] str A string that may contain any characters.
961 * \param[in] len Pass -1 to print until nul char, or >= 0 to force a length.
962 * \returns dynamically-allocated buffer, containing an escaped representation.
963 */
964char *osmo_escape_cstr_c(void *ctx, const char *str, int in_len)
965{
966 /* 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. */
968 OSMO_NAME_C_IMPL(ctx, in_len + 16, "ERROR", _osmo_escape_str_buf, str, in_len, false);
969}
970
971/*! Like osmo_escape_str_buf2(), but returns double-quotes around a string, or "NULL" for a NULL string.
972 * This allows passing any char* value and get its C representation as string.
973 * The function signature is suitable for OSMO_STRBUF_APPEND_NOLEN().
974 * In contrast to osmo_escape_str_buf2(), this returns the needed buffer size suitable for OSMO_STRBUF_APPEND(), and
975 * this escapes characters in a way compatible with C string constant syntax.
976 * \param[out] buf string buffer to write escaped characters to.
977 * \param[in] bufsize sizeof(buf).
978 * \param[in] str A string that may contain any characters.
979 * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length.
980 * \return Number of characters that would be written if bufsize were large enough excluding '\0' (like snprintf()).
981 */
982size_t osmo_quote_cstr_buf(char *buf, size_t bufsize, const char *str, int in_len)
983{
984 return _osmo_quote_str_buf(buf, bufsize, str, in_len, false);
985}
986
987/*! Return the string quoted and with all non-printable characters escaped, in dynamically-allocated buffer.
988 * In contrast to osmo_quote_str_c(), this escapes characters in a way compatible with C string constant syntax, and
989 * allocates sufficient memory in all cases.
990 * \param[in] str A string that may contain any characters.
991 * \param[in] len Pass -1 to print until nul char, or >= 0 to force a length.
992 * \returns dynamically-allocated buffer, containing a quoted and escaped representation.
993 */
994char *osmo_quote_cstr_c(void *ctx, const char *str, int in_len)
995{
996 /* The string will be at least as long as in_len plus two quotes, but some characters might need escaping.
997 * These extra bytes should catch most usual escaping situations, avoiding a second run in OSMO_NAME_C_IMPL. */
998 OSMO_NAME_C_IMPL(ctx, in_len + 16, "ERROR", _osmo_quote_str_buf, str, in_len, false);
Harald Welte179f3572019-03-18 18:38:47 +0100999}
1000
Harald Welte15a5f8d2018-06-06 16:58:17 +02001001/*! perform an integer square root operation on unsigned 32bit integer.
1002 * This implementation is taken from "Hacker's Delight" Figure 11-1 "Integer square root, Newton's
1003 * method", which can also be found at http://www.hackersdelight.org/hdcodetxt/isqrt.c.txt */
1004uint32_t osmo_isqrt32(uint32_t x)
1005{
1006 uint32_t x1;
1007 int s, g0, g1;
1008
1009 if (x <= 1)
1010 return x;
1011
1012 s = 1;
1013 x1 = x - 1;
1014 if (x1 > 0xffff) {
1015 s = s + 8;
1016 x1 = x1 >> 16;
1017 }
1018 if (x1 > 0xff) {
1019 s = s + 4;
1020 x1 = x1 >> 8;
1021 }
1022 if (x1 > 0xf) {
1023 s = s + 2;
1024 x1 = x1 >> 4;
1025 }
1026 if (x1 > 0x3) {
1027 s = s + 1;
1028 }
1029
1030 g0 = 1 << s; /* g0 = 2**s */
1031 g1 = (g0 + (x >> s)) >> 1; /* g1 = (g0 + x/g0)/2 */
1032
1033 /* converges after four to five divisions for arguments up to 16,785,407 */
1034 while (g1 < g0) {
1035 g0 = g1;
1036 g1 = (g0 + (x/g0)) >> 1;
1037 }
1038 return g0;
1039}
1040
Neels Hofmeyr7c749892018-09-07 03:01:38 +02001041/*! Convert a string to lowercase, while checking buffer size boundaries.
1042 * The result written to \a dest is guaranteed to be nul terminated if \a dest_len > 0.
1043 * If dest == src, the string is converted in-place, if necessary truncated at dest_len - 1 characters
1044 * length as well as nul terminated.
1045 * Note: similar osmo_str2lower(), but safe to use for src strings of arbitrary length.
1046 * \param[out] dest Target buffer to write lowercase string.
1047 * \param[in] dest_len Maximum buffer size of dest (e.g. sizeof(dest)).
1048 * \param[in] src String to convert to lowercase.
1049 * \returns Length of \a src, like osmo_strlcpy(), but if \a dest == \a src at most \a dest_len - 1.
1050 */
1051size_t osmo_str_tolower_buf(char *dest, size_t dest_len, const char *src)
1052{
1053 size_t rc;
1054 if (dest == src) {
1055 if (dest_len < 1)
1056 return 0;
1057 dest[dest_len - 1] = '\0';
1058 rc = strlen(dest);
1059 } else {
1060 if (dest_len < 1)
1061 return strlen(src);
1062 rc = osmo_strlcpy(dest, src, dest_len);
1063 }
1064 for (; *dest; dest++)
1065 *dest = tolower(*dest);
1066 return rc;
1067}
1068
1069/*! Convert a string to lowercase, using a static buffer.
1070 * The resulting string may be truncated if the internally used static buffer is shorter than src.
1071 * 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 +02001072 * terminating nul. The static buffer returned is shared with osmo_str_toupper().
Neels Hofmeyr7c749892018-09-07 03:01:38 +02001073 * See also osmo_str_tolower_buf().
1074 * \param[in] src String to convert to lowercase.
1075 * \returns Resulting lowercase string in a static buffer, always nul terminated.
1076 */
1077const char *osmo_str_tolower(const char *src)
1078{
Pau Espin Pedrola37f58e2019-08-01 18:11:41 +02001079 osmo_str_tolower_buf(capsbuf, sizeof(capsbuf), src);
1080 return capsbuf;
Neels Hofmeyr7c749892018-09-07 03:01:38 +02001081}
1082
Harald Welte179f3572019-03-18 18:38:47 +01001083/*! Convert a string to lowercase, dynamically allocating the output from given talloc context
1084 * See also osmo_str_tolower_buf().
1085 * \param[in] ctx talloc context from where to allocate the output string
1086 * \param[in] src String to convert to lowercase.
1087 * \returns Resulting lowercase string in a dynamically allocated buffer, always nul terminated.
1088 */
1089char *osmo_str_tolower_c(const void *ctx, const char *src)
1090{
Vadim Yanitskiy4f619c22019-04-12 21:48:07 +07001091 size_t buf_len = strlen(src) + 1;
1092 char *buf = talloc_size(ctx, buf_len);
Harald Welte179f3572019-03-18 18:38:47 +01001093 if (!buf)
1094 return NULL;
Vadim Yanitskiy4f619c22019-04-12 21:48:07 +07001095 osmo_str_tolower_buf(buf, buf_len, src);
Harald Welte179f3572019-03-18 18:38:47 +01001096 return buf;
1097}
1098
Neels Hofmeyr7c749892018-09-07 03:01:38 +02001099/*! Convert a string to uppercase, while checking buffer size boundaries.
1100 * The result written to \a dest is guaranteed to be nul terminated if \a dest_len > 0.
1101 * If dest == src, the string is converted in-place, if necessary truncated at dest_len - 1 characters
1102 * length as well as nul terminated.
1103 * Note: similar osmo_str2upper(), but safe to use for src strings of arbitrary length.
1104 * \param[out] dest Target buffer to write uppercase string.
1105 * \param[in] dest_len Maximum buffer size of dest (e.g. sizeof(dest)).
1106 * \param[in] src String to convert to uppercase.
1107 * \returns Length of \a src, like osmo_strlcpy(), but if \a dest == \a src at most \a dest_len - 1.
1108 */
1109size_t osmo_str_toupper_buf(char *dest, size_t dest_len, const char *src)
1110{
1111 size_t rc;
1112 if (dest == src) {
1113 if (dest_len < 1)
1114 return 0;
1115 dest[dest_len - 1] = '\0';
1116 rc = strlen(dest);
1117 } else {
1118 if (dest_len < 1)
1119 return strlen(src);
1120 rc = osmo_strlcpy(dest, src, dest_len);
1121 }
1122 for (; *dest; dest++)
1123 *dest = toupper(*dest);
1124 return rc;
1125}
1126
1127/*! Convert a string to uppercase, using a static buffer.
1128 * The resulting string may be truncated if the internally used static buffer is shorter than src.
1129 * 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 +02001130 * terminating nul. The static buffer returned is shared with osmo_str_tolower().
Neels Hofmeyr7c749892018-09-07 03:01:38 +02001131 * See also osmo_str_toupper_buf().
1132 * \param[in] src String to convert to uppercase.
1133 * \returns Resulting uppercase string in a static buffer, always nul terminated.
1134 */
1135const char *osmo_str_toupper(const char *src)
1136{
Pau Espin Pedrola37f58e2019-08-01 18:11:41 +02001137 osmo_str_toupper_buf(capsbuf, sizeof(capsbuf), src);
1138 return capsbuf;
Neels Hofmeyr7c749892018-09-07 03:01:38 +02001139}
1140
Harald Welte179f3572019-03-18 18:38:47 +01001141/*! Convert a string to uppercase, dynamically allocating the output from given talloc context
1142 * See also osmo_str_tolower_buf().
1143 * \param[in] ctx talloc context from where to allocate the output string
1144 * \param[in] src String to convert to uppercase.
1145 * \returns Resulting uppercase string in a dynamically allocated buffer, always nul terminated.
1146 */
1147char *osmo_str_toupper_c(const void *ctx, const char *src)
1148{
Vadim Yanitskiy4f619c22019-04-12 21:48:07 +07001149 size_t buf_len = strlen(src) + 1;
1150 char *buf = talloc_size(ctx, buf_len);
Harald Welte179f3572019-03-18 18:38:47 +01001151 if (!buf)
1152 return NULL;
Vadim Yanitskiy4f619c22019-04-12 21:48:07 +07001153 osmo_str_toupper_buf(buf, buf_len, src);
Harald Welte179f3572019-03-18 18:38:47 +01001154 return buf;
1155}
1156
Oliver Smith894be2d2019-01-11 13:13:37 +01001157/*! Calculate the Luhn checksum (as used for IMEIs).
1158 * \param[in] in Input digits in ASCII string representation.
1159 * \param[in] in_len Count of digits to use for the input (14 for IMEI).
1160 * \returns checksum char (e.g. '3'); negative on error
1161 */
Vadim Yanitskiyd9fc6042019-06-12 15:49:03 +07001162char osmo_luhn(const char* in, int in_len)
Oliver Smith894be2d2019-01-11 13:13:37 +01001163{
1164 int i, sum = 0;
1165
1166 /* All input must be numbers */
1167 for (i = 0; i < in_len; i++) {
KĂ©vin Redon1af2cd52019-05-23 19:00:19 +02001168 if (!isdigit((unsigned char)in[i]))
Oliver Smith894be2d2019-01-11 13:13:37 +01001169 return -EINVAL;
1170 }
1171
1172 /* Double every second digit and add it to sum */
1173 for (i = in_len - 1; i >= 0; i -= 2) {
1174 int dbl = (in[i] - '0') * 2;
1175 if (dbl > 9)
1176 dbl -= 9;
1177 sum += dbl;
1178 }
1179
1180 /* Add other digits to sum */
1181 for (i = in_len - 2; i >= 0; i -= 2)
1182 sum += in[i] - '0';
1183
1184 /* Final checksum */
1185 return (sum * 9) % 10 + '0';
1186}
1187
Neels Hofmeyrd79ccc62019-03-07 23:08:40 +01001188/*! Compare start of a string.
1189 * This is an optimisation of 'strstr(str, startswith_str) == str' because it doesn't search through the entire string.
1190 * \param str (Longer) string to compare.
1191 * \param startswith_str (Shorter) string to compare with the start of str.
1192 * \return true iff the first characters of str fully match startswith_str or startswith_str is empty. */
1193bool osmo_str_startswith(const char *str, const char *startswith_str)
1194{
1195 if (!startswith_str || !*startswith_str)
1196 return true;
1197 if (!str)
1198 return false;
1199 return strncmp(str, startswith_str, strlen(startswith_str)) == 0;
1200}
1201
Neels Hofmeyr87c3afb2020-09-30 21:47:47 +00001202/*! Convert a string of a floating point number to a signed int, with a decimal factor (fixed-point precision).
1203 * For example, with precision=3, convert "-1.23" to -1230. In other words, the float value is multiplied by
1204 * 10 to-the-power-of precision to obtain the returned integer.
1205 * The usable range of digits is -INT64_MAX .. INT64_MAX -- note, not INT64_MIN! The value of INT64_MIN is excluded to
1206 * reduce implementation complexity. See also utils_test.c.
Neels Hofmeyr6d744982020-10-08 13:09:49 +02001207 * The advantage over using sscanf("%f") is guaranteed precision: float or double types may apply rounding in the
1208 * conversion result. osmo_float_str_to_int() and osmo_int_to_float_str_buf() guarantee true results when converting
1209 * back and forth between string and int.
Neels Hofmeyr87c3afb2020-09-30 21:47:47 +00001210 * \param[out] val Returned integer value.
1211 * \param[in] str String of a float, like '-12.345'.
Neels Hofmeyr87c3afb2020-09-30 21:47:47 +00001212 * \param[in] precision Fixed-point precision, or * \returns 0 on success, negative on error.
1213 */
1214int osmo_float_str_to_int(int64_t *val, const char *str, unsigned int precision)
1215{
1216 const char *point;
1217 char *endptr;
1218 const char *p;
1219 int64_t sign = 1;
1220 int64_t integer = 0;
1221 int64_t decimal = 0;
1222 int64_t precision_factor;
1223 int64_t integer_max;
1224 int64_t decimal_max;
1225 int i;
1226
1227 OSMO_ASSERT(val);
1228 *val = 0;
1229
1230 if (!str)
1231 return -EINVAL;
1232 if (str[0] == '-') {
1233 str = str + 1;
1234 sign = -1;
1235 } else if (str[0] == '+') {
1236 str = str + 1;
1237 }
1238 if (!str[0])
1239 return -EINVAL;
1240
1241 /* Validate entire string as purely digits and at most one decimal dot. If not doing this here in advance,
1242 * parsing digits might stop early because of precision cut-off and miss validation of input data. */
1243 point = NULL;
1244 for (p = str; *p; p++) {
1245 if (*p == '.') {
1246 if (point)
1247 return -EINVAL;
1248 point = p;
Eric79f29032021-11-19 12:58:39 +01001249 } else if (!isdigit((unsigned char)*p))
Neels Hofmeyr87c3afb2020-09-30 21:47:47 +00001250 return -EINVAL;
1251 }
1252
1253 /* Parse integer part if there is one. If the string starts with a point, there's nothing to parse for the
1254 * integer part. */
1255 if (!point || point > str) {
1256 errno = 0;
1257 integer = strtoll(str, &endptr, 10);
Harald Weltecb11a602020-10-09 10:08:44 +02001258 if ((errno == ERANGE && (integer == LLONG_MAX || integer == LLONG_MIN))
Neels Hofmeyr87c3afb2020-09-30 21:47:47 +00001259 || (errno != 0 && integer == 0))
1260 return -ERANGE;
1261
1262 if ((point && endptr != point)
1263 || (!point && *endptr))
1264 return -EINVAL;
1265 }
1266
1267 /* Parse the fractional part if there is any, and if the precision is nonzero (if we even care about fractional
1268 * digits) */
1269 if (precision && point && point[1] != '\0') {
1270 /* limit the number of digits parsed to 'precision'.
1271 * If 'precision' is larger than the 19 digits representable in int64_t, skip some, to pick up lower
1272 * magnitude digits. */
1273 unsigned int skip_digits = (precision < 20) ? 0 : precision - 20;
1274 char decimal_str[precision + 1];
1275 osmo_strlcpy(decimal_str, point+1, precision+1);
1276
1277 /* fill with zeros to make exactly 'precision' digits */
1278 for (i = strlen(decimal_str); i < precision; i++)
1279 decimal_str[i] = '0';
1280 decimal_str[precision] = '\0';
1281
1282 for (i = 0; i < skip_digits; i++) {
1283 /* When skipping digits because precision > nr-of-digits-in-int64_t, they must be zero;
1284 * if there is a nonzero digit above the precision, it's -ERANGE. */
1285 if (decimal_str[i] != '0')
1286 return -ERANGE;
1287 }
1288 errno = 0;
1289 decimal = strtoll(decimal_str + skip_digits, &endptr, 10);
Harald Weltecb11a602020-10-09 10:08:44 +02001290 if ((errno == ERANGE && (decimal == LLONG_MAX || decimal == LLONG_MIN))
Neels Hofmeyr87c3afb2020-09-30 21:47:47 +00001291 || (errno != 0 && decimal == 0))
1292 return -ERANGE;
1293
1294 if (*endptr)
1295 return -EINVAL;
1296 }
1297
1298 if (precision > 18) {
1299 /* Special case of returning more digits than fit in int64_t range, e.g.
1300 * osmo_float_str_to_int("0.0000000012345678901234567", precision=25) -> 12345678901234567. */
1301 precision_factor = 0;
1302 integer_max = 0;
1303 decimal_max = INT64_MAX;
1304 } else {
1305 /* Do not surpass the resulting int64_t range. Depending on the amount of precision, the integer part
1306 * and decimal part have specific ranges they must comply to. */
1307 precision_factor = 1;
1308 for (i = 0; i < precision; i++)
1309 precision_factor *= 10;
1310 integer_max = INT64_MAX / precision_factor;
1311 if (integer == integer_max)
1312 decimal_max = INT64_MAX % precision_factor;
1313 else
1314 decimal_max = INT64_MAX;
1315 }
1316
1317 if (integer > integer_max)
1318 return -ERANGE;
1319 if (decimal > decimal_max)
1320 return -ERANGE;
1321
1322 *val = sign * (integer * precision_factor + decimal);
1323 return 0;
1324}
1325
Neels Hofmeyr6d744982020-10-08 13:09:49 +02001326/*! Convert an integer to a floating point string using a decimal quotient (fixed-point precision).
Neels Hofmeyr87c3afb2020-09-30 21:47:47 +00001327 * For example, with precision = 3, convert -1230 to "-1.23".
Neels Hofmeyr6d744982020-10-08 13:09:49 +02001328 * The usable range of digits is -INT64_MAX .. INT64_MAX -- note, not INT64_MIN! The value of INT64_MIN is excluded to
1329 * reduce implementation complexity. See also utils_test.c.
1330 * The advantage over using printf("%.6g") is guaranteed precision: float or double types may apply rounding in the
1331 * conversion result. osmo_float_str_to_int() and osmo_int_to_float_str_buf() guarantee true results when converting
1332 * back and forth between string and int.
1333 * The resulting string omits trailing zeros in the fractional part (like "%g" would) but never applies rounding.
Neels Hofmeyr87c3afb2020-09-30 21:47:47 +00001334 * \param[out] buf Buffer to write string to.
1335 * \param[in] buflen sizeof(buf).
1336 * \param[in] val Value to convert to float.
1337 * \returns number of chars that would be written, like snprintf().
1338 */
1339int osmo_int_to_float_str_buf(char *buf, size_t buflen, int64_t val, unsigned int precision)
1340{
1341 struct osmo_strbuf sb = { .buf = buf, .len = buflen };
1342 unsigned int i;
1343 unsigned int w;
1344 int64_t precision_factor;
1345 if (val < 0) {
1346 OSMO_STRBUF_PRINTF(sb, "-");
1347 if (val == INT64_MIN) {
1348 OSMO_STRBUF_PRINTF(sb, "ERR");
1349 return sb.chars_needed;
1350 }
1351 val = -val;
1352 }
1353
1354 if (precision > 18) {
1355 /* Special case of returning more digits than fit in int64_t range, e.g.
1356 * osmo_int_to_float_str(12345678901234567, precision=25) -> "0.0000000012345678901234567". */
1357 if (!val) {
1358 OSMO_STRBUF_PRINTF(sb, "0");
1359 return sb.chars_needed;
1360 }
1361 OSMO_STRBUF_PRINTF(sb, "0.");
1362 for (i = 19; i < precision; i++)
1363 OSMO_STRBUF_PRINTF(sb, "0");
1364 precision = 19;
1365 } else {
1366 precision_factor = 1;
1367 for (i = 0; i < precision; i++)
1368 precision_factor *= 10;
1369
1370 OSMO_STRBUF_PRINTF(sb, "%" PRId64, val / precision_factor);
1371 val %= precision_factor;
1372 if (!val)
1373 return sb.chars_needed;
1374 OSMO_STRBUF_PRINTF(sb, ".");
1375 }
1376
1377 /* print fractional part, skip trailing zeros */
1378 w = precision;
1379 while (!(val % 10)) {
1380 val /= 10;
1381 w--;
1382 }
1383 OSMO_STRBUF_PRINTF(sb, "%0*" PRId64, w, val);
1384 return sb.chars_needed;
1385}
1386
1387/*! Convert an integer with a factor of a million to a floating point string.
1388 * For example, convert -1230000 to "-1.23".
1389 * \param[in] ctx Talloc ctx to allocate string buffer from.
1390 * \param[in] val Value to convert to float.
1391 * \returns resulting string, dynamically allocated.
1392 */
1393char *osmo_int_to_float_str_c(void *ctx, int64_t val, unsigned int precision)
1394{
1395 OSMO_NAME_C_IMPL(ctx, 16, "ERROR", osmo_int_to_float_str_buf, val, precision)
1396}
1397
Neels Hofmeyr47773342021-09-05 18:48:31 +02001398/*! Convert a string of a number to int64_t, including all common strtoll() validity checks.
1399 * It's not so trivial to call strtoll() and properly verify that the input string was indeed a valid number string.
1400 * \param[out] result Buffer for the resulting integer number, or NULL if the caller is only interested in the
1401 * validation result (returned rc).
1402 * \param[in] str The string to convert.
1403 * \param[in] base The integer base, i.e. 10 for decimal numbers or 16 for hexadecimal, as in strtoll().
1404 * \param[in] min_val The smallest valid number expected in the string.
1405 * \param[in] max_val The largest valid number expected in the string.
1406 * \return 0 on success, -EOVERFLOW if the number in the string exceeds int64_t, -ENOTSUPP if the base is not supported,
1407 * -ERANGE if the converted number exceeds the range [min_val..max_val] but is still within int64_t range, -E2BIG if
1408 * surplus characters follow after the number, -EINVAL if the string does not contain a number. In case of -ERANGE and
1409 * -E2BIG, the converted number is still accurately returned in result. In case of -EOVERFLOW, the returned value is
1410 * clamped to INT64_MIN..INT64_MAX.
1411 */
1412int osmo_str_to_int64(int64_t *result, const char *str, int base, int64_t min_val, int64_t max_val)
1413{
1414 long long int val;
1415 char *endptr;
1416 if (result)
1417 *result = 0;
1418 if (!str || !*str)
1419 return -EINVAL;
1420 errno = 0;
1421 val = strtoll(str, &endptr, base);
1422 /* In case the number string exceeds long long int range, strtoll() clamps the returned value to LLONG_MIN or
1423 * LLONG_MAX. Make sure of the same here with respect to int64_t. */
1424 if (val < INT64_MIN) {
1425 if (result)
1426 *result = INT64_MIN;
1427 return -ERANGE;
1428 }
1429 if (val > INT64_MAX) {
1430 if (result)
1431 *result = INT64_MAX;
1432 return -ERANGE;
1433 }
1434 if (result)
1435 *result = (int64_t)val;
1436 switch (errno) {
1437 case 0:
1438 break;
1439 case ERANGE:
1440 return -EOVERFLOW;
1441 default:
1442 case EINVAL:
1443 return -ENOTSUP;
1444 }
1445 if (!endptr || *endptr) {
1446 /* No chars were converted */
1447 if (endptr == str)
1448 return -EINVAL;
1449 /* Or there are surplus chars after the converted number */
1450 return -E2BIG;
1451 }
1452 if (val < min_val || val > max_val)
1453 return -ERANGE;
1454 return 0;
1455}
1456
1457/*! Convert a string of a number to int, including all common strtoll() validity checks.
1458 * Same as osmo_str_to_int64() but using the plain int data type.
1459 * \param[out] result Buffer for the resulting integer number, or NULL if the caller is only interested in the
1460 * validation result (returned rc).
1461 * \param[in] str The string to convert.
1462 * \param[in] base The integer base, i.e. 10 for decimal numbers or 16 for hexadecimal, as in strtoll().
1463 * \param[in] min_val The smallest valid number expected in the string.
1464 * \param[in] max_val The largest valid number expected in the string.
1465 * \return 0 on success, -EOVERFLOW if the number in the string exceeds int range, -ENOTSUPP if the base is not supported,
1466 * -ERANGE if the converted number exceeds the range [min_val..max_val] but is still within int range, -E2BIG if
1467 * surplus characters follow after the number, -EINVAL if the string does not contain a number. In case of -ERANGE and
1468 * -E2BIG, the converted number is still accurately returned in result. In case of -EOVERFLOW, the returned value is
1469 * clamped to INT_MIN..INT_MAX.
1470 */
1471int osmo_str_to_int(int *result, const char *str, int base, int min_val, int max_val)
1472{
1473 int64_t val;
1474 int rc = osmo_str_to_int64(&val, str, base, min_val, max_val);
1475 /* In case the number string exceeds long long int range, strtoll() clamps the returned value to LLONG_MIN or
1476 * LLONG_MAX. Make sure of the same here with respect to int. */
1477 if (val < INT_MIN) {
1478 if (result)
1479 *result = INT_MIN;
1480 return -EOVERFLOW;
1481 }
1482 if (val > INT_MAX) {
1483 if (result)
1484 *result = INT_MAX;
1485 return -EOVERFLOW;
1486 }
1487 if (result)
1488 *result = (int)val;
1489 return rc;
1490}
1491
Vadim Yanitskiyc5497192021-06-07 16:30:28 +02001492/*! Replace a string using talloc and release its prior content (if any).
1493 * This is a format string capable equivalent of osmo_talloc_replace_string().
1494 * \param[in] ctx Talloc context to use for allocation.
1495 * \param[out] dst Pointer to string, will be updated with ptr to new string.
1496 * \param[in] fmt Format string that will be copied to newly allocated string. */
1497void osmo_talloc_replace_string_fmt(void *ctx, char **dst, const char *fmt, ...)
1498{
1499 char *name = NULL;
1500
1501 if (fmt != NULL) {
1502 va_list ap;
1503
1504 va_start(ap, fmt);
1505 name = talloc_vasprintf(ctx, fmt, ap);
1506 va_end(ap);
1507 }
1508
1509 talloc_free(*dst);
1510 *dst = name;
1511}
1512
Neels Hofmeyr0aeda1b2017-01-13 14:16:02 +01001513/*! @} */