blob: ef8e916eece6c06f15d1f7780123b51dcc9c9860 [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 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 *
22 */
23
Harald Welted284cd92010-03-01 21:58:31 +010024
Harald Weltefebe83c2017-10-03 17:41:59 +080025#include <stdbool.h>
Harald Welted284cd92010-03-01 21:58:31 +010026#include <string.h>
27#include <stdint.h>
28#include <errno.h>
Harald Welteb59f9352010-03-25 11:37:04 +080029#include <stdio.h>
Pau Espin Pedrol45735022017-06-18 14:05:24 +020030#include <inttypes.h>
Harald Welted284cd92010-03-01 21:58:31 +010031
Pablo Neira Ayuso83419342011-03-22 16:36:13 +010032#include <osmocom/core/utils.h>
Harald Welte9709b2e2016-04-25 18:47:53 +020033#include <osmocom/core/bit64gen.h>
34
Harald Welted284cd92010-03-01 21:58:31 +010035
Harald Welte8598f182011-08-17 14:19:27 +020036/*! \addtogroup utils
37 * @{
Neels Hofmeyr87e45502017-06-20 00:17:59 +020038 * various utility routines
Neels Hofmeyr17518fe2017-06-20 04:35:06 +020039 *
40 * \file utils.c */
Harald Welte8598f182011-08-17 14:19:27 +020041
Harald Welteb59f9352010-03-25 11:37:04 +080042static char namebuf[255];
Harald Welte8598f182011-08-17 14:19:27 +020043
Neels Hofmeyr87e45502017-06-20 00:17:59 +020044/*! get human-readable string for given value
Harald Welte8598f182011-08-17 14:19:27 +020045 * \param[in] vs Array of value_string tuples
46 * \param[in] val Value to be converted
47 * \returns pointer to human-readable string
Neels Hofmeyr8a3c83e2016-06-13 13:16:58 +020048 *
49 * If val is found in vs, the array's string entry is returned. Otherwise, an
50 * "unknown" string containing the actual value is composed in a static buffer
51 * that is reused across invocations.
Harald Welte8598f182011-08-17 14:19:27 +020052 */
Harald Welted284cd92010-03-01 21:58:31 +010053const char *get_value_string(const struct value_string *vs, uint32_t val)
54{
Neels Hofmeyr8d6dcd92016-06-06 18:05:23 +020055 const char *str = get_value_string_or_null(vs, val);
56 if (str)
57 return str;
58
Pau Espin Pedrol45735022017-06-18 14:05:24 +020059 snprintf(namebuf, sizeof(namebuf), "unknown 0x%"PRIx32, val);
Neels Hofmeyr8d6dcd92016-06-06 18:05:23 +020060 namebuf[sizeof(namebuf) - 1] = '\0';
61 return namebuf;
62}
63
Neels Hofmeyr87e45502017-06-20 00:17:59 +020064/*! get human-readable string or NULL for given value
Neels Hofmeyr8d6dcd92016-06-06 18:05:23 +020065 * \param[in] vs Array of value_string tuples
66 * \param[in] val Value to be converted
67 * \returns pointer to human-readable string or NULL if val is not found
68 */
69const char *get_value_string_or_null(const struct value_string *vs,
70 uint32_t val)
71{
Harald Welted284cd92010-03-01 21:58:31 +010072 int i;
73
74 for (i = 0;; i++) {
75 if (vs[i].value == 0 && vs[i].str == NULL)
76 break;
77 if (vs[i].value == val)
78 return vs[i].str;
79 }
Harald Welteb59f9352010-03-25 11:37:04 +080080
Neels Hofmeyr8d6dcd92016-06-06 18:05:23 +020081 return NULL;
Harald Welted284cd92010-03-01 21:58:31 +010082}
83
Neels Hofmeyr87e45502017-06-20 00:17:59 +020084/*! get numeric value for given human-readable string
Harald Welte8598f182011-08-17 14:19:27 +020085 * \param[in] vs Array of value_string tuples
86 * \param[in] str human-readable string
87 * \returns numeric value (>0) or negative numer in case of error
88 */
Harald Welted284cd92010-03-01 21:58:31 +010089int get_string_value(const struct value_string *vs, const char *str)
90{
91 int i;
92
93 for (i = 0;; i++) {
94 if (vs[i].value == 0 && vs[i].str == NULL)
95 break;
96 if (!strcasecmp(vs[i].str, str))
97 return vs[i].value;
98 }
99 return -EINVAL;
100}
Harald Weltea73e2f92010-03-04 10:50:32 +0100101
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200102/*! Convert BCD-encoded digit into printable character
Harald Welte8598f182011-08-17 14:19:27 +0200103 * \param[in] bcd A single BCD-encoded digit
104 * \returns single printable character
105 */
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200106char osmo_bcd2char(uint8_t bcd)
Harald Weltea73e2f92010-03-04 10:50:32 +0100107{
108 if (bcd < 0xa)
109 return '0' + bcd;
110 else
111 return 'A' + (bcd - 0xa);
112}
113
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200114/*! Convert number in ASCII to BCD value
Harald Weltede6e4982012-12-06 21:25:27 +0100115 * \param[in] c ASCII character
116 * \returns BCD encoded value of character
117 */
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200118uint8_t osmo_char2bcd(char c)
Harald Weltea73e2f92010-03-04 10:50:32 +0100119{
120 return c - 0x30;
121}
Harald Welte3eba9912010-07-30 10:37:29 +0200122
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200123/*! Parse a string containing hexadecimal digits
Harald Weltede6e4982012-12-06 21:25:27 +0100124 * \param[in] str string containing ASCII encoded hexadecimal digits
125 * \param[out] b output buffer
126 * \param[in] max_len maximum space in output buffer
Neels Hofmeyr3de7b052015-09-23 23:16:53 +0200127 * \returns number of parsed octets, or -1 on error
Harald Weltede6e4982012-12-06 21:25:27 +0100128 */
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200129int osmo_hexparse(const char *str, uint8_t *b, int max_len)
Harald Welte3eba9912010-07-30 10:37:29 +0200130
131{
Neels Hofmeyr437ed4a2017-02-14 15:54:31 +0100132 char c;
133 uint8_t v;
134 const char *strpos;
135 unsigned int nibblepos = 0;
Harald Welte3eba9912010-07-30 10:37:29 +0200136
137 memset(b, 0x00, max_len);
138
Neels Hofmeyr437ed4a2017-02-14 15:54:31 +0100139 for (strpos = str; (c = *strpos); strpos++) {
140 /* skip whitespace */
141 if (c == ' ' || c == '\t' || c == '\n' || c == '\r')
142 continue;
143
144 /* If the buffer is too small, error out */
145 if (nibblepos >= (max_len << 1))
146 return -1;
147
Harald Welte3eba9912010-07-30 10:37:29 +0200148 if (c >= '0' && c <= '9')
149 v = c - '0';
150 else if (c >= 'a' && c <= 'f')
151 v = 10 + (c - 'a');
152 else if (c >= 'A' && c <= 'F')
153 v = 10 + (c - 'A');
154 else
155 return -1;
Neels Hofmeyr437ed4a2017-02-14 15:54:31 +0100156
157 b[nibblepos >> 1] |= v << (nibblepos & 1 ? 0 : 4);
158 nibblepos ++;
Harald Welte3eba9912010-07-30 10:37:29 +0200159 }
160
Neels Hofmeyr437ed4a2017-02-14 15:54:31 +0100161 /* In case of uneven amount of digits, the last byte is not complete
162 * and that's an error. */
163 if (nibblepos & 1)
164 return -1;
165
166 return nibblepos >> 1;
Harald Welte3eba9912010-07-30 10:37:29 +0200167}
Harald Welte40481e82010-07-30 11:40:32 +0200168
169static char hexd_buff[4096];
Nils O. SelÄsdal32447022014-01-02 14:04:43 +0100170static const char hex_chars[] = "0123456789abcdef";
Harald Welte40481e82010-07-30 11:40:32 +0200171
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200172static char *_osmo_hexdump(const unsigned char *buf, int len, char *delim)
Harald Welte40481e82010-07-30 11:40:32 +0200173{
174 int i;
175 char *cur = hexd_buff;
176
177 hexd_buff[0] = 0;
178 for (i = 0; i < len; i++) {
Nils O. SelÄsdal32447022014-01-02 14:04:43 +0100179 const char *delimp = delim;
Harald Welte40481e82010-07-30 11:40:32 +0200180 int len_remain = sizeof(hexd_buff) - (cur - hexd_buff);
Nils O. SelÄsdal32447022014-01-02 14:04:43 +0100181 if (len_remain < 3)
Holger Hans Peter Freyther128d9e22011-07-15 16:07:23 +0200182 break;
Nils O. SelÄsdal32447022014-01-02 14:04:43 +0100183
184 *cur++ = hex_chars[buf[i] >> 4];
185 *cur++ = hex_chars[buf[i] & 0xf];
186
187 while (len_remain > 1 && *delimp) {
188 *cur++ = *delimp++;
189 len_remain--;
190 }
191
192 *cur = 0;
Harald Welte40481e82010-07-30 11:40:32 +0200193 }
194 hexd_buff[sizeof(hexd_buff)-1] = 0;
195 return hexd_buff;
196}
Harald Weltedee47cd2010-07-30 11:43:30 +0200197
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200198/*! Convert a sequence of unpacked bits to ASCII string
Harald Welte8598f182011-08-17 14:19:27 +0200199 * \param[in] bits A sequence of unpacked bits
200 * \param[in] len Length of bits
201 */
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200202char *osmo_ubit_dump(const uint8_t *bits, unsigned int len)
Harald Welte3d0ac5e2011-02-08 16:55:03 +0100203{
204 int i;
205
206 if (len > sizeof(hexd_buff)-1)
207 len = sizeof(hexd_buff)-1;
208 memset(hexd_buff, 0, sizeof(hexd_buff));
209
210 for (i = 0; i < len; i++) {
211 char outch;
212 switch (bits[i]) {
213 case 0:
214 outch = '0';
215 break;
216 case 0xff:
217 outch = '?';
218 break;
219 case 1:
220 outch = '1';
221 break;
222 default:
223 outch = 'E';
224 break;
225 }
226 hexd_buff[i] = outch;
227 }
228 hexd_buff[sizeof(hexd_buff)-1] = 0;
229 return hexd_buff;
230}
231
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200232/*! Convert binary sequence to hexadecimal ASCII string
Harald Welte8598f182011-08-17 14:19:27 +0200233 * \param[in] buf pointer to sequence of bytes
234 * \param[in] len length of buf in number of bytes
235 * \returns pointer to zero-terminated string
236 *
237 * This function will print a sequence of bytes as hexadecimal numbers,
238 * adding one space character between each byte (e.g. "1a ef d9")
Harald Welte096a6662017-10-16 14:33:11 +0200239 *
240 * The maximum size of the output buffer is 4096 bytes, i.e. the maximum
241 * number of input bytes that can be printed in one call is 1365!
Harald Welte8598f182011-08-17 14:19:27 +0200242 */
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200243char *osmo_hexdump(const unsigned char *buf, int len)
Harald Weltedee47cd2010-07-30 11:43:30 +0200244{
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200245 return _osmo_hexdump(buf, len, " ");
Harald Weltedee47cd2010-07-30 11:43:30 +0200246}
247
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200248/*! Convert binary sequence to hexadecimal ASCII string
Harald Welte8598f182011-08-17 14:19:27 +0200249 * \param[in] buf pointer to sequence of bytes
250 * \param[in] len length of buf in number of bytes
251 * \returns pointer to zero-terminated string
252 *
253 * This function will print a sequence of bytes as hexadecimal numbers,
254 * without any space character between each byte (e.g. "1aefd9")
Harald Welte096a6662017-10-16 14:33:11 +0200255 *
256 * The maximum size of the output buffer is 4096 bytes, i.e. the maximum
257 * number of input bytes that can be printed in one call is 2048!
Harald Welte8598f182011-08-17 14:19:27 +0200258 */
Sylvain Munautff23d242011-11-10 23:03:18 +0100259char *osmo_hexdump_nospc(const unsigned char *buf, int len)
Harald Weltedee47cd2010-07-30 11:43:30 +0200260{
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200261 return _osmo_hexdump(buf, len, "");
Harald Weltedee47cd2010-07-30 11:43:30 +0200262}
Harald Welte28222962011-02-18 20:37:04 +0100263
Holger Hans Peter Freyther9a1a5a12015-04-11 19:26:55 +0200264/* Compat with previous typo to preserve abi */
Sylvain Munaute55ae3a2011-11-11 23:06:55 +0100265char *osmo_osmo_hexdump_nospc(const unsigned char *buf, int len)
Holger Hans Peter Freyther9a1a5a12015-04-11 19:26:55 +0200266#if defined(__MACH__) && defined(__APPLE__)
267 ;
268#else
Sylvain Munaut17af41d2011-11-19 22:30:39 +0100269 __attribute__((weak, alias("osmo_hexdump_nospc")));
Holger Hans Peter Freyther9a1a5a12015-04-11 19:26:55 +0200270#endif
Sylvain Munaute55ae3a2011-11-11 23:06:55 +0100271
Harald Welte28222962011-02-18 20:37:04 +0100272#include "../config.h"
273#ifdef HAVE_CTYPE_H
274#include <ctype.h>
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200275/*! Convert an entire string to lower case
Harald Welte8598f182011-08-17 14:19:27 +0200276 * \param[out] out output string, caller-allocated
277 * \param[in] in input string
278 */
Harald Welte28222962011-02-18 20:37:04 +0100279void osmo_str2lower(char *out, const char *in)
280{
281 unsigned int i;
282
283 for (i = 0; i < strlen(in); i++)
Pau Espin Pedrol399a6f02017-06-18 14:07:37 +0200284 out[i] = tolower((const unsigned char)in[i]);
Harald Welte28222962011-02-18 20:37:04 +0100285 out[strlen(in)] = '\0';
286}
287
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200288/*! Convert an entire string to upper case
Harald Welte8598f182011-08-17 14:19:27 +0200289 * \param[out] out output string, caller-allocated
290 * \param[in] in input string
291 */
Harald Welte28222962011-02-18 20:37:04 +0100292void osmo_str2upper(char *out, const char *in)
293{
294 unsigned int i;
295
296 for (i = 0; i < strlen(in); i++)
Pau Espin Pedrol399a6f02017-06-18 14:07:37 +0200297 out[i] = toupper((const unsigned char)in[i]);
Harald Welte28222962011-02-18 20:37:04 +0100298 out[strlen(in)] = '\0';
299}
300#endif /* HAVE_CTYPE_H */
Harald Welte8598f182011-08-17 14:19:27 +0200301
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200302/*! Wishful thinking to generate a constant time compare
Harald Welte9709b2e2016-04-25 18:47:53 +0200303 * \param[in] exp Expected data
304 * \param[in] rel Comparison value
305 * \param[in] count Number of bytes to compare
306 * \returns 1 in case \a exp equals \a rel; zero otherwise
307 *
308 * Compare count bytes of exp to rel. Return 0 if they are identical, 1
309 * otherwise. Do not return a mismatch on the first mismatching byte,
310 * but always compare all bytes, regardless. The idea is that the amount of
311 * matching bytes cannot be inferred from the time the comparison took. */
312int osmo_constant_time_cmp(const uint8_t *exp, const uint8_t *rel, const int count)
313{
314 int x = 0, i;
315
316 for (i = 0; i < count; ++i)
317 x |= exp[i] ^ rel[i];
318
319 /* if x is zero, all data was identical */
320 return x? 1 : 0;
321}
322
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200323/*! Generic retrieval of 1..8 bytes as big-endian uint64_t
Harald Welte9709b2e2016-04-25 18:47:53 +0200324 * \param[in] data Input data as byte-array
325 * \param[in] data_len Length of \a data in octets
326 * \returns uint64_t of \a data interpreted as big-endian
327 *
328 * This is like osmo_load64be_ext, except that if data_len is less than
329 * sizeof(uint64_t), the data is interpreted as the least significant bytes
330 * (osmo_load64be_ext loads them as the most significant bytes into the
331 * returned uint64_t). In this way, any integer size up to 64 bits can be
332 * decoded conveniently by using sizeof(), without the need to call specific
333 * numbered functions (osmo_load16, 32, ...). */
334uint64_t osmo_decode_big_endian(const uint8_t *data, size_t data_len)
335{
336 uint64_t value = 0;
337
338 while (data_len > 0) {
339 value = (value << 8) + *data;
340 data += 1;
341 data_len -= 1;
342 }
343
344 return value;
345}
346
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200347/*! Generic big-endian encoding of big endian number up to 64bit
Harald Welte9709b2e2016-04-25 18:47:53 +0200348 * \param[in] value unsigned integer value to be stored
349 * \param[in] data_len number of octets
350 * \returns static buffer containing big-endian stored value
351 *
352 * This is like osmo_store64be_ext, except that this returns a static buffer of
353 * the result (for convenience, but not threadsafe). If data_len is less than
354 * sizeof(uint64_t), only the least significant bytes of value are encoded. */
355uint8_t *osmo_encode_big_endian(uint64_t value, size_t data_len)
356{
357 static uint8_t buf[sizeof(uint64_t)];
358 OSMO_ASSERT(data_len <= ARRAY_SIZE(buf));
359 osmo_store64be_ext(value, buf, data_len);
360 return buf;
361}
Harald Welteaeecc482016-11-26 10:41:40 +0100362
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200363/*! Copy a C-string into a sized buffer
Harald Welteaeecc482016-11-26 10:41:40 +0100364 * \param[in] src source string
365 * \param[out] dst destination string
Neels Hofmeyrdf83ece2017-01-13 13:55:43 +0100366 * \param[in] siz size of the \a dst buffer
367 * \returns length of \a src
Harald Welteaeecc482016-11-26 10:41:40 +0100368 *
Neels Hofmeyrdf83ece2017-01-13 13:55:43 +0100369 * Copy at most \a siz bytes from \a src to \a dst, ensuring that the result is
370 * NUL terminated. The NUL character is included in \a siz, i.e. passing the
371 * actual sizeof(*dst) is correct.
Harald Welteaeecc482016-11-26 10:41:40 +0100372 */
373size_t osmo_strlcpy(char *dst, const char *src, size_t siz)
374{
375 size_t ret = strlen(src);
376
377 if (siz) {
378 size_t len = (ret >= siz) ? siz - 1 : ret;
379 memcpy(dst, src, len);
380 dst[len] = '\0';
381 }
382 return ret;
383}
Neels Hofmeyr0aeda1b2017-01-13 14:16:02 +0100384
Neels Hofmeyr4335bad2017-10-07 04:39:14 +0200385/*! Validate that a given string is a hex string within given size limits.
386 * Note that each hex digit amounts to a nibble, so if checking for a hex
387 * string to result in N bytes, pass amount of digits as 2*N.
388 * \param str A nul-terminated string to validate, or NULL.
389 * \param min_digits least permitted amount of digits.
390 * \param max_digits most permitted amount of digits.
391 * \param require_even if true, require an even amount of digits.
392 * \returns true when the hex_str contains only hexadecimal digits (no
393 * whitespace) and matches the requested length; also true
394 * when min_digits <= 0 and str is NULL.
395 */
396bool osmo_is_hexstr(const char *str, int min_digits, int max_digits,
397 bool require_even)
398{
399 int len;
400 /* Use unsigned char * to avoid a compiler warning of
401 * "error: array subscript has type 'char' [-Werror=char-subscripts]" */
402 const unsigned char *pos = (const unsigned char*)str;
403 if (!pos)
404 return min_digits < 1;
405 for (len = 0; *pos && len < max_digits; len++, pos++)
406 if (!isxdigit(*pos))
407 return false;
408 if (len < min_digits)
409 return false;
410 /* With not too many digits, we should have reached *str == nul */
411 if (*pos)
412 return false;
413 if (require_even && (len & 1))
414 return false;
Harald Weltefebe83c2017-10-03 17:41:59 +0800415
416 return true;
417}
418
419/*! Determine if a given identifier is valid, i.e. doesn't contain illegal chars
420 * \param[in] str String to validate
421 * \returns true in case string contains valid identifier, false otherwise
422 */
423bool osmo_identifier_valid(const char *str)
424{
425 /* characters that are illegal in names */
426 static const char illegal_chars[] = "., {}[]()<>|~\\^`'\"?=;/+*&%$#!";
427 unsigned int i;
428
429 /* an empty string is not a valid identifier */
430 if (!str || strlen(str) == 0)
431 return false;
432
433 for (i = 0; i < strlen(str); i++) {
434 /* check for 7-bit ASCII */
435 if (str[i] & 0x80)
436 return false;
437 /* check for some explicit reserved control characters */
438 if (strchr(illegal_chars, str[i]))
439 return false;
440 }
441
Neels Hofmeyr4335bad2017-10-07 04:39:14 +0200442 return true;
443}
444
Neels Hofmeyr0aeda1b2017-01-13 14:16:02 +0100445/*! @} */