blob: df806dffda5972599bfbfc71ff45f062b2a7290f [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 * @{
36 */
37
38/*! \file utils.c */
39
Harald Welteb59f9352010-03-25 11:37:04 +080040static char namebuf[255];
Harald Welte8598f182011-08-17 14:19:27 +020041
42/*! \brief get human-readable string for given value
43 * \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
62/*! \brief get human-readable string or NULL for given value
63 * \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
Harald Welte8598f182011-08-17 14:19:27 +020082/*! \brief get numeric value for given human-readable string
83 * \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
Harald Welte8598f182011-08-17 14:19:27 +0200100/*! \brief Convert BCD-encoded digit into printable character
101 * \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
Harald Weltede6e4982012-12-06 21:25:27 +0100112/*! \brief Convert number in ASCII to BCD value
113 * \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 Hofmeyrb6d58e82016-12-21 14:35:46 +0100121/*! \brief 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{
130 int i, l, v;
131
132 l = strlen(str);
133 if ((l&1) || ((l>>1) > max_len))
134 return -1;
135
136 memset(b, 0x00, max_len);
137
138 for (i=0; i<l; i++) {
139 char c = str[i];
140 if (c >= '0' && c <= '9')
141 v = c - '0';
142 else if (c >= 'a' && c <= 'f')
143 v = 10 + (c - 'a');
144 else if (c >= 'A' && c <= 'F')
145 v = 10 + (c - 'A');
146 else
147 return -1;
148 b[i>>1] |= v << (i&1 ? 0 : 4);
149 }
150
151 return i>>1;
152}
Harald Welte40481e82010-07-30 11:40:32 +0200153
154static char hexd_buff[4096];
Nils O. SelÄsdal32447022014-01-02 14:04:43 +0100155static const char hex_chars[] = "0123456789abcdef";
Harald Welte40481e82010-07-30 11:40:32 +0200156
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200157static char *_osmo_hexdump(const unsigned char *buf, int len, char *delim)
Harald Welte40481e82010-07-30 11:40:32 +0200158{
159 int i;
160 char *cur = hexd_buff;
161
162 hexd_buff[0] = 0;
163 for (i = 0; i < len; i++) {
Nils O. SelÄsdal32447022014-01-02 14:04:43 +0100164 const char *delimp = delim;
Harald Welte40481e82010-07-30 11:40:32 +0200165 int len_remain = sizeof(hexd_buff) - (cur - hexd_buff);
Nils O. SelÄsdal32447022014-01-02 14:04:43 +0100166 if (len_remain < 3)
Holger Hans Peter Freyther128d9e22011-07-15 16:07:23 +0200167 break;
Nils O. SelÄsdal32447022014-01-02 14:04:43 +0100168
169 *cur++ = hex_chars[buf[i] >> 4];
170 *cur++ = hex_chars[buf[i] & 0xf];
171
172 while (len_remain > 1 && *delimp) {
173 *cur++ = *delimp++;
174 len_remain--;
175 }
176
177 *cur = 0;
Harald Welte40481e82010-07-30 11:40:32 +0200178 }
179 hexd_buff[sizeof(hexd_buff)-1] = 0;
180 return hexd_buff;
181}
Harald Weltedee47cd2010-07-30 11:43:30 +0200182
Harald Welte8598f182011-08-17 14:19:27 +0200183/*! \brief Convert a sequence of unpacked bits to ASCII string
184 * \param[in] bits A sequence of unpacked bits
185 * \param[in] len Length of bits
186 */
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200187char *osmo_ubit_dump(const uint8_t *bits, unsigned int len)
Harald Welte3d0ac5e2011-02-08 16:55:03 +0100188{
189 int i;
190
191 if (len > sizeof(hexd_buff)-1)
192 len = sizeof(hexd_buff)-1;
193 memset(hexd_buff, 0, sizeof(hexd_buff));
194
195 for (i = 0; i < len; i++) {
196 char outch;
197 switch (bits[i]) {
198 case 0:
199 outch = '0';
200 break;
201 case 0xff:
202 outch = '?';
203 break;
204 case 1:
205 outch = '1';
206 break;
207 default:
208 outch = 'E';
209 break;
210 }
211 hexd_buff[i] = outch;
212 }
213 hexd_buff[sizeof(hexd_buff)-1] = 0;
214 return hexd_buff;
215}
216
Harald Welte8598f182011-08-17 14:19:27 +0200217/*! \brief Convert binary sequence to hexadecimal ASCII string
218 * \param[in] buf pointer to sequence of bytes
219 * \param[in] len length of buf in number of bytes
220 * \returns pointer to zero-terminated string
221 *
222 * This function will print a sequence of bytes as hexadecimal numbers,
223 * adding one space character between each byte (e.g. "1a ef d9")
224 */
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200225char *osmo_hexdump(const unsigned char *buf, int len)
Harald Weltedee47cd2010-07-30 11:43:30 +0200226{
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200227 return _osmo_hexdump(buf, len, " ");
Harald Weltedee47cd2010-07-30 11:43:30 +0200228}
229
Harald Welte8598f182011-08-17 14:19:27 +0200230/*! \brief Convert binary sequence to hexadecimal ASCII string
231 * \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 * without any space character between each byte (e.g. "1aefd9")
237 */
Sylvain Munautff23d242011-11-10 23:03:18 +0100238char *osmo_hexdump_nospc(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}
Harald Welte28222962011-02-18 20:37:04 +0100242
Holger Hans Peter Freyther9a1a5a12015-04-11 19:26:55 +0200243/* Compat with previous typo to preserve abi */
Sylvain Munaute55ae3a2011-11-11 23:06:55 +0100244char *osmo_osmo_hexdump_nospc(const unsigned char *buf, int len)
Holger Hans Peter Freyther9a1a5a12015-04-11 19:26:55 +0200245#if defined(__MACH__) && defined(__APPLE__)
246 ;
247#else
Sylvain Munaut17af41d2011-11-19 22:30:39 +0100248 __attribute__((weak, alias("osmo_hexdump_nospc")));
Holger Hans Peter Freyther9a1a5a12015-04-11 19:26:55 +0200249#endif
Sylvain Munaute55ae3a2011-11-11 23:06:55 +0100250
Harald Welte28222962011-02-18 20:37:04 +0100251#include "../config.h"
252#ifdef HAVE_CTYPE_H
253#include <ctype.h>
Harald Welte8598f182011-08-17 14:19:27 +0200254/*! \brief Convert an entire string to lower case
255 * \param[out] out output string, caller-allocated
256 * \param[in] in input string
257 */
Harald Welte28222962011-02-18 20:37:04 +0100258void osmo_str2lower(char *out, const char *in)
259{
260 unsigned int i;
261
262 for (i = 0; i < strlen(in); i++)
263 out[i] = tolower(in[i]);
264 out[strlen(in)] = '\0';
265}
266
Harald Welte8598f182011-08-17 14:19:27 +0200267/*! \brief Convert an entire string to upper case
268 * \param[out] out output string, caller-allocated
269 * \param[in] in input string
270 */
Harald Welte28222962011-02-18 20:37:04 +0100271void osmo_str2upper(char *out, const char *in)
272{
273 unsigned int i;
274
275 for (i = 0; i < strlen(in); i++)
276 out[i] = toupper(in[i]);
277 out[strlen(in)] = '\0';
278}
279#endif /* HAVE_CTYPE_H */
Harald Welte8598f182011-08-17 14:19:27 +0200280
Harald Welte9709b2e2016-04-25 18:47:53 +0200281/*! \brief Wishful thinking to generate a constant time compare
282 * \param[in] exp Expected data
283 * \param[in] rel Comparison value
284 * \param[in] count Number of bytes to compare
285 * \returns 1 in case \a exp equals \a rel; zero otherwise
286 *
287 * Compare count bytes of exp to rel. Return 0 if they are identical, 1
288 * otherwise. Do not return a mismatch on the first mismatching byte,
289 * but always compare all bytes, regardless. The idea is that the amount of
290 * matching bytes cannot be inferred from the time the comparison took. */
291int osmo_constant_time_cmp(const uint8_t *exp, const uint8_t *rel, const int count)
292{
293 int x = 0, i;
294
295 for (i = 0; i < count; ++i)
296 x |= exp[i] ^ rel[i];
297
298 /* if x is zero, all data was identical */
299 return x? 1 : 0;
300}
301
302/*! \brief Generic retrieval of 1..8 bytes as big-endian uint64_t
303 * \param[in] data Input data as byte-array
304 * \param[in] data_len Length of \a data in octets
305 * \returns uint64_t of \a data interpreted as big-endian
306 *
307 * This is like osmo_load64be_ext, except that if data_len is less than
308 * sizeof(uint64_t), the data is interpreted as the least significant bytes
309 * (osmo_load64be_ext loads them as the most significant bytes into the
310 * returned uint64_t). In this way, any integer size up to 64 bits can be
311 * decoded conveniently by using sizeof(), without the need to call specific
312 * numbered functions (osmo_load16, 32, ...). */
313uint64_t osmo_decode_big_endian(const uint8_t *data, size_t data_len)
314{
315 uint64_t value = 0;
316
317 while (data_len > 0) {
318 value = (value << 8) + *data;
319 data += 1;
320 data_len -= 1;
321 }
322
323 return value;
324}
325
326/*! \brief Generic big-endian encoding of big endian number up to 64bit
327 * \param[in] value unsigned integer value to be stored
328 * \param[in] data_len number of octets
329 * \returns static buffer containing big-endian stored value
330 *
331 * This is like osmo_store64be_ext, except that this returns a static buffer of
332 * the result (for convenience, but not threadsafe). If data_len is less than
333 * sizeof(uint64_t), only the least significant bytes of value are encoded. */
334uint8_t *osmo_encode_big_endian(uint64_t value, size_t data_len)
335{
336 static uint8_t buf[sizeof(uint64_t)];
337 OSMO_ASSERT(data_len <= ARRAY_SIZE(buf));
338 osmo_store64be_ext(value, buf, data_len);
339 return buf;
340}
Sylvain Munautdca7d2c2012-04-18 21:53:23 +0200341/*! @} */
Harald Welteaeecc482016-11-26 10:41:40 +0100342
343/*! \brief Copy a C-string into a sized buffer
344 * \param[in] src source string
345 * \param[out] dst destination string
Neels Hofmeyrdf83ece2017-01-13 13:55:43 +0100346 * \param[in] siz size of the \a dst buffer
347 * \returns length of \a src
Harald Welteaeecc482016-11-26 10:41:40 +0100348 *
Neels Hofmeyrdf83ece2017-01-13 13:55:43 +0100349 * Copy at most \a siz bytes from \a src to \a dst, ensuring that the result is
350 * NUL terminated. The NUL character is included in \a siz, i.e. passing the
351 * actual sizeof(*dst) is correct.
Harald Welteaeecc482016-11-26 10:41:40 +0100352 */
353size_t osmo_strlcpy(char *dst, const char *src, size_t siz)
354{
355 size_t ret = strlen(src);
356
357 if (siz) {
358 size_t len = (ret >= siz) ? siz - 1 : ret;
359 memcpy(dst, src, len);
360 dst[len] = '\0';
361 }
362 return ret;
363}