blob: ea0bbde0695cbf04ff657704c49a0b040284e500 [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>
Harald Welted284cd92010-03-01 21:58:31 +010033
Pablo Neira Ayuso83419342011-03-22 16:36:13 +010034#include <osmocom/core/utils.h>
Harald Welte9709b2e2016-04-25 18:47:53 +020035#include <osmocom/core/bit64gen.h>
36
Harald Welted284cd92010-03-01 21:58:31 +010037
Harald Welte8598f182011-08-17 14:19:27 +020038/*! \addtogroup utils
39 * @{
Neels Hofmeyr87e45502017-06-20 00:17:59 +020040 * various utility routines
Neels Hofmeyr17518fe2017-06-20 04:35:06 +020041 *
42 * \file utils.c */
Harald Welte8598f182011-08-17 14:19:27 +020043
Harald Welteb59f9352010-03-25 11:37:04 +080044static char namebuf[255];
Harald Welte8598f182011-08-17 14:19:27 +020045
Neels Hofmeyr87e45502017-06-20 00:17:59 +020046/*! get human-readable string for given value
Harald Welte8598f182011-08-17 14:19:27 +020047 * \param[in] vs Array of value_string tuples
48 * \param[in] val Value to be converted
49 * \returns pointer to human-readable string
Neels Hofmeyr8a3c83e2016-06-13 13:16:58 +020050 *
51 * If val is found in vs, the array's string entry is returned. Otherwise, an
52 * "unknown" string containing the actual value is composed in a static buffer
53 * that is reused across invocations.
Harald Welte8598f182011-08-17 14:19:27 +020054 */
Harald Welted284cd92010-03-01 21:58:31 +010055const char *get_value_string(const struct value_string *vs, uint32_t val)
56{
Neels Hofmeyr8d6dcd92016-06-06 18:05:23 +020057 const char *str = get_value_string_or_null(vs, val);
58 if (str)
59 return str;
60
Pau Espin Pedrol45735022017-06-18 14:05:24 +020061 snprintf(namebuf, sizeof(namebuf), "unknown 0x%"PRIx32, val);
Neels Hofmeyr8d6dcd92016-06-06 18:05:23 +020062 namebuf[sizeof(namebuf) - 1] = '\0';
63 return namebuf;
64}
65
Neels Hofmeyr87e45502017-06-20 00:17:59 +020066/*! get human-readable string or NULL for given value
Neels Hofmeyr8d6dcd92016-06-06 18:05:23 +020067 * \param[in] vs Array of value_string tuples
68 * \param[in] val Value to be converted
69 * \returns pointer to human-readable string or NULL if val is not found
70 */
71const char *get_value_string_or_null(const struct value_string *vs,
72 uint32_t val)
73{
Harald Welted284cd92010-03-01 21:58:31 +010074 int i;
75
76 for (i = 0;; i++) {
77 if (vs[i].value == 0 && vs[i].str == NULL)
78 break;
79 if (vs[i].value == val)
80 return vs[i].str;
81 }
Harald Welteb59f9352010-03-25 11:37:04 +080082
Neels Hofmeyr8d6dcd92016-06-06 18:05:23 +020083 return NULL;
Harald Welted284cd92010-03-01 21:58:31 +010084}
85
Neels Hofmeyr87e45502017-06-20 00:17:59 +020086/*! get numeric value for given human-readable string
Harald Welte8598f182011-08-17 14:19:27 +020087 * \param[in] vs Array of value_string tuples
88 * \param[in] str human-readable string
89 * \returns numeric value (>0) or negative numer in case of error
90 */
Harald Welted284cd92010-03-01 21:58:31 +010091int get_string_value(const struct value_string *vs, const char *str)
92{
93 int i;
94
95 for (i = 0;; i++) {
96 if (vs[i].value == 0 && vs[i].str == NULL)
97 break;
98 if (!strcasecmp(vs[i].str, str))
99 return vs[i].value;
100 }
101 return -EINVAL;
102}
Harald Weltea73e2f92010-03-04 10:50:32 +0100103
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200104/*! Convert BCD-encoded digit into printable character
Harald Welte8598f182011-08-17 14:19:27 +0200105 * \param[in] bcd A single BCD-encoded digit
106 * \returns single printable character
107 */
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200108char osmo_bcd2char(uint8_t bcd)
Harald Weltea73e2f92010-03-04 10:50:32 +0100109{
110 if (bcd < 0xa)
111 return '0' + bcd;
112 else
113 return 'A' + (bcd - 0xa);
114}
115
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200116/*! Convert number in ASCII to BCD value
Harald Weltede6e4982012-12-06 21:25:27 +0100117 * \param[in] c ASCII character
118 * \returns BCD encoded value of character
119 */
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200120uint8_t osmo_char2bcd(char c)
Harald Weltea73e2f92010-03-04 10:50:32 +0100121{
Harald Weltefa8983d2017-10-27 16:52:59 +0200122 if (c >= '0' && c <= '9')
123 return c - 0x30;
124 else if (c >= 'A' && c <= 'F')
125 return 0xa + (c - 'A');
126 else if (c >= 'a' && c <= 'f')
127 return 0xa + (c - 'a');
128 else
129 return 0;
Harald Weltea73e2f92010-03-04 10:50:32 +0100130}
Harald Welte3eba9912010-07-30 10:37:29 +0200131
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200132/*! Parse a string containing hexadecimal digits
Harald Weltede6e4982012-12-06 21:25:27 +0100133 * \param[in] str string containing ASCII encoded hexadecimal digits
134 * \param[out] b output buffer
135 * \param[in] max_len maximum space in output buffer
Neels Hofmeyr3de7b052015-09-23 23:16:53 +0200136 * \returns number of parsed octets, or -1 on error
Harald Weltede6e4982012-12-06 21:25:27 +0100137 */
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200138int osmo_hexparse(const char *str, uint8_t *b, int max_len)
Harald Welte3eba9912010-07-30 10:37:29 +0200139
140{
Neels Hofmeyr437ed4a2017-02-14 15:54:31 +0100141 char c;
142 uint8_t v;
143 const char *strpos;
144 unsigned int nibblepos = 0;
Harald Welte3eba9912010-07-30 10:37:29 +0200145
146 memset(b, 0x00, max_len);
147
Neels Hofmeyr437ed4a2017-02-14 15:54:31 +0100148 for (strpos = str; (c = *strpos); strpos++) {
149 /* skip whitespace */
150 if (c == ' ' || c == '\t' || c == '\n' || c == '\r')
151 continue;
152
153 /* If the buffer is too small, error out */
154 if (nibblepos >= (max_len << 1))
155 return -1;
156
Harald Welte3eba9912010-07-30 10:37:29 +0200157 if (c >= '0' && c <= '9')
158 v = c - '0';
159 else if (c >= 'a' && c <= 'f')
160 v = 10 + (c - 'a');
161 else if (c >= 'A' && c <= 'F')
162 v = 10 + (c - 'A');
163 else
164 return -1;
Neels Hofmeyr437ed4a2017-02-14 15:54:31 +0100165
166 b[nibblepos >> 1] |= v << (nibblepos & 1 ? 0 : 4);
167 nibblepos ++;
Harald Welte3eba9912010-07-30 10:37:29 +0200168 }
169
Neels Hofmeyr437ed4a2017-02-14 15:54:31 +0100170 /* In case of uneven amount of digits, the last byte is not complete
171 * and that's an error. */
172 if (nibblepos & 1)
173 return -1;
174
175 return nibblepos >> 1;
Harald Welte3eba9912010-07-30 10:37:29 +0200176}
Harald Welte40481e82010-07-30 11:40:32 +0200177
178static char hexd_buff[4096];
Nils O. SelÄsdal32447022014-01-02 14:04:43 +0100179static const char hex_chars[] = "0123456789abcdef";
Harald Welte40481e82010-07-30 11:40:32 +0200180
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200181static char *_osmo_hexdump(const unsigned char *buf, int len, char *delim)
Harald Welte40481e82010-07-30 11:40:32 +0200182{
183 int i;
184 char *cur = hexd_buff;
185
186 hexd_buff[0] = 0;
187 for (i = 0; i < len; i++) {
Nils O. SelÄsdal32447022014-01-02 14:04:43 +0100188 const char *delimp = delim;
Harald Welte40481e82010-07-30 11:40:32 +0200189 int len_remain = sizeof(hexd_buff) - (cur - hexd_buff);
Nils O. SelÄsdal32447022014-01-02 14:04:43 +0100190 if (len_remain < 3)
Holger Hans Peter Freyther128d9e22011-07-15 16:07:23 +0200191 break;
Nils O. SelÄsdal32447022014-01-02 14:04:43 +0100192
193 *cur++ = hex_chars[buf[i] >> 4];
194 *cur++ = hex_chars[buf[i] & 0xf];
195
196 while (len_remain > 1 && *delimp) {
197 *cur++ = *delimp++;
198 len_remain--;
199 }
200
201 *cur = 0;
Harald Welte40481e82010-07-30 11:40:32 +0200202 }
203 hexd_buff[sizeof(hexd_buff)-1] = 0;
204 return hexd_buff;
205}
Harald Weltedee47cd2010-07-30 11:43:30 +0200206
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200207/*! Convert a sequence of unpacked bits to ASCII string
Harald Welte8598f182011-08-17 14:19:27 +0200208 * \param[in] bits A sequence of unpacked bits
209 * \param[in] len Length of bits
210 */
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200211char *osmo_ubit_dump(const uint8_t *bits, unsigned int len)
Harald Welte3d0ac5e2011-02-08 16:55:03 +0100212{
213 int i;
214
215 if (len > sizeof(hexd_buff)-1)
216 len = sizeof(hexd_buff)-1;
217 memset(hexd_buff, 0, sizeof(hexd_buff));
218
219 for (i = 0; i < len; i++) {
220 char outch;
221 switch (bits[i]) {
222 case 0:
223 outch = '0';
224 break;
225 case 0xff:
226 outch = '?';
227 break;
228 case 1:
229 outch = '1';
230 break;
231 default:
232 outch = 'E';
233 break;
234 }
235 hexd_buff[i] = outch;
236 }
237 hexd_buff[sizeof(hexd_buff)-1] = 0;
238 return hexd_buff;
239}
240
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200241/*! Convert binary sequence to hexadecimal ASCII string
Harald Welte8598f182011-08-17 14:19:27 +0200242 * \param[in] buf pointer to sequence of bytes
243 * \param[in] len length of buf in number of bytes
244 * \returns pointer to zero-terminated string
245 *
246 * This function will print a sequence of bytes as hexadecimal numbers,
247 * adding one space character between each byte (e.g. "1a ef d9")
Harald Welte096a6662017-10-16 14:33:11 +0200248 *
249 * The maximum size of the output buffer is 4096 bytes, i.e. the maximum
250 * number of input bytes that can be printed in one call is 1365!
Harald Welte8598f182011-08-17 14:19:27 +0200251 */
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200252char *osmo_hexdump(const unsigned char *buf, int len)
Harald Weltedee47cd2010-07-30 11:43:30 +0200253{
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200254 return _osmo_hexdump(buf, len, " ");
Harald Weltedee47cd2010-07-30 11:43:30 +0200255}
256
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200257/*! Convert binary sequence to hexadecimal ASCII string
Harald Welte8598f182011-08-17 14:19:27 +0200258 * \param[in] buf pointer to sequence of bytes
259 * \param[in] len length of buf in number of bytes
260 * \returns pointer to zero-terminated string
261 *
262 * This function will print a sequence of bytes as hexadecimal numbers,
263 * without any space character between each byte (e.g. "1aefd9")
Harald Welte096a6662017-10-16 14:33:11 +0200264 *
265 * The maximum size of the output buffer is 4096 bytes, i.e. the maximum
266 * number of input bytes that can be printed in one call is 2048!
Harald Welte8598f182011-08-17 14:19:27 +0200267 */
Sylvain Munautff23d242011-11-10 23:03:18 +0100268char *osmo_hexdump_nospc(const unsigned char *buf, int len)
Harald Weltedee47cd2010-07-30 11:43:30 +0200269{
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200270 return _osmo_hexdump(buf, len, "");
Harald Weltedee47cd2010-07-30 11:43:30 +0200271}
Harald Welte28222962011-02-18 20:37:04 +0100272
Holger Hans Peter Freyther9a1a5a12015-04-11 19:26:55 +0200273/* Compat with previous typo to preserve abi */
Sylvain Munaute55ae3a2011-11-11 23:06:55 +0100274char *osmo_osmo_hexdump_nospc(const unsigned char *buf, int len)
Holger Hans Peter Freyther9a1a5a12015-04-11 19:26:55 +0200275#if defined(__MACH__) && defined(__APPLE__)
276 ;
277#else
Sylvain Munaut17af41d2011-11-19 22:30:39 +0100278 __attribute__((weak, alias("osmo_hexdump_nospc")));
Holger Hans Peter Freyther9a1a5a12015-04-11 19:26:55 +0200279#endif
Sylvain Munaute55ae3a2011-11-11 23:06:55 +0100280
Harald Welte28222962011-02-18 20:37:04 +0100281#include "../config.h"
282#ifdef HAVE_CTYPE_H
283#include <ctype.h>
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200284/*! Convert an entire string to lower case
Harald Welte8598f182011-08-17 14:19:27 +0200285 * \param[out] out output string, caller-allocated
286 * \param[in] in input string
287 */
Harald Welte28222962011-02-18 20:37:04 +0100288void osmo_str2lower(char *out, const char *in)
289{
290 unsigned int i;
291
292 for (i = 0; i < strlen(in); i++)
Pau Espin Pedrol399a6f02017-06-18 14:07:37 +0200293 out[i] = tolower((const unsigned char)in[i]);
Harald Welte28222962011-02-18 20:37:04 +0100294 out[strlen(in)] = '\0';
295}
296
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200297/*! Convert an entire string to upper case
Harald Welte8598f182011-08-17 14:19:27 +0200298 * \param[out] out output string, caller-allocated
299 * \param[in] in input string
300 */
Harald Welte28222962011-02-18 20:37:04 +0100301void osmo_str2upper(char *out, const char *in)
302{
303 unsigned int i;
304
305 for (i = 0; i < strlen(in); i++)
Pau Espin Pedrol399a6f02017-06-18 14:07:37 +0200306 out[i] = toupper((const unsigned char)in[i]);
Harald Welte28222962011-02-18 20:37:04 +0100307 out[strlen(in)] = '\0';
308}
309#endif /* HAVE_CTYPE_H */
Harald Welte8598f182011-08-17 14:19:27 +0200310
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200311/*! Wishful thinking to generate a constant time compare
Harald Welte9709b2e2016-04-25 18:47:53 +0200312 * \param[in] exp Expected data
313 * \param[in] rel Comparison value
314 * \param[in] count Number of bytes to compare
315 * \returns 1 in case \a exp equals \a rel; zero otherwise
316 *
317 * Compare count bytes of exp to rel. Return 0 if they are identical, 1
318 * otherwise. Do not return a mismatch on the first mismatching byte,
319 * but always compare all bytes, regardless. The idea is that the amount of
320 * matching bytes cannot be inferred from the time the comparison took. */
321int osmo_constant_time_cmp(const uint8_t *exp, const uint8_t *rel, const int count)
322{
323 int x = 0, i;
324
325 for (i = 0; i < count; ++i)
326 x |= exp[i] ^ rel[i];
327
328 /* if x is zero, all data was identical */
329 return x? 1 : 0;
330}
331
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200332/*! Generic retrieval of 1..8 bytes as big-endian uint64_t
Harald Welte9709b2e2016-04-25 18:47:53 +0200333 * \param[in] data Input data as byte-array
334 * \param[in] data_len Length of \a data in octets
335 * \returns uint64_t of \a data interpreted as big-endian
336 *
337 * This is like osmo_load64be_ext, except that if data_len is less than
338 * sizeof(uint64_t), the data is interpreted as the least significant bytes
339 * (osmo_load64be_ext loads them as the most significant bytes into the
340 * returned uint64_t). In this way, any integer size up to 64 bits can be
341 * decoded conveniently by using sizeof(), without the need to call specific
342 * numbered functions (osmo_load16, 32, ...). */
343uint64_t osmo_decode_big_endian(const uint8_t *data, size_t data_len)
344{
345 uint64_t value = 0;
346
347 while (data_len > 0) {
348 value = (value << 8) + *data;
349 data += 1;
350 data_len -= 1;
351 }
352
353 return value;
354}
355
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200356/*! Generic big-endian encoding of big endian number up to 64bit
Harald Welte9709b2e2016-04-25 18:47:53 +0200357 * \param[in] value unsigned integer value to be stored
358 * \param[in] data_len number of octets
359 * \returns static buffer containing big-endian stored value
360 *
361 * This is like osmo_store64be_ext, except that this returns a static buffer of
362 * the result (for convenience, but not threadsafe). If data_len is less than
363 * sizeof(uint64_t), only the least significant bytes of value are encoded. */
364uint8_t *osmo_encode_big_endian(uint64_t value, size_t data_len)
365{
366 static uint8_t buf[sizeof(uint64_t)];
367 OSMO_ASSERT(data_len <= ARRAY_SIZE(buf));
368 osmo_store64be_ext(value, buf, data_len);
369 return buf;
370}
Harald Welteaeecc482016-11-26 10:41:40 +0100371
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200372/*! Copy a C-string into a sized buffer
Harald Welteaeecc482016-11-26 10:41:40 +0100373 * \param[in] src source string
374 * \param[out] dst destination string
Neels Hofmeyrdf83ece2017-01-13 13:55:43 +0100375 * \param[in] siz size of the \a dst buffer
376 * \returns length of \a src
Harald Welteaeecc482016-11-26 10:41:40 +0100377 *
Neels Hofmeyrdf83ece2017-01-13 13:55:43 +0100378 * Copy at most \a siz bytes from \a src to \a dst, ensuring that the result is
379 * NUL terminated. The NUL character is included in \a siz, i.e. passing the
380 * actual sizeof(*dst) is correct.
Harald Welteaeecc482016-11-26 10:41:40 +0100381 */
382size_t osmo_strlcpy(char *dst, const char *src, size_t siz)
383{
Neels Hofmeyrbcf9f232017-10-25 04:16:45 +0200384 size_t ret = src ? strlen(src) : 0;
Harald Welteaeecc482016-11-26 10:41:40 +0100385
386 if (siz) {
387 size_t len = (ret >= siz) ? siz - 1 : ret;
Neels Hofmeyrebd3cdd2017-11-18 23:07:38 +0100388 if (src)
389 memcpy(dst, src, len);
Harald Welteaeecc482016-11-26 10:41:40 +0100390 dst[len] = '\0';
391 }
392 return ret;
393}
Neels Hofmeyr0aeda1b2017-01-13 14:16:02 +0100394
Neels Hofmeyr4335bad2017-10-07 04:39:14 +0200395/*! Validate that a given string is a hex string within given size limits.
396 * Note that each hex digit amounts to a nibble, so if checking for a hex
397 * string to result in N bytes, pass amount of digits as 2*N.
398 * \param str A nul-terminated string to validate, or NULL.
399 * \param min_digits least permitted amount of digits.
400 * \param max_digits most permitted amount of digits.
401 * \param require_even if true, require an even amount of digits.
402 * \returns true when the hex_str contains only hexadecimal digits (no
403 * whitespace) and matches the requested length; also true
404 * when min_digits <= 0 and str is NULL.
405 */
406bool osmo_is_hexstr(const char *str, int min_digits, int max_digits,
407 bool require_even)
408{
409 int len;
410 /* Use unsigned char * to avoid a compiler warning of
411 * "error: array subscript has type 'char' [-Werror=char-subscripts]" */
412 const unsigned char *pos = (const unsigned char*)str;
413 if (!pos)
414 return min_digits < 1;
415 for (len = 0; *pos && len < max_digits; len++, pos++)
416 if (!isxdigit(*pos))
417 return false;
418 if (len < min_digits)
419 return false;
420 /* With not too many digits, we should have reached *str == nul */
421 if (*pos)
422 return false;
423 if (require_even && (len & 1))
424 return false;
Harald Weltefebe83c2017-10-03 17:41:59 +0800425
426 return true;
427}
428
429/*! Determine if a given identifier is valid, i.e. doesn't contain illegal chars
430 * \param[in] str String to validate
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100431 * \param[in] sep_chars Permitted separation characters between identifiers.
432 * \returns true in case \a str contains only valid identifiers and sep_chars, false otherwise
Harald Weltefebe83c2017-10-03 17:41:59 +0800433 */
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100434bool osmo_separated_identifiers_valid(const char *str, const char *sep_chars)
Harald Weltefebe83c2017-10-03 17:41:59 +0800435{
436 /* characters that are illegal in names */
437 static const char illegal_chars[] = "., {}[]()<>|~\\^`'\"?=;/+*&%$#!";
438 unsigned int i;
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100439 size_t len;
Harald Weltefebe83c2017-10-03 17:41:59 +0800440
441 /* an empty string is not a valid identifier */
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100442 if (!str || (len = strlen(str)) == 0)
Harald Weltefebe83c2017-10-03 17:41:59 +0800443 return false;
444
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100445 for (i = 0; i < len; i++) {
446 if (sep_chars && strchr(sep_chars, str[i]))
447 continue;
Harald Weltefebe83c2017-10-03 17:41:59 +0800448 /* check for 7-bit ASCII */
449 if (str[i] & 0x80)
450 return false;
Neels Hofmeyre5a2bdb2017-12-16 04:54:37 +0100451 if (!isprint((int)str[i]))
452 return false;
Harald Weltefebe83c2017-10-03 17:41:59 +0800453 /* check for some explicit reserved control characters */
454 if (strchr(illegal_chars, str[i]))
455 return false;
456 }
457
Neels Hofmeyr4335bad2017-10-07 04:39:14 +0200458 return true;
459}
460
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100461/*! Determine if a given identifier is valid, i.e. doesn't contain illegal chars
462 * \param[in] str String to validate
463 * \returns true in case \a str contains valid identifier, false otherwise
464 */
465bool osmo_identifier_valid(const char *str)
466{
467 return osmo_separated_identifiers_valid(str, NULL);
468}
469
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100470/*! Return the string with all non-printable characters escaped.
471 * \param[in] str A string that may contain any characters.
472 * \param[in] len Pass -1 to print until nul char, or >= 0 to force a length.
473 * \param[inout] buf string buffer to write escaped characters to.
474 * \param[in] bufsize size of \a buf.
475 * \returns buf containing an escaped representation, possibly truncated, or str itself.
476 */
477const char *osmo_escape_str_buf(const char *str, int in_len, char *buf, size_t bufsize)
478{
479 int in_pos = 0;
480 int next_unprintable = 0;
481 int out_pos = 0;
482 char *out = buf;
483 /* -1 to leave space for a final \0 */
484 int out_len = bufsize-1;
485
486 if (!str)
487 return "(null)";
488
489 if (in_len < 0)
490 in_len = strlen(str);
491
492 while (in_pos < in_len) {
493 for (next_unprintable = in_pos;
494 next_unprintable < in_len && isprint((int)str[next_unprintable])
495 && str[next_unprintable] != '"'
496 && str[next_unprintable] != '\\';
497 next_unprintable++);
498
499 if (next_unprintable == in_len
500 && in_pos == 0)
501 return str;
502
503 while (in_pos < next_unprintable && out_pos < out_len)
504 out[out_pos++] = str[in_pos++];
505
506 if (out_pos == out_len || in_pos == in_len)
507 goto done;
508
509 switch (str[next_unprintable]) {
510#define BACKSLASH_CASE(c, repr) \
511 case c: \
512 if (out_pos > out_len-2) \
513 goto done; \
514 out[out_pos++] = '\\'; \
515 out[out_pos++] = repr; \
516 break
517
518 BACKSLASH_CASE('\n', 'n');
519 BACKSLASH_CASE('\r', 'r');
520 BACKSLASH_CASE('\t', 't');
521 BACKSLASH_CASE('\0', '0');
522 BACKSLASH_CASE('\a', 'a');
523 BACKSLASH_CASE('\b', 'b');
524 BACKSLASH_CASE('\v', 'v');
525 BACKSLASH_CASE('\f', 'f');
526 BACKSLASH_CASE('\\', '\\');
527 BACKSLASH_CASE('"', '"');
528#undef BACKSLASH_CASE
529
530 default:
531 out_pos += snprintf(&out[out_pos], out_len - out_pos, "\\%u", (unsigned char)str[in_pos]);
532 if (out_pos > out_len) {
533 out_pos = out_len;
534 goto done;
535 }
536 break;
537 }
538 in_pos ++;
539 }
540
541done:
542 out[out_pos] = '\0';
543 return out;
544}
545
546/*! Return the string with all non-printable characters escaped.
547 * Call osmo_escape_str_buf() with a static buffer.
548 * \param[in] str A string that may contain any characters.
549 * \param[in] len Pass -1 to print until nul char, or >= 0 to force a length.
550 * \returns buf containing an escaped representation, possibly truncated, or str itself.
551 */
552const char *osmo_escape_str(const char *str, int in_len)
553{
554 return osmo_escape_str_buf(str, in_len, namebuf, sizeof(namebuf));
555}
556
Neels Hofmeyr04eb56f2018-04-09 00:41:28 +0200557/*! Like osmo_escape_str(), but returns double-quotes around a string, or "NULL" for a NULL string.
558 * This allows passing any char* value and get its C representation as string.
559 * \param[in] str A string that may contain any characters.
560 * \param[in] len Pass -1 to print until nul char, or >= 0 to force a length.
561 * \returns buf containing an escaped representation, possibly truncated, or str itself.
562 */
563const char *osmo_quote_str_buf(const char *str, int in_len, char *buf, size_t bufsize)
564{
565 const char *res;
566 int l;
567 if (!str)
568 return "NULL";
569 if (bufsize < 3)
570 return "<buf-too-small>";
571 buf[0] = '"';
572 res = osmo_escape_str_buf(str, in_len, buf + 1, bufsize - 2);
573 /* if osmo_escape_str_buf() returned the str itself, we need to copy it to buf to be able to
574 * quote it. */
575 if (res == str) {
576 /* max_len = bufsize - two quotes - nul term */
577 int max_len = bufsize - 2 - 1;
578 if (in_len >= 0)
579 max_len = OSMO_MIN(in_len, max_len);
580 /* It is not allowed to pass unterminated strings into osmo_strlcpy() :/ */
581 strncpy(buf + 1, str, max_len);
582 buf[1 + max_len] = '\0';
583 }
584 l = strlen(buf);
585 buf[l] = '"';
586 buf[l+1] = '\0'; /* both osmo_escape_str_buf() and max_len above ensure room for '\0' */
587 return buf;
588}
589
590const char *osmo_quote_str(const char *str, int in_len)
591{
592 return osmo_quote_str_buf(str, in_len, namebuf, sizeof(namebuf));
593}
594
Harald Welte15a5f8d2018-06-06 16:58:17 +0200595/*! perform an integer square root operation on unsigned 32bit integer.
596 * This implementation is taken from "Hacker's Delight" Figure 11-1 "Integer square root, Newton's
597 * method", which can also be found at http://www.hackersdelight.org/hdcodetxt/isqrt.c.txt */
598uint32_t osmo_isqrt32(uint32_t x)
599{
600 uint32_t x1;
601 int s, g0, g1;
602
603 if (x <= 1)
604 return x;
605
606 s = 1;
607 x1 = x - 1;
608 if (x1 > 0xffff) {
609 s = s + 8;
610 x1 = x1 >> 16;
611 }
612 if (x1 > 0xff) {
613 s = s + 4;
614 x1 = x1 >> 8;
615 }
616 if (x1 > 0xf) {
617 s = s + 2;
618 x1 = x1 >> 4;
619 }
620 if (x1 > 0x3) {
621 s = s + 1;
622 }
623
624 g0 = 1 << s; /* g0 = 2**s */
625 g1 = (g0 + (x >> s)) >> 1; /* g1 = (g0 + x/g0)/2 */
626
627 /* converges after four to five divisions for arguments up to 16,785,407 */
628 while (g1 < g0) {
629 g0 = g1;
630 g1 = (g0 + (x/g0)) >> 1;
631 }
632 return g0;
633}
634
Neels Hofmeyr0aeda1b2017-01-13 14:16:02 +0100635/*! @} */