blob: a62f5e97d12a393d9051e3994bb922b4f643f225 [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{
Harald Weltefa8983d2017-10-27 16:52:59 +0200120 if (c >= '0' && c <= '9')
121 return c - 0x30;
122 else if (c >= 'A' && c <= 'F')
123 return 0xa + (c - 'A');
124 else if (c >= 'a' && c <= 'f')
125 return 0xa + (c - 'a');
126 else
127 return 0;
Harald Weltea73e2f92010-03-04 10:50:32 +0100128}
Harald Welte3eba9912010-07-30 10:37:29 +0200129
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200130/*! Parse a string containing hexadecimal digits
Harald Weltede6e4982012-12-06 21:25:27 +0100131 * \param[in] str string containing ASCII encoded hexadecimal digits
132 * \param[out] b output buffer
133 * \param[in] max_len maximum space in output buffer
Neels Hofmeyr3de7b052015-09-23 23:16:53 +0200134 * \returns number of parsed octets, or -1 on error
Harald Weltede6e4982012-12-06 21:25:27 +0100135 */
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200136int osmo_hexparse(const char *str, uint8_t *b, int max_len)
Harald Welte3eba9912010-07-30 10:37:29 +0200137
138{
Neels Hofmeyr437ed4a2017-02-14 15:54:31 +0100139 char c;
140 uint8_t v;
141 const char *strpos;
142 unsigned int nibblepos = 0;
Harald Welte3eba9912010-07-30 10:37:29 +0200143
144 memset(b, 0x00, max_len);
145
Neels Hofmeyr437ed4a2017-02-14 15:54:31 +0100146 for (strpos = str; (c = *strpos); strpos++) {
147 /* skip whitespace */
148 if (c == ' ' || c == '\t' || c == '\n' || c == '\r')
149 continue;
150
151 /* If the buffer is too small, error out */
152 if (nibblepos >= (max_len << 1))
153 return -1;
154
Harald Welte3eba9912010-07-30 10:37:29 +0200155 if (c >= '0' && c <= '9')
156 v = c - '0';
157 else if (c >= 'a' && c <= 'f')
158 v = 10 + (c - 'a');
159 else if (c >= 'A' && c <= 'F')
160 v = 10 + (c - 'A');
161 else
162 return -1;
Neels Hofmeyr437ed4a2017-02-14 15:54:31 +0100163
164 b[nibblepos >> 1] |= v << (nibblepos & 1 ? 0 : 4);
165 nibblepos ++;
Harald Welte3eba9912010-07-30 10:37:29 +0200166 }
167
Neels Hofmeyr437ed4a2017-02-14 15:54:31 +0100168 /* In case of uneven amount of digits, the last byte is not complete
169 * and that's an error. */
170 if (nibblepos & 1)
171 return -1;
172
173 return nibblepos >> 1;
Harald Welte3eba9912010-07-30 10:37:29 +0200174}
Harald Welte40481e82010-07-30 11:40:32 +0200175
176static char hexd_buff[4096];
Nils O. SelÄsdal32447022014-01-02 14:04:43 +0100177static const char hex_chars[] = "0123456789abcdef";
Harald Welte40481e82010-07-30 11:40:32 +0200178
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200179static char *_osmo_hexdump(const unsigned char *buf, int len, char *delim)
Harald Welte40481e82010-07-30 11:40:32 +0200180{
181 int i;
182 char *cur = hexd_buff;
183
184 hexd_buff[0] = 0;
185 for (i = 0; i < len; i++) {
Nils O. SelÄsdal32447022014-01-02 14:04:43 +0100186 const char *delimp = delim;
Harald Welte40481e82010-07-30 11:40:32 +0200187 int len_remain = sizeof(hexd_buff) - (cur - hexd_buff);
Nils O. SelÄsdal32447022014-01-02 14:04:43 +0100188 if (len_remain < 3)
Holger Hans Peter Freyther128d9e22011-07-15 16:07:23 +0200189 break;
Nils O. SelÄsdal32447022014-01-02 14:04:43 +0100190
191 *cur++ = hex_chars[buf[i] >> 4];
192 *cur++ = hex_chars[buf[i] & 0xf];
193
194 while (len_remain > 1 && *delimp) {
195 *cur++ = *delimp++;
196 len_remain--;
197 }
198
199 *cur = 0;
Harald Welte40481e82010-07-30 11:40:32 +0200200 }
201 hexd_buff[sizeof(hexd_buff)-1] = 0;
202 return hexd_buff;
203}
Harald Weltedee47cd2010-07-30 11:43:30 +0200204
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200205/*! Convert a sequence of unpacked bits to ASCII string
Harald Welte8598f182011-08-17 14:19:27 +0200206 * \param[in] bits A sequence of unpacked bits
207 * \param[in] len Length of bits
208 */
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200209char *osmo_ubit_dump(const uint8_t *bits, unsigned int len)
Harald Welte3d0ac5e2011-02-08 16:55:03 +0100210{
211 int i;
212
213 if (len > sizeof(hexd_buff)-1)
214 len = sizeof(hexd_buff)-1;
215 memset(hexd_buff, 0, sizeof(hexd_buff));
216
217 for (i = 0; i < len; i++) {
218 char outch;
219 switch (bits[i]) {
220 case 0:
221 outch = '0';
222 break;
223 case 0xff:
224 outch = '?';
225 break;
226 case 1:
227 outch = '1';
228 break;
229 default:
230 outch = 'E';
231 break;
232 }
233 hexd_buff[i] = outch;
234 }
235 hexd_buff[sizeof(hexd_buff)-1] = 0;
236 return hexd_buff;
237}
238
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200239/*! Convert binary sequence to hexadecimal ASCII string
Harald Welte8598f182011-08-17 14:19:27 +0200240 * \param[in] buf pointer to sequence of bytes
241 * \param[in] len length of buf in number of bytes
242 * \returns pointer to zero-terminated string
243 *
244 * This function will print a sequence of bytes as hexadecimal numbers,
245 * adding one space character between each byte (e.g. "1a ef d9")
Harald Welte096a6662017-10-16 14:33:11 +0200246 *
247 * The maximum size of the output buffer is 4096 bytes, i.e. the maximum
248 * number of input bytes that can be printed in one call is 1365!
Harald Welte8598f182011-08-17 14:19:27 +0200249 */
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200250char *osmo_hexdump(const unsigned char *buf, int len)
Harald Weltedee47cd2010-07-30 11:43:30 +0200251{
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200252 return _osmo_hexdump(buf, len, " ");
Harald Weltedee47cd2010-07-30 11:43:30 +0200253}
254
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200255/*! Convert binary sequence to hexadecimal ASCII string
Harald Welte8598f182011-08-17 14:19:27 +0200256 * \param[in] buf pointer to sequence of bytes
257 * \param[in] len length of buf in number of bytes
258 * \returns pointer to zero-terminated string
259 *
260 * This function will print a sequence of bytes as hexadecimal numbers,
261 * without any space character between each byte (e.g. "1aefd9")
Harald Welte096a6662017-10-16 14:33:11 +0200262 *
263 * The maximum size of the output buffer is 4096 bytes, i.e. the maximum
264 * number of input bytes that can be printed in one call is 2048!
Harald Welte8598f182011-08-17 14:19:27 +0200265 */
Sylvain Munautff23d242011-11-10 23:03:18 +0100266char *osmo_hexdump_nospc(const unsigned char *buf, int len)
Harald Weltedee47cd2010-07-30 11:43:30 +0200267{
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200268 return _osmo_hexdump(buf, len, "");
Harald Weltedee47cd2010-07-30 11:43:30 +0200269}
Harald Welte28222962011-02-18 20:37:04 +0100270
Holger Hans Peter Freyther9a1a5a12015-04-11 19:26:55 +0200271/* Compat with previous typo to preserve abi */
Sylvain Munaute55ae3a2011-11-11 23:06:55 +0100272char *osmo_osmo_hexdump_nospc(const unsigned char *buf, int len)
Holger Hans Peter Freyther9a1a5a12015-04-11 19:26:55 +0200273#if defined(__MACH__) && defined(__APPLE__)
274 ;
275#else
Sylvain Munaut17af41d2011-11-19 22:30:39 +0100276 __attribute__((weak, alias("osmo_hexdump_nospc")));
Holger Hans Peter Freyther9a1a5a12015-04-11 19:26:55 +0200277#endif
Sylvain Munaute55ae3a2011-11-11 23:06:55 +0100278
Harald Welte28222962011-02-18 20:37:04 +0100279#include "../config.h"
280#ifdef HAVE_CTYPE_H
281#include <ctype.h>
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200282/*! Convert an entire string to lower case
Harald Welte8598f182011-08-17 14:19:27 +0200283 * \param[out] out output string, caller-allocated
284 * \param[in] in input string
285 */
Harald Welte28222962011-02-18 20:37:04 +0100286void osmo_str2lower(char *out, const char *in)
287{
288 unsigned int i;
289
290 for (i = 0; i < strlen(in); i++)
Pau Espin Pedrol399a6f02017-06-18 14:07:37 +0200291 out[i] = tolower((const unsigned char)in[i]);
Harald Welte28222962011-02-18 20:37:04 +0100292 out[strlen(in)] = '\0';
293}
294
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200295/*! Convert an entire string to upper case
Harald Welte8598f182011-08-17 14:19:27 +0200296 * \param[out] out output string, caller-allocated
297 * \param[in] in input string
298 */
Harald Welte28222962011-02-18 20:37:04 +0100299void osmo_str2upper(char *out, const char *in)
300{
301 unsigned int i;
302
303 for (i = 0; i < strlen(in); i++)
Pau Espin Pedrol399a6f02017-06-18 14:07:37 +0200304 out[i] = toupper((const unsigned char)in[i]);
Harald Welte28222962011-02-18 20:37:04 +0100305 out[strlen(in)] = '\0';
306}
307#endif /* HAVE_CTYPE_H */
Harald Welte8598f182011-08-17 14:19:27 +0200308
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200309/*! Wishful thinking to generate a constant time compare
Harald Welte9709b2e2016-04-25 18:47:53 +0200310 * \param[in] exp Expected data
311 * \param[in] rel Comparison value
312 * \param[in] count Number of bytes to compare
313 * \returns 1 in case \a exp equals \a rel; zero otherwise
314 *
315 * Compare count bytes of exp to rel. Return 0 if they are identical, 1
316 * otherwise. Do not return a mismatch on the first mismatching byte,
317 * but always compare all bytes, regardless. The idea is that the amount of
318 * matching bytes cannot be inferred from the time the comparison took. */
319int osmo_constant_time_cmp(const uint8_t *exp, const uint8_t *rel, const int count)
320{
321 int x = 0, i;
322
323 for (i = 0; i < count; ++i)
324 x |= exp[i] ^ rel[i];
325
326 /* if x is zero, all data was identical */
327 return x? 1 : 0;
328}
329
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200330/*! Generic retrieval of 1..8 bytes as big-endian uint64_t
Harald Welte9709b2e2016-04-25 18:47:53 +0200331 * \param[in] data Input data as byte-array
332 * \param[in] data_len Length of \a data in octets
333 * \returns uint64_t of \a data interpreted as big-endian
334 *
335 * This is like osmo_load64be_ext, except that if data_len is less than
336 * sizeof(uint64_t), the data is interpreted as the least significant bytes
337 * (osmo_load64be_ext loads them as the most significant bytes into the
338 * returned uint64_t). In this way, any integer size up to 64 bits can be
339 * decoded conveniently by using sizeof(), without the need to call specific
340 * numbered functions (osmo_load16, 32, ...). */
341uint64_t osmo_decode_big_endian(const uint8_t *data, size_t data_len)
342{
343 uint64_t value = 0;
344
345 while (data_len > 0) {
346 value = (value << 8) + *data;
347 data += 1;
348 data_len -= 1;
349 }
350
351 return value;
352}
353
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200354/*! Generic big-endian encoding of big endian number up to 64bit
Harald Welte9709b2e2016-04-25 18:47:53 +0200355 * \param[in] value unsigned integer value to be stored
356 * \param[in] data_len number of octets
357 * \returns static buffer containing big-endian stored value
358 *
359 * This is like osmo_store64be_ext, except that this returns a static buffer of
360 * the result (for convenience, but not threadsafe). If data_len is less than
361 * sizeof(uint64_t), only the least significant bytes of value are encoded. */
362uint8_t *osmo_encode_big_endian(uint64_t value, size_t data_len)
363{
364 static uint8_t buf[sizeof(uint64_t)];
365 OSMO_ASSERT(data_len <= ARRAY_SIZE(buf));
366 osmo_store64be_ext(value, buf, data_len);
367 return buf;
368}
Harald Welteaeecc482016-11-26 10:41:40 +0100369
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200370/*! Copy a C-string into a sized buffer
Harald Welteaeecc482016-11-26 10:41:40 +0100371 * \param[in] src source string
372 * \param[out] dst destination string
Neels Hofmeyrdf83ece2017-01-13 13:55:43 +0100373 * \param[in] siz size of the \a dst buffer
374 * \returns length of \a src
Harald Welteaeecc482016-11-26 10:41:40 +0100375 *
Neels Hofmeyrdf83ece2017-01-13 13:55:43 +0100376 * Copy at most \a siz bytes from \a src to \a dst, ensuring that the result is
377 * NUL terminated. The NUL character is included in \a siz, i.e. passing the
378 * actual sizeof(*dst) is correct.
Harald Welteaeecc482016-11-26 10:41:40 +0100379 */
380size_t osmo_strlcpy(char *dst, const char *src, size_t siz)
381{
Neels Hofmeyrbcf9f232017-10-25 04:16:45 +0200382 size_t ret = src ? strlen(src) : 0;
Harald Welteaeecc482016-11-26 10:41:40 +0100383
384 if (siz) {
385 size_t len = (ret >= siz) ? siz - 1 : ret;
386 memcpy(dst, src, len);
387 dst[len] = '\0';
388 }
389 return ret;
390}
Neels Hofmeyr0aeda1b2017-01-13 14:16:02 +0100391
Neels Hofmeyr4335bad2017-10-07 04:39:14 +0200392/*! Validate that a given string is a hex string within given size limits.
393 * Note that each hex digit amounts to a nibble, so if checking for a hex
394 * string to result in N bytes, pass amount of digits as 2*N.
395 * \param str A nul-terminated string to validate, or NULL.
396 * \param min_digits least permitted amount of digits.
397 * \param max_digits most permitted amount of digits.
398 * \param require_even if true, require an even amount of digits.
399 * \returns true when the hex_str contains only hexadecimal digits (no
400 * whitespace) and matches the requested length; also true
401 * when min_digits <= 0 and str is NULL.
402 */
403bool osmo_is_hexstr(const char *str, int min_digits, int max_digits,
404 bool require_even)
405{
406 int len;
407 /* Use unsigned char * to avoid a compiler warning of
408 * "error: array subscript has type 'char' [-Werror=char-subscripts]" */
409 const unsigned char *pos = (const unsigned char*)str;
410 if (!pos)
411 return min_digits < 1;
412 for (len = 0; *pos && len < max_digits; len++, pos++)
413 if (!isxdigit(*pos))
414 return false;
415 if (len < min_digits)
416 return false;
417 /* With not too many digits, we should have reached *str == nul */
418 if (*pos)
419 return false;
420 if (require_even && (len & 1))
421 return false;
Harald Weltefebe83c2017-10-03 17:41:59 +0800422
423 return true;
424}
425
426/*! Determine if a given identifier is valid, i.e. doesn't contain illegal chars
427 * \param[in] str String to validate
428 * \returns true in case string contains valid identifier, false otherwise
429 */
430bool osmo_identifier_valid(const char *str)
431{
432 /* characters that are illegal in names */
433 static const char illegal_chars[] = "., {}[]()<>|~\\^`'\"?=;/+*&%$#!";
434 unsigned int i;
435
436 /* an empty string is not a valid identifier */
437 if (!str || strlen(str) == 0)
438 return false;
439
440 for (i = 0; i < strlen(str); i++) {
441 /* check for 7-bit ASCII */
442 if (str[i] & 0x80)
443 return false;
444 /* check for some explicit reserved control characters */
445 if (strchr(illegal_chars, str[i]))
446 return false;
447 }
448
Neels Hofmeyr4335bad2017-10-07 04:39:14 +0200449 return true;
450}
451
Neels Hofmeyr0aeda1b2017-01-13 14:16:02 +0100452/*! @} */