blob: 9e3414b2dfa315469e1ede9f19dc4c8dbf9e49df [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
25#include <string.h>
26#include <stdint.h>
27#include <errno.h>
Harald Welteb59f9352010-03-25 11:37:04 +080028#include <stdio.h>
Harald Welted284cd92010-03-01 21:58:31 +010029
Pablo Neira Ayuso83419342011-03-22 16:36:13 +010030#include <osmocom/core/utils.h>
Harald Welte9709b2e2016-04-25 18:47:53 +020031#include <osmocom/core/bit64gen.h>
32
Harald Welted284cd92010-03-01 21:58:31 +010033
Harald Welte8598f182011-08-17 14:19:27 +020034/*! \addtogroup utils
35 * @{
Neels Hofmeyr87e45502017-06-20 00:17:59 +020036 * various utility routines
Neels Hofmeyr17518fe2017-06-20 04:35:06 +020037 *
38 * \file utils.c */
Harald Welte8598f182011-08-17 14:19:27 +020039
Harald Welteb59f9352010-03-25 11:37:04 +080040static char namebuf[255];
Harald Welte8598f182011-08-17 14:19:27 +020041
Neels Hofmeyr87e45502017-06-20 00:17:59 +020042/*! get human-readable string for given value
Harald Welte8598f182011-08-17 14:19:27 +020043 * \param[in] vs Array of value_string tuples
44 * \param[in] val Value to be converted
45 * \returns pointer to human-readable string
Neels Hofmeyr8a3c83e2016-06-13 13:16:58 +020046 *
47 * If val is found in vs, the array's string entry is returned. Otherwise, an
48 * "unknown" string containing the actual value is composed in a static buffer
49 * that is reused across invocations.
Harald Welte8598f182011-08-17 14:19:27 +020050 */
Harald Welted284cd92010-03-01 21:58:31 +010051const char *get_value_string(const struct value_string *vs, uint32_t val)
52{
Neels Hofmeyr8d6dcd92016-06-06 18:05:23 +020053 const char *str = get_value_string_or_null(vs, val);
54 if (str)
55 return str;
56
57 snprintf(namebuf, sizeof(namebuf), "unknown 0x%x", val);
58 namebuf[sizeof(namebuf) - 1] = '\0';
59 return namebuf;
60}
61
Neels Hofmeyr87e45502017-06-20 00:17:59 +020062/*! get human-readable string or NULL for given value
Neels Hofmeyr8d6dcd92016-06-06 18:05:23 +020063 * \param[in] vs Array of value_string tuples
64 * \param[in] val Value to be converted
65 * \returns pointer to human-readable string or NULL if val is not found
66 */
67const char *get_value_string_or_null(const struct value_string *vs,
68 uint32_t val)
69{
Harald Welted284cd92010-03-01 21:58:31 +010070 int i;
71
72 for (i = 0;; i++) {
73 if (vs[i].value == 0 && vs[i].str == NULL)
74 break;
75 if (vs[i].value == val)
76 return vs[i].str;
77 }
Harald Welteb59f9352010-03-25 11:37:04 +080078
Neels Hofmeyr8d6dcd92016-06-06 18:05:23 +020079 return NULL;
Harald Welted284cd92010-03-01 21:58:31 +010080}
81
Neels Hofmeyr87e45502017-06-20 00:17:59 +020082/*! get numeric value for given human-readable string
Harald Welte8598f182011-08-17 14:19:27 +020083 * \param[in] vs Array of value_string tuples
84 * \param[in] str human-readable string
85 * \returns numeric value (>0) or negative numer in case of error
86 */
Harald Welted284cd92010-03-01 21:58:31 +010087int get_string_value(const struct value_string *vs, const char *str)
88{
89 int i;
90
91 for (i = 0;; i++) {
92 if (vs[i].value == 0 && vs[i].str == NULL)
93 break;
94 if (!strcasecmp(vs[i].str, str))
95 return vs[i].value;
96 }
97 return -EINVAL;
98}
Harald Weltea73e2f92010-03-04 10:50:32 +010099
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200100/*! Convert BCD-encoded digit into printable character
Harald Welte8598f182011-08-17 14:19:27 +0200101 * \param[in] bcd A single BCD-encoded digit
102 * \returns single printable character
103 */
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200104char osmo_bcd2char(uint8_t bcd)
Harald Weltea73e2f92010-03-04 10:50:32 +0100105{
106 if (bcd < 0xa)
107 return '0' + bcd;
108 else
109 return 'A' + (bcd - 0xa);
110}
111
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200112/*! Convert number in ASCII to BCD value
Harald Weltede6e4982012-12-06 21:25:27 +0100113 * \param[in] c ASCII character
114 * \returns BCD encoded value of character
115 */
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200116uint8_t osmo_char2bcd(char c)
Harald Weltea73e2f92010-03-04 10:50:32 +0100117{
118 return c - 0x30;
119}
Harald Welte3eba9912010-07-30 10:37:29 +0200120
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200121/*! Parse a string containing hexadecimal digits
Harald Weltede6e4982012-12-06 21:25:27 +0100122 * \param[in] str string containing ASCII encoded hexadecimal digits
123 * \param[out] b output buffer
124 * \param[in] max_len maximum space in output buffer
Neels Hofmeyr3de7b052015-09-23 23:16:53 +0200125 * \returns number of parsed octets, or -1 on error
Harald Weltede6e4982012-12-06 21:25:27 +0100126 */
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200127int osmo_hexparse(const char *str, uint8_t *b, int max_len)
Harald Welte3eba9912010-07-30 10:37:29 +0200128
129{
Neels Hofmeyr437ed4a2017-02-14 15:54:31 +0100130 char c;
131 uint8_t v;
132 const char *strpos;
133 unsigned int nibblepos = 0;
Harald Welte3eba9912010-07-30 10:37:29 +0200134
135 memset(b, 0x00, max_len);
136
Neels Hofmeyr437ed4a2017-02-14 15:54:31 +0100137 for (strpos = str; (c = *strpos); strpos++) {
138 /* skip whitespace */
139 if (c == ' ' || c == '\t' || c == '\n' || c == '\r')
140 continue;
141
142 /* If the buffer is too small, error out */
143 if (nibblepos >= (max_len << 1))
144 return -1;
145
Harald Welte3eba9912010-07-30 10:37:29 +0200146 if (c >= '0' && c <= '9')
147 v = c - '0';
148 else if (c >= 'a' && c <= 'f')
149 v = 10 + (c - 'a');
150 else if (c >= 'A' && c <= 'F')
151 v = 10 + (c - 'A');
152 else
153 return -1;
Neels Hofmeyr437ed4a2017-02-14 15:54:31 +0100154
155 b[nibblepos >> 1] |= v << (nibblepos & 1 ? 0 : 4);
156 nibblepos ++;
Harald Welte3eba9912010-07-30 10:37:29 +0200157 }
158
Neels Hofmeyr437ed4a2017-02-14 15:54:31 +0100159 /* In case of uneven amount of digits, the last byte is not complete
160 * and that's an error. */
161 if (nibblepos & 1)
162 return -1;
163
164 return nibblepos >> 1;
Harald Welte3eba9912010-07-30 10:37:29 +0200165}
Harald Welte40481e82010-07-30 11:40:32 +0200166
167static char hexd_buff[4096];
Nils O. SelÄsdal32447022014-01-02 14:04:43 +0100168static const char hex_chars[] = "0123456789abcdef";
Harald Welte40481e82010-07-30 11:40:32 +0200169
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200170static char *_osmo_hexdump(const unsigned char *buf, int len, char *delim)
Harald Welte40481e82010-07-30 11:40:32 +0200171{
172 int i;
173 char *cur = hexd_buff;
174
175 hexd_buff[0] = 0;
176 for (i = 0; i < len; i++) {
Nils O. SelÄsdal32447022014-01-02 14:04:43 +0100177 const char *delimp = delim;
Harald Welte40481e82010-07-30 11:40:32 +0200178 int len_remain = sizeof(hexd_buff) - (cur - hexd_buff);
Nils O. SelÄsdal32447022014-01-02 14:04:43 +0100179 if (len_remain < 3)
Holger Hans Peter Freyther128d9e22011-07-15 16:07:23 +0200180 break;
Nils O. SelÄsdal32447022014-01-02 14:04:43 +0100181
182 *cur++ = hex_chars[buf[i] >> 4];
183 *cur++ = hex_chars[buf[i] & 0xf];
184
185 while (len_remain > 1 && *delimp) {
186 *cur++ = *delimp++;
187 len_remain--;
188 }
189
190 *cur = 0;
Harald Welte40481e82010-07-30 11:40:32 +0200191 }
192 hexd_buff[sizeof(hexd_buff)-1] = 0;
193 return hexd_buff;
194}
Harald Weltedee47cd2010-07-30 11:43:30 +0200195
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200196/*! Convert a sequence of unpacked bits to ASCII string
Harald Welte8598f182011-08-17 14:19:27 +0200197 * \param[in] bits A sequence of unpacked bits
198 * \param[in] len Length of bits
199 */
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200200char *osmo_ubit_dump(const uint8_t *bits, unsigned int len)
Harald Welte3d0ac5e2011-02-08 16:55:03 +0100201{
202 int i;
203
204 if (len > sizeof(hexd_buff)-1)
205 len = sizeof(hexd_buff)-1;
206 memset(hexd_buff, 0, sizeof(hexd_buff));
207
208 for (i = 0; i < len; i++) {
209 char outch;
210 switch (bits[i]) {
211 case 0:
212 outch = '0';
213 break;
214 case 0xff:
215 outch = '?';
216 break;
217 case 1:
218 outch = '1';
219 break;
220 default:
221 outch = 'E';
222 break;
223 }
224 hexd_buff[i] = outch;
225 }
226 hexd_buff[sizeof(hexd_buff)-1] = 0;
227 return hexd_buff;
228}
229
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200230/*! Convert binary sequence to hexadecimal ASCII string
Harald Welte8598f182011-08-17 14:19:27 +0200231 * \param[in] buf pointer to sequence of bytes
232 * \param[in] len length of buf in number of bytes
233 * \returns pointer to zero-terminated string
234 *
235 * This function will print a sequence of bytes as hexadecimal numbers,
236 * adding one space character between each byte (e.g. "1a ef d9")
237 */
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200238char *osmo_hexdump(const unsigned char *buf, int len)
Harald Weltedee47cd2010-07-30 11:43:30 +0200239{
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200240 return _osmo_hexdump(buf, len, " ");
Harald Weltedee47cd2010-07-30 11:43:30 +0200241}
242
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200243/*! Convert binary sequence to hexadecimal ASCII string
Harald Welte8598f182011-08-17 14:19:27 +0200244 * \param[in] buf pointer to sequence of bytes
245 * \param[in] len length of buf in number of bytes
246 * \returns pointer to zero-terminated string
247 *
248 * This function will print a sequence of bytes as hexadecimal numbers,
249 * without any space character between each byte (e.g. "1aefd9")
250 */
Sylvain Munautff23d242011-11-10 23:03:18 +0100251char *osmo_hexdump_nospc(const unsigned char *buf, int len)
Harald Weltedee47cd2010-07-30 11:43:30 +0200252{
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200253 return _osmo_hexdump(buf, len, "");
Harald Weltedee47cd2010-07-30 11:43:30 +0200254}
Harald Welte28222962011-02-18 20:37:04 +0100255
Holger Hans Peter Freyther9a1a5a12015-04-11 19:26:55 +0200256/* Compat with previous typo to preserve abi */
Sylvain Munaute55ae3a2011-11-11 23:06:55 +0100257char *osmo_osmo_hexdump_nospc(const unsigned char *buf, int len)
Holger Hans Peter Freyther9a1a5a12015-04-11 19:26:55 +0200258#if defined(__MACH__) && defined(__APPLE__)
259 ;
260#else
Sylvain Munaut17af41d2011-11-19 22:30:39 +0100261 __attribute__((weak, alias("osmo_hexdump_nospc")));
Holger Hans Peter Freyther9a1a5a12015-04-11 19:26:55 +0200262#endif
Sylvain Munaute55ae3a2011-11-11 23:06:55 +0100263
Harald Welte28222962011-02-18 20:37:04 +0100264#include "../config.h"
265#ifdef HAVE_CTYPE_H
266#include <ctype.h>
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200267/*! Convert an entire string to lower case
Harald Welte8598f182011-08-17 14:19:27 +0200268 * \param[out] out output string, caller-allocated
269 * \param[in] in input string
270 */
Harald Welte28222962011-02-18 20:37:04 +0100271void osmo_str2lower(char *out, const char *in)
272{
273 unsigned int i;
274
275 for (i = 0; i < strlen(in); i++)
276 out[i] = tolower(in[i]);
277 out[strlen(in)] = '\0';
278}
279
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200280/*! Convert an entire string to upper case
Harald Welte8598f182011-08-17 14:19:27 +0200281 * \param[out] out output string, caller-allocated
282 * \param[in] in input string
283 */
Harald Welte28222962011-02-18 20:37:04 +0100284void osmo_str2upper(char *out, const char *in)
285{
286 unsigned int i;
287
288 for (i = 0; i < strlen(in); i++)
289 out[i] = toupper(in[i]);
290 out[strlen(in)] = '\0';
291}
292#endif /* HAVE_CTYPE_H */
Harald Welte8598f182011-08-17 14:19:27 +0200293
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200294/*! Wishful thinking to generate a constant time compare
Harald Welte9709b2e2016-04-25 18:47:53 +0200295 * \param[in] exp Expected data
296 * \param[in] rel Comparison value
297 * \param[in] count Number of bytes to compare
298 * \returns 1 in case \a exp equals \a rel; zero otherwise
299 *
300 * Compare count bytes of exp to rel. Return 0 if they are identical, 1
301 * otherwise. Do not return a mismatch on the first mismatching byte,
302 * but always compare all bytes, regardless. The idea is that the amount of
303 * matching bytes cannot be inferred from the time the comparison took. */
304int osmo_constant_time_cmp(const uint8_t *exp, const uint8_t *rel, const int count)
305{
306 int x = 0, i;
307
308 for (i = 0; i < count; ++i)
309 x |= exp[i] ^ rel[i];
310
311 /* if x is zero, all data was identical */
312 return x? 1 : 0;
313}
314
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200315/*! Generic retrieval of 1..8 bytes as big-endian uint64_t
Harald Welte9709b2e2016-04-25 18:47:53 +0200316 * \param[in] data Input data as byte-array
317 * \param[in] data_len Length of \a data in octets
318 * \returns uint64_t of \a data interpreted as big-endian
319 *
320 * This is like osmo_load64be_ext, except that if data_len is less than
321 * sizeof(uint64_t), the data is interpreted as the least significant bytes
322 * (osmo_load64be_ext loads them as the most significant bytes into the
323 * returned uint64_t). In this way, any integer size up to 64 bits can be
324 * decoded conveniently by using sizeof(), without the need to call specific
325 * numbered functions (osmo_load16, 32, ...). */
326uint64_t osmo_decode_big_endian(const uint8_t *data, size_t data_len)
327{
328 uint64_t value = 0;
329
330 while (data_len > 0) {
331 value = (value << 8) + *data;
332 data += 1;
333 data_len -= 1;
334 }
335
336 return value;
337}
338
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200339/*! Generic big-endian encoding of big endian number up to 64bit
Harald Welte9709b2e2016-04-25 18:47:53 +0200340 * \param[in] value unsigned integer value to be stored
341 * \param[in] data_len number of octets
342 * \returns static buffer containing big-endian stored value
343 *
344 * This is like osmo_store64be_ext, except that this returns a static buffer of
345 * the result (for convenience, but not threadsafe). If data_len is less than
346 * sizeof(uint64_t), only the least significant bytes of value are encoded. */
347uint8_t *osmo_encode_big_endian(uint64_t value, size_t data_len)
348{
349 static uint8_t buf[sizeof(uint64_t)];
350 OSMO_ASSERT(data_len <= ARRAY_SIZE(buf));
351 osmo_store64be_ext(value, buf, data_len);
352 return buf;
353}
Harald Welteaeecc482016-11-26 10:41:40 +0100354
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200355/*! Copy a C-string into a sized buffer
Harald Welteaeecc482016-11-26 10:41:40 +0100356 * \param[in] src source string
357 * \param[out] dst destination string
Neels Hofmeyrdf83ece2017-01-13 13:55:43 +0100358 * \param[in] siz size of the \a dst buffer
359 * \returns length of \a src
Harald Welteaeecc482016-11-26 10:41:40 +0100360 *
Neels Hofmeyrdf83ece2017-01-13 13:55:43 +0100361 * Copy at most \a siz bytes from \a src to \a dst, ensuring that the result is
362 * NUL terminated. The NUL character is included in \a siz, i.e. passing the
363 * actual sizeof(*dst) is correct.
Harald Welteaeecc482016-11-26 10:41:40 +0100364 */
365size_t osmo_strlcpy(char *dst, const char *src, size_t siz)
366{
367 size_t ret = strlen(src);
368
369 if (siz) {
370 size_t len = (ret >= siz) ? siz - 1 : ret;
371 memcpy(dst, src, len);
372 dst[len] = '\0';
373 }
374 return ret;
375}
Neels Hofmeyr0aeda1b2017-01-13 14:16:02 +0100376
377/*! @} */