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