libosmocore  1.0.1.85-9f28
Osmocom core library
 All Data Structures Files Functions Variables Typedefs Enumerations Enumerator Macros Modules Pages
General-purpose utility functions

various utility routines More...

Files

file  defs.h
 General definitions that are meant to be included from header files.
 
file  panic.h
 
file  utils.h
 
file  macaddr.c
 MAC address utility routines.
 
file  panic.c
 Routines for panic handling.
 
file  plugin.c
 Routines for loading and managing shared library plug-ins.
 
file  strrb.c
 Ringbuffer implementation, tailored for logging.
 

Data Structures

struct  value_string
 A mapping between human-readable string and numeric value. More...
 
struct  osmo_strbuf
 State for OSMO_STRBUF_APPEND() and OSMO_STRBUF_PRINTF(). More...
 

Macros

#define OSMO_GNUC_PREREQ(maj, min)   0
 Check for gcc and version. More...
 
#define OSMO_DEPRECATED(text)
 Set the deprecated attribute with a message. More...
 
#define OSMO_DEPRECATED_OUTSIDE_LIBOSMOCORE   OSMO_DEPRECATED("For internal use inside libosmocore only.")
 
#define ARRAY_SIZE(x)   (sizeof(x) / sizeof((x)[0]))
 Determine number of elements in an array of static size. More...
 
#define OSMO_MAX(a, b)   ((a) >= (b) ? (a) : (b))
 Return the maximum of two specified values. More...
 
#define OSMO_MIN(a, b)   ((a) >= (b) ? (b) : (a))
 Return the minimum of two specified values. More...
 
#define OSMO_STRINGIFY(x)   #x
 Stringify the name of a macro x, e.g. More...
 
#define OSMO_STRINGIFY_VAL(x)   OSMO_STRINGIFY(x)
 Stringify the value of a macro x, e.g. More...
 
#define OSMO_VALUE_STRING(x)   { x, #x }
 Make a value_string entry from an enum value name. More...
 
#define OSMO_BYTES_FOR_BITS(BITS)   ((BITS + 8 - 1) / 8)
 Number of bytes necessary to store given BITS. More...
 
#define OSMO_STRLCPY_ARRAY(array, src)   osmo_strlcpy(array, src, sizeof(array))
 Copy a C-string into a sized buffer using sizeof to detect buffer's size. More...
 
#define osmo_static_assert(exp, name)   typedef int dummy##name [(exp) ? 1 : -1] __attribute__((__unused__));
 
#define OSMO_SNPRINTF_RET(ret, rem, offset, len)
 
#define OSMO_ASSERT(exp)
 Helper macro to terminate when an assertion failes. More...
 
#define osmo_talloc_asprintf(ctx, dest, fmt, args...)
 Append to a string and re-/allocate if necessary. More...
 
#define OSMO_STRBUF_APPEND(STRBUF, func, args...)
 Append a string to a buffer, as printed by an snprintf()-like function and with similar bounds checking. More...
 
#define OSMO_STRBUF_PRINTF(STRBUF, fmt, args...)   OSMO_STRBUF_APPEND(STRBUF, snprintf, fmt, ##args)
 Shortcut for OSMO_STRBUF_APPEND() invocation using snprintf(). More...
 

Typedefs

typedef void(* osmo_panic_handler_t )(const char *fmt, va_list args)
 panic handler callback function type More...
 

Functions

void osmo_panic (const char *fmt,...)
 Terminate the current program with a panic. More...
 
void osmo_set_panic_handler (osmo_panic_handler_t h)
 Set the panic handler. More...
 
const char * get_value_string (const struct value_string *vs, uint32_t val)
 get human-readable string for given value More...
 
const char * get_value_string_or_null (const struct value_string *vs, uint32_t val)
 get human-readable string or NULL for given value More...
 
int get_string_value (const struct value_string *vs, const char *str)
 get numeric value for given human-readable string More...
 
char osmo_bcd2char (uint8_t bcd)
 Convert BCD-encoded digit into printable character. More...
 
uint8_t osmo_char2bcd (char c)
 Convert number in ASCII to BCD value. More...
 
int osmo_bcd2str (char *dst, size_t dst_size, const uint8_t *bcd, int start_nibble, int end_nibble, bool allow_hex)
 Convert BCD to string. More...
 
int osmo_hexparse (const char *str, uint8_t *b, int max_len)
 Parse a string containing hexadecimal digits. More...
 
char * osmo_ubit_dump (const uint8_t *bits, unsigned int len)
 Convert a sequence of unpacked bits to ASCII string. More...
 
char * osmo_hexdump (const unsigned char *buf, int len)
 Convert binary sequence to hexadecimal ASCII string. More...
 
char * osmo_hexdump_nospc (const unsigned char *buf, int len)
 Convert binary sequence to hexadecimal ASCII string. More...
 
const char * osmo_hexdump_buf (char *out_buf, size_t out_buf_size, const unsigned char *buf, int len, const char *delim, bool delim_after_last)
 Convert binary sequence to hexadecimal ASCII string. More...
 
char * osmo_osmo_hexdump_nospc (const unsigned char *buf, int len) __attribute__((__deprecated__))
 
void osmo_str2lower (char *out, const char *in) OSMO_DEPRECATED("Use osmo_str_tolower() or osmo_str_tolower_buf() instead
 
void osmo_str2upper (char *out, const char *in) OSMO_DEPRECATED("Use osmo_str_toupper() or osmo_str_toupper_buf() instead
 
size_t osmo_str_tolower_buf (char *dest, size_t dest_len, const char *src)
 Convert a string to lowercase, while checking buffer size boundaries. More...
 
const char * osmo_str_tolower (const char *src)
 Convert a string to lowercase, using a static buffer. More...
 
size_t osmo_str_toupper_buf (char *dest, size_t dest_len, const char *src)
 Convert a string to uppercase, while checking buffer size boundaries. More...
 
const char * osmo_str_toupper (const char *src)
 Convert a string to uppercase, using a static buffer. More...
 
static void osmo_talloc_replace_string (void *ctx, char **dst, const char *newstr)
 duplicate a string using talloc and release its prior content (if any) More...
 
int osmo_constant_time_cmp (const uint8_t *exp, const uint8_t *rel, const int count)
 Wishful thinking to generate a constant time compare. More...
 
uint64_t osmo_decode_big_endian (const uint8_t *data, size_t data_len)
 Generic retrieval of 1..8 bytes as big-endian uint64_t. More...
 
uint8_t * osmo_encode_big_endian (uint64_t value, size_t data_len)
 Generic big-endian encoding of big endian number up to 64bit. More...
 
size_t osmo_strlcpy (char *dst, const char *src, size_t siz)
 Copy a C-string into a sized buffer. More...
 
bool osmo_is_hexstr (const char *str, int min_digits, int max_digits, bool require_even)
 Validate that a given string is a hex string within given size limits. More...
 
bool osmo_identifier_valid (const char *str)
 Determine if a given identifier is valid, i.e. More...
 
bool osmo_separated_identifiers_valid (const char *str, const char *sep_chars)
 Determine if a given identifier is valid, i.e. More...
 
const char * osmo_escape_str (const char *str, int in_len)
 Return the string with all non-printable characters escaped. More...
 
const char * osmo_escape_str_buf (const char *str, int in_len, char *buf, size_t bufsize)
 Return the string with all non-printable characters escaped. More...
 
const char * osmo_quote_str (const char *str, int in_len)
 Like osmo_quote_str_buf() but returns the result in a static buffer. More...
 
const char * osmo_quote_str_buf (const char *str, int in_len, char *buf, size_t bufsize)
 Like osmo_escape_str(), but returns double-quotes around a string, or "NULL" for a NULL string. More...
 
uint32_t osmo_isqrt32 (uint32_t x)
 perform an integer square root operation on unsigned 32bit integer. More...
 
const char osmo_luhn (const char *in, int in_len)
 Calculate the Luhn checksum (as used for IMEIs). More...
 
int osmo_macaddr_parse (uint8_t *out, const char *in)
 Parse a MAC address from human-readable notation This function parses an ethernet MAC address in the commonly-used hex/colon notation (00:00:00:00:00:00) and generates the binary representation from it. More...
 
int osmo_get_macaddr (uint8_t *mac_out, const char *dev_name)
 Obtain the MAC address of a given network device. More...
 
static void osmo_panic_default (const char *fmt, va_list args)
 
int osmo_plugin_load_all (const char *directory)
 
struct osmo_strrbosmo_strrb_create (TALLOC_CTX *ctx, size_t rb_size)
 Create an empty, initialized osmo_strrb. More...
 
bool osmo_strrb_is_empty (const struct osmo_strrb *rb)
 Check if an osmo_strrb is empty. More...
 
const char * osmo_strrb_get_nth (const struct osmo_strrb *rb, unsigned int string_index)
 Return a pointer to the Nth string in the osmo_strrb. More...
 
bool _osmo_strrb_is_bufindex_valid (const struct osmo_strrb *rb, unsigned int bufi)
 
size_t osmo_strrb_elements (const struct osmo_strrb *rb)
 Count the number of log messages in an osmo_strrb. More...
 
int osmo_strrb_add (struct osmo_strrb *rb, const char *data)
 Add a string to the osmo_strrb. More...
 
char alias ("osmo_hexdump_nospc")))
 

Variables

void to properly check target
memory 
bounds
 
static osmo_panic_handler_t osmo_panic_handler = (void*)0
 
static char namebuf [255]
 
static char hexd_buff [4096]
 
static const char hex_chars [] = "0123456789abcdef"
 

Detailed Description

various utility routines

Macro Definition Documentation

#define ARRAY_SIZE (   x)    (sizeof(x) / sizeof((x)[0]))
#define OSMO_ASSERT (   exp)
Value:
if (!(exp)) { \
osmo_panic("Assert failed %s %s:%d\n", #exp, __FILE__, __LINE__); \
}
void osmo_panic(const char *fmt,...) __attribute__((noreturn))
Terminate the current program with a panic.
Definition: panic.c:75

Helper macro to terminate when an assertion failes.

Parameters
[in]expPredicate to verify This function will generate a backtrace and terminate the program if the predicate evaluates to false (0).

Referenced by _osmo_fsm_inst_dispatch(), _osmo_tdef_fsm_inst_state_chg(), assert_loginfo(), log_parse_category_mask(), mangle_identifier_ifneeded(), map_subsys(), msgb_printf(), osmo_encode_big_endian(), osmo_stats_reporter_alloc(), osmo_tdef_get(), osmo_tdef_get_state_timeout(), and rate_ctr_group_desc_mangle().

#define OSMO_BYTES_FOR_BITS (   BITS)    ((BITS + 8 - 1) / 8)

Number of bytes necessary to store given BITS.

#define OSMO_DEPRECATED (   text)

Set the deprecated attribute with a message.

#define OSMO_DEPRECATED_OUTSIDE_LIBOSMOCORE   OSMO_DEPRECATED("For internal use inside libosmocore only.")
#define OSMO_GNUC_PREREQ (   maj,
  min 
)    0

Check for gcc and version.

Note
Albeit glibc provides a features.h file that contains a similar definition (__GNUC_PREREQ), this definition has been copied from there to have it available with other libraries, too.
Returns
!= 0 iff gcc is used and it's version is at least maj.min.
#define OSMO_MAX (   a,
 
)    ((a) >= (b) ? (a) : (b))

Return the maximum of two specified values.

Referenced by osmo_bcd2str().

#define OSMO_MIN (   a,
 
)    ((a) >= (b) ? (b) : (a))

Return the minimum of two specified values.

Referenced by osmo_quote_str_buf().

#define OSMO_SNPRINTF_RET (   ret,
  rem,
  offset,
  len 
)
Value:
do { \
len += ret; \
if (ret > rem) \
ret = rem; \
offset += ret; \
rem -= ret; \
} while (0)
if(vty->type==VTY_SHELL_SERV)
static size_t len(const char *str)

Referenced by _output().

#define osmo_static_assert (   exp,
  name 
)    typedef int dummy##name [(exp) ? 1 : -1] __attribute__((__unused__));

Referenced by msgb_alloc_headroom().

#define OSMO_STRBUF_APPEND (   STRBUF,
  func,
  args... 
)
Value:
do { \
if (!(STRBUF).pos) \
(STRBUF).pos = (STRBUF).buf; \
size_t remain = (STRBUF).buf ? (STRBUF).len - ((STRBUF).pos - (STRBUF).buf) : 0; \
int l = func((STRBUF).pos, remain, ##args); \
if (l < 0 || l > remain) \
(STRBUF).pos = (STRBUF).buf + (STRBUF).len; \
(STRBUF).pos += l; \
if (l > 0) \
(STRBUF).chars_needed += l; \
} while(0)
else
if(vty->type==VTY_SHELL_SERV)
static size_t len(const char *str)

Append a string to a buffer, as printed by an snprintf()-like function and with similar bounds checking.

Make sure to never write past the end of the buffer, and collect the total size that would be needed.

// an example function implementation to append: write N spaces.
int print_spaces(char *dst, size_t dst_len, int n)
{
        int i;
        if (n < 0)
                return -EINVAL;
        for (i = 0; i < n && i < dst_len; i++)
                dst[i] = ' ';
        if (dst_len)
                dst[OSMO_MIN(dst_len - 1, n)] = '\0';
        // return the n that we would have liked to write if space were available:
        return n;
}

// append above spaces as well as an snprintf()
void strbuf_example()
{
        char buf[23];
        struct osmo_strbuf sb = { .buf = buf, .len = sizeof(buf) };

        OSMO_STRBUF_APPEND(sb, print_spaces, 5);
        OSMO_STRBUF_APPEND(sb, snprintf, "The answer is %d but what is the question?", 42);
        OSMO_STRBUF_APPEND(sb, print_spaces, 423423);

        printf("%s\n", buf);
        printf("would have needed %zu bytes\n", sb.chars_needed);
}
Parameters
[in,out]STRBUFA struct osmo_strbuf instance.
[in]funcA function with a signature of int func(char *dst, size_t dst_len [, args]) with semantics like snprintf().
[in]argsArguments passed to func, if any.
#define OSMO_STRBUF_PRINTF (   STRBUF,
  fmt,
  args... 
)    OSMO_STRBUF_APPEND(STRBUF, snprintf, fmt, ##args)

Shortcut for OSMO_STRBUF_APPEND() invocation using snprintf().

int strbuf_example2(char *buf, size_t buflen) { int i; struct osmo_strbuf sb = { .buf = buf, .len = buflen };

OSMO_STRBUF_PRINTF(sb, "T minus"); for (i = 10; i; i–) OSMO_STRBUF_PRINTF(sb, " %d", i); OSMO_STRBUF_PRINTF(sb, " ... Lift off!");

return sb.chars_needed; }

Parameters
[in,out]STRBUFA struct osmo_strbuf instance.
[in]fmtFormat string passed to snprintf.
[in]argsAdditional arguments passed to snprintf, if any.
#define OSMO_STRINGIFY (   x)    #x

Stringify the name of a macro x, e.g.

an FSM event name. Note: if nested within another preprocessor macro, this will stringify the value of x instead of its name.

#define OSMO_STRINGIFY_VAL (   x)    OSMO_STRINGIFY(x)

Stringify the value of a macro x, e.g.

a port number.

#define OSMO_STRLCPY_ARRAY (   array,
  src 
)    osmo_strlcpy(array, src, sizeof(array))

Copy a C-string into a sized buffer using sizeof to detect buffer's size.

Referenced by _gsmtap_raw_output().

#define osmo_talloc_asprintf (   ctx,
  dest,
  fmt,
  args... 
)
Value:
do { \
if (!dest) \
dest = talloc_asprintf(ctx, fmt, ## args); \
else \
dest = talloc_asprintf_append((char*)dest, fmt, ## args); \
} while (0)
if(vty->type==VTY_SHELL_SERV)

Append to a string and re-/allocate if necessary.

Parameters
[in]ctxTalloc context to use for initial allocation.
[in,out]destchar* to re-/allocate and append to.
[in]fmtprintf-like string format.
[in]argsArguments for fmt.

dest may be passed in NULL, or a string previously allocated by talloc. If an existing string is passed in, it will remain associated with whichever ctx it was allocated before, regardless whether it matches ctx or not.

#define OSMO_VALUE_STRING (   x)    { x, #x }

Make a value_string entry from an enum value name.

Typedef Documentation

typedef void(* osmo_panic_handler_t)(const char *fmt, va_list args)

panic handler callback function type

Function Documentation

bool _osmo_strrb_is_bufindex_valid ( const struct osmo_strrb rb,
unsigned int  bufi 
)
char alias ( "osmo_hexdump_nospc"  )
int get_string_value ( const struct value_string vs,
const char *  str 
)

get numeric value for given human-readable string

Parameters
[in]vsArray of value_string tuples
[in]strhuman-readable string
Returns
numeric value (>0) or negative numer in case of error

References value_string::value.

Referenced by log_parse_level().

const char * get_value_string ( const struct value_string vs,
uint32_t  val 
)

get human-readable string for given value

Parameters
[in]vsArray of value_string tuples
[in]valValue to be converted
Returns
pointer to human-readable string

If val is found in vs, the array's string entry is returned. Otherwise, an "unknown" string containing the actual value is composed in a static buffer that is reused across invocations.

References get_value_string_or_null(), and namebuf.

Referenced by level_color(), log_level_str(), osmo_fsm_event_name(), osmo_fsm_term_cause_name(), and osmo_tdef_unit_name().

const char * get_value_string_or_null ( const struct value_string vs,
uint32_t  val 
)

get human-readable string or NULL for given value

Parameters
[in]vsArray of value_string tuples
[in]valValue to be converted
Returns
pointer to human-readable string or NULL if val is not found

References value_string::str.

Referenced by get_value_string(), and level_color().

char osmo_bcd2char ( uint8_t  bcd)

Convert BCD-encoded digit into printable character.

Parameters
[in]bcdA single BCD-encoded digit
Returns
single printable character

Referenced by osmo_bcd2str().

int osmo_bcd2str ( char *  dst,
size_t  dst_size,
const uint8_t *  bcd,
int  start_nibble,
int  end_nibble,
bool  allow_hex 
)

Convert BCD to string.

The given nibble offsets are interpreted in BCD order, i.e. nibble 0 is bcd[0] & 0xf, nibble 1 is bcd[0] >> 4, nibble 3 is bcd[1] & 0xf, etc..

Parameters
[out]dstOutput string buffer, is always nul terminated when dst_size > 0.
[in]dst_sizesizeof() the output string buffer.
[in]bcdBinary coded data buffer.
[in]start_nibbleOffset to start from, in nibbles, typically 1 to skip the first nibble.
[in]end_nibbleOffset to stop before, in nibbles, e.g. sizeof(bcd)*2 - (bcd[0] & GSM_MI_ODD? 0:1).
[in]allow_hexIf false, return error if there are digits other than 0-9. If true, return those as [A-F].
Returns
The strlen that would be written if the output buffer is large enough, excluding nul byte (like snprintf()), or -EINVAL if allow_hex is false and a digit > 9 is encountered. On -EINVAL, the conversion is still completed as if allow_hex were passed as true. Return -ENOMEM if dst is NULL or dst_size is zero. If end_nibble <= start_nibble, write an empty string to dst and return 0.

References osmo_bcd2char(), and OSMO_MAX.

uint8_t osmo_char2bcd ( char  c)

Convert number in ASCII to BCD value.

Parameters
[in]cASCII character
Returns
BCD encoded value of character
int osmo_constant_time_cmp ( const uint8_t *  exp,
const uint8_t *  rel,
const int  count 
)

Wishful thinking to generate a constant time compare.

Parameters
[in]expExpected data
[in]relComparison value
[in]countNumber of bytes to compare
Returns
1 in case exp equals rel; zero otherwise

Compare count bytes of exp to rel. Return 0 if they are identical, 1 otherwise. Do not return a mismatch on the first mismatching byte, but always compare all bytes, regardless. The idea is that the amount of matching bytes cannot be inferred from the time the comparison took.

uint64_t osmo_decode_big_endian ( const uint8_t *  data,
size_t  data_len 
)

Generic retrieval of 1..8 bytes as big-endian uint64_t.

Parameters
[in]dataInput data as byte-array
[in]data_lenLength of data in octets
Returns
uint64_t of data interpreted as big-endian

This is like osmo_load64be_ext, except that if data_len is less than sizeof(uint64_t), the data is interpreted as the least significant bytes (osmo_load64be_ext loads them as the most significant bytes into the returned uint64_t). In this way, any integer size up to 64 bits can be decoded conveniently by using sizeof(), without the need to call specific numbered functions (osmo_load16, 32, ...).

uint8_t * osmo_encode_big_endian ( uint64_t  value,
size_t  data_len 
)

Generic big-endian encoding of big endian number up to 64bit.

Parameters
[in]valueunsigned integer value to be stored
[in]data_lennumber of octets
Returns
static buffer containing big-endian stored value

This is like osmo_store64be_ext, except that this returns a static buffer of the result (for convenience, but not threadsafe). If data_len is less than sizeof(uint64_t), only the least significant bytes of value are encoded.

References ARRAY_SIZE, OSMO_ASSERT, and osmo_store64be_ext().

const char * osmo_escape_str ( const char *  str,
int  in_len 
)

Return the string with all non-printable characters escaped.

Call osmo_escape_str_buf() with a static buffer.

Parameters
[in]strA string that may contain any characters.
[in]lenPass -1 to print until nul char, or >= 0 to force a length.
Returns
buf containing an escaped representation, possibly truncated, or str itself.

References namebuf, and osmo_escape_str_buf().

const char * osmo_escape_str_buf ( const char *  str,
int  in_len,
char *  buf,
size_t  bufsize 
)

Return the string with all non-printable characters escaped.

Parameters
[in]strA string that may contain any characters.
[in]lenPass -1 to print until nul char, or >= 0 to force a length.
[in,out]bufstring buffer to write escaped characters to.
[in]bufsizesize of buf.
Returns
buf containing an escaped representation, possibly truncated, or str itself.

References BACKSLASH_CASE.

Referenced by osmo_escape_str(), and osmo_quote_str_buf().

int osmo_get_macaddr ( uint8_t *  mac_out,
const char *  dev_name 
)

Obtain the MAC address of a given network device.

Parameters
[out]mac_outpointer to caller-allocated buffer of 6 bytes
[in]dev_namestring name of the network device
Returns
0 in case of success; negative otherwise
char * osmo_hexdump ( const unsigned char *  buf,
int  len 
)

Convert binary sequence to hexadecimal ASCII string.

Parameters
[in]bufpointer to sequence of bytes
[in]lenlength of buf in number of bytes
Returns
pointer to zero-terminated string

This function will print a sequence of bytes as hexadecimal numbers, adding one space character between each byte (e.g. "1a ef d9")

The maximum size of the output buffer is 4096 bytes, i.e. the maximum number of input bytes that can be printed in one call is 1365!

References hexd_buff, and osmo_hexdump_buf().

Referenced by _msgb_eq(), msgb_hexdump(), msgb_hexdump_l1(), msgb_hexdump_l2(), msgb_hexdump_l3(), and msgb_hexdump_l4().

const char * osmo_hexdump_buf ( char *  out_buf,
size_t  out_buf_size,
const unsigned char *  buf,
int  len,
const char *  delim,
bool  delim_after_last 
)

Convert binary sequence to hexadecimal ASCII string.

Parameters
[out]out_bufOutput buffer to write the resulting string to.
[in]out_buf_sizesizeof(out_buf).
[in]bufInput buffer, pointer to sequence of bytes.
[in]lenLength of input buf in number of bytes.
[in]delimString to separate each byte; NULL or "" for no delim.
[in]delim_after_lastIf true, end the string in delim (true: "1a:ef:d9:", false: "1a:ef:d9"); if out_buf has insufficient space, the string will always end in a delim.
Returns
out_buf, containing a zero-terminated string, or "" (empty string) if out_buf == NULL or out_buf_size < 1.

This function will print a sequence of bytes as hexadecimal numbers, adding one delim between each byte (e.g. for delim passed as ":", return a string like "1a:ef:d9").

The delim_after_last argument exists to be able to exactly show the original osmo_hexdump() behavior, which always ends the string with a delimiter.

References hex_chars, and len().

Referenced by osmo_hexdump(), and osmo_hexdump_nospc().

char * osmo_hexdump_nospc ( const unsigned char *  buf,
int  len 
)

Convert binary sequence to hexadecimal ASCII string.

Parameters
[in]bufpointer to sequence of bytes
[in]lenlength of buf in number of bytes
Returns
pointer to zero-terminated string

This function will print a sequence of bytes as hexadecimal numbers, without any space character between each byte (e.g. "1aefd9")

The maximum size of the output buffer is 4096 bytes, i.e. the maximum number of input bytes that can be printed in one call is 2048!

References hexd_buff, and osmo_hexdump_buf().

int osmo_hexparse ( const char *  str,
uint8_t *  b,
int  max_len 
)

Parse a string containing hexadecimal digits.

Parameters
[in]strstring containing ASCII encoded hexadecimal digits
[out]boutput buffer
[in]max_lenmaximum space in output buffer
Returns
number of parsed octets, or -1 on error

References c.

bool osmo_identifier_valid ( const char *  str)

Determine if a given identifier is valid, i.e.

doesn't contain illegal chars

Parameters
[in]strString to validate
Returns
true in case str contains valid identifier, false otherwise

References osmo_separated_identifiers_valid().

Referenced by osmo_fsm_inst_update_id_f(), osmo_fsm_register(), and rate_ctrl_group_desc_validate().

bool osmo_is_hexstr ( const char *  str,
int  min_digits,
int  max_digits,
bool  require_even 
)

Validate that a given string is a hex string within given size limits.

Note that each hex digit amounts to a nibble, so if checking for a hex string to result in N bytes, pass amount of digits as 2*N.

Parameters
strA nul-terminated string to validate, or NULL.
min_digitsleast permitted amount of digits.
max_digitsmost permitted amount of digits.
require_evenif true, require an even amount of digits.
Returns
true when the hex_str contains only hexadecimal digits (no whitespace) and matches the requested length; also true when min_digits <= 0 and str is NULL.

References len().

uint32_t osmo_isqrt32 ( uint32_t  x)

perform an integer square root operation on unsigned 32bit integer.

This implementation is taken from "Hacker's Delight" Figure 11-1 "Integer square root, Newton's method", which can also be found at http://www.hackersdelight.org/hdcodetxt/isqrt.c.txt

const char osmo_luhn ( const char *  in,
int  in_len 
)

Calculate the Luhn checksum (as used for IMEIs).

Parameters
[in]inInput digits in ASCII string representation.
[in]in_lenCount of digits to use for the input (14 for IMEI).
Returns
checksum char (e.g. '3'); negative on error
int osmo_macaddr_parse ( uint8_t *  out,
const char *  in 
)

Parse a MAC address from human-readable notation This function parses an ethernet MAC address in the commonly-used hex/colon notation (00:00:00:00:00:00) and generates the binary representation from it.

Parameters
[out]outpointer to caller-allocated buffer of 6 bytes
[in]inpointer to input data as string with hex/colon notation
char * osmo_osmo_hexdump_nospc ( const unsigned char *  buf,
int  len 
)
void osmo_panic ( const char *  fmt,
  ... 
)

Terminate the current program with a panic.

You can call this function in case some severely unexpected situation is detected and the program is supposed to terminate in a way that reports the fact that it terminates.

The application can register a panic handler function using osmo_set_panic_handler. If it doesn't, a default panic handler function is called automatically.

The default function on most systems will generate a backtrace and then abort() the process.

References osmo_panic_default(), and osmo_panic_handler.

Referenced by bit_value_to_char().

static void osmo_panic_default ( const char *  fmt,
va_list  args 
)
static

References osmo_generate_backtrace().

Referenced by osmo_panic().

int osmo_plugin_load_all ( const char *  directory)
const char * osmo_quote_str ( const char *  str,
int  in_len 
)

Like osmo_quote_str_buf() but returns the result in a static buffer.

The static buffer is shared with get_value_string() and osmo_escape_str().

Parameters
[in]strA string that may contain any characters.
[in]in_lenPass -1 to print until nul char, or >= 0 to force a length.
Returns
static buffer containing a quoted and escaped representation, possibly truncated.

References namebuf, and osmo_quote_str_buf().

Referenced by osmo_fsm_inst_update_id_f().

const char * osmo_quote_str_buf ( const char *  str,
int  in_len,
char *  buf,
size_t  bufsize 
)

Like osmo_escape_str(), but returns double-quotes around a string, or "NULL" for a NULL string.

This allows passing any char* value and get its C representation as string.

Parameters
[in]strA string that may contain any characters.
[in]in_lenPass -1 to print until nul char, or >= 0 to force a length.
Returns
buf containing a quoted and escaped representation, possibly truncated.

References osmo_escape_str_buf(), OSMO_MIN, and res.

Referenced by osmo_quote_str().

bool osmo_separated_identifiers_valid ( const char *  str,
const char *  sep_chars 
)

Determine if a given identifier is valid, i.e.

doesn't contain illegal chars

Parameters
[in]strString to validate
[in]sep_charsPermitted separation characters between identifiers.
Returns
true in case str contains only valid identifiers and sep_chars, false otherwise

References len().

Referenced by osmo_identifier_valid().

void osmo_set_panic_handler ( osmo_panic_handler_t  h)

Set the panic handler.

Parameters
[in]hNew panic handler function

This changes the panic handling function from the currently active function to a new call-back function supplied by the caller.

References osmo_panic_handler.

void osmo_str2lower ( char *  out,
const char *  in 
)
void osmo_str2upper ( char *  out,
const char *  in 
)
const char * osmo_str_tolower ( const char *  src)

Convert a string to lowercase, using a static buffer.

The resulting string may be truncated if the internally used static buffer is shorter than src. The internal buffer is at least 128 bytes long, i.e. guaranteed to hold at least 127 characters and a terminating nul. See also osmo_str_tolower_buf().

Parameters
[in]srcString to convert to lowercase.
Returns
Resulting lowercase string in a static buffer, always nul terminated.

References osmo_str_tolower_buf().

size_t osmo_str_tolower_buf ( char *  dest,
size_t  dest_len,
const char *  src 
)

Convert a string to lowercase, while checking buffer size boundaries.

The result written to dest is guaranteed to be nul terminated if dest_len > 0. If dest == src, the string is converted in-place, if necessary truncated at dest_len - 1 characters length as well as nul terminated. Note: similar osmo_str2lower(), but safe to use for src strings of arbitrary length.

Parameters
[out]destTarget buffer to write lowercase string.
[in]dest_lenMaximum buffer size of dest (e.g. sizeof(dest)).
[in]srcString to convert to lowercase.
Returns
Length of src, like osmo_strlcpy(), but if dest == src at most dest_len - 1.

References osmo_strlcpy().

Referenced by osmo_str_tolower().

const char * osmo_str_toupper ( const char *  src)

Convert a string to uppercase, using a static buffer.

The resulting string may be truncated if the internally used static buffer is shorter than src. The internal buffer is at least 128 bytes long, i.e. guaranteed to hold at least 127 characters and a terminating nul. See also osmo_str_toupper_buf().

Parameters
[in]srcString to convert to uppercase.
Returns
Resulting uppercase string in a static buffer, always nul terminated.

References osmo_str_toupper_buf().

size_t osmo_str_toupper_buf ( char *  dest,
size_t  dest_len,
const char *  src 
)

Convert a string to uppercase, while checking buffer size boundaries.

The result written to dest is guaranteed to be nul terminated if dest_len > 0. If dest == src, the string is converted in-place, if necessary truncated at dest_len - 1 characters length as well as nul terminated. Note: similar osmo_str2upper(), but safe to use for src strings of arbitrary length.

Parameters
[out]destTarget buffer to write uppercase string.
[in]dest_lenMaximum buffer size of dest (e.g. sizeof(dest)).
[in]srcString to convert to uppercase.
Returns
Length of src, like osmo_strlcpy(), but if dest == src at most dest_len - 1.

References osmo_strlcpy().

Referenced by osmo_str_toupper().

size_t osmo_strlcpy ( char *  dst,
const char *  src,
size_t  siz 
)

Copy a C-string into a sized buffer.

Parameters
[in]srcsource string
[out]dstdestination string
[in]sizsize of the dst buffer
Returns
length of src

Copy at most siz bytes from src to dst, ensuring that the result is NUL terminated. The NUL character is included in siz, i.e. passing the actual sizeof(*dst) is correct.

References len().

Referenced by osmo_str_tolower_buf(), and osmo_str_toupper_buf().

int osmo_strrb_add ( struct osmo_strrb rb,
const char *  data 
)

Add a string to the osmo_strrb.

Parameters
[in]rbThe osmo_strrb to add to.
[in]dataThe string to add.

Add a message to the osmo_strrb. Older messages will be overwritten as necessary.

Returns
0 normally, 1 as a warning (ie, if data was truncated).

References osmo_strrb::buffer, osmo_strrb::end, len(), RB_MAX_MESSAGE_SIZE, osmo_strrb::size, and osmo_strrb::start.

Referenced by _rb_output().

struct osmo_strrb* osmo_strrb_create ( TALLOC_CTX *  ctx,
size_t  rb_size 
)

Create an empty, initialized osmo_strrb.

Parameters
[in]ctxThe talloc memory context which should own this.
[in]rb_sizeThe number of message slots the osmo_strrb can hold.
Returns
A struct osmo_strrb* on success, NULL in case of error.

This function creates and initializes a ringbuffer. Note that the ringbuffer stores at most rb_size - 1 messages.

References osmo_strrb::buffer, RB_MAX_MESSAGE_SIZE, and osmo_strrb::size.

Referenced by log_target_create_rb().

size_t osmo_strrb_elements ( const struct osmo_strrb rb)

Count the number of log messages in an osmo_strrb.

Parameters
[in]rbThe osmo_strrb to count the elements of.
Returns
The number of log messages in the osmo_strrb.

References osmo_strrb::end, osmo_strrb::size, and osmo_strrb::start.

Referenced by log_target_rb_used_size().

const char* osmo_strrb_get_nth ( const struct osmo_strrb rb,
unsigned int  string_index 
)

Return a pointer to the Nth string in the osmo_strrb.

Parameters
[in]rbThe osmo_strrb to search.
[in]string_indexThe index sought (N), zero-indexed.

Return a pointer to the Nth string in the osmo_strrb. Return NULL if there is no Nth string. Note that N is zero-indexed.

Returns
A pointer to the target string on success, NULL in case of error.

References _osmo_strrb_is_bufindex_valid(), osmo_strrb::buffer, osmo_strrb::end, osmo_strrb::size, and osmo_strrb::start.

Referenced by log_target_rb_get().

bool osmo_strrb_is_empty ( const struct osmo_strrb rb)

Check if an osmo_strrb is empty.

Parameters
[in]rbThe osmo_strrb to check.
Returns
True if the osmo_strrb is empty, false otherwise.

References osmo_strrb::end, and osmo_strrb::start.

Referenced by _osmo_strrb_is_bufindex_valid().

static void osmo_talloc_replace_string ( void *  ctx,
char **  dst,
const char *  newstr 
)
inlinestatic

duplicate a string using talloc and release its prior content (if any)

Parameters
[in]ctxTalloc context to use for allocation
[out]dstpointer to string, will be updated with ptr to new string
[in]newstrString that will be copieed to newly allocated string
char * osmo_ubit_dump ( const uint8_t *  bits,
unsigned int  len 
)

Convert a sequence of unpacked bits to ASCII string.

Parameters
[in]bitsA sequence of unpacked bits
[in]lenLength of bits

References hexd_buff, and len().

Variable Documentation

void to properly check target memory bounds
const char hex_chars[] = "0123456789abcdef"
static

Referenced by osmo_hexdump_buf().

char hexd_buff[4096]
static
char namebuf[255]
static
osmo_panic_handler_t osmo_panic_handler = (void*)0
static