blob: 772b67147e9f2ac6a72798a85cee90d3fdbd12d7 [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
Neels Hofmeyr0b6a8c82020-06-12 16:34:20 +0200157 if (!dst || dst_size < 1 || start_nibble < 0)
Neels Hofmeyr7079e692018-12-05 21:02:36 +0100158 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 Hofmeyr83025bf2020-05-26 02:45:23 +0200178/*! Convert string to BCD.
179 * The given nibble offsets are interpreted in BCD order, i.e. nibble 0 is bcd[0] & 0x0f, nibble 1 is bcd[0] & 0xf0, nibble
180 * 3 is bcd[1] & 0x0f, etc..
181 * \param[out] dst Output BCD buffer.
182 * \param[in] dst_size sizeof() the output string buffer.
183 * \param[in] digits String containing decimal or hexadecimal digits in upper or lower case.
184 * \param[in] start_nibble Offset to start from, in nibbles, typically 1 to skip the first (MI type) nibble.
185 * \param[in] end_nibble Negative to write all digits found in str, followed by 0xf nibbles to fill any started octet.
186 * If >= 0, stop before this offset in nibbles, e.g. to get default behavior, pass
187 * start_nibble + strlen(str) + ((start_nibble + strlen(str)) & 1? 1 : 0) + 1.
188 * \param[in] allow_hex If false, return error if there are hexadecimal digits (A-F). If true, write those to
189 * BCD.
190 * \returns The buffer size in octets that is used to place all bcd digits (including the skipped nibbles
191 * from 'start_nibble' and rounded up to full octets); -EINVAL on invalid digits;
192 * -ENOMEM if dst is NULL, if dst_size is too small to contain all nibbles, or if start_nibble is negative.
193 */
194int osmo_str2bcd(uint8_t *dst, size_t dst_size, const char *digits, int start_nibble, int end_nibble, bool allow_hex)
195{
196 const char *digit = digits;
197 int nibble_i;
198
199 if (!dst || !dst_size || start_nibble < 0)
200 return -ENOMEM;
201
202 if (end_nibble < 0) {
203 end_nibble = start_nibble + strlen(digits);
204 /* If the last octet is not complete, add another filler nibble */
205 if (end_nibble & 1)
206 end_nibble++;
207 }
208 if ((end_nibble / 2) > dst_size)
209 return -ENOMEM;
210
211 for (nibble_i = start_nibble; nibble_i < end_nibble; nibble_i++) {
212 uint8_t nibble = 0xf;
213 int octet = nibble_i >> 1;
214 if (*digit) {
215 char c = *digit;
216 digit++;
217 if (c >= '0' && c <= '9')
218 nibble = c - '0';
219 else if (allow_hex && c >= 'A' && c <= 'F')
220 nibble = 0xa + (c - 'A');
221 else if (allow_hex && c >= 'a' && c <= 'f')
222 nibble = 0xa + (c - 'a');
223 else
224 return -EINVAL;
225 }
226 nibble &= 0xf;
227 if ((nibble_i & 1))
228 dst[octet] = (nibble << 4) | (dst[octet] & 0x0f);
229 else
230 dst[octet] = (dst[octet] & 0xf0) | nibble;
231 }
232
233 /* floor(float(end_nibble) / 2) */
234 return end_nibble / 2;
235}
236
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200237/*! Parse a string containing hexadecimal digits
Harald Weltede6e4982012-12-06 21:25:27 +0100238 * \param[in] str string containing ASCII encoded hexadecimal digits
239 * \param[out] b output buffer
240 * \param[in] max_len maximum space in output buffer
Neels Hofmeyr3de7b052015-09-23 23:16:53 +0200241 * \returns number of parsed octets, or -1 on error
Harald Weltede6e4982012-12-06 21:25:27 +0100242 */
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200243int osmo_hexparse(const char *str, uint8_t *b, int max_len)
Harald Welte3eba9912010-07-30 10:37:29 +0200244
245{
Neels Hofmeyr437ed4a2017-02-14 15:54:31 +0100246 char c;
247 uint8_t v;
248 const char *strpos;
249 unsigned int nibblepos = 0;
Harald Welte3eba9912010-07-30 10:37:29 +0200250
251 memset(b, 0x00, max_len);
252
Neels Hofmeyr437ed4a2017-02-14 15:54:31 +0100253 for (strpos = str; (c = *strpos); strpos++) {
254 /* skip whitespace */
255 if (c == ' ' || c == '\t' || c == '\n' || c == '\r')
256 continue;
257
258 /* If the buffer is too small, error out */
259 if (nibblepos >= (max_len << 1))
260 return -1;
261
Harald Welte3eba9912010-07-30 10:37:29 +0200262 if (c >= '0' && c <= '9')
263 v = c - '0';
264 else if (c >= 'a' && c <= 'f')
265 v = 10 + (c - 'a');
266 else if (c >= 'A' && c <= 'F')
267 v = 10 + (c - 'A');
268 else
269 return -1;
Neels Hofmeyr437ed4a2017-02-14 15:54:31 +0100270
271 b[nibblepos >> 1] |= v << (nibblepos & 1 ? 0 : 4);
272 nibblepos ++;
Harald Welte3eba9912010-07-30 10:37:29 +0200273 }
274
Neels Hofmeyr437ed4a2017-02-14 15:54:31 +0100275 /* In case of uneven amount of digits, the last byte is not complete
276 * and that's an error. */
277 if (nibblepos & 1)
278 return -1;
279
280 return nibblepos >> 1;
Harald Welte3eba9912010-07-30 10:37:29 +0200281}
Harald Welte40481e82010-07-30 11:40:32 +0200282
Harald Welte171ef822019-03-28 10:49:05 +0100283static __thread char hexd_buff[4096];
Nils O. Selåsdal32447022014-01-02 14:04:43 +0100284static const char hex_chars[] = "0123456789abcdef";
Harald Welte40481e82010-07-30 11:40:32 +0200285
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100286/*! Convert binary sequence to hexadecimal ASCII string.
287 * \param[out] out_buf Output buffer to write the resulting string to.
288 * \param[in] out_buf_size sizeof(out_buf).
289 * \param[in] buf Input buffer, pointer to sequence of bytes.
290 * \param[in] len Length of input buf in number of bytes.
291 * \param[in] delim String to separate each byte; NULL or "" for no delim.
292 * \param[in] delim_after_last If true, end the string in delim (true: "1a:ef:d9:", false: "1a:ef:d9");
293 * if out_buf has insufficient space, the string will always end in a delim.
294 * \returns out_buf, containing a zero-terminated string, or "" (empty string) if out_buf == NULL or out_buf_size < 1.
295 *
296 * This function will print a sequence of bytes as hexadecimal numbers, adding one delim between each byte (e.g. for
297 * delim passed as ":", return a string like "1a:ef:d9").
298 *
299 * The delim_after_last argument exists to be able to exactly show the original osmo_hexdump() behavior, which always
300 * ends the string with a delimiter.
301 */
302const char *osmo_hexdump_buf(char *out_buf, size_t out_buf_size, const unsigned char *buf, int len, const char *delim,
303 bool delim_after_last)
Harald Welte40481e82010-07-30 11:40:32 +0200304{
305 int i;
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100306 char *cur = out_buf;
307 size_t delim_len;
Harald Welte40481e82010-07-30 11:40:32 +0200308
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100309 if (!out_buf || !out_buf_size)
310 return "";
311
312 delim = delim ? : "";
313 delim_len = strlen(delim);
314
Harald Welte40481e82010-07-30 11:40:32 +0200315 for (i = 0; i < len; i++) {
Nils O. Selåsdal32447022014-01-02 14:04:43 +0100316 const char *delimp = delim;
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100317 int len_remain = out_buf_size - (cur - out_buf) - 1;
318 if (len_remain < (2 + delim_len)
319 && !(!delim_after_last && i == (len - 1) && len_remain >= 2))
Holger Hans Peter Freyther128d9e22011-07-15 16:07:23 +0200320 break;
Nils O. Selåsdal32447022014-01-02 14:04:43 +0100321
322 *cur++ = hex_chars[buf[i] >> 4];
323 *cur++ = hex_chars[buf[i] & 0xf];
324
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100325 if (i == (len - 1) && !delim_after_last)
326 break;
327
Nils O. Selåsdal32447022014-01-02 14:04:43 +0100328 while (len_remain > 1 && *delimp) {
329 *cur++ = *delimp++;
330 len_remain--;
331 }
Harald Welte40481e82010-07-30 11:40:32 +0200332 }
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100333 *cur = '\0';
334 return out_buf;
Harald Welte40481e82010-07-30 11:40:32 +0200335}
Harald Weltedee47cd2010-07-30 11:43:30 +0200336
Harald Welte4a62eda2019-03-18 18:27:00 +0100337/*! Convert a sequence of unpacked bits to ASCII string, in user-supplied buffer.
338 * \param[out] buf caller-provided output string buffer
339 * \param[out] buf_len size of buf in bytes
Harald Welte8598f182011-08-17 14:19:27 +0200340 * \param[in] bits A sequence of unpacked bits
341 * \param[in] len Length of bits
Neels Hofmeyrdd7b6f92019-11-20 21:32:29 +0100342 * \return The output buffer (buf).
Harald Welte8598f182011-08-17 14:19:27 +0200343 */
Harald Welte4a62eda2019-03-18 18:27:00 +0100344char *osmo_ubit_dump_buf(char *buf, size_t buf_len, const uint8_t *bits, unsigned int len)
Harald Welte3d0ac5e2011-02-08 16:55:03 +0100345{
346 int i;
347
Harald Welte4a62eda2019-03-18 18:27:00 +0100348 if (len > buf_len-1)
349 len = buf_len-1;
350 memset(buf, 0, buf_len);
Harald Welte3d0ac5e2011-02-08 16:55:03 +0100351
352 for (i = 0; i < len; i++) {
353 char outch;
354 switch (bits[i]) {
355 case 0:
356 outch = '0';
357 break;
358 case 0xff:
359 outch = '?';
360 break;
361 case 1:
362 outch = '1';
363 break;
364 default:
365 outch = 'E';
366 break;
367 }
Harald Welte4a62eda2019-03-18 18:27:00 +0100368 buf[i] = outch;
Harald Welte3d0ac5e2011-02-08 16:55:03 +0100369 }
Harald Welte4a62eda2019-03-18 18:27:00 +0100370 buf[buf_len-1] = 0;
371 return buf;
372}
373
374/*! Convert a sequence of unpacked bits to ASCII string, in static buffer.
375 * \param[in] bits A sequence of unpacked bits
376 * \param[in] len Length of bits
377 * \returns string representation in static buffer.
378 */
379char *osmo_ubit_dump(const uint8_t *bits, unsigned int len)
380{
381 return osmo_ubit_dump_buf(hexd_buff, sizeof(hexd_buff), bits, len);
Harald Welte3d0ac5e2011-02-08 16:55:03 +0100382}
383
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200384/*! Convert binary sequence to hexadecimal ASCII string
Harald Welte8598f182011-08-17 14:19:27 +0200385 * \param[in] buf pointer to sequence of bytes
386 * \param[in] len length of buf in number of bytes
387 * \returns pointer to zero-terminated string
388 *
389 * This function will print a sequence of bytes as hexadecimal numbers,
390 * adding one space character between each byte (e.g. "1a ef d9")
Harald Welte096a6662017-10-16 14:33:11 +0200391 *
392 * The maximum size of the output buffer is 4096 bytes, i.e. the maximum
393 * number of input bytes that can be printed in one call is 1365!
Harald Welte8598f182011-08-17 14:19:27 +0200394 */
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +0200395char *osmo_hexdump(const unsigned char *buf, int len)
Harald Weltedee47cd2010-07-30 11:43:30 +0200396{
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100397 osmo_hexdump_buf(hexd_buff, sizeof(hexd_buff), buf, len, " ", true);
398 return hexd_buff;
Harald Weltedee47cd2010-07-30 11:43:30 +0200399}
400
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200401/*! Convert binary sequence to hexadecimal ASCII string
Harald Welte179f3572019-03-18 18:38:47 +0100402 * \param[in] ctx talloc context from where to allocate the output string
403 * \param[in] buf pointer to sequence of bytes
404 * \param[in] len length of buf in number of bytes
405 * \returns pointer to zero-terminated string
406 *
407 * This function will print a sequence of bytes as hexadecimal numbers,
408 * adding one space character between each byte (e.g. "1a ef d9")
409 *
410 * The maximum size of the output buffer is 4096 bytes, i.e. the maximum
411 * number of input bytes that can be printed in one call is 1365!
412 */
413char *osmo_hexdump_c(const void *ctx, const unsigned char *buf, int len)
414{
Vadim Yanitskiy4f619c22019-04-12 21:48:07 +0700415 size_t hexd_buff_len = len * 3 + 1;
416 char *hexd_buff = talloc_size(ctx, hexd_buff_len);
Harald Welte179f3572019-03-18 18:38:47 +0100417 if (!hexd_buff)
418 return NULL;
Vadim Yanitskiy4f619c22019-04-12 21:48:07 +0700419 osmo_hexdump_buf(hexd_buff, hexd_buff_len, buf, len, " ", true);
Harald Welte179f3572019-03-18 18:38:47 +0100420 return hexd_buff;
421}
422
423/*! Convert binary sequence to hexadecimal ASCII string
Harald Welte8598f182011-08-17 14:19:27 +0200424 * \param[in] buf pointer to sequence of bytes
425 * \param[in] len length of buf in number of bytes
426 * \returns pointer to zero-terminated string
427 *
428 * This function will print a sequence of bytes as hexadecimal numbers,
429 * without any space character between each byte (e.g. "1aefd9")
Harald Welte096a6662017-10-16 14:33:11 +0200430 *
431 * The maximum size of the output buffer is 4096 bytes, i.e. the maximum
432 * number of input bytes that can be printed in one call is 2048!
Harald Welte8598f182011-08-17 14:19:27 +0200433 */
Sylvain Munautff23d242011-11-10 23:03:18 +0100434char *osmo_hexdump_nospc(const unsigned char *buf, int len)
Harald Weltedee47cd2010-07-30 11:43:30 +0200435{
Neels Hofmeyr0423b612019-01-14 23:32:53 +0100436 osmo_hexdump_buf(hexd_buff, sizeof(hexd_buff), buf, len, "", true);
437 return hexd_buff;
Harald Weltedee47cd2010-07-30 11:43:30 +0200438}
Harald Welte28222962011-02-18 20:37:04 +0100439
Harald Welte179f3572019-03-18 18:38:47 +0100440/*! Convert binary sequence to hexadecimal ASCII string
441 * \param[in] ctx talloc context from where to allocate the output string
442 * \param[in] buf pointer to sequence of bytes
443 * \param[in] len length of buf in number of bytes
444 * \returns pointer to zero-terminated string
445 *
446 * This function will print a sequence of bytes as hexadecimal numbers,
447 * without any space character between each byte (e.g. "1aefd9")
448 *
449 * The maximum size of the output buffer is 4096 bytes, i.e. the maximum
450 * number of input bytes that can be printed in one call is 2048!
451 */
452char *osmo_hexdump_nospc_c(const void *ctx, const unsigned char *buf, int len)
453{
Vadim Yanitskiy4f619c22019-04-12 21:48:07 +0700454 size_t hexd_buff_len = len * 2 + 1;
455 char *hexd_buff = talloc_size(ctx, hexd_buff_len);
Harald Welte179f3572019-03-18 18:38:47 +0100456 if (!hexd_buff)
457 return NULL;
Vadim Yanitskiy4f619c22019-04-12 21:48:07 +0700458 osmo_hexdump_buf(hexd_buff, hexd_buff_len, buf, len, "", true);
Harald Welte179f3572019-03-18 18:38:47 +0100459 return hexd_buff;
460}
461
462
Holger Hans Peter Freyther9a1a5a12015-04-11 19:26:55 +0200463/* Compat with previous typo to preserve abi */
Sylvain Munaute55ae3a2011-11-11 23:06:55 +0100464char *osmo_osmo_hexdump_nospc(const unsigned char *buf, int len)
Holger Hans Peter Freyther9a1a5a12015-04-11 19:26:55 +0200465#if defined(__MACH__) && defined(__APPLE__)
466 ;
467#else
Sylvain Munaut17af41d2011-11-19 22:30:39 +0100468 __attribute__((weak, alias("osmo_hexdump_nospc")));
Holger Hans Peter Freyther9a1a5a12015-04-11 19:26:55 +0200469#endif
Sylvain Munaute55ae3a2011-11-11 23:06:55 +0100470
Harald Welte28222962011-02-18 20:37:04 +0100471#include "../config.h"
472#ifdef HAVE_CTYPE_H
473#include <ctype.h>
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200474/*! Convert an entire string to lower case
Harald Welte8598f182011-08-17 14:19:27 +0200475 * \param[out] out output string, caller-allocated
476 * \param[in] in input string
477 */
Harald Welte28222962011-02-18 20:37:04 +0100478void osmo_str2lower(char *out, const char *in)
479{
480 unsigned int i;
481
482 for (i = 0; i < strlen(in); i++)
Pau Espin Pedrol399a6f02017-06-18 14:07:37 +0200483 out[i] = tolower((const unsigned char)in[i]);
Harald Welte28222962011-02-18 20:37:04 +0100484 out[strlen(in)] = '\0';
485}
486
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200487/*! Convert an entire string to upper case
Harald Welte8598f182011-08-17 14:19:27 +0200488 * \param[out] out output string, caller-allocated
489 * \param[in] in input string
490 */
Harald Welte28222962011-02-18 20:37:04 +0100491void osmo_str2upper(char *out, const char *in)
492{
493 unsigned int i;
494
495 for (i = 0; i < strlen(in); i++)
Pau Espin Pedrol399a6f02017-06-18 14:07:37 +0200496 out[i] = toupper((const unsigned char)in[i]);
Harald Welte28222962011-02-18 20:37:04 +0100497 out[strlen(in)] = '\0';
498}
499#endif /* HAVE_CTYPE_H */
Harald Welte8598f182011-08-17 14:19:27 +0200500
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200501/*! Wishful thinking to generate a constant time compare
Harald Welte9709b2e2016-04-25 18:47:53 +0200502 * \param[in] exp Expected data
503 * \param[in] rel Comparison value
504 * \param[in] count Number of bytes to compare
505 * \returns 1 in case \a exp equals \a rel; zero otherwise
506 *
507 * Compare count bytes of exp to rel. Return 0 if they are identical, 1
508 * otherwise. Do not return a mismatch on the first mismatching byte,
509 * but always compare all bytes, regardless. The idea is that the amount of
510 * matching bytes cannot be inferred from the time the comparison took. */
511int osmo_constant_time_cmp(const uint8_t *exp, const uint8_t *rel, const int count)
512{
513 int x = 0, i;
514
515 for (i = 0; i < count; ++i)
516 x |= exp[i] ^ rel[i];
517
518 /* if x is zero, all data was identical */
519 return x? 1 : 0;
520}
521
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200522/*! Generic retrieval of 1..8 bytes as big-endian uint64_t
Harald Welte9709b2e2016-04-25 18:47:53 +0200523 * \param[in] data Input data as byte-array
524 * \param[in] data_len Length of \a data in octets
525 * \returns uint64_t of \a data interpreted as big-endian
526 *
527 * This is like osmo_load64be_ext, except that if data_len is less than
528 * sizeof(uint64_t), the data is interpreted as the least significant bytes
529 * (osmo_load64be_ext loads them as the most significant bytes into the
530 * returned uint64_t). In this way, any integer size up to 64 bits can be
531 * decoded conveniently by using sizeof(), without the need to call specific
532 * numbered functions (osmo_load16, 32, ...). */
533uint64_t osmo_decode_big_endian(const uint8_t *data, size_t data_len)
534{
535 uint64_t value = 0;
536
537 while (data_len > 0) {
538 value = (value << 8) + *data;
539 data += 1;
540 data_len -= 1;
541 }
542
543 return value;
544}
545
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200546/*! Generic big-endian encoding of big endian number up to 64bit
Harald Welte9709b2e2016-04-25 18:47:53 +0200547 * \param[in] value unsigned integer value to be stored
Pau Espin Pedrolc29d5132020-09-21 17:09:31 +0200548 * \param[in] data_len number of octets
Harald Welte9709b2e2016-04-25 18:47:53 +0200549 * \returns static buffer containing big-endian stored value
550 *
551 * This is like osmo_store64be_ext, except that this returns a static buffer of
552 * the result (for convenience, but not threadsafe). If data_len is less than
553 * sizeof(uint64_t), only the least significant bytes of value are encoded. */
554uint8_t *osmo_encode_big_endian(uint64_t value, size_t data_len)
555{
Harald Welte171ef822019-03-28 10:49:05 +0100556 static __thread uint8_t buf[sizeof(uint64_t)];
Harald Welte9709b2e2016-04-25 18:47:53 +0200557 OSMO_ASSERT(data_len <= ARRAY_SIZE(buf));
558 osmo_store64be_ext(value, buf, data_len);
559 return buf;
560}
Harald Welteaeecc482016-11-26 10:41:40 +0100561
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200562/*! Copy a C-string into a sized buffer
Harald Welteaeecc482016-11-26 10:41:40 +0100563 * \param[in] src source string
564 * \param[out] dst destination string
Neels Hofmeyrdf83ece2017-01-13 13:55:43 +0100565 * \param[in] siz size of the \a dst buffer
566 * \returns length of \a src
Harald Welteaeecc482016-11-26 10:41:40 +0100567 *
Neels Hofmeyrdf83ece2017-01-13 13:55:43 +0100568 * Copy at most \a siz bytes from \a src to \a dst, ensuring that the result is
569 * NUL terminated. The NUL character is included in \a siz, i.e. passing the
570 * actual sizeof(*dst) is correct.
Neels Hofmeyrff65d242019-11-19 00:21:14 +0100571 *
572 * Note, a similar function that also limits the input buffer size is osmo_print_n().
Harald Welteaeecc482016-11-26 10:41:40 +0100573 */
574size_t osmo_strlcpy(char *dst, const char *src, size_t siz)
575{
Neels Hofmeyrbcf9f232017-10-25 04:16:45 +0200576 size_t ret = src ? strlen(src) : 0;
Harald Welteaeecc482016-11-26 10:41:40 +0100577
578 if (siz) {
Pau Espin Pedrol53fbc672020-09-21 17:13:30 +0200579 size_t len = OSMO_MIN(siz - 1, ret);
Pau Espin Pedrolc29d5132020-09-21 17:09:31 +0200580 if (len)
Neels Hofmeyrebd3cdd2017-11-18 23:07:38 +0100581 memcpy(dst, src, len);
Harald Welteaeecc482016-11-26 10:41:40 +0100582 dst[len] = '\0';
583 }
584 return ret;
585}
Neels Hofmeyr0aeda1b2017-01-13 14:16:02 +0100586
Neels Hofmeyr06356fd2019-11-19 01:38:10 +0100587/*! Find first occurence of a char in a size limited string.
588 * Like strchr() but with a buffer size limit.
589 * \param[in] str String buffer to examine.
590 * \param[in] str_size sizeof(str).
591 * \param[in] c Character to look for.
592 * \return Pointer to the matched char, or NULL if not found.
593 */
594const char *osmo_strnchr(const char *str, size_t str_size, char c)
595{
596 const char *end = str + str_size;
597 const char *pos;
598 if (!str)
599 return NULL;
600 for (pos = str; pos < end; pos++) {
601 if (c == *pos)
602 return pos;
603 if (!*pos)
604 return NULL;
605 }
606 return NULL;
607}
608
Neels Hofmeyr4335bad2017-10-07 04:39:14 +0200609/*! Validate that a given string is a hex string within given size limits.
610 * Note that each hex digit amounts to a nibble, so if checking for a hex
611 * string to result in N bytes, pass amount of digits as 2*N.
612 * \param str A nul-terminated string to validate, or NULL.
613 * \param min_digits least permitted amount of digits.
614 * \param max_digits most permitted amount of digits.
615 * \param require_even if true, require an even amount of digits.
616 * \returns true when the hex_str contains only hexadecimal digits (no
617 * whitespace) and matches the requested length; also true
618 * when min_digits <= 0 and str is NULL.
619 */
620bool osmo_is_hexstr(const char *str, int min_digits, int max_digits,
621 bool require_even)
622{
623 int len;
624 /* Use unsigned char * to avoid a compiler warning of
625 * "error: array subscript has type 'char' [-Werror=char-subscripts]" */
626 const unsigned char *pos = (const unsigned char*)str;
627 if (!pos)
628 return min_digits < 1;
629 for (len = 0; *pos && len < max_digits; len++, pos++)
630 if (!isxdigit(*pos))
631 return false;
632 if (len < min_digits)
633 return false;
634 /* With not too many digits, we should have reached *str == nul */
635 if (*pos)
636 return false;
637 if (require_even && (len & 1))
638 return false;
Harald Weltefebe83c2017-10-03 17:41:59 +0800639
640 return true;
641}
642
Neels Hofmeyrb480b742019-04-11 06:58:44 +0200643static const char osmo_identifier_illegal_chars[] = "., {}[]()<>|~\\^`'\"?=;/+*&%$#!";
644
Harald Weltefebe83c2017-10-03 17:41:59 +0800645/*! Determine if a given identifier is valid, i.e. doesn't contain illegal chars
646 * \param[in] str String to validate
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100647 * \param[in] sep_chars Permitted separation characters between identifiers.
648 * \returns true in case \a str contains only valid identifiers and sep_chars, false otherwise
Harald Weltefebe83c2017-10-03 17:41:59 +0800649 */
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100650bool osmo_separated_identifiers_valid(const char *str, const char *sep_chars)
Harald Weltefebe83c2017-10-03 17:41:59 +0800651{
652 /* characters that are illegal in names */
Harald Weltefebe83c2017-10-03 17:41:59 +0800653 unsigned int i;
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100654 size_t len;
Harald Weltefebe83c2017-10-03 17:41:59 +0800655
656 /* an empty string is not a valid identifier */
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100657 if (!str || (len = strlen(str)) == 0)
Harald Weltefebe83c2017-10-03 17:41:59 +0800658 return false;
659
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100660 for (i = 0; i < len; i++) {
661 if (sep_chars && strchr(sep_chars, str[i]))
662 continue;
Harald Weltefebe83c2017-10-03 17:41:59 +0800663 /* check for 7-bit ASCII */
664 if (str[i] & 0x80)
665 return false;
Neels Hofmeyre5a2bdb2017-12-16 04:54:37 +0100666 if (!isprint((int)str[i]))
667 return false;
Harald Weltefebe83c2017-10-03 17:41:59 +0800668 /* check for some explicit reserved control characters */
Neels Hofmeyrb480b742019-04-11 06:58:44 +0200669 if (strchr(osmo_identifier_illegal_chars, str[i]))
Harald Weltefebe83c2017-10-03 17:41:59 +0800670 return false;
671 }
672
Neels Hofmeyr4335bad2017-10-07 04:39:14 +0200673 return true;
674}
675
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100676/*! Determine if a given identifier is valid, i.e. doesn't contain illegal chars
677 * \param[in] str String to validate
678 * \returns true in case \a str contains valid identifier, false otherwise
679 */
680bool osmo_identifier_valid(const char *str)
681{
682 return osmo_separated_identifiers_valid(str, NULL);
683}
684
Neels Hofmeyrb480b742019-04-11 06:58:44 +0200685/*! Replace characters in the given string buffer so that it is guaranteed to pass osmo_separated_identifiers_valid().
686 * To guarantee passing osmo_separated_identifiers_valid(), replace_with must not itself be an illegal character. If in
687 * doubt, use '-'.
688 * \param[inout] str Identifier to sanitize, must be nul terminated and in a writable buffer.
689 * \param[in] sep_chars Additional characters that are allowed besides osmo_identifier_illegal_chars.
690 * \param[in] replace_with Replace any illegal characters with this character.
691 */
692void osmo_identifier_sanitize_buf(char *str, const char *sep_chars, char replace_with)
693{
694 char *pos;
695 if (!str)
696 return;
697 for (pos = str; *pos; pos++) {
698 if (strchr(osmo_identifier_illegal_chars, *pos)
699 || (sep_chars && strchr(sep_chars, *pos)))
700 *pos = replace_with;
701 }
702}
703
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100704/*! Like osmo_escape_str_buf2, but with unusual ordering of arguments, and may sometimes return string constants instead
705 * of writing to buf for error cases or empty input.
706 * Most *_buf() functions have the buffer and size as first arguments, here the arguments are last.
707 * In particular, this function signature doesn't work with OSMO_STRBUF_APPEND_NOLEN().
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100708 * \param[in] str A string that may contain any characters.
709 * \param[in] len Pass -1 to print until nul char, or >= 0 to force a length.
710 * \param[inout] buf string buffer to write escaped characters to.
711 * \param[in] bufsize size of \a buf.
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100712 * \returns buf containing an escaped representation, possibly truncated,
713 * or "(null)" if str == NULL, or "(error)" in case of errors.
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100714 */
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100715const char *osmo_escape_str_buf(const char *str, int in_len, char *buf, size_t bufsize)
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100716{
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100717 if (!str)
718 return "(null)";
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100719 if (!buf || !bufsize)
720 return "(error)";
721 return osmo_escape_str_buf2(buf, bufsize, str, in_len);
722}
723
724/*! Copy N characters to a buffer with a function signature useful for OSMO_STRBUF_APPEND().
725 * Similarly to snprintf(), the result is always nul terminated (except if buf is NULL or bufsize is 0).
726 * \param[out] buf Target buffer.
727 * \param[in] bufsize sizeof(buf).
728 * \param[in] str String to copy.
729 * \param[in] n Maximum number of non-nul characters to copy.
730 * \return Number of characters that would be written if bufsize were large enough excluding '\0' (like snprintf()).
731 */
732int osmo_print_n(char *buf, size_t bufsize, const char *str, size_t n)
733{
734 size_t write_n;
735
736 if (!str)
737 str = "";
738
739 n = strnlen(str, n);
740
741 if (!buf || !bufsize)
742 return n;
743 write_n = n;
744 if (write_n >= bufsize)
745 write_n = bufsize - 1;
746 if (write_n)
747 strncpy(buf, str, write_n);
748 buf[write_n] = '\0';
749
750 return n;
751}
752
753/*! Return the string with all non-printable characters escaped.
Neels Hofmeyrc36e2e42019-11-20 21:57:32 +0100754 * This internal function is the implementation for all osmo_escape_str* and osmo_quote_str* API versions.
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100755 * It provides both the legacy (non C compatible) escaping, as well as C compatible string constant syntax,
756 * 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 +0100757 * \param[out] buf string buffer to write escaped characters to.
758 * \param[in] bufsize sizeof(buf).
759 * \param[in] str A string that may contain any characters.
760 * \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 +0100761 * \param[in] legacy_format If false, return C compatible string constants ("\x0f"), if true the legacy
762 * escaping format ("\15"). The legacy format also escapes as "\a\b\f\v", while
763 * the non-legacy format also escapes those as "\xNN" sequences.
Neels Hofmeyrc36e2e42019-11-20 21:57:32 +0100764 * \return Number of characters that would be written if bufsize were large enough excluding '\0' (like snprintf()).
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100765 */
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100766static 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 +0100767{
768 struct osmo_strbuf sb = { .buf = buf, .len = bufsize };
769 int in_pos = 0;
770 int next_unprintable = 0;
771
772 if (!str)
773 in_len = 0;
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100774
775 if (in_len < 0)
776 in_len = strlen(str);
777
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100778 /* Make sure of '\0' termination */
779 if (!in_len)
780 OSMO_STRBUF_PRINTF(sb, "%s", "");
781
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100782 while (in_pos < in_len) {
783 for (next_unprintable = in_pos;
784 next_unprintable < in_len && isprint((int)str[next_unprintable])
785 && str[next_unprintable] != '"'
786 && str[next_unprintable] != '\\';
787 next_unprintable++);
788
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100789 OSMO_STRBUF_APPEND(sb, osmo_print_n, &str[in_pos], next_unprintable - in_pos);
790 in_pos = next_unprintable;
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100791
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100792 if (in_pos == in_len)
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100793 goto done;
794
795 switch (str[next_unprintable]) {
796#define BACKSLASH_CASE(c, repr) \
797 case c: \
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100798 OSMO_STRBUF_PRINTF(sb, "\\%c", repr); \
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100799 break
800
801 BACKSLASH_CASE('\n', 'n');
802 BACKSLASH_CASE('\r', 'r');
803 BACKSLASH_CASE('\t', 't');
804 BACKSLASH_CASE('\0', '0');
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100805 BACKSLASH_CASE('\\', '\\');
806 BACKSLASH_CASE('"', '"');
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100807
808 default:
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100809 if (legacy_format) {
810 switch (str[next_unprintable]) {
811 BACKSLASH_CASE('\a', 'a');
812 BACKSLASH_CASE('\b', 'b');
813 BACKSLASH_CASE('\v', 'v');
814 BACKSLASH_CASE('\f', 'f');
815 default:
816 OSMO_STRBUF_PRINTF(sb, "\\%u", (unsigned char)str[in_pos]);
817 break;
818 }
819 break;
820 }
821
822 OSMO_STRBUF_PRINTF(sb, "\\x%02x", (unsigned char)str[in_pos]);
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100823 break;
824 }
825 in_pos ++;
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100826#undef BACKSLASH_CASE
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100827 }
828
829done:
Neels Hofmeyrc36e2e42019-11-20 21:57:32 +0100830 return sb.chars_needed;
831}
832
833/*! Return the string with all non-printable characters escaped.
834 * \param[out] buf string buffer to write escaped characters to.
835 * \param[in] bufsize sizeof(buf).
836 * \param[in] str A string that may contain any characters.
837 * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length (also past nul chars).
838 * \return The output buffer (buf).
839 */
840char *osmo_escape_str_buf2(char *buf, size_t bufsize, const char *str, int in_len)
841{
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100842 _osmo_escape_str_buf(buf, bufsize, str, in_len, true);
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100843 return buf;
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100844}
845
846/*! Return the string with all non-printable characters escaped.
847 * Call osmo_escape_str_buf() with a static buffer.
848 * \param[in] str A string that may contain any characters.
849 * \param[in] len Pass -1 to print until nul char, or >= 0 to force a length.
850 * \returns buf containing an escaped representation, possibly truncated, or str itself.
851 */
852const char *osmo_escape_str(const char *str, int in_len)
853{
854 return osmo_escape_str_buf(str, in_len, namebuf, sizeof(namebuf));
855}
856
Harald Welte179f3572019-03-18 18:38:47 +0100857/*! Return the string with all non-printable characters escaped, in dynamically-allocated buffer.
858 * \param[in] str A string that may contain any characters.
859 * \param[in] len Pass -1 to print until nul char, or >= 0 to force a length.
860 * \returns dynamically-allocated output buffer, containing an escaped representation
861 */
862char *osmo_escape_str_c(const void *ctx, const char *str, int in_len)
863{
Neels Hofmeyrc36e2e42019-11-20 21:57:32 +0100864 /* The string will be at least as long as in_len, but some characters might need escaping.
865 * 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 +0100866 OSMO_NAME_C_IMPL(ctx, in_len + 16, "ERROR", _osmo_escape_str_buf, str, in_len, true);
Neels Hofmeyrc36e2e42019-11-20 21:57:32 +0100867}
868
869/*! Return a quoted and escaped representation of the string.
870 * This internal function is the implementation for all osmo_quote_str* API versions.
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100871 * It provides both the legacy (non C compatible) escaping, as well as C compatible string constant syntax,
872 * 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 +0100873 * \param[out] buf string buffer to write escaped characters to.
874 * \param[in] bufsize sizeof(buf).
875 * \param[in] str A string that may contain any characters.
876 * \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 +0100877 * \param[in] legacy_format If false, return C compatible string constants ("\x0f"), if true the legacy
878 * escaping format ("\15"). The legacy format also escapes as "\a\b\f\v", while
879 * the non-legacy format also escapes those as "\xNN" sequences.
Neels Hofmeyrc36e2e42019-11-20 21:57:32 +0100880 * \return Number of characters that would be written if bufsize were large enough excluding '\0' (like snprintf()).
881 */
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100882static 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 +0100883{
884 struct osmo_strbuf sb = { .buf = buf, .len = bufsize };
885 if (!str)
886 OSMO_STRBUF_PRINTF(sb, "NULL");
887 else {
888 OSMO_STRBUF_PRINTF(sb, "\"");
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100889 OSMO_STRBUF_APPEND(sb, _osmo_escape_str_buf, str, in_len, legacy_format);
Neels Hofmeyrc36e2e42019-11-20 21:57:32 +0100890 OSMO_STRBUF_PRINTF(sb, "\"");
891 }
892 return sb.chars_needed;
Harald Welte179f3572019-03-18 18:38:47 +0100893}
894
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100895/*! 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 +0200896 * This allows passing any char* value and get its C representation as string.
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100897 * The function signature is suitable for OSMO_STRBUF_APPEND_NOLEN().
898 * \param[out] buf string buffer to write escaped characters to.
899 * \param[in] bufsize sizeof(buf).
900 * \param[in] str A string that may contain any characters.
901 * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length.
Neels Hofmeyrdd7b6f92019-11-20 21:32:29 +0100902 * \return The output buffer (buf).
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100903 */
904char *osmo_quote_str_buf2(char *buf, size_t bufsize, const char *str, int in_len)
905{
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100906 _osmo_quote_str_buf(buf, bufsize, str, in_len, true);
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100907 return buf;
908}
909
910/*! Like osmo_quote_str_buf2, but with unusual ordering of arguments, and may sometimes return string constants instead
911 * of writing to buf for error cases or empty input.
912 * Most *_buf() functions have the buffer and size as first arguments, here the arguments are last.
913 * In particular, this function signature doesn't work with OSMO_STRBUF_APPEND_NOLEN().
Neels Hofmeyr04eb56f2018-04-09 00:41:28 +0200914 * \param[in] str A string that may contain any characters.
Neels Hofmeyr03e75532018-09-07 03:12:05 +0200915 * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length.
916 * \returns buf containing a quoted and escaped representation, possibly truncated.
Neels Hofmeyr04eb56f2018-04-09 00:41:28 +0200917 */
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100918const char *osmo_quote_str_buf(const char *str, int in_len, char *buf, size_t bufsize)
Neels Hofmeyr04eb56f2018-04-09 00:41:28 +0200919{
Neels Hofmeyr04eb56f2018-04-09 00:41:28 +0200920 if (!str)
921 return "NULL";
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100922 if (!buf || !bufsize)
923 return "(error)";
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100924 _osmo_quote_str_buf(buf, bufsize, str, in_len, true);
Neels Hofmeyr04eb56f2018-04-09 00:41:28 +0200925 return buf;
926}
927
Neels Hofmeyr03e75532018-09-07 03:12:05 +0200928/*! Like osmo_quote_str_buf() but returns the result in a static buffer.
929 * The static buffer is shared with get_value_string() and osmo_escape_str().
930 * \param[in] str A string that may contain any characters.
931 * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length.
932 * \returns static buffer containing a quoted and escaped representation, possibly truncated.
933 */
Neels Hofmeyr04eb56f2018-04-09 00:41:28 +0200934const char *osmo_quote_str(const char *str, int in_len)
935{
Neels Hofmeyr8a7eed52019-11-21 00:12:10 +0100936 _osmo_quote_str_buf(namebuf, sizeof(namebuf), str, in_len, true);
Neels Hofmeyrc36e2e42019-11-20 21:57:32 +0100937 return namebuf;
Neels Hofmeyr04eb56f2018-04-09 00:41:28 +0200938}
939
Harald Welte179f3572019-03-18 18:38:47 +0100940/*! Like osmo_quote_str_buf() but returns the result in a dynamically-allocated buffer.
Harald Welte179f3572019-03-18 18:38:47 +0100941 * \param[in] str A string that may contain any characters.
942 * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length.
943 * \returns dynamically-allocated buffer containing a quoted and escaped representation.
944 */
945char *osmo_quote_str_c(const void *ctx, const char *str, int in_len)
946{
Neels Hofmeyrc36e2e42019-11-20 21:57:32 +0100947 /* The string will be at least as long as in_len, but some characters might need escaping.
948 * 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 +0100949 OSMO_NAME_C_IMPL(ctx, in_len + 16, "ERROR", _osmo_quote_str_buf, str, in_len, true);
950}
951
952/*! Return the string with all non-printable characters escaped.
953 * In contrast to osmo_escape_str_buf2(), this returns the needed buffer size suitable for OSMO_STRBUF_APPEND(), and
954 * this escapes characters in a way compatible with C string constant syntax.
955 * \param[out] buf string buffer to write escaped characters to.
956 * \param[in] bufsize sizeof(buf).
957 * \param[in] str A string that may contain any characters.
958 * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length (also past nul chars).
959 * \return Number of characters that would be written if bufsize were large enough excluding '\0' (like snprintf()).
960 */
961size_t osmo_escape_cstr_buf(char *buf, size_t bufsize, const char *str, int in_len)
962{
963 return _osmo_escape_str_buf(buf, bufsize, str, in_len, false);
964}
965
966/*! Return the string with all non-printable characters escaped, in dynamically-allocated buffer.
967 * In contrast to osmo_escape_str_c(), this escapes characters in a way compatible with C string constant syntax, and
968 * allocates sufficient memory in all cases.
969 * \param[in] str A string that may contain any characters.
970 * \param[in] len Pass -1 to print until nul char, or >= 0 to force a length.
971 * \returns dynamically-allocated buffer, containing an escaped representation.
972 */
973char *osmo_escape_cstr_c(void *ctx, const char *str, int in_len)
974{
975 /* The string will be at least as long as in_len, but some characters might need escaping.
976 * These extra bytes should catch most usual escaping situations, avoiding a second run in OSMO_NAME_C_IMPL. */
977 OSMO_NAME_C_IMPL(ctx, in_len + 16, "ERROR", _osmo_escape_str_buf, str, in_len, false);
978}
979
980/*! Like osmo_escape_str_buf2(), but returns double-quotes around a string, or "NULL" for a NULL string.
981 * This allows passing any char* value and get its C representation as string.
982 * The function signature is suitable for OSMO_STRBUF_APPEND_NOLEN().
983 * In contrast to osmo_escape_str_buf2(), this returns the needed buffer size suitable for OSMO_STRBUF_APPEND(), and
984 * this escapes characters in a way compatible with C string constant syntax.
985 * \param[out] buf string buffer to write escaped characters to.
986 * \param[in] bufsize sizeof(buf).
987 * \param[in] str A string that may contain any characters.
988 * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length.
989 * \return Number of characters that would be written if bufsize were large enough excluding '\0' (like snprintf()).
990 */
991size_t osmo_quote_cstr_buf(char *buf, size_t bufsize, const char *str, int in_len)
992{
993 return _osmo_quote_str_buf(buf, bufsize, str, in_len, false);
994}
995
996/*! Return the string quoted and with all non-printable characters escaped, in dynamically-allocated buffer.
997 * In contrast to osmo_quote_str_c(), this escapes characters in a way compatible with C string constant syntax, and
998 * allocates sufficient memory in all cases.
999 * \param[in] str A string that may contain any characters.
1000 * \param[in] len Pass -1 to print until nul char, or >= 0 to force a length.
1001 * \returns dynamically-allocated buffer, containing a quoted and escaped representation.
1002 */
1003char *osmo_quote_cstr_c(void *ctx, const char *str, int in_len)
1004{
1005 /* The string will be at least as long as in_len plus two quotes, but some characters might need escaping.
1006 * These extra bytes should catch most usual escaping situations, avoiding a second run in OSMO_NAME_C_IMPL. */
1007 OSMO_NAME_C_IMPL(ctx, in_len + 16, "ERROR", _osmo_quote_str_buf, str, in_len, false);
Harald Welte179f3572019-03-18 18:38:47 +01001008}
1009
Harald Welte15a5f8d2018-06-06 16:58:17 +02001010/*! perform an integer square root operation on unsigned 32bit integer.
1011 * This implementation is taken from "Hacker's Delight" Figure 11-1 "Integer square root, Newton's
1012 * method", which can also be found at http://www.hackersdelight.org/hdcodetxt/isqrt.c.txt */
1013uint32_t osmo_isqrt32(uint32_t x)
1014{
1015 uint32_t x1;
1016 int s, g0, g1;
1017
1018 if (x <= 1)
1019 return x;
1020
1021 s = 1;
1022 x1 = x - 1;
1023 if (x1 > 0xffff) {
1024 s = s + 8;
1025 x1 = x1 >> 16;
1026 }
1027 if (x1 > 0xff) {
1028 s = s + 4;
1029 x1 = x1 >> 8;
1030 }
1031 if (x1 > 0xf) {
1032 s = s + 2;
1033 x1 = x1 >> 4;
1034 }
1035 if (x1 > 0x3) {
1036 s = s + 1;
1037 }
1038
1039 g0 = 1 << s; /* g0 = 2**s */
1040 g1 = (g0 + (x >> s)) >> 1; /* g1 = (g0 + x/g0)/2 */
1041
1042 /* converges after four to five divisions for arguments up to 16,785,407 */
1043 while (g1 < g0) {
1044 g0 = g1;
1045 g1 = (g0 + (x/g0)) >> 1;
1046 }
1047 return g0;
1048}
1049
Neels Hofmeyr7c749892018-09-07 03:01:38 +02001050/*! Convert a string to lowercase, while checking buffer size boundaries.
1051 * The result written to \a dest is guaranteed to be nul terminated if \a dest_len > 0.
1052 * If dest == src, the string is converted in-place, if necessary truncated at dest_len - 1 characters
1053 * length as well as nul terminated.
1054 * Note: similar osmo_str2lower(), but safe to use for src strings of arbitrary length.
1055 * \param[out] dest Target buffer to write lowercase string.
1056 * \param[in] dest_len Maximum buffer size of dest (e.g. sizeof(dest)).
1057 * \param[in] src String to convert to lowercase.
1058 * \returns Length of \a src, like osmo_strlcpy(), but if \a dest == \a src at most \a dest_len - 1.
1059 */
1060size_t osmo_str_tolower_buf(char *dest, size_t dest_len, const char *src)
1061{
1062 size_t rc;
1063 if (dest == src) {
1064 if (dest_len < 1)
1065 return 0;
1066 dest[dest_len - 1] = '\0';
1067 rc = strlen(dest);
1068 } else {
1069 if (dest_len < 1)
1070 return strlen(src);
1071 rc = osmo_strlcpy(dest, src, dest_len);
1072 }
1073 for (; *dest; dest++)
1074 *dest = tolower(*dest);
1075 return rc;
1076}
1077
1078/*! Convert a string to lowercase, using a static buffer.
1079 * The resulting string may be truncated if the internally used static buffer is shorter than src.
1080 * 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 +02001081 * terminating nul. The static buffer returned is shared with osmo_str_toupper().
Neels Hofmeyr7c749892018-09-07 03:01:38 +02001082 * See also osmo_str_tolower_buf().
1083 * \param[in] src String to convert to lowercase.
1084 * \returns Resulting lowercase string in a static buffer, always nul terminated.
1085 */
1086const char *osmo_str_tolower(const char *src)
1087{
Pau Espin Pedrola37f58e2019-08-01 18:11:41 +02001088 osmo_str_tolower_buf(capsbuf, sizeof(capsbuf), src);
1089 return capsbuf;
Neels Hofmeyr7c749892018-09-07 03:01:38 +02001090}
1091
Harald Welte179f3572019-03-18 18:38:47 +01001092/*! Convert a string to lowercase, dynamically allocating the output from given talloc context
1093 * See also osmo_str_tolower_buf().
1094 * \param[in] ctx talloc context from where to allocate the output string
1095 * \param[in] src String to convert to lowercase.
1096 * \returns Resulting lowercase string in a dynamically allocated buffer, always nul terminated.
1097 */
1098char *osmo_str_tolower_c(const void *ctx, const char *src)
1099{
Vadim Yanitskiy4f619c22019-04-12 21:48:07 +07001100 size_t buf_len = strlen(src) + 1;
1101 char *buf = talloc_size(ctx, buf_len);
Harald Welte179f3572019-03-18 18:38:47 +01001102 if (!buf)
1103 return NULL;
Vadim Yanitskiy4f619c22019-04-12 21:48:07 +07001104 osmo_str_tolower_buf(buf, buf_len, src);
Harald Welte179f3572019-03-18 18:38:47 +01001105 return buf;
1106}
1107
Neels Hofmeyr7c749892018-09-07 03:01:38 +02001108/*! Convert a string to uppercase, while checking buffer size boundaries.
1109 * The result written to \a dest is guaranteed to be nul terminated if \a dest_len > 0.
1110 * If dest == src, the string is converted in-place, if necessary truncated at dest_len - 1 characters
1111 * length as well as nul terminated.
1112 * Note: similar osmo_str2upper(), but safe to use for src strings of arbitrary length.
1113 * \param[out] dest Target buffer to write uppercase string.
1114 * \param[in] dest_len Maximum buffer size of dest (e.g. sizeof(dest)).
1115 * \param[in] src String to convert to uppercase.
1116 * \returns Length of \a src, like osmo_strlcpy(), but if \a dest == \a src at most \a dest_len - 1.
1117 */
1118size_t osmo_str_toupper_buf(char *dest, size_t dest_len, const char *src)
1119{
1120 size_t rc;
1121 if (dest == src) {
1122 if (dest_len < 1)
1123 return 0;
1124 dest[dest_len - 1] = '\0';
1125 rc = strlen(dest);
1126 } else {
1127 if (dest_len < 1)
1128 return strlen(src);
1129 rc = osmo_strlcpy(dest, src, dest_len);
1130 }
1131 for (; *dest; dest++)
1132 *dest = toupper(*dest);
1133 return rc;
1134}
1135
1136/*! Convert a string to uppercase, using a static buffer.
1137 * The resulting string may be truncated if the internally used static buffer is shorter than src.
1138 * 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 +02001139 * terminating nul. The static buffer returned is shared with osmo_str_tolower().
Neels Hofmeyr7c749892018-09-07 03:01:38 +02001140 * See also osmo_str_toupper_buf().
1141 * \param[in] src String to convert to uppercase.
1142 * \returns Resulting uppercase string in a static buffer, always nul terminated.
1143 */
1144const char *osmo_str_toupper(const char *src)
1145{
Pau Espin Pedrola37f58e2019-08-01 18:11:41 +02001146 osmo_str_toupper_buf(capsbuf, sizeof(capsbuf), src);
1147 return capsbuf;
Neels Hofmeyr7c749892018-09-07 03:01:38 +02001148}
1149
Harald Welte179f3572019-03-18 18:38:47 +01001150/*! Convert a string to uppercase, dynamically allocating the output from given talloc context
1151 * See also osmo_str_tolower_buf().
1152 * \param[in] ctx talloc context from where to allocate the output string
1153 * \param[in] src String to convert to uppercase.
1154 * \returns Resulting uppercase string in a dynamically allocated buffer, always nul terminated.
1155 */
1156char *osmo_str_toupper_c(const void *ctx, const char *src)
1157{
Vadim Yanitskiy4f619c22019-04-12 21:48:07 +07001158 size_t buf_len = strlen(src) + 1;
1159 char *buf = talloc_size(ctx, buf_len);
Harald Welte179f3572019-03-18 18:38:47 +01001160 if (!buf)
1161 return NULL;
Vadim Yanitskiy4f619c22019-04-12 21:48:07 +07001162 osmo_str_toupper_buf(buf, buf_len, src);
Harald Welte179f3572019-03-18 18:38:47 +01001163 return buf;
1164}
1165
Oliver Smith894be2d2019-01-11 13:13:37 +01001166/*! Calculate the Luhn checksum (as used for IMEIs).
1167 * \param[in] in Input digits in ASCII string representation.
1168 * \param[in] in_len Count of digits to use for the input (14 for IMEI).
1169 * \returns checksum char (e.g. '3'); negative on error
1170 */
Vadim Yanitskiyd9fc6042019-06-12 15:49:03 +07001171char osmo_luhn(const char* in, int in_len)
Oliver Smith894be2d2019-01-11 13:13:37 +01001172{
1173 int i, sum = 0;
1174
1175 /* All input must be numbers */
1176 for (i = 0; i < in_len; i++) {
Kévin Redon1af2cd52019-05-23 19:00:19 +02001177 if (!isdigit((unsigned char)in[i]))
Oliver Smith894be2d2019-01-11 13:13:37 +01001178 return -EINVAL;
1179 }
1180
1181 /* Double every second digit and add it to sum */
1182 for (i = in_len - 1; i >= 0; i -= 2) {
1183 int dbl = (in[i] - '0') * 2;
1184 if (dbl > 9)
1185 dbl -= 9;
1186 sum += dbl;
1187 }
1188
1189 /* Add other digits to sum */
1190 for (i = in_len - 2; i >= 0; i -= 2)
1191 sum += in[i] - '0';
1192
1193 /* Final checksum */
1194 return (sum * 9) % 10 + '0';
1195}
1196
Neels Hofmeyrd79ccc62019-03-07 23:08:40 +01001197/*! Compare start of a string.
1198 * This is an optimisation of 'strstr(str, startswith_str) == str' because it doesn't search through the entire string.
1199 * \param str (Longer) string to compare.
1200 * \param startswith_str (Shorter) string to compare with the start of str.
1201 * \return true iff the first characters of str fully match startswith_str or startswith_str is empty. */
1202bool osmo_str_startswith(const char *str, const char *startswith_str)
1203{
1204 if (!startswith_str || !*startswith_str)
1205 return true;
1206 if (!str)
1207 return false;
1208 return strncmp(str, startswith_str, strlen(startswith_str)) == 0;
1209}
1210
Neels Hofmeyr0aeda1b2017-01-13 14:16:02 +01001211/*! @} */