Harald Welte | 468b643 | 2014-09-11 13:05:51 +0800 | [diff] [blame] | 1 | /* |
| 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 Welte | e08da97 | 2017-11-13 01:00:26 +0900 | [diff] [blame] | 8 | * SPDX-License-Identifier: GPL-2.0+ |
| 9 | * |
Harald Welte | 468b643 | 2014-09-11 13:05:51 +0800 | [diff] [blame] | 10 | * 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 | * |
Harald Welte | 468b643 | 2014-09-11 13:05:51 +0800 | [diff] [blame] | 20 | */ |
| 21 | |
Harald Welte | d284cd9 | 2010-03-01 21:58:31 +0100 | [diff] [blame] | 22 | |
Harald Welte | febe83c | 2017-10-03 17:41:59 +0800 | [diff] [blame] | 23 | #include <stdbool.h> |
Harald Welte | d284cd9 | 2010-03-01 21:58:31 +0100 | [diff] [blame] | 24 | #include <string.h> |
| 25 | #include <stdint.h> |
| 26 | #include <errno.h> |
Harald Welte | b59f935 | 2010-03-25 11:37:04 +0800 | [diff] [blame] | 27 | #include <stdio.h> |
Pau Espin Pedrol | 4573502 | 2017-06-18 14:05:24 +0200 | [diff] [blame] | 28 | #include <inttypes.h> |
Neels Hofmeyr | 87c3afb | 2020-09-30 21:47:47 +0000 | [diff] [blame] | 29 | #include <limits.h> |
Harald Welte | d284cd9 | 2010-03-01 21:58:31 +0100 | [diff] [blame] | 30 | |
Pablo Neira Ayuso | 8341934 | 2011-03-22 16:36:13 +0100 | [diff] [blame] | 31 | #include <osmocom/core/utils.h> |
Harald Welte | 9709b2e | 2016-04-25 18:47:53 +0200 | [diff] [blame] | 32 | #include <osmocom/core/bit64gen.h> |
| 33 | |
Harald Welte | d284cd9 | 2010-03-01 21:58:31 +0100 | [diff] [blame] | 34 | |
Harald Welte | 8598f18 | 2011-08-17 14:19:27 +0200 | [diff] [blame] | 35 | /*! \addtogroup utils |
| 36 | * @{ |
Neels Hofmeyr | 87e4550 | 2017-06-20 00:17:59 +0200 | [diff] [blame] | 37 | * various utility routines |
Neels Hofmeyr | 17518fe | 2017-06-20 04:35:06 +0200 | [diff] [blame] | 38 | * |
| 39 | * \file utils.c */ |
Harald Welte | 8598f18 | 2011-08-17 14:19:27 +0200 | [diff] [blame] | 40 | |
Harald Welte | 171ef82 | 2019-03-28 10:49:05 +0100 | [diff] [blame] | 41 | static __thread char namebuf[255]; |
Pau Espin Pedrol | a37f58e | 2019-08-01 18:11:41 +0200 | [diff] [blame] | 42 | /* shared by osmo_str_tolower() and osmo_str_toupper() */ |
| 43 | static __thread char capsbuf[128]; |
Harald Welte | 8598f18 | 2011-08-17 14:19:27 +0200 | [diff] [blame] | 44 | |
Neels Hofmeyr | 87e4550 | 2017-06-20 00:17:59 +0200 | [diff] [blame] | 45 | /*! get human-readable string for given value |
Harald Welte | 8598f18 | 2011-08-17 14:19:27 +0200 | [diff] [blame] | 46 | * \param[in] vs Array of value_string tuples |
| 47 | * \param[in] val Value to be converted |
| 48 | * \returns pointer to human-readable string |
Neels Hofmeyr | 8a3c83e | 2016-06-13 13:16:58 +0200 | [diff] [blame] | 49 | * |
| 50 | * If val is found in vs, the array's string entry is returned. Otherwise, an |
| 51 | * "unknown" string containing the actual value is composed in a static buffer |
| 52 | * that is reused across invocations. |
Harald Welte | 8598f18 | 2011-08-17 14:19:27 +0200 | [diff] [blame] | 53 | */ |
Harald Welte | d284cd9 | 2010-03-01 21:58:31 +0100 | [diff] [blame] | 54 | const char *get_value_string(const struct value_string *vs, uint32_t val) |
| 55 | { |
Neels Hofmeyr | 8d6dcd9 | 2016-06-06 18:05:23 +0200 | [diff] [blame] | 56 | const char *str = get_value_string_or_null(vs, val); |
| 57 | if (str) |
| 58 | return str; |
| 59 | |
Pau Espin Pedrol | 4573502 | 2017-06-18 14:05:24 +0200 | [diff] [blame] | 60 | snprintf(namebuf, sizeof(namebuf), "unknown 0x%"PRIx32, val); |
Neels Hofmeyr | 8d6dcd9 | 2016-06-06 18:05:23 +0200 | [diff] [blame] | 61 | namebuf[sizeof(namebuf) - 1] = '\0'; |
| 62 | return namebuf; |
| 63 | } |
| 64 | |
Neels Hofmeyr | 87e4550 | 2017-06-20 00:17:59 +0200 | [diff] [blame] | 65 | /*! get human-readable string or NULL for given value |
Neels Hofmeyr | 8d6dcd9 | 2016-06-06 18:05:23 +0200 | [diff] [blame] | 66 | * \param[in] vs Array of value_string tuples |
| 67 | * \param[in] val Value to be converted |
| 68 | * \returns pointer to human-readable string or NULL if val is not found |
| 69 | */ |
| 70 | const char *get_value_string_or_null(const struct value_string *vs, |
| 71 | uint32_t val) |
| 72 | { |
Harald Welte | d284cd9 | 2010-03-01 21:58:31 +0100 | [diff] [blame] | 73 | int i; |
| 74 | |
Neels Hofmeyr | a0331ed | 2019-02-11 21:24:40 +0100 | [diff] [blame] | 75 | if (!vs) |
| 76 | return NULL; |
| 77 | |
Harald Welte | d284cd9 | 2010-03-01 21:58:31 +0100 | [diff] [blame] | 78 | for (i = 0;; i++) { |
| 79 | if (vs[i].value == 0 && vs[i].str == NULL) |
| 80 | break; |
| 81 | if (vs[i].value == val) |
| 82 | return vs[i].str; |
| 83 | } |
Harald Welte | b59f935 | 2010-03-25 11:37:04 +0800 | [diff] [blame] | 84 | |
Neels Hofmeyr | 8d6dcd9 | 2016-06-06 18:05:23 +0200 | [diff] [blame] | 85 | return NULL; |
Harald Welte | d284cd9 | 2010-03-01 21:58:31 +0100 | [diff] [blame] | 86 | } |
| 87 | |
Neels Hofmeyr | 87e4550 | 2017-06-20 00:17:59 +0200 | [diff] [blame] | 88 | /*! get numeric value for given human-readable string |
Harald Welte | 8598f18 | 2011-08-17 14:19:27 +0200 | [diff] [blame] | 89 | * \param[in] vs Array of value_string tuples |
| 90 | * \param[in] str human-readable string |
| 91 | * \returns numeric value (>0) or negative numer in case of error |
| 92 | */ |
Harald Welte | d284cd9 | 2010-03-01 21:58:31 +0100 | [diff] [blame] | 93 | int get_string_value(const struct value_string *vs, const char *str) |
| 94 | { |
| 95 | int i; |
| 96 | |
| 97 | for (i = 0;; i++) { |
| 98 | if (vs[i].value == 0 && vs[i].str == NULL) |
| 99 | break; |
| 100 | if (!strcasecmp(vs[i].str, str)) |
| 101 | return vs[i].value; |
| 102 | } |
| 103 | return -EINVAL; |
| 104 | } |
Harald Welte | a73e2f9 | 2010-03-04 10:50:32 +0100 | [diff] [blame] | 105 | |
Neels Hofmeyr | 87e4550 | 2017-06-20 00:17:59 +0200 | [diff] [blame] | 106 | /*! Convert BCD-encoded digit into printable character |
Harald Welte | 8598f18 | 2011-08-17 14:19:27 +0200 | [diff] [blame] | 107 | * \param[in] bcd A single BCD-encoded digit |
| 108 | * \returns single printable character |
| 109 | */ |
Pablo Neira Ayuso | 87f7b25 | 2011-05-07 12:43:08 +0200 | [diff] [blame] | 110 | char osmo_bcd2char(uint8_t bcd) |
Harald Welte | a73e2f9 | 2010-03-04 10:50:32 +0100 | [diff] [blame] | 111 | { |
| 112 | if (bcd < 0xa) |
| 113 | return '0' + bcd; |
| 114 | else |
| 115 | return 'A' + (bcd - 0xa); |
| 116 | } |
| 117 | |
Neels Hofmeyr | 87e4550 | 2017-06-20 00:17:59 +0200 | [diff] [blame] | 118 | /*! Convert number in ASCII to BCD value |
Harald Welte | de6e498 | 2012-12-06 21:25:27 +0100 | [diff] [blame] | 119 | * \param[in] c ASCII character |
| 120 | * \returns BCD encoded value of character |
| 121 | */ |
Pablo Neira Ayuso | 87f7b25 | 2011-05-07 12:43:08 +0200 | [diff] [blame] | 122 | uint8_t osmo_char2bcd(char c) |
Harald Welte | a73e2f9 | 2010-03-04 10:50:32 +0100 | [diff] [blame] | 123 | { |
Harald Welte | fa8983d | 2017-10-27 16:52:59 +0200 | [diff] [blame] | 124 | if (c >= '0' && c <= '9') |
| 125 | return c - 0x30; |
| 126 | else if (c >= 'A' && c <= 'F') |
| 127 | return 0xa + (c - 'A'); |
| 128 | else if (c >= 'a' && c <= 'f') |
| 129 | return 0xa + (c - 'a'); |
| 130 | else |
| 131 | return 0; |
Harald Welte | a73e2f9 | 2010-03-04 10:50:32 +0100 | [diff] [blame] | 132 | } |
Harald Welte | 3eba991 | 2010-07-30 10:37:29 +0200 | [diff] [blame] | 133 | |
Neels Hofmeyr | 7079e69 | 2018-12-05 21:02:36 +0100 | [diff] [blame] | 134 | /*! Convert BCD to string. |
| 135 | * The given nibble offsets are interpreted in BCD order, i.e. nibble 0 is bcd[0] & 0xf, nibble 1 is bcd[0] >> 4, nibble |
| 136 | * 3 is bcd[1] & 0xf, etc.. |
| 137 | * \param[out] dst Output string buffer, is always nul terminated when dst_size > 0. |
| 138 | * \param[in] dst_size sizeof() the output string buffer. |
| 139 | * \param[in] bcd Binary coded data buffer. |
| 140 | * \param[in] start_nibble Offset to start from, in nibbles, typically 1 to skip the first nibble. |
Neels Hofmeyr | 48b2de0 | 2018-12-11 02:13:57 +0100 | [diff] [blame] | 141 | * \param[in] end_nibble Offset to stop before, in nibbles, e.g. sizeof(bcd)*2 - (bcd[0] & GSM_MI_ODD? 0:1). |
Neels Hofmeyr | 7079e69 | 2018-12-05 21:02:36 +0100 | [diff] [blame] | 142 | * \param[in] allow_hex If false, return error if there are digits other than 0-9. If true, return those as [A-F]. |
| 143 | * \returns The strlen that would be written if the output buffer is large enough, excluding nul byte (like |
| 144 | * snprintf()), or -EINVAL if allow_hex is false and a digit > 9 is encountered. On -EINVAL, the conversion is |
| 145 | * still completed as if allow_hex were passed as true. Return -ENOMEM if dst is NULL or dst_size is zero. |
| 146 | * If end_nibble <= start_nibble, write an empty string to dst and return 0. |
| 147 | */ |
| 148 | int osmo_bcd2str(char *dst, size_t dst_size, const uint8_t *bcd, int start_nibble, int end_nibble, bool allow_hex) |
| 149 | { |
| 150 | char *dst_end = dst + dst_size - 1; |
| 151 | int nibble_i; |
| 152 | int rc = 0; |
| 153 | |
Neels Hofmeyr | 0b6a8c8 | 2020-06-12 16:34:20 +0200 | [diff] [blame] | 154 | if (!dst || dst_size < 1 || start_nibble < 0) |
Neels Hofmeyr | 7079e69 | 2018-12-05 21:02:36 +0100 | [diff] [blame] | 155 | return -ENOMEM; |
| 156 | |
| 157 | for (nibble_i = start_nibble; nibble_i < end_nibble && dst < dst_end; nibble_i++, dst++) { |
| 158 | uint8_t nibble = bcd[nibble_i >> 1]; |
| 159 | if ((nibble_i & 1)) |
| 160 | nibble >>= 4; |
| 161 | nibble &= 0xf; |
| 162 | |
| 163 | if (!allow_hex && nibble > 9) |
| 164 | rc = -EINVAL; |
| 165 | |
| 166 | *dst = osmo_bcd2char(nibble); |
| 167 | } |
| 168 | *dst = '\0'; |
| 169 | |
| 170 | if (rc < 0) |
| 171 | return rc; |
| 172 | return OSMO_MAX(0, end_nibble - start_nibble); |
| 173 | } |
| 174 | |
Neels Hofmeyr | 83025bf | 2020-05-26 02:45:23 +0200 | [diff] [blame] | 175 | /*! Convert string to BCD. |
| 176 | * The given nibble offsets are interpreted in BCD order, i.e. nibble 0 is bcd[0] & 0x0f, nibble 1 is bcd[0] & 0xf0, nibble |
| 177 | * 3 is bcd[1] & 0x0f, etc.. |
| 178 | * \param[out] dst Output BCD buffer. |
| 179 | * \param[in] dst_size sizeof() the output string buffer. |
| 180 | * \param[in] digits String containing decimal or hexadecimal digits in upper or lower case. |
| 181 | * \param[in] start_nibble Offset to start from, in nibbles, typically 1 to skip the first (MI type) nibble. |
| 182 | * \param[in] end_nibble Negative to write all digits found in str, followed by 0xf nibbles to fill any started octet. |
| 183 | * If >= 0, stop before this offset in nibbles, e.g. to get default behavior, pass |
| 184 | * start_nibble + strlen(str) + ((start_nibble + strlen(str)) & 1? 1 : 0) + 1. |
| 185 | * \param[in] allow_hex If false, return error if there are hexadecimal digits (A-F). If true, write those to |
| 186 | * BCD. |
| 187 | * \returns The buffer size in octets that is used to place all bcd digits (including the skipped nibbles |
| 188 | * from 'start_nibble' and rounded up to full octets); -EINVAL on invalid digits; |
| 189 | * -ENOMEM if dst is NULL, if dst_size is too small to contain all nibbles, or if start_nibble is negative. |
| 190 | */ |
| 191 | int osmo_str2bcd(uint8_t *dst, size_t dst_size, const char *digits, int start_nibble, int end_nibble, bool allow_hex) |
| 192 | { |
| 193 | const char *digit = digits; |
| 194 | int nibble_i; |
| 195 | |
| 196 | if (!dst || !dst_size || start_nibble < 0) |
| 197 | return -ENOMEM; |
| 198 | |
| 199 | if (end_nibble < 0) { |
| 200 | end_nibble = start_nibble + strlen(digits); |
| 201 | /* If the last octet is not complete, add another filler nibble */ |
| 202 | if (end_nibble & 1) |
| 203 | end_nibble++; |
| 204 | } |
Harald Welte | 7d6166a | 2022-01-09 11:57:01 +0100 | [diff] [blame] | 205 | if ((unsigned int) (end_nibble / 2) > dst_size) |
Neels Hofmeyr | 83025bf | 2020-05-26 02:45:23 +0200 | [diff] [blame] | 206 | return -ENOMEM; |
| 207 | |
| 208 | for (nibble_i = start_nibble; nibble_i < end_nibble; nibble_i++) { |
| 209 | uint8_t nibble = 0xf; |
| 210 | int octet = nibble_i >> 1; |
| 211 | if (*digit) { |
| 212 | char c = *digit; |
| 213 | digit++; |
| 214 | if (c >= '0' && c <= '9') |
| 215 | nibble = c - '0'; |
| 216 | else if (allow_hex && c >= 'A' && c <= 'F') |
| 217 | nibble = 0xa + (c - 'A'); |
| 218 | else if (allow_hex && c >= 'a' && c <= 'f') |
| 219 | nibble = 0xa + (c - 'a'); |
| 220 | else |
| 221 | return -EINVAL; |
| 222 | } |
| 223 | nibble &= 0xf; |
| 224 | if ((nibble_i & 1)) |
| 225 | dst[octet] = (nibble << 4) | (dst[octet] & 0x0f); |
| 226 | else |
| 227 | dst[octet] = (dst[octet] & 0xf0) | nibble; |
| 228 | } |
| 229 | |
| 230 | /* floor(float(end_nibble) / 2) */ |
| 231 | return end_nibble / 2; |
| 232 | } |
| 233 | |
Neels Hofmeyr | 87e4550 | 2017-06-20 00:17:59 +0200 | [diff] [blame] | 234 | /*! Parse a string containing hexadecimal digits |
Harald Welte | de6e498 | 2012-12-06 21:25:27 +0100 | [diff] [blame] | 235 | * \param[in] str string containing ASCII encoded hexadecimal digits |
| 236 | * \param[out] b output buffer |
| 237 | * \param[in] max_len maximum space in output buffer |
Neels Hofmeyr | 3de7b05 | 2015-09-23 23:16:53 +0200 | [diff] [blame] | 238 | * \returns number of parsed octets, or -1 on error |
Harald Welte | de6e498 | 2012-12-06 21:25:27 +0100 | [diff] [blame] | 239 | */ |
Harald Welte | 7d6166a | 2022-01-09 11:57:01 +0100 | [diff] [blame] | 240 | int osmo_hexparse(const char *str, uint8_t *b, unsigned int max_len) |
Harald Welte | 3eba991 | 2010-07-30 10:37:29 +0200 | [diff] [blame] | 241 | |
| 242 | { |
Neels Hofmeyr | 437ed4a | 2017-02-14 15:54:31 +0100 | [diff] [blame] | 243 | char c; |
| 244 | uint8_t v; |
| 245 | const char *strpos; |
| 246 | unsigned int nibblepos = 0; |
Harald Welte | 3eba991 | 2010-07-30 10:37:29 +0200 | [diff] [blame] | 247 | |
| 248 | memset(b, 0x00, max_len); |
| 249 | |
Neels Hofmeyr | 437ed4a | 2017-02-14 15:54:31 +0100 | [diff] [blame] | 250 | for (strpos = str; (c = *strpos); strpos++) { |
| 251 | /* skip whitespace */ |
| 252 | if (c == ' ' || c == '\t' || c == '\n' || c == '\r') |
| 253 | continue; |
| 254 | |
| 255 | /* If the buffer is too small, error out */ |
| 256 | if (nibblepos >= (max_len << 1)) |
| 257 | return -1; |
| 258 | |
Harald Welte | 3eba991 | 2010-07-30 10:37:29 +0200 | [diff] [blame] | 259 | if (c >= '0' && c <= '9') |
| 260 | v = c - '0'; |
| 261 | else if (c >= 'a' && c <= 'f') |
| 262 | v = 10 + (c - 'a'); |
| 263 | else if (c >= 'A' && c <= 'F') |
| 264 | v = 10 + (c - 'A'); |
| 265 | else |
| 266 | return -1; |
Neels Hofmeyr | 437ed4a | 2017-02-14 15:54:31 +0100 | [diff] [blame] | 267 | |
| 268 | b[nibblepos >> 1] |= v << (nibblepos & 1 ? 0 : 4); |
| 269 | nibblepos ++; |
Harald Welte | 3eba991 | 2010-07-30 10:37:29 +0200 | [diff] [blame] | 270 | } |
| 271 | |
Neels Hofmeyr | 437ed4a | 2017-02-14 15:54:31 +0100 | [diff] [blame] | 272 | /* In case of uneven amount of digits, the last byte is not complete |
| 273 | * and that's an error. */ |
| 274 | if (nibblepos & 1) |
| 275 | return -1; |
| 276 | |
| 277 | return nibblepos >> 1; |
Harald Welte | 3eba991 | 2010-07-30 10:37:29 +0200 | [diff] [blame] | 278 | } |
Harald Welte | 40481e8 | 2010-07-30 11:40:32 +0200 | [diff] [blame] | 279 | |
Harald Welte | 171ef82 | 2019-03-28 10:49:05 +0100 | [diff] [blame] | 280 | static __thread char hexd_buff[4096]; |
Nils O. SelÄsdal | 3244702 | 2014-01-02 14:04:43 +0100 | [diff] [blame] | 281 | static const char hex_chars[] = "0123456789abcdef"; |
Harald Welte | 40481e8 | 2010-07-30 11:40:32 +0200 | [diff] [blame] | 282 | |
Neels Hofmeyr | 0423b61 | 2019-01-14 23:32:53 +0100 | [diff] [blame] | 283 | /*! Convert binary sequence to hexadecimal ASCII string. |
| 284 | * \param[out] out_buf Output buffer to write the resulting string to. |
| 285 | * \param[in] out_buf_size sizeof(out_buf). |
| 286 | * \param[in] buf Input buffer, pointer to sequence of bytes. |
| 287 | * \param[in] len Length of input buf in number of bytes. |
| 288 | * \param[in] delim String to separate each byte; NULL or "" for no delim. |
| 289 | * \param[in] delim_after_last If true, end the string in delim (true: "1a:ef:d9:", false: "1a:ef:d9"); |
| 290 | * if out_buf has insufficient space, the string will always end in a delim. |
| 291 | * \returns out_buf, containing a zero-terminated string, or "" (empty string) if out_buf == NULL or out_buf_size < 1. |
| 292 | * |
| 293 | * This function will print a sequence of bytes as hexadecimal numbers, adding one delim between each byte (e.g. for |
| 294 | * delim passed as ":", return a string like "1a:ef:d9"). |
| 295 | * |
| 296 | * The delim_after_last argument exists to be able to exactly show the original osmo_hexdump() behavior, which always |
| 297 | * ends the string with a delimiter. |
| 298 | */ |
| 299 | const char *osmo_hexdump_buf(char *out_buf, size_t out_buf_size, const unsigned char *buf, int len, const char *delim, |
| 300 | bool delim_after_last) |
Harald Welte | 40481e8 | 2010-07-30 11:40:32 +0200 | [diff] [blame] | 301 | { |
| 302 | int i; |
Neels Hofmeyr | 0423b61 | 2019-01-14 23:32:53 +0100 | [diff] [blame] | 303 | char *cur = out_buf; |
| 304 | size_t delim_len; |
Harald Welte | 40481e8 | 2010-07-30 11:40:32 +0200 | [diff] [blame] | 305 | |
Neels Hofmeyr | 0423b61 | 2019-01-14 23:32:53 +0100 | [diff] [blame] | 306 | if (!out_buf || !out_buf_size) |
| 307 | return ""; |
| 308 | |
| 309 | delim = delim ? : ""; |
| 310 | delim_len = strlen(delim); |
| 311 | |
Harald Welte | 40481e8 | 2010-07-30 11:40:32 +0200 | [diff] [blame] | 312 | for (i = 0; i < len; i++) { |
Nils O. SelÄsdal | 3244702 | 2014-01-02 14:04:43 +0100 | [diff] [blame] | 313 | const char *delimp = delim; |
Neels Hofmeyr | 0423b61 | 2019-01-14 23:32:53 +0100 | [diff] [blame] | 314 | int len_remain = out_buf_size - (cur - out_buf) - 1; |
Harald Welte | 7d6166a | 2022-01-09 11:57:01 +0100 | [diff] [blame] | 315 | if (len_remain < (int) (2 + delim_len) |
Neels Hofmeyr | 0423b61 | 2019-01-14 23:32:53 +0100 | [diff] [blame] | 316 | && !(!delim_after_last && i == (len - 1) && len_remain >= 2)) |
Holger Hans Peter Freyther | 128d9e2 | 2011-07-15 16:07:23 +0200 | [diff] [blame] | 317 | break; |
Nils O. SelÄsdal | 3244702 | 2014-01-02 14:04:43 +0100 | [diff] [blame] | 318 | |
| 319 | *cur++ = hex_chars[buf[i] >> 4]; |
| 320 | *cur++ = hex_chars[buf[i] & 0xf]; |
| 321 | |
Neels Hofmeyr | 0423b61 | 2019-01-14 23:32:53 +0100 | [diff] [blame] | 322 | if (i == (len - 1) && !delim_after_last) |
| 323 | break; |
| 324 | |
Nils O. SelÄsdal | 3244702 | 2014-01-02 14:04:43 +0100 | [diff] [blame] | 325 | while (len_remain > 1 && *delimp) { |
| 326 | *cur++ = *delimp++; |
| 327 | len_remain--; |
| 328 | } |
Harald Welte | 40481e8 | 2010-07-30 11:40:32 +0200 | [diff] [blame] | 329 | } |
Neels Hofmeyr | 0423b61 | 2019-01-14 23:32:53 +0100 | [diff] [blame] | 330 | *cur = '\0'; |
| 331 | return out_buf; |
Harald Welte | 40481e8 | 2010-07-30 11:40:32 +0200 | [diff] [blame] | 332 | } |
Harald Welte | dee47cd | 2010-07-30 11:43:30 +0200 | [diff] [blame] | 333 | |
Harald Welte | 4a62eda | 2019-03-18 18:27:00 +0100 | [diff] [blame] | 334 | /*! Convert a sequence of unpacked bits to ASCII string, in user-supplied buffer. |
| 335 | * \param[out] buf caller-provided output string buffer |
| 336 | * \param[out] buf_len size of buf in bytes |
Harald Welte | 8598f18 | 2011-08-17 14:19:27 +0200 | [diff] [blame] | 337 | * \param[in] bits A sequence of unpacked bits |
| 338 | * \param[in] len Length of bits |
Neels Hofmeyr | dd7b6f9 | 2019-11-20 21:32:29 +0100 | [diff] [blame] | 339 | * \return The output buffer (buf). |
Harald Welte | 8598f18 | 2011-08-17 14:19:27 +0200 | [diff] [blame] | 340 | */ |
Harald Welte | 4a62eda | 2019-03-18 18:27:00 +0100 | [diff] [blame] | 341 | char *osmo_ubit_dump_buf(char *buf, size_t buf_len, const uint8_t *bits, unsigned int len) |
Harald Welte | 3d0ac5e | 2011-02-08 16:55:03 +0100 | [diff] [blame] | 342 | { |
Harald Welte | 7d6166a | 2022-01-09 11:57:01 +0100 | [diff] [blame] | 343 | unsigned int i; |
Harald Welte | 3d0ac5e | 2011-02-08 16:55:03 +0100 | [diff] [blame] | 344 | |
Harald Welte | 4a62eda | 2019-03-18 18:27:00 +0100 | [diff] [blame] | 345 | if (len > buf_len-1) |
| 346 | len = buf_len-1; |
| 347 | memset(buf, 0, buf_len); |
Harald Welte | 3d0ac5e | 2011-02-08 16:55:03 +0100 | [diff] [blame] | 348 | |
| 349 | for (i = 0; i < len; i++) { |
| 350 | char outch; |
| 351 | switch (bits[i]) { |
| 352 | case 0: |
| 353 | outch = '0'; |
| 354 | break; |
| 355 | case 0xff: |
| 356 | outch = '?'; |
| 357 | break; |
| 358 | case 1: |
| 359 | outch = '1'; |
| 360 | break; |
| 361 | default: |
| 362 | outch = 'E'; |
| 363 | break; |
| 364 | } |
Harald Welte | 4a62eda | 2019-03-18 18:27:00 +0100 | [diff] [blame] | 365 | buf[i] = outch; |
Harald Welte | 3d0ac5e | 2011-02-08 16:55:03 +0100 | [diff] [blame] | 366 | } |
Harald Welte | 4a62eda | 2019-03-18 18:27:00 +0100 | [diff] [blame] | 367 | buf[buf_len-1] = 0; |
| 368 | return buf; |
| 369 | } |
| 370 | |
| 371 | /*! Convert a sequence of unpacked bits to ASCII string, in static buffer. |
| 372 | * \param[in] bits A sequence of unpacked bits |
| 373 | * \param[in] len Length of bits |
| 374 | * \returns string representation in static buffer. |
| 375 | */ |
| 376 | char *osmo_ubit_dump(const uint8_t *bits, unsigned int len) |
| 377 | { |
| 378 | return osmo_ubit_dump_buf(hexd_buff, sizeof(hexd_buff), bits, len); |
Harald Welte | 3d0ac5e | 2011-02-08 16:55:03 +0100 | [diff] [blame] | 379 | } |
| 380 | |
Neels Hofmeyr | 87e4550 | 2017-06-20 00:17:59 +0200 | [diff] [blame] | 381 | /*! Convert binary sequence to hexadecimal ASCII string |
Harald Welte | 8598f18 | 2011-08-17 14:19:27 +0200 | [diff] [blame] | 382 | * \param[in] buf pointer to sequence of bytes |
| 383 | * \param[in] len length of buf in number of bytes |
| 384 | * \returns pointer to zero-terminated string |
| 385 | * |
| 386 | * This function will print a sequence of bytes as hexadecimal numbers, |
| 387 | * adding one space character between each byte (e.g. "1a ef d9") |
Harald Welte | 096a666 | 2017-10-16 14:33:11 +0200 | [diff] [blame] | 388 | * |
| 389 | * The maximum size of the output buffer is 4096 bytes, i.e. the maximum |
| 390 | * number of input bytes that can be printed in one call is 1365! |
Harald Welte | 8598f18 | 2011-08-17 14:19:27 +0200 | [diff] [blame] | 391 | */ |
Pablo Neira Ayuso | 87f7b25 | 2011-05-07 12:43:08 +0200 | [diff] [blame] | 392 | char *osmo_hexdump(const unsigned char *buf, int len) |
Harald Welte | dee47cd | 2010-07-30 11:43:30 +0200 | [diff] [blame] | 393 | { |
Neels Hofmeyr | 0423b61 | 2019-01-14 23:32:53 +0100 | [diff] [blame] | 394 | osmo_hexdump_buf(hexd_buff, sizeof(hexd_buff), buf, len, " ", true); |
| 395 | return hexd_buff; |
Harald Welte | dee47cd | 2010-07-30 11:43:30 +0200 | [diff] [blame] | 396 | } |
| 397 | |
Neels Hofmeyr | 87e4550 | 2017-06-20 00:17:59 +0200 | [diff] [blame] | 398 | /*! Convert binary sequence to hexadecimal ASCII string |
Harald Welte | 179f357 | 2019-03-18 18:38:47 +0100 | [diff] [blame] | 399 | * \param[in] ctx talloc context from where to allocate the output string |
| 400 | * \param[in] buf pointer to sequence of bytes |
| 401 | * \param[in] len length of buf in number of bytes |
| 402 | * \returns pointer to zero-terminated string |
| 403 | * |
| 404 | * This function will print a sequence of bytes as hexadecimal numbers, |
| 405 | * adding one space character between each byte (e.g. "1a ef d9") |
Harald Welte | 179f357 | 2019-03-18 18:38:47 +0100 | [diff] [blame] | 406 | */ |
| 407 | char *osmo_hexdump_c(const void *ctx, const unsigned char *buf, int len) |
| 408 | { |
Vadim Yanitskiy | 4f619c2 | 2019-04-12 21:48:07 +0700 | [diff] [blame] | 409 | size_t hexd_buff_len = len * 3 + 1; |
| 410 | char *hexd_buff = talloc_size(ctx, hexd_buff_len); |
Harald Welte | 179f357 | 2019-03-18 18:38:47 +0100 | [diff] [blame] | 411 | if (!hexd_buff) |
| 412 | return NULL; |
Vadim Yanitskiy | 4f619c2 | 2019-04-12 21:48:07 +0700 | [diff] [blame] | 413 | osmo_hexdump_buf(hexd_buff, hexd_buff_len, buf, len, " ", true); |
Harald Welte | 179f357 | 2019-03-18 18:38:47 +0100 | [diff] [blame] | 414 | return hexd_buff; |
| 415 | } |
| 416 | |
| 417 | /*! Convert binary sequence to hexadecimal ASCII string |
Harald Welte | 8598f18 | 2011-08-17 14:19:27 +0200 | [diff] [blame] | 418 | * \param[in] buf pointer to sequence of bytes |
| 419 | * \param[in] len length of buf in number of bytes |
| 420 | * \returns pointer to zero-terminated string |
| 421 | * |
| 422 | * This function will print a sequence of bytes as hexadecimal numbers, |
| 423 | * without any space character between each byte (e.g. "1aefd9") |
Harald Welte | 096a666 | 2017-10-16 14:33:11 +0200 | [diff] [blame] | 424 | * |
| 425 | * The maximum size of the output buffer is 4096 bytes, i.e. the maximum |
| 426 | * number of input bytes that can be printed in one call is 2048! |
Harald Welte | 8598f18 | 2011-08-17 14:19:27 +0200 | [diff] [blame] | 427 | */ |
Sylvain Munaut | ff23d24 | 2011-11-10 23:03:18 +0100 | [diff] [blame] | 428 | char *osmo_hexdump_nospc(const unsigned char *buf, int len) |
Harald Welte | dee47cd | 2010-07-30 11:43:30 +0200 | [diff] [blame] | 429 | { |
Neels Hofmeyr | 0423b61 | 2019-01-14 23:32:53 +0100 | [diff] [blame] | 430 | osmo_hexdump_buf(hexd_buff, sizeof(hexd_buff), buf, len, "", true); |
| 431 | return hexd_buff; |
Harald Welte | dee47cd | 2010-07-30 11:43:30 +0200 | [diff] [blame] | 432 | } |
Harald Welte | 2822296 | 2011-02-18 20:37:04 +0100 | [diff] [blame] | 433 | |
Harald Welte | 179f357 | 2019-03-18 18:38:47 +0100 | [diff] [blame] | 434 | /*! Convert binary sequence to hexadecimal ASCII string |
| 435 | * \param[in] ctx talloc context from where to allocate the output string |
| 436 | * \param[in] buf pointer to sequence of bytes |
| 437 | * \param[in] len length of buf in number of bytes |
| 438 | * \returns pointer to zero-terminated string |
| 439 | * |
| 440 | * This function will print a sequence of bytes as hexadecimal numbers, |
| 441 | * without any space character between each byte (e.g. "1aefd9") |
Harald Welte | 179f357 | 2019-03-18 18:38:47 +0100 | [diff] [blame] | 442 | */ |
| 443 | char *osmo_hexdump_nospc_c(const void *ctx, const unsigned char *buf, int len) |
| 444 | { |
Vadim Yanitskiy | 4f619c2 | 2019-04-12 21:48:07 +0700 | [diff] [blame] | 445 | size_t hexd_buff_len = len * 2 + 1; |
| 446 | char *hexd_buff = talloc_size(ctx, hexd_buff_len); |
Harald Welte | 179f357 | 2019-03-18 18:38:47 +0100 | [diff] [blame] | 447 | if (!hexd_buff) |
| 448 | return NULL; |
Vadim Yanitskiy | 4f619c2 | 2019-04-12 21:48:07 +0700 | [diff] [blame] | 449 | osmo_hexdump_buf(hexd_buff, hexd_buff_len, buf, len, "", true); |
Harald Welte | 179f357 | 2019-03-18 18:38:47 +0100 | [diff] [blame] | 450 | return hexd_buff; |
| 451 | } |
| 452 | |
| 453 | |
Holger Hans Peter Freyther | 9a1a5a1 | 2015-04-11 19:26:55 +0200 | [diff] [blame] | 454 | /* Compat with previous typo to preserve abi */ |
Sylvain Munaut | e55ae3a | 2011-11-11 23:06:55 +0100 | [diff] [blame] | 455 | char *osmo_osmo_hexdump_nospc(const unsigned char *buf, int len) |
Holger Hans Peter Freyther | 9a1a5a1 | 2015-04-11 19:26:55 +0200 | [diff] [blame] | 456 | #if defined(__MACH__) && defined(__APPLE__) |
| 457 | ; |
| 458 | #else |
Sylvain Munaut | 17af41d | 2011-11-19 22:30:39 +0100 | [diff] [blame] | 459 | __attribute__((weak, alias("osmo_hexdump_nospc"))); |
Holger Hans Peter Freyther | 9a1a5a1 | 2015-04-11 19:26:55 +0200 | [diff] [blame] | 460 | #endif |
Sylvain Munaut | e55ae3a | 2011-11-11 23:06:55 +0100 | [diff] [blame] | 461 | |
Pau Espin Pedrol | 88955fb | 2023-01-18 18:54:00 +0100 | [diff] [blame] | 462 | #include "config.h" |
Harald Welte | 2822296 | 2011-02-18 20:37:04 +0100 | [diff] [blame] | 463 | #ifdef HAVE_CTYPE_H |
| 464 | #include <ctype.h> |
Neels Hofmeyr | 87e4550 | 2017-06-20 00:17:59 +0200 | [diff] [blame] | 465 | /*! Convert an entire string to lower case |
Harald Welte | 8598f18 | 2011-08-17 14:19:27 +0200 | [diff] [blame] | 466 | * \param[out] out output string, caller-allocated |
| 467 | * \param[in] in input string |
| 468 | */ |
Harald Welte | 2822296 | 2011-02-18 20:37:04 +0100 | [diff] [blame] | 469 | void osmo_str2lower(char *out, const char *in) |
| 470 | { |
| 471 | unsigned int i; |
| 472 | |
| 473 | for (i = 0; i < strlen(in); i++) |
Pau Espin Pedrol | 399a6f0 | 2017-06-18 14:07:37 +0200 | [diff] [blame] | 474 | out[i] = tolower((const unsigned char)in[i]); |
Harald Welte | 2822296 | 2011-02-18 20:37:04 +0100 | [diff] [blame] | 475 | out[strlen(in)] = '\0'; |
| 476 | } |
| 477 | |
Neels Hofmeyr | 87e4550 | 2017-06-20 00:17:59 +0200 | [diff] [blame] | 478 | /*! Convert an entire string to upper case |
Harald Welte | 8598f18 | 2011-08-17 14:19:27 +0200 | [diff] [blame] | 479 | * \param[out] out output string, caller-allocated |
| 480 | * \param[in] in input string |
| 481 | */ |
Harald Welte | 2822296 | 2011-02-18 20:37:04 +0100 | [diff] [blame] | 482 | void osmo_str2upper(char *out, const char *in) |
| 483 | { |
| 484 | unsigned int i; |
| 485 | |
| 486 | for (i = 0; i < strlen(in); i++) |
Pau Espin Pedrol | 399a6f0 | 2017-06-18 14:07:37 +0200 | [diff] [blame] | 487 | out[i] = toupper((const unsigned char)in[i]); |
Harald Welte | 2822296 | 2011-02-18 20:37:04 +0100 | [diff] [blame] | 488 | out[strlen(in)] = '\0'; |
| 489 | } |
| 490 | #endif /* HAVE_CTYPE_H */ |
Harald Welte | 8598f18 | 2011-08-17 14:19:27 +0200 | [diff] [blame] | 491 | |
Neels Hofmeyr | 87e4550 | 2017-06-20 00:17:59 +0200 | [diff] [blame] | 492 | /*! Wishful thinking to generate a constant time compare |
Harald Welte | 9709b2e | 2016-04-25 18:47:53 +0200 | [diff] [blame] | 493 | * \param[in] exp Expected data |
| 494 | * \param[in] rel Comparison value |
| 495 | * \param[in] count Number of bytes to compare |
| 496 | * \returns 1 in case \a exp equals \a rel; zero otherwise |
| 497 | * |
| 498 | * Compare count bytes of exp to rel. Return 0 if they are identical, 1 |
| 499 | * otherwise. Do not return a mismatch on the first mismatching byte, |
| 500 | * but always compare all bytes, regardless. The idea is that the amount of |
| 501 | * matching bytes cannot be inferred from the time the comparison took. */ |
| 502 | int osmo_constant_time_cmp(const uint8_t *exp, const uint8_t *rel, const int count) |
| 503 | { |
| 504 | int x = 0, i; |
| 505 | |
| 506 | for (i = 0; i < count; ++i) |
| 507 | x |= exp[i] ^ rel[i]; |
| 508 | |
| 509 | /* if x is zero, all data was identical */ |
| 510 | return x? 1 : 0; |
| 511 | } |
| 512 | |
Neels Hofmeyr | 87e4550 | 2017-06-20 00:17:59 +0200 | [diff] [blame] | 513 | /*! Generic retrieval of 1..8 bytes as big-endian uint64_t |
Harald Welte | 9709b2e | 2016-04-25 18:47:53 +0200 | [diff] [blame] | 514 | * \param[in] data Input data as byte-array |
| 515 | * \param[in] data_len Length of \a data in octets |
| 516 | * \returns uint64_t of \a data interpreted as big-endian |
| 517 | * |
| 518 | * This is like osmo_load64be_ext, except that if data_len is less than |
| 519 | * sizeof(uint64_t), the data is interpreted as the least significant bytes |
| 520 | * (osmo_load64be_ext loads them as the most significant bytes into the |
| 521 | * returned uint64_t). In this way, any integer size up to 64 bits can be |
| 522 | * decoded conveniently by using sizeof(), without the need to call specific |
| 523 | * numbered functions (osmo_load16, 32, ...). */ |
| 524 | uint64_t osmo_decode_big_endian(const uint8_t *data, size_t data_len) |
| 525 | { |
| 526 | uint64_t value = 0; |
| 527 | |
| 528 | while (data_len > 0) { |
| 529 | value = (value << 8) + *data; |
| 530 | data += 1; |
| 531 | data_len -= 1; |
| 532 | } |
| 533 | |
| 534 | return value; |
| 535 | } |
| 536 | |
Neels Hofmeyr | 87e4550 | 2017-06-20 00:17:59 +0200 | [diff] [blame] | 537 | /*! Generic big-endian encoding of big endian number up to 64bit |
Harald Welte | 9709b2e | 2016-04-25 18:47:53 +0200 | [diff] [blame] | 538 | * \param[in] value unsigned integer value to be stored |
Pau Espin Pedrol | c29d513 | 2020-09-21 17:09:31 +0200 | [diff] [blame] | 539 | * \param[in] data_len number of octets |
Harald Welte | 9709b2e | 2016-04-25 18:47:53 +0200 | [diff] [blame] | 540 | * \returns static buffer containing big-endian stored value |
| 541 | * |
| 542 | * This is like osmo_store64be_ext, except that this returns a static buffer of |
| 543 | * the result (for convenience, but not threadsafe). If data_len is less than |
| 544 | * sizeof(uint64_t), only the least significant bytes of value are encoded. */ |
| 545 | uint8_t *osmo_encode_big_endian(uint64_t value, size_t data_len) |
| 546 | { |
Harald Welte | 171ef82 | 2019-03-28 10:49:05 +0100 | [diff] [blame] | 547 | static __thread uint8_t buf[sizeof(uint64_t)]; |
Harald Welte | 9709b2e | 2016-04-25 18:47:53 +0200 | [diff] [blame] | 548 | OSMO_ASSERT(data_len <= ARRAY_SIZE(buf)); |
| 549 | osmo_store64be_ext(value, buf, data_len); |
| 550 | return buf; |
| 551 | } |
Harald Welte | aeecc48 | 2016-11-26 10:41:40 +0100 | [diff] [blame] | 552 | |
Neels Hofmeyr | 87e4550 | 2017-06-20 00:17:59 +0200 | [diff] [blame] | 553 | /*! Copy a C-string into a sized buffer |
Harald Welte | aeecc48 | 2016-11-26 10:41:40 +0100 | [diff] [blame] | 554 | * \param[in] src source string |
| 555 | * \param[out] dst destination string |
Neels Hofmeyr | df83ece | 2017-01-13 13:55:43 +0100 | [diff] [blame] | 556 | * \param[in] siz size of the \a dst buffer |
| 557 | * \returns length of \a src |
Harald Welte | aeecc48 | 2016-11-26 10:41:40 +0100 | [diff] [blame] | 558 | * |
Neels Hofmeyr | df83ece | 2017-01-13 13:55:43 +0100 | [diff] [blame] | 559 | * Copy at most \a siz bytes from \a src to \a dst, ensuring that the result is |
| 560 | * NUL terminated. The NUL character is included in \a siz, i.e. passing the |
| 561 | * actual sizeof(*dst) is correct. |
Neels Hofmeyr | ff65d24 | 2019-11-19 00:21:14 +0100 | [diff] [blame] | 562 | * |
| 563 | * Note, a similar function that also limits the input buffer size is osmo_print_n(). |
Harald Welte | aeecc48 | 2016-11-26 10:41:40 +0100 | [diff] [blame] | 564 | */ |
| 565 | size_t osmo_strlcpy(char *dst, const char *src, size_t siz) |
| 566 | { |
Neels Hofmeyr | bcf9f23 | 2017-10-25 04:16:45 +0200 | [diff] [blame] | 567 | size_t ret = src ? strlen(src) : 0; |
Harald Welte | aeecc48 | 2016-11-26 10:41:40 +0100 | [diff] [blame] | 568 | |
| 569 | if (siz) { |
Pau Espin Pedrol | 53fbc67 | 2020-09-21 17:13:30 +0200 | [diff] [blame] | 570 | size_t len = OSMO_MIN(siz - 1, ret); |
Pau Espin Pedrol | c29d513 | 2020-09-21 17:09:31 +0200 | [diff] [blame] | 571 | if (len) |
Neels Hofmeyr | ebd3cdd | 2017-11-18 23:07:38 +0100 | [diff] [blame] | 572 | memcpy(dst, src, len); |
Harald Welte | aeecc48 | 2016-11-26 10:41:40 +0100 | [diff] [blame] | 573 | dst[len] = '\0'; |
| 574 | } |
| 575 | return ret; |
| 576 | } |
Neels Hofmeyr | 0aeda1b | 2017-01-13 14:16:02 +0100 | [diff] [blame] | 577 | |
Neels Hofmeyr | 06356fd | 2019-11-19 01:38:10 +0100 | [diff] [blame] | 578 | /*! Find first occurence of a char in a size limited string. |
| 579 | * Like strchr() but with a buffer size limit. |
| 580 | * \param[in] str String buffer to examine. |
| 581 | * \param[in] str_size sizeof(str). |
| 582 | * \param[in] c Character to look for. |
| 583 | * \return Pointer to the matched char, or NULL if not found. |
| 584 | */ |
| 585 | const char *osmo_strnchr(const char *str, size_t str_size, char c) |
| 586 | { |
| 587 | const char *end = str + str_size; |
| 588 | const char *pos; |
| 589 | if (!str) |
| 590 | return NULL; |
| 591 | for (pos = str; pos < end; pos++) { |
| 592 | if (c == *pos) |
| 593 | return pos; |
| 594 | if (!*pos) |
| 595 | return NULL; |
| 596 | } |
| 597 | return NULL; |
| 598 | } |
| 599 | |
Neels Hofmeyr | 4335bad | 2017-10-07 04:39:14 +0200 | [diff] [blame] | 600 | /*! Validate that a given string is a hex string within given size limits. |
| 601 | * Note that each hex digit amounts to a nibble, so if checking for a hex |
| 602 | * string to result in N bytes, pass amount of digits as 2*N. |
| 603 | * \param str A nul-terminated string to validate, or NULL. |
| 604 | * \param min_digits least permitted amount of digits. |
| 605 | * \param max_digits most permitted amount of digits. |
| 606 | * \param require_even if true, require an even amount of digits. |
| 607 | * \returns true when the hex_str contains only hexadecimal digits (no |
| 608 | * whitespace) and matches the requested length; also true |
| 609 | * when min_digits <= 0 and str is NULL. |
| 610 | */ |
| 611 | bool osmo_is_hexstr(const char *str, int min_digits, int max_digits, |
| 612 | bool require_even) |
| 613 | { |
| 614 | int len; |
| 615 | /* Use unsigned char * to avoid a compiler warning of |
| 616 | * "error: array subscript has type 'char' [-Werror=char-subscripts]" */ |
| 617 | const unsigned char *pos = (const unsigned char*)str; |
| 618 | if (!pos) |
| 619 | return min_digits < 1; |
| 620 | for (len = 0; *pos && len < max_digits; len++, pos++) |
| 621 | if (!isxdigit(*pos)) |
| 622 | return false; |
| 623 | if (len < min_digits) |
| 624 | return false; |
| 625 | /* With not too many digits, we should have reached *str == nul */ |
| 626 | if (*pos) |
| 627 | return false; |
| 628 | if (require_even && (len & 1)) |
| 629 | return false; |
Harald Welte | febe83c | 2017-10-03 17:41:59 +0800 | [diff] [blame] | 630 | |
| 631 | return true; |
| 632 | } |
| 633 | |
Neels Hofmeyr | b480b74 | 2019-04-11 06:58:44 +0200 | [diff] [blame] | 634 | static const char osmo_identifier_illegal_chars[] = "., {}[]()<>|~\\^`'\"?=;/+*&%$#!"; |
| 635 | |
Harald Welte | febe83c | 2017-10-03 17:41:59 +0800 | [diff] [blame] | 636 | /*! Determine if a given identifier is valid, i.e. doesn't contain illegal chars |
| 637 | * \param[in] str String to validate |
Neels Hofmeyr | 937ddea | 2017-12-16 00:46:50 +0100 | [diff] [blame] | 638 | * \param[in] sep_chars Permitted separation characters between identifiers. |
| 639 | * \returns true in case \a str contains only valid identifiers and sep_chars, false otherwise |
Harald Welte | febe83c | 2017-10-03 17:41:59 +0800 | [diff] [blame] | 640 | */ |
Neels Hofmeyr | 937ddea | 2017-12-16 00:46:50 +0100 | [diff] [blame] | 641 | bool osmo_separated_identifiers_valid(const char *str, const char *sep_chars) |
Harald Welte | febe83c | 2017-10-03 17:41:59 +0800 | [diff] [blame] | 642 | { |
| 643 | /* characters that are illegal in names */ |
Harald Welte | febe83c | 2017-10-03 17:41:59 +0800 | [diff] [blame] | 644 | unsigned int i; |
Neels Hofmeyr | 937ddea | 2017-12-16 00:46:50 +0100 | [diff] [blame] | 645 | size_t len; |
Harald Welte | febe83c | 2017-10-03 17:41:59 +0800 | [diff] [blame] | 646 | |
| 647 | /* an empty string is not a valid identifier */ |
Neels Hofmeyr | 937ddea | 2017-12-16 00:46:50 +0100 | [diff] [blame] | 648 | if (!str || (len = strlen(str)) == 0) |
Harald Welte | febe83c | 2017-10-03 17:41:59 +0800 | [diff] [blame] | 649 | return false; |
| 650 | |
Neels Hofmeyr | 937ddea | 2017-12-16 00:46:50 +0100 | [diff] [blame] | 651 | for (i = 0; i < len; i++) { |
| 652 | if (sep_chars && strchr(sep_chars, str[i])) |
| 653 | continue; |
Harald Welte | febe83c | 2017-10-03 17:41:59 +0800 | [diff] [blame] | 654 | /* check for 7-bit ASCII */ |
| 655 | if (str[i] & 0x80) |
| 656 | return false; |
Neels Hofmeyr | e5a2bdb | 2017-12-16 04:54:37 +0100 | [diff] [blame] | 657 | if (!isprint((int)str[i])) |
| 658 | return false; |
Harald Welte | febe83c | 2017-10-03 17:41:59 +0800 | [diff] [blame] | 659 | /* check for some explicit reserved control characters */ |
Neels Hofmeyr | b480b74 | 2019-04-11 06:58:44 +0200 | [diff] [blame] | 660 | if (strchr(osmo_identifier_illegal_chars, str[i])) |
Harald Welte | febe83c | 2017-10-03 17:41:59 +0800 | [diff] [blame] | 661 | return false; |
| 662 | } |
| 663 | |
Neels Hofmeyr | 4335bad | 2017-10-07 04:39:14 +0200 | [diff] [blame] | 664 | return true; |
| 665 | } |
| 666 | |
Neels Hofmeyr | 937ddea | 2017-12-16 00:46:50 +0100 | [diff] [blame] | 667 | /*! Determine if a given identifier is valid, i.e. doesn't contain illegal chars |
| 668 | * \param[in] str String to validate |
| 669 | * \returns true in case \a str contains valid identifier, false otherwise |
| 670 | */ |
| 671 | bool osmo_identifier_valid(const char *str) |
| 672 | { |
| 673 | return osmo_separated_identifiers_valid(str, NULL); |
| 674 | } |
| 675 | |
Neels Hofmeyr | b480b74 | 2019-04-11 06:58:44 +0200 | [diff] [blame] | 676 | /*! Replace characters in the given string buffer so that it is guaranteed to pass osmo_separated_identifiers_valid(). |
| 677 | * To guarantee passing osmo_separated_identifiers_valid(), replace_with must not itself be an illegal character. If in |
| 678 | * doubt, use '-'. |
| 679 | * \param[inout] str Identifier to sanitize, must be nul terminated and in a writable buffer. |
Neels Hofmeyr | 5aa421f | 2021-07-07 23:50:29 +0200 | [diff] [blame] | 680 | * \param[in] sep_chars Additional characters that are to be replaced besides osmo_identifier_illegal_chars. |
Neels Hofmeyr | b480b74 | 2019-04-11 06:58:44 +0200 | [diff] [blame] | 681 | * \param[in] replace_with Replace any illegal characters with this character. |
| 682 | */ |
| 683 | void osmo_identifier_sanitize_buf(char *str, const char *sep_chars, char replace_with) |
| 684 | { |
| 685 | char *pos; |
| 686 | if (!str) |
| 687 | return; |
| 688 | for (pos = str; *pos; pos++) { |
| 689 | if (strchr(osmo_identifier_illegal_chars, *pos) |
| 690 | || (sep_chars && strchr(sep_chars, *pos))) |
| 691 | *pos = replace_with; |
| 692 | } |
| 693 | } |
| 694 | |
Neels Hofmeyr | ecef7ec | 2019-03-05 16:42:50 +0100 | [diff] [blame] | 695 | /*! Like osmo_escape_str_buf2, but with unusual ordering of arguments, and may sometimes return string constants instead |
| 696 | * of writing to buf for error cases or empty input. |
| 697 | * Most *_buf() functions have the buffer and size as first arguments, here the arguments are last. |
| 698 | * In particular, this function signature doesn't work with OSMO_STRBUF_APPEND_NOLEN(). |
Neels Hofmeyr | 9910bbc | 2017-12-16 00:54:52 +0100 | [diff] [blame] | 699 | * \param[in] str A string that may contain any characters. |
| 700 | * \param[in] len Pass -1 to print until nul char, or >= 0 to force a length. |
| 701 | * \param[inout] buf string buffer to write escaped characters to. |
| 702 | * \param[in] bufsize size of \a buf. |
Neels Hofmeyr | ecef7ec | 2019-03-05 16:42:50 +0100 | [diff] [blame] | 703 | * \returns buf containing an escaped representation, possibly truncated, |
| 704 | * or "(null)" if str == NULL, or "(error)" in case of errors. |
Neels Hofmeyr | 9910bbc | 2017-12-16 00:54:52 +0100 | [diff] [blame] | 705 | */ |
Neels Hofmeyr | ecef7ec | 2019-03-05 16:42:50 +0100 | [diff] [blame] | 706 | const char *osmo_escape_str_buf(const char *str, int in_len, char *buf, size_t bufsize) |
Neels Hofmeyr | 9910bbc | 2017-12-16 00:54:52 +0100 | [diff] [blame] | 707 | { |
Neels Hofmeyr | 9910bbc | 2017-12-16 00:54:52 +0100 | [diff] [blame] | 708 | if (!str) |
| 709 | return "(null)"; |
Neels Hofmeyr | ecef7ec | 2019-03-05 16:42:50 +0100 | [diff] [blame] | 710 | if (!buf || !bufsize) |
| 711 | return "(error)"; |
| 712 | return osmo_escape_str_buf2(buf, bufsize, str, in_len); |
| 713 | } |
| 714 | |
| 715 | /*! Copy N characters to a buffer with a function signature useful for OSMO_STRBUF_APPEND(). |
| 716 | * Similarly to snprintf(), the result is always nul terminated (except if buf is NULL or bufsize is 0). |
| 717 | * \param[out] buf Target buffer. |
| 718 | * \param[in] bufsize sizeof(buf). |
| 719 | * \param[in] str String to copy. |
| 720 | * \param[in] n Maximum number of non-nul characters to copy. |
| 721 | * \return Number of characters that would be written if bufsize were large enough excluding '\0' (like snprintf()). |
| 722 | */ |
| 723 | int osmo_print_n(char *buf, size_t bufsize, const char *str, size_t n) |
| 724 | { |
| 725 | size_t write_n; |
| 726 | |
| 727 | if (!str) |
| 728 | str = ""; |
| 729 | |
| 730 | n = strnlen(str, n); |
| 731 | |
| 732 | if (!buf || !bufsize) |
| 733 | return n; |
| 734 | write_n = n; |
| 735 | if (write_n >= bufsize) |
| 736 | write_n = bufsize - 1; |
| 737 | if (write_n) |
| 738 | strncpy(buf, str, write_n); |
| 739 | buf[write_n] = '\0'; |
| 740 | |
| 741 | return n; |
| 742 | } |
| 743 | |
| 744 | /*! Return the string with all non-printable characters escaped. |
Neels Hofmeyr | c36e2e4 | 2019-11-20 21:57:32 +0100 | [diff] [blame] | 745 | * This internal function is the implementation for all osmo_escape_str* and osmo_quote_str* API versions. |
Neels Hofmeyr | 8a7eed5 | 2019-11-21 00:12:10 +0100 | [diff] [blame] | 746 | * It provides both the legacy (non C compatible) escaping, as well as C compatible string constant syntax, |
| 747 | * and it provides a return value of characters-needed, to allow producing un-truncated strings in all cases. |
Neels Hofmeyr | ecef7ec | 2019-03-05 16:42:50 +0100 | [diff] [blame] | 748 | * \param[out] buf string buffer to write escaped characters to. |
| 749 | * \param[in] bufsize sizeof(buf). |
| 750 | * \param[in] str A string that may contain any characters. |
| 751 | * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length (also past nul chars). |
Neels Hofmeyr | 8a7eed5 | 2019-11-21 00:12:10 +0100 | [diff] [blame] | 752 | * \param[in] legacy_format If false, return C compatible string constants ("\x0f"), if true the legacy |
| 753 | * escaping format ("\15"). The legacy format also escapes as "\a\b\f\v", while |
| 754 | * the non-legacy format also escapes those as "\xNN" sequences. |
Neels Hofmeyr | c36e2e4 | 2019-11-20 21:57:32 +0100 | [diff] [blame] | 755 | * \return Number of characters that would be written if bufsize were large enough excluding '\0' (like snprintf()). |
Neels Hofmeyr | ecef7ec | 2019-03-05 16:42:50 +0100 | [diff] [blame] | 756 | */ |
Neels Hofmeyr | 1633735 | 2022-01-31 15:56:02 +0100 | [diff] [blame] | 757 | static int _osmo_escape_str_buf(char *buf, size_t bufsize, const char *str, int in_len, bool legacy_format) |
Neels Hofmeyr | ecef7ec | 2019-03-05 16:42:50 +0100 | [diff] [blame] | 758 | { |
| 759 | struct osmo_strbuf sb = { .buf = buf, .len = bufsize }; |
| 760 | int in_pos = 0; |
| 761 | int next_unprintable = 0; |
| 762 | |
| 763 | if (!str) |
| 764 | in_len = 0; |
Neels Hofmeyr | 9910bbc | 2017-12-16 00:54:52 +0100 | [diff] [blame] | 765 | |
| 766 | if (in_len < 0) |
| 767 | in_len = strlen(str); |
| 768 | |
Neels Hofmeyr | ecef7ec | 2019-03-05 16:42:50 +0100 | [diff] [blame] | 769 | /* Make sure of '\0' termination */ |
| 770 | if (!in_len) |
| 771 | OSMO_STRBUF_PRINTF(sb, "%s", ""); |
| 772 | |
Neels Hofmeyr | 9910bbc | 2017-12-16 00:54:52 +0100 | [diff] [blame] | 773 | while (in_pos < in_len) { |
| 774 | for (next_unprintable = in_pos; |
| 775 | next_unprintable < in_len && isprint((int)str[next_unprintable]) |
| 776 | && str[next_unprintable] != '"' |
| 777 | && str[next_unprintable] != '\\'; |
| 778 | next_unprintable++); |
| 779 | |
Neels Hofmeyr | ecef7ec | 2019-03-05 16:42:50 +0100 | [diff] [blame] | 780 | OSMO_STRBUF_APPEND(sb, osmo_print_n, &str[in_pos], next_unprintable - in_pos); |
| 781 | in_pos = next_unprintable; |
Neels Hofmeyr | 9910bbc | 2017-12-16 00:54:52 +0100 | [diff] [blame] | 782 | |
Neels Hofmeyr | ecef7ec | 2019-03-05 16:42:50 +0100 | [diff] [blame] | 783 | if (in_pos == in_len) |
Neels Hofmeyr | 9910bbc | 2017-12-16 00:54:52 +0100 | [diff] [blame] | 784 | goto done; |
| 785 | |
| 786 | switch (str[next_unprintable]) { |
| 787 | #define BACKSLASH_CASE(c, repr) \ |
| 788 | case c: \ |
Neels Hofmeyr | ecef7ec | 2019-03-05 16:42:50 +0100 | [diff] [blame] | 789 | OSMO_STRBUF_PRINTF(sb, "\\%c", repr); \ |
Neels Hofmeyr | 9910bbc | 2017-12-16 00:54:52 +0100 | [diff] [blame] | 790 | break |
| 791 | |
| 792 | BACKSLASH_CASE('\n', 'n'); |
| 793 | BACKSLASH_CASE('\r', 'r'); |
| 794 | BACKSLASH_CASE('\t', 't'); |
| 795 | BACKSLASH_CASE('\0', '0'); |
Neels Hofmeyr | 9910bbc | 2017-12-16 00:54:52 +0100 | [diff] [blame] | 796 | BACKSLASH_CASE('\\', '\\'); |
| 797 | BACKSLASH_CASE('"', '"'); |
Neels Hofmeyr | 9910bbc | 2017-12-16 00:54:52 +0100 | [diff] [blame] | 798 | |
| 799 | default: |
Neels Hofmeyr | 8a7eed5 | 2019-11-21 00:12:10 +0100 | [diff] [blame] | 800 | if (legacy_format) { |
| 801 | switch (str[next_unprintable]) { |
| 802 | BACKSLASH_CASE('\a', 'a'); |
| 803 | BACKSLASH_CASE('\b', 'b'); |
| 804 | BACKSLASH_CASE('\v', 'v'); |
| 805 | BACKSLASH_CASE('\f', 'f'); |
| 806 | default: |
| 807 | OSMO_STRBUF_PRINTF(sb, "\\%u", (unsigned char)str[in_pos]); |
| 808 | break; |
| 809 | } |
| 810 | break; |
| 811 | } |
| 812 | |
| 813 | OSMO_STRBUF_PRINTF(sb, "\\x%02x", (unsigned char)str[in_pos]); |
Neels Hofmeyr | 9910bbc | 2017-12-16 00:54:52 +0100 | [diff] [blame] | 814 | break; |
| 815 | } |
| 816 | in_pos ++; |
Neels Hofmeyr | 8a7eed5 | 2019-11-21 00:12:10 +0100 | [diff] [blame] | 817 | #undef BACKSLASH_CASE |
Neels Hofmeyr | 9910bbc | 2017-12-16 00:54:52 +0100 | [diff] [blame] | 818 | } |
| 819 | |
| 820 | done: |
Neels Hofmeyr | c36e2e4 | 2019-11-20 21:57:32 +0100 | [diff] [blame] | 821 | return sb.chars_needed; |
| 822 | } |
| 823 | |
| 824 | /*! Return the string with all non-printable characters escaped. |
| 825 | * \param[out] buf string buffer to write escaped characters to. |
| 826 | * \param[in] bufsize sizeof(buf). |
| 827 | * \param[in] str A string that may contain any characters. |
| 828 | * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length (also past nul chars). |
Neels Hofmeyr | 1633735 | 2022-01-31 15:56:02 +0100 | [diff] [blame] | 829 | * \return Number of characters that would be written if bufsize were large enough excluding '\0' (like snprintf()). |
| 830 | */ |
| 831 | int osmo_escape_str_buf3(char *buf, size_t bufsize, const char *str, int in_len) |
| 832 | { |
| 833 | return _osmo_escape_str_buf(buf, bufsize, str, in_len, false); |
| 834 | } |
| 835 | |
| 836 | /*! Return the string with all non-printable characters escaped. |
| 837 | * \param[out] buf string buffer to write escaped characters to. |
| 838 | * \param[in] bufsize sizeof(buf). |
| 839 | * \param[in] str A string that may contain any characters. |
| 840 | * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length (also past nul chars). |
Neels Hofmeyr | c36e2e4 | 2019-11-20 21:57:32 +0100 | [diff] [blame] | 841 | * \return The output buffer (buf). |
| 842 | */ |
| 843 | char *osmo_escape_str_buf2(char *buf, size_t bufsize, const char *str, int in_len) |
| 844 | { |
Neels Hofmeyr | 8a7eed5 | 2019-11-21 00:12:10 +0100 | [diff] [blame] | 845 | _osmo_escape_str_buf(buf, bufsize, str, in_len, true); |
Neels Hofmeyr | ecef7ec | 2019-03-05 16:42:50 +0100 | [diff] [blame] | 846 | return buf; |
Neels Hofmeyr | 9910bbc | 2017-12-16 00:54:52 +0100 | [diff] [blame] | 847 | } |
| 848 | |
| 849 | /*! Return the string with all non-printable characters escaped. |
| 850 | * Call osmo_escape_str_buf() with a static buffer. |
| 851 | * \param[in] str A string that may contain any characters. |
| 852 | * \param[in] len Pass -1 to print until nul char, or >= 0 to force a length. |
| 853 | * \returns buf containing an escaped representation, possibly truncated, or str itself. |
| 854 | */ |
| 855 | const char *osmo_escape_str(const char *str, int in_len) |
| 856 | { |
| 857 | return osmo_escape_str_buf(str, in_len, namebuf, sizeof(namebuf)); |
| 858 | } |
| 859 | |
Harald Welte | 179f357 | 2019-03-18 18:38:47 +0100 | [diff] [blame] | 860 | /*! Return the string with all non-printable characters escaped, in dynamically-allocated buffer. |
| 861 | * \param[in] str A string that may contain any characters. |
| 862 | * \param[in] len Pass -1 to print until nul char, or >= 0 to force a length. |
| 863 | * \returns dynamically-allocated output buffer, containing an escaped representation |
| 864 | */ |
| 865 | char *osmo_escape_str_c(const void *ctx, const char *str, int in_len) |
| 866 | { |
Neels Hofmeyr | c36e2e4 | 2019-11-20 21:57:32 +0100 | [diff] [blame] | 867 | /* The string will be at least as long as in_len, but some characters might need escaping. |
| 868 | * These extra bytes should catch most usual escaping situations, avoiding a second run in OSMO_NAME_C_IMPL. */ |
Neels Hofmeyr | 8a7eed5 | 2019-11-21 00:12:10 +0100 | [diff] [blame] | 869 | OSMO_NAME_C_IMPL(ctx, in_len + 16, "ERROR", _osmo_escape_str_buf, str, in_len, true); |
Neels Hofmeyr | c36e2e4 | 2019-11-20 21:57:32 +0100 | [diff] [blame] | 870 | } |
| 871 | |
| 872 | /*! Return a quoted and escaped representation of the string. |
| 873 | * This internal function is the implementation for all osmo_quote_str* API versions. |
Neels Hofmeyr | 8a7eed5 | 2019-11-21 00:12:10 +0100 | [diff] [blame] | 874 | * It provides both the legacy (non C compatible) escaping, as well as C compatible string constant syntax, |
| 875 | * and it provides a return value of characters-needed, to allow producing un-truncated strings in all cases. |
Neels Hofmeyr | c36e2e4 | 2019-11-20 21:57:32 +0100 | [diff] [blame] | 876 | * \param[out] buf string buffer to write escaped characters to. |
| 877 | * \param[in] bufsize sizeof(buf). |
| 878 | * \param[in] str A string that may contain any characters. |
| 879 | * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length (also past nul chars). |
Neels Hofmeyr | 8a7eed5 | 2019-11-21 00:12:10 +0100 | [diff] [blame] | 880 | * \param[in] legacy_format If false, return C compatible string constants ("\x0f"), if true the legacy |
| 881 | * escaping format ("\15"). The legacy format also escapes as "\a\b\f\v", while |
| 882 | * the non-legacy format also escapes those as "\xNN" sequences. |
Neels Hofmeyr | c36e2e4 | 2019-11-20 21:57:32 +0100 | [diff] [blame] | 883 | * \return Number of characters that would be written if bufsize were large enough excluding '\0' (like snprintf()). |
| 884 | */ |
Neels Hofmeyr | 8a7eed5 | 2019-11-21 00:12:10 +0100 | [diff] [blame] | 885 | static size_t _osmo_quote_str_buf(char *buf, size_t bufsize, const char *str, int in_len, bool legacy_format) |
Neels Hofmeyr | c36e2e4 | 2019-11-20 21:57:32 +0100 | [diff] [blame] | 886 | { |
| 887 | struct osmo_strbuf sb = { .buf = buf, .len = bufsize }; |
| 888 | if (!str) |
| 889 | OSMO_STRBUF_PRINTF(sb, "NULL"); |
| 890 | else { |
| 891 | OSMO_STRBUF_PRINTF(sb, "\""); |
Neels Hofmeyr | 8a7eed5 | 2019-11-21 00:12:10 +0100 | [diff] [blame] | 892 | OSMO_STRBUF_APPEND(sb, _osmo_escape_str_buf, str, in_len, legacy_format); |
Neels Hofmeyr | c36e2e4 | 2019-11-20 21:57:32 +0100 | [diff] [blame] | 893 | OSMO_STRBUF_PRINTF(sb, "\""); |
| 894 | } |
| 895 | return sb.chars_needed; |
Harald Welte | 179f357 | 2019-03-18 18:38:47 +0100 | [diff] [blame] | 896 | } |
| 897 | |
Neels Hofmeyr | 1633735 | 2022-01-31 15:56:02 +0100 | [diff] [blame] | 898 | /*! Like osmo_escape_str_buf3(), but returns double-quotes around a string, or "NULL" for a NULL string. |
| 899 | * This allows passing any char* value and get its C representation as string. |
| 900 | * The function signature is suitable for OSMO_STRBUF_APPEND_NOLEN(). |
| 901 | * \param[out] buf string buffer to write escaped characters to. |
| 902 | * \param[in] bufsize sizeof(buf). |
| 903 | * \param[in] str A string that may contain any characters. |
| 904 | * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length. |
| 905 | * \return Number of characters that would be written if bufsize were large enough excluding '\0' (like snprintf()). |
| 906 | */ |
| 907 | int osmo_quote_str_buf3(char *buf, size_t bufsize, const char *str, int in_len) |
| 908 | { |
| 909 | return _osmo_quote_str_buf(buf, bufsize, str, in_len, false); |
| 910 | } |
| 911 | |
Neels Hofmeyr | ecef7ec | 2019-03-05 16:42:50 +0100 | [diff] [blame] | 912 | /*! Like osmo_escape_str_buf2(), but returns double-quotes around a string, or "NULL" for a NULL string. |
Neels Hofmeyr | 04eb56f | 2018-04-09 00:41:28 +0200 | [diff] [blame] | 913 | * This allows passing any char* value and get its C representation as string. |
Neels Hofmeyr | ecef7ec | 2019-03-05 16:42:50 +0100 | [diff] [blame] | 914 | * The function signature is suitable for OSMO_STRBUF_APPEND_NOLEN(). |
| 915 | * \param[out] buf string buffer to write escaped characters to. |
| 916 | * \param[in] bufsize sizeof(buf). |
| 917 | * \param[in] str A string that may contain any characters. |
| 918 | * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length. |
Neels Hofmeyr | dd7b6f9 | 2019-11-20 21:32:29 +0100 | [diff] [blame] | 919 | * \return The output buffer (buf). |
Neels Hofmeyr | ecef7ec | 2019-03-05 16:42:50 +0100 | [diff] [blame] | 920 | */ |
| 921 | char *osmo_quote_str_buf2(char *buf, size_t bufsize, const char *str, int in_len) |
| 922 | { |
Neels Hofmeyr | 8a7eed5 | 2019-11-21 00:12:10 +0100 | [diff] [blame] | 923 | _osmo_quote_str_buf(buf, bufsize, str, in_len, true); |
Neels Hofmeyr | ecef7ec | 2019-03-05 16:42:50 +0100 | [diff] [blame] | 924 | return buf; |
| 925 | } |
| 926 | |
| 927 | /*! Like osmo_quote_str_buf2, but with unusual ordering of arguments, and may sometimes return string constants instead |
| 928 | * of writing to buf for error cases or empty input. |
| 929 | * Most *_buf() functions have the buffer and size as first arguments, here the arguments are last. |
| 930 | * In particular, this function signature doesn't work with OSMO_STRBUF_APPEND_NOLEN(). |
Neels Hofmeyr | 04eb56f | 2018-04-09 00:41:28 +0200 | [diff] [blame] | 931 | * \param[in] str A string that may contain any characters. |
Neels Hofmeyr | 03e7553 | 2018-09-07 03:12:05 +0200 | [diff] [blame] | 932 | * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length. |
| 933 | * \returns buf containing a quoted and escaped representation, possibly truncated. |
Neels Hofmeyr | 04eb56f | 2018-04-09 00:41:28 +0200 | [diff] [blame] | 934 | */ |
Neels Hofmeyr | ecef7ec | 2019-03-05 16:42:50 +0100 | [diff] [blame] | 935 | const char *osmo_quote_str_buf(const char *str, int in_len, char *buf, size_t bufsize) |
Neels Hofmeyr | 04eb56f | 2018-04-09 00:41:28 +0200 | [diff] [blame] | 936 | { |
Neels Hofmeyr | 04eb56f | 2018-04-09 00:41:28 +0200 | [diff] [blame] | 937 | if (!str) |
| 938 | return "NULL"; |
Neels Hofmeyr | ecef7ec | 2019-03-05 16:42:50 +0100 | [diff] [blame] | 939 | if (!buf || !bufsize) |
| 940 | return "(error)"; |
Neels Hofmeyr | 8a7eed5 | 2019-11-21 00:12:10 +0100 | [diff] [blame] | 941 | _osmo_quote_str_buf(buf, bufsize, str, in_len, true); |
Neels Hofmeyr | 04eb56f | 2018-04-09 00:41:28 +0200 | [diff] [blame] | 942 | return buf; |
| 943 | } |
| 944 | |
Neels Hofmeyr | 03e7553 | 2018-09-07 03:12:05 +0200 | [diff] [blame] | 945 | /*! Like osmo_quote_str_buf() but returns the result in a static buffer. |
| 946 | * The static buffer is shared with get_value_string() and osmo_escape_str(). |
| 947 | * \param[in] str A string that may contain any characters. |
| 948 | * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length. |
| 949 | * \returns static buffer containing a quoted and escaped representation, possibly truncated. |
| 950 | */ |
Neels Hofmeyr | 04eb56f | 2018-04-09 00:41:28 +0200 | [diff] [blame] | 951 | const char *osmo_quote_str(const char *str, int in_len) |
| 952 | { |
Neels Hofmeyr | 8a7eed5 | 2019-11-21 00:12:10 +0100 | [diff] [blame] | 953 | _osmo_quote_str_buf(namebuf, sizeof(namebuf), str, in_len, true); |
Neels Hofmeyr | c36e2e4 | 2019-11-20 21:57:32 +0100 | [diff] [blame] | 954 | return namebuf; |
Neels Hofmeyr | 04eb56f | 2018-04-09 00:41:28 +0200 | [diff] [blame] | 955 | } |
| 956 | |
Harald Welte | 179f357 | 2019-03-18 18:38:47 +0100 | [diff] [blame] | 957 | /*! Like osmo_quote_str_buf() but returns the result in a dynamically-allocated buffer. |
Harald Welte | 179f357 | 2019-03-18 18:38:47 +0100 | [diff] [blame] | 958 | * \param[in] str A string that may contain any characters. |
| 959 | * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length. |
| 960 | * \returns dynamically-allocated buffer containing a quoted and escaped representation. |
| 961 | */ |
| 962 | char *osmo_quote_str_c(const void *ctx, const char *str, int in_len) |
| 963 | { |
Neels Hofmeyr | c36e2e4 | 2019-11-20 21:57:32 +0100 | [diff] [blame] | 964 | /* The string will be at least as long as in_len, but some characters might need escaping. |
| 965 | * These extra bytes should catch most usual escaping situations, avoiding a second run in OSMO_NAME_C_IMPL. */ |
Neels Hofmeyr | 8a7eed5 | 2019-11-21 00:12:10 +0100 | [diff] [blame] | 966 | OSMO_NAME_C_IMPL(ctx, in_len + 16, "ERROR", _osmo_quote_str_buf, str, in_len, true); |
| 967 | } |
| 968 | |
| 969 | /*! Return the string with all non-printable characters escaped. |
| 970 | * In contrast to osmo_escape_str_buf2(), this returns the needed buffer size suitable for OSMO_STRBUF_APPEND(), and |
| 971 | * this escapes characters in a way compatible with C string constant syntax. |
| 972 | * \param[out] buf string buffer to write escaped characters to. |
| 973 | * \param[in] bufsize sizeof(buf). |
| 974 | * \param[in] str A string that may contain any characters. |
| 975 | * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length (also past nul chars). |
| 976 | * \return Number of characters that would be written if bufsize were large enough excluding '\0' (like snprintf()). |
| 977 | */ |
| 978 | size_t osmo_escape_cstr_buf(char *buf, size_t bufsize, const char *str, int in_len) |
| 979 | { |
| 980 | return _osmo_escape_str_buf(buf, bufsize, str, in_len, false); |
| 981 | } |
| 982 | |
| 983 | /*! Return the string with all non-printable characters escaped, in dynamically-allocated buffer. |
| 984 | * In contrast to osmo_escape_str_c(), this escapes characters in a way compatible with C string constant syntax, and |
| 985 | * allocates sufficient memory in all cases. |
| 986 | * \param[in] str A string that may contain any characters. |
| 987 | * \param[in] len Pass -1 to print until nul char, or >= 0 to force a length. |
| 988 | * \returns dynamically-allocated buffer, containing an escaped representation. |
| 989 | */ |
| 990 | char *osmo_escape_cstr_c(void *ctx, const char *str, int in_len) |
| 991 | { |
| 992 | /* The string will be at least as long as in_len, but some characters might need escaping. |
| 993 | * These extra bytes should catch most usual escaping situations, avoiding a second run in OSMO_NAME_C_IMPL. */ |
| 994 | OSMO_NAME_C_IMPL(ctx, in_len + 16, "ERROR", _osmo_escape_str_buf, str, in_len, false); |
| 995 | } |
| 996 | |
| 997 | /*! Like osmo_escape_str_buf2(), but returns double-quotes around a string, or "NULL" for a NULL string. |
| 998 | * This allows passing any char* value and get its C representation as string. |
| 999 | * The function signature is suitable for OSMO_STRBUF_APPEND_NOLEN(). |
| 1000 | * In contrast to osmo_escape_str_buf2(), this returns the needed buffer size suitable for OSMO_STRBUF_APPEND(), and |
| 1001 | * this escapes characters in a way compatible with C string constant syntax. |
| 1002 | * \param[out] buf string buffer to write escaped characters to. |
| 1003 | * \param[in] bufsize sizeof(buf). |
| 1004 | * \param[in] str A string that may contain any characters. |
| 1005 | * \param[in] in_len Pass -1 to print until nul char, or >= 0 to force a length. |
| 1006 | * \return Number of characters that would be written if bufsize were large enough excluding '\0' (like snprintf()). |
| 1007 | */ |
| 1008 | size_t osmo_quote_cstr_buf(char *buf, size_t bufsize, const char *str, int in_len) |
| 1009 | { |
| 1010 | return _osmo_quote_str_buf(buf, bufsize, str, in_len, false); |
| 1011 | } |
| 1012 | |
| 1013 | /*! Return the string quoted and with all non-printable characters escaped, in dynamically-allocated buffer. |
| 1014 | * In contrast to osmo_quote_str_c(), this escapes characters in a way compatible with C string constant syntax, and |
| 1015 | * allocates sufficient memory in all cases. |
| 1016 | * \param[in] str A string that may contain any characters. |
| 1017 | * \param[in] len Pass -1 to print until nul char, or >= 0 to force a length. |
| 1018 | * \returns dynamically-allocated buffer, containing a quoted and escaped representation. |
| 1019 | */ |
| 1020 | char *osmo_quote_cstr_c(void *ctx, const char *str, int in_len) |
| 1021 | { |
| 1022 | /* The string will be at least as long as in_len plus two quotes, but some characters might need escaping. |
| 1023 | * These extra bytes should catch most usual escaping situations, avoiding a second run in OSMO_NAME_C_IMPL. */ |
| 1024 | OSMO_NAME_C_IMPL(ctx, in_len + 16, "ERROR", _osmo_quote_str_buf, str, in_len, false); |
Harald Welte | 179f357 | 2019-03-18 18:38:47 +0100 | [diff] [blame] | 1025 | } |
| 1026 | |
Harald Welte | 15a5f8d | 2018-06-06 16:58:17 +0200 | [diff] [blame] | 1027 | /*! perform an integer square root operation on unsigned 32bit integer. |
| 1028 | * This implementation is taken from "Hacker's Delight" Figure 11-1 "Integer square root, Newton's |
| 1029 | * method", which can also be found at http://www.hackersdelight.org/hdcodetxt/isqrt.c.txt */ |
| 1030 | uint32_t osmo_isqrt32(uint32_t x) |
| 1031 | { |
| 1032 | uint32_t x1; |
| 1033 | int s, g0, g1; |
| 1034 | |
| 1035 | if (x <= 1) |
| 1036 | return x; |
| 1037 | |
| 1038 | s = 1; |
| 1039 | x1 = x - 1; |
| 1040 | if (x1 > 0xffff) { |
| 1041 | s = s + 8; |
| 1042 | x1 = x1 >> 16; |
| 1043 | } |
| 1044 | if (x1 > 0xff) { |
| 1045 | s = s + 4; |
| 1046 | x1 = x1 >> 8; |
| 1047 | } |
| 1048 | if (x1 > 0xf) { |
| 1049 | s = s + 2; |
| 1050 | x1 = x1 >> 4; |
| 1051 | } |
| 1052 | if (x1 > 0x3) { |
| 1053 | s = s + 1; |
| 1054 | } |
| 1055 | |
| 1056 | g0 = 1 << s; /* g0 = 2**s */ |
| 1057 | g1 = (g0 + (x >> s)) >> 1; /* g1 = (g0 + x/g0)/2 */ |
| 1058 | |
| 1059 | /* converges after four to five divisions for arguments up to 16,785,407 */ |
| 1060 | while (g1 < g0) { |
| 1061 | g0 = g1; |
| 1062 | g1 = (g0 + (x/g0)) >> 1; |
| 1063 | } |
| 1064 | return g0; |
| 1065 | } |
| 1066 | |
Neels Hofmeyr | 7c74989 | 2018-09-07 03:01:38 +0200 | [diff] [blame] | 1067 | /*! Convert a string to lowercase, while checking buffer size boundaries. |
| 1068 | * The result written to \a dest is guaranteed to be nul terminated if \a dest_len > 0. |
| 1069 | * If dest == src, the string is converted in-place, if necessary truncated at dest_len - 1 characters |
| 1070 | * length as well as nul terminated. |
| 1071 | * Note: similar osmo_str2lower(), but safe to use for src strings of arbitrary length. |
| 1072 | * \param[out] dest Target buffer to write lowercase string. |
| 1073 | * \param[in] dest_len Maximum buffer size of dest (e.g. sizeof(dest)). |
| 1074 | * \param[in] src String to convert to lowercase. |
| 1075 | * \returns Length of \a src, like osmo_strlcpy(), but if \a dest == \a src at most \a dest_len - 1. |
| 1076 | */ |
| 1077 | size_t osmo_str_tolower_buf(char *dest, size_t dest_len, const char *src) |
| 1078 | { |
| 1079 | size_t rc; |
| 1080 | if (dest == src) { |
| 1081 | if (dest_len < 1) |
| 1082 | return 0; |
| 1083 | dest[dest_len - 1] = '\0'; |
| 1084 | rc = strlen(dest); |
| 1085 | } else { |
| 1086 | if (dest_len < 1) |
| 1087 | return strlen(src); |
| 1088 | rc = osmo_strlcpy(dest, src, dest_len); |
| 1089 | } |
| 1090 | for (; *dest; dest++) |
| 1091 | *dest = tolower(*dest); |
| 1092 | return rc; |
| 1093 | } |
| 1094 | |
| 1095 | /*! Convert a string to lowercase, using a static buffer. |
| 1096 | * The resulting string may be truncated if the internally used static buffer is shorter than src. |
| 1097 | * The internal buffer is at least 128 bytes long, i.e. guaranteed to hold at least 127 characters and a |
Pau Espin Pedrol | a37f58e | 2019-08-01 18:11:41 +0200 | [diff] [blame] | 1098 | * terminating nul. The static buffer returned is shared with osmo_str_toupper(). |
Neels Hofmeyr | 7c74989 | 2018-09-07 03:01:38 +0200 | [diff] [blame] | 1099 | * See also osmo_str_tolower_buf(). |
| 1100 | * \param[in] src String to convert to lowercase. |
| 1101 | * \returns Resulting lowercase string in a static buffer, always nul terminated. |
| 1102 | */ |
| 1103 | const char *osmo_str_tolower(const char *src) |
| 1104 | { |
Pau Espin Pedrol | a37f58e | 2019-08-01 18:11:41 +0200 | [diff] [blame] | 1105 | osmo_str_tolower_buf(capsbuf, sizeof(capsbuf), src); |
| 1106 | return capsbuf; |
Neels Hofmeyr | 7c74989 | 2018-09-07 03:01:38 +0200 | [diff] [blame] | 1107 | } |
| 1108 | |
Harald Welte | 179f357 | 2019-03-18 18:38:47 +0100 | [diff] [blame] | 1109 | /*! Convert a string to lowercase, dynamically allocating the output from given talloc context |
| 1110 | * See also osmo_str_tolower_buf(). |
| 1111 | * \param[in] ctx talloc context from where to allocate the output string |
| 1112 | * \param[in] src String to convert to lowercase. |
| 1113 | * \returns Resulting lowercase string in a dynamically allocated buffer, always nul terminated. |
| 1114 | */ |
| 1115 | char *osmo_str_tolower_c(const void *ctx, const char *src) |
| 1116 | { |
Vadim Yanitskiy | 4f619c2 | 2019-04-12 21:48:07 +0700 | [diff] [blame] | 1117 | size_t buf_len = strlen(src) + 1; |
| 1118 | char *buf = talloc_size(ctx, buf_len); |
Harald Welte | 179f357 | 2019-03-18 18:38:47 +0100 | [diff] [blame] | 1119 | if (!buf) |
| 1120 | return NULL; |
Vadim Yanitskiy | 4f619c2 | 2019-04-12 21:48:07 +0700 | [diff] [blame] | 1121 | osmo_str_tolower_buf(buf, buf_len, src); |
Harald Welte | 179f357 | 2019-03-18 18:38:47 +0100 | [diff] [blame] | 1122 | return buf; |
| 1123 | } |
| 1124 | |
Neels Hofmeyr | 7c74989 | 2018-09-07 03:01:38 +0200 | [diff] [blame] | 1125 | /*! Convert a string to uppercase, while checking buffer size boundaries. |
| 1126 | * The result written to \a dest is guaranteed to be nul terminated if \a dest_len > 0. |
| 1127 | * If dest == src, the string is converted in-place, if necessary truncated at dest_len - 1 characters |
| 1128 | * length as well as nul terminated. |
| 1129 | * Note: similar osmo_str2upper(), but safe to use for src strings of arbitrary length. |
| 1130 | * \param[out] dest Target buffer to write uppercase string. |
| 1131 | * \param[in] dest_len Maximum buffer size of dest (e.g. sizeof(dest)). |
| 1132 | * \param[in] src String to convert to uppercase. |
| 1133 | * \returns Length of \a src, like osmo_strlcpy(), but if \a dest == \a src at most \a dest_len - 1. |
| 1134 | */ |
| 1135 | size_t osmo_str_toupper_buf(char *dest, size_t dest_len, const char *src) |
| 1136 | { |
| 1137 | size_t rc; |
| 1138 | if (dest == src) { |
| 1139 | if (dest_len < 1) |
| 1140 | return 0; |
| 1141 | dest[dest_len - 1] = '\0'; |
| 1142 | rc = strlen(dest); |
| 1143 | } else { |
| 1144 | if (dest_len < 1) |
| 1145 | return strlen(src); |
| 1146 | rc = osmo_strlcpy(dest, src, dest_len); |
| 1147 | } |
| 1148 | for (; *dest; dest++) |
| 1149 | *dest = toupper(*dest); |
| 1150 | return rc; |
| 1151 | } |
| 1152 | |
| 1153 | /*! Convert a string to uppercase, using a static buffer. |
| 1154 | * The resulting string may be truncated if the internally used static buffer is shorter than src. |
| 1155 | * The internal buffer is at least 128 bytes long, i.e. guaranteed to hold at least 127 characters and a |
Pau Espin Pedrol | a37f58e | 2019-08-01 18:11:41 +0200 | [diff] [blame] | 1156 | * terminating nul. The static buffer returned is shared with osmo_str_tolower(). |
Neels Hofmeyr | 7c74989 | 2018-09-07 03:01:38 +0200 | [diff] [blame] | 1157 | * See also osmo_str_toupper_buf(). |
| 1158 | * \param[in] src String to convert to uppercase. |
| 1159 | * \returns Resulting uppercase string in a static buffer, always nul terminated. |
| 1160 | */ |
| 1161 | const char *osmo_str_toupper(const char *src) |
| 1162 | { |
Pau Espin Pedrol | a37f58e | 2019-08-01 18:11:41 +0200 | [diff] [blame] | 1163 | osmo_str_toupper_buf(capsbuf, sizeof(capsbuf), src); |
| 1164 | return capsbuf; |
Neels Hofmeyr | 7c74989 | 2018-09-07 03:01:38 +0200 | [diff] [blame] | 1165 | } |
| 1166 | |
Harald Welte | 179f357 | 2019-03-18 18:38:47 +0100 | [diff] [blame] | 1167 | /*! Convert a string to uppercase, dynamically allocating the output from given talloc context |
| 1168 | * See also osmo_str_tolower_buf(). |
| 1169 | * \param[in] ctx talloc context from where to allocate the output string |
| 1170 | * \param[in] src String to convert to uppercase. |
| 1171 | * \returns Resulting uppercase string in a dynamically allocated buffer, always nul terminated. |
| 1172 | */ |
| 1173 | char *osmo_str_toupper_c(const void *ctx, const char *src) |
| 1174 | { |
Vadim Yanitskiy | 4f619c2 | 2019-04-12 21:48:07 +0700 | [diff] [blame] | 1175 | size_t buf_len = strlen(src) + 1; |
| 1176 | char *buf = talloc_size(ctx, buf_len); |
Harald Welte | 179f357 | 2019-03-18 18:38:47 +0100 | [diff] [blame] | 1177 | if (!buf) |
| 1178 | return NULL; |
Vadim Yanitskiy | 4f619c2 | 2019-04-12 21:48:07 +0700 | [diff] [blame] | 1179 | osmo_str_toupper_buf(buf, buf_len, src); |
Harald Welte | 179f357 | 2019-03-18 18:38:47 +0100 | [diff] [blame] | 1180 | return buf; |
| 1181 | } |
| 1182 | |
Oliver Smith | 894be2d | 2019-01-11 13:13:37 +0100 | [diff] [blame] | 1183 | /*! Calculate the Luhn checksum (as used for IMEIs). |
| 1184 | * \param[in] in Input digits in ASCII string representation. |
| 1185 | * \param[in] in_len Count of digits to use for the input (14 for IMEI). |
| 1186 | * \returns checksum char (e.g. '3'); negative on error |
| 1187 | */ |
Vadim Yanitskiy | d9fc604 | 2019-06-12 15:49:03 +0700 | [diff] [blame] | 1188 | char osmo_luhn(const char* in, int in_len) |
Oliver Smith | 894be2d | 2019-01-11 13:13:37 +0100 | [diff] [blame] | 1189 | { |
| 1190 | int i, sum = 0; |
| 1191 | |
| 1192 | /* All input must be numbers */ |
| 1193 | for (i = 0; i < in_len; i++) { |
KĂ©vin Redon | 1af2cd5 | 2019-05-23 19:00:19 +0200 | [diff] [blame] | 1194 | if (!isdigit((unsigned char)in[i])) |
Oliver Smith | 894be2d | 2019-01-11 13:13:37 +0100 | [diff] [blame] | 1195 | return -EINVAL; |
| 1196 | } |
| 1197 | |
| 1198 | /* Double every second digit and add it to sum */ |
| 1199 | for (i = in_len - 1; i >= 0; i -= 2) { |
| 1200 | int dbl = (in[i] - '0') * 2; |
| 1201 | if (dbl > 9) |
| 1202 | dbl -= 9; |
| 1203 | sum += dbl; |
| 1204 | } |
| 1205 | |
| 1206 | /* Add other digits to sum */ |
| 1207 | for (i = in_len - 2; i >= 0; i -= 2) |
| 1208 | sum += in[i] - '0'; |
| 1209 | |
| 1210 | /* Final checksum */ |
| 1211 | return (sum * 9) % 10 + '0'; |
| 1212 | } |
| 1213 | |
Neels Hofmeyr | d79ccc6 | 2019-03-07 23:08:40 +0100 | [diff] [blame] | 1214 | /*! Compare start of a string. |
| 1215 | * This is an optimisation of 'strstr(str, startswith_str) == str' because it doesn't search through the entire string. |
| 1216 | * \param str (Longer) string to compare. |
| 1217 | * \param startswith_str (Shorter) string to compare with the start of str. |
| 1218 | * \return true iff the first characters of str fully match startswith_str or startswith_str is empty. */ |
| 1219 | bool osmo_str_startswith(const char *str, const char *startswith_str) |
| 1220 | { |
| 1221 | if (!startswith_str || !*startswith_str) |
| 1222 | return true; |
| 1223 | if (!str) |
| 1224 | return false; |
| 1225 | return strncmp(str, startswith_str, strlen(startswith_str)) == 0; |
| 1226 | } |
| 1227 | |
Neels Hofmeyr | 87c3afb | 2020-09-30 21:47:47 +0000 | [diff] [blame] | 1228 | /*! Convert a string of a floating point number to a signed int, with a decimal factor (fixed-point precision). |
| 1229 | * For example, with precision=3, convert "-1.23" to -1230. In other words, the float value is multiplied by |
| 1230 | * 10 to-the-power-of precision to obtain the returned integer. |
| 1231 | * The usable range of digits is -INT64_MAX .. INT64_MAX -- note, not INT64_MIN! The value of INT64_MIN is excluded to |
| 1232 | * reduce implementation complexity. See also utils_test.c. |
Neels Hofmeyr | 6d74498 | 2020-10-08 13:09:49 +0200 | [diff] [blame] | 1233 | * The advantage over using sscanf("%f") is guaranteed precision: float or double types may apply rounding in the |
| 1234 | * conversion result. osmo_float_str_to_int() and osmo_int_to_float_str_buf() guarantee true results when converting |
| 1235 | * back and forth between string and int. |
Neels Hofmeyr | 87c3afb | 2020-09-30 21:47:47 +0000 | [diff] [blame] | 1236 | * \param[out] val Returned integer value. |
| 1237 | * \param[in] str String of a float, like '-12.345'. |
Neels Hofmeyr | 87c3afb | 2020-09-30 21:47:47 +0000 | [diff] [blame] | 1238 | * \param[in] precision Fixed-point precision, or * \returns 0 on success, negative on error. |
| 1239 | */ |
| 1240 | int osmo_float_str_to_int(int64_t *val, const char *str, unsigned int precision) |
| 1241 | { |
| 1242 | const char *point; |
| 1243 | char *endptr; |
| 1244 | const char *p; |
| 1245 | int64_t sign = 1; |
| 1246 | int64_t integer = 0; |
| 1247 | int64_t decimal = 0; |
| 1248 | int64_t precision_factor; |
| 1249 | int64_t integer_max; |
| 1250 | int64_t decimal_max; |
Harald Welte | 7d6166a | 2022-01-09 11:57:01 +0100 | [diff] [blame] | 1251 | unsigned int i; |
Neels Hofmeyr | 87c3afb | 2020-09-30 21:47:47 +0000 | [diff] [blame] | 1252 | |
| 1253 | OSMO_ASSERT(val); |
| 1254 | *val = 0; |
| 1255 | |
| 1256 | if (!str) |
| 1257 | return -EINVAL; |
| 1258 | if (str[0] == '-') { |
| 1259 | str = str + 1; |
| 1260 | sign = -1; |
| 1261 | } else if (str[0] == '+') { |
| 1262 | str = str + 1; |
| 1263 | } |
| 1264 | if (!str[0]) |
| 1265 | return -EINVAL; |
| 1266 | |
| 1267 | /* Validate entire string as purely digits and at most one decimal dot. If not doing this here in advance, |
| 1268 | * parsing digits might stop early because of precision cut-off and miss validation of input data. */ |
| 1269 | point = NULL; |
| 1270 | for (p = str; *p; p++) { |
| 1271 | if (*p == '.') { |
| 1272 | if (point) |
| 1273 | return -EINVAL; |
| 1274 | point = p; |
Eric | 79f2903 | 2021-11-19 12:58:39 +0100 | [diff] [blame] | 1275 | } else if (!isdigit((unsigned char)*p)) |
Neels Hofmeyr | 87c3afb | 2020-09-30 21:47:47 +0000 | [diff] [blame] | 1276 | return -EINVAL; |
| 1277 | } |
| 1278 | |
| 1279 | /* Parse integer part if there is one. If the string starts with a point, there's nothing to parse for the |
| 1280 | * integer part. */ |
| 1281 | if (!point || point > str) { |
| 1282 | errno = 0; |
| 1283 | integer = strtoll(str, &endptr, 10); |
Harald Welte | cb11a60 | 2020-10-09 10:08:44 +0200 | [diff] [blame] | 1284 | if ((errno == ERANGE && (integer == LLONG_MAX || integer == LLONG_MIN)) |
Neels Hofmeyr | 87c3afb | 2020-09-30 21:47:47 +0000 | [diff] [blame] | 1285 | || (errno != 0 && integer == 0)) |
| 1286 | return -ERANGE; |
| 1287 | |
| 1288 | if ((point && endptr != point) |
| 1289 | || (!point && *endptr)) |
| 1290 | return -EINVAL; |
| 1291 | } |
| 1292 | |
| 1293 | /* Parse the fractional part if there is any, and if the precision is nonzero (if we even care about fractional |
| 1294 | * digits) */ |
| 1295 | if (precision && point && point[1] != '\0') { |
| 1296 | /* limit the number of digits parsed to 'precision'. |
| 1297 | * If 'precision' is larger than the 19 digits representable in int64_t, skip some, to pick up lower |
| 1298 | * magnitude digits. */ |
| 1299 | unsigned int skip_digits = (precision < 20) ? 0 : precision - 20; |
| 1300 | char decimal_str[precision + 1]; |
| 1301 | osmo_strlcpy(decimal_str, point+1, precision+1); |
| 1302 | |
| 1303 | /* fill with zeros to make exactly 'precision' digits */ |
| 1304 | for (i = strlen(decimal_str); i < precision; i++) |
| 1305 | decimal_str[i] = '0'; |
| 1306 | decimal_str[precision] = '\0'; |
| 1307 | |
| 1308 | for (i = 0; i < skip_digits; i++) { |
| 1309 | /* When skipping digits because precision > nr-of-digits-in-int64_t, they must be zero; |
| 1310 | * if there is a nonzero digit above the precision, it's -ERANGE. */ |
| 1311 | if (decimal_str[i] != '0') |
| 1312 | return -ERANGE; |
| 1313 | } |
| 1314 | errno = 0; |
| 1315 | decimal = strtoll(decimal_str + skip_digits, &endptr, 10); |
Harald Welte | cb11a60 | 2020-10-09 10:08:44 +0200 | [diff] [blame] | 1316 | if ((errno == ERANGE && (decimal == LLONG_MAX || decimal == LLONG_MIN)) |
Neels Hofmeyr | 87c3afb | 2020-09-30 21:47:47 +0000 | [diff] [blame] | 1317 | || (errno != 0 && decimal == 0)) |
| 1318 | return -ERANGE; |
| 1319 | |
| 1320 | if (*endptr) |
| 1321 | return -EINVAL; |
| 1322 | } |
| 1323 | |
| 1324 | if (precision > 18) { |
| 1325 | /* Special case of returning more digits than fit in int64_t range, e.g. |
| 1326 | * osmo_float_str_to_int("0.0000000012345678901234567", precision=25) -> 12345678901234567. */ |
| 1327 | precision_factor = 0; |
| 1328 | integer_max = 0; |
| 1329 | decimal_max = INT64_MAX; |
| 1330 | } else { |
| 1331 | /* Do not surpass the resulting int64_t range. Depending on the amount of precision, the integer part |
| 1332 | * and decimal part have specific ranges they must comply to. */ |
| 1333 | precision_factor = 1; |
| 1334 | for (i = 0; i < precision; i++) |
| 1335 | precision_factor *= 10; |
| 1336 | integer_max = INT64_MAX / precision_factor; |
| 1337 | if (integer == integer_max) |
| 1338 | decimal_max = INT64_MAX % precision_factor; |
| 1339 | else |
| 1340 | decimal_max = INT64_MAX; |
| 1341 | } |
| 1342 | |
| 1343 | if (integer > integer_max) |
| 1344 | return -ERANGE; |
| 1345 | if (decimal > decimal_max) |
| 1346 | return -ERANGE; |
| 1347 | |
| 1348 | *val = sign * (integer * precision_factor + decimal); |
| 1349 | return 0; |
| 1350 | } |
| 1351 | |
Neels Hofmeyr | 6d74498 | 2020-10-08 13:09:49 +0200 | [diff] [blame] | 1352 | /*! Convert an integer to a floating point string using a decimal quotient (fixed-point precision). |
Neels Hofmeyr | 87c3afb | 2020-09-30 21:47:47 +0000 | [diff] [blame] | 1353 | * For example, with precision = 3, convert -1230 to "-1.23". |
Neels Hofmeyr | 6d74498 | 2020-10-08 13:09:49 +0200 | [diff] [blame] | 1354 | * The usable range of digits is -INT64_MAX .. INT64_MAX -- note, not INT64_MIN! The value of INT64_MIN is excluded to |
| 1355 | * reduce implementation complexity. See also utils_test.c. |
| 1356 | * The advantage over using printf("%.6g") is guaranteed precision: float or double types may apply rounding in the |
| 1357 | * conversion result. osmo_float_str_to_int() and osmo_int_to_float_str_buf() guarantee true results when converting |
| 1358 | * back and forth between string and int. |
| 1359 | * The resulting string omits trailing zeros in the fractional part (like "%g" would) but never applies rounding. |
Neels Hofmeyr | 87c3afb | 2020-09-30 21:47:47 +0000 | [diff] [blame] | 1360 | * \param[out] buf Buffer to write string to. |
| 1361 | * \param[in] buflen sizeof(buf). |
| 1362 | * \param[in] val Value to convert to float. |
| 1363 | * \returns number of chars that would be written, like snprintf(). |
| 1364 | */ |
| 1365 | int osmo_int_to_float_str_buf(char *buf, size_t buflen, int64_t val, unsigned int precision) |
| 1366 | { |
| 1367 | struct osmo_strbuf sb = { .buf = buf, .len = buflen }; |
| 1368 | unsigned int i; |
| 1369 | unsigned int w; |
| 1370 | int64_t precision_factor; |
| 1371 | if (val < 0) { |
| 1372 | OSMO_STRBUF_PRINTF(sb, "-"); |
| 1373 | if (val == INT64_MIN) { |
| 1374 | OSMO_STRBUF_PRINTF(sb, "ERR"); |
| 1375 | return sb.chars_needed; |
| 1376 | } |
| 1377 | val = -val; |
| 1378 | } |
| 1379 | |
| 1380 | if (precision > 18) { |
| 1381 | /* Special case of returning more digits than fit in int64_t range, e.g. |
| 1382 | * osmo_int_to_float_str(12345678901234567, precision=25) -> "0.0000000012345678901234567". */ |
| 1383 | if (!val) { |
| 1384 | OSMO_STRBUF_PRINTF(sb, "0"); |
| 1385 | return sb.chars_needed; |
| 1386 | } |
| 1387 | OSMO_STRBUF_PRINTF(sb, "0."); |
| 1388 | for (i = 19; i < precision; i++) |
| 1389 | OSMO_STRBUF_PRINTF(sb, "0"); |
| 1390 | precision = 19; |
| 1391 | } else { |
| 1392 | precision_factor = 1; |
| 1393 | for (i = 0; i < precision; i++) |
| 1394 | precision_factor *= 10; |
| 1395 | |
| 1396 | OSMO_STRBUF_PRINTF(sb, "%" PRId64, val / precision_factor); |
| 1397 | val %= precision_factor; |
| 1398 | if (!val) |
| 1399 | return sb.chars_needed; |
| 1400 | OSMO_STRBUF_PRINTF(sb, "."); |
| 1401 | } |
| 1402 | |
| 1403 | /* print fractional part, skip trailing zeros */ |
| 1404 | w = precision; |
| 1405 | while (!(val % 10)) { |
| 1406 | val /= 10; |
| 1407 | w--; |
| 1408 | } |
| 1409 | OSMO_STRBUF_PRINTF(sb, "%0*" PRId64, w, val); |
| 1410 | return sb.chars_needed; |
| 1411 | } |
| 1412 | |
| 1413 | /*! Convert an integer with a factor of a million to a floating point string. |
| 1414 | * For example, convert -1230000 to "-1.23". |
| 1415 | * \param[in] ctx Talloc ctx to allocate string buffer from. |
| 1416 | * \param[in] val Value to convert to float. |
| 1417 | * \returns resulting string, dynamically allocated. |
| 1418 | */ |
| 1419 | char *osmo_int_to_float_str_c(void *ctx, int64_t val, unsigned int precision) |
| 1420 | { |
| 1421 | OSMO_NAME_C_IMPL(ctx, 16, "ERROR", osmo_int_to_float_str_buf, val, precision) |
| 1422 | } |
| 1423 | |
Neels Hofmeyr | 4777334 | 2021-09-05 18:48:31 +0200 | [diff] [blame] | 1424 | /*! Convert a string of a number to int64_t, including all common strtoll() validity checks. |
| 1425 | * It's not so trivial to call strtoll() and properly verify that the input string was indeed a valid number string. |
| 1426 | * \param[out] result Buffer for the resulting integer number, or NULL if the caller is only interested in the |
| 1427 | * validation result (returned rc). |
| 1428 | * \param[in] str The string to convert. |
| 1429 | * \param[in] base The integer base, i.e. 10 for decimal numbers or 16 for hexadecimal, as in strtoll(). |
| 1430 | * \param[in] min_val The smallest valid number expected in the string. |
| 1431 | * \param[in] max_val The largest valid number expected in the string. |
| 1432 | * \return 0 on success, -EOVERFLOW if the number in the string exceeds int64_t, -ENOTSUPP if the base is not supported, |
| 1433 | * -ERANGE if the converted number exceeds the range [min_val..max_val] but is still within int64_t range, -E2BIG if |
| 1434 | * surplus characters follow after the number, -EINVAL if the string does not contain a number. In case of -ERANGE and |
| 1435 | * -E2BIG, the converted number is still accurately returned in result. In case of -EOVERFLOW, the returned value is |
| 1436 | * clamped to INT64_MIN..INT64_MAX. |
| 1437 | */ |
| 1438 | int osmo_str_to_int64(int64_t *result, const char *str, int base, int64_t min_val, int64_t max_val) |
| 1439 | { |
| 1440 | long long int val; |
| 1441 | char *endptr; |
| 1442 | if (result) |
| 1443 | *result = 0; |
| 1444 | if (!str || !*str) |
| 1445 | return -EINVAL; |
| 1446 | errno = 0; |
| 1447 | val = strtoll(str, &endptr, base); |
| 1448 | /* In case the number string exceeds long long int range, strtoll() clamps the returned value to LLONG_MIN or |
| 1449 | * LLONG_MAX. Make sure of the same here with respect to int64_t. */ |
| 1450 | if (val < INT64_MIN) { |
| 1451 | if (result) |
| 1452 | *result = INT64_MIN; |
| 1453 | return -ERANGE; |
| 1454 | } |
| 1455 | if (val > INT64_MAX) { |
| 1456 | if (result) |
| 1457 | *result = INT64_MAX; |
| 1458 | return -ERANGE; |
| 1459 | } |
| 1460 | if (result) |
| 1461 | *result = (int64_t)val; |
| 1462 | switch (errno) { |
| 1463 | case 0: |
| 1464 | break; |
| 1465 | case ERANGE: |
| 1466 | return -EOVERFLOW; |
| 1467 | default: |
| 1468 | case EINVAL: |
| 1469 | return -ENOTSUP; |
| 1470 | } |
| 1471 | if (!endptr || *endptr) { |
| 1472 | /* No chars were converted */ |
| 1473 | if (endptr == str) |
| 1474 | return -EINVAL; |
| 1475 | /* Or there are surplus chars after the converted number */ |
| 1476 | return -E2BIG; |
| 1477 | } |
| 1478 | if (val < min_val || val > max_val) |
| 1479 | return -ERANGE; |
| 1480 | return 0; |
| 1481 | } |
| 1482 | |
| 1483 | /*! Convert a string of a number to int, including all common strtoll() validity checks. |
| 1484 | * Same as osmo_str_to_int64() but using the plain int data type. |
| 1485 | * \param[out] result Buffer for the resulting integer number, or NULL if the caller is only interested in the |
| 1486 | * validation result (returned rc). |
| 1487 | * \param[in] str The string to convert. |
| 1488 | * \param[in] base The integer base, i.e. 10 for decimal numbers or 16 for hexadecimal, as in strtoll(). |
| 1489 | * \param[in] min_val The smallest valid number expected in the string. |
| 1490 | * \param[in] max_val The largest valid number expected in the string. |
| 1491 | * \return 0 on success, -EOVERFLOW if the number in the string exceeds int range, -ENOTSUPP if the base is not supported, |
| 1492 | * -ERANGE if the converted number exceeds the range [min_val..max_val] but is still within int range, -E2BIG if |
| 1493 | * surplus characters follow after the number, -EINVAL if the string does not contain a number. In case of -ERANGE and |
| 1494 | * -E2BIG, the converted number is still accurately returned in result. In case of -EOVERFLOW, the returned value is |
| 1495 | * clamped to INT_MIN..INT_MAX. |
| 1496 | */ |
| 1497 | int osmo_str_to_int(int *result, const char *str, int base, int min_val, int max_val) |
| 1498 | { |
| 1499 | int64_t val; |
| 1500 | int rc = osmo_str_to_int64(&val, str, base, min_val, max_val); |
| 1501 | /* In case the number string exceeds long long int range, strtoll() clamps the returned value to LLONG_MIN or |
| 1502 | * LLONG_MAX. Make sure of the same here with respect to int. */ |
| 1503 | if (val < INT_MIN) { |
| 1504 | if (result) |
| 1505 | *result = INT_MIN; |
| 1506 | return -EOVERFLOW; |
| 1507 | } |
| 1508 | if (val > INT_MAX) { |
| 1509 | if (result) |
| 1510 | *result = INT_MAX; |
| 1511 | return -EOVERFLOW; |
| 1512 | } |
| 1513 | if (result) |
| 1514 | *result = (int)val; |
| 1515 | return rc; |
| 1516 | } |
| 1517 | |
Vadim Yanitskiy | c549719 | 2021-06-07 16:30:28 +0200 | [diff] [blame] | 1518 | /*! Replace a string using talloc and release its prior content (if any). |
| 1519 | * This is a format string capable equivalent of osmo_talloc_replace_string(). |
| 1520 | * \param[in] ctx Talloc context to use for allocation. |
| 1521 | * \param[out] dst Pointer to string, will be updated with ptr to new string. |
| 1522 | * \param[in] fmt Format string that will be copied to newly allocated string. */ |
| 1523 | void osmo_talloc_replace_string_fmt(void *ctx, char **dst, const char *fmt, ...) |
| 1524 | { |
| 1525 | char *name = NULL; |
| 1526 | |
| 1527 | if (fmt != NULL) { |
| 1528 | va_list ap; |
| 1529 | |
| 1530 | va_start(ap, fmt); |
| 1531 | name = talloc_vasprintf(ctx, fmt, ap); |
| 1532 | va_end(ap); |
| 1533 | } |
| 1534 | |
| 1535 | talloc_free(*dst); |
| 1536 | *dst = name; |
| 1537 | } |
| 1538 | |
Neels Hofmeyr | 0aeda1b | 2017-01-13 14:16:02 +0100 | [diff] [blame] | 1539 | /*! @} */ |