blob: f5896c413b6ca03f02d2ee026e6e92d130b5535d [file] [log] [blame]
Harald Welte468b6432014-09-11 13:05:51 +08001/*
2 * (C) 2011 by Harald Welte <laforge@gnumonks.org>
3 * (C) 2011 by Sylvain Munaut <tnt@246tNt.com>
4 * (C) 2014 by Nils O. SelÄsdal <noselasd@fiane.dyndns.org>
5 *
6 * All Rights Reserved
7 *
Harald Weltee08da972017-11-13 01:00:26 +09008 * SPDX-License-Identifier: GPL-2.0+
9 *
Harald Welte468b6432014-09-11 13:05:51 +080010 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23 *
24 */
25
Harald Welted284cd92010-03-01 21:58:31 +010026
Harald Weltefebe83c2017-10-03 17:41:59 +080027#include <stdbool.h>
Harald Welted284cd92010-03-01 21:58:31 +010028#include <string.h>
29#include <stdint.h>
30#include <errno.h>
Harald Welteb59f9352010-03-25 11:37:04 +080031#include <stdio.h>
Pau Espin Pedrol45735022017-06-18 14:05:24 +020032#include <inttypes.h>
Neels Hofmeyr87c3afb2020-09-30 21:47:47 +000033#include <limits.h>
Harald Welted284cd92010-03-01 21:58:31 +010034
Pablo Neira Ayuso83419342011-03-22 16:36:13 +010035#include <osmocom/core/utils.h>
Harald Welte9709b2e2016-04-25 18:47:53 +020036#include <osmocom/core/bit64gen.h>
37
Harald Welted284cd92010-03-01 21:58:31 +010038
Harald Welte8598f182011-08-17 14:19:27 +020039/*! \addtogroup utils
40 * @{
Neels Hofmeyr87e45502017-06-20 00:17:59 +020041 * various utility routines
Neels Hofmeyr17518fe2017-06-20 04:35:06 +020042 *
43 * \file utils.c */
Harald Welte8598f182011-08-17 14:19:27 +020044
Harald Welte171ef822019-03-28 10:49:05 +010045static __thread char namebuf[255];
Pau Espin Pedrola37f58e2019-08-01 18:11:41 +020046/* shared by osmo_str_tolower() and osmo_str_toupper() */
47static __thread char capsbuf[128];
Harald Welte8598f182011-08-17 14:19:27 +020048
Neels Hofmeyr87e45502017-06-20 00:17:59 +020049/*! get human-readable string for given value
Harald Welte8598f182011-08-17 14:19:27 +020050 * \param[in] vs Array of value_string tuples
51 * \param[in] val Value to be converted
52 * \returns pointer to human-readable string
Neels Hofmeyr8a3c83e2016-06-13 13:16:58 +020053 *
54 * If val is found in vs, the array's string entry is returned. Otherwise, an
55 * "unknown" string containing the actual value is composed in a static buffer
56 * that is reused across invocations.
Harald Welte8598f182011-08-17 14:19:27 +020057 */
Harald Welted284cd92010-03-01 21:58:31 +010058const char *get_value_string(const struct value_string *vs, uint32_t val)
59{
Neels Hofmeyr8d6dcd92016-06-06 18:05:23 +020060 const char *str = get_value_string_or_null(vs, val);
61 if (str)
62 return str;
63
Pau Espin Pedrol45735022017-06-18 14:05:24 +020064 snprintf(namebuf, sizeof(namebuf), "unknown 0x%"PRIx32, val);
Neels Hofmeyr8d6dcd92016-06-06 18:05:23 +020065 namebuf[sizeof(namebuf) - 1] = '\0';
66 return namebuf;
67}
68
Neels Hofmeyr87e45502017-06-20 00:17:59 +020069/*! get human-readable string or NULL for given value
Neels Hofmeyr8d6dcd92016-06-06 18:05:23 +020070 * \param[in] vs Array of value_string tuples
71 * \param[in] val Value to be converted
72 * \returns pointer to human-readable string or NULL if val is not found
73 */
74const char *get_value_string_or_null(const struct value_string *vs,
75 uint32_t val)
76{
Harald Welted284cd92010-03-01 21:58:31 +010077 int i;
78
Neels Hofmeyra0331ed2019-02-11 21:24:40 +010079 if (!vs)
80 return NULL;
81
Harald Welted284cd92010-03-01 21:58:31 +010082 for (i = 0;; i++) {
83 if (vs[i].value == 0 && vs[i].str == NULL)
84 break;
85 if (vs[i].value == val)
86 return vs[i].str;
87 }
Harald Welteb59f9352010-03-25 11:37:04 +080088
Neels Hofmeyr8d6dcd92016-06-06 18:05:23 +020089 return NULL;
Harald Welted284cd92010-03-01 21:58:31 +010090}
91
Neels Hofmeyr87e45502017-06-20 00:17:59 +020092/*! get numeric value for given human-readable string
Harald Welte8598f182011-08-17 14:19:27 +020093 * \param[in] vs Array of value_string tuples
94 * \param[in] str human-readable string
95 * \returns numeric value (>0) or negative numer in case of error
96 */
Harald Welted284cd92010-03-01 21:58:31 +010097int get_string_value(const struct value_string *vs, const char *str)
98{
99 int i;
100
101 for (i = 0;; i++) {
102 if (vs[i].value == 0 && vs[i].str == NULL)
103 break;
104 if (!strcasecmp(vs[i].str, str))
105 return vs[i].value;
106 }
107 return -EINVAL;
108}
Harald Weltea73e2f92010-03-04 10:50:32 +0100109
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200110/*! Convert BCD-encoded digit into printable character
Harald Welte8598f182011-08-17 14:19:27 +0200111 * \param[in] bcd A single BCD-encoded digit
112 * \returns single printable character
113 */
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200114char osmo_bcd2char(uint8_t bcd)
Harald Weltea73e2f92010-03-04 10:50:32 +0100115{
116 if (bcd < 0xa)
117 return '0' + bcd;
118 else
119 return 'A' + (bcd - 0xa);
120}
121
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200122/*! Convert number in ASCII to BCD value
Harald Weltede6e4982012-12-06 21:25:27 +0100123 * \param[in] c ASCII character
124 * \returns BCD encoded value of character
125 */
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200126uint8_t osmo_char2bcd(char c)
Harald Weltea73e2f92010-03-04 10:50:32 +0100127{
Harald Weltefa8983d2017-10-27 16:52:59 +0200128 if (c >= '0' && c <= '9')
129 return c - 0x30;
130 else if (c >= 'A' && c <= 'F')
131 return 0xa + (c - 'A');
132 else if (c >= 'a' && c <= 'f')
133 return 0xa + (c - 'a');
134 else
135 return 0;
Harald Weltea73e2f92010-03-04 10:50:32 +0100136}
Harald Welte3eba9912010-07-30 10:37:29 +0200137
Neels Hofmeyr7079e692018-12-05 21:02:36 +0100138/*! Convert BCD to string.
139 * The given nibble offsets are interpreted in BCD order, i.e. nibble 0 is bcd[0] & 0xf, nibble 1 is bcd[0] >> 4, nibble
140 * 3 is bcd[1] & 0xf, etc..
141 * \param[out] dst Output string buffer, is always nul terminated when dst_size > 0.
142 * \param[in] dst_size sizeof() the output string buffer.
143 * \param[in] bcd Binary coded data buffer.
144 * \param[in] start_nibble Offset to start from, in nibbles, typically 1 to skip the first nibble.
Neels Hofmeyr48b2de02018-12-11 02:13:57 +0100145 * \param[in] end_nibble Offset to stop before, in nibbles, e.g. sizeof(bcd)*2 - (bcd[0] & GSM_MI_ODD? 0:1).
Neels Hofmeyr7079e692018-12-05 21:02:36 +0100146 * \param[in] allow_hex If false, return error if there are digits other than 0-9. If true, return those as [A-F].
147 * \returns The strlen that would be written if the output buffer is large enough, excluding nul byte (like
148 * snprintf()), or -EINVAL if allow_hex is false and a digit > 9 is encountered. On -EINVAL, the conversion is
149 * still completed as if allow_hex were passed as true. Return -ENOMEM if dst is NULL or dst_size is zero.
150 * If end_nibble <= start_nibble, write an empty string to dst and return 0.
151 */
152int osmo_bcd2str(char *dst, size_t dst_size, const uint8_t *bcd, int start_nibble, int end_nibble, bool allow_hex)
153{
154 char *dst_end = dst + dst_size - 1;
155 int nibble_i;
156 int rc = 0;
157
Neels Hofmeyr0b6a8c82020-06-12 16:34:20 +0200158 if (!dst || dst_size < 1 || start_nibble < 0)
Neels Hofmeyr7079e692018-12-05 21:02:36 +0100159 return -ENOMEM;
160
161 for (nibble_i = start_nibble; nibble_i < end_nibble && dst < dst_end; nibble_i++, dst++) {
162 uint8_t nibble = bcd[nibble_i >> 1];
163 if ((nibble_i & 1))
164 nibble >>= 4;
165 nibble &= 0xf;
166
167 if (!allow_hex && nibble > 9)
168 rc = -EINVAL;
169
170 *dst = osmo_bcd2char(nibble);
171 }
172 *dst = '\0';
173
174 if (rc < 0)
175 return rc;
176 return OSMO_MAX(0, end_nibble - start_nibble);
177}
178
Neels Hofmeyr83025bf2020-05-26 02:45:23 +0200179/*! Convert string to BCD.
180 * The given nibble offsets are interpreted in BCD order, i.e. nibble 0 is bcd[0] & 0x0f, nibble 1 is bcd[0] & 0xf0, nibble
181 * 3 is bcd[1] & 0x0f, etc..
182 * \param[out] dst Output BCD buffer.
183 * \param[in] dst_size sizeof() the output string buffer.
184 * \param[in] digits String containing decimal or hexadecimal digits in upper or lower case.
185 * \param[in] start_nibble Offset to start from, in nibbles, typically 1 to skip the first (MI type) nibble.
186 * \param[in] end_nibble Negative to write all digits found in str, followed by 0xf nibbles to fill any started octet.
187 * If >= 0, stop before this offset in nibbles, e.g. to get default behavior, pass
188 * start_nibble + strlen(str) + ((start_nibble + strlen(str)) & 1? 1 : 0) + 1.
189 * \param[in] allow_hex If false, return error if there are hexadecimal digits (A-F). If true, write those to
190 * BCD.
191 * \returns The buffer size in octets that is used to place all bcd digits (including the skipped nibbles
192 * from 'start_nibble' and rounded up to full octets); -EINVAL on invalid digits;
193 * -ENOMEM if dst is NULL, if dst_size is too small to contain all nibbles, or if start_nibble is negative.
194 */
195int osmo_str2bcd(uint8_t *dst, size_t dst_size, const char *digits, int start_nibble, int end_nibble, bool allow_hex)
196{
197 const char *digit = digits;
198 int nibble_i;
199
200 if (!dst || !dst_size || start_nibble < 0)
201 return -ENOMEM;
202
203 if (end_nibble < 0) {
204 end_nibble = start_nibble + strlen(digits);
205 /* If the last octet is not complete, add another filler nibble */
206 if (end_nibble & 1)
207 end_nibble++;
208 }
209 if ((end_nibble / 2) > dst_size)
210 return -ENOMEM;
211
212 for (nibble_i = start_nibble; nibble_i < end_nibble; nibble_i++) {
213 uint8_t nibble = 0xf;
214 int octet = nibble_i >> 1;
215 if (*digit) {
216 char c = *digit;
217 digit++;
218 if (c >= '0' && c <= '9')
219 nibble = c - '0';
220 else if (allow_hex && c >= 'A' && c <= 'F')
221 nibble = 0xa + (c - 'A');
222 else if (allow_hex && c >= 'a' && c <= 'f')
223 nibble = 0xa + (c - 'a');
224 else
225 return -EINVAL;
226 }
227 nibble &= 0xf;
228 if ((nibble_i & 1))
229 dst[octet] = (nibble << 4) | (dst[octet] & 0x0f);
230 else
231 dst[octet] = (dst[octet] & 0xf0) | nibble;
232 }
233
234 /* floor(float(end_nibble) / 2) */
235 return end_nibble / 2;
236}
237
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200238/*! Parse a string containing hexadecimal digits
Harald Weltede6e4982012-12-06 21:25:27 +0100239 * \param[in] str string containing ASCII encoded hexadecimal digits
240 * \param[out] b output buffer
241 * \param[in] max_len maximum space in output buffer
Neels Hofmeyr3de7b052015-09-23 23:16:53 +0200242 * \returns number of parsed octets, or -1 on error
Harald Weltede6e4982012-12-06 21:25:27 +0100243 */
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200244int osmo_hexparse(const char *str, uint8_t *b, int max_len)
Harald Welte3eba9912010-07-30 10:37:29 +0200245
246{
Neels Hofmeyr437ed4a2017-02-14 15:54:31 +0100247 char c;
248 uint8_t v;
249 const char *strpos;
250 unsigned int nibblepos = 0;
Harald Welte3eba9912010-07-30 10:37:29 +0200251
252 memset(b, 0x00, max_len);
253
Neels Hofmeyr437ed4a2017-02-14 15:54:31 +0100254 for (strpos = str; (c = *strpos); strpos++) {
255 /* skip whitespace */
256 if (c == ' ' || c == '\t' || c == '\n' || c == '\r')
257 continue;
258
259 /* If the buffer is too small, error out */
260 if (nibblepos >= (max_len << 1))
261 return -1;
262
Harald Welte3eba9912010-07-30 10:37:29 +0200263 if (c >= '0' && c <= '9')
264 v = c - '0';
265 else if (c >= 'a' && c <= 'f')
266 v = 10 + (c - 'a');
267 else if (c >= 'A' && c <= 'F')
268 v = 10 + (c - 'A');
269 else
270 return -1;
Neels Hofmeyr437ed4a2017-02-14 15:54:31 +0100271
272 b[nibblepos >> 1] |= v << (nibblepos & 1 ? 0 : 4);
273 nibblepos ++;
Harald Welte3eba9912010-07-30 10:37:29 +0200274 }
275
Neels Hofmeyr437ed4a2017-02-14 15:54:31 +0100276 /* In case of uneven amount of digits, the last byte is not complete
277 * and that's an error. */
278 if (nibblepos & 1)
279 return -1;
280
281 return nibblepos >> 1;
Harald Welte3eba9912010-07-30 10:37:29 +0200282}
Harald Welte40481e82010-07-30 11:40:32 +0200283
Harald Welte171ef822019-03-28 10:49:05 +0100284static __thread char hexd_buff[4096];
Nils O. SelÄsdal32447022014-01-02 14:04:43 +0100285static const char hex_chars[] = "0123456789abcdef";
Harald Welte40481e82010-07-30 11:40:32 +0200286
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100287/*! Convert binary sequence to hexadecimal ASCII string.
288 * \param[out] out_buf Output buffer to write the resulting string to.
289 * \param[in] out_buf_size sizeof(out_buf).
290 * \param[in] buf Input buffer, pointer to sequence of bytes.
291 * \param[in] len Length of input buf in number of bytes.
292 * \param[in] delim String to separate each byte; NULL or "" for no delim.
293 * \param[in] delim_after_last If true, end the string in delim (true: "1a:ef:d9:", false: "1a:ef:d9");
294 * if out_buf has insufficient space, the string will always end in a delim.
295 * \returns out_buf, containing a zero-terminated string, or "" (empty string) if out_buf == NULL or out_buf_size < 1.
296 *
297 * This function will print a sequence of bytes as hexadecimal numbers, adding one delim between each byte (e.g. for
298 * delim passed as ":", return a string like "1a:ef:d9").
299 *
300 * The delim_after_last argument exists to be able to exactly show the original osmo_hexdump() behavior, which always
301 * ends the string with a delimiter.
302 */
303const char *osmo_hexdump_buf(char *out_buf, size_t out_buf_size, const unsigned char *buf, int len, const char *delim,
304 bool delim_after_last)
Harald Welte40481e82010-07-30 11:40:32 +0200305{
306 int i;
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100307 char *cur = out_buf;
308 size_t delim_len;
Harald Welte40481e82010-07-30 11:40:32 +0200309
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100310 if (!out_buf || !out_buf_size)
311 return "";
312
313 delim = delim ? : "";
314 delim_len = strlen(delim);
315
Harald Welte40481e82010-07-30 11:40:32 +0200316 for (i = 0; i < len; i++) {
Nils O. SelÄsdal32447022014-01-02 14:04:43 +0100317 const char *delimp = delim;
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100318 int len_remain = out_buf_size - (cur - out_buf) - 1;
319 if (len_remain < (2 + delim_len)
320 && !(!delim_after_last && i == (len - 1) && len_remain >= 2))
Holger Hans Peter Freyther128d9e22011-07-15 16:07:23 +0200321 break;
Nils O. SelÄsdal32447022014-01-02 14:04:43 +0100322
323 *cur++ = hex_chars[buf[i] >> 4];
324 *cur++ = hex_chars[buf[i] & 0xf];
325
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100326 if (i == (len - 1) && !delim_after_last)
327 break;
328
Nils O. SelÄsdal32447022014-01-02 14:04:43 +0100329 while (len_remain > 1 && *delimp) {
330 *cur++ = *delimp++;
331 len_remain--;
332 }
Harald Welte40481e82010-07-30 11:40:32 +0200333 }
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100334 *cur = '\0';
335 return out_buf;
Harald Welte40481e82010-07-30 11:40:32 +0200336}
Harald Weltedee47cd2010-07-30 11:43:30 +0200337
Harald Welte4a62eda2019-03-18 18:27:00 +0100338/*! Convert a sequence of unpacked bits to ASCII string, in user-supplied buffer.
339 * \param[out] buf caller-provided output string buffer
340 * \param[out] buf_len size of buf in bytes
Harald Welte8598f182011-08-17 14:19:27 +0200341 * \param[in] bits A sequence of unpacked bits
342 * \param[in] len Length of bits
Neels Hofmeyrdd7b6f92019-11-20 21:32:29 +0100343 * \return The output buffer (buf).
Harald Welte8598f182011-08-17 14:19:27 +0200344 */
Harald Welte4a62eda2019-03-18 18:27:00 +0100345char *osmo_ubit_dump_buf(char *buf, size_t buf_len, const uint8_t *bits, unsigned int len)
Harald Welte3d0ac5e2011-02-08 16:55:03 +0100346{
347 int i;
348
Harald Welte4a62eda2019-03-18 18:27:00 +0100349 if (len > buf_len-1)
350 len = buf_len-1;
351 memset(buf, 0, buf_len);
Harald Welte3d0ac5e2011-02-08 16:55:03 +0100352
353 for (i = 0; i < len; i++) {
354 char outch;
355 switch (bits[i]) {
356 case 0:
357 outch = '0';
358 break;
359 case 0xff:
360 outch = '?';
361 break;
362 case 1:
363 outch = '1';
364 break;
365 default:
366 outch = 'E';
367 break;
368 }
Harald Welte4a62eda2019-03-18 18:27:00 +0100369 buf[i] = outch;
Harald Welte3d0ac5e2011-02-08 16:55:03 +0100370 }
Harald Welte4a62eda2019-03-18 18:27:00 +0100371 buf[buf_len-1] = 0;
372 return buf;
373}
374
375/*! Convert a sequence of unpacked bits to ASCII string, in static buffer.
376 * \param[in] bits A sequence of unpacked bits
377 * \param[in] len Length of bits
378 * \returns string representation in static buffer.
379 */
380char *osmo_ubit_dump(const uint8_t *bits, unsigned int len)
381{
382 return osmo_ubit_dump_buf(hexd_buff, sizeof(hexd_buff), bits, len);
Harald Welte3d0ac5e2011-02-08 16:55:03 +0100383}
384
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200385/*! Convert binary sequence to hexadecimal ASCII string
Harald Welte8598f182011-08-17 14:19:27 +0200386 * \param[in] buf pointer to sequence of bytes
387 * \param[in] len length of buf in number of bytes
388 * \returns pointer to zero-terminated string
389 *
390 * This function will print a sequence of bytes as hexadecimal numbers,
391 * adding one space character between each byte (e.g. "1a ef d9")
Harald Welte096a6662017-10-16 14:33:11 +0200392 *
393 * The maximum size of the output buffer is 4096 bytes, i.e. the maximum
394 * number of input bytes that can be printed in one call is 1365!
Harald Welte8598f182011-08-17 14:19:27 +0200395 */
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200396char *osmo_hexdump(const unsigned char *buf, int len)
Harald Weltedee47cd2010-07-30 11:43:30 +0200397{
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100398 osmo_hexdump_buf(hexd_buff, sizeof(hexd_buff), buf, len, " ", true);
399 return hexd_buff;
Harald Weltedee47cd2010-07-30 11:43:30 +0200400}
401
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200402/*! Convert binary sequence to hexadecimal ASCII string
Harald Welte179f3572019-03-18 18:38:47 +0100403 * \param[in] ctx talloc context from where to allocate the output string
404 * \param[in] buf pointer to sequence of bytes
405 * \param[in] len length of buf in number of bytes
406 * \returns pointer to zero-terminated string
407 *
408 * This function will print a sequence of bytes as hexadecimal numbers,
409 * adding one space character between each byte (e.g. "1a ef d9")
410 *
411 * The maximum size of the output buffer is 4096 bytes, i.e. the maximum
412 * number of input bytes that can be printed in one call is 1365!
413 */
414char *osmo_hexdump_c(const void *ctx, const unsigned char *buf, int len)
415{
Vadim Yanitskiy4f619c22019-04-12 21:48:07 +0700416 size_t hexd_buff_len = len * 3 + 1;
417 char *hexd_buff = talloc_size(ctx, hexd_buff_len);
Harald Welte179f3572019-03-18 18:38:47 +0100418 if (!hexd_buff)
419 return NULL;
Vadim Yanitskiy4f619c22019-04-12 21:48:07 +0700420 osmo_hexdump_buf(hexd_buff, hexd_buff_len, buf, len, " ", true);
Harald Welte179f3572019-03-18 18:38:47 +0100421 return hexd_buff;
422}
423
424/*! Convert binary sequence to hexadecimal ASCII string
Harald Welte8598f182011-08-17 14:19:27 +0200425 * \param[in] buf pointer to sequence of bytes
426 * \param[in] len length of buf in number of bytes
427 * \returns pointer to zero-terminated string
428 *
429 * This function will print a sequence of bytes as hexadecimal numbers,
430 * without any space character between each byte (e.g. "1aefd9")
Harald Welte096a6662017-10-16 14:33:11 +0200431 *
432 * The maximum size of the output buffer is 4096 bytes, i.e. the maximum
433 * number of input bytes that can be printed in one call is 2048!
Harald Welte8598f182011-08-17 14:19:27 +0200434 */
Sylvain Munautff23d242011-11-10 23:03:18 +0100435char *osmo_hexdump_nospc(const unsigned char *buf, int len)
Harald Weltedee47cd2010-07-30 11:43:30 +0200436{
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100437 osmo_hexdump_buf(hexd_buff, sizeof(hexd_buff), buf, len, "", true);
438 return hexd_buff;
Harald Weltedee47cd2010-07-30 11:43:30 +0200439}
Harald Welte28222962011-02-18 20:37:04 +0100440
Harald Welte179f3572019-03-18 18:38:47 +0100441/*! Convert binary sequence to hexadecimal ASCII string
442 * \param[in] ctx talloc context from where to allocate the output string
443 * \param[in] buf pointer to sequence of bytes
444 * \param[in] len length of buf in number of bytes
445 * \returns pointer to zero-terminated string
446 *
447 * This function will print a sequence of bytes as hexadecimal numbers,
448 * without any space character between each byte (e.g. "1aefd9")
449 *
450 * The maximum size of the output buffer is 4096 bytes, i.e. the maximum
451 * number of input bytes that can be printed in one call is 2048!
452 */
453char *osmo_hexdump_nospc_c(const void *ctx, const unsigned char *buf, int len)
454{
Vadim Yanitskiy4f619c22019-04-12 21:48:07 +0700455 size_t hexd_buff_len = len * 2 + 1;
456 char *hexd_buff = talloc_size(ctx, hexd_buff_len);
Harald Welte179f3572019-03-18 18:38:47 +0100457 if (!hexd_buff)
458 return NULL;
Vadim Yanitskiy4f619c22019-04-12 21:48:07 +0700459 osmo_hexdump_buf(hexd_buff, hexd_buff_len, buf, len, "", true);
Harald Welte179f3572019-03-18 18:38:47 +0100460 return hexd_buff;
461}
462
463
Holger Hans Peter Freyther9a1a5a12015-04-11 19:26:55 +0200464/* Compat with previous typo to preserve abi */
Sylvain Munaute55ae3a2011-11-11 23:06:55 +0100465char *osmo_osmo_hexdump_nospc(const unsigned char *buf, int len)
Holger Hans Peter Freyther9a1a5a12015-04-11 19:26:55 +0200466#if defined(__MACH__) && defined(__APPLE__)
467 ;
468#else
Sylvain Munaut17af41d2011-11-19 22:30:39 +0100469 __attribute__((weak, alias("osmo_hexdump_nospc")));
Holger Hans Peter Freyther9a1a5a12015-04-11 19:26:55 +0200470#endif
Sylvain Munaute55ae3a2011-11-11 23:06:55 +0100471
Harald Welte28222962011-02-18 20:37:04 +0100472#include "../config.h"
473#ifdef HAVE_CTYPE_H
474#include <ctype.h>
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200475/*! Convert an entire string to lower case
Harald Welte8598f182011-08-17 14:19:27 +0200476 * \param[out] out output string, caller-allocated
477 * \param[in] in input string
478 */
Harald Welte28222962011-02-18 20:37:04 +0100479void osmo_str2lower(char *out, const char *in)
480{
481 unsigned int i;
482
483 for (i = 0; i < strlen(in); i++)
Pau Espin Pedrol399a6f02017-06-18 14:07:37 +0200484 out[i] = tolower((const unsigned char)in[i]);
Harald Welte28222962011-02-18 20:37:04 +0100485 out[strlen(in)] = '\0';
486}
487
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200488/*! Convert an entire string to upper case
Harald Welte8598f182011-08-17 14:19:27 +0200489 * \param[out] out output string, caller-allocated
490 * \param[in] in input string
491 */
Harald Welte28222962011-02-18 20:37:04 +0100492void osmo_str2upper(char *out, const char *in)
493{
494 unsigned int i;
495
496 for (i = 0; i < strlen(in); i++)
Pau Espin Pedrol399a6f02017-06-18 14:07:37 +0200497 out[i] = toupper((const unsigned char)in[i]);
Harald Welte28222962011-02-18 20:37:04 +0100498 out[strlen(in)] = '\0';
499}
500#endif /* HAVE_CTYPE_H */
Harald Welte8598f182011-08-17 14:19:27 +0200501
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200502/*! Wishful thinking to generate a constant time compare
Harald Welte9709b2e2016-04-25 18:47:53 +0200503 * \param[in] exp Expected data
504 * \param[in] rel Comparison value
505 * \param[in] count Number of bytes to compare
506 * \returns 1 in case \a exp equals \a rel; zero otherwise
507 *
508 * Compare count bytes of exp to rel. Return 0 if they are identical, 1
509 * otherwise. Do not return a mismatch on the first mismatching byte,
510 * but always compare all bytes, regardless. The idea is that the amount of
511 * matching bytes cannot be inferred from the time the comparison took. */
512int osmo_constant_time_cmp(const uint8_t *exp, const uint8_t *rel, const int count)
513{
514 int x = 0, i;
515
516 for (i = 0; i < count; ++i)
517 x |= exp[i] ^ rel[i];
518
519 /* if x is zero, all data was identical */
520 return x? 1 : 0;
521}
522
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200523/*! Generic retrieval of 1..8 bytes as big-endian uint64_t
Harald Welte9709b2e2016-04-25 18:47:53 +0200524 * \param[in] data Input data as byte-array
525 * \param[in] data_len Length of \a data in octets
526 * \returns uint64_t of \a data interpreted as big-endian
527 *
528 * This is like osmo_load64be_ext, except that if data_len is less than
529 * sizeof(uint64_t), the data is interpreted as the least significant bytes
530 * (osmo_load64be_ext loads them as the most significant bytes into the
531 * returned uint64_t). In this way, any integer size up to 64 bits can be
532 * decoded conveniently by using sizeof(), without the need to call specific
533 * numbered functions (osmo_load16, 32, ...). */
534uint64_t osmo_decode_big_endian(const uint8_t *data, size_t data_len)
535{
536 uint64_t value = 0;
537
538 while (data_len > 0) {
539 value = (value << 8) + *data;
540 data += 1;
541 data_len -= 1;
542 }
543
544 return value;
545}
546
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200547/*! Generic big-endian encoding of big endian number up to 64bit
Harald Welte9709b2e2016-04-25 18:47:53 +0200548 * \param[in] value unsigned integer value to be stored
Pau Espin Pedrolc29d5132020-09-21 17:09:31 +0200549 * \param[in] data_len number of octets
Harald Welte9709b2e2016-04-25 18:47:53 +0200550 * \returns static buffer containing big-endian stored value
551 *
552 * This is like osmo_store64be_ext, except that this returns a static buffer of
553 * the result (for convenience, but not threadsafe). If data_len is less than
554 * sizeof(uint64_t), only the least significant bytes of value are encoded. */
555uint8_t *osmo_encode_big_endian(uint64_t value, size_t data_len)
556{
Harald Welte171ef822019-03-28 10:49:05 +0100557 static __thread uint8_t buf[sizeof(uint64_t)];
Harald Welte9709b2e2016-04-25 18:47:53 +0200558 OSMO_ASSERT(data_len <= ARRAY_SIZE(buf));
559 osmo_store64be_ext(value, buf, data_len);
560 return buf;
561}
Harald Welteaeecc482016-11-26 10:41:40 +0100562
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200563/*! Copy a C-string into a sized buffer
Harald Welteaeecc482016-11-26 10:41:40 +0100564 * \param[in] src source string
565 * \param[out] dst destination string
Neels Hofmeyrdf83ece2017-01-13 13:55:43 +0100566 * \param[in] siz size of the \a dst buffer
567 * \returns length of \a src
Harald Welteaeecc482016-11-26 10:41:40 +0100568 *
Neels Hofmeyrdf83ece2017-01-13 13:55:43 +0100569 * Copy at most \a siz bytes from \a src to \a dst, ensuring that the result is
570 * NUL terminated. The NUL character is included in \a siz, i.e. passing the
571 * actual sizeof(*dst) is correct.
Neels Hofmeyrff65d242019-11-19 00:21:14 +0100572 *
573 * Note, a similar function that also limits the input buffer size is osmo_print_n().
Harald Welteaeecc482016-11-26 10:41:40 +0100574 */
575size_t osmo_strlcpy(char *dst, const char *src, size_t siz)
576{
Neels Hofmeyrbcf9f232017-10-25 04:16:45 +0200577 size_t ret = src ? strlen(src) : 0;
Harald Welteaeecc482016-11-26 10:41:40 +0100578
579 if (siz) {
Pau Espin Pedrol53fbc672020-09-21 17:13:30 +0200580 size_t len = OSMO_MIN(siz - 1, ret);
Pau Espin Pedrolc29d5132020-09-21 17:09:31 +0200581 if (len)
Neels Hofmeyrebd3cdd2017-11-18 23:07:38 +0100582 memcpy(dst, src, len);
Harald Welteaeecc482016-11-26 10:41:40 +0100583 dst[len] = '\0';
584 }
585 return ret;
586}
Neels Hofmeyr0aeda1b2017-01-13 14:16:02 +0100587
Neels Hofmeyr06356fd2019-11-19 01:38:10 +0100588/*! Find first occurence of a char in a size limited string.
589 * Like strchr() but with a buffer size limit.
590 * \param[in] str String buffer to examine.
591 * \param[in] str_size sizeof(str).
592 * \param[in] c Character to look for.
593 * \return Pointer to the matched char, or NULL if not found.
594 */
595const char *osmo_strnchr(const char *str, size_t str_size, char c)
596{
597 const char *end = str + str_size;
598 const char *pos;
599 if (!str)
600 return NULL;
601 for (pos = str; pos < end; pos++) {
602 if (c == *pos)
603 return pos;
604 if (!*pos)
605 return NULL;
606 }
607 return NULL;
608}
609
Neels Hofmeyr4335bad2017-10-07 04:39:14 +0200610/*! Validate that a given string is a hex string within given size limits.
611 * Note that each hex digit amounts to a nibble, so if checking for a hex
612 * string to result in N bytes, pass amount of digits as 2*N.
613 * \param str A nul-terminated string to validate, or NULL.
614 * \param min_digits least permitted amount of digits.
615 * \param max_digits most permitted amount of digits.
616 * \param require_even if true, require an even amount of digits.
617 * \returns true when the hex_str contains only hexadecimal digits (no
618 * whitespace) and matches the requested length; also true
619 * when min_digits <= 0 and str is NULL.
620 */
621bool osmo_is_hexstr(const char *str, int min_digits, int max_digits,
622 bool require_even)
623{
624 int len;
625 /* Use unsigned char * to avoid a compiler warning of
626 * "error: array subscript has type 'char' [-Werror=char-subscripts]" */
627 const unsigned char *pos = (const unsigned char*)str;
628 if (!pos)
629 return min_digits < 1;
630 for (len = 0; *pos && len < max_digits; len++, pos++)
631 if (!isxdigit(*pos))
632 return false;
633 if (len < min_digits)
634 return false;
635 /* With not too many digits, we should have reached *str == nul */
636 if (*pos)
637 return false;
638 if (require_even && (len & 1))
639 return false;
Harald Weltefebe83c2017-10-03 17:41:59 +0800640
641 return true;
642}
643
Neels Hofmeyrb480b742019-04-11 06:58:44 +0200644static const char osmo_identifier_illegal_chars[] = "., {}[]()<>|~\\^`'\"?=;/+*&%$#!";
645
Harald Weltefebe83c2017-10-03 17:41:59 +0800646/*! Determine if a given identifier is valid, i.e. doesn't contain illegal chars
647 * \param[in] str String to validate
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100648 * \param[in] sep_chars Permitted separation characters between identifiers.
649 * \returns true in case \a str contains only valid identifiers and sep_chars, false otherwise
Harald Weltefebe83c2017-10-03 17:41:59 +0800650 */
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100651bool osmo_separated_identifiers_valid(const char *str, const char *sep_chars)
Harald Weltefebe83c2017-10-03 17:41:59 +0800652{
653 /* characters that are illegal in names */
Harald Weltefebe83c2017-10-03 17:41:59 +0800654 unsigned int i;
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100655 size_t len;
Harald Weltefebe83c2017-10-03 17:41:59 +0800656
657 /* an empty string is not a valid identifier */
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100658 if (!str || (len = strlen(str)) == 0)
Harald Weltefebe83c2017-10-03 17:41:59 +0800659 return false;
660
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100661 for (i = 0; i < len; i++) {
662 if (sep_chars && strchr(sep_chars, str[i]))
663 continue;
Harald Weltefebe83c2017-10-03 17:41:59 +0800664 /* check for 7-bit ASCII */
665 if (str[i] & 0x80)
666 return false;
Neels Hofmeyre5a2bdb2017-12-16 04:54:37 +0100667 if (!isprint((int)str[i]))
668 return false;
Harald Weltefebe83c2017-10-03 17:41:59 +0800669 /* check for some explicit reserved control characters */
Neels Hofmeyrb480b742019-04-11 06:58:44 +0200670 if (strchr(osmo_identifier_illegal_chars, str[i]))
Harald Weltefebe83c2017-10-03 17:41:59 +0800671 return false;
672 }
673
Neels Hofmeyr4335bad2017-10-07 04:39:14 +0200674 return true;
675}
676
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100677/*! Determine if a given identifier is valid, i.e. doesn't contain illegal chars
678 * \param[in] str String to validate
679 * \returns true in case \a str contains valid identifier, false otherwise
680 */
681bool osmo_identifier_valid(const char *str)
682{
683 return osmo_separated_identifiers_valid(str, NULL);
684}
685
Neels Hofmeyrb480b742019-04-11 06:58:44 +0200686/*! Replace characters in the given string buffer so that it is guaranteed to pass osmo_separated_identifiers_valid().
687 * To guarantee passing osmo_separated_identifiers_valid(), replace_with must not itself be an illegal character. If in
688 * doubt, use '-'.
689 * \param[inout] str Identifier to sanitize, must be nul terminated and in a writable buffer.
690 * \param[in] sep_chars Additional characters that are allowed besides osmo_identifier_illegal_chars.
691 * \param[in] replace_with Replace any illegal characters with this character.
692 */
693void osmo_identifier_sanitize_buf(char *str, const char *sep_chars, char replace_with)
694{
695 char *pos;
696 if (!str)
697 return;
698 for (pos = str; *pos; pos++) {
699 if (strchr(osmo_identifier_illegal_chars, *pos)
700 || (sep_chars && strchr(sep_chars, *pos)))
701 *pos = replace_with;
702 }
703}
704
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100705/*! Like osmo_escape_str_buf2, but with unusual ordering of arguments, and may sometimes return string constants instead
706 * of writing to buf for error cases or empty input.
707 * Most *_buf() functions have the buffer and size as first arguments, here the arguments are last.
708 * In particular, this function signature doesn't work with OSMO_STRBUF_APPEND_NOLEN().
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100709 * \param[in] str A string that may contain any characters.
710 * \param[in] len Pass -1 to print until nul char, or >= 0 to force a length.
711 * \param[inout] buf string buffer to write escaped characters to.
712 * \param[in] bufsize size of \a buf.
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100713 * \returns buf containing an escaped representation, possibly truncated,
714 * or "(null)" if str == NULL, or "(error)" in case of errors.
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100715 */
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100716const char *osmo_escape_str_buf(const char *str, int in_len, char *buf, size_t bufsize)
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100717{
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100718 if (!str)
719 return "(null)";
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100720 if (!buf || !bufsize)
721 return "(error)";
722 return osmo_escape_str_buf2(buf, bufsize, str, in_len);
723}
724
725/*! Copy N characters to a buffer with a function signature useful for OSMO_STRBUF_APPEND().
726 * Similarly to snprintf(), the result is always nul terminated (except if buf is NULL or bufsize is 0).
727 * \param[out] buf Target buffer.
728 * \param[in] bufsize sizeof(buf).
729 * \param[in] str String to copy.
730 * \param[in] n Maximum number of non-nul characters to copy.
731 * \return Number of characters that would be written if bufsize were large enough excluding '\0' (like snprintf()).
732 */
733int osmo_print_n(char *buf, size_t bufsize, const char *str, size_t n)
734{
735 size_t write_n;
736
737 if (!str)
738 str = "";
739
740 n = strnlen(str, n);
741
742 if (!buf || !bufsize)
743 return n;
744 write_n = n;
745 if (write_n >= bufsize)
746 write_n = bufsize - 1;
747 if (write_n)
748 strncpy(buf, str, write_n);
749 buf[write_n] = '\0';
750
751 return n;
752}
753
754/*! Return the string with all non-printable characters escaped.
Neels Hofmeyrc36e2e42019-11-20 21:57:32 +0100755 * This internal function is the implementation for all osmo_escape_str* and osmo_quote_str* API versions.
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100756 * It provides both the legacy (non C compatible) escaping, as well as C compatible string constant syntax,
757 * 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 +0100758 * \param[out] buf string buffer to write escaped characters to.
759 * \param[in] bufsize sizeof(buf).
760 * \param[in] str A string that may contain any characters.
761 * \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 +0100762 * \param[in] legacy_format If false, return C compatible string constants ("\x0f"), if true the legacy
763 * escaping format ("\15"). The legacy format also escapes as "\a\b\f\v", while
764 * the non-legacy format also escapes those as "\xNN" sequences.
Neels Hofmeyrc36e2e42019-11-20 21:57:32 +0100765 * \return Number of characters that would be written if bufsize were large enough excluding '\0' (like snprintf()).
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100766 */
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100767static 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 +0100768{
769 struct osmo_strbuf sb = { .buf = buf, .len = bufsize };
770 int in_pos = 0;
771 int next_unprintable = 0;
772
773 if (!str)
774 in_len = 0;
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100775
776 if (in_len < 0)
777 in_len = strlen(str);
778
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100779 /* Make sure of '\0' termination */
780 if (!in_len)
781 OSMO_STRBUF_PRINTF(sb, "%s", "");
782
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100783 while (in_pos < in_len) {
784 for (next_unprintable = in_pos;
785 next_unprintable < in_len && isprint((int)str[next_unprintable])
786 && str[next_unprintable] != '"'
787 && str[next_unprintable] != '\\';
788 next_unprintable++);
789
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100790 OSMO_STRBUF_APPEND(sb, osmo_print_n, &str[in_pos], next_unprintable - in_pos);
791 in_pos = next_unprintable;
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100792
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100793 if (in_pos == in_len)
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100794 goto done;
795
796 switch (str[next_unprintable]) {
797#define BACKSLASH_CASE(c, repr) \
798 case c: \
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100799 OSMO_STRBUF_PRINTF(sb, "\\%c", repr); \
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100800 break
801
802 BACKSLASH_CASE('\n', 'n');
803 BACKSLASH_CASE('\r', 'r');
804 BACKSLASH_CASE('\t', 't');
805 BACKSLASH_CASE('\0', '0');
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100806 BACKSLASH_CASE('\\', '\\');
807 BACKSLASH_CASE('"', '"');
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100808
809 default:
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100810 if (legacy_format) {
811 switch (str[next_unprintable]) {
812 BACKSLASH_CASE('\a', 'a');
813 BACKSLASH_CASE('\b', 'b');
814 BACKSLASH_CASE('\v', 'v');
815 BACKSLASH_CASE('\f', 'f');
816 default:
817 OSMO_STRBUF_PRINTF(sb, "\\%u", (unsigned char)str[in_pos]);
818 break;
819 }
820 break;
821 }
822
823 OSMO_STRBUF_PRINTF(sb, "\\x%02x", (unsigned char)str[in_pos]);
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100824 break;
825 }
826 in_pos ++;
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100827#undef BACKSLASH_CASE
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100828 }
829
830done:
Neels Hofmeyrc36e2e42019-11-20 21:57:32 +0100831 return sb.chars_needed;
832}
833
834/*! Return the string with all non-printable characters escaped.
835 * \param[out] buf string buffer to write escaped characters to.
836 * \param[in] bufsize sizeof(buf).
837 * \param[in] str A string that may contain any characters.
838 * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length (also past nul chars).
839 * \return The output buffer (buf).
840 */
841char *osmo_escape_str_buf2(char *buf, size_t bufsize, const char *str, int in_len)
842{
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100843 _osmo_escape_str_buf(buf, bufsize, str, in_len, true);
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100844 return buf;
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100845}
846
847/*! Return the string with all non-printable characters escaped.
848 * Call osmo_escape_str_buf() with a static 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 buf containing an escaped representation, possibly truncated, or str itself.
852 */
853const char *osmo_escape_str(const char *str, int in_len)
854{
855 return osmo_escape_str_buf(str, in_len, namebuf, sizeof(namebuf));
856}
857
Harald Welte179f3572019-03-18 18:38:47 +0100858/*! Return the string with all non-printable characters escaped, in dynamically-allocated buffer.
859 * \param[in] str A string that may contain any characters.
860 * \param[in] len Pass -1 to print until nul char, or >= 0 to force a length.
861 * \returns dynamically-allocated output buffer, containing an escaped representation
862 */
863char *osmo_escape_str_c(const void *ctx, const char *str, int in_len)
864{
Neels Hofmeyrc36e2e42019-11-20 21:57:32 +0100865 /* The string will be at least as long as in_len, but some characters might need escaping.
866 * 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 +0100867 OSMO_NAME_C_IMPL(ctx, in_len + 16, "ERROR", _osmo_escape_str_buf, str, in_len, true);
Neels Hofmeyrc36e2e42019-11-20 21:57:32 +0100868}
869
870/*! Return a quoted and escaped representation of the string.
871 * This internal function is the implementation for all osmo_quote_str* API versions.
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100872 * It provides both the legacy (non C compatible) escaping, as well as C compatible string constant syntax,
873 * 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 +0100874 * \param[out] buf string buffer to write escaped characters to.
875 * \param[in] bufsize sizeof(buf).
876 * \param[in] str A string that may contain any characters.
877 * \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 +0100878 * \param[in] legacy_format If false, return C compatible string constants ("\x0f"), if true the legacy
879 * escaping format ("\15"). The legacy format also escapes as "\a\b\f\v", while
880 * the non-legacy format also escapes those as "\xNN" sequences.
Neels Hofmeyrc36e2e42019-11-20 21:57:32 +0100881 * \return Number of characters that would be written if bufsize were large enough excluding '\0' (like snprintf()).
882 */
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100883static 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 +0100884{
885 struct osmo_strbuf sb = { .buf = buf, .len = bufsize };
886 if (!str)
887 OSMO_STRBUF_PRINTF(sb, "NULL");
888 else {
889 OSMO_STRBUF_PRINTF(sb, "\"");
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100890 OSMO_STRBUF_APPEND(sb, _osmo_escape_str_buf, str, in_len, legacy_format);
Neels Hofmeyrc36e2e42019-11-20 21:57:32 +0100891 OSMO_STRBUF_PRINTF(sb, "\"");
892 }
893 return sb.chars_needed;
Harald Welte179f3572019-03-18 18:38:47 +0100894}
895
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100896/*! 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 +0200897 * This allows passing any char* value and get its C representation as string.
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100898 * The function signature is suitable for OSMO_STRBUF_APPEND_NOLEN().
899 * \param[out] buf string buffer to write escaped characters to.
900 * \param[in] bufsize sizeof(buf).
901 * \param[in] str A string that may contain any characters.
902 * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length.
Neels Hofmeyrdd7b6f92019-11-20 21:32:29 +0100903 * \return The output buffer (buf).
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100904 */
905char *osmo_quote_str_buf2(char *buf, size_t bufsize, const char *str, int in_len)
906{
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100907 _osmo_quote_str_buf(buf, bufsize, str, in_len, true);
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100908 return buf;
909}
910
911/*! Like osmo_quote_str_buf2, but with unusual ordering of arguments, and may sometimes return string constants instead
912 * of writing to buf for error cases or empty input.
913 * Most *_buf() functions have the buffer and size as first arguments, here the arguments are last.
914 * In particular, this function signature doesn't work with OSMO_STRBUF_APPEND_NOLEN().
Neels Hofmeyr04eb56f2018-04-09 00:41:28 +0200915 * \param[in] str A string that may contain any characters.
Neels Hofmeyr03e75532018-09-07 03:12:05 +0200916 * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length.
917 * \returns buf containing a quoted and escaped representation, possibly truncated.
Neels Hofmeyr04eb56f2018-04-09 00:41:28 +0200918 */
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100919const char *osmo_quote_str_buf(const char *str, int in_len, char *buf, size_t bufsize)
Neels Hofmeyr04eb56f2018-04-09 00:41:28 +0200920{
Neels Hofmeyr04eb56f2018-04-09 00:41:28 +0200921 if (!str)
922 return "NULL";
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100923 if (!buf || !bufsize)
924 return "(error)";
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100925 _osmo_quote_str_buf(buf, bufsize, str, in_len, true);
Neels Hofmeyr04eb56f2018-04-09 00:41:28 +0200926 return buf;
927}
928
Neels Hofmeyr03e75532018-09-07 03:12:05 +0200929/*! Like osmo_quote_str_buf() but returns the result in a static buffer.
930 * The static buffer is shared with get_value_string() and osmo_escape_str().
931 * \param[in] str A string that may contain any characters.
932 * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length.
933 * \returns static buffer containing a quoted and escaped representation, possibly truncated.
934 */
Neels Hofmeyr04eb56f2018-04-09 00:41:28 +0200935const char *osmo_quote_str(const char *str, int in_len)
936{
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100937 _osmo_quote_str_buf(namebuf, sizeof(namebuf), str, in_len, true);
Neels Hofmeyrc36e2e42019-11-20 21:57:32 +0100938 return namebuf;
Neels Hofmeyr04eb56f2018-04-09 00:41:28 +0200939}
940
Harald Welte179f3572019-03-18 18:38:47 +0100941/*! Like osmo_quote_str_buf() but returns the result in a dynamically-allocated buffer.
Harald Welte179f3572019-03-18 18:38:47 +0100942 * \param[in] str A string that may contain any characters.
943 * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length.
944 * \returns dynamically-allocated buffer containing a quoted and escaped representation.
945 */
946char *osmo_quote_str_c(const void *ctx, const char *str, int in_len)
947{
Neels Hofmeyrc36e2e42019-11-20 21:57:32 +0100948 /* The string will be at least as long as in_len, but some characters might need escaping.
949 * 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 +0100950 OSMO_NAME_C_IMPL(ctx, in_len + 16, "ERROR", _osmo_quote_str_buf, str, in_len, true);
951}
952
953/*! Return the string with all non-printable characters escaped.
954 * In contrast to osmo_escape_str_buf2(), this returns the needed buffer size suitable for OSMO_STRBUF_APPEND(), and
955 * this escapes characters in a way compatible with C string constant syntax.
956 * \param[out] buf string buffer to write escaped characters to.
957 * \param[in] bufsize sizeof(buf).
958 * \param[in] str A string that may contain any characters.
959 * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length (also past nul chars).
960 * \return Number of characters that would be written if bufsize were large enough excluding '\0' (like snprintf()).
961 */
962size_t osmo_escape_cstr_buf(char *buf, size_t bufsize, const char *str, int in_len)
963{
964 return _osmo_escape_str_buf(buf, bufsize, str, in_len, false);
965}
966
967/*! Return the string with all non-printable characters escaped, in dynamically-allocated buffer.
968 * In contrast to osmo_escape_str_c(), this escapes characters in a way compatible with C string constant syntax, and
969 * allocates sufficient memory in all cases.
970 * \param[in] str A string that may contain any characters.
971 * \param[in] len Pass -1 to print until nul char, or >= 0 to force a length.
972 * \returns dynamically-allocated buffer, containing an escaped representation.
973 */
974char *osmo_escape_cstr_c(void *ctx, const char *str, int in_len)
975{
976 /* The string will be at least as long as in_len, but some characters might need escaping.
977 * These extra bytes should catch most usual escaping situations, avoiding a second run in OSMO_NAME_C_IMPL. */
978 OSMO_NAME_C_IMPL(ctx, in_len + 16, "ERROR", _osmo_escape_str_buf, str, in_len, false);
979}
980
981/*! Like osmo_escape_str_buf2(), but returns double-quotes around a string, or "NULL" for a NULL string.
982 * This allows passing any char* value and get its C representation as string.
983 * The function signature is suitable for OSMO_STRBUF_APPEND_NOLEN().
984 * In contrast to osmo_escape_str_buf2(), this returns the needed buffer size suitable for OSMO_STRBUF_APPEND(), and
985 * this escapes characters in a way compatible with C string constant syntax.
986 * \param[out] buf string buffer to write escaped characters to.
987 * \param[in] bufsize sizeof(buf).
988 * \param[in] str A string that may contain any characters.
989 * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length.
990 * \return Number of characters that would be written if bufsize were large enough excluding '\0' (like snprintf()).
991 */
992size_t osmo_quote_cstr_buf(char *buf, size_t bufsize, const char *str, int in_len)
993{
994 return _osmo_quote_str_buf(buf, bufsize, str, in_len, false);
995}
996
997/*! Return the string quoted and with all non-printable characters escaped, in dynamically-allocated buffer.
998 * In contrast to osmo_quote_str_c(), this escapes characters in a way compatible with C string constant syntax, and
999 * allocates sufficient memory in all cases.
1000 * \param[in] str A string that may contain any characters.
1001 * \param[in] len Pass -1 to print until nul char, or >= 0 to force a length.
1002 * \returns dynamically-allocated buffer, containing a quoted and escaped representation.
1003 */
1004char *osmo_quote_cstr_c(void *ctx, const char *str, int in_len)
1005{
1006 /* The string will be at least as long as in_len plus two quotes, but some characters might need escaping.
1007 * These extra bytes should catch most usual escaping situations, avoiding a second run in OSMO_NAME_C_IMPL. */
1008 OSMO_NAME_C_IMPL(ctx, in_len + 16, "ERROR", _osmo_quote_str_buf, str, in_len, false);
Harald Welte179f3572019-03-18 18:38:47 +01001009}
1010
Harald Welte15a5f8d2018-06-06 16:58:17 +02001011/*! perform an integer square root operation on unsigned 32bit integer.
1012 * This implementation is taken from "Hacker's Delight" Figure 11-1 "Integer square root, Newton's
1013 * method", which can also be found at http://www.hackersdelight.org/hdcodetxt/isqrt.c.txt */
1014uint32_t osmo_isqrt32(uint32_t x)
1015{
1016 uint32_t x1;
1017 int s, g0, g1;
1018
1019 if (x <= 1)
1020 return x;
1021
1022 s = 1;
1023 x1 = x - 1;
1024 if (x1 > 0xffff) {
1025 s = s + 8;
1026 x1 = x1 >> 16;
1027 }
1028 if (x1 > 0xff) {
1029 s = s + 4;
1030 x1 = x1 >> 8;
1031 }
1032 if (x1 > 0xf) {
1033 s = s + 2;
1034 x1 = x1 >> 4;
1035 }
1036 if (x1 > 0x3) {
1037 s = s + 1;
1038 }
1039
1040 g0 = 1 << s; /* g0 = 2**s */
1041 g1 = (g0 + (x >> s)) >> 1; /* g1 = (g0 + x/g0)/2 */
1042
1043 /* converges after four to five divisions for arguments up to 16,785,407 */
1044 while (g1 < g0) {
1045 g0 = g1;
1046 g1 = (g0 + (x/g0)) >> 1;
1047 }
1048 return g0;
1049}
1050
Neels Hofmeyr7c749892018-09-07 03:01:38 +02001051/*! Convert a string to lowercase, while checking buffer size boundaries.
1052 * The result written to \a dest is guaranteed to be nul terminated if \a dest_len > 0.
1053 * If dest == src, the string is converted in-place, if necessary truncated at dest_len - 1 characters
1054 * length as well as nul terminated.
1055 * Note: similar osmo_str2lower(), but safe to use for src strings of arbitrary length.
1056 * \param[out] dest Target buffer to write lowercase string.
1057 * \param[in] dest_len Maximum buffer size of dest (e.g. sizeof(dest)).
1058 * \param[in] src String to convert to lowercase.
1059 * \returns Length of \a src, like osmo_strlcpy(), but if \a dest == \a src at most \a dest_len - 1.
1060 */
1061size_t osmo_str_tolower_buf(char *dest, size_t dest_len, const char *src)
1062{
1063 size_t rc;
1064 if (dest == src) {
1065 if (dest_len < 1)
1066 return 0;
1067 dest[dest_len - 1] = '\0';
1068 rc = strlen(dest);
1069 } else {
1070 if (dest_len < 1)
1071 return strlen(src);
1072 rc = osmo_strlcpy(dest, src, dest_len);
1073 }
1074 for (; *dest; dest++)
1075 *dest = tolower(*dest);
1076 return rc;
1077}
1078
1079/*! Convert a string to lowercase, using a static buffer.
1080 * The resulting string may be truncated if the internally used static buffer is shorter than src.
1081 * 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 +02001082 * terminating nul. The static buffer returned is shared with osmo_str_toupper().
Neels Hofmeyr7c749892018-09-07 03:01:38 +02001083 * See also osmo_str_tolower_buf().
1084 * \param[in] src String to convert to lowercase.
1085 * \returns Resulting lowercase string in a static buffer, always nul terminated.
1086 */
1087const char *osmo_str_tolower(const char *src)
1088{
Pau Espin Pedrola37f58e2019-08-01 18:11:41 +02001089 osmo_str_tolower_buf(capsbuf, sizeof(capsbuf), src);
1090 return capsbuf;
Neels Hofmeyr7c749892018-09-07 03:01:38 +02001091}
1092
Harald Welte179f3572019-03-18 18:38:47 +01001093/*! Convert a string to lowercase, dynamically allocating the output from given talloc context
1094 * See also osmo_str_tolower_buf().
1095 * \param[in] ctx talloc context from where to allocate the output string
1096 * \param[in] src String to convert to lowercase.
1097 * \returns Resulting lowercase string in a dynamically allocated buffer, always nul terminated.
1098 */
1099char *osmo_str_tolower_c(const void *ctx, const char *src)
1100{
Vadim Yanitskiy4f619c22019-04-12 21:48:07 +07001101 size_t buf_len = strlen(src) + 1;
1102 char *buf = talloc_size(ctx, buf_len);
Harald Welte179f3572019-03-18 18:38:47 +01001103 if (!buf)
1104 return NULL;
Vadim Yanitskiy4f619c22019-04-12 21:48:07 +07001105 osmo_str_tolower_buf(buf, buf_len, src);
Harald Welte179f3572019-03-18 18:38:47 +01001106 return buf;
1107}
1108
Neels Hofmeyr7c749892018-09-07 03:01:38 +02001109/*! Convert a string to uppercase, while checking buffer size boundaries.
1110 * The result written to \a dest is guaranteed to be nul terminated if \a dest_len > 0.
1111 * If dest == src, the string is converted in-place, if necessary truncated at dest_len - 1 characters
1112 * length as well as nul terminated.
1113 * Note: similar osmo_str2upper(), but safe to use for src strings of arbitrary length.
1114 * \param[out] dest Target buffer to write uppercase string.
1115 * \param[in] dest_len Maximum buffer size of dest (e.g. sizeof(dest)).
1116 * \param[in] src String to convert to uppercase.
1117 * \returns Length of \a src, like osmo_strlcpy(), but if \a dest == \a src at most \a dest_len - 1.
1118 */
1119size_t osmo_str_toupper_buf(char *dest, size_t dest_len, const char *src)
1120{
1121 size_t rc;
1122 if (dest == src) {
1123 if (dest_len < 1)
1124 return 0;
1125 dest[dest_len - 1] = '\0';
1126 rc = strlen(dest);
1127 } else {
1128 if (dest_len < 1)
1129 return strlen(src);
1130 rc = osmo_strlcpy(dest, src, dest_len);
1131 }
1132 for (; *dest; dest++)
1133 *dest = toupper(*dest);
1134 return rc;
1135}
1136
1137/*! Convert a string to uppercase, using a static buffer.
1138 * The resulting string may be truncated if the internally used static buffer is shorter than src.
1139 * 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 +02001140 * terminating nul. The static buffer returned is shared with osmo_str_tolower().
Neels Hofmeyr7c749892018-09-07 03:01:38 +02001141 * See also osmo_str_toupper_buf().
1142 * \param[in] src String to convert to uppercase.
1143 * \returns Resulting uppercase string in a static buffer, always nul terminated.
1144 */
1145const char *osmo_str_toupper(const char *src)
1146{
Pau Espin Pedrola37f58e2019-08-01 18:11:41 +02001147 osmo_str_toupper_buf(capsbuf, sizeof(capsbuf), src);
1148 return capsbuf;
Neels Hofmeyr7c749892018-09-07 03:01:38 +02001149}
1150
Harald Welte179f3572019-03-18 18:38:47 +01001151/*! Convert a string to uppercase, dynamically allocating the output from given talloc context
1152 * See also osmo_str_tolower_buf().
1153 * \param[in] ctx talloc context from where to allocate the output string
1154 * \param[in] src String to convert to uppercase.
1155 * \returns Resulting uppercase string in a dynamically allocated buffer, always nul terminated.
1156 */
1157char *osmo_str_toupper_c(const void *ctx, const char *src)
1158{
Vadim Yanitskiy4f619c22019-04-12 21:48:07 +07001159 size_t buf_len = strlen(src) + 1;
1160 char *buf = talloc_size(ctx, buf_len);
Harald Welte179f3572019-03-18 18:38:47 +01001161 if (!buf)
1162 return NULL;
Vadim Yanitskiy4f619c22019-04-12 21:48:07 +07001163 osmo_str_toupper_buf(buf, buf_len, src);
Harald Welte179f3572019-03-18 18:38:47 +01001164 return buf;
1165}
1166
Oliver Smith894be2d2019-01-11 13:13:37 +01001167/*! Calculate the Luhn checksum (as used for IMEIs).
1168 * \param[in] in Input digits in ASCII string representation.
1169 * \param[in] in_len Count of digits to use for the input (14 for IMEI).
1170 * \returns checksum char (e.g. '3'); negative on error
1171 */
Vadim Yanitskiyd9fc6042019-06-12 15:49:03 +07001172char osmo_luhn(const char* in, int in_len)
Oliver Smith894be2d2019-01-11 13:13:37 +01001173{
1174 int i, sum = 0;
1175
1176 /* All input must be numbers */
1177 for (i = 0; i < in_len; i++) {
KĂ©vin Redon1af2cd52019-05-23 19:00:19 +02001178 if (!isdigit((unsigned char)in[i]))
Oliver Smith894be2d2019-01-11 13:13:37 +01001179 return -EINVAL;
1180 }
1181
1182 /* Double every second digit and add it to sum */
1183 for (i = in_len - 1; i >= 0; i -= 2) {
1184 int dbl = (in[i] - '0') * 2;
1185 if (dbl > 9)
1186 dbl -= 9;
1187 sum += dbl;
1188 }
1189
1190 /* Add other digits to sum */
1191 for (i = in_len - 2; i >= 0; i -= 2)
1192 sum += in[i] - '0';
1193
1194 /* Final checksum */
1195 return (sum * 9) % 10 + '0';
1196}
1197
Neels Hofmeyrd79ccc62019-03-07 23:08:40 +01001198/*! Compare start of a string.
1199 * This is an optimisation of 'strstr(str, startswith_str) == str' because it doesn't search through the entire string.
1200 * \param str (Longer) string to compare.
1201 * \param startswith_str (Shorter) string to compare with the start of str.
1202 * \return true iff the first characters of str fully match startswith_str or startswith_str is empty. */
1203bool osmo_str_startswith(const char *str, const char *startswith_str)
1204{
1205 if (!startswith_str || !*startswith_str)
1206 return true;
1207 if (!str)
1208 return false;
1209 return strncmp(str, startswith_str, strlen(startswith_str)) == 0;
1210}
1211
Neels Hofmeyr87c3afb2020-09-30 21:47:47 +00001212/*! Convert a string of a floating point number to a signed int, with a decimal factor (fixed-point precision).
1213 * For example, with precision=3, convert "-1.23" to -1230. In other words, the float value is multiplied by
1214 * 10 to-the-power-of precision to obtain the returned integer.
1215 * The usable range of digits is -INT64_MAX .. INT64_MAX -- note, not INT64_MIN! The value of INT64_MIN is excluded to
1216 * reduce implementation complexity. See also utils_test.c.
Neels Hofmeyr6d744982020-10-08 13:09:49 +02001217 * The advantage over using sscanf("%f") is guaranteed precision: float or double types may apply rounding in the
1218 * conversion result. osmo_float_str_to_int() and osmo_int_to_float_str_buf() guarantee true results when converting
1219 * back and forth between string and int.
Neels Hofmeyr87c3afb2020-09-30 21:47:47 +00001220 * \param[out] val Returned integer value.
1221 * \param[in] str String of a float, like '-12.345'.
Neels Hofmeyr87c3afb2020-09-30 21:47:47 +00001222 * \param[in] precision Fixed-point precision, or * \returns 0 on success, negative on error.
1223 */
1224int osmo_float_str_to_int(int64_t *val, const char *str, unsigned int precision)
1225{
1226 const char *point;
1227 char *endptr;
1228 const char *p;
1229 int64_t sign = 1;
1230 int64_t integer = 0;
1231 int64_t decimal = 0;
1232 int64_t precision_factor;
1233 int64_t integer_max;
1234 int64_t decimal_max;
1235 int i;
1236
1237 OSMO_ASSERT(val);
1238 *val = 0;
1239
1240 if (!str)
1241 return -EINVAL;
1242 if (str[0] == '-') {
1243 str = str + 1;
1244 sign = -1;
1245 } else if (str[0] == '+') {
1246 str = str + 1;
1247 }
1248 if (!str[0])
1249 return -EINVAL;
1250
1251 /* Validate entire string as purely digits and at most one decimal dot. If not doing this here in advance,
1252 * parsing digits might stop early because of precision cut-off and miss validation of input data. */
1253 point = NULL;
1254 for (p = str; *p; p++) {
1255 if (*p == '.') {
1256 if (point)
1257 return -EINVAL;
1258 point = p;
1259 } else if (!isdigit(*p))
1260 return -EINVAL;
1261 }
1262
1263 /* Parse integer part if there is one. If the string starts with a point, there's nothing to parse for the
1264 * integer part. */
1265 if (!point || point > str) {
1266 errno = 0;
1267 integer = strtoll(str, &endptr, 10);
Harald Weltecb11a602020-10-09 10:08:44 +02001268 if ((errno == ERANGE && (integer == LLONG_MAX || integer == LLONG_MIN))
Neels Hofmeyr87c3afb2020-09-30 21:47:47 +00001269 || (errno != 0 && integer == 0))
1270 return -ERANGE;
1271
1272 if ((point && endptr != point)
1273 || (!point && *endptr))
1274 return -EINVAL;
1275 }
1276
1277 /* Parse the fractional part if there is any, and if the precision is nonzero (if we even care about fractional
1278 * digits) */
1279 if (precision && point && point[1] != '\0') {
1280 /* limit the number of digits parsed to 'precision'.
1281 * If 'precision' is larger than the 19 digits representable in int64_t, skip some, to pick up lower
1282 * magnitude digits. */
1283 unsigned int skip_digits = (precision < 20) ? 0 : precision - 20;
1284 char decimal_str[precision + 1];
1285 osmo_strlcpy(decimal_str, point+1, precision+1);
1286
1287 /* fill with zeros to make exactly 'precision' digits */
1288 for (i = strlen(decimal_str); i < precision; i++)
1289 decimal_str[i] = '0';
1290 decimal_str[precision] = '\0';
1291
1292 for (i = 0; i < skip_digits; i++) {
1293 /* When skipping digits because precision > nr-of-digits-in-int64_t, they must be zero;
1294 * if there is a nonzero digit above the precision, it's -ERANGE. */
1295 if (decimal_str[i] != '0')
1296 return -ERANGE;
1297 }
1298 errno = 0;
1299 decimal = strtoll(decimal_str + skip_digits, &endptr, 10);
Harald Weltecb11a602020-10-09 10:08:44 +02001300 if ((errno == ERANGE && (decimal == LLONG_MAX || decimal == LLONG_MIN))
Neels Hofmeyr87c3afb2020-09-30 21:47:47 +00001301 || (errno != 0 && decimal == 0))
1302 return -ERANGE;
1303
1304 if (*endptr)
1305 return -EINVAL;
1306 }
1307
1308 if (precision > 18) {
1309 /* Special case of returning more digits than fit in int64_t range, e.g.
1310 * osmo_float_str_to_int("0.0000000012345678901234567", precision=25) -> 12345678901234567. */
1311 precision_factor = 0;
1312 integer_max = 0;
1313 decimal_max = INT64_MAX;
1314 } else {
1315 /* Do not surpass the resulting int64_t range. Depending on the amount of precision, the integer part
1316 * and decimal part have specific ranges they must comply to. */
1317 precision_factor = 1;
1318 for (i = 0; i < precision; i++)
1319 precision_factor *= 10;
1320 integer_max = INT64_MAX / precision_factor;
1321 if (integer == integer_max)
1322 decimal_max = INT64_MAX % precision_factor;
1323 else
1324 decimal_max = INT64_MAX;
1325 }
1326
1327 if (integer > integer_max)
1328 return -ERANGE;
1329 if (decimal > decimal_max)
1330 return -ERANGE;
1331
1332 *val = sign * (integer * precision_factor + decimal);
1333 return 0;
1334}
1335
Neels Hofmeyr6d744982020-10-08 13:09:49 +02001336/*! Convert an integer to a floating point string using a decimal quotient (fixed-point precision).
Neels Hofmeyr87c3afb2020-09-30 21:47:47 +00001337 * For example, with precision = 3, convert -1230 to "-1.23".
Neels Hofmeyr6d744982020-10-08 13:09:49 +02001338 * The usable range of digits is -INT64_MAX .. INT64_MAX -- note, not INT64_MIN! The value of INT64_MIN is excluded to
1339 * reduce implementation complexity. See also utils_test.c.
1340 * The advantage over using printf("%.6g") is guaranteed precision: float or double types may apply rounding in the
1341 * conversion result. osmo_float_str_to_int() and osmo_int_to_float_str_buf() guarantee true results when converting
1342 * back and forth between string and int.
1343 * The resulting string omits trailing zeros in the fractional part (like "%g" would) but never applies rounding.
Neels Hofmeyr87c3afb2020-09-30 21:47:47 +00001344 * \param[out] buf Buffer to write string to.
1345 * \param[in] buflen sizeof(buf).
1346 * \param[in] val Value to convert to float.
1347 * \returns number of chars that would be written, like snprintf().
1348 */
1349int osmo_int_to_float_str_buf(char *buf, size_t buflen, int64_t val, unsigned int precision)
1350{
1351 struct osmo_strbuf sb = { .buf = buf, .len = buflen };
1352 unsigned int i;
1353 unsigned int w;
1354 int64_t precision_factor;
1355 if (val < 0) {
1356 OSMO_STRBUF_PRINTF(sb, "-");
1357 if (val == INT64_MIN) {
1358 OSMO_STRBUF_PRINTF(sb, "ERR");
1359 return sb.chars_needed;
1360 }
1361 val = -val;
1362 }
1363
1364 if (precision > 18) {
1365 /* Special case of returning more digits than fit in int64_t range, e.g.
1366 * osmo_int_to_float_str(12345678901234567, precision=25) -> "0.0000000012345678901234567". */
1367 if (!val) {
1368 OSMO_STRBUF_PRINTF(sb, "0");
1369 return sb.chars_needed;
1370 }
1371 OSMO_STRBUF_PRINTF(sb, "0.");
1372 for (i = 19; i < precision; i++)
1373 OSMO_STRBUF_PRINTF(sb, "0");
1374 precision = 19;
1375 } else {
1376 precision_factor = 1;
1377 for (i = 0; i < precision; i++)
1378 precision_factor *= 10;
1379
1380 OSMO_STRBUF_PRINTF(sb, "%" PRId64, val / precision_factor);
1381 val %= precision_factor;
1382 if (!val)
1383 return sb.chars_needed;
1384 OSMO_STRBUF_PRINTF(sb, ".");
1385 }
1386
1387 /* print fractional part, skip trailing zeros */
1388 w = precision;
1389 while (!(val % 10)) {
1390 val /= 10;
1391 w--;
1392 }
1393 OSMO_STRBUF_PRINTF(sb, "%0*" PRId64, w, val);
1394 return sb.chars_needed;
1395}
1396
1397/*! Convert an integer with a factor of a million to a floating point string.
1398 * For example, convert -1230000 to "-1.23".
1399 * \param[in] ctx Talloc ctx to allocate string buffer from.
1400 * \param[in] val Value to convert to float.
1401 * \returns resulting string, dynamically allocated.
1402 */
1403char *osmo_int_to_float_str_c(void *ctx, int64_t val, unsigned int precision)
1404{
1405 OSMO_NAME_C_IMPL(ctx, 16, "ERROR", osmo_int_to_float_str_buf, val, precision)
1406}
1407
Neels Hofmeyr0aeda1b2017-01-13 14:16:02 +01001408/*! @} */