blob: 2d5bcb0e875ac4993b0fcf21ddea0f1657db051f [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
Neels Hofmeyra0331ed2019-02-11 21:24:40 +010076 if (!vs)
77 return NULL;
78
Harald Welted284cd92010-03-01 21:58:31 +010079 for (i = 0;; i++) {
80 if (vs[i].value == 0 && vs[i].str == NULL)
81 break;
82 if (vs[i].value == val)
83 return vs[i].str;
84 }
Harald Welteb59f9352010-03-25 11:37:04 +080085
Neels Hofmeyr8d6dcd92016-06-06 18:05:23 +020086 return NULL;
Harald Welted284cd92010-03-01 21:58:31 +010087}
88
Neels Hofmeyr87e45502017-06-20 00:17:59 +020089/*! get numeric value for given human-readable string
Harald Welte8598f182011-08-17 14:19:27 +020090 * \param[in] vs Array of value_string tuples
91 * \param[in] str human-readable string
92 * \returns numeric value (>0) or negative numer in case of error
93 */
Harald Welted284cd92010-03-01 21:58:31 +010094int get_string_value(const struct value_string *vs, const char *str)
95{
96 int i;
97
98 for (i = 0;; i++) {
99 if (vs[i].value == 0 && vs[i].str == NULL)
100 break;
101 if (!strcasecmp(vs[i].str, str))
102 return vs[i].value;
103 }
104 return -EINVAL;
105}
Harald Weltea73e2f92010-03-04 10:50:32 +0100106
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200107/*! Convert BCD-encoded digit into printable character
Harald Welte8598f182011-08-17 14:19:27 +0200108 * \param[in] bcd A single BCD-encoded digit
109 * \returns single printable character
110 */
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200111char osmo_bcd2char(uint8_t bcd)
Harald Weltea73e2f92010-03-04 10:50:32 +0100112{
113 if (bcd < 0xa)
114 return '0' + bcd;
115 else
116 return 'A' + (bcd - 0xa);
117}
118
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200119/*! Convert number in ASCII to BCD value
Harald Weltede6e4982012-12-06 21:25:27 +0100120 * \param[in] c ASCII character
121 * \returns BCD encoded value of character
122 */
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200123uint8_t osmo_char2bcd(char c)
Harald Weltea73e2f92010-03-04 10:50:32 +0100124{
Harald Weltefa8983d2017-10-27 16:52:59 +0200125 if (c >= '0' && c <= '9')
126 return c - 0x30;
127 else if (c >= 'A' && c <= 'F')
128 return 0xa + (c - 'A');
129 else if (c >= 'a' && c <= 'f')
130 return 0xa + (c - 'a');
131 else
132 return 0;
Harald Weltea73e2f92010-03-04 10:50:32 +0100133}
Harald Welte3eba9912010-07-30 10:37:29 +0200134
Neels Hofmeyr7079e692018-12-05 21:02:36 +0100135/*! Convert BCD to string.
136 * The given nibble offsets are interpreted in BCD order, i.e. nibble 0 is bcd[0] & 0xf, nibble 1 is bcd[0] >> 4, nibble
137 * 3 is bcd[1] & 0xf, etc..
138 * \param[out] dst Output string buffer, is always nul terminated when dst_size > 0.
139 * \param[in] dst_size sizeof() the output string buffer.
140 * \param[in] bcd Binary coded data buffer.
141 * \param[in] start_nibble Offset to start from, in nibbles, typically 1 to skip the first nibble.
Neels Hofmeyr48b2de02018-12-11 02:13:57 +0100142 * \param[in] end_nibble Offset to stop before, in nibbles, e.g. sizeof(bcd)*2 - (bcd[0] & GSM_MI_ODD? 0:1).
Neels Hofmeyr7079e692018-12-05 21:02:36 +0100143 * \param[in] allow_hex If false, return error if there are digits other than 0-9. If true, return those as [A-F].
144 * \returns The strlen that would be written if the output buffer is large enough, excluding nul byte (like
145 * snprintf()), or -EINVAL if allow_hex is false and a digit > 9 is encountered. On -EINVAL, the conversion is
146 * still completed as if allow_hex were passed as true. Return -ENOMEM if dst is NULL or dst_size is zero.
147 * If end_nibble <= start_nibble, write an empty string to dst and return 0.
148 */
149int osmo_bcd2str(char *dst, size_t dst_size, const uint8_t *bcd, int start_nibble, int end_nibble, bool allow_hex)
150{
151 char *dst_end = dst + dst_size - 1;
152 int nibble_i;
153 int rc = 0;
154
155 if (!dst || dst_size < 1)
156 return -ENOMEM;
157
158 for (nibble_i = start_nibble; nibble_i < end_nibble && dst < dst_end; nibble_i++, dst++) {
159 uint8_t nibble = bcd[nibble_i >> 1];
160 if ((nibble_i & 1))
161 nibble >>= 4;
162 nibble &= 0xf;
163
164 if (!allow_hex && nibble > 9)
165 rc = -EINVAL;
166
167 *dst = osmo_bcd2char(nibble);
168 }
169 *dst = '\0';
170
171 if (rc < 0)
172 return rc;
173 return OSMO_MAX(0, end_nibble - start_nibble);
174}
175
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200176/*! Parse a string containing hexadecimal digits
Harald Weltede6e4982012-12-06 21:25:27 +0100177 * \param[in] str string containing ASCII encoded hexadecimal digits
178 * \param[out] b output buffer
179 * \param[in] max_len maximum space in output buffer
Neels Hofmeyr3de7b052015-09-23 23:16:53 +0200180 * \returns number of parsed octets, or -1 on error
Harald Weltede6e4982012-12-06 21:25:27 +0100181 */
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200182int osmo_hexparse(const char *str, uint8_t *b, int max_len)
Harald Welte3eba9912010-07-30 10:37:29 +0200183
184{
Neels Hofmeyr437ed4a2017-02-14 15:54:31 +0100185 char c;
186 uint8_t v;
187 const char *strpos;
188 unsigned int nibblepos = 0;
Harald Welte3eba9912010-07-30 10:37:29 +0200189
190 memset(b, 0x00, max_len);
191
Neels Hofmeyr437ed4a2017-02-14 15:54:31 +0100192 for (strpos = str; (c = *strpos); strpos++) {
193 /* skip whitespace */
194 if (c == ' ' || c == '\t' || c == '\n' || c == '\r')
195 continue;
196
197 /* If the buffer is too small, error out */
198 if (nibblepos >= (max_len << 1))
199 return -1;
200
Harald Welte3eba9912010-07-30 10:37:29 +0200201 if (c >= '0' && c <= '9')
202 v = c - '0';
203 else if (c >= 'a' && c <= 'f')
204 v = 10 + (c - 'a');
205 else if (c >= 'A' && c <= 'F')
206 v = 10 + (c - 'A');
207 else
208 return -1;
Neels Hofmeyr437ed4a2017-02-14 15:54:31 +0100209
210 b[nibblepos >> 1] |= v << (nibblepos & 1 ? 0 : 4);
211 nibblepos ++;
Harald Welte3eba9912010-07-30 10:37:29 +0200212 }
213
Neels Hofmeyr437ed4a2017-02-14 15:54:31 +0100214 /* In case of uneven amount of digits, the last byte is not complete
215 * and that's an error. */
216 if (nibblepos & 1)
217 return -1;
218
219 return nibblepos >> 1;
Harald Welte3eba9912010-07-30 10:37:29 +0200220}
Harald Welte40481e82010-07-30 11:40:32 +0200221
222static char hexd_buff[4096];
Nils O. SelÄsdal32447022014-01-02 14:04:43 +0100223static const char hex_chars[] = "0123456789abcdef";
Harald Welte40481e82010-07-30 11:40:32 +0200224
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100225/*! Convert binary sequence to hexadecimal ASCII string.
226 * \param[out] out_buf Output buffer to write the resulting string to.
227 * \param[in] out_buf_size sizeof(out_buf).
228 * \param[in] buf Input buffer, pointer to sequence of bytes.
229 * \param[in] len Length of input buf in number of bytes.
230 * \param[in] delim String to separate each byte; NULL or "" for no delim.
231 * \param[in] delim_after_last If true, end the string in delim (true: "1a:ef:d9:", false: "1a:ef:d9");
232 * if out_buf has insufficient space, the string will always end in a delim.
233 * \returns out_buf, containing a zero-terminated string, or "" (empty string) if out_buf == NULL or out_buf_size < 1.
234 *
235 * This function will print a sequence of bytes as hexadecimal numbers, adding one delim between each byte (e.g. for
236 * delim passed as ":", return a string like "1a:ef:d9").
237 *
238 * The delim_after_last argument exists to be able to exactly show the original osmo_hexdump() behavior, which always
239 * ends the string with a delimiter.
240 */
241const char *osmo_hexdump_buf(char *out_buf, size_t out_buf_size, const unsigned char *buf, int len, const char *delim,
242 bool delim_after_last)
Harald Welte40481e82010-07-30 11:40:32 +0200243{
244 int i;
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100245 char *cur = out_buf;
246 size_t delim_len;
Harald Welte40481e82010-07-30 11:40:32 +0200247
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100248 if (!out_buf || !out_buf_size)
249 return "";
250
251 delim = delim ? : "";
252 delim_len = strlen(delim);
253
Harald Welte40481e82010-07-30 11:40:32 +0200254 for (i = 0; i < len; i++) {
Nils O. SelÄsdal32447022014-01-02 14:04:43 +0100255 const char *delimp = delim;
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100256 int len_remain = out_buf_size - (cur - out_buf) - 1;
257 if (len_remain < (2 + delim_len)
258 && !(!delim_after_last && i == (len - 1) && len_remain >= 2))
Holger Hans Peter Freyther128d9e22011-07-15 16:07:23 +0200259 break;
Nils O. SelÄsdal32447022014-01-02 14:04:43 +0100260
261 *cur++ = hex_chars[buf[i] >> 4];
262 *cur++ = hex_chars[buf[i] & 0xf];
263
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100264 if (i == (len - 1) && !delim_after_last)
265 break;
266
Nils O. SelÄsdal32447022014-01-02 14:04:43 +0100267 while (len_remain > 1 && *delimp) {
268 *cur++ = *delimp++;
269 len_remain--;
270 }
Harald Welte40481e82010-07-30 11:40:32 +0200271 }
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100272 *cur = '\0';
273 return out_buf;
Harald Welte40481e82010-07-30 11:40:32 +0200274}
Harald Weltedee47cd2010-07-30 11:43:30 +0200275
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200276/*! Convert a sequence of unpacked bits to ASCII string
Harald Welte8598f182011-08-17 14:19:27 +0200277 * \param[in] bits A sequence of unpacked bits
278 * \param[in] len Length of bits
279 */
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200280char *osmo_ubit_dump(const uint8_t *bits, unsigned int len)
Harald Welte3d0ac5e2011-02-08 16:55:03 +0100281{
282 int i;
283
284 if (len > sizeof(hexd_buff)-1)
285 len = sizeof(hexd_buff)-1;
286 memset(hexd_buff, 0, sizeof(hexd_buff));
287
288 for (i = 0; i < len; i++) {
289 char outch;
290 switch (bits[i]) {
291 case 0:
292 outch = '0';
293 break;
294 case 0xff:
295 outch = '?';
296 break;
297 case 1:
298 outch = '1';
299 break;
300 default:
301 outch = 'E';
302 break;
303 }
304 hexd_buff[i] = outch;
305 }
306 hexd_buff[sizeof(hexd_buff)-1] = 0;
307 return hexd_buff;
308}
309
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200310/*! Convert binary sequence to hexadecimal ASCII string
Harald Welte8598f182011-08-17 14:19:27 +0200311 * \param[in] buf pointer to sequence of bytes
312 * \param[in] len length of buf in number of bytes
313 * \returns pointer to zero-terminated string
314 *
315 * This function will print a sequence of bytes as hexadecimal numbers,
316 * adding one space character between each byte (e.g. "1a ef d9")
Harald Welte096a6662017-10-16 14:33:11 +0200317 *
318 * The maximum size of the output buffer is 4096 bytes, i.e. the maximum
319 * number of input bytes that can be printed in one call is 1365!
Harald Welte8598f182011-08-17 14:19:27 +0200320 */
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200321char *osmo_hexdump(const unsigned char *buf, int len)
Harald Weltedee47cd2010-07-30 11:43:30 +0200322{
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100323 osmo_hexdump_buf(hexd_buff, sizeof(hexd_buff), buf, len, " ", true);
324 return hexd_buff;
Harald Weltedee47cd2010-07-30 11:43:30 +0200325}
326
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200327/*! Convert binary sequence to hexadecimal ASCII string
Harald Welte8598f182011-08-17 14:19:27 +0200328 * \param[in] buf pointer to sequence of bytes
329 * \param[in] len length of buf in number of bytes
330 * \returns pointer to zero-terminated string
331 *
332 * This function will print a sequence of bytes as hexadecimal numbers,
333 * without any space character between each byte (e.g. "1aefd9")
Harald Welte096a6662017-10-16 14:33:11 +0200334 *
335 * The maximum size of the output buffer is 4096 bytes, i.e. the maximum
336 * number of input bytes that can be printed in one call is 2048!
Harald Welte8598f182011-08-17 14:19:27 +0200337 */
Sylvain Munautff23d242011-11-10 23:03:18 +0100338char *osmo_hexdump_nospc(const unsigned char *buf, int len)
Harald Weltedee47cd2010-07-30 11:43:30 +0200339{
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100340 osmo_hexdump_buf(hexd_buff, sizeof(hexd_buff), buf, len, "", true);
341 return hexd_buff;
Harald Weltedee47cd2010-07-30 11:43:30 +0200342}
Harald Welte28222962011-02-18 20:37:04 +0100343
Holger Hans Peter Freyther9a1a5a12015-04-11 19:26:55 +0200344/* Compat with previous typo to preserve abi */
Sylvain Munaute55ae3a2011-11-11 23:06:55 +0100345char *osmo_osmo_hexdump_nospc(const unsigned char *buf, int len)
Holger Hans Peter Freyther9a1a5a12015-04-11 19:26:55 +0200346#if defined(__MACH__) && defined(__APPLE__)
347 ;
348#else
Sylvain Munaut17af41d2011-11-19 22:30:39 +0100349 __attribute__((weak, alias("osmo_hexdump_nospc")));
Holger Hans Peter Freyther9a1a5a12015-04-11 19:26:55 +0200350#endif
Sylvain Munaute55ae3a2011-11-11 23:06:55 +0100351
Harald Welte28222962011-02-18 20:37:04 +0100352#include "../config.h"
353#ifdef HAVE_CTYPE_H
354#include <ctype.h>
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200355/*! Convert an entire string to lower case
Harald Welte8598f182011-08-17 14:19:27 +0200356 * \param[out] out output string, caller-allocated
357 * \param[in] in input string
358 */
Harald Welte28222962011-02-18 20:37:04 +0100359void osmo_str2lower(char *out, const char *in)
360{
361 unsigned int i;
362
363 for (i = 0; i < strlen(in); i++)
Pau Espin Pedrol399a6f02017-06-18 14:07:37 +0200364 out[i] = tolower((const unsigned char)in[i]);
Harald Welte28222962011-02-18 20:37:04 +0100365 out[strlen(in)] = '\0';
366}
367
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200368/*! Convert an entire string to upper case
Harald Welte8598f182011-08-17 14:19:27 +0200369 * \param[out] out output string, caller-allocated
370 * \param[in] in input string
371 */
Harald Welte28222962011-02-18 20:37:04 +0100372void osmo_str2upper(char *out, const char *in)
373{
374 unsigned int i;
375
376 for (i = 0; i < strlen(in); i++)
Pau Espin Pedrol399a6f02017-06-18 14:07:37 +0200377 out[i] = toupper((const unsigned char)in[i]);
Harald Welte28222962011-02-18 20:37:04 +0100378 out[strlen(in)] = '\0';
379}
380#endif /* HAVE_CTYPE_H */
Harald Welte8598f182011-08-17 14:19:27 +0200381
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200382/*! Wishful thinking to generate a constant time compare
Harald Welte9709b2e2016-04-25 18:47:53 +0200383 * \param[in] exp Expected data
384 * \param[in] rel Comparison value
385 * \param[in] count Number of bytes to compare
386 * \returns 1 in case \a exp equals \a rel; zero otherwise
387 *
388 * Compare count bytes of exp to rel. Return 0 if they are identical, 1
389 * otherwise. Do not return a mismatch on the first mismatching byte,
390 * but always compare all bytes, regardless. The idea is that the amount of
391 * matching bytes cannot be inferred from the time the comparison took. */
392int osmo_constant_time_cmp(const uint8_t *exp, const uint8_t *rel, const int count)
393{
394 int x = 0, i;
395
396 for (i = 0; i < count; ++i)
397 x |= exp[i] ^ rel[i];
398
399 /* if x is zero, all data was identical */
400 return x? 1 : 0;
401}
402
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200403/*! Generic retrieval of 1..8 bytes as big-endian uint64_t
Harald Welte9709b2e2016-04-25 18:47:53 +0200404 * \param[in] data Input data as byte-array
405 * \param[in] data_len Length of \a data in octets
406 * \returns uint64_t of \a data interpreted as big-endian
407 *
408 * This is like osmo_load64be_ext, except that if data_len is less than
409 * sizeof(uint64_t), the data is interpreted as the least significant bytes
410 * (osmo_load64be_ext loads them as the most significant bytes into the
411 * returned uint64_t). In this way, any integer size up to 64 bits can be
412 * decoded conveniently by using sizeof(), without the need to call specific
413 * numbered functions (osmo_load16, 32, ...). */
414uint64_t osmo_decode_big_endian(const uint8_t *data, size_t data_len)
415{
416 uint64_t value = 0;
417
418 while (data_len > 0) {
419 value = (value << 8) + *data;
420 data += 1;
421 data_len -= 1;
422 }
423
424 return value;
425}
426
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200427/*! Generic big-endian encoding of big endian number up to 64bit
Harald Welte9709b2e2016-04-25 18:47:53 +0200428 * \param[in] value unsigned integer value to be stored
429 * \param[in] data_len number of octets
430 * \returns static buffer containing big-endian stored value
431 *
432 * This is like osmo_store64be_ext, except that this returns a static buffer of
433 * the result (for convenience, but not threadsafe). If data_len is less than
434 * sizeof(uint64_t), only the least significant bytes of value are encoded. */
435uint8_t *osmo_encode_big_endian(uint64_t value, size_t data_len)
436{
437 static uint8_t buf[sizeof(uint64_t)];
438 OSMO_ASSERT(data_len <= ARRAY_SIZE(buf));
439 osmo_store64be_ext(value, buf, data_len);
440 return buf;
441}
Harald Welteaeecc482016-11-26 10:41:40 +0100442
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200443/*! Copy a C-string into a sized buffer
Harald Welteaeecc482016-11-26 10:41:40 +0100444 * \param[in] src source string
445 * \param[out] dst destination string
Neels Hofmeyrdf83ece2017-01-13 13:55:43 +0100446 * \param[in] siz size of the \a dst buffer
447 * \returns length of \a src
Harald Welteaeecc482016-11-26 10:41:40 +0100448 *
Neels Hofmeyrdf83ece2017-01-13 13:55:43 +0100449 * Copy at most \a siz bytes from \a src to \a dst, ensuring that the result is
450 * NUL terminated. The NUL character is included in \a siz, i.e. passing the
451 * actual sizeof(*dst) is correct.
Harald Welteaeecc482016-11-26 10:41:40 +0100452 */
453size_t osmo_strlcpy(char *dst, const char *src, size_t siz)
454{
Neels Hofmeyrbcf9f232017-10-25 04:16:45 +0200455 size_t ret = src ? strlen(src) : 0;
Harald Welteaeecc482016-11-26 10:41:40 +0100456
457 if (siz) {
458 size_t len = (ret >= siz) ? siz - 1 : ret;
Neels Hofmeyrebd3cdd2017-11-18 23:07:38 +0100459 if (src)
460 memcpy(dst, src, len);
Harald Welteaeecc482016-11-26 10:41:40 +0100461 dst[len] = '\0';
462 }
463 return ret;
464}
Neels Hofmeyr0aeda1b2017-01-13 14:16:02 +0100465
Neels Hofmeyr4335bad2017-10-07 04:39:14 +0200466/*! Validate that a given string is a hex string within given size limits.
467 * Note that each hex digit amounts to a nibble, so if checking for a hex
468 * string to result in N bytes, pass amount of digits as 2*N.
469 * \param str A nul-terminated string to validate, or NULL.
470 * \param min_digits least permitted amount of digits.
471 * \param max_digits most permitted amount of digits.
472 * \param require_even if true, require an even amount of digits.
473 * \returns true when the hex_str contains only hexadecimal digits (no
474 * whitespace) and matches the requested length; also true
475 * when min_digits <= 0 and str is NULL.
476 */
477bool osmo_is_hexstr(const char *str, int min_digits, int max_digits,
478 bool require_even)
479{
480 int len;
481 /* Use unsigned char * to avoid a compiler warning of
482 * "error: array subscript has type 'char' [-Werror=char-subscripts]" */
483 const unsigned char *pos = (const unsigned char*)str;
484 if (!pos)
485 return min_digits < 1;
486 for (len = 0; *pos && len < max_digits; len++, pos++)
487 if (!isxdigit(*pos))
488 return false;
489 if (len < min_digits)
490 return false;
491 /* With not too many digits, we should have reached *str == nul */
492 if (*pos)
493 return false;
494 if (require_even && (len & 1))
495 return false;
Harald Weltefebe83c2017-10-03 17:41:59 +0800496
497 return true;
498}
499
500/*! Determine if a given identifier is valid, i.e. doesn't contain illegal chars
501 * \param[in] str String to validate
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100502 * \param[in] sep_chars Permitted separation characters between identifiers.
503 * \returns true in case \a str contains only valid identifiers and sep_chars, false otherwise
Harald Weltefebe83c2017-10-03 17:41:59 +0800504 */
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100505bool osmo_separated_identifiers_valid(const char *str, const char *sep_chars)
Harald Weltefebe83c2017-10-03 17:41:59 +0800506{
507 /* characters that are illegal in names */
508 static const char illegal_chars[] = "., {}[]()<>|~\\^`'\"?=;/+*&%$#!";
509 unsigned int i;
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100510 size_t len;
Harald Weltefebe83c2017-10-03 17:41:59 +0800511
512 /* an empty string is not a valid identifier */
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100513 if (!str || (len = strlen(str)) == 0)
Harald Weltefebe83c2017-10-03 17:41:59 +0800514 return false;
515
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100516 for (i = 0; i < len; i++) {
517 if (sep_chars && strchr(sep_chars, str[i]))
518 continue;
Harald Weltefebe83c2017-10-03 17:41:59 +0800519 /* check for 7-bit ASCII */
520 if (str[i] & 0x80)
521 return false;
Neels Hofmeyre5a2bdb2017-12-16 04:54:37 +0100522 if (!isprint((int)str[i]))
523 return false;
Harald Weltefebe83c2017-10-03 17:41:59 +0800524 /* check for some explicit reserved control characters */
525 if (strchr(illegal_chars, str[i]))
526 return false;
527 }
528
Neels Hofmeyr4335bad2017-10-07 04:39:14 +0200529 return true;
530}
531
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100532/*! Determine if a given identifier is valid, i.e. doesn't contain illegal chars
533 * \param[in] str String to validate
534 * \returns true in case \a str contains valid identifier, false otherwise
535 */
536bool osmo_identifier_valid(const char *str)
537{
538 return osmo_separated_identifiers_valid(str, NULL);
539}
540
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100541/*! Return the string with all non-printable characters escaped.
542 * \param[in] str A string that may contain any characters.
543 * \param[in] len Pass -1 to print until nul char, or >= 0 to force a length.
544 * \param[inout] buf string buffer to write escaped characters to.
545 * \param[in] bufsize size of \a buf.
546 * \returns buf containing an escaped representation, possibly truncated, or str itself.
547 */
548const char *osmo_escape_str_buf(const char *str, int in_len, char *buf, size_t bufsize)
549{
550 int in_pos = 0;
551 int next_unprintable = 0;
552 int out_pos = 0;
553 char *out = buf;
554 /* -1 to leave space for a final \0 */
555 int out_len = bufsize-1;
556
557 if (!str)
558 return "(null)";
559
560 if (in_len < 0)
561 in_len = strlen(str);
562
563 while (in_pos < in_len) {
564 for (next_unprintable = in_pos;
565 next_unprintable < in_len && isprint((int)str[next_unprintable])
566 && str[next_unprintable] != '"'
567 && str[next_unprintable] != '\\';
568 next_unprintable++);
569
570 if (next_unprintable == in_len
571 && in_pos == 0)
572 return str;
573
574 while (in_pos < next_unprintable && out_pos < out_len)
575 out[out_pos++] = str[in_pos++];
576
577 if (out_pos == out_len || in_pos == in_len)
578 goto done;
579
580 switch (str[next_unprintable]) {
581#define BACKSLASH_CASE(c, repr) \
582 case c: \
583 if (out_pos > out_len-2) \
584 goto done; \
585 out[out_pos++] = '\\'; \
586 out[out_pos++] = repr; \
587 break
588
589 BACKSLASH_CASE('\n', 'n');
590 BACKSLASH_CASE('\r', 'r');
591 BACKSLASH_CASE('\t', 't');
592 BACKSLASH_CASE('\0', '0');
593 BACKSLASH_CASE('\a', 'a');
594 BACKSLASH_CASE('\b', 'b');
595 BACKSLASH_CASE('\v', 'v');
596 BACKSLASH_CASE('\f', 'f');
597 BACKSLASH_CASE('\\', '\\');
598 BACKSLASH_CASE('"', '"');
599#undef BACKSLASH_CASE
600
601 default:
602 out_pos += snprintf(&out[out_pos], out_len - out_pos, "\\%u", (unsigned char)str[in_pos]);
603 if (out_pos > out_len) {
604 out_pos = out_len;
605 goto done;
606 }
607 break;
608 }
609 in_pos ++;
610 }
611
612done:
613 out[out_pos] = '\0';
614 return out;
615}
616
617/*! Return the string with all non-printable characters escaped.
618 * Call osmo_escape_str_buf() with a static buffer.
619 * \param[in] str A string that may contain any characters.
620 * \param[in] len Pass -1 to print until nul char, or >= 0 to force a length.
621 * \returns buf containing an escaped representation, possibly truncated, or str itself.
622 */
623const char *osmo_escape_str(const char *str, int in_len)
624{
625 return osmo_escape_str_buf(str, in_len, namebuf, sizeof(namebuf));
626}
627
Neels Hofmeyr04eb56f2018-04-09 00:41:28 +0200628/*! Like osmo_escape_str(), but returns double-quotes around a string, or "NULL" for a NULL string.
629 * This allows passing any char* value and get its C representation as string.
630 * \param[in] str A string that may contain any characters.
Neels Hofmeyr03e75532018-09-07 03:12:05 +0200631 * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length.
632 * \returns buf containing a quoted and escaped representation, possibly truncated.
Neels Hofmeyr04eb56f2018-04-09 00:41:28 +0200633 */
634const char *osmo_quote_str_buf(const char *str, int in_len, char *buf, size_t bufsize)
635{
636 const char *res;
637 int l;
638 if (!str)
639 return "NULL";
640 if (bufsize < 3)
641 return "<buf-too-small>";
642 buf[0] = '"';
643 res = osmo_escape_str_buf(str, in_len, buf + 1, bufsize - 2);
644 /* if osmo_escape_str_buf() returned the str itself, we need to copy it to buf to be able to
645 * quote it. */
646 if (res == str) {
647 /* max_len = bufsize - two quotes - nul term */
648 int max_len = bufsize - 2 - 1;
649 if (in_len >= 0)
650 max_len = OSMO_MIN(in_len, max_len);
651 /* It is not allowed to pass unterminated strings into osmo_strlcpy() :/ */
652 strncpy(buf + 1, str, max_len);
653 buf[1 + max_len] = '\0';
654 }
655 l = strlen(buf);
656 buf[l] = '"';
657 buf[l+1] = '\0'; /* both osmo_escape_str_buf() and max_len above ensure room for '\0' */
658 return buf;
659}
660
Neels Hofmeyr03e75532018-09-07 03:12:05 +0200661/*! Like osmo_quote_str_buf() but returns the result in a static buffer.
662 * The static buffer is shared with get_value_string() and osmo_escape_str().
663 * \param[in] str A string that may contain any characters.
664 * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length.
665 * \returns static buffer containing a quoted and escaped representation, possibly truncated.
666 */
Neels Hofmeyr04eb56f2018-04-09 00:41:28 +0200667const char *osmo_quote_str(const char *str, int in_len)
668{
669 return osmo_quote_str_buf(str, in_len, namebuf, sizeof(namebuf));
670}
671
Harald Welte15a5f8d2018-06-06 16:58:17 +0200672/*! perform an integer square root operation on unsigned 32bit integer.
673 * This implementation is taken from "Hacker's Delight" Figure 11-1 "Integer square root, Newton's
674 * method", which can also be found at http://www.hackersdelight.org/hdcodetxt/isqrt.c.txt */
675uint32_t osmo_isqrt32(uint32_t x)
676{
677 uint32_t x1;
678 int s, g0, g1;
679
680 if (x <= 1)
681 return x;
682
683 s = 1;
684 x1 = x - 1;
685 if (x1 > 0xffff) {
686 s = s + 8;
687 x1 = x1 >> 16;
688 }
689 if (x1 > 0xff) {
690 s = s + 4;
691 x1 = x1 >> 8;
692 }
693 if (x1 > 0xf) {
694 s = s + 2;
695 x1 = x1 >> 4;
696 }
697 if (x1 > 0x3) {
698 s = s + 1;
699 }
700
701 g0 = 1 << s; /* g0 = 2**s */
702 g1 = (g0 + (x >> s)) >> 1; /* g1 = (g0 + x/g0)/2 */
703
704 /* converges after four to five divisions for arguments up to 16,785,407 */
705 while (g1 < g0) {
706 g0 = g1;
707 g1 = (g0 + (x/g0)) >> 1;
708 }
709 return g0;
710}
711
Neels Hofmeyr7c749892018-09-07 03:01:38 +0200712/*! Convert a string to lowercase, while checking buffer size boundaries.
713 * The result written to \a dest is guaranteed to be nul terminated if \a dest_len > 0.
714 * If dest == src, the string is converted in-place, if necessary truncated at dest_len - 1 characters
715 * length as well as nul terminated.
716 * Note: similar osmo_str2lower(), but safe to use for src strings of arbitrary length.
717 * \param[out] dest Target buffer to write lowercase string.
718 * \param[in] dest_len Maximum buffer size of dest (e.g. sizeof(dest)).
719 * \param[in] src String to convert to lowercase.
720 * \returns Length of \a src, like osmo_strlcpy(), but if \a dest == \a src at most \a dest_len - 1.
721 */
722size_t osmo_str_tolower_buf(char *dest, size_t dest_len, const char *src)
723{
724 size_t rc;
725 if (dest == src) {
726 if (dest_len < 1)
727 return 0;
728 dest[dest_len - 1] = '\0';
729 rc = strlen(dest);
730 } else {
731 if (dest_len < 1)
732 return strlen(src);
733 rc = osmo_strlcpy(dest, src, dest_len);
734 }
735 for (; *dest; dest++)
736 *dest = tolower(*dest);
737 return rc;
738}
739
740/*! Convert a string to lowercase, using a static buffer.
741 * The resulting string may be truncated if the internally used static buffer is shorter than src.
742 * The internal buffer is at least 128 bytes long, i.e. guaranteed to hold at least 127 characters and a
743 * terminating nul.
744 * See also osmo_str_tolower_buf().
745 * \param[in] src String to convert to lowercase.
746 * \returns Resulting lowercase string in a static buffer, always nul terminated.
747 */
748const char *osmo_str_tolower(const char *src)
749{
750 static char buf[128];
751 osmo_str_tolower_buf(buf, sizeof(buf), src);
752 return buf;
753}
754
755/*! Convert a string to uppercase, while checking buffer size boundaries.
756 * The result written to \a dest is guaranteed to be nul terminated if \a dest_len > 0.
757 * If dest == src, the string is converted in-place, if necessary truncated at dest_len - 1 characters
758 * length as well as nul terminated.
759 * Note: similar osmo_str2upper(), but safe to use for src strings of arbitrary length.
760 * \param[out] dest Target buffer to write uppercase string.
761 * \param[in] dest_len Maximum buffer size of dest (e.g. sizeof(dest)).
762 * \param[in] src String to convert to uppercase.
763 * \returns Length of \a src, like osmo_strlcpy(), but if \a dest == \a src at most \a dest_len - 1.
764 */
765size_t osmo_str_toupper_buf(char *dest, size_t dest_len, const char *src)
766{
767 size_t rc;
768 if (dest == src) {
769 if (dest_len < 1)
770 return 0;
771 dest[dest_len - 1] = '\0';
772 rc = strlen(dest);
773 } else {
774 if (dest_len < 1)
775 return strlen(src);
776 rc = osmo_strlcpy(dest, src, dest_len);
777 }
778 for (; *dest; dest++)
779 *dest = toupper(*dest);
780 return rc;
781}
782
783/*! Convert a string to uppercase, using a static buffer.
784 * The resulting string may be truncated if the internally used static buffer is shorter than src.
785 * The internal buffer is at least 128 bytes long, i.e. guaranteed to hold at least 127 characters and a
786 * terminating nul.
787 * See also osmo_str_toupper_buf().
788 * \param[in] src String to convert to uppercase.
789 * \returns Resulting uppercase string in a static buffer, always nul terminated.
790 */
791const char *osmo_str_toupper(const char *src)
792{
793 static char buf[128];
794 osmo_str_toupper_buf(buf, sizeof(buf), src);
795 return buf;
796}
797
Oliver Smith894be2d2019-01-11 13:13:37 +0100798/*! Calculate the Luhn checksum (as used for IMEIs).
799 * \param[in] in Input digits in ASCII string representation.
800 * \param[in] in_len Count of digits to use for the input (14 for IMEI).
801 * \returns checksum char (e.g. '3'); negative on error
802 */
803const char osmo_luhn(const char* in, int in_len)
804{
805 int i, sum = 0;
806
807 /* All input must be numbers */
808 for (i = 0; i < in_len; i++) {
809 if (!isdigit(in[i]))
810 return -EINVAL;
811 }
812
813 /* Double every second digit and add it to sum */
814 for (i = in_len - 1; i >= 0; i -= 2) {
815 int dbl = (in[i] - '0') * 2;
816 if (dbl > 9)
817 dbl -= 9;
818 sum += dbl;
819 }
820
821 /* Add other digits to sum */
822 for (i = in_len - 2; i >= 0; i -= 2)
823 sum += in[i] - '0';
824
825 /* Final checksum */
826 return (sum * 9) % 10 + '0';
827}
828
Neels Hofmeyr0aeda1b2017-01-13 14:16:02 +0100829/*! @} */