blob: c4e6f5fcf75cb14323f3f95c78f4d3288170b298 [file] [log] [blame]
Sylvain Munaut12ba7782014-06-16 10:13:40 +02001#pragma once
Harald Welteec8b4502010-02-20 20:34:29 +01002
Neels Hofmeyr4335bad2017-10-07 04:39:14 +02003#include <stdbool.h>
Vadim Yanitskiy55944302018-09-05 02:58:03 +07004#include <stdint.h>
5#include <stdio.h>
Neels Hofmeyr4335bad2017-10-07 04:39:14 +02006
Harald Welteb8add362013-07-06 23:49:41 +02007#include <osmocom/core/backtrace.h>
Harald Weltef3c7e852014-08-20 22:50:47 +02008#include <osmocom/core/talloc.h>
Harald Welte459a1802018-06-28 09:24:17 +02009#include <osmocom/core/panic.h>
Neels Hofmeyr7c749892018-09-07 03:01:38 +020010#include <osmocom/core/defs.h>
Harald Welteb8add362013-07-06 23:49:41 +020011
Harald Welte8598f182011-08-17 14:19:27 +020012/*! \defgroup utils General-purpose utility functions
13 * @{
Neels Hofmeyr17518fe2017-06-20 04:35:06 +020014 * \file utils.h */
Harald Welte8598f182011-08-17 14:19:27 +020015
Neels Hofmeyr87e45502017-06-20 00:17:59 +020016/*! Determine number of elements in an array of static size */
Kévin Redond1e220f2019-06-13 13:41:00 +020017#ifndef ARRAY_SIZE
Harald Welteec8b4502010-02-20 20:34:29 +010018#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
Kévin Redond1e220f2019-06-13 13:41:00 +020019#endif
Neels Hofmeyr87e45502017-06-20 00:17:59 +020020/*! Return the maximum of two specified values */
Holger Hans Peter Freyther08b28622012-08-15 17:02:59 +020021#define OSMO_MAX(a, b) ((a) >= (b) ? (a) : (b))
Neels Hofmeyr87e45502017-06-20 00:17:59 +020022/*! Return the minimum of two specified values */
Holger Hans Peter Freyther08b28622012-08-15 17:02:59 +020023#define OSMO_MIN(a, b) ((a) >= (b) ? (b) : (a))
Neels Hofmeyr002a51d2019-10-30 04:37:47 +010024/*! Return a typical cmp result for comparable entities a and b. */
25#define OSMO_CMP(a, b) ((a) < (b)? -1 : ((a) > (b)? 1 : 0))
Neels Hofmeyrdc75b112017-12-09 05:51:42 +010026/*! Stringify the name of a macro x, e.g. an FSM event name.
27 * Note: if nested within another preprocessor macro, this will
28 * stringify the value of x instead of its name. */
Neels Hofmeyr18080962016-12-16 13:43:54 +010029#define OSMO_STRINGIFY(x) #x
Neels Hofmeyr84ea2e02017-12-09 05:53:18 +010030/*! Stringify the value of a macro x, e.g. a port number. */
31#define OSMO_STRINGIFY_VAL(x) OSMO_STRINGIFY(x)
Neels Hofmeyr87e45502017-06-20 00:17:59 +020032/*! Make a value_string entry from an enum value name */
Neels Hofmeyr8a5d60b2017-03-09 23:01:37 +010033#define OSMO_VALUE_STRING(x) { x, #x }
Neels Hofmeyr87e45502017-06-20 00:17:59 +020034/*! Number of bytes necessary to store given BITS */
Maxdd75bac2017-06-13 15:07:01 +020035#define OSMO_BYTES_FOR_BITS(BITS) ((BITS + 8 - 1) / 8)
Harald Welteec8b4502010-02-20 20:34:29 +010036
Max18c014d2018-01-30 14:33:01 +010037/*! Copy a C-string into a sized buffer using sizeof to detect buffer's size */
38#define OSMO_STRLCPY_ARRAY(array, src) osmo_strlcpy(array, src, sizeof(array))
39
Neels Hofmeyr87e45502017-06-20 00:17:59 +020040/*! A mapping between human-readable string and numeric value */
Harald Welted284cd92010-03-01 21:58:31 +010041struct value_string {
Neels Hofmeyr87e45502017-06-20 00:17:59 +020042 unsigned int value; /*!< numeric value */
43 const char *str; /*!< human-readable string */
Harald Welted284cd92010-03-01 21:58:31 +010044};
45
46const char *get_value_string(const struct value_string *vs, uint32_t val);
Neels Hofmeyr8d6dcd92016-06-06 18:05:23 +020047const char *get_value_string_or_null(const struct value_string *vs,
48 uint32_t val);
Harald Weltebd598e32011-08-16 23:26:52 +020049
Harald Welted284cd92010-03-01 21:58:31 +010050int get_string_value(const struct value_string *vs, const char *str);
51
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +020052char osmo_bcd2char(uint8_t bcd);
Kévin Redon77021c72019-06-13 18:12:33 +020053/* only works for numbers in ASCII */
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +020054uint8_t osmo_char2bcd(char c);
Harald Welted284cd92010-03-01 21:58:31 +010055
Neels Hofmeyr7079e692018-12-05 21:02:36 +010056int osmo_bcd2str(char *dst, size_t dst_size, const uint8_t *bcd, int start_nibble, int end_nibble, bool allow_hex);
57
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +020058int osmo_hexparse(const char *str, uint8_t *b, int max_len);
Harald Weltebd598e32011-08-16 23:26:52 +020059
Harald Welte4a62eda2019-03-18 18:27:00 +010060char *osmo_ubit_dump_buf(char *buf, size_t buf_len, const uint8_t *bits, unsigned int len);
Pablo Neira Ayuso87f7b252011-05-07 12:43:08 +020061char *osmo_ubit_dump(const uint8_t *bits, unsigned int len);
Harald Welte8598f182011-08-17 14:19:27 +020062char *osmo_hexdump(const unsigned char *buf, int len);
Harald Welte179f3572019-03-18 18:38:47 +010063char *osmo_hexdump_c(const void *ctx, const unsigned char *buf, int len);
Sylvain Munautff23d242011-11-10 23:03:18 +010064char *osmo_hexdump_nospc(const unsigned char *buf, int len);
Harald Welte179f3572019-03-18 18:38:47 +010065char *osmo_hexdump_nospc_c(const void *ctx, const unsigned char *buf, int len);
Neels Hofmeyr0423b612019-01-14 23:32:53 +010066const char *osmo_hexdump_buf(char *out_buf, size_t out_buf_size, const unsigned char *buf, int len, const char *delim,
67 bool delim_after_last);
68
Sylvain Munaut4cfbae82011-11-13 23:04:00 +010069char *osmo_osmo_hexdump_nospc(const unsigned char *buf, int len) __attribute__((__deprecated__));
Harald Welte3eba9912010-07-30 10:37:29 +020070
Holger Hans Peter Freyther0f40ae12015-04-13 09:21:05 +020071#define osmo_static_assert(exp, name) typedef int dummy##name [(exp) ? 1 : -1] __attribute__((__unused__));
Holger Hans Peter Freyther52c07ca2011-01-16 17:37:27 +010072
Neels Hofmeyr7c749892018-09-07 03:01:38 +020073void osmo_str2lower(char *out, const char *in)
74 OSMO_DEPRECATED("Use osmo_str_tolower() or osmo_str_tolower_buf() instead,"
75 " to properly check target memory bounds");
76void osmo_str2upper(char *out, const char *in)
77 OSMO_DEPRECATED("Use osmo_str_toupper() or osmo_str_toupper_buf() instead,"
78 " to properly check target memory bounds");
79
80size_t osmo_str_tolower_buf(char *dest, size_t dest_len, const char *src);
81const char *osmo_str_tolower(const char *src);
Harald Welte179f3572019-03-18 18:38:47 +010082char *osmo_str_tolower_c(const void *ctx, const char *src);
Neels Hofmeyr7c749892018-09-07 03:01:38 +020083
84size_t osmo_str_toupper_buf(char *dest, size_t dest_len, const char *src);
85const char *osmo_str_toupper(const char *src);
Harald Welte179f3572019-03-18 18:38:47 +010086char *osmo_str_toupper_c(const void *ctx, const char *src);
Harald Welte28222962011-02-18 20:37:04 +010087
Pablo Neira Ayuso3abad6a2011-03-28 19:24:22 +020088#define OSMO_SNPRINTF_RET(ret, rem, offset, len) \
89do { \
90 len += ret; \
91 if (ret > rem) \
92 ret = rem; \
93 offset += ret; \
94 rem -= ret; \
95} while (0)
96
Kévin Redon77021c72019-06-13 18:12:33 +020097/*! Helper macro to terminate when an assertion fails
Harald Welte2d2e2cc2016-04-25 12:11:20 +020098 * \param[in] exp Predicate to verify
99 * This function will generate a backtrace and terminate the program if
100 * the predicate evaluates to false (0).
101 */
Katerina Barone-Adesi008e53b2013-03-03 10:36:52 +0000102#define OSMO_ASSERT(exp) \
Vadim Yanitskiye2425482019-07-09 13:56:24 +0700103 if (!(exp)) { \
Neels Hofmeyr983dcb92018-08-20 12:33:22 +0200104 osmo_panic("Assert failed %s %s:%d\n", #exp, __FILE__, __LINE__); \
Vadim Yanitskiye2425482019-07-09 13:56:24 +0700105 }
Katerina Barone-Adesi008e53b2013-03-03 10:36:52 +0000106
Harald Welte2d2e2cc2016-04-25 12:11:20 +0200107/*! duplicate a string using talloc and release its prior content (if any)
108 * \param[in] ctx Talloc context to use for allocation
109 * \param[out] dst pointer to string, will be updated with ptr to new string
Kévin Redon77021c72019-06-13 18:12:33 +0200110 * \param[in] newstr String that will be copied to newly allocated string */
Harald Welte881dcaf2016-07-28 08:02:48 +0200111static inline void osmo_talloc_replace_string(void *ctx, char **dst, const char *newstr)
Harald Weltef3c7e852014-08-20 22:50:47 +0200112{
113 if (*dst)
114 talloc_free(*dst);
115 *dst = talloc_strdup(ctx, newstr);
116}
Katerina Barone-Adesi008e53b2013-03-03 10:36:52 +0000117
Neels Hofmeyrabdd7a22017-10-19 02:40:01 +0200118/*! Append to a string and re-/allocate if necessary.
119 * \param[in] ctx Talloc context to use for initial allocation.
120 * \param[in,out] dest char* to re-/allocate and append to.
121 * \param[in] fmt printf-like string format.
122 * \param[in] args Arguments for fmt.
123 *
124 * \a dest may be passed in NULL, or a string previously allocated by talloc.
125 * If an existing string is passed in, it will remain associated with whichever
126 * ctx it was allocated before, regardless whether it matches \a ctx or not.
127 */
128#define osmo_talloc_asprintf(ctx, dest, fmt, args ...) \
129 do { \
130 if (!dest) \
131 dest = talloc_asprintf(ctx, fmt, ## args); \
132 else \
133 dest = talloc_asprintf_append((char*)dest, fmt, ## args); \
134 } while (0)
135
Harald Welte9709b2e2016-04-25 18:47:53 +0200136int osmo_constant_time_cmp(const uint8_t *exp, const uint8_t *rel, const int count);
137uint64_t osmo_decode_big_endian(const uint8_t *data, size_t data_len);
138uint8_t *osmo_encode_big_endian(uint64_t value, size_t data_len);
139
Harald Welteaeecc482016-11-26 10:41:40 +0100140size_t osmo_strlcpy(char *dst, const char *src, size_t siz);
141
Neels Hofmeyr4335bad2017-10-07 04:39:14 +0200142bool osmo_is_hexstr(const char *str, int min_digits, int max_digits,
143 bool require_even);
144
Harald Weltefebe83c2017-10-03 17:41:59 +0800145bool osmo_identifier_valid(const char *str);
Neels Hofmeyr937ddea2017-12-16 00:46:50 +0100146bool osmo_separated_identifiers_valid(const char *str, const char *sep_chars);
Neels Hofmeyrb480b742019-04-11 06:58:44 +0200147void osmo_identifier_sanitize_buf(char *str, const char *sep_chars, char replace_with);
Harald Weltefebe83c2017-10-03 17:41:59 +0800148
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100149const char *osmo_escape_str(const char *str, int len);
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100150char *osmo_escape_str_buf2(char *buf, size_t bufsize, const char *str, int in_len);
151const char *osmo_escape_str_buf(const char *str, int in_len, char *buf, size_t bufsize);
Harald Welte179f3572019-03-18 18:38:47 +0100152char *osmo_escape_str_c(const void *ctx, const char *str, int in_len);
Neels Hofmeyr04eb56f2018-04-09 00:41:28 +0200153const char *osmo_quote_str(const char *str, int in_len);
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100154char *osmo_quote_str_buf2(char *buf, size_t bufsize, const char *str, int in_len);
155const char *osmo_quote_str_buf(const char *str, int in_len, char *buf, size_t bufsize);
Harald Welte179f3572019-03-18 18:38:47 +0100156char *osmo_quote_str_c(const void *ctx, const char *str, int in_len);
Neels Hofmeyr9910bbc2017-12-16 00:54:52 +0100157
Neels Hofmeyrecef7ec2019-03-05 16:42:50 +0100158int osmo_print_n(char *buf, size_t bufsize, const char *str, size_t n);
159
Harald Welte15a5f8d2018-06-06 16:58:17 +0200160uint32_t osmo_isqrt32(uint32_t x);
161
Vadim Yanitskiyd9fc6042019-06-12 15:49:03 +0700162char osmo_luhn(const char* in, int in_len);
Oliver Smith894be2d2019-01-11 13:13:37 +0100163
Neels Hofmeyr2cbe25f2019-02-11 20:32:06 +0100164/*! State for OSMO_STRBUF_APPEND() and OSMO_STRBUF_PRINTF(). See there for examples. */
165struct osmo_strbuf {
166 /*! Point to the start of a string buffer. */
167 char *buf;
168 /*! Total sizeof() the buffer buf points at. */
169 size_t len;
170 /*! Current writing position in buf (end of the string written so far). */
171 char *pos;
172 /*! After all OSMO_STRBUF_APPEND operations, reflects the total number of characters that would be written had
173 * buf been large enough. Like snprintf()'s return value, this does not include the terminating nul character.
174 * Hence, to allocate an adequately sized buffer, add 1 to this number. */
175 size_t chars_needed;
176};
177
178/*! Append a string to a buffer, as printed by an snprintf()-like function and with similar bounds checking.
179 * Make sure to never write past the end of the buffer, and collect the total size that would be needed.
180 *
181 * // an example function implementation to append: write N spaces.
182 * int print_spaces(char *dst, size_t dst_len, int n)
183 * {
184 * int i;
185 * if (n < 0)
186 * return -EINVAL;
187 * for (i = 0; i < n && i < dst_len; i++)
188 * dst[i] = ' ';
189 * if (dst_len)
190 * dst[OSMO_MIN(dst_len - 1, n)] = '\0';
191 * // return the n that we would have liked to write if space were available:
192 * return n;
193 * }
194 *
195 * // append above spaces as well as an snprintf()
196 * void strbuf_example()
197 * {
198 * char buf[23];
199 * struct osmo_strbuf sb = { .buf = buf, .len = sizeof(buf) };
200 *
201 * OSMO_STRBUF_APPEND(sb, print_spaces, 5);
202 * OSMO_STRBUF_APPEND(sb, snprintf, "The answer is %d but what is the question?", 42);
203 * OSMO_STRBUF_APPEND(sb, print_spaces, 423423);
204 *
205 * printf("%s\n", buf);
206 * printf("would have needed %zu bytes\n", sb.chars_needed);
207 * }
208 *
209 * \param[inout] STRBUF A struct osmo_strbuf instance.
210 * \param[in] func A function with a signature of int func(char *dst, size_t dst_len [, args]) with semantics like
211 * snprintf().
212 * \param[in] args Arguments passed to func, if any.
213 */
214#define OSMO_STRBUF_APPEND(STRBUF, func, args...) do { \
215 if (!(STRBUF).pos) \
216 (STRBUF).pos = (STRBUF).buf; \
Neels Hofmeyr8531d662019-04-11 07:16:02 +0200217 size_t _sb_remain = (STRBUF).buf ? (STRBUF).len - ((STRBUF).pos - (STRBUF).buf) : 0; \
218 int _sb_l = func((STRBUF).pos, _sb_remain, ##args); \
219 if (_sb_l < 0 || _sb_l > _sb_remain) \
Neels Hofmeyr2cbe25f2019-02-11 20:32:06 +0100220 (STRBUF).pos = (STRBUF).buf + (STRBUF).len; \
Neels Hofmeyr8531d662019-04-11 07:16:02 +0200221 else if ((STRBUF).pos) \
222 (STRBUF).pos += _sb_l; \
223 if (_sb_l > 0) \
224 (STRBUF).chars_needed += _sb_l; \
Neels Hofmeyr2cbe25f2019-02-11 20:32:06 +0100225 } while(0)
226
227/*! Shortcut for OSMO_STRBUF_APPEND() invocation using snprintf().
228 *
229 * int strbuf_example2(char *buf, size_t buflen)
230 * {
231 * int i;
232 * struct osmo_strbuf sb = { .buf = buf, .len = buflen };
233 *
234 * OSMO_STRBUF_PRINTF(sb, "T minus");
235 * for (i = 10; i; i--)
236 * OSMO_STRBUF_PRINTF(sb, " %d", i);
237 * OSMO_STRBUF_PRINTF(sb, " ... Lift off!");
238 *
239 * return sb.chars_needed;
240 * }
241 *
242 * \param[inout] STRBUF A struct osmo_strbuf instance.
243 * \param[in] fmt Format string passed to snprintf.
244 * \param[in] args Additional arguments passed to snprintf, if any.
245 */
246#define OSMO_STRBUF_PRINTF(STRBUF, fmt, args...) \
247 OSMO_STRBUF_APPEND(STRBUF, snprintf, fmt, ##args)
248
Neels Hofmeyr8531d662019-04-11 07:16:02 +0200249/*! Like OSMO_STRBUF_APPEND(), but for function signatures that return the char* buffer instead of a length.
250 * When using this function, the final STRBUF.chars_needed may not reflect the actual number of characters needed, since
251 * that number cannot be obtained from this kind of function signature.
252 * \param[inout] STRBUF A struct osmo_strbuf instance.
253 * \param[in] func A function with a signature of char *func(char *dst, size_t dst_len [, args]) where
254 * the returned string is always written to dst.
255 * \param[in] args Arguments passed to func, if any.
256 */
257#define OSMO_STRBUF_APPEND_NOLEN(STRBUF, func, args...) do { \
258 if (!(STRBUF).pos) \
259 (STRBUF).pos = (STRBUF).buf; \
260 size_t _sb_remain = (STRBUF).buf ? (STRBUF).len - ((STRBUF).pos - (STRBUF).buf) : 0; \
261 if (_sb_remain) { \
262 func((STRBUF).pos, _sb_remain, ##args); \
263 } \
264 size_t _sb_l = (STRBUF).pos ? strnlen((STRBUF).pos, _sb_remain) : 0; \
265 if (_sb_l > _sb_remain) \
266 (STRBUF).pos = (STRBUF).buf + (STRBUF).len; \
267 else if ((STRBUF).pos) \
268 (STRBUF).pos += _sb_l; \
269 (STRBUF).chars_needed += _sb_l; \
270 } while(0)
271
Neels Hofmeyrd79ccc62019-03-07 23:08:40 +0100272bool osmo_str_startswith(const char *str, const char *startswith_str);
273
Sylvain Munautdca7d2c2012-04-18 21:53:23 +0200274/*! @} */