blob: 0b2ed31d9792652eef2210814c9609b85db25f3d [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
76 for (i = 0;; i++) {
77 if (vs[i].value == 0 && vs[i].str == NULL)
78 break;
79 if (vs[i].value == val)
80 return vs[i].str;
81 }
Harald Welteb59f9352010-03-25 11:37:04 +080082
Neels Hofmeyr8d6dcd92016-06-06 18:05:23 +020083 return NULL;
Harald Welted284cd92010-03-01 21:58:31 +010084}
85
Neels Hofmeyr87e45502017-06-20 00:17:59 +020086/*! get numeric value for given human-readable string
Harald Welte8598f182011-08-17 14:19:27 +020087 * \param[in] vs Array of value_string tuples
88 * \param[in] str human-readable string
89 * \returns numeric value (>0) or negative numer in case of error
90 */
Harald Welted284cd92010-03-01 21:58:31 +010091int get_string_value(const struct value_string *vs, const char *str)
92{
93 int i;
94
95 for (i = 0;; i++) {
96 if (vs[i].value == 0 && vs[i].str == NULL)
97 break;
98 if (!strcasecmp(vs[i].str, str))
99 return vs[i].value;
100 }
101 return -EINVAL;
102}
Harald Weltea73e2f92010-03-04 10:50:32 +0100103
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200104/*! Convert BCD-encoded digit into printable character
Harald Welte8598f182011-08-17 14:19:27 +0200105 * \param[in] bcd A single BCD-encoded digit
106 * \returns single printable character
107 */
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200108char osmo_bcd2char(uint8_t bcd)
Harald Weltea73e2f92010-03-04 10:50:32 +0100109{
110 if (bcd < 0xa)
111 return '0' + bcd;
112 else
113 return 'A' + (bcd - 0xa);
114}
115
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200116/*! Convert number in ASCII to BCD value
Harald Weltede6e4982012-12-06 21:25:27 +0100117 * \param[in] c ASCII character
118 * \returns BCD encoded value of character
119 */
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200120uint8_t osmo_char2bcd(char c)
Harald Weltea73e2f92010-03-04 10:50:32 +0100121{
Harald Weltefa8983d2017-10-27 16:52:59 +0200122 if (c >= '0' && c <= '9')
123 return c - 0x30;
124 else if (c >= 'A' && c <= 'F')
125 return 0xa + (c - 'A');
126 else if (c >= 'a' && c <= 'f')
127 return 0xa + (c - 'a');
128 else
129 return 0;
Harald Weltea73e2f92010-03-04 10:50:32 +0100130}
Harald Welte3eba9912010-07-30 10:37:29 +0200131
Neels Hofmeyr7079e692018-12-05 21:02:36 +0100132/*! Convert BCD to string.
133 * The given nibble offsets are interpreted in BCD order, i.e. nibble 0 is bcd[0] & 0xf, nibble 1 is bcd[0] >> 4, nibble
134 * 3 is bcd[1] & 0xf, etc..
135 * \param[out] dst Output string buffer, is always nul terminated when dst_size > 0.
136 * \param[in] dst_size sizeof() the output string buffer.
137 * \param[in] bcd Binary coded data buffer.
138 * \param[in] start_nibble Offset to start from, in nibbles, typically 1 to skip the first nibble.
Neels Hofmeyr48b2de02018-12-11 02:13:57 +0100139 * \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 +0100140 * \param[in] allow_hex If false, return error if there are digits other than 0-9. If true, return those as [A-F].
141 * \returns The strlen that would be written if the output buffer is large enough, excluding nul byte (like
142 * snprintf()), or -EINVAL if allow_hex is false and a digit > 9 is encountered. On -EINVAL, the conversion is
143 * still completed as if allow_hex were passed as true. Return -ENOMEM if dst is NULL or dst_size is zero.
144 * If end_nibble <= start_nibble, write an empty string to dst and return 0.
145 */
146int osmo_bcd2str(char *dst, size_t dst_size, const uint8_t *bcd, int start_nibble, int end_nibble, bool allow_hex)
147{
148 char *dst_end = dst + dst_size - 1;
149 int nibble_i;
150 int rc = 0;
151
152 if (!dst || dst_size < 1)
153 return -ENOMEM;
154
155 for (nibble_i = start_nibble; nibble_i < end_nibble && dst < dst_end; nibble_i++, dst++) {
156 uint8_t nibble = bcd[nibble_i >> 1];
157 if ((nibble_i & 1))
158 nibble >>= 4;
159 nibble &= 0xf;
160
161 if (!allow_hex && nibble > 9)
162 rc = -EINVAL;
163
164 *dst = osmo_bcd2char(nibble);
165 }
166 *dst = '\0';
167
168 if (rc < 0)
169 return rc;
170 return OSMO_MAX(0, end_nibble - start_nibble);
171}
172
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200173/*! Parse a string containing hexadecimal digits
Harald Weltede6e4982012-12-06 21:25:27 +0100174 * \param[in] str string containing ASCII encoded hexadecimal digits
175 * \param[out] b output buffer
176 * \param[in] max_len maximum space in output buffer
Neels Hofmeyr3de7b052015-09-23 23:16:53 +0200177 * \returns number of parsed octets, or -1 on error
Harald Weltede6e4982012-12-06 21:25:27 +0100178 */
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200179int osmo_hexparse(const char *str, uint8_t *b, int max_len)
Harald Welte3eba9912010-07-30 10:37:29 +0200180
181{
Neels Hofmeyr437ed4a2017-02-14 15:54:31 +0100182 char c;
183 uint8_t v;
184 const char *strpos;
185 unsigned int nibblepos = 0;
Harald Welte3eba9912010-07-30 10:37:29 +0200186
187 memset(b, 0x00, max_len);
188
Neels Hofmeyr437ed4a2017-02-14 15:54:31 +0100189 for (strpos = str; (c = *strpos); strpos++) {
190 /* skip whitespace */
191 if (c == ' ' || c == '\t' || c == '\n' || c == '\r')
192 continue;
193
194 /* If the buffer is too small, error out */
195 if (nibblepos >= (max_len << 1))
196 return -1;
197
Harald Welte3eba9912010-07-30 10:37:29 +0200198 if (c >= '0' && c <= '9')
199 v = c - '0';
200 else if (c >= 'a' && c <= 'f')
201 v = 10 + (c - 'a');
202 else if (c >= 'A' && c <= 'F')
203 v = 10 + (c - 'A');
204 else
205 return -1;
Neels Hofmeyr437ed4a2017-02-14 15:54:31 +0100206
207 b[nibblepos >> 1] |= v << (nibblepos & 1 ? 0 : 4);
208 nibblepos ++;
Harald Welte3eba9912010-07-30 10:37:29 +0200209 }
210
Neels Hofmeyr437ed4a2017-02-14 15:54:31 +0100211 /* In case of uneven amount of digits, the last byte is not complete
212 * and that's an error. */
213 if (nibblepos & 1)
214 return -1;
215
216 return nibblepos >> 1;
Harald Welte3eba9912010-07-30 10:37:29 +0200217}
Harald Welte40481e82010-07-30 11:40:32 +0200218
219static char hexd_buff[4096];
Nils O. SelÄsdal32447022014-01-02 14:04:43 +0100220static const char hex_chars[] = "0123456789abcdef";
Harald Welte40481e82010-07-30 11:40:32 +0200221
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100222/*! Convert binary sequence to hexadecimal ASCII string.
223 * \param[out] out_buf Output buffer to write the resulting string to.
224 * \param[in] out_buf_size sizeof(out_buf).
225 * \param[in] buf Input buffer, pointer to sequence of bytes.
226 * \param[in] len Length of input buf in number of bytes.
227 * \param[in] delim String to separate each byte; NULL or "" for no delim.
228 * \param[in] delim_after_last If true, end the string in delim (true: "1a:ef:d9:", false: "1a:ef:d9");
229 * if out_buf has insufficient space, the string will always end in a delim.
230 * \returns out_buf, containing a zero-terminated string, or "" (empty string) if out_buf == NULL or out_buf_size < 1.
231 *
232 * This function will print a sequence of bytes as hexadecimal numbers, adding one delim between each byte (e.g. for
233 * delim passed as ":", return a string like "1a:ef:d9").
234 *
235 * The delim_after_last argument exists to be able to exactly show the original osmo_hexdump() behavior, which always
236 * ends the string with a delimiter.
237 */
238const char *osmo_hexdump_buf(char *out_buf, size_t out_buf_size, const unsigned char *buf, int len, const char *delim,
239 bool delim_after_last)
Harald Welte40481e82010-07-30 11:40:32 +0200240{
241 int i;
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100242 char *cur = out_buf;
243 size_t delim_len;
Harald Welte40481e82010-07-30 11:40:32 +0200244
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100245 if (!out_buf || !out_buf_size)
246 return "";
247
248 delim = delim ? : "";
249 delim_len = strlen(delim);
250
Harald Welte40481e82010-07-30 11:40:32 +0200251 for (i = 0; i < len; i++) {
Nils O. SelÄsdal32447022014-01-02 14:04:43 +0100252 const char *delimp = delim;
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100253 int len_remain = out_buf_size - (cur - out_buf) - 1;
254 if (len_remain < (2 + delim_len)
255 && !(!delim_after_last && i == (len - 1) && len_remain >= 2))
Holger Hans Peter Freyther128d9e22011-07-15 16:07:23 +0200256 break;
Nils O. SelÄsdal32447022014-01-02 14:04:43 +0100257
258 *cur++ = hex_chars[buf[i] >> 4];
259 *cur++ = hex_chars[buf[i] & 0xf];
260
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100261 if (i == (len - 1) && !delim_after_last)
262 break;
263
Nils O. SelÄsdal32447022014-01-02 14:04:43 +0100264 while (len_remain > 1 && *delimp) {
265 *cur++ = *delimp++;
266 len_remain--;
267 }
Harald Welte40481e82010-07-30 11:40:32 +0200268 }
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100269 *cur = '\0';
270 return out_buf;
Harald Welte40481e82010-07-30 11:40:32 +0200271}
Harald Weltedee47cd2010-07-30 11:43:30 +0200272
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200273/*! Convert a sequence of unpacked bits to ASCII string
Harald Welte8598f182011-08-17 14:19:27 +0200274 * \param[in] bits A sequence of unpacked bits
275 * \param[in] len Length of bits
276 */
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200277char *osmo_ubit_dump(const uint8_t *bits, unsigned int len)
Harald Welte3d0ac5e2011-02-08 16:55:03 +0100278{
279 int i;
280
281 if (len > sizeof(hexd_buff)-1)
282 len = sizeof(hexd_buff)-1;
283 memset(hexd_buff, 0, sizeof(hexd_buff));
284
285 for (i = 0; i < len; i++) {
286 char outch;
287 switch (bits[i]) {
288 case 0:
289 outch = '0';
290 break;
291 case 0xff:
292 outch = '?';
293 break;
294 case 1:
295 outch = '1';
296 break;
297 default:
298 outch = 'E';
299 break;
300 }
301 hexd_buff[i] = outch;
302 }
303 hexd_buff[sizeof(hexd_buff)-1] = 0;
304 return hexd_buff;
305}
306
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200307/*! Convert binary sequence to hexadecimal ASCII string
Harald Welte8598f182011-08-17 14:19:27 +0200308 * \param[in] buf pointer to sequence of bytes
309 * \param[in] len length of buf in number of bytes
310 * \returns pointer to zero-terminated string
311 *
312 * This function will print a sequence of bytes as hexadecimal numbers,
313 * adding one space character between each byte (e.g. "1a ef d9")
Harald Welte096a6662017-10-16 14:33:11 +0200314 *
315 * The maximum size of the output buffer is 4096 bytes, i.e. the maximum
316 * number of input bytes that can be printed in one call is 1365!
Harald Welte8598f182011-08-17 14:19:27 +0200317 */
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200318char *osmo_hexdump(const unsigned char *buf, int len)
Harald Weltedee47cd2010-07-30 11:43:30 +0200319{
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100320 osmo_hexdump_buf(hexd_buff, sizeof(hexd_buff), buf, len, " ", true);
321 return hexd_buff;
Harald Weltedee47cd2010-07-30 11:43:30 +0200322}
323
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200324/*! Convert binary sequence to hexadecimal ASCII string
Harald Welte8598f182011-08-17 14:19:27 +0200325 * \param[in] buf pointer to sequence of bytes
326 * \param[in] len length of buf in number of bytes
327 * \returns pointer to zero-terminated string
328 *
329 * This function will print a sequence of bytes as hexadecimal numbers,
330 * without any space character between each byte (e.g. "1aefd9")
Harald Welte096a6662017-10-16 14:33:11 +0200331 *
332 * The maximum size of the output buffer is 4096 bytes, i.e. the maximum
333 * number of input bytes that can be printed in one call is 2048!
Harald Welte8598f182011-08-17 14:19:27 +0200334 */
Sylvain Munautff23d242011-11-10 23:03:18 +0100335char *osmo_hexdump_nospc(const unsigned char *buf, int len)
Harald Weltedee47cd2010-07-30 11:43:30 +0200336{
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100337 osmo_hexdump_buf(hexd_buff, sizeof(hexd_buff), buf, len, "", true);
338 return hexd_buff;
Harald Weltedee47cd2010-07-30 11:43:30 +0200339}
Harald Welte28222962011-02-18 20:37:04 +0100340
Holger Hans Peter Freyther9a1a5a12015-04-11 19:26:55 +0200341/* Compat with previous typo to preserve abi */
Sylvain Munaute55ae3a2011-11-11 23:06:55 +0100342char *osmo_osmo_hexdump_nospc(const unsigned char *buf, int len)
Holger Hans Peter Freyther9a1a5a12015-04-11 19:26:55 +0200343#if defined(__MACH__) && defined(__APPLE__)
344 ;
345#else
Sylvain Munaut17af41d2011-11-19 22:30:39 +0100346 __attribute__((weak, alias("osmo_hexdump_nospc")));
Holger Hans Peter Freyther9a1a5a12015-04-11 19:26:55 +0200347#endif
Sylvain Munaute55ae3a2011-11-11 23:06:55 +0100348
Harald Welte28222962011-02-18 20:37:04 +0100349#include "../config.h"
350#ifdef HAVE_CTYPE_H
351#include <ctype.h>
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200352/*! Convert an entire string to lower case
Harald Welte8598f182011-08-17 14:19:27 +0200353 * \param[out] out output string, caller-allocated
354 * \param[in] in input string
355 */
Harald Welte28222962011-02-18 20:37:04 +0100356void osmo_str2lower(char *out, const char *in)
357{
358 unsigned int i;
359
360 for (i = 0; i < strlen(in); i++)
Pau Espin Pedrol399a6f02017-06-18 14:07:37 +0200361 out[i] = tolower((const unsigned char)in[i]);
Harald Welte28222962011-02-18 20:37:04 +0100362 out[strlen(in)] = '\0';
363}
364
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200365/*! Convert an entire string to upper case
Harald Welte8598f182011-08-17 14:19:27 +0200366 * \param[out] out output string, caller-allocated
367 * \param[in] in input string
368 */
Harald Welte28222962011-02-18 20:37:04 +0100369void osmo_str2upper(char *out, const char *in)
370{
371 unsigned int i;
372
373 for (i = 0; i < strlen(in); i++)
Pau Espin Pedrol399a6f02017-06-18 14:07:37 +0200374 out[i] = toupper((const unsigned char)in[i]);
Harald Welte28222962011-02-18 20:37:04 +0100375 out[strlen(in)] = '\0';
376}
377#endif /* HAVE_CTYPE_H */
Harald Welte8598f182011-08-17 14:19:27 +0200378
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200379/*! Wishful thinking to generate a constant time compare
Harald Welte9709b2e2016-04-25 18:47:53 +0200380 * \param[in] exp Expected data
381 * \param[in] rel Comparison value
382 * \param[in] count Number of bytes to compare
383 * \returns 1 in case \a exp equals \a rel; zero otherwise
384 *
385 * Compare count bytes of exp to rel. Return 0 if they are identical, 1
386 * otherwise. Do not return a mismatch on the first mismatching byte,
387 * but always compare all bytes, regardless. The idea is that the amount of
388 * matching bytes cannot be inferred from the time the comparison took. */
389int osmo_constant_time_cmp(const uint8_t *exp, const uint8_t *rel, const int count)
390{
391 int x = 0, i;
392
393 for (i = 0; i < count; ++i)
394 x |= exp[i] ^ rel[i];
395
396 /* if x is zero, all data was identical */
397 return x? 1 : 0;
398}
399
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200400/*! Generic retrieval of 1..8 bytes as big-endian uint64_t
Harald Welte9709b2e2016-04-25 18:47:53 +0200401 * \param[in] data Input data as byte-array
402 * \param[in] data_len Length of \a data in octets
403 * \returns uint64_t of \a data interpreted as big-endian
404 *
405 * This is like osmo_load64be_ext, except that if data_len is less than
406 * sizeof(uint64_t), the data is interpreted as the least significant bytes
407 * (osmo_load64be_ext loads them as the most significant bytes into the
408 * returned uint64_t). In this way, any integer size up to 64 bits can be
409 * decoded conveniently by using sizeof(), without the need to call specific
410 * numbered functions (osmo_load16, 32, ...). */
411uint64_t osmo_decode_big_endian(const uint8_t *data, size_t data_len)
412{
413 uint64_t value = 0;
414
415 while (data_len > 0) {
416 value = (value << 8) + *data;
417 data += 1;
418 data_len -= 1;
419 }
420
421 return value;
422}
423
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200424/*! Generic big-endian encoding of big endian number up to 64bit
Harald Welte9709b2e2016-04-25 18:47:53 +0200425 * \param[in] value unsigned integer value to be stored
426 * \param[in] data_len number of octets
427 * \returns static buffer containing big-endian stored value
428 *
429 * This is like osmo_store64be_ext, except that this returns a static buffer of
430 * the result (for convenience, but not threadsafe). If data_len is less than
431 * sizeof(uint64_t), only the least significant bytes of value are encoded. */
432uint8_t *osmo_encode_big_endian(uint64_t value, size_t data_len)
433{
434 static uint8_t buf[sizeof(uint64_t)];
435 OSMO_ASSERT(data_len <= ARRAY_SIZE(buf));
436 osmo_store64be_ext(value, buf, data_len);
437 return buf;
438}
Harald Welteaeecc482016-11-26 10:41:40 +0100439
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200440/*! Copy a C-string into a sized buffer
Harald Welteaeecc482016-11-26 10:41:40 +0100441 * \param[in] src source string
442 * \param[out] dst destination string
Neels Hofmeyrdf83ece2017-01-13 13:55:43 +0100443 * \param[in] siz size of the \a dst buffer
444 * \returns length of \a src
Harald Welteaeecc482016-11-26 10:41:40 +0100445 *
Neels Hofmeyrdf83ece2017-01-13 13:55:43 +0100446 * Copy at most \a siz bytes from \a src to \a dst, ensuring that the result is
447 * NUL terminated. The NUL character is included in \a siz, i.e. passing the
448 * actual sizeof(*dst) is correct.
Harald Welteaeecc482016-11-26 10:41:40 +0100449 */
450size_t osmo_strlcpy(char *dst, const char *src, size_t siz)
451{
Neels Hofmeyrbcf9f232017-10-25 04:16:45 +0200452 size_t ret = src ? strlen(src) : 0;
Harald Welteaeecc482016-11-26 10:41:40 +0100453
454 if (siz) {
455 size_t len = (ret >= siz) ? siz - 1 : ret;
Neels Hofmeyrebd3cdd2017-11-18 23:07:38 +0100456 if (src)
457 memcpy(dst, src, len);
Harald Welteaeecc482016-11-26 10:41:40 +0100458 dst[len] = '\0';
459 }
460 return ret;
461}
Neels Hofmeyr0aeda1b2017-01-13 14:16:02 +0100462
Neels Hofmeyr4335bad2017-10-07 04:39:14 +0200463/*! Validate that a given string is a hex string within given size limits.
464 * Note that each hex digit amounts to a nibble, so if checking for a hex
465 * string to result in N bytes, pass amount of digits as 2*N.
466 * \param str A nul-terminated string to validate, or NULL.
467 * \param min_digits least permitted amount of digits.
468 * \param max_digits most permitted amount of digits.
469 * \param require_even if true, require an even amount of digits.
470 * \returns true when the hex_str contains only hexadecimal digits (no
471 * whitespace) and matches the requested length; also true
472 * when min_digits <= 0 and str is NULL.
473 */
474bool osmo_is_hexstr(const char *str, int min_digits, int max_digits,
475 bool require_even)
476{
477 int len;
478 /* Use unsigned char * to avoid a compiler warning of
479 * "error: array subscript has type 'char' [-Werror=char-subscripts]" */
480 const unsigned char *pos = (const unsigned char*)str;
481 if (!pos)
482 return min_digits < 1;
483 for (len = 0; *pos && len < max_digits; len++, pos++)
484 if (!isxdigit(*pos))
485 return false;
486 if (len < min_digits)
487 return false;
488 /* With not too many digits, we should have reached *str == nul */
489 if (*pos)
490 return false;
491 if (require_even && (len & 1))
492 return false;
Harald Weltefebe83c2017-10-03 17:41:59 +0800493
494 return true;
495}
496
497/*! Determine if a given identifier is valid, i.e. doesn't contain illegal chars
498 * \param[in] str String to validate
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100499 * \param[in] sep_chars Permitted separation characters between identifiers.
500 * \returns true in case \a str contains only valid identifiers and sep_chars, false otherwise
Harald Weltefebe83c2017-10-03 17:41:59 +0800501 */
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100502bool osmo_separated_identifiers_valid(const char *str, const char *sep_chars)
Harald Weltefebe83c2017-10-03 17:41:59 +0800503{
504 /* characters that are illegal in names */
505 static const char illegal_chars[] = "., {}[]()<>|~\\^`'\"?=;/+*&%$#!";
506 unsigned int i;
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100507 size_t len;
Harald Weltefebe83c2017-10-03 17:41:59 +0800508
509 /* an empty string is not a valid identifier */
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100510 if (!str || (len = strlen(str)) == 0)
Harald Weltefebe83c2017-10-03 17:41:59 +0800511 return false;
512
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100513 for (i = 0; i < len; i++) {
514 if (sep_chars && strchr(sep_chars, str[i]))
515 continue;
Harald Weltefebe83c2017-10-03 17:41:59 +0800516 /* check for 7-bit ASCII */
517 if (str[i] & 0x80)
518 return false;
Neels Hofmeyre5a2bdb2017-12-16 04:54:37 +0100519 if (!isprint((int)str[i]))
520 return false;
Harald Weltefebe83c2017-10-03 17:41:59 +0800521 /* check for some explicit reserved control characters */
522 if (strchr(illegal_chars, str[i]))
523 return false;
524 }
525
Neels Hofmeyr4335bad2017-10-07 04:39:14 +0200526 return true;
527}
528
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100529/*! Determine if a given identifier is valid, i.e. doesn't contain illegal chars
530 * \param[in] str String to validate
531 * \returns true in case \a str contains valid identifier, false otherwise
532 */
533bool osmo_identifier_valid(const char *str)
534{
535 return osmo_separated_identifiers_valid(str, NULL);
536}
537
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100538/*! Return the string with all non-printable characters escaped.
539 * \param[in] str A string that may contain any characters.
540 * \param[in] len Pass -1 to print until nul char, or >= 0 to force a length.
541 * \param[inout] buf string buffer to write escaped characters to.
542 * \param[in] bufsize size of \a buf.
543 * \returns buf containing an escaped representation, possibly truncated, or str itself.
544 */
545const char *osmo_escape_str_buf(const char *str, int in_len, char *buf, size_t bufsize)
546{
547 int in_pos = 0;
548 int next_unprintable = 0;
549 int out_pos = 0;
550 char *out = buf;
551 /* -1 to leave space for a final \0 */
552 int out_len = bufsize-1;
553
554 if (!str)
555 return "(null)";
556
557 if (in_len < 0)
558 in_len = strlen(str);
559
560 while (in_pos < in_len) {
561 for (next_unprintable = in_pos;
562 next_unprintable < in_len && isprint((int)str[next_unprintable])
563 && str[next_unprintable] != '"'
564 && str[next_unprintable] != '\\';
565 next_unprintable++);
566
567 if (next_unprintable == in_len
568 && in_pos == 0)
569 return str;
570
571 while (in_pos < next_unprintable && out_pos < out_len)
572 out[out_pos++] = str[in_pos++];
573
574 if (out_pos == out_len || in_pos == in_len)
575 goto done;
576
577 switch (str[next_unprintable]) {
578#define BACKSLASH_CASE(c, repr) \
579 case c: \
580 if (out_pos > out_len-2) \
581 goto done; \
582 out[out_pos++] = '\\'; \
583 out[out_pos++] = repr; \
584 break
585
586 BACKSLASH_CASE('\n', 'n');
587 BACKSLASH_CASE('\r', 'r');
588 BACKSLASH_CASE('\t', 't');
589 BACKSLASH_CASE('\0', '0');
590 BACKSLASH_CASE('\a', 'a');
591 BACKSLASH_CASE('\b', 'b');
592 BACKSLASH_CASE('\v', 'v');
593 BACKSLASH_CASE('\f', 'f');
594 BACKSLASH_CASE('\\', '\\');
595 BACKSLASH_CASE('"', '"');
596#undef BACKSLASH_CASE
597
598 default:
599 out_pos += snprintf(&out[out_pos], out_len - out_pos, "\\%u", (unsigned char)str[in_pos]);
600 if (out_pos > out_len) {
601 out_pos = out_len;
602 goto done;
603 }
604 break;
605 }
606 in_pos ++;
607 }
608
609done:
610 out[out_pos] = '\0';
611 return out;
612}
613
614/*! Return the string with all non-printable characters escaped.
615 * Call osmo_escape_str_buf() with a static buffer.
616 * \param[in] str A string that may contain any characters.
617 * \param[in] len Pass -1 to print until nul char, or >= 0 to force a length.
618 * \returns buf containing an escaped representation, possibly truncated, or str itself.
619 */
620const char *osmo_escape_str(const char *str, int in_len)
621{
622 return osmo_escape_str_buf(str, in_len, namebuf, sizeof(namebuf));
623}
624
Neels Hofmeyr04eb56f2018-04-09 00:41:28 +0200625/*! Like osmo_escape_str(), but returns double-quotes around a string, or "NULL" for a NULL string.
626 * This allows passing any char* value and get its C representation as string.
627 * \param[in] str A string that may contain any characters.
Neels Hofmeyr03e75532018-09-07 03:12:05 +0200628 * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length.
629 * \returns buf containing a quoted and escaped representation, possibly truncated.
Neels Hofmeyr04eb56f2018-04-09 00:41:28 +0200630 */
631const char *osmo_quote_str_buf(const char *str, int in_len, char *buf, size_t bufsize)
632{
633 const char *res;
634 int l;
635 if (!str)
636 return "NULL";
637 if (bufsize < 3)
638 return "<buf-too-small>";
639 buf[0] = '"';
640 res = osmo_escape_str_buf(str, in_len, buf + 1, bufsize - 2);
641 /* if osmo_escape_str_buf() returned the str itself, we need to copy it to buf to be able to
642 * quote it. */
643 if (res == str) {
644 /* max_len = bufsize - two quotes - nul term */
645 int max_len = bufsize - 2 - 1;
646 if (in_len >= 0)
647 max_len = OSMO_MIN(in_len, max_len);
648 /* It is not allowed to pass unterminated strings into osmo_strlcpy() :/ */
649 strncpy(buf + 1, str, max_len);
650 buf[1 + max_len] = '\0';
651 }
652 l = strlen(buf);
653 buf[l] = '"';
654 buf[l+1] = '\0'; /* both osmo_escape_str_buf() and max_len above ensure room for '\0' */
655 return buf;
656}
657
Neels Hofmeyr03e75532018-09-07 03:12:05 +0200658/*! Like osmo_quote_str_buf() but returns the result in a static buffer.
659 * The static buffer is shared with get_value_string() and osmo_escape_str().
660 * \param[in] str A string that may contain any characters.
661 * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length.
662 * \returns static buffer containing a quoted and escaped representation, possibly truncated.
663 */
Neels Hofmeyr04eb56f2018-04-09 00:41:28 +0200664const char *osmo_quote_str(const char *str, int in_len)
665{
666 return osmo_quote_str_buf(str, in_len, namebuf, sizeof(namebuf));
667}
668
Harald Welte15a5f8d2018-06-06 16:58:17 +0200669/*! perform an integer square root operation on unsigned 32bit integer.
670 * This implementation is taken from "Hacker's Delight" Figure 11-1 "Integer square root, Newton's
671 * method", which can also be found at http://www.hackersdelight.org/hdcodetxt/isqrt.c.txt */
672uint32_t osmo_isqrt32(uint32_t x)
673{
674 uint32_t x1;
675 int s, g0, g1;
676
677 if (x <= 1)
678 return x;
679
680 s = 1;
681 x1 = x - 1;
682 if (x1 > 0xffff) {
683 s = s + 8;
684 x1 = x1 >> 16;
685 }
686 if (x1 > 0xff) {
687 s = s + 4;
688 x1 = x1 >> 8;
689 }
690 if (x1 > 0xf) {
691 s = s + 2;
692 x1 = x1 >> 4;
693 }
694 if (x1 > 0x3) {
695 s = s + 1;
696 }
697
698 g0 = 1 << s; /* g0 = 2**s */
699 g1 = (g0 + (x >> s)) >> 1; /* g1 = (g0 + x/g0)/2 */
700
701 /* converges after four to five divisions for arguments up to 16,785,407 */
702 while (g1 < g0) {
703 g0 = g1;
704 g1 = (g0 + (x/g0)) >> 1;
705 }
706 return g0;
707}
708
Neels Hofmeyr7c749892018-09-07 03:01:38 +0200709/*! Convert a string to lowercase, while checking buffer size boundaries.
710 * The result written to \a dest is guaranteed to be nul terminated if \a dest_len > 0.
711 * If dest == src, the string is converted in-place, if necessary truncated at dest_len - 1 characters
712 * length as well as nul terminated.
713 * Note: similar osmo_str2lower(), but safe to use for src strings of arbitrary length.
714 * \param[out] dest Target buffer to write lowercase string.
715 * \param[in] dest_len Maximum buffer size of dest (e.g. sizeof(dest)).
716 * \param[in] src String to convert to lowercase.
717 * \returns Length of \a src, like osmo_strlcpy(), but if \a dest == \a src at most \a dest_len - 1.
718 */
719size_t osmo_str_tolower_buf(char *dest, size_t dest_len, const char *src)
720{
721 size_t rc;
722 if (dest == src) {
723 if (dest_len < 1)
724 return 0;
725 dest[dest_len - 1] = '\0';
726 rc = strlen(dest);
727 } else {
728 if (dest_len < 1)
729 return strlen(src);
730 rc = osmo_strlcpy(dest, src, dest_len);
731 }
732 for (; *dest; dest++)
733 *dest = tolower(*dest);
734 return rc;
735}
736
737/*! Convert a string to lowercase, using a static buffer.
738 * The resulting string may be truncated if the internally used static buffer is shorter than src.
739 * The internal buffer is at least 128 bytes long, i.e. guaranteed to hold at least 127 characters and a
740 * terminating nul.
741 * See also osmo_str_tolower_buf().
742 * \param[in] src String to convert to lowercase.
743 * \returns Resulting lowercase string in a static buffer, always nul terminated.
744 */
745const char *osmo_str_tolower(const char *src)
746{
747 static char buf[128];
748 osmo_str_tolower_buf(buf, sizeof(buf), src);
749 return buf;
750}
751
752/*! Convert a string to uppercase, while checking buffer size boundaries.
753 * The result written to \a dest is guaranteed to be nul terminated if \a dest_len > 0.
754 * If dest == src, the string is converted in-place, if necessary truncated at dest_len - 1 characters
755 * length as well as nul terminated.
756 * Note: similar osmo_str2upper(), but safe to use for src strings of arbitrary length.
757 * \param[out] dest Target buffer to write uppercase string.
758 * \param[in] dest_len Maximum buffer size of dest (e.g. sizeof(dest)).
759 * \param[in] src String to convert to uppercase.
760 * \returns Length of \a src, like osmo_strlcpy(), but if \a dest == \a src at most \a dest_len - 1.
761 */
762size_t osmo_str_toupper_buf(char *dest, size_t dest_len, const char *src)
763{
764 size_t rc;
765 if (dest == src) {
766 if (dest_len < 1)
767 return 0;
768 dest[dest_len - 1] = '\0';
769 rc = strlen(dest);
770 } else {
771 if (dest_len < 1)
772 return strlen(src);
773 rc = osmo_strlcpy(dest, src, dest_len);
774 }
775 for (; *dest; dest++)
776 *dest = toupper(*dest);
777 return rc;
778}
779
780/*! Convert a string to uppercase, using a static buffer.
781 * The resulting string may be truncated if the internally used static buffer is shorter than src.
782 * The internal buffer is at least 128 bytes long, i.e. guaranteed to hold at least 127 characters and a
783 * terminating nul.
784 * See also osmo_str_toupper_buf().
785 * \param[in] src String to convert to uppercase.
786 * \returns Resulting uppercase string in a static buffer, always nul terminated.
787 */
788const char *osmo_str_toupper(const char *src)
789{
790 static char buf[128];
791 osmo_str_toupper_buf(buf, sizeof(buf), src);
792 return buf;
793}
794
Oliver Smith894be2d2019-01-11 13:13:37 +0100795/*! Calculate the Luhn checksum (as used for IMEIs).
796 * \param[in] in Input digits in ASCII string representation.
797 * \param[in] in_len Count of digits to use for the input (14 for IMEI).
798 * \returns checksum char (e.g. '3'); negative on error
799 */
800const char osmo_luhn(const char* in, int in_len)
801{
802 int i, sum = 0;
803
804 /* All input must be numbers */
805 for (i = 0; i < in_len; i++) {
806 if (!isdigit(in[i]))
807 return -EINVAL;
808 }
809
810 /* Double every second digit and add it to sum */
811 for (i = in_len - 1; i >= 0; i -= 2) {
812 int dbl = (in[i] - '0') * 2;
813 if (dbl > 9)
814 dbl -= 9;
815 sum += dbl;
816 }
817
818 /* Add other digits to sum */
819 for (i = in_len - 2; i >= 0; i -= 2)
820 sum += in[i] - '0';
821
822 /* Final checksum */
823 return (sum * 9) % 10 + '0';
824}
825
Neels Hofmeyr0aeda1b2017-01-13 14:16:02 +0100826/*! @} */