blob: 896e91776aff857fe57ac17b02d4aa5aafe2e3a8 [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
Harald Welte4a62eda2019-03-18 18:27:00 +0100276/*! Convert a sequence of unpacked bits to ASCII string, in user-supplied buffer.
277 * \param[out] buf caller-provided output string buffer
278 * \param[out] buf_len size of buf in bytes
Harald Welte8598f182011-08-17 14:19:27 +0200279 * \param[in] bits A sequence of unpacked bits
280 * \param[in] len Length of bits
Harald Welte4a62eda2019-03-18 18:27:00 +0100281 * \returns string representation in static buffer.
Harald Welte8598f182011-08-17 14:19:27 +0200282 */
Harald Welte4a62eda2019-03-18 18:27:00 +0100283char *osmo_ubit_dump_buf(char *buf, size_t buf_len, const uint8_t *bits, unsigned int len)
Harald Welte3d0ac5e2011-02-08 16:55:03 +0100284{
285 int i;
286
Harald Welte4a62eda2019-03-18 18:27:00 +0100287 if (len > buf_len-1)
288 len = buf_len-1;
289 memset(buf, 0, buf_len);
Harald Welte3d0ac5e2011-02-08 16:55:03 +0100290
291 for (i = 0; i < len; i++) {
292 char outch;
293 switch (bits[i]) {
294 case 0:
295 outch = '0';
296 break;
297 case 0xff:
298 outch = '?';
299 break;
300 case 1:
301 outch = '1';
302 break;
303 default:
304 outch = 'E';
305 break;
306 }
Harald Welte4a62eda2019-03-18 18:27:00 +0100307 buf[i] = outch;
Harald Welte3d0ac5e2011-02-08 16:55:03 +0100308 }
Harald Welte4a62eda2019-03-18 18:27:00 +0100309 buf[buf_len-1] = 0;
310 return buf;
311}
312
313/*! Convert a sequence of unpacked bits to ASCII string, in static buffer.
314 * \param[in] bits A sequence of unpacked bits
315 * \param[in] len Length of bits
316 * \returns string representation in static buffer.
317 */
318char *osmo_ubit_dump(const uint8_t *bits, unsigned int len)
319{
320 return osmo_ubit_dump_buf(hexd_buff, sizeof(hexd_buff), bits, len);
Harald Welte3d0ac5e2011-02-08 16:55:03 +0100321}
322
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200323/*! Convert binary sequence to hexadecimal ASCII string
Harald Welte8598f182011-08-17 14:19:27 +0200324 * \param[in] buf pointer to sequence of bytes
325 * \param[in] len length of buf in number of bytes
326 * \returns pointer to zero-terminated string
327 *
328 * This function will print a sequence of bytes as hexadecimal numbers,
329 * adding one space character between each byte (e.g. "1a ef d9")
Harald Welte096a6662017-10-16 14:33:11 +0200330 *
331 * The maximum size of the output buffer is 4096 bytes, i.e. the maximum
332 * number of input bytes that can be printed in one call is 1365!
Harald Welte8598f182011-08-17 14:19:27 +0200333 */
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200334char *osmo_hexdump(const unsigned char *buf, int len)
Harald Weltedee47cd2010-07-30 11:43:30 +0200335{
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100336 osmo_hexdump_buf(hexd_buff, sizeof(hexd_buff), buf, len, " ", true);
337 return hexd_buff;
Harald Weltedee47cd2010-07-30 11:43:30 +0200338}
339
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200340/*! Convert binary sequence to hexadecimal ASCII string
Harald Welte179f3572019-03-18 18:38:47 +0100341 * \param[in] ctx talloc context from where to allocate the output string
342 * \param[in] buf pointer to sequence of bytes
343 * \param[in] len length of buf in number of bytes
344 * \returns pointer to zero-terminated string
345 *
346 * This function will print a sequence of bytes as hexadecimal numbers,
347 * adding one space character between each byte (e.g. "1a ef d9")
348 *
349 * The maximum size of the output buffer is 4096 bytes, i.e. the maximum
350 * number of input bytes that can be printed in one call is 1365!
351 */
352char *osmo_hexdump_c(const void *ctx, const unsigned char *buf, int len)
353{
354 char *hexd_buff = talloc_size(ctx, len*3 + 1);
355 if (!hexd_buff)
356 return NULL;
357 osmo_hexdump_buf(hexd_buff, sizeof(hexd_buff), buf, len, " ", true);
358 return hexd_buff;
359}
360
361/*! Convert binary sequence to hexadecimal ASCII string
Harald Welte8598f182011-08-17 14:19:27 +0200362 * \param[in] buf pointer to sequence of bytes
363 * \param[in] len length of buf in number of bytes
364 * \returns pointer to zero-terminated string
365 *
366 * This function will print a sequence of bytes as hexadecimal numbers,
367 * without any space character between each byte (e.g. "1aefd9")
Harald Welte096a6662017-10-16 14:33:11 +0200368 *
369 * The maximum size of the output buffer is 4096 bytes, i.e. the maximum
370 * number of input bytes that can be printed in one call is 2048!
Harald Welte8598f182011-08-17 14:19:27 +0200371 */
Sylvain Munautff23d242011-11-10 23:03:18 +0100372char *osmo_hexdump_nospc(const unsigned char *buf, int len)
Harald Weltedee47cd2010-07-30 11:43:30 +0200373{
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100374 osmo_hexdump_buf(hexd_buff, sizeof(hexd_buff), buf, len, "", true);
375 return hexd_buff;
Harald Weltedee47cd2010-07-30 11:43:30 +0200376}
Harald Welte28222962011-02-18 20:37:04 +0100377
Harald Welte179f3572019-03-18 18:38:47 +0100378/*! Convert binary sequence to hexadecimal ASCII string
379 * \param[in] ctx talloc context from where to allocate the output string
380 * \param[in] buf pointer to sequence of bytes
381 * \param[in] len length of buf in number of bytes
382 * \returns pointer to zero-terminated string
383 *
384 * This function will print a sequence of bytes as hexadecimal numbers,
385 * without any space character between each byte (e.g. "1aefd9")
386 *
387 * The maximum size of the output buffer is 4096 bytes, i.e. the maximum
388 * number of input bytes that can be printed in one call is 2048!
389 */
390char *osmo_hexdump_nospc_c(const void *ctx, const unsigned char *buf, int len)
391{
392 char *hexd_buff = talloc_size(ctx, len*2 + 1);
393 if (!hexd_buff)
394 return NULL;
395 osmo_hexdump_buf(hexd_buff, sizeof(hexd_buff), buf, len, "", true);
396 return hexd_buff;
397}
398
399
Holger Hans Peter Freyther9a1a5a12015-04-11 19:26:55 +0200400/* Compat with previous typo to preserve abi */
Sylvain Munaute55ae3a2011-11-11 23:06:55 +0100401char *osmo_osmo_hexdump_nospc(const unsigned char *buf, int len)
Holger Hans Peter Freyther9a1a5a12015-04-11 19:26:55 +0200402#if defined(__MACH__) && defined(__APPLE__)
403 ;
404#else
Sylvain Munaut17af41d2011-11-19 22:30:39 +0100405 __attribute__((weak, alias("osmo_hexdump_nospc")));
Holger Hans Peter Freyther9a1a5a12015-04-11 19:26:55 +0200406#endif
Sylvain Munaute55ae3a2011-11-11 23:06:55 +0100407
Harald Welte28222962011-02-18 20:37:04 +0100408#include "../config.h"
409#ifdef HAVE_CTYPE_H
410#include <ctype.h>
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200411/*! Convert an entire string to lower case
Harald Welte8598f182011-08-17 14:19:27 +0200412 * \param[out] out output string, caller-allocated
413 * \param[in] in input string
414 */
Harald Welte28222962011-02-18 20:37:04 +0100415void osmo_str2lower(char *out, const char *in)
416{
417 unsigned int i;
418
419 for (i = 0; i < strlen(in); i++)
Pau Espin Pedrol399a6f02017-06-18 14:07:37 +0200420 out[i] = tolower((const unsigned char)in[i]);
Harald Welte28222962011-02-18 20:37:04 +0100421 out[strlen(in)] = '\0';
422}
423
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200424/*! Convert an entire string to upper case
Harald Welte8598f182011-08-17 14:19:27 +0200425 * \param[out] out output string, caller-allocated
426 * \param[in] in input string
427 */
Harald Welte28222962011-02-18 20:37:04 +0100428void osmo_str2upper(char *out, const char *in)
429{
430 unsigned int i;
431
432 for (i = 0; i < strlen(in); i++)
Pau Espin Pedrol399a6f02017-06-18 14:07:37 +0200433 out[i] = toupper((const unsigned char)in[i]);
Harald Welte28222962011-02-18 20:37:04 +0100434 out[strlen(in)] = '\0';
435}
436#endif /* HAVE_CTYPE_H */
Harald Welte8598f182011-08-17 14:19:27 +0200437
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200438/*! Wishful thinking to generate a constant time compare
Harald Welte9709b2e2016-04-25 18:47:53 +0200439 * \param[in] exp Expected data
440 * \param[in] rel Comparison value
441 * \param[in] count Number of bytes to compare
442 * \returns 1 in case \a exp equals \a rel; zero otherwise
443 *
444 * Compare count bytes of exp to rel. Return 0 if they are identical, 1
445 * otherwise. Do not return a mismatch on the first mismatching byte,
446 * but always compare all bytes, regardless. The idea is that the amount of
447 * matching bytes cannot be inferred from the time the comparison took. */
448int osmo_constant_time_cmp(const uint8_t *exp, const uint8_t *rel, const int count)
449{
450 int x = 0, i;
451
452 for (i = 0; i < count; ++i)
453 x |= exp[i] ^ rel[i];
454
455 /* if x is zero, all data was identical */
456 return x? 1 : 0;
457}
458
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200459/*! Generic retrieval of 1..8 bytes as big-endian uint64_t
Harald Welte9709b2e2016-04-25 18:47:53 +0200460 * \param[in] data Input data as byte-array
461 * \param[in] data_len Length of \a data in octets
462 * \returns uint64_t of \a data interpreted as big-endian
463 *
464 * This is like osmo_load64be_ext, except that if data_len is less than
465 * sizeof(uint64_t), the data is interpreted as the least significant bytes
466 * (osmo_load64be_ext loads them as the most significant bytes into the
467 * returned uint64_t). In this way, any integer size up to 64 bits can be
468 * decoded conveniently by using sizeof(), without the need to call specific
469 * numbered functions (osmo_load16, 32, ...). */
470uint64_t osmo_decode_big_endian(const uint8_t *data, size_t data_len)
471{
472 uint64_t value = 0;
473
474 while (data_len > 0) {
475 value = (value << 8) + *data;
476 data += 1;
477 data_len -= 1;
478 }
479
480 return value;
481}
482
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200483/*! Generic big-endian encoding of big endian number up to 64bit
Harald Welte9709b2e2016-04-25 18:47:53 +0200484 * \param[in] value unsigned integer value to be stored
485 * \param[in] data_len number of octets
486 * \returns static buffer containing big-endian stored value
487 *
488 * This is like osmo_store64be_ext, except that this returns a static buffer of
489 * the result (for convenience, but not threadsafe). If data_len is less than
490 * sizeof(uint64_t), only the least significant bytes of value are encoded. */
491uint8_t *osmo_encode_big_endian(uint64_t value, size_t data_len)
492{
493 static uint8_t buf[sizeof(uint64_t)];
494 OSMO_ASSERT(data_len <= ARRAY_SIZE(buf));
495 osmo_store64be_ext(value, buf, data_len);
496 return buf;
497}
Harald Welteaeecc482016-11-26 10:41:40 +0100498
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200499/*! Copy a C-string into a sized buffer
Harald Welteaeecc482016-11-26 10:41:40 +0100500 * \param[in] src source string
501 * \param[out] dst destination string
Neels Hofmeyrdf83ece2017-01-13 13:55:43 +0100502 * \param[in] siz size of the \a dst buffer
503 * \returns length of \a src
Harald Welteaeecc482016-11-26 10:41:40 +0100504 *
Neels Hofmeyrdf83ece2017-01-13 13:55:43 +0100505 * Copy at most \a siz bytes from \a src to \a dst, ensuring that the result is
506 * NUL terminated. The NUL character is included in \a siz, i.e. passing the
507 * actual sizeof(*dst) is correct.
Harald Welteaeecc482016-11-26 10:41:40 +0100508 */
509size_t osmo_strlcpy(char *dst, const char *src, size_t siz)
510{
Neels Hofmeyrbcf9f232017-10-25 04:16:45 +0200511 size_t ret = src ? strlen(src) : 0;
Harald Welteaeecc482016-11-26 10:41:40 +0100512
513 if (siz) {
514 size_t len = (ret >= siz) ? siz - 1 : ret;
Neels Hofmeyrebd3cdd2017-11-18 23:07:38 +0100515 if (src)
516 memcpy(dst, src, len);
Harald Welteaeecc482016-11-26 10:41:40 +0100517 dst[len] = '\0';
518 }
519 return ret;
520}
Neels Hofmeyr0aeda1b2017-01-13 14:16:02 +0100521
Neels Hofmeyr4335bad2017-10-07 04:39:14 +0200522/*! Validate that a given string is a hex string within given size limits.
523 * Note that each hex digit amounts to a nibble, so if checking for a hex
524 * string to result in N bytes, pass amount of digits as 2*N.
525 * \param str A nul-terminated string to validate, or NULL.
526 * \param min_digits least permitted amount of digits.
527 * \param max_digits most permitted amount of digits.
528 * \param require_even if true, require an even amount of digits.
529 * \returns true when the hex_str contains only hexadecimal digits (no
530 * whitespace) and matches the requested length; also true
531 * when min_digits <= 0 and str is NULL.
532 */
533bool osmo_is_hexstr(const char *str, int min_digits, int max_digits,
534 bool require_even)
535{
536 int len;
537 /* Use unsigned char * to avoid a compiler warning of
538 * "error: array subscript has type 'char' [-Werror=char-subscripts]" */
539 const unsigned char *pos = (const unsigned char*)str;
540 if (!pos)
541 return min_digits < 1;
542 for (len = 0; *pos && len < max_digits; len++, pos++)
543 if (!isxdigit(*pos))
544 return false;
545 if (len < min_digits)
546 return false;
547 /* With not too many digits, we should have reached *str == nul */
548 if (*pos)
549 return false;
550 if (require_even && (len & 1))
551 return false;
Harald Weltefebe83c2017-10-03 17:41:59 +0800552
553 return true;
554}
555
Neels Hofmeyrb480b742019-04-11 06:58:44 +0200556static const char osmo_identifier_illegal_chars[] = "., {}[]()<>|~\\^`'\"?=;/+*&%$#!";
557
Harald Weltefebe83c2017-10-03 17:41:59 +0800558/*! Determine if a given identifier is valid, i.e. doesn't contain illegal chars
559 * \param[in] str String to validate
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100560 * \param[in] sep_chars Permitted separation characters between identifiers.
561 * \returns true in case \a str contains only valid identifiers and sep_chars, false otherwise
Harald Weltefebe83c2017-10-03 17:41:59 +0800562 */
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100563bool osmo_separated_identifiers_valid(const char *str, const char *sep_chars)
Harald Weltefebe83c2017-10-03 17:41:59 +0800564{
565 /* characters that are illegal in names */
Harald Weltefebe83c2017-10-03 17:41:59 +0800566 unsigned int i;
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100567 size_t len;
Harald Weltefebe83c2017-10-03 17:41:59 +0800568
569 /* an empty string is not a valid identifier */
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100570 if (!str || (len = strlen(str)) == 0)
Harald Weltefebe83c2017-10-03 17:41:59 +0800571 return false;
572
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100573 for (i = 0; i < len; i++) {
574 if (sep_chars && strchr(sep_chars, str[i]))
575 continue;
Harald Weltefebe83c2017-10-03 17:41:59 +0800576 /* check for 7-bit ASCII */
577 if (str[i] & 0x80)
578 return false;
Neels Hofmeyre5a2bdb2017-12-16 04:54:37 +0100579 if (!isprint((int)str[i]))
580 return false;
Harald Weltefebe83c2017-10-03 17:41:59 +0800581 /* check for some explicit reserved control characters */
Neels Hofmeyrb480b742019-04-11 06:58:44 +0200582 if (strchr(osmo_identifier_illegal_chars, str[i]))
Harald Weltefebe83c2017-10-03 17:41:59 +0800583 return false;
584 }
585
Neels Hofmeyr4335bad2017-10-07 04:39:14 +0200586 return true;
587}
588
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100589/*! Determine if a given identifier is valid, i.e. doesn't contain illegal chars
590 * \param[in] str String to validate
591 * \returns true in case \a str contains valid identifier, false otherwise
592 */
593bool osmo_identifier_valid(const char *str)
594{
595 return osmo_separated_identifiers_valid(str, NULL);
596}
597
Neels Hofmeyrb480b742019-04-11 06:58:44 +0200598/*! Replace characters in the given string buffer so that it is guaranteed to pass osmo_separated_identifiers_valid().
599 * To guarantee passing osmo_separated_identifiers_valid(), replace_with must not itself be an illegal character. If in
600 * doubt, use '-'.
601 * \param[inout] str Identifier to sanitize, must be nul terminated and in a writable buffer.
602 * \param[in] sep_chars Additional characters that are allowed besides osmo_identifier_illegal_chars.
603 * \param[in] replace_with Replace any illegal characters with this character.
604 */
605void osmo_identifier_sanitize_buf(char *str, const char *sep_chars, char replace_with)
606{
607 char *pos;
608 if (!str)
609 return;
610 for (pos = str; *pos; pos++) {
611 if (strchr(osmo_identifier_illegal_chars, *pos)
612 || (sep_chars && strchr(sep_chars, *pos)))
613 *pos = replace_with;
614 }
615}
616
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100617/*! Like osmo_escape_str_buf2, but with unusual ordering of arguments, and may sometimes return string constants instead
618 * of writing to buf for error cases or empty input.
619 * Most *_buf() functions have the buffer and size as first arguments, here the arguments are last.
620 * In particular, this function signature doesn't work with OSMO_STRBUF_APPEND_NOLEN().
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100621 * \param[in] str A string that may contain any characters.
622 * \param[in] len Pass -1 to print until nul char, or >= 0 to force a length.
623 * \param[inout] buf string buffer to write escaped characters to.
624 * \param[in] bufsize size of \a buf.
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100625 * \returns buf containing an escaped representation, possibly truncated,
626 * or "(null)" if str == NULL, or "(error)" in case of errors.
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100627 */
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100628const char *osmo_escape_str_buf(const char *str, int in_len, char *buf, size_t bufsize)
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100629{
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100630 if (!str)
631 return "(null)";
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100632 if (!buf || !bufsize)
633 return "(error)";
634 return osmo_escape_str_buf2(buf, bufsize, str, in_len);
635}
636
637/*! Copy N characters to a buffer with a function signature useful for OSMO_STRBUF_APPEND().
638 * Similarly to snprintf(), the result is always nul terminated (except if buf is NULL or bufsize is 0).
639 * \param[out] buf Target buffer.
640 * \param[in] bufsize sizeof(buf).
641 * \param[in] str String to copy.
642 * \param[in] n Maximum number of non-nul characters to copy.
643 * \return Number of characters that would be written if bufsize were large enough excluding '\0' (like snprintf()).
644 */
645int osmo_print_n(char *buf, size_t bufsize, const char *str, size_t n)
646{
647 size_t write_n;
648
649 if (!str)
650 str = "";
651
652 n = strnlen(str, n);
653
654 if (!buf || !bufsize)
655 return n;
656 write_n = n;
657 if (write_n >= bufsize)
658 write_n = bufsize - 1;
659 if (write_n)
660 strncpy(buf, str, write_n);
661 buf[write_n] = '\0';
662
663 return n;
664}
665
666/*! Return the string with all non-printable characters escaped.
667 * \param[out] buf string buffer to write escaped characters to.
668 * \param[in] bufsize sizeof(buf).
669 * \param[in] str A string that may contain any characters.
670 * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length (also past nul chars).
671 * \return Number of characters that would be written if bufsize were large enough excluding '\0' (like snprintf()).
672 */
673char *osmo_escape_str_buf2(char *buf, size_t bufsize, const char *str, int in_len)
674{
675 struct osmo_strbuf sb = { .buf = buf, .len = bufsize };
676 int in_pos = 0;
677 int next_unprintable = 0;
678
679 if (!str)
680 in_len = 0;
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100681
682 if (in_len < 0)
683 in_len = strlen(str);
684
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100685 /* Make sure of '\0' termination */
686 if (!in_len)
687 OSMO_STRBUF_PRINTF(sb, "%s", "");
688
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100689 while (in_pos < in_len) {
690 for (next_unprintable = in_pos;
691 next_unprintable < in_len && isprint((int)str[next_unprintable])
692 && str[next_unprintable] != '"'
693 && str[next_unprintable] != '\\';
694 next_unprintable++);
695
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100696 OSMO_STRBUF_APPEND(sb, osmo_print_n, &str[in_pos], next_unprintable - in_pos);
697 in_pos = next_unprintable;
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100698
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100699 if (in_pos == in_len)
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100700 goto done;
701
702 switch (str[next_unprintable]) {
703#define BACKSLASH_CASE(c, repr) \
704 case c: \
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100705 OSMO_STRBUF_PRINTF(sb, "\\%c", repr); \
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100706 break
707
708 BACKSLASH_CASE('\n', 'n');
709 BACKSLASH_CASE('\r', 'r');
710 BACKSLASH_CASE('\t', 't');
711 BACKSLASH_CASE('\0', '0');
712 BACKSLASH_CASE('\a', 'a');
713 BACKSLASH_CASE('\b', 'b');
714 BACKSLASH_CASE('\v', 'v');
715 BACKSLASH_CASE('\f', 'f');
716 BACKSLASH_CASE('\\', '\\');
717 BACKSLASH_CASE('"', '"');
718#undef BACKSLASH_CASE
719
720 default:
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100721 OSMO_STRBUF_PRINTF(sb, "\\%u", (unsigned char)str[in_pos]);
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100722 break;
723 }
724 in_pos ++;
725 }
726
727done:
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100728 return buf;
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100729}
730
731/*! Return the string with all non-printable characters escaped.
732 * Call osmo_escape_str_buf() with a static buffer.
733 * \param[in] str A string that may contain any characters.
734 * \param[in] len Pass -1 to print until nul char, or >= 0 to force a length.
735 * \returns buf containing an escaped representation, possibly truncated, or str itself.
736 */
737const char *osmo_escape_str(const char *str, int in_len)
738{
739 return osmo_escape_str_buf(str, in_len, namebuf, sizeof(namebuf));
740}
741
Harald Welte179f3572019-03-18 18:38:47 +0100742/*! Return the string with all non-printable characters escaped, in dynamically-allocated buffer.
743 * \param[in] str A string that may contain any characters.
744 * \param[in] len Pass -1 to print until nul char, or >= 0 to force a length.
745 * \returns dynamically-allocated output buffer, containing an escaped representation
746 */
747char *osmo_escape_str_c(const void *ctx, const char *str, int in_len)
748{
749 char *buf = talloc_size(ctx, in_len+1);
750 if (!buf)
751 return NULL;
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100752 return osmo_escape_str_buf2(buf, in_len+1, str, in_len);
Harald Welte179f3572019-03-18 18:38:47 +0100753}
754
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100755/*! Like osmo_escape_str_buf2(), but returns double-quotes around a string, or "NULL" for a NULL string.
Neels Hofmeyr04eb56f2018-04-09 00:41:28 +0200756 * This allows passing any char* value and get its C representation as string.
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100757 * The function signature is suitable for OSMO_STRBUF_APPEND_NOLEN().
758 * \param[out] buf string buffer to write escaped characters to.
759 * \param[in] bufsize sizeof(buf).
760 * \param[in] str A string that may contain any characters.
761 * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length.
762 * \return Number of characters that would be written if bufsize were large enough excluding '\0' (like snprintf()).
763 */
764char *osmo_quote_str_buf2(char *buf, size_t bufsize, const char *str, int in_len)
765{
766 struct osmo_strbuf sb = { .buf = buf, .len = bufsize };
767 if (!str)
768 OSMO_STRBUF_PRINTF(sb, "NULL");
769 else {
770 OSMO_STRBUF_PRINTF(sb, "\"");
771 OSMO_STRBUF_APPEND_NOLEN(sb, osmo_escape_str_buf2, str, in_len);
772 OSMO_STRBUF_PRINTF(sb, "\"");
773 }
774 return buf;
775}
776
777/*! Like osmo_quote_str_buf2, but with unusual ordering of arguments, and may sometimes return string constants instead
778 * of writing to buf for error cases or empty input.
779 * Most *_buf() functions have the buffer and size as first arguments, here the arguments are last.
780 * In particular, this function signature doesn't work with OSMO_STRBUF_APPEND_NOLEN().
Neels Hofmeyr04eb56f2018-04-09 00:41:28 +0200781 * \param[in] str A string that may contain any characters.
Neels Hofmeyr03e75532018-09-07 03:12:05 +0200782 * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length.
783 * \returns buf containing a quoted and escaped representation, possibly truncated.
Neels Hofmeyr04eb56f2018-04-09 00:41:28 +0200784 */
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100785const char *osmo_quote_str_buf(const char *str, int in_len, char *buf, size_t bufsize)
Neels Hofmeyr04eb56f2018-04-09 00:41:28 +0200786{
Neels Hofmeyr04eb56f2018-04-09 00:41:28 +0200787 if (!str)
788 return "NULL";
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100789 if (!buf || !bufsize)
790 return "(error)";
791 osmo_quote_str_buf2(buf, bufsize, str, in_len);
Neels Hofmeyr04eb56f2018-04-09 00:41:28 +0200792 return buf;
793}
794
Neels Hofmeyr03e75532018-09-07 03:12:05 +0200795/*! Like osmo_quote_str_buf() but returns the result in a static buffer.
796 * The static buffer is shared with get_value_string() and osmo_escape_str().
797 * \param[in] str A string that may contain any characters.
798 * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length.
799 * \returns static buffer containing a quoted and escaped representation, possibly truncated.
800 */
Neels Hofmeyr04eb56f2018-04-09 00:41:28 +0200801const char *osmo_quote_str(const char *str, int in_len)
802{
803 return osmo_quote_str_buf(str, in_len, namebuf, sizeof(namebuf));
804}
805
Harald Welte179f3572019-03-18 18:38:47 +0100806/*! Like osmo_quote_str_buf() but returns the result in a dynamically-allocated buffer.
807 * The static buffer is shared with get_value_string() and osmo_escape_str().
808 * \param[in] str A string that may contain any characters.
809 * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length.
810 * \returns dynamically-allocated buffer containing a quoted and escaped representation.
811 */
812char *osmo_quote_str_c(const void *ctx, const char *str, int in_len)
813{
814 char *buf = talloc_size(ctx, OSMO_MAX(in_len+2, 32));
815 if (!buf)
816 return NULL;
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100817 return osmo_quote_str_buf2(buf, 32, str, in_len);
Harald Welte179f3572019-03-18 18:38:47 +0100818}
819
Harald Welte15a5f8d2018-06-06 16:58:17 +0200820/*! perform an integer square root operation on unsigned 32bit integer.
821 * This implementation is taken from "Hacker's Delight" Figure 11-1 "Integer square root, Newton's
822 * method", which can also be found at http://www.hackersdelight.org/hdcodetxt/isqrt.c.txt */
823uint32_t osmo_isqrt32(uint32_t x)
824{
825 uint32_t x1;
826 int s, g0, g1;
827
828 if (x <= 1)
829 return x;
830
831 s = 1;
832 x1 = x - 1;
833 if (x1 > 0xffff) {
834 s = s + 8;
835 x1 = x1 >> 16;
836 }
837 if (x1 > 0xff) {
838 s = s + 4;
839 x1 = x1 >> 8;
840 }
841 if (x1 > 0xf) {
842 s = s + 2;
843 x1 = x1 >> 4;
844 }
845 if (x1 > 0x3) {
846 s = s + 1;
847 }
848
849 g0 = 1 << s; /* g0 = 2**s */
850 g1 = (g0 + (x >> s)) >> 1; /* g1 = (g0 + x/g0)/2 */
851
852 /* converges after four to five divisions for arguments up to 16,785,407 */
853 while (g1 < g0) {
854 g0 = g1;
855 g1 = (g0 + (x/g0)) >> 1;
856 }
857 return g0;
858}
859
Neels Hofmeyr7c749892018-09-07 03:01:38 +0200860/*! Convert a string to lowercase, while checking buffer size boundaries.
861 * The result written to \a dest is guaranteed to be nul terminated if \a dest_len > 0.
862 * If dest == src, the string is converted in-place, if necessary truncated at dest_len - 1 characters
863 * length as well as nul terminated.
864 * Note: similar osmo_str2lower(), but safe to use for src strings of arbitrary length.
865 * \param[out] dest Target buffer to write lowercase string.
866 * \param[in] dest_len Maximum buffer size of dest (e.g. sizeof(dest)).
867 * \param[in] src String to convert to lowercase.
868 * \returns Length of \a src, like osmo_strlcpy(), but if \a dest == \a src at most \a dest_len - 1.
869 */
870size_t osmo_str_tolower_buf(char *dest, size_t dest_len, const char *src)
871{
872 size_t rc;
873 if (dest == src) {
874 if (dest_len < 1)
875 return 0;
876 dest[dest_len - 1] = '\0';
877 rc = strlen(dest);
878 } else {
879 if (dest_len < 1)
880 return strlen(src);
881 rc = osmo_strlcpy(dest, src, dest_len);
882 }
883 for (; *dest; dest++)
884 *dest = tolower(*dest);
885 return rc;
886}
887
888/*! Convert a string to lowercase, using a static buffer.
889 * The resulting string may be truncated if the internally used static buffer is shorter than src.
890 * The internal buffer is at least 128 bytes long, i.e. guaranteed to hold at least 127 characters and a
891 * terminating nul.
892 * See also osmo_str_tolower_buf().
893 * \param[in] src String to convert to lowercase.
894 * \returns Resulting lowercase string in a static buffer, always nul terminated.
895 */
896const char *osmo_str_tolower(const char *src)
897{
898 static char buf[128];
899 osmo_str_tolower_buf(buf, sizeof(buf), src);
900 return buf;
901}
902
Harald Welte179f3572019-03-18 18:38:47 +0100903/*! Convert a string to lowercase, dynamically allocating the output from given talloc context
904 * See also osmo_str_tolower_buf().
905 * \param[in] ctx talloc context from where to allocate the output string
906 * \param[in] src String to convert to lowercase.
907 * \returns Resulting lowercase string in a dynamically allocated buffer, always nul terminated.
908 */
909char *osmo_str_tolower_c(const void *ctx, const char *src)
910{
911 char *buf = talloc_size(ctx, strlen(src)+1);
912 if (!buf)
913 return NULL;
914 osmo_str_tolower_buf(buf, sizeof(buf), src);
915 return buf;
916}
917
Neels Hofmeyr7c749892018-09-07 03:01:38 +0200918/*! Convert a string to uppercase, while checking buffer size boundaries.
919 * The result written to \a dest is guaranteed to be nul terminated if \a dest_len > 0.
920 * If dest == src, the string is converted in-place, if necessary truncated at dest_len - 1 characters
921 * length as well as nul terminated.
922 * Note: similar osmo_str2upper(), but safe to use for src strings of arbitrary length.
923 * \param[out] dest Target buffer to write uppercase string.
924 * \param[in] dest_len Maximum buffer size of dest (e.g. sizeof(dest)).
925 * \param[in] src String to convert to uppercase.
926 * \returns Length of \a src, like osmo_strlcpy(), but if \a dest == \a src at most \a dest_len - 1.
927 */
928size_t osmo_str_toupper_buf(char *dest, size_t dest_len, const char *src)
929{
930 size_t rc;
931 if (dest == src) {
932 if (dest_len < 1)
933 return 0;
934 dest[dest_len - 1] = '\0';
935 rc = strlen(dest);
936 } else {
937 if (dest_len < 1)
938 return strlen(src);
939 rc = osmo_strlcpy(dest, src, dest_len);
940 }
941 for (; *dest; dest++)
942 *dest = toupper(*dest);
943 return rc;
944}
945
946/*! Convert a string to uppercase, using a static buffer.
947 * The resulting string may be truncated if the internally used static buffer is shorter than src.
948 * The internal buffer is at least 128 bytes long, i.e. guaranteed to hold at least 127 characters and a
949 * terminating nul.
950 * See also osmo_str_toupper_buf().
951 * \param[in] src String to convert to uppercase.
952 * \returns Resulting uppercase string in a static buffer, always nul terminated.
953 */
954const char *osmo_str_toupper(const char *src)
955{
956 static char buf[128];
957 osmo_str_toupper_buf(buf, sizeof(buf), src);
958 return buf;
959}
960
Harald Welte179f3572019-03-18 18:38:47 +0100961/*! Convert a string to uppercase, dynamically allocating the output from given talloc context
962 * See also osmo_str_tolower_buf().
963 * \param[in] ctx talloc context from where to allocate the output string
964 * \param[in] src String to convert to uppercase.
965 * \returns Resulting uppercase string in a dynamically allocated buffer, always nul terminated.
966 */
967char *osmo_str_toupper_c(const void *ctx, const char *src)
968{
969 char *buf = talloc_size(ctx, strlen(src)+1);
970 if (!buf)
971 return NULL;
972 osmo_str_toupper_buf(buf, sizeof(buf), src);
973 return buf;
974}
975
Oliver Smith894be2d2019-01-11 13:13:37 +0100976/*! Calculate the Luhn checksum (as used for IMEIs).
977 * \param[in] in Input digits in ASCII string representation.
978 * \param[in] in_len Count of digits to use for the input (14 for IMEI).
979 * \returns checksum char (e.g. '3'); negative on error
980 */
981const char osmo_luhn(const char* in, int in_len)
982{
983 int i, sum = 0;
984
985 /* All input must be numbers */
986 for (i = 0; i < in_len; i++) {
987 if (!isdigit(in[i]))
988 return -EINVAL;
989 }
990
991 /* Double every second digit and add it to sum */
992 for (i = in_len - 1; i >= 0; i -= 2) {
993 int dbl = (in[i] - '0') * 2;
994 if (dbl > 9)
995 dbl -= 9;
996 sum += dbl;
997 }
998
999 /* Add other digits to sum */
1000 for (i = in_len - 2; i >= 0; i -= 2)
1001 sum += in[i] - '0';
1002
1003 /* Final checksum */
1004 return (sum * 9) % 10 + '0';
1005}
1006
Neels Hofmeyrd79ccc62019-03-07 23:08:40 +01001007/*! Compare start of a string.
1008 * This is an optimisation of 'strstr(str, startswith_str) == str' because it doesn't search through the entire string.
1009 * \param str (Longer) string to compare.
1010 * \param startswith_str (Shorter) string to compare with the start of str.
1011 * \return true iff the first characters of str fully match startswith_str or startswith_str is empty. */
1012bool osmo_str_startswith(const char *str, const char *startswith_str)
1013{
1014 if (!startswith_str || !*startswith_str)
1015 return true;
1016 if (!str)
1017 return false;
1018 return strncmp(str, startswith_str, strlen(startswith_str)) == 0;
1019}
1020
Neels Hofmeyr0aeda1b2017-01-13 14:16:02 +01001021/*! @} */