blob: 038288c5c324c27537b1b24855157cf5ecec371f [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 Welte171ef822019-03-28 10:49:05 +010044static __thread char namebuf[255];
Pau Espin Pedrola37f58e2019-08-01 18:11:41 +020045/* shared by osmo_str_tolower() and osmo_str_toupper() */
46static __thread char capsbuf[128];
Harald Welte8598f182011-08-17 14:19:27 +020047
Neels Hofmeyr87e45502017-06-20 00:17:59 +020048/*! get human-readable string for given value
Harald Welte8598f182011-08-17 14:19:27 +020049 * \param[in] vs Array of value_string tuples
50 * \param[in] val Value to be converted
51 * \returns pointer to human-readable string
Neels Hofmeyr8a3c83e2016-06-13 13:16:58 +020052 *
53 * If val is found in vs, the array's string entry is returned. Otherwise, an
54 * "unknown" string containing the actual value is composed in a static buffer
55 * that is reused across invocations.
Harald Welte8598f182011-08-17 14:19:27 +020056 */
Harald Welted284cd92010-03-01 21:58:31 +010057const char *get_value_string(const struct value_string *vs, uint32_t val)
58{
Neels Hofmeyr8d6dcd92016-06-06 18:05:23 +020059 const char *str = get_value_string_or_null(vs, val);
60 if (str)
61 return str;
62
Pau Espin Pedrol45735022017-06-18 14:05:24 +020063 snprintf(namebuf, sizeof(namebuf), "unknown 0x%"PRIx32, val);
Neels Hofmeyr8d6dcd92016-06-06 18:05:23 +020064 namebuf[sizeof(namebuf) - 1] = '\0';
65 return namebuf;
66}
67
Neels Hofmeyr87e45502017-06-20 00:17:59 +020068/*! get human-readable string or NULL for given value
Neels Hofmeyr8d6dcd92016-06-06 18:05:23 +020069 * \param[in] vs Array of value_string tuples
70 * \param[in] val Value to be converted
71 * \returns pointer to human-readable string or NULL if val is not found
72 */
73const char *get_value_string_or_null(const struct value_string *vs,
74 uint32_t val)
75{
Harald Welted284cd92010-03-01 21:58:31 +010076 int i;
77
Neels Hofmeyra0331ed2019-02-11 21:24:40 +010078 if (!vs)
79 return NULL;
80
Harald Welted284cd92010-03-01 21:58:31 +010081 for (i = 0;; i++) {
82 if (vs[i].value == 0 && vs[i].str == NULL)
83 break;
84 if (vs[i].value == val)
85 return vs[i].str;
86 }
Harald Welteb59f9352010-03-25 11:37:04 +080087
Neels Hofmeyr8d6dcd92016-06-06 18:05:23 +020088 return NULL;
Harald Welted284cd92010-03-01 21:58:31 +010089}
90
Neels Hofmeyr87e45502017-06-20 00:17:59 +020091/*! get numeric value for given human-readable string
Harald Welte8598f182011-08-17 14:19:27 +020092 * \param[in] vs Array of value_string tuples
93 * \param[in] str human-readable string
94 * \returns numeric value (>0) or negative numer in case of error
95 */
Harald Welted284cd92010-03-01 21:58:31 +010096int get_string_value(const struct value_string *vs, const char *str)
97{
98 int i;
99
100 for (i = 0;; i++) {
101 if (vs[i].value == 0 && vs[i].str == NULL)
102 break;
103 if (!strcasecmp(vs[i].str, str))
104 return vs[i].value;
105 }
106 return -EINVAL;
107}
Harald Weltea73e2f92010-03-04 10:50:32 +0100108
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200109/*! Convert BCD-encoded digit into printable character
Harald Welte8598f182011-08-17 14:19:27 +0200110 * \param[in] bcd A single BCD-encoded digit
111 * \returns single printable character
112 */
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200113char osmo_bcd2char(uint8_t bcd)
Harald Weltea73e2f92010-03-04 10:50:32 +0100114{
115 if (bcd < 0xa)
116 return '0' + bcd;
117 else
118 return 'A' + (bcd - 0xa);
119}
120
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200121/*! Convert number in ASCII to BCD value
Harald Weltede6e4982012-12-06 21:25:27 +0100122 * \param[in] c ASCII character
123 * \returns BCD encoded value of character
124 */
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200125uint8_t osmo_char2bcd(char c)
Harald Weltea73e2f92010-03-04 10:50:32 +0100126{
Harald Weltefa8983d2017-10-27 16:52:59 +0200127 if (c >= '0' && c <= '9')
128 return c - 0x30;
129 else if (c >= 'A' && c <= 'F')
130 return 0xa + (c - 'A');
131 else if (c >= 'a' && c <= 'f')
132 return 0xa + (c - 'a');
133 else
134 return 0;
Harald Weltea73e2f92010-03-04 10:50:32 +0100135}
Harald Welte3eba9912010-07-30 10:37:29 +0200136
Neels Hofmeyr7079e692018-12-05 21:02:36 +0100137/*! Convert BCD to string.
138 * The given nibble offsets are interpreted in BCD order, i.e. nibble 0 is bcd[0] & 0xf, nibble 1 is bcd[0] >> 4, nibble
139 * 3 is bcd[1] & 0xf, etc..
140 * \param[out] dst Output string buffer, is always nul terminated when dst_size > 0.
141 * \param[in] dst_size sizeof() the output string buffer.
142 * \param[in] bcd Binary coded data buffer.
143 * \param[in] start_nibble Offset to start from, in nibbles, typically 1 to skip the first nibble.
Neels Hofmeyr48b2de02018-12-11 02:13:57 +0100144 * \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 +0100145 * \param[in] allow_hex If false, return error if there are digits other than 0-9. If true, return those as [A-F].
146 * \returns The strlen that would be written if the output buffer is large enough, excluding nul byte (like
147 * snprintf()), or -EINVAL if allow_hex is false and a digit > 9 is encountered. On -EINVAL, the conversion is
148 * still completed as if allow_hex were passed as true. Return -ENOMEM if dst is NULL or dst_size is zero.
149 * If end_nibble <= start_nibble, write an empty string to dst and return 0.
150 */
151int osmo_bcd2str(char *dst, size_t dst_size, const uint8_t *bcd, int start_nibble, int end_nibble, bool allow_hex)
152{
153 char *dst_end = dst + dst_size - 1;
154 int nibble_i;
155 int rc = 0;
156
157 if (!dst || dst_size < 1)
158 return -ENOMEM;
159
160 for (nibble_i = start_nibble; nibble_i < end_nibble && dst < dst_end; nibble_i++, dst++) {
161 uint8_t nibble = bcd[nibble_i >> 1];
162 if ((nibble_i & 1))
163 nibble >>= 4;
164 nibble &= 0xf;
165
166 if (!allow_hex && nibble > 9)
167 rc = -EINVAL;
168
169 *dst = osmo_bcd2char(nibble);
170 }
171 *dst = '\0';
172
173 if (rc < 0)
174 return rc;
175 return OSMO_MAX(0, end_nibble - start_nibble);
176}
177
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200178/*! Parse a string containing hexadecimal digits
Harald Weltede6e4982012-12-06 21:25:27 +0100179 * \param[in] str string containing ASCII encoded hexadecimal digits
180 * \param[out] b output buffer
181 * \param[in] max_len maximum space in output buffer
Neels Hofmeyr3de7b052015-09-23 23:16:53 +0200182 * \returns number of parsed octets, or -1 on error
Harald Weltede6e4982012-12-06 21:25:27 +0100183 */
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200184int osmo_hexparse(const char *str, uint8_t *b, int max_len)
Harald Welte3eba9912010-07-30 10:37:29 +0200185
186{
Neels Hofmeyr437ed4a2017-02-14 15:54:31 +0100187 char c;
188 uint8_t v;
189 const char *strpos;
190 unsigned int nibblepos = 0;
Harald Welte3eba9912010-07-30 10:37:29 +0200191
192 memset(b, 0x00, max_len);
193
Neels Hofmeyr437ed4a2017-02-14 15:54:31 +0100194 for (strpos = str; (c = *strpos); strpos++) {
195 /* skip whitespace */
196 if (c == ' ' || c == '\t' || c == '\n' || c == '\r')
197 continue;
198
199 /* If the buffer is too small, error out */
200 if (nibblepos >= (max_len << 1))
201 return -1;
202
Harald Welte3eba9912010-07-30 10:37:29 +0200203 if (c >= '0' && c <= '9')
204 v = c - '0';
205 else if (c >= 'a' && c <= 'f')
206 v = 10 + (c - 'a');
207 else if (c >= 'A' && c <= 'F')
208 v = 10 + (c - 'A');
209 else
210 return -1;
Neels Hofmeyr437ed4a2017-02-14 15:54:31 +0100211
212 b[nibblepos >> 1] |= v << (nibblepos & 1 ? 0 : 4);
213 nibblepos ++;
Harald Welte3eba9912010-07-30 10:37:29 +0200214 }
215
Neels Hofmeyr437ed4a2017-02-14 15:54:31 +0100216 /* In case of uneven amount of digits, the last byte is not complete
217 * and that's an error. */
218 if (nibblepos & 1)
219 return -1;
220
221 return nibblepos >> 1;
Harald Welte3eba9912010-07-30 10:37:29 +0200222}
Harald Welte40481e82010-07-30 11:40:32 +0200223
Harald Welte171ef822019-03-28 10:49:05 +0100224static __thread char hexd_buff[4096];
Nils O. Selåsdal32447022014-01-02 14:04:43 +0100225static const char hex_chars[] = "0123456789abcdef";
Harald Welte40481e82010-07-30 11:40:32 +0200226
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100227/*! Convert binary sequence to hexadecimal ASCII string.
228 * \param[out] out_buf Output buffer to write the resulting string to.
229 * \param[in] out_buf_size sizeof(out_buf).
230 * \param[in] buf Input buffer, pointer to sequence of bytes.
231 * \param[in] len Length of input buf in number of bytes.
232 * \param[in] delim String to separate each byte; NULL or "" for no delim.
233 * \param[in] delim_after_last If true, end the string in delim (true: "1a:ef:d9:", false: "1a:ef:d9");
234 * if out_buf has insufficient space, the string will always end in a delim.
235 * \returns out_buf, containing a zero-terminated string, or "" (empty string) if out_buf == NULL or out_buf_size < 1.
236 *
237 * This function will print a sequence of bytes as hexadecimal numbers, adding one delim between each byte (e.g. for
238 * delim passed as ":", return a string like "1a:ef:d9").
239 *
240 * The delim_after_last argument exists to be able to exactly show the original osmo_hexdump() behavior, which always
241 * ends the string with a delimiter.
242 */
243const char *osmo_hexdump_buf(char *out_buf, size_t out_buf_size, const unsigned char *buf, int len, const char *delim,
244 bool delim_after_last)
Harald Welte40481e82010-07-30 11:40:32 +0200245{
246 int i;
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100247 char *cur = out_buf;
248 size_t delim_len;
Harald Welte40481e82010-07-30 11:40:32 +0200249
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100250 if (!out_buf || !out_buf_size)
251 return "";
252
253 delim = delim ? : "";
254 delim_len = strlen(delim);
255
Harald Welte40481e82010-07-30 11:40:32 +0200256 for (i = 0; i < len; i++) {
Nils O. Selåsdal32447022014-01-02 14:04:43 +0100257 const char *delimp = delim;
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100258 int len_remain = out_buf_size - (cur - out_buf) - 1;
259 if (len_remain < (2 + delim_len)
260 && !(!delim_after_last && i == (len - 1) && len_remain >= 2))
Holger Hans Peter Freyther128d9e22011-07-15 16:07:23 +0200261 break;
Nils O. Selåsdal32447022014-01-02 14:04:43 +0100262
263 *cur++ = hex_chars[buf[i] >> 4];
264 *cur++ = hex_chars[buf[i] & 0xf];
265
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100266 if (i == (len - 1) && !delim_after_last)
267 break;
268
Nils O. Selåsdal32447022014-01-02 14:04:43 +0100269 while (len_remain > 1 && *delimp) {
270 *cur++ = *delimp++;
271 len_remain--;
272 }
Harald Welte40481e82010-07-30 11:40:32 +0200273 }
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100274 *cur = '\0';
275 return out_buf;
Harald Welte40481e82010-07-30 11:40:32 +0200276}
Harald Weltedee47cd2010-07-30 11:43:30 +0200277
Harald Welte4a62eda2019-03-18 18:27:00 +0100278/*! Convert a sequence of unpacked bits to ASCII string, in user-supplied buffer.
279 * \param[out] buf caller-provided output string buffer
280 * \param[out] buf_len size of buf in bytes
Harald Welte8598f182011-08-17 14:19:27 +0200281 * \param[in] bits A sequence of unpacked bits
282 * \param[in] len Length of bits
Neels Hofmeyrdd7b6f92019-11-20 21:32:29 +0100283 * \return The output buffer (buf).
Harald Welte8598f182011-08-17 14:19:27 +0200284 */
Harald Welte4a62eda2019-03-18 18:27:00 +0100285char *osmo_ubit_dump_buf(char *buf, size_t buf_len, const uint8_t *bits, unsigned int len)
Harald Welte3d0ac5e2011-02-08 16:55:03 +0100286{
287 int i;
288
Harald Welte4a62eda2019-03-18 18:27:00 +0100289 if (len > buf_len-1)
290 len = buf_len-1;
291 memset(buf, 0, buf_len);
Harald Welte3d0ac5e2011-02-08 16:55:03 +0100292
293 for (i = 0; i < len; i++) {
294 char outch;
295 switch (bits[i]) {
296 case 0:
297 outch = '0';
298 break;
299 case 0xff:
300 outch = '?';
301 break;
302 case 1:
303 outch = '1';
304 break;
305 default:
306 outch = 'E';
307 break;
308 }
Harald Welte4a62eda2019-03-18 18:27:00 +0100309 buf[i] = outch;
Harald Welte3d0ac5e2011-02-08 16:55:03 +0100310 }
Harald Welte4a62eda2019-03-18 18:27:00 +0100311 buf[buf_len-1] = 0;
312 return buf;
313}
314
315/*! Convert a sequence of unpacked bits to ASCII string, in static buffer.
316 * \param[in] bits A sequence of unpacked bits
317 * \param[in] len Length of bits
318 * \returns string representation in static buffer.
319 */
320char *osmo_ubit_dump(const uint8_t *bits, unsigned int len)
321{
322 return osmo_ubit_dump_buf(hexd_buff, sizeof(hexd_buff), bits, len);
Harald Welte3d0ac5e2011-02-08 16:55:03 +0100323}
324
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200325/*! Convert binary sequence to hexadecimal ASCII string
Harald Welte8598f182011-08-17 14:19:27 +0200326 * \param[in] buf pointer to sequence of bytes
327 * \param[in] len length of buf in number of bytes
328 * \returns pointer to zero-terminated string
329 *
330 * This function will print a sequence of bytes as hexadecimal numbers,
331 * adding one space character between each byte (e.g. "1a ef d9")
Harald Welte096a6662017-10-16 14:33:11 +0200332 *
333 * The maximum size of the output buffer is 4096 bytes, i.e. the maximum
334 * number of input bytes that can be printed in one call is 1365!
Harald Welte8598f182011-08-17 14:19:27 +0200335 */
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200336char *osmo_hexdump(const unsigned char *buf, int len)
Harald Weltedee47cd2010-07-30 11:43:30 +0200337{
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100338 osmo_hexdump_buf(hexd_buff, sizeof(hexd_buff), buf, len, " ", true);
339 return hexd_buff;
Harald Weltedee47cd2010-07-30 11:43:30 +0200340}
341
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200342/*! Convert binary sequence to hexadecimal ASCII string
Harald Welte179f3572019-03-18 18:38:47 +0100343 * \param[in] ctx talloc context from where to allocate the output string
344 * \param[in] buf pointer to sequence of bytes
345 * \param[in] len length of buf in number of bytes
346 * \returns pointer to zero-terminated string
347 *
348 * This function will print a sequence of bytes as hexadecimal numbers,
349 * adding one space character between each byte (e.g. "1a ef d9")
350 *
351 * The maximum size of the output buffer is 4096 bytes, i.e. the maximum
352 * number of input bytes that can be printed in one call is 1365!
353 */
354char *osmo_hexdump_c(const void *ctx, const unsigned char *buf, int len)
355{
Vadim Yanitskiy4f619c22019-04-12 21:48:07 +0700356 size_t hexd_buff_len = len * 3 + 1;
357 char *hexd_buff = talloc_size(ctx, hexd_buff_len);
Harald Welte179f3572019-03-18 18:38:47 +0100358 if (!hexd_buff)
359 return NULL;
Vadim Yanitskiy4f619c22019-04-12 21:48:07 +0700360 osmo_hexdump_buf(hexd_buff, hexd_buff_len, buf, len, " ", true);
Harald Welte179f3572019-03-18 18:38:47 +0100361 return hexd_buff;
362}
363
364/*! Convert binary sequence to hexadecimal ASCII string
Harald Welte8598f182011-08-17 14:19:27 +0200365 * \param[in] buf pointer to sequence of bytes
366 * \param[in] len length of buf in number of bytes
367 * \returns pointer to zero-terminated string
368 *
369 * This function will print a sequence of bytes as hexadecimal numbers,
370 * without any space character between each byte (e.g. "1aefd9")
Harald Welte096a6662017-10-16 14:33:11 +0200371 *
372 * The maximum size of the output buffer is 4096 bytes, i.e. the maximum
373 * number of input bytes that can be printed in one call is 2048!
Harald Welte8598f182011-08-17 14:19:27 +0200374 */
Sylvain Munautff23d242011-11-10 23:03:18 +0100375char *osmo_hexdump_nospc(const unsigned char *buf, int len)
Harald Weltedee47cd2010-07-30 11:43:30 +0200376{
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100377 osmo_hexdump_buf(hexd_buff, sizeof(hexd_buff), buf, len, "", true);
378 return hexd_buff;
Harald Weltedee47cd2010-07-30 11:43:30 +0200379}
Harald Welte28222962011-02-18 20:37:04 +0100380
Harald Welte179f3572019-03-18 18:38:47 +0100381/*! Convert binary sequence to hexadecimal ASCII string
382 * \param[in] ctx talloc context from where to allocate the output string
383 * \param[in] buf pointer to sequence of bytes
384 * \param[in] len length of buf in number of bytes
385 * \returns pointer to zero-terminated string
386 *
387 * This function will print a sequence of bytes as hexadecimal numbers,
388 * without any space character between each byte (e.g. "1aefd9")
389 *
390 * The maximum size of the output buffer is 4096 bytes, i.e. the maximum
391 * number of input bytes that can be printed in one call is 2048!
392 */
393char *osmo_hexdump_nospc_c(const void *ctx, const unsigned char *buf, int len)
394{
Vadim Yanitskiy4f619c22019-04-12 21:48:07 +0700395 size_t hexd_buff_len = len * 2 + 1;
396 char *hexd_buff = talloc_size(ctx, hexd_buff_len);
Harald Welte179f3572019-03-18 18:38:47 +0100397 if (!hexd_buff)
398 return NULL;
Vadim Yanitskiy4f619c22019-04-12 21:48:07 +0700399 osmo_hexdump_buf(hexd_buff, hexd_buff_len, buf, len, "", true);
Harald Welte179f3572019-03-18 18:38:47 +0100400 return hexd_buff;
401}
402
403
Holger Hans Peter Freyther9a1a5a12015-04-11 19:26:55 +0200404/* Compat with previous typo to preserve abi */
Sylvain Munaute55ae3a2011-11-11 23:06:55 +0100405char *osmo_osmo_hexdump_nospc(const unsigned char *buf, int len)
Holger Hans Peter Freyther9a1a5a12015-04-11 19:26:55 +0200406#if defined(__MACH__) && defined(__APPLE__)
407 ;
408#else
Sylvain Munaut17af41d2011-11-19 22:30:39 +0100409 __attribute__((weak, alias("osmo_hexdump_nospc")));
Holger Hans Peter Freyther9a1a5a12015-04-11 19:26:55 +0200410#endif
Sylvain Munaute55ae3a2011-11-11 23:06:55 +0100411
Harald Welte28222962011-02-18 20:37:04 +0100412#include "../config.h"
413#ifdef HAVE_CTYPE_H
414#include <ctype.h>
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200415/*! Convert an entire string to lower case
Harald Welte8598f182011-08-17 14:19:27 +0200416 * \param[out] out output string, caller-allocated
417 * \param[in] in input string
418 */
Harald Welte28222962011-02-18 20:37:04 +0100419void osmo_str2lower(char *out, const char *in)
420{
421 unsigned int i;
422
423 for (i = 0; i < strlen(in); i++)
Pau Espin Pedrol399a6f02017-06-18 14:07:37 +0200424 out[i] = tolower((const unsigned char)in[i]);
Harald Welte28222962011-02-18 20:37:04 +0100425 out[strlen(in)] = '\0';
426}
427
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200428/*! Convert an entire string to upper case
Harald Welte8598f182011-08-17 14:19:27 +0200429 * \param[out] out output string, caller-allocated
430 * \param[in] in input string
431 */
Harald Welte28222962011-02-18 20:37:04 +0100432void osmo_str2upper(char *out, const char *in)
433{
434 unsigned int i;
435
436 for (i = 0; i < strlen(in); i++)
Pau Espin Pedrol399a6f02017-06-18 14:07:37 +0200437 out[i] = toupper((const unsigned char)in[i]);
Harald Welte28222962011-02-18 20:37:04 +0100438 out[strlen(in)] = '\0';
439}
440#endif /* HAVE_CTYPE_H */
Harald Welte8598f182011-08-17 14:19:27 +0200441
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200442/*! Wishful thinking to generate a constant time compare
Harald Welte9709b2e2016-04-25 18:47:53 +0200443 * \param[in] exp Expected data
444 * \param[in] rel Comparison value
445 * \param[in] count Number of bytes to compare
446 * \returns 1 in case \a exp equals \a rel; zero otherwise
447 *
448 * Compare count bytes of exp to rel. Return 0 if they are identical, 1
449 * otherwise. Do not return a mismatch on the first mismatching byte,
450 * but always compare all bytes, regardless. The idea is that the amount of
451 * matching bytes cannot be inferred from the time the comparison took. */
452int osmo_constant_time_cmp(const uint8_t *exp, const uint8_t *rel, const int count)
453{
454 int x = 0, i;
455
456 for (i = 0; i < count; ++i)
457 x |= exp[i] ^ rel[i];
458
459 /* if x is zero, all data was identical */
460 return x? 1 : 0;
461}
462
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200463/*! Generic retrieval of 1..8 bytes as big-endian uint64_t
Harald Welte9709b2e2016-04-25 18:47:53 +0200464 * \param[in] data Input data as byte-array
465 * \param[in] data_len Length of \a data in octets
466 * \returns uint64_t of \a data interpreted as big-endian
467 *
468 * This is like osmo_load64be_ext, except that if data_len is less than
469 * sizeof(uint64_t), the data is interpreted as the least significant bytes
470 * (osmo_load64be_ext loads them as the most significant bytes into the
471 * returned uint64_t). In this way, any integer size up to 64 bits can be
472 * decoded conveniently by using sizeof(), without the need to call specific
473 * numbered functions (osmo_load16, 32, ...). */
474uint64_t osmo_decode_big_endian(const uint8_t *data, size_t data_len)
475{
476 uint64_t value = 0;
477
478 while (data_len > 0) {
479 value = (value << 8) + *data;
480 data += 1;
481 data_len -= 1;
482 }
483
484 return value;
485}
486
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200487/*! Generic big-endian encoding of big endian number up to 64bit
Harald Welte9709b2e2016-04-25 18:47:53 +0200488 * \param[in] value unsigned integer value to be stored
489 * \param[in] data_len number of octets
490 * \returns static buffer containing big-endian stored value
491 *
492 * This is like osmo_store64be_ext, except that this returns a static buffer of
493 * the result (for convenience, but not threadsafe). If data_len is less than
494 * sizeof(uint64_t), only the least significant bytes of value are encoded. */
495uint8_t *osmo_encode_big_endian(uint64_t value, size_t data_len)
496{
Harald Welte171ef822019-03-28 10:49:05 +0100497 static __thread uint8_t buf[sizeof(uint64_t)];
Harald Welte9709b2e2016-04-25 18:47:53 +0200498 OSMO_ASSERT(data_len <= ARRAY_SIZE(buf));
499 osmo_store64be_ext(value, buf, data_len);
500 return buf;
501}
Harald Welteaeecc482016-11-26 10:41:40 +0100502
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200503/*! Copy a C-string into a sized buffer
Harald Welteaeecc482016-11-26 10:41:40 +0100504 * \param[in] src source string
505 * \param[out] dst destination string
Neels Hofmeyrdf83ece2017-01-13 13:55:43 +0100506 * \param[in] siz size of the \a dst buffer
507 * \returns length of \a src
Harald Welteaeecc482016-11-26 10:41:40 +0100508 *
Neels Hofmeyrdf83ece2017-01-13 13:55:43 +0100509 * Copy at most \a siz bytes from \a src to \a dst, ensuring that the result is
510 * NUL terminated. The NUL character is included in \a siz, i.e. passing the
511 * actual sizeof(*dst) is correct.
Neels Hofmeyrff65d242019-11-19 00:21:14 +0100512 *
513 * Note, a similar function that also limits the input buffer size is osmo_print_n().
Harald Welteaeecc482016-11-26 10:41:40 +0100514 */
515size_t osmo_strlcpy(char *dst, const char *src, size_t siz)
516{
Neels Hofmeyrbcf9f232017-10-25 04:16:45 +0200517 size_t ret = src ? strlen(src) : 0;
Harald Welteaeecc482016-11-26 10:41:40 +0100518
519 if (siz) {
520 size_t len = (ret >= siz) ? siz - 1 : ret;
Neels Hofmeyrebd3cdd2017-11-18 23:07:38 +0100521 if (src)
522 memcpy(dst, src, len);
Harald Welteaeecc482016-11-26 10:41:40 +0100523 dst[len] = '\0';
524 }
525 return ret;
526}
Neels Hofmeyr0aeda1b2017-01-13 14:16:02 +0100527
Neels Hofmeyr06356fd2019-11-19 01:38:10 +0100528/*! Find first occurence of a char in a size limited string.
529 * Like strchr() but with a buffer size limit.
530 * \param[in] str String buffer to examine.
531 * \param[in] str_size sizeof(str).
532 * \param[in] c Character to look for.
533 * \return Pointer to the matched char, or NULL if not found.
534 */
535const char *osmo_strnchr(const char *str, size_t str_size, char c)
536{
537 const char *end = str + str_size;
538 const char *pos;
539 if (!str)
540 return NULL;
541 for (pos = str; pos < end; pos++) {
542 if (c == *pos)
543 return pos;
544 if (!*pos)
545 return NULL;
546 }
547 return NULL;
548}
549
Neels Hofmeyr4335bad2017-10-07 04:39:14 +0200550/*! Validate that a given string is a hex string within given size limits.
551 * Note that each hex digit amounts to a nibble, so if checking for a hex
552 * string to result in N bytes, pass amount of digits as 2*N.
553 * \param str A nul-terminated string to validate, or NULL.
554 * \param min_digits least permitted amount of digits.
555 * \param max_digits most permitted amount of digits.
556 * \param require_even if true, require an even amount of digits.
557 * \returns true when the hex_str contains only hexadecimal digits (no
558 * whitespace) and matches the requested length; also true
559 * when min_digits <= 0 and str is NULL.
560 */
561bool osmo_is_hexstr(const char *str, int min_digits, int max_digits,
562 bool require_even)
563{
564 int len;
565 /* Use unsigned char * to avoid a compiler warning of
566 * "error: array subscript has type 'char' [-Werror=char-subscripts]" */
567 const unsigned char *pos = (const unsigned char*)str;
568 if (!pos)
569 return min_digits < 1;
570 for (len = 0; *pos && len < max_digits; len++, pos++)
571 if (!isxdigit(*pos))
572 return false;
573 if (len < min_digits)
574 return false;
575 /* With not too many digits, we should have reached *str == nul */
576 if (*pos)
577 return false;
578 if (require_even && (len & 1))
579 return false;
Harald Weltefebe83c2017-10-03 17:41:59 +0800580
581 return true;
582}
583
Neels Hofmeyrb480b742019-04-11 06:58:44 +0200584static const char osmo_identifier_illegal_chars[] = "., {}[]()<>|~\\^`'\"?=;/+*&%$#!";
585
Harald Weltefebe83c2017-10-03 17:41:59 +0800586/*! Determine if a given identifier is valid, i.e. doesn't contain illegal chars
587 * \param[in] str String to validate
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100588 * \param[in] sep_chars Permitted separation characters between identifiers.
589 * \returns true in case \a str contains only valid identifiers and sep_chars, false otherwise
Harald Weltefebe83c2017-10-03 17:41:59 +0800590 */
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100591bool osmo_separated_identifiers_valid(const char *str, const char *sep_chars)
Harald Weltefebe83c2017-10-03 17:41:59 +0800592{
593 /* characters that are illegal in names */
Harald Weltefebe83c2017-10-03 17:41:59 +0800594 unsigned int i;
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100595 size_t len;
Harald Weltefebe83c2017-10-03 17:41:59 +0800596
597 /* an empty string is not a valid identifier */
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100598 if (!str || (len = strlen(str)) == 0)
Harald Weltefebe83c2017-10-03 17:41:59 +0800599 return false;
600
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100601 for (i = 0; i < len; i++) {
602 if (sep_chars && strchr(sep_chars, str[i]))
603 continue;
Harald Weltefebe83c2017-10-03 17:41:59 +0800604 /* check for 7-bit ASCII */
605 if (str[i] & 0x80)
606 return false;
Neels Hofmeyre5a2bdb2017-12-16 04:54:37 +0100607 if (!isprint((int)str[i]))
608 return false;
Harald Weltefebe83c2017-10-03 17:41:59 +0800609 /* check for some explicit reserved control characters */
Neels Hofmeyrb480b742019-04-11 06:58:44 +0200610 if (strchr(osmo_identifier_illegal_chars, str[i]))
Harald Weltefebe83c2017-10-03 17:41:59 +0800611 return false;
612 }
613
Neels Hofmeyr4335bad2017-10-07 04:39:14 +0200614 return true;
615}
616
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100617/*! Determine if a given identifier is valid, i.e. doesn't contain illegal chars
618 * \param[in] str String to validate
619 * \returns true in case \a str contains valid identifier, false otherwise
620 */
621bool osmo_identifier_valid(const char *str)
622{
623 return osmo_separated_identifiers_valid(str, NULL);
624}
625
Neels Hofmeyrb480b742019-04-11 06:58:44 +0200626/*! Replace characters in the given string buffer so that it is guaranteed to pass osmo_separated_identifiers_valid().
627 * To guarantee passing osmo_separated_identifiers_valid(), replace_with must not itself be an illegal character. If in
628 * doubt, use '-'.
629 * \param[inout] str Identifier to sanitize, must be nul terminated and in a writable buffer.
630 * \param[in] sep_chars Additional characters that are allowed besides osmo_identifier_illegal_chars.
631 * \param[in] replace_with Replace any illegal characters with this character.
632 */
633void osmo_identifier_sanitize_buf(char *str, const char *sep_chars, char replace_with)
634{
635 char *pos;
636 if (!str)
637 return;
638 for (pos = str; *pos; pos++) {
639 if (strchr(osmo_identifier_illegal_chars, *pos)
640 || (sep_chars && strchr(sep_chars, *pos)))
641 *pos = replace_with;
642 }
643}
644
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100645/*! Like osmo_escape_str_buf2, but with unusual ordering of arguments, and may sometimes return string constants instead
646 * of writing to buf for error cases or empty input.
647 * Most *_buf() functions have the buffer and size as first arguments, here the arguments are last.
648 * In particular, this function signature doesn't work with OSMO_STRBUF_APPEND_NOLEN().
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100649 * \param[in] str A string that may contain any characters.
650 * \param[in] len Pass -1 to print until nul char, or >= 0 to force a length.
651 * \param[inout] buf string buffer to write escaped characters to.
652 * \param[in] bufsize size of \a buf.
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100653 * \returns buf containing an escaped representation, possibly truncated,
654 * or "(null)" if str == NULL, or "(error)" in case of errors.
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100655 */
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100656const char *osmo_escape_str_buf(const char *str, int in_len, char *buf, size_t bufsize)
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100657{
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100658 if (!str)
659 return "(null)";
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100660 if (!buf || !bufsize)
661 return "(error)";
662 return osmo_escape_str_buf2(buf, bufsize, str, in_len);
663}
664
665/*! Copy N characters to a buffer with a function signature useful for OSMO_STRBUF_APPEND().
666 * Similarly to snprintf(), the result is always nul terminated (except if buf is NULL or bufsize is 0).
667 * \param[out] buf Target buffer.
668 * \param[in] bufsize sizeof(buf).
669 * \param[in] str String to copy.
670 * \param[in] n Maximum number of non-nul characters to copy.
671 * \return Number of characters that would be written if bufsize were large enough excluding '\0' (like snprintf()).
672 */
673int osmo_print_n(char *buf, size_t bufsize, const char *str, size_t n)
674{
675 size_t write_n;
676
677 if (!str)
678 str = "";
679
680 n = strnlen(str, n);
681
682 if (!buf || !bufsize)
683 return n;
684 write_n = n;
685 if (write_n >= bufsize)
686 write_n = bufsize - 1;
687 if (write_n)
688 strncpy(buf, str, write_n);
689 buf[write_n] = '\0';
690
691 return n;
692}
693
694/*! Return the string with all non-printable characters escaped.
Neels Hofmeyrc36e2e42019-11-20 21:57:32 +0100695 * This internal function is the implementation for all osmo_escape_str* and osmo_quote_str* API versions.
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100696 * It provides both the legacy (non C compatible) escaping, as well as C compatible string constant syntax,
697 * and it provides a return value of characters-needed, to allow producing un-truncated strings in all cases.
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100698 * \param[out] buf string buffer to write escaped characters to.
699 * \param[in] bufsize sizeof(buf).
700 * \param[in] str A string that may contain any characters.
701 * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length (also past nul chars).
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100702 * \param[in] legacy_format If false, return C compatible string constants ("\x0f"), if true the legacy
703 * escaping format ("\15"). The legacy format also escapes as "\a\b\f\v", while
704 * the non-legacy format also escapes those as "\xNN" sequences.
Neels Hofmeyrc36e2e42019-11-20 21:57:32 +0100705 * \return Number of characters that would be written if bufsize were large enough excluding '\0' (like snprintf()).
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100706 */
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100707static size_t _osmo_escape_str_buf(char *buf, size_t bufsize, const char *str, int in_len, bool legacy_format)
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100708{
709 struct osmo_strbuf sb = { .buf = buf, .len = bufsize };
710 int in_pos = 0;
711 int next_unprintable = 0;
712
713 if (!str)
714 in_len = 0;
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100715
716 if (in_len < 0)
717 in_len = strlen(str);
718
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100719 /* Make sure of '\0' termination */
720 if (!in_len)
721 OSMO_STRBUF_PRINTF(sb, "%s", "");
722
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100723 while (in_pos < in_len) {
724 for (next_unprintable = in_pos;
725 next_unprintable < in_len && isprint((int)str[next_unprintable])
726 && str[next_unprintable] != '"'
727 && str[next_unprintable] != '\\';
728 next_unprintable++);
729
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100730 OSMO_STRBUF_APPEND(sb, osmo_print_n, &str[in_pos], next_unprintable - in_pos);
731 in_pos = next_unprintable;
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100732
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100733 if (in_pos == in_len)
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100734 goto done;
735
736 switch (str[next_unprintable]) {
737#define BACKSLASH_CASE(c, repr) \
738 case c: \
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100739 OSMO_STRBUF_PRINTF(sb, "\\%c", repr); \
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100740 break
741
742 BACKSLASH_CASE('\n', 'n');
743 BACKSLASH_CASE('\r', 'r');
744 BACKSLASH_CASE('\t', 't');
745 BACKSLASH_CASE('\0', '0');
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100746 BACKSLASH_CASE('\\', '\\');
747 BACKSLASH_CASE('"', '"');
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100748
749 default:
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100750 if (legacy_format) {
751 switch (str[next_unprintable]) {
752 BACKSLASH_CASE('\a', 'a');
753 BACKSLASH_CASE('\b', 'b');
754 BACKSLASH_CASE('\v', 'v');
755 BACKSLASH_CASE('\f', 'f');
756 default:
757 OSMO_STRBUF_PRINTF(sb, "\\%u", (unsigned char)str[in_pos]);
758 break;
759 }
760 break;
761 }
762
763 OSMO_STRBUF_PRINTF(sb, "\\x%02x", (unsigned char)str[in_pos]);
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100764 break;
765 }
766 in_pos ++;
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100767#undef BACKSLASH_CASE
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100768 }
769
770done:
Neels Hofmeyrc36e2e42019-11-20 21:57:32 +0100771 return sb.chars_needed;
772}
773
774/*! Return the string with all non-printable characters escaped.
775 * \param[out] buf string buffer to write escaped characters to.
776 * \param[in] bufsize sizeof(buf).
777 * \param[in] str A string that may contain any characters.
778 * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length (also past nul chars).
779 * \return The output buffer (buf).
780 */
781char *osmo_escape_str_buf2(char *buf, size_t bufsize, const char *str, int in_len)
782{
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100783 _osmo_escape_str_buf(buf, bufsize, str, in_len, true);
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100784 return buf;
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100785}
786
787/*! Return the string with all non-printable characters escaped.
788 * Call osmo_escape_str_buf() with a static buffer.
789 * \param[in] str A string that may contain any characters.
790 * \param[in] len Pass -1 to print until nul char, or >= 0 to force a length.
791 * \returns buf containing an escaped representation, possibly truncated, or str itself.
792 */
793const char *osmo_escape_str(const char *str, int in_len)
794{
795 return osmo_escape_str_buf(str, in_len, namebuf, sizeof(namebuf));
796}
797
Harald Welte179f3572019-03-18 18:38:47 +0100798/*! Return the string with all non-printable characters escaped, in dynamically-allocated buffer.
799 * \param[in] str A string that may contain any characters.
800 * \param[in] len Pass -1 to print until nul char, or >= 0 to force a length.
801 * \returns dynamically-allocated output buffer, containing an escaped representation
802 */
803char *osmo_escape_str_c(const void *ctx, const char *str, int in_len)
804{
Neels Hofmeyrc36e2e42019-11-20 21:57:32 +0100805 /* The string will be at least as long as in_len, but some characters might need escaping.
806 * These extra bytes should catch most usual escaping situations, avoiding a second run in OSMO_NAME_C_IMPL. */
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100807 OSMO_NAME_C_IMPL(ctx, in_len + 16, "ERROR", _osmo_escape_str_buf, str, in_len, true);
Neels Hofmeyrc36e2e42019-11-20 21:57:32 +0100808}
809
810/*! Return a quoted and escaped representation of the string.
811 * This internal function is the implementation for all osmo_quote_str* API versions.
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100812 * It provides both the legacy (non C compatible) escaping, as well as C compatible string constant syntax,
813 * and it provides a return value of characters-needed, to allow producing un-truncated strings in all cases.
Neels Hofmeyrc36e2e42019-11-20 21:57:32 +0100814 * \param[out] buf string buffer to write escaped characters to.
815 * \param[in] bufsize sizeof(buf).
816 * \param[in] str A string that may contain any characters.
817 * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length (also past nul chars).
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100818 * \param[in] legacy_format If false, return C compatible string constants ("\x0f"), if true the legacy
819 * escaping format ("\15"). The legacy format also escapes as "\a\b\f\v", while
820 * the non-legacy format also escapes those as "\xNN" sequences.
Neels Hofmeyrc36e2e42019-11-20 21:57:32 +0100821 * \return Number of characters that would be written if bufsize were large enough excluding '\0' (like snprintf()).
822 */
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100823static size_t _osmo_quote_str_buf(char *buf, size_t bufsize, const char *str, int in_len, bool legacy_format)
Neels Hofmeyrc36e2e42019-11-20 21:57:32 +0100824{
825 struct osmo_strbuf sb = { .buf = buf, .len = bufsize };
826 if (!str)
827 OSMO_STRBUF_PRINTF(sb, "NULL");
828 else {
829 OSMO_STRBUF_PRINTF(sb, "\"");
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100830 OSMO_STRBUF_APPEND(sb, _osmo_escape_str_buf, str, in_len, legacy_format);
Neels Hofmeyrc36e2e42019-11-20 21:57:32 +0100831 OSMO_STRBUF_PRINTF(sb, "\"");
832 }
833 return sb.chars_needed;
Harald Welte179f3572019-03-18 18:38:47 +0100834}
835
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100836/*! 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 +0200837 * This allows passing any char* value and get its C representation as string.
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100838 * The function signature is suitable for OSMO_STRBUF_APPEND_NOLEN().
839 * \param[out] buf string buffer to write escaped characters to.
840 * \param[in] bufsize sizeof(buf).
841 * \param[in] str A string that may contain any characters.
842 * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length.
Neels Hofmeyrdd7b6f92019-11-20 21:32:29 +0100843 * \return The output buffer (buf).
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100844 */
845char *osmo_quote_str_buf2(char *buf, size_t bufsize, const char *str, int in_len)
846{
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100847 _osmo_quote_str_buf(buf, bufsize, str, in_len, true);
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100848 return buf;
849}
850
851/*! Like osmo_quote_str_buf2, but with unusual ordering of arguments, and may sometimes return string constants instead
852 * of writing to buf for error cases or empty input.
853 * Most *_buf() functions have the buffer and size as first arguments, here the arguments are last.
854 * In particular, this function signature doesn't work with OSMO_STRBUF_APPEND_NOLEN().
Neels Hofmeyr04eb56f2018-04-09 00:41:28 +0200855 * \param[in] str A string that may contain any characters.
Neels Hofmeyr03e75532018-09-07 03:12:05 +0200856 * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length.
857 * \returns buf containing a quoted and escaped representation, possibly truncated.
Neels Hofmeyr04eb56f2018-04-09 00:41:28 +0200858 */
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100859const char *osmo_quote_str_buf(const char *str, int in_len, char *buf, size_t bufsize)
Neels Hofmeyr04eb56f2018-04-09 00:41:28 +0200860{
Neels Hofmeyr04eb56f2018-04-09 00:41:28 +0200861 if (!str)
862 return "NULL";
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100863 if (!buf || !bufsize)
864 return "(error)";
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100865 _osmo_quote_str_buf(buf, bufsize, str, in_len, true);
Neels Hofmeyr04eb56f2018-04-09 00:41:28 +0200866 return buf;
867}
868
Neels Hofmeyr03e75532018-09-07 03:12:05 +0200869/*! Like osmo_quote_str_buf() but returns the result in a static buffer.
870 * The static buffer is shared with get_value_string() and osmo_escape_str().
871 * \param[in] str A string that may contain any characters.
872 * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length.
873 * \returns static buffer containing a quoted and escaped representation, possibly truncated.
874 */
Neels Hofmeyr04eb56f2018-04-09 00:41:28 +0200875const char *osmo_quote_str(const char *str, int in_len)
876{
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100877 _osmo_quote_str_buf(namebuf, sizeof(namebuf), str, in_len, true);
Neels Hofmeyrc36e2e42019-11-20 21:57:32 +0100878 return namebuf;
Neels Hofmeyr04eb56f2018-04-09 00:41:28 +0200879}
880
Harald Welte179f3572019-03-18 18:38:47 +0100881/*! Like osmo_quote_str_buf() but returns the result in a dynamically-allocated buffer.
Harald Welte179f3572019-03-18 18:38:47 +0100882 * \param[in] str A string that may contain any characters.
883 * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length.
884 * \returns dynamically-allocated buffer containing a quoted and escaped representation.
885 */
886char *osmo_quote_str_c(const void *ctx, const char *str, int in_len)
887{
Neels Hofmeyrc36e2e42019-11-20 21:57:32 +0100888 /* The string will be at least as long as in_len, but some characters might need escaping.
889 * These extra bytes should catch most usual escaping situations, avoiding a second run in OSMO_NAME_C_IMPL. */
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100890 OSMO_NAME_C_IMPL(ctx, in_len + 16, "ERROR", _osmo_quote_str_buf, str, in_len, true);
891}
892
893/*! Return the string with all non-printable characters escaped.
894 * In contrast to osmo_escape_str_buf2(), this returns the needed buffer size suitable for OSMO_STRBUF_APPEND(), and
895 * this escapes characters in a way compatible with C string constant syntax.
896 * \param[out] buf string buffer to write escaped characters to.
897 * \param[in] bufsize sizeof(buf).
898 * \param[in] str A string that may contain any characters.
899 * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length (also past nul chars).
900 * \return Number of characters that would be written if bufsize were large enough excluding '\0' (like snprintf()).
901 */
902size_t osmo_escape_cstr_buf(char *buf, size_t bufsize, const char *str, int in_len)
903{
904 return _osmo_escape_str_buf(buf, bufsize, str, in_len, false);
905}
906
907/*! Return the string with all non-printable characters escaped, in dynamically-allocated buffer.
908 * In contrast to osmo_escape_str_c(), this escapes characters in a way compatible with C string constant syntax, and
909 * allocates sufficient memory in all cases.
910 * \param[in] str A string that may contain any characters.
911 * \param[in] len Pass -1 to print until nul char, or >= 0 to force a length.
912 * \returns dynamically-allocated buffer, containing an escaped representation.
913 */
914char *osmo_escape_cstr_c(void *ctx, const char *str, int in_len)
915{
916 /* The string will be at least as long as in_len, but some characters might need escaping.
917 * These extra bytes should catch most usual escaping situations, avoiding a second run in OSMO_NAME_C_IMPL. */
918 OSMO_NAME_C_IMPL(ctx, in_len + 16, "ERROR", _osmo_escape_str_buf, str, in_len, false);
919}
920
921/*! Like osmo_escape_str_buf2(), but returns double-quotes around a string, or "NULL" for a NULL string.
922 * This allows passing any char* value and get its C representation as string.
923 * The function signature is suitable for OSMO_STRBUF_APPEND_NOLEN().
924 * In contrast to osmo_escape_str_buf2(), this returns the needed buffer size suitable for OSMO_STRBUF_APPEND(), and
925 * this escapes characters in a way compatible with C string constant syntax.
926 * \param[out] buf string buffer to write escaped characters to.
927 * \param[in] bufsize sizeof(buf).
928 * \param[in] str A string that may contain any characters.
929 * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length.
930 * \return Number of characters that would be written if bufsize were large enough excluding '\0' (like snprintf()).
931 */
932size_t osmo_quote_cstr_buf(char *buf, size_t bufsize, const char *str, int in_len)
933{
934 return _osmo_quote_str_buf(buf, bufsize, str, in_len, false);
935}
936
937/*! Return the string quoted and with all non-printable characters escaped, in dynamically-allocated buffer.
938 * In contrast to osmo_quote_str_c(), this escapes characters in a way compatible with C string constant syntax, and
939 * allocates sufficient memory in all cases.
940 * \param[in] str A string that may contain any characters.
941 * \param[in] len Pass -1 to print until nul char, or >= 0 to force a length.
942 * \returns dynamically-allocated buffer, containing a quoted and escaped representation.
943 */
944char *osmo_quote_cstr_c(void *ctx, const char *str, int in_len)
945{
946 /* The string will be at least as long as in_len plus two quotes, but some characters might need escaping.
947 * These extra bytes should catch most usual escaping situations, avoiding a second run in OSMO_NAME_C_IMPL. */
948 OSMO_NAME_C_IMPL(ctx, in_len + 16, "ERROR", _osmo_quote_str_buf, str, in_len, false);
Harald Welte179f3572019-03-18 18:38:47 +0100949}
950
Harald Welte15a5f8d2018-06-06 16:58:17 +0200951/*! perform an integer square root operation on unsigned 32bit integer.
952 * This implementation is taken from "Hacker's Delight" Figure 11-1 "Integer square root, Newton's
953 * method", which can also be found at http://www.hackersdelight.org/hdcodetxt/isqrt.c.txt */
954uint32_t osmo_isqrt32(uint32_t x)
955{
956 uint32_t x1;
957 int s, g0, g1;
958
959 if (x <= 1)
960 return x;
961
962 s = 1;
963 x1 = x - 1;
964 if (x1 > 0xffff) {
965 s = s + 8;
966 x1 = x1 >> 16;
967 }
968 if (x1 > 0xff) {
969 s = s + 4;
970 x1 = x1 >> 8;
971 }
972 if (x1 > 0xf) {
973 s = s + 2;
974 x1 = x1 >> 4;
975 }
976 if (x1 > 0x3) {
977 s = s + 1;
978 }
979
980 g0 = 1 << s; /* g0 = 2**s */
981 g1 = (g0 + (x >> s)) >> 1; /* g1 = (g0 + x/g0)/2 */
982
983 /* converges after four to five divisions for arguments up to 16,785,407 */
984 while (g1 < g0) {
985 g0 = g1;
986 g1 = (g0 + (x/g0)) >> 1;
987 }
988 return g0;
989}
990
Neels Hofmeyr7c749892018-09-07 03:01:38 +0200991/*! Convert a string to lowercase, while checking buffer size boundaries.
992 * The result written to \a dest is guaranteed to be nul terminated if \a dest_len > 0.
993 * If dest == src, the string is converted in-place, if necessary truncated at dest_len - 1 characters
994 * length as well as nul terminated.
995 * Note: similar osmo_str2lower(), but safe to use for src strings of arbitrary length.
996 * \param[out] dest Target buffer to write lowercase string.
997 * \param[in] dest_len Maximum buffer size of dest (e.g. sizeof(dest)).
998 * \param[in] src String to convert to lowercase.
999 * \returns Length of \a src, like osmo_strlcpy(), but if \a dest == \a src at most \a dest_len - 1.
1000 */
1001size_t osmo_str_tolower_buf(char *dest, size_t dest_len, const char *src)
1002{
1003 size_t rc;
1004 if (dest == src) {
1005 if (dest_len < 1)
1006 return 0;
1007 dest[dest_len - 1] = '\0';
1008 rc = strlen(dest);
1009 } else {
1010 if (dest_len < 1)
1011 return strlen(src);
1012 rc = osmo_strlcpy(dest, src, dest_len);
1013 }
1014 for (; *dest; dest++)
1015 *dest = tolower(*dest);
1016 return rc;
1017}
1018
1019/*! Convert a string to lowercase, using a static buffer.
1020 * The resulting string may be truncated if the internally used static buffer is shorter than src.
1021 * The internal buffer is at least 128 bytes long, i.e. guaranteed to hold at least 127 characters and a
Pau Espin Pedrola37f58e2019-08-01 18:11:41 +02001022 * terminating nul. The static buffer returned is shared with osmo_str_toupper().
Neels Hofmeyr7c749892018-09-07 03:01:38 +02001023 * See also osmo_str_tolower_buf().
1024 * \param[in] src String to convert to lowercase.
1025 * \returns Resulting lowercase string in a static buffer, always nul terminated.
1026 */
1027const char *osmo_str_tolower(const char *src)
1028{
Pau Espin Pedrola37f58e2019-08-01 18:11:41 +02001029 osmo_str_tolower_buf(capsbuf, sizeof(capsbuf), src);
1030 return capsbuf;
Neels Hofmeyr7c749892018-09-07 03:01:38 +02001031}
1032
Harald Welte179f3572019-03-18 18:38:47 +01001033/*! Convert a string to lowercase, dynamically allocating the output from given talloc context
1034 * See also osmo_str_tolower_buf().
1035 * \param[in] ctx talloc context from where to allocate the output string
1036 * \param[in] src String to convert to lowercase.
1037 * \returns Resulting lowercase string in a dynamically allocated buffer, always nul terminated.
1038 */
1039char *osmo_str_tolower_c(const void *ctx, const char *src)
1040{
Vadim Yanitskiy4f619c22019-04-12 21:48:07 +07001041 size_t buf_len = strlen(src) + 1;
1042 char *buf = talloc_size(ctx, buf_len);
Harald Welte179f3572019-03-18 18:38:47 +01001043 if (!buf)
1044 return NULL;
Vadim Yanitskiy4f619c22019-04-12 21:48:07 +07001045 osmo_str_tolower_buf(buf, buf_len, src);
Harald Welte179f3572019-03-18 18:38:47 +01001046 return buf;
1047}
1048
Neels Hofmeyr7c749892018-09-07 03:01:38 +02001049/*! Convert a string to uppercase, while checking buffer size boundaries.
1050 * The result written to \a dest is guaranteed to be nul terminated if \a dest_len > 0.
1051 * If dest == src, the string is converted in-place, if necessary truncated at dest_len - 1 characters
1052 * length as well as nul terminated.
1053 * Note: similar osmo_str2upper(), but safe to use for src strings of arbitrary length.
1054 * \param[out] dest Target buffer to write uppercase string.
1055 * \param[in] dest_len Maximum buffer size of dest (e.g. sizeof(dest)).
1056 * \param[in] src String to convert to uppercase.
1057 * \returns Length of \a src, like osmo_strlcpy(), but if \a dest == \a src at most \a dest_len - 1.
1058 */
1059size_t osmo_str_toupper_buf(char *dest, size_t dest_len, const char *src)
1060{
1061 size_t rc;
1062 if (dest == src) {
1063 if (dest_len < 1)
1064 return 0;
1065 dest[dest_len - 1] = '\0';
1066 rc = strlen(dest);
1067 } else {
1068 if (dest_len < 1)
1069 return strlen(src);
1070 rc = osmo_strlcpy(dest, src, dest_len);
1071 }
1072 for (; *dest; dest++)
1073 *dest = toupper(*dest);
1074 return rc;
1075}
1076
1077/*! Convert a string to uppercase, using a static buffer.
1078 * The resulting string may be truncated if the internally used static buffer is shorter than src.
1079 * The internal buffer is at least 128 bytes long, i.e. guaranteed to hold at least 127 characters and a
Pau Espin Pedrola37f58e2019-08-01 18:11:41 +02001080 * terminating nul. The static buffer returned is shared with osmo_str_tolower().
Neels Hofmeyr7c749892018-09-07 03:01:38 +02001081 * See also osmo_str_toupper_buf().
1082 * \param[in] src String to convert to uppercase.
1083 * \returns Resulting uppercase string in a static buffer, always nul terminated.
1084 */
1085const char *osmo_str_toupper(const char *src)
1086{
Pau Espin Pedrola37f58e2019-08-01 18:11:41 +02001087 osmo_str_toupper_buf(capsbuf, sizeof(capsbuf), src);
1088 return capsbuf;
Neels Hofmeyr7c749892018-09-07 03:01:38 +02001089}
1090
Harald Welte179f3572019-03-18 18:38:47 +01001091/*! Convert a string to uppercase, dynamically allocating the output from given talloc context
1092 * See also osmo_str_tolower_buf().
1093 * \param[in] ctx talloc context from where to allocate the output string
1094 * \param[in] src String to convert to uppercase.
1095 * \returns Resulting uppercase string in a dynamically allocated buffer, always nul terminated.
1096 */
1097char *osmo_str_toupper_c(const void *ctx, const char *src)
1098{
Vadim Yanitskiy4f619c22019-04-12 21:48:07 +07001099 size_t buf_len = strlen(src) + 1;
1100 char *buf = talloc_size(ctx, buf_len);
Harald Welte179f3572019-03-18 18:38:47 +01001101 if (!buf)
1102 return NULL;
Vadim Yanitskiy4f619c22019-04-12 21:48:07 +07001103 osmo_str_toupper_buf(buf, buf_len, src);
Harald Welte179f3572019-03-18 18:38:47 +01001104 return buf;
1105}
1106
Oliver Smith894be2d2019-01-11 13:13:37 +01001107/*! Calculate the Luhn checksum (as used for IMEIs).
1108 * \param[in] in Input digits in ASCII string representation.
1109 * \param[in] in_len Count of digits to use for the input (14 for IMEI).
1110 * \returns checksum char (e.g. '3'); negative on error
1111 */
Vadim Yanitskiyd9fc6042019-06-12 15:49:03 +07001112char osmo_luhn(const char* in, int in_len)
Oliver Smith894be2d2019-01-11 13:13:37 +01001113{
1114 int i, sum = 0;
1115
1116 /* All input must be numbers */
1117 for (i = 0; i < in_len; i++) {
Kévin Redon1af2cd52019-05-23 19:00:19 +02001118 if (!isdigit((unsigned char)in[i]))
Oliver Smith894be2d2019-01-11 13:13:37 +01001119 return -EINVAL;
1120 }
1121
1122 /* Double every second digit and add it to sum */
1123 for (i = in_len - 1; i >= 0; i -= 2) {
1124 int dbl = (in[i] - '0') * 2;
1125 if (dbl > 9)
1126 dbl -= 9;
1127 sum += dbl;
1128 }
1129
1130 /* Add other digits to sum */
1131 for (i = in_len - 2; i >= 0; i -= 2)
1132 sum += in[i] - '0';
1133
1134 /* Final checksum */
1135 return (sum * 9) % 10 + '0';
1136}
1137
Neels Hofmeyrd79ccc62019-03-07 23:08:40 +01001138/*! Compare start of a string.
1139 * This is an optimisation of 'strstr(str, startswith_str) == str' because it doesn't search through the entire string.
1140 * \param str (Longer) string to compare.
1141 * \param startswith_str (Shorter) string to compare with the start of str.
1142 * \return true iff the first characters of str fully match startswith_str or startswith_str is empty. */
1143bool osmo_str_startswith(const char *str, const char *startswith_str)
1144{
1145 if (!startswith_str || !*startswith_str)
1146 return true;
1147 if (!str)
1148 return false;
1149 return strncmp(str, startswith_str, strlen(startswith_str)) == 0;
1150}
1151
Neels Hofmeyr0aeda1b2017-01-13 14:16:02 +01001152/*! @} */