blob: f63ff891dcaa2663ba4fabde042fceec11a75ce4 [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;
388 memcpy(dst, src, len);
389 dst[len] = '\0';
390 }
391 return ret;
392}
Neels Hofmeyr0aeda1b2017-01-13 14:16:02 +0100393
Neels Hofmeyr4335bad2017-10-07 04:39:14 +0200394/*! Validate that a given string is a hex string within given size limits.
395 * Note that each hex digit amounts to a nibble, so if checking for a hex
396 * string to result in N bytes, pass amount of digits as 2*N.
397 * \param str A nul-terminated string to validate, or NULL.
398 * \param min_digits least permitted amount of digits.
399 * \param max_digits most permitted amount of digits.
400 * \param require_even if true, require an even amount of digits.
401 * \returns true when the hex_str contains only hexadecimal digits (no
402 * whitespace) and matches the requested length; also true
403 * when min_digits <= 0 and str is NULL.
404 */
405bool osmo_is_hexstr(const char *str, int min_digits, int max_digits,
406 bool require_even)
407{
408 int len;
409 /* Use unsigned char * to avoid a compiler warning of
410 * "error: array subscript has type 'char' [-Werror=char-subscripts]" */
411 const unsigned char *pos = (const unsigned char*)str;
412 if (!pos)
413 return min_digits < 1;
414 for (len = 0; *pos && len < max_digits; len++, pos++)
415 if (!isxdigit(*pos))
416 return false;
417 if (len < min_digits)
418 return false;
419 /* With not too many digits, we should have reached *str == nul */
420 if (*pos)
421 return false;
422 if (require_even && (len & 1))
423 return false;
Harald Weltefebe83c2017-10-03 17:41:59 +0800424
425 return true;
426}
427
428/*! Determine if a given identifier is valid, i.e. doesn't contain illegal chars
429 * \param[in] str String to validate
430 * \returns true in case string contains valid identifier, false otherwise
431 */
432bool osmo_identifier_valid(const char *str)
433{
434 /* characters that are illegal in names */
435 static const char illegal_chars[] = "., {}[]()<>|~\\^`'\"?=;/+*&%$#!";
436 unsigned int i;
437
438 /* an empty string is not a valid identifier */
439 if (!str || strlen(str) == 0)
440 return false;
441
442 for (i = 0; i < strlen(str); i++) {
443 /* check for 7-bit ASCII */
444 if (str[i] & 0x80)
445 return false;
446 /* check for some explicit reserved control characters */
447 if (strchr(illegal_chars, str[i]))
448 return false;
449 }
450
Neels Hofmeyr4335bad2017-10-07 04:39:14 +0200451 return true;
452}
453
Neels Hofmeyr0aeda1b2017-01-13 14:16:02 +0100454/*! @} */