Asterisk - The Open Source Telephony Project  21.4.1
Data Structures | Macros | Enumerations | Functions
strings.h File Reference

String manipulation functions. More...

#include <ctype.h>
#include <limits.h>
#include "asterisk/utils.h"
#include "asterisk/threadstorage.h"
#include "asterisk/astobj2.h"

Go to the source code of this file.

Data Structures

struct  ast_str
 Support for dynamic strings. More...
 

Macros

#define __AST_STR_LEN   len
 
#define __AST_STR_STR   str
 
#define __AST_STR_TS   ts
 
#define __AST_STR_USED   used
 
#define _ast_str_helper(buf, max_len, append, fmt, ap)   __ast_str_helper(buf, max_len, append, fmt, ap, __FILE__, __LINE__, __PRETTY_FUNCTION__)
 
#define _DB1(x)
 
#define AS_OR(a, b)   (a && ast_str_strlen(a)) ? ast_str_buffer(a) : (b)
 
#define ast_join(s, len, w)   ast_join_delim(s, len, w, -1, ' ')
 Join an array of strings into a single string. More...
 
#define ast_str_alloca(init_len)
 
#define ast_str_container_alloc(buckets)   ast_str_container_alloc_options(AO2_ALLOC_OPT_LOCK_MUTEX, buckets)
 Allocates a hash container for bare strings. More...
 
#define ast_str_create(init_len)   _ast_str_create(init_len, __FILE__, __LINE__, __PRETTY_FUNCTION__)
 Create a malloc'ed dynamic length string. More...
 
#define ast_str_make_space(buf, new_len)   _ast_str_make_space(buf, new_len, __FILE__, __LINE__, __PRETTY_FUNCTION__)
 
#define ast_str_tmp(init_len, __expr)
 Provides a temporary ast_str and returns a copy of its buffer. More...
 
#define ast_to_camel_case(s)   ast_to_camel_case_delim(s, "_")
 Attempts to convert the given string to camel case using an underscore as the specified delimiter. More...
 
#define AST_YESNO(x)   ((x) ? "Yes" : "No")
 return Yes or No depending on the argument. More...
 
#define DS_ALLOCA   ((struct ast_threadstorage *)2)
 
#define DS_MALLOC   ((struct ast_threadstorage *)1)
 
#define DS_STATIC   ((struct ast_threadstorage *)3) /* not supported yet */
 
#define S_COR(a, b, c)   ({typeof(&((b)[0])) __x = (b); (a) && !ast_strlen_zero(__x) ? (__x) : (c);})
 returns the equivalent of logic or for strings, with an additional boolean check: second one if not empty and first one is true, otherwise third one. example: S_COR(usewidget, widget, "<no widget>")
 
#define S_OR(a, b)   ({typeof(&((a)[0])) __x = (a); ast_strlen_zero(__x) ? (b) : __x;})
 returns the equivalent of logic or for strings: first one if not empty, otherwise second one.
 

Enumerations

enum  { AST_DYNSTR_BUILD_FAILED = -1, AST_DYNSTR_BUILD_RETRY = -2 }
 Error codes from __ast_str_helper() The underlying processing to manipulate dynamic string is done by __ast_str_helper(), which can return a success or a permanent failure (e.g. no memory). More...
 
enum  ast_strsep_flags { AST_STRSEP_STRIP = 0x01, AST_STRSEP_TRIM = 0x02, AST_STRSEP_UNESCAPE = 0x04, AST_STRSEP_ALL = 0x07 }
 Flags for ast_strsep. More...
 

Functions

int __ast_str_helper (struct ast_str **buf, ssize_t max_len, int append, const char *fmt, va_list ap, const char *file, int lineno, const char *func)
 Core functionality of ast_str_(set|append)_va. More...
 
char * __ast_str_helper2 (struct ast_str **buf, ssize_t max_len, const char *src, size_t maxsrc, int append, int escapecommas)
 
struct ast_str_ast_str_create (size_t init_len, const char *file, int lineno, const char *func)
 
int _ast_str_make_space (struct ast_str **buf, size_t new_len, const char *file, int lineno, const char *function)
 
static int force_inline attribute_pure ast_begins_with (const char *str, const char *prefix)
 Checks whether a string begins with another. More...
 
int ast_build_string (char **buffer, size_t *space, const char *fmt,...)
 Build a string in a buffer, designed to be called repeatedly. More...
 
int ast_build_string_va (char **buffer, size_t *space, const char *fmt, va_list ap)
 Build a string in a buffer, designed to be called repeatedly. More...
 
int ast_check_digits (const char *arg)
 Check if a string is only digits. More...
 
void ast_copy_string (char *dst, const char *src, size_t size)
 Size-limited null-terminating string copy. More...
 
static int force_inline attribute_pure ast_ends_with (const char *str, const char *suffix)
 Checks whether a string ends with another. More...
 
char * ast_escape (char *dest, const char *s, size_t size, const char *to_escape)
 Escape the 'to_escape' characters in the given string. More...
 
char * ast_escape_alloc (const char *s, const char *to_escape)
 Escape the 'to_escape' characters in the given string. More...
 
char * ast_escape_c (char *dest, const char *s, size_t size)
 Escape standard 'C' sequences in the given string. More...
 
char * ast_escape_c_alloc (const char *s)
 Escape standard 'C' sequences in the given string. More...
 
int attribute_pure ast_false (const char *val)
 Make sure something is false. Determine if a string containing a boolean value is "false". This function checks to see whether a string passed to it is an indication of an "false" value. It checks to see if the string is "no", "false", "n", "f", "off" or "0". More...
 
char * ast_generate_random_string (char *buf, size_t size)
 Create a pseudo-random string of a fixed length. More...
 
int ast_get_time_t (const char *src, time_t *dst, time_t _default, int *consumed)
 Parse a time (integer) string. More...
 
int ast_get_timeval (const char *src, struct timeval *tv, struct timeval _default, int *consumed)
 Parse a time (float) string. More...
 
int ast_in_delimited_string (const char *needle, const char *haystack, char delim)
 Check if there is an exact match for 'needle' between delimiters in 'haystack'. More...
 
void ast_join_delim (char *s, size_t len, const char *const w[], unsigned int size, char delim)
 Join an array of strings into a single string. More...
 
char * ast_read_line_from_buffer (char **buffer)
 Read lines from a string buffer. More...
 
int ast_regex_string_to_regex_pattern (const char *regex_string, struct ast_str **regex_pattern)
 Given a string regex_string in the form of "/regex/", convert it into the form of "regex". More...
 
char * ast_skip_blanks (const char *str)
 Gets a pointer to the first non-whitespace character in a string. More...
 
char * ast_skip_nonblanks (const char *str)
 Gets a pointer to first whitespace character in a string. More...
 
int ast_str_append (struct ast_str **buf, ssize_t max_len, const char *fmt,...)
 Append to a thread local dynamic string. More...
 
char * ast_str_append_escapecommas (struct ast_str **buf, ssize_t maxlen, const char *src, size_t maxsrc)
 Append a non-NULL terminated substring to the end of a dynamic string, with escaping of commas.
 
char * ast_str_append_substr (struct ast_str **buf, ssize_t maxlen, const char *src, size_t maxsrc)
 Append a non-NULL terminated substring to the end of a dynamic string.
 
int ast_str_append_va (struct ast_str **buf, ssize_t max_len, const char *fmt, va_list ap)
 Append to a dynamic string using a va_list. More...
 
char * ast_str_buffer (const struct ast_str *buf)
 Returns the string buffer within the ast_str buf. More...
 
static force_inline int attribute_pure ast_str_case_hash (const char *str)
 Compute a hash value on a case-insensitive string. More...
 
int ast_str_container_add (struct ao2_container *str_container, const char *add)
 Adds a string to a string container allocated by ast_str_container_alloc. More...
 
struct ao2_containerast_str_container_alloc_options (enum ao2_alloc_opts opts, int buckets)
 Allocates a hash container for bare strings. More...
 
void ast_str_container_remove (struct ao2_container *str_container, const char *remove)
 Removes a string from a string container allocated by ast_str_container_alloc. More...
 
int ast_str_copy_string (struct ast_str **dst, struct ast_str *src)
 
static force_inline int attribute_pure ast_str_hash (const char *str)
 Compute a hash value on a string. More...
 
static force_inline int ast_str_hash_add (const char *str, int seed)
 Compute a hash value on a string. More...
 
static force_inline int attribute_pure ast_str_hash_restrict (unsigned int hash)
 Restrict hash value range. More...
 
void ast_str_reset (struct ast_str *buf)
 Reset the content of a dynamic string. Useful before a series of ast_str_append.
 
int ast_str_set (struct ast_str **buf, ssize_t max_len, const char *fmt,...)
 Set a dynamic string using variable arguments. More...
 
char * ast_str_set_escapecommas (struct ast_str **buf, ssize_t maxlen, const char *src, size_t maxsrc)
 Set a dynamic string to a non-NULL terminated substring, with escaping of commas.
 
char * ast_str_set_substr (struct ast_str **buf, ssize_t maxlen, const char *src, size_t maxsrc)
 Set a dynamic string to a non-NULL terminated substring.
 
int ast_str_set_va (struct ast_str **buf, ssize_t max_len, const char *fmt, va_list ap)
 Set a dynamic string from a va_list. More...
 
size_t ast_str_size (const struct ast_str *buf)
 Returns the current maximum length (without reallocation) of the current buffer. More...
 
size_t ast_str_strlen (const struct ast_str *buf)
 Returns the current length of the string stored within buf. More...
 
struct ast_strast_str_thread_get (struct ast_threadstorage *ts, size_t init_len)
 Retrieve a thread locally stored dynamic string. More...
 
static force_inline char * ast_str_to_lower (char *str)
 Convert a string to all lower-case. More...
 
static force_inline char * ast_str_to_upper (char *str)
 Convert a string to all upper-case. More...
 
void ast_str_trim_blanks (struct ast_str *buf)
 Trims trailing whitespace characters from an ast_str string. More...
 
char * ast_str_truncate (struct ast_str *buf, ssize_t len)
 Truncates the enclosed string to the given length. More...
 
void ast_str_update (struct ast_str *buf)
 Update the length of the buffer, after using ast_str merely as a buffer. More...
 
int ast_strings_equal (const char *str1, const char *str2)
 Compare strings for equality checking for NULL. More...
 
int ast_strings_match (const char *left, const char *op, const char *right)
 Compares 2 strings using realtime-style operators. More...
 
char * ast_strip (char *s)
 Strip leading/trailing whitespace from a string. More...
 
char * ast_strip_quoted (char *s, const char *beg_quotes, const char *end_quotes)
 Strip leading/trailing whitespace and quotes from a string. More...
 
static force_inline int attribute_pure ast_strlen_zero (const char *s)
 
char * ast_strsep (char **s, const char sep, uint32_t flags)
 Act like strsep but ignore separators inside quotes. More...
 
char * ast_strsep_quoted (char **s, const char sep, const char quote, uint32_t flags)
 Like ast_strsep() except you can specify a specific quote character. More...
 
char * ast_tech_to_upper (char *dev_str)
 Convert the tech portion of a device string to upper case. More...
 
char * ast_to_camel_case_delim (const char *s, const char *delim)
 Attempts to convert the given string to camel case using the specified delimiter. More...
 
char * ast_trim_blanks (char *str)
 Trims trailing whitespace characters from a string. More...
 
int attribute_pure ast_true (const char *val)
 Make sure something is true. Determine if a string containing a boolean value is "true". This function checks to see whether a string passed to it is an indication of an "true" value. It checks to see if the string is "yes", "true", "y", "t", "on" or "1". More...
 
char * ast_unescape_c (char *s)
 Convert some C escape sequences. More...
 
char * ast_unescape_semicolon (char *s)
 Strip backslash for "escaped" semicolons, the string to be stripped (will be modified). More...
 

Detailed Description

String manipulation functions.

Definition in file strings.h.

Macro Definition Documentation

#define ast_join (   s,
  len,
 
)    ast_join_delim(s, len, w, -1, ' ')

Join an array of strings into a single string.

Parameters
sthe resulting string buffer
lenthe length of the result buffer, s
wan array of strings to join.

This function will join all of the strings in the array 'w' into a single string. It will also place a space in the result buffer in between each string from 'w'.

Definition at line 520 of file strings.h.

Referenced by ast_cli_command_full(), cli_console_sendtext(), handle_cli_check_permissions(), help1(), and set_full_cmd().

#define ast_str_container_alloc (   buckets)    ast_str_container_alloc_options(AO2_ALLOC_OPT_LOCK_MUTEX, buckets)

Allocates a hash container for bare strings.

Since
12
Parameters
bucketsThe number of buckets to use for the hash container
Returns
AO2 container for strings
Return values
NULLif allocation failed

Definition at line 1365 of file strings.h.

Referenced by ast_bridge_snapshot_create(), ast_cel_general_config_alloc(), ast_media_get_media(), ast_media_get_variants(), event_session_alloc(), get_languages(), stasis_app_get_all(), and test_cel_peer_strings_match().

#define ast_str_create (   init_len)    _ast_str_create(init_len, __FILE__, __LINE__, __PRETTY_FUNCTION__)

Create a malloc'ed dynamic length string.

Parameters
init_lenThis is the initial length of the string buffer
Returns
This function returns a pointer to the dynamic string length. The result will be NULL in the case of a memory allocation error.
Note
The result of this function is dynamically allocated memory, and must be free()'d after it is no longer needed.

Definition at line 659 of file strings.h.

Referenced by add_ice_to_stream(), ast_ari_asterisk_get_global_var(), ast_ari_channels_create(), ast_ari_channels_get_channel_var(), ast_category_get_templates(), ast_cc_agent_set_interfaces_chanvar(), ast_channel_dialed_causes_channels(), ast_func_read(), ast_get_character_str(), ast_get_digit_str(), ast_get_phonetic_str(), ast_http_auth(), ast_http_create_response(), ast_http_error(), ast_http_send(), ast_log_backtrace(), ast_logger_get_channels(), ast_manager_build_bridge_state_string_prefix(), ast_manager_build_channel_state_string_prefix(), ast_manager_hangup_helper(), ast_manager_str_from_json_object(), ast_parse_digest(), ast_pbx_exec_application(), ast_set_cc_interfaces_chanvar(), ast_sounds_get_index_for_file(), ast_str_append_event_header(), ast_str_substitute_variables_full2(), ast_stream_create_resolved(), ast_tcptls_client_create(), ast_variable_list_join(), ast_xmldoc_printable(), ast_xmldoc_query(), config_text_file_load(), dump_queue_members(), generic_http_callback(), get_languages(), handle_exec(), handle_missing_table(), handle_options(), handle_showchan(), handle_updates(), init_queue(), join_conference_bridge(), leave_voicemail(), load_modules(), make_email_file(), manager_build_parked_call_string(), parking_lot_cfg_create_extensions(), pbx_retrieve_variable(), pjsip_acf_dial_contacts_read(), process_description_file(), prometheus_scrape_to_string(), queue_set_param(), realtime_ldap_status(), realtime_sqlite3_destroy(), realtime_sqlite3_helper(), realtime_sqlite3_store(), realtime_sqlite3_update(), realtime_sqlite3_update2(), stasis_app_control_snoop(), store_odbc(), and websocket_client_parse_uri().

#define ast_str_tmp (   init_len,
  __expr 
)

Provides a temporary ast_str and returns a copy of its buffer.

Since
16.12
17.6
18.0
Parameters
init_lenThe initial length of the temporary ast_str needed.
__exprAn expression that needs the temporary ast_str and returns a char *.
Returns
A copy of __expr's return buffer allocated on the stack.

There are a few query functions scattered around that need an ast_str in which to assemble the results but it's not always convenient to create an ast_str and ensure it's freed just to print a log message. For example:

1 struct ast_str *temp = ast_str_create(128);
2 ast_log(LOG_INFO, "Format caps: %s\n", ast_format_cap_get_names(caps, &temp));
3 ast_free(temp);

That's not bad if you only have to do it once but some of our code that deals with streams and codecs is pretty complex and good instrumentation is essential. The aim of this function is to make that easier.

With this macro, the above code can be simplified:

1 ast_log(LOG_INFO, "Format caps: %s\n",
2  ast_str_tmp(128, ast_format_cap_get_names(caps, &STR_TMP));

STR_TMP will always be a reference to the temporary ast_str created by the macro. Its scope is limited by the macro so you can use it multiple times without conflict:

1 ast_log(LOG_INFO, "Format caps in: %s Format caps out: %s\n",
2  ast_str_tmp(128, ast_format_cap_get_names(caps_in, &STR_TMP),
3  ast_str_tmp(128, ast_format_cap_get_names(caps_out, &STR_TMP)
4  );
Warning
The returned string is stack allocated so don't go overboard.

Definition at line 1189 of file strings.h.

Referenced by ast_channel_request_stream_topology_change(), ast_channel_set_stream_topology(), ast_stream_create_resolved(), chan_pjsip_call(), chan_pjsip_get_codec(), chan_pjsip_indicate(), chan_pjsip_request_with_stream_topology(), chan_pjsip_set_rtp_peer(), chan_rtp_get_codec(), compatible_formats_exist(), create_outgoing_sdp_stream(), and dial_exec_full().

#define ast_to_camel_case (   s)    ast_to_camel_case_delim(s, "_")

Attempts to convert the given string to camel case using an underscore as the specified delimiter.

note - returned string needs to be freed

Parameters
sthe string to convert
Returns
The string converted to "CamelCase"

Definition at line 546 of file strings.h.

#define AST_YESNO (   x)    ((x) ? "Yes" : "No")

return Yes or No depending on the argument.

Note that this macro is used my AMI, where a literal "Yes" and "No" are expected, and translations would cause problems.

Parameters
xBoolean value
Return values
Yesif x is true (non-zero)
Noif x is false (zero)

Definition at line 143 of file strings.h.

Referenced by pjsip_acf_moh_passthrough_read().

Enumeration Type Documentation

anonymous enum

Error codes from __ast_str_helper() The underlying processing to manipulate dynamic string is done by __ast_str_helper(), which can return a success or a permanent failure (e.g. no memory).

Enumerator
AST_DYNSTR_BUILD_FAILED 

An error has occurred and the contents of the dynamic string are undefined

AST_DYNSTR_BUILD_RETRY 

The buffer size for the dynamic string had to be increased, and __ast_str_helper() needs to be called again after a va_end() and va_start(). This return value is legacy and will no longer be used.

Definition at line 940 of file strings.h.

940  {
941  /*! An error has occurred and the contents of the dynamic string
942  * are undefined */
944  /*! The buffer size for the dynamic string had to be increased, and
945  * __ast_str_helper() needs to be called again after
946  * a va_end() and va_start(). This return value is legacy and will
947  * no longer be used.
948  */
950 };

Flags for ast_strsep.

Enumerator
AST_STRSEP_STRIP 

Trim, then strip quotes. You may want to trim again

AST_STRSEP_TRIM 

Trim leading and trailing whitespace

AST_STRSEP_UNESCAPE 

Unescape '\'

AST_STRSEP_ALL 

Trim, strip, unescape

Definition at line 254 of file strings.h.

254  {
255  AST_STRSEP_STRIP = 0x01, /*!< Trim, then strip quotes. You may want to trim again */
256  AST_STRSEP_TRIM = 0x02, /*!< Trim leading and trailing whitespace */
257  AST_STRSEP_UNESCAPE = 0x04, /*!< Unescape '\' */
258  AST_STRSEP_ALL = 0x07, /*!< Trim, strip, unescape */
259 };

Function Documentation

int __ast_str_helper ( struct ast_str **  buf,
ssize_t  max_len,
int  append,
const char *  fmt,
va_list  ap,
const char *  file,
int  lineno,
const char *  function 
)

Core functionality of ast_str_(set|append)_va.

The arguments to this function are the same as those described for ast_str_set_va except for an addition argument, append. If append is non-zero, this will append to the current string instead of writing over it.

AST_DYNSTR_BUILD_RETRY is a legacy define. It should probably never again be used.

A return of AST_DYNSTR_BUILD_FAILED indicates a memory allocation error.

A return value greater than or equal to zero indicates the number of characters that have been written, not including the terminating '\0'. In the append case, this only includes the number of characters appended.

Note
This function should never need to be called directly. It should through calling one of the other functions or macros defined in this file.

core handler for dynamic strings. This is not meant to be called directly, but rather through the various wrapper macros ast_str_set(...) ast_str_append(...) ast_str_set_va(...) ast_str_append_va(...)

Definition at line 55 of file strings.c.

References _ast_str_make_space(), AST_DYNSTR_BUILD_FAILED, and ast_log_safe().

58 {
59  int res;
60  int added;
61  int need;
62  int offset = (append && (*buf)->__AST_STR_LEN) ? (*buf)->__AST_STR_USED : 0;
63  va_list aq;
64 
65  if (max_len < 0) {
66  max_len = (*buf)->__AST_STR_LEN; /* don't exceed the allocated space */
67  }
68 
69  do {
70  va_copy(aq, ap);
71  res = vsnprintf((*buf)->__AST_STR_STR + offset, (*buf)->__AST_STR_LEN - offset, fmt, aq);
72  va_end(aq);
73 
74  if (res < 0) {
75  /*
76  * vsnprintf write to string failed.
77  * I don't think this is possible with a memory buffer.
78  */
80  added = 0;
81  break;
82  }
83 
84  /*
85  * vsnprintf returns how much space we used or would need.
86  * Remember that vsnprintf does not count the nil terminator
87  * so we must add 1.
88  */
89  added = res;
90  need = offset + added + 1;
91  if (need <= (*buf)->__AST_STR_LEN
92  || (max_len && max_len <= (*buf)->__AST_STR_LEN)) {
93  /*
94  * There was enough room for the string or we are not
95  * allowed to try growing the string buffer.
96  */
97  break;
98  }
99 
100  /* Reallocate the buffer and try again. */
101  if (max_len == 0) {
102  /* unbounded, give more room for next time */
103  need += 16 + need / 4;
104  } else if (max_len < need) {
105  /* truncate as needed */
106  need = max_len;
107  }
108 
109  if (_ast_str_make_space(buf, need, file, lineno, function)) {
110  ast_log_safe(LOG_VERBOSE, "failed to extend from %d to %d\n",
111  (int) (*buf)->__AST_STR_LEN, need);
112 
114  break;
115  }
116  } while (1);
117 
118  /* Update space used, keep in mind truncation may be necessary. */
119  (*buf)->__AST_STR_USED = ((*buf)->__AST_STR_LEN <= offset + added)
120  ? (*buf)->__AST_STR_LEN - 1
121  : offset + added;
122 
123  /* Ensure that the string is terminated. */
124  (*buf)->__AST_STR_STR[(*buf)->__AST_STR_USED] = '\0';
125 
126  return res;
127 }
void ast_log_safe(int level, const char *file, int line, const char *function, const char *fmt,...)
Used for sending a log message with protection against recursion.
Definition: logger.c:2475
int _ast_str_make_space(struct ast_str **buf, size_t new_len, const char *file, int lineno, const char *function)
Definition: strings.h:827
int _ast_str_make_space ( struct ast_str **  buf,
size_t  new_len,
const char *  file,
int  lineno,
const char *  function 
)
inline

Make space in a new string (e.g. to read in data from a file)

Definition at line 827 of file strings.h.

Referenced by __ast_str_helper().

833 {
static int force_inline attribute_pure ast_begins_with ( const char *  str,
const char *  prefix 
)
static

Checks whether a string begins with another.

Since
12.0.0
Parameters
strString to check.
prefixPrefix to look for.
Return values
1if str begins with prefix
0otherwise.

Definition at line 97 of file strings.h.

Referenced by ast_crypt(), ast_http_get_auth(), ast_sendtext_data(), coreshowchannelmap_add_connected_channels(), curl_header_cb(), get_object_variables(), handle_updates(), restrictedFile(), and stasis_app_user_event().

98 {
99  ast_assert(str != NULL);
100  ast_assert(prefix != NULL);
101  while (*str == *prefix && *prefix != '\0') {
102  ++str;
103  ++prefix;
104  }
105  return *prefix == '\0';
106 }
int ast_build_string ( char **  buffer,
size_t *  space,
const char *  fmt,
  ... 
)

Build a string in a buffer, designed to be called repeatedly.

Note
This method is not recommended. New code should use ast_str_*() instead.

This is a wrapper for snprintf, that properly handles the buffer pointer and buffer space available.

Parameters
buffercurrent position in buffer to place string into (will be updated on return)
spaceremaining space in buffer (will be updated on return)
fmtprintf-style format string
Return values
0on success
non-zeroon failure.

Definition at line 2167 of file utils.c.

References ast_build_string_va().

Referenced by generate_filenames_string().

2168 {
2169  va_list ap;
2170  int result;
2171 
2172  va_start(ap, fmt);
2173  result = ast_build_string_va(buffer, space, fmt, ap);
2174  va_end(ap);
2175 
2176  return result;
2177 }
int ast_build_string_va(char **buffer, size_t *space, const char *fmt, va_list ap)
Build a string in a buffer, designed to be called repeatedly.
Definition: utils.c:2148
int ast_build_string_va ( char **  buffer,
size_t *  space,
const char *  fmt,
va_list  ap 
)

Build a string in a buffer, designed to be called repeatedly.

This is a wrapper for snprintf, that properly handles the buffer pointer and buffer space available.

Return values
zeroon success.
non-zeroon failure.
Parameters
buffercurrent position in buffer to place string into (will be updated on return)
spaceremaining space in buffer (will be updated on return)
fmtprintf-style format string
apvarargs list of arguments for format

Definition at line 2148 of file utils.c.

Referenced by ast_build_string().

2149 {
2150  int result;
2151 
2152  if (!buffer || !*buffer || !space || !*space)
2153  return -1;
2154 
2155  result = vsnprintf(*buffer, *space, fmt, ap);
2156 
2157  if (result < 0)
2158  return -1;
2159  else if (result > *space)
2160  result = *space;
2161 
2162  *buffer += result;
2163  *space -= result;
2164  return 0;
2165 }
int ast_check_digits ( const char *  arg)
inline

Check if a string is only digits.

Return values
1The string contains only digits
0The string contains non-digit characters

Definition at line 1216 of file strings.h.

1225 {
void ast_copy_string ( char *  dst,
const char *  src,
size_t  size 
)
inline

Size-limited null-terminating string copy.

Parameters
dstThe destination buffer.
srcThe source string
sizeThe size of the destination buffer

This is similar to strncpy, with two important differences:

  • the destination buffer will always be null-terminated
  • the destination buffer is not filled with zeros past the copied string length These differences make it slightly more efficient, and safer to use since it will not leave the destination buffer unterminated. There is no need to pass an artificially reduced buffer size to this function (unlike strncpy), and the buffer does not need to be initialized to zeroes prior to calling this function.

Definition at line 425 of file strings.h.

Referenced by __analog_handle_event(), __ast_pbx_run(), __ast_play_and_record(), __ast_sorcery_object_field_register(), acf_faxopt_read(), add_redirect(), add_to_queue(), alarmreceiver_exec(), alloc_profile(), answer_exec_enable(), apply_general_options(), apply_option(), apply_options_full(), ast_aoc_s_add_rate_duration(), ast_aoc_s_add_rate_flat(), ast_aoc_s_add_rate_volume(), ast_aoc_set_association_number(), ast_aoc_set_currency_info(), ast_app_group_split_group(), ast_apply_ha(), ast_attended_transfer_message_add_app(), ast_attended_transfer_message_add_merge(), ast_blind_transfer_message_create(), ast_bridge_dtmf_hook(), ast_bridge_features_register(), ast_bucket_alloc(), ast_bucket_file_alloc(), ast_call_forward(), ast_callerid_parse(), ast_category_new(), ast_cc_extension_monitor_add_dialstring(), ast_cc_get_param(), ast_cdr_format_var(), ast_cdr_setuserfield(), ast_channel_destructor(), ast_channel_get_cc_agent_type(), ast_channel_get_device_name(), ast_channel_internal_set_fake_ids(), ast_devstate_prov_add(), ast_escape(), ast_expr(), ast_frame_subclass2str(), ast_frame_type2str(), ast_func_read(), ast_get_enum(), ast_get_extension_data(), ast_get_hint(), ast_get_indication_zone(), ast_get_srv(), ast_get_txt(), ast_http_prefix(), ast_init_logger_for_socket_console(), ast_jb_conf_default(), ast_linear_stream(), ast_media_cache_retrieve(), ast_media_cache_retrieve_metadata(), ast_merge_contexts_and_delete(), ast_msg_data_alloc(), ast_multi_channel_blob_add_channel(), ast_presence_state_prov_add(), ast_read_image(), ast_remove_hint(), ast_rtp_ice_set_authentication(), ast_rtp_instance_set_channel_id(), ast_say_date_th(), ast_say_date_with_format_da(), ast_say_date_with_format_de(), ast_say_date_with_format_en(), ast_say_date_with_format_es(), ast_say_date_with_format_fr(), ast_say_date_with_format_gr(), ast_say_date_with_format_it(), ast_say_date_with_format_nl(), ast_say_date_with_format_pl(), ast_say_date_with_format_th(), ast_say_date_with_format_vi(), ast_say_date_with_format_zh(), ast_say_datetime_from_now_pt(), ast_say_datetime_th(), ast_say_enumeration_full_da(), ast_say_enumeration_full_de(), ast_say_enumeration_full_en(), ast_say_enumeration_full_is(), ast_say_number_full_cs(), ast_say_number_full_da(), ast_say_number_full_de(), ast_say_number_full_en_GB(), ast_say_number_full_es(), ast_say_number_full_fr(), ast_say_number_full_gr(), ast_say_number_full_hu(), ast_say_number_full_is(), ast_say_number_full_it(), ast_say_number_full_nl(), ast_say_number_full_no(), ast_say_number_full_ru(), ast_say_number_full_se(), ast_say_number_full_th(), ast_say_number_full_vi(), ast_say_number_full_zh(), ast_set_cc_agent_dialstring(), ast_set_cc_callback_sub(), ast_setstate(), ast_sip_sched_task_get_name(), ast_sorcery_alloc(), ast_sorcery_object_fields_register(), ast_to_camel_case_delim(), ast_unregister_indication_country(), ast_xmldoc_printable(), audiosocket_request(), begin_dial_channel(), blr_ebl(), bridge_agent_hold_push(), bucket_file_wizard_retrieve(), bucket_wizard_retrieve(), build_conf(), callerid_feed(), callerid_feed_jp(), callerid_read(), cdr_object_create_public_records(), cdr_object_format_property(), cdr_object_format_var_internal(), cdr_object_update_party_b_userfield_cb(), chan_pjsip_add_hold(), chan_pjsip_incoming_response_update_cause(), change_password_realtime(), channel_do_masquerade(), chararray_handler_fn(), conf_exec(), config_text_file_load(), context_table_create_autohints(), copy_error(), copy_message(), coreshowchannelmap_add_connected_channels(), create_followme_number(), create_queue_member(), create_vmaccount(), curl_header_cb(), device_state_cb(), dial_exec_full(), dns_srv_alloc(), do_forward(), dtmf_store_framehook(), ebl_callback(), find_engine(), find_queue_by_name_rt(), find_user_realtime(), forward_message(), func_get_parkingslot_channel(), grab_transfer(), handle_cli_keys_init(), hangupcause_read(), has_voicemail(), iax2_ack_registry(), iax2_exec(), inboxcount2(), init_logger_chain(), jingle_action_session_terminate(), jingle_alloc(), jingle_outgoing_hook(), jingle_request(), join_conference_bridge(), leave_voicemail(), load_config(), load_modules(), load_realtime_rules(), local_alloc(), log_events(), make_email_file(), make_filename(), mbl_load_adapter(), mbl_load_device(), message_template_parse_filebody(), minivm_accmess_exec(), minivm_account_func_read(), mkintf(), named_acl_alloc(), named_acl_find(), parse_config(), parse_naptr(), pbx_extension_helper(), pbx_load_users(), pbx_retrieve_variable(), pbx_substitute_variables_helper_full_location(), peer_status(), pjsip_acf_dial_contacts_read(), play_message_by_id(), populate_defaults(), private_enum_init(), profile_set_param(), queue_exec(), queue_function_queuegetchannel(), queue_set_param(), receive_ademco_event(), register_verify(), reload_followme(), reload_queue_rules(), reload_single_member(), remove_from_queue(), reset_user_pw(), ring_entry(), rt_handle_member_record(), set_config(), setup_privacy_args(), sig_pri_call(), sig_pri_sendtext(), sms_handleincoming(), sms_handleincoming_proto2(), sms_writefile(), sorcery_object_type_alloc(), speech_grammar(), speech_read(), speech_score(), speech_text(), stasis_app_control_continue(), store_tone_zone_ring_cadence(), substring(), term_color(), timezone_add(), try_load_key(), txt_callback(), uridecode(), vm_change_password(), wait_for_answer(), write_metadata(), xmpp_client_alloc(), xmpp_client_create_buddy(), xmpp_pak_message(), and xmpp_pak_presence().

623 {
static int force_inline attribute_pure ast_ends_with ( const char *  str,
const char *  suffix 
)
static

Checks whether a string ends with another.

Since
12.0.0
Parameters
strString to check.
suffixSuffix to look for.
Return values
1if str ends with suffix
0otherwise.

Definition at line 116 of file strings.h.

Referenced by coreshowchannelmap_add_connected_channels().

117 {
118  size_t str_len;
119  size_t suffix_len;
120 
121  ast_assert(str != NULL);
122  ast_assert(suffix != NULL);
123  str_len = strlen(str);
124  suffix_len = strlen(suffix);
125 
126  if (suffix_len > str_len) {
127  return 0;
128  }
129 
130  return strcmp(str + str_len - suffix_len, suffix) == 0;
131 }
char* ast_escape ( char *  dest,
const char *  s,
size_t  size,
const char *  to_escape 
)

Escape the 'to_escape' characters in the given string.

Note
The given output buffer will contain a truncated escaped version of the source string if the given buffer is not large enough.
Parameters
destthe escaped string
sthe source string to escape
sizeThe size of the destination buffer
to_escapean array of characters to escape
Returns
Pointer to the destination.

Definition at line 2034 of file utils.c.

References ast_copy_string().

Referenced by ast_escape_alloc().

2035 {
2036  char *p;
2037  char *c;
2038 
2039  if (!dest || !size) {
2040  return dest;
2041  }
2042  if (ast_strlen_zero(s)) {
2043  *dest = '\0';
2044  return dest;
2045  }
2046 
2047  if (ast_strlen_zero(to_escape)) {
2048  ast_copy_string(dest, s, size);
2049  return dest;
2050  }
2051 
2052  for (p = dest; *s && --size; ++s, ++p) {
2053  /* If in the list of characters to escape then escape it */
2054  if (strchr(to_escape, *s)) {
2055  if (!--size) {
2056  /* Not enough room left for the escape sequence. */
2057  break;
2058  }
2059 
2060  /*
2061  * See if the character to escape is part of the standard escape
2062  * sequences. If so we'll have to use its mapped counterpart
2063  * otherwise just use the current character.
2064  */
2065  c = strchr(escape_sequences, *s);
2066  *p++ = '\\';
2067  *p = c ? escape_sequences_map[c - escape_sequences] : *s;
2068  } else {
2069  *p = *s;
2070  }
2071  }
2072  *p = '\0';
2073 
2074  return dest;
2075 }
void ast_copy_string(char *dst, const char *src, size_t size)
Size-limited null-terminating string copy.
Definition: strings.h:425
char* ast_escape_alloc ( const char *  s,
const char *  to_escape 
)

Escape the 'to_escape' characters in the given string.

Note
Caller is responsible for freeing the returned string
Parameters
sthe source string to escape
to_escapean array of characters to escape
Returns
Pointer to the escaped string or NULL.

Definition at line 2132 of file utils.c.

References ast_escape().

2133 {
2134  size_t size = 0;
2135  char *dest = escape_alloc(s, &size);
2136 
2137  return ast_escape(dest, s, size, to_escape);
2138 }
char * ast_escape(char *dest, const char *s, size_t size, const char *to_escape)
Escape the 'to_escape' characters in the given string.
Definition: utils.c:2034
char* ast_escape_c ( char *  dest,
const char *  s,
size_t  size 
)

Escape standard 'C' sequences in the given string.

Note
The given output buffer will contain a truncated escaped version of the source string if the given buffer is not large enough.
Parameters
destthe escaped string
sthe source string to escape
sizeThe size of the destination buffer
Returns
Pointer to the escaped string.

Definition at line 2077 of file utils.c.

Referenced by ast_escape_c_alloc().

2078 {
2079  /*
2080  * Note - This is an optimized version of ast_escape. When looking only
2081  * for escape_sequences a couple of checks used in the generic case can
2082  * be left out thus making it slightly more efficient.
2083  */
2084  char *p;
2085  char *c;
2086 
2087  if (!dest || !size) {
2088  return dest;
2089  }
2090  if (ast_strlen_zero(s)) {
2091  *dest = '\0';
2092  return dest;
2093  }
2094 
2095  for (p = dest; *s && --size; ++s, ++p) {
2096  /*
2097  * See if the character to escape is part of the standard escape
2098  * sequences. If so use its mapped counterpart.
2099  */
2100  c = strchr(escape_sequences, *s);
2101  if (c) {
2102  if (!--size) {
2103  /* Not enough room left for the escape sequence. */
2104  break;
2105  }
2106 
2107  *p++ = '\\';
2108  *p = escape_sequences_map[c - escape_sequences];
2109  } else {
2110  *p = *s;
2111  }
2112  }
2113  *p = '\0';
2114 
2115  return dest;
2116 }
char* ast_escape_c_alloc ( const char *  s)

Escape standard 'C' sequences in the given string.

Note
Caller is responsible for freeing the returned string
Parameters
sthe source string to escape
Returns
Pointer to the escaped string or NULL.

Definition at line 2140 of file utils.c.

References ast_escape_c().

Referenced by ast_manager_build_channel_state_string_prefix().

2141 {
2142  size_t size = 0;
2143  char *dest = escape_alloc(s, &size);
2144 
2145  return ast_escape_c(dest, s, size);
2146 }
char * ast_escape_c(char *dest, const char *s, size_t size)
Escape standard 'C' sequences in the given string.
Definition: utils.c:2077
int attribute_pure ast_false ( const char *  val)

Make sure something is false. Determine if a string containing a boolean value is "false". This function checks to see whether a string passed to it is an indication of an "false" value. It checks to see if the string is "no", "false", "n", "f", "off" or "0".

Return values
-1if "true".
0otherwise, like NUL pointer.

Definition at line 2216 of file utils.c.

Referenced by acf_faxopt_write(), bool_handler_fn(), boolflag_handler_fn(), build_peer(), build_user(), load_config(), manager_mute_mixmonitor(), parking_feature_flag_cfg(), reload_single_member(), rt_handle_member_record(), rtp_reload(), run_agi(), set_config(), and strings_to_mask().

2217 {
2218  if (ast_strlen_zero(s))
2219  return 0;
2220 
2221  /* Determine if this is a false value */
2222  if (!strcasecmp(s, "no") ||
2223  !strcasecmp(s, "false") ||
2224  !strcasecmp(s, "n") ||
2225  !strcasecmp(s, "f") ||
2226  !strcasecmp(s, "0") ||
2227  !strcasecmp(s, "off"))
2228  return -1;
2229 
2230  return 0;
2231 }
char* ast_generate_random_string ( char *  buf,
size_t  size 
)

Create a pseudo-random string of a fixed length.

This function is useful for generating a string whose randomness does not need to be across all time and space, does not need to be cryptographically secure, and needs to fit in a limited space.

This function will write a null byte at the final position in the buffer (buf[size - 1]). So if you pass in a size of 10, then this will generate a random 9-character string.

Parameters
bufBuffer to write random string into.
sizeThe size of the buffer.
Returns
A pointer to buf

Definition at line 226 of file strings.c.

227 {
228  int i;
229 
230  for (i = 0; i < size - 1; ++i) {
231  buf[i] = 'a' + (ast_random() % 26);
232  }
233  buf[i] = '\0';
234 
235  return buf;
236 }
int ast_get_time_t ( const char *  src,
time_t *  dst,
time_t  _default,
int *  consumed 
)

Parse a time (integer) string.

Parameters
srcString to parse
dstDestination
_defaultValue to use if the string does not contain a valid time
consumedThe number of characters 'consumed' in the string by the parse (see 'man sscanf' for details)
Return values
zeroon success.
non-zeroon failure.

Parse a time (integer) string.

Definition at line 2446 of file utils.c.

Referenced by realtime_peer().

2447 {
2448  long t;
2449  int scanned;
2450 
2451  if (dst == NULL)
2452  return -1;
2453 
2454  *dst = _default;
2455 
2456  if (ast_strlen_zero(src))
2457  return -1;
2458 
2459  /* only integer at the moment, but one day we could accept more formats */
2460  if (sscanf(src, "%30ld%n", &t, &scanned) == 1) {
2461  *dst = t;
2462  if (consumed)
2463  *consumed = scanned;
2464  return 0;
2465  } else
2466  return -1;
2467 }
int ast_get_timeval ( const char *  src,
struct timeval *  dst,
struct timeval  _default,
int *  consumed 
)

Parse a time (float) string.

Parameters
srcString to parse
dstDestination
_defaultValue to use if the string does not contain a valid time
consumedThe number of characters 'consumed' in the string by the parse (see 'man sscanf' for details)
Return values
zeroon success.
non-zeroon failure.

Parse a time (float) string.

Definition at line 2419 of file utils.c.

Referenced by timeval_str2struct().

2420 {
2421  long double dtv = 0.0;
2422  int scanned;
2423 
2424  if (dst == NULL)
2425  return -1;
2426 
2427  *dst = _default;
2428 
2429  if (ast_strlen_zero(src))
2430  return -1;
2431 
2432  /* only integer at the moment, but one day we could accept more formats */
2433  if (sscanf(src, "%30Lf%n", &dtv, &scanned) > 0) {
2434  dst->tv_sec = dtv;
2435  dst->tv_usec = (dtv - dst->tv_sec) * 1000000.0;
2436  if (consumed)
2437  *consumed = scanned;
2438  return 0;
2439  } else
2440  return -1;
2441 }
int ast_in_delimited_string ( const char *  needle,
const char *  haystack,
char  delim 
)

Check if there is an exact match for 'needle' between delimiters in 'haystack'.

Note
This will skip extra leading spaces between delimiters.
Parameters
needleThe string to search for
haystackThe string searched in
delimThe haystack delimiter
Return values
trueIf an exact match for needle is in haystack.
falseotherwise

Definition at line 433 of file strings.c.

References ast_skip_blanks().

Referenced by ast_json_object_create_vars().

434 {
435  const char *end;
436  unsigned long needle_size;
437 
438  ast_assert(haystack != NULL);
439 
440  if (!needle) {
441  return 0;
442  }
443 
444  needle_size = strlen(needle);
445  haystack = ast_skip_blanks(haystack);
446 
447  while ((end = strchr(haystack, delim))) {
448  if (needle_size == end - haystack && !strncmp(haystack, needle, needle_size)) {
449  return 1;
450  }
451  haystack = ast_skip_blanks(end + 1);
452  }
453 
454  return strcmp(haystack, needle) ? 0 : -1;
455 }
char * ast_skip_blanks(const char *str)
Gets a pointer to the first non-whitespace character in a string.
Definition: strings.h:161
void ast_join_delim ( char *  s,
size_t  len,
const char *const  w[],
unsigned int  size,
char  delim 
)

Join an array of strings into a single string.

Parameters
sthe resulting string buffer
lenthe length of the result buffer, s
wan array of strings to join.
sizethe number of elements to join
delimdelimiter between elements

This function will join all of the strings in the array 'w' into a single string. It will also place 'delim' in the result buffer in between each string from 'w'.

Since
12

Definition at line 2378 of file utils.c.

2379 {
2380  int x, ofs = 0;
2381  const char *src;
2382 
2383  /* Join words into a string */
2384  if (!s)
2385  return;
2386  for (x = 0; ofs < len && x < size && w[x] ; x++) {
2387  if (x > 0)
2388  s[ofs++] = delim;
2389  for (src = w[x]; *src && ofs < len; src++)
2390  s[ofs++] = *src;
2391  }
2392  if (ofs == len)
2393  ofs--;
2394  s[ofs] = '\0';
2395 }
char* ast_read_line_from_buffer ( char **  buffer)

Read lines from a string buffer.

Since
13.18.0
Parameters
[in,out]bufferA pointer to a char * string with either Unix or Windows line endings
Returns
The "next" line
Warning
The original string and *buffer will be modified.

Both '\n' and '\r\n' are treated as single delimiters but consecutive occurrences of the delimiters are NOT considered to be a single delimiter. This preserves blank lines in the input.

macOS line endings ('\r') are not supported at this time.

Definition at line 371 of file strings.c.

372 {
373  char *start = *buffer;
374 
375  if (!buffer || !*buffer || *(*buffer) == '\0') {
376  return NULL;
377  }
378 
379  while (*(*buffer) && *(*buffer) != '\n' ) {
380  (*buffer)++;
381  }
382 
383  *(*buffer) = '\0';
384  if (*(*buffer - 1) == '\r') {
385  *(*buffer - 1) = '\0';
386  }
387  (*buffer)++;
388 
389  return start;
390 }
int ast_regex_string_to_regex_pattern ( const char *  regex_string,
struct ast_str **  regex_pattern 
)

Given a string regex_string in the form of "/regex/", convert it into the form of "regex".

This function will trim one leading / and one trailing / from a given input string ast_str regex_pattern must be preallocated before calling this function

Return values
0on success, non-zero on failure.
1if we only stripped a leading /
2if we only stripped a trailing /
3if we did not strip any / characters
Parameters
regex_stringthe string containing /regex/
regex_patternthe destination ast_str which will contain "regex" after execution

Definition at line 2179 of file utils.c.

References ast_str_set(), and ast_str_truncate().

Referenced by ast_manager_hangup_helper().

2180 {
2181  int regex_len = strlen(regex_string);
2182  int ret = 3;
2183 
2184  /* Chop off the leading / if there is one */
2185  if ((regex_len >= 1) && (regex_string[0] == '/')) {
2186  ast_str_set(regex_pattern, 0, "%s", regex_string + 1);
2187  ret -= 2;
2188  }
2189 
2190  /* Chop off the ending / if there is one */
2191  if ((regex_len > 1) && (regex_string[regex_len - 1] == '/')) {
2192  ast_str_truncate(*regex_pattern, -1);
2193  ret -= 1;
2194  }
2195 
2196  return ret;
2197 }
char * ast_str_truncate(struct ast_str *buf, ssize_t len)
Truncates the enclosed string to the given length.
Definition: strings.h:786
int ast_str_set(struct ast_str **buf, ssize_t max_len, const char *fmt,...)
Set a dynamic string using variable arguments.
Definition: strings.h:1113
char * ast_skip_blanks ( const char *  str)
inline

Gets a pointer to the first non-whitespace character in a string.

Parameters
strthe input string
Returns
a pointer to the first non-whitespace character

Definition at line 161 of file strings.h.

Referenced by __astman_get_header(), acf_faxopt_write(), add_redirect(), ast_append_acl(), ast_get_namedgroups(), ast_http_header_parse(), ast_in_delimited_string(), ast_parse_arg(), ast_parse_digest(), ast_sip_header_to_security_mechanism(), ast_skip_nonblanks(), ast_trim_blanks(), curl_header_cb(), do_say(), process_description_file(), process_text_line(), rtp_reload(), and xml_translate().

170 {
char * ast_skip_nonblanks ( const char *  str)
inline

Gets a pointer to first whitespace character in a string.

Parameters
strthe input string
Returns
a pointer to the first whitespace character

Definition at line 204 of file strings.h.

References ast_skip_blanks(), and ast_trim_blanks().

217 {
int ast_str_append ( struct ast_str **  buf,
ssize_t  max_len,
const char *  fmt,
  ... 
)
inline

Append to a thread local dynamic string.

Note
Care should be taken when using this function. The function can result in reallocating the ast_str. If a pointer to the ast_str is passed by value to a function that calls ast_str_append(), then the original ast_str pointer may be invalidated due to a reallocation.

The arguments, return values, and usage of this function are the same as ast_str_set(), but the new data is appended to the current value.

Definition at line 1139 of file strings.h.

Referenced by add_ice_to_stream(), append_var_and_value_to_filter(), ast_aoc_decoded2str(), ast_ari_channels_create(), ast_ari_recordings_get_stored_file(), ast_ari_response_created(), ast_category_get_templates(), ast_cdr_serialize_variables(), ast_get_character_str(), ast_get_digit_str(), ast_get_phonetic_str(), ast_ha_join(), ast_ha_join_cidr(), ast_json_ipaddr(), ast_log_backtrace(), ast_logger_get_channels(), ast_manager_build_bridge_state_string_prefix(), ast_manager_build_channel_state_string_prefix(), ast_odbc_print_errors(), ast_print_namedgroups(), ast_realtime_encode_chunk(), ast_rtp_lookup_mime_multiple2(), ast_sched_report(), ast_str_append_event_header(), ast_str_encode_mime(), ast_str_quote(), ast_str_substitute_variables_full2(), ast_stream_codec_prefs_parse(), ast_stream_codec_prefs_to_str(), ast_stream_create_resolved(), ast_stream_to_str(), ast_stream_topology_to_str(), ast_strings_match(), ast_term_color_code(), ast_translate_path_to_str(), ast_variable_list_join(), ast_xmldoc_printable(), astman_send_response_full(), authority_to_str(), cli_alias_passthrough(), destroy_curl(), destroy_odbc(), dump_queue_members(), generic_http_callback(), handle_missing_table(), handle_options(), handle_showchan(), load_modules(), pbx_builtin_serialize_variables(), pjsip_acf_dial_contacts_read(), print_queue(), process_cors_request(), process_description_file(), process_text_line(), prometheus_metric_to_string(), realtime_curl(), realtime_ldap_status(), realtime_multi_curl(), realtime_multi_odbc(), realtime_odbc(), realtime_sqlite3_destroy(), realtime_sqlite3_helper(), realtime_sqlite3_store(), realtime_sqlite3_update(), realtime_sqlite3_update2(), stasis_app_control_snoop(), store_curl(), store_odbc(), str_appender(), test_core_format_generate_sdp_fmtp(), update_curl(), update_odbc(), user_authority_to_str(), websocket_client_parse_uri(), and xml_translate().

1190 { \
int ast_str_append_va ( struct ast_str **  buf,
ssize_t  max_len,
const char *  fmt,
va_list  ap 
)
inline

Append to a dynamic string using a va_list.

Same as ast_str_set_va(), but append to the current content.

Note
Care should be taken when using this function. The function can result in reallocating the ast_str. If a pointer to the ast_str is passed by value to a function that calls ast_str_append_va(), then the original ast_str pointer may be invalidated due to a reallocation.
Parameters
buf,max_len,fmt,ap

Definition at line 1048 of file strings.h.

Referenced by ast_str_set().

1052 {
char * ast_str_buffer ( const struct ast_str buf)
inline

Returns the string buffer within the ast_str buf.

Parameters
bufA pointer to the ast_str structure.
Returns
A pointer to the enclosed string.

Definition at line 761 of file strings.h.

Referenced by __queues_show(), acf_odbc_write(), action_coreshowchannels(), add_hintdevice(), add_ice_to_stream(), ari_channel_thread(), ast_ari_channels_get_channel_var(), ast_cc_agent_set_interfaces_chanvar(), ast_func_read(), ast_func_read2(), ast_http_create_response(), ast_http_send(), ast_json_ipaddr(), ast_json_load_str(), ast_log_backtrace(), ast_logger_get_channels(), ast_manager_hangup_helper(), ast_odbc_ast_str_SQLGetData(), ast_parse_digest(), ast_pbx_exec_application(), ast_print_namedgroups(), ast_realtime_encode_chunk(), ast_rtp_lookup_mime_multiple2(), ast_set_cc_interfaces_chanvar(), ast_sockaddr_stringify_fmt(), ast_sounds_get_index_for_file(), ast_str_encode_mime(), ast_str_get_encoded_str(), ast_str_quote(), ast_str_retrieve_variable(), ast_str_substitute_variables_full2(), ast_stream_codec_prefs_to_str(), ast_stream_create_resolved(), ast_stream_to_str(), ast_stream_topology_to_str(), ast_strings_match(), ast_translate_path_to_str(), ast_xmldoc_printable(), ast_xmldoc_query(), astman_append(), astman_send_error_va(), authority_to_str(), channel_dial_cb(), cli_alias_passthrough(), config_text_file_load(), dahdi_cc_callback(), destroy_curl(), destroy_odbc(), dump_queue_members(), get_languages(), handle_cli_iax2_show_peer(), handle_exec(), handle_missing_table(), handle_options(), handle_showchan(), leave_voicemail(), load_modules(), make_email_file(), manager_build_parked_call_string(), mwi_app_event_cb(), parking_lot_cfg_create_extensions(), pbx_retrieve_variable(), pjsip_acf_dial_contacts_read(), print_queue(), process_description_file(), process_text_line(), realtime_curl(), realtime_ldap_base_ap(), realtime_ldap_status(), realtime_multi_curl(), realtime_multi_odbc(), realtime_odbc(), realtime_sqlite3_destroy(), realtime_sqlite3_helper(), realtime_sqlite3_store(), realtime_sqlite3_update(), realtime_sqlite3_update2(), say_periodic_announcement(), snoop_stasis_thread(), store_curl(), store_odbc(), str_appender(), update2_odbc(), update_curl(), update_odbc(), and user_authority_to_str().

773 {
static force_inline int attribute_pure ast_str_case_hash ( const char *  str)
static

Compute a hash value on a case-insensitive string.

Uses the same hash algorithm as ast_str_hash, but converts all characters to lowercase prior to computing a hash. This allows for easy case-insensitive lookups in a hash table.

Examples:
app_skel.c.

Definition at line 1303 of file strings.h.

References ast_str_hash_restrict().

Referenced by autohint_hash_cb(), conference_bridge_hash_cb(), hintdevice_hash_cb(), protocol_hash_fn(), and tps_hash_cb().

1304 {
1305  unsigned int hash = 5381;
1306 
1307  while (*str) {
1308  hash = hash * 33 ^ (unsigned char) tolower(*str++);
1309  }
1310 
1311  return ast_str_hash_restrict(hash);
1312 }
static force_inline int attribute_pure ast_str_hash_restrict(unsigned int hash)
Restrict hash value range.
Definition: strings.h:1246
int ast_str_container_add ( struct ao2_container str_container,
const char *  add 
)

Adds a string to a string container allocated by ast_str_container_alloc.

Since
12
Parameters
str_containerThe container to which to add a string
addThe string to add to the container
Return values
zeroon success
non-zeroif the operation failed

Definition at line 205 of file strings.c.

References AO2_ALLOC_OPT_LOCK_NOLOCK, ao2_link, and ao2_ref.

Referenced by add_media_cb(), add_variant_cb(), ast_bridge_snapshot_create(), ast_dns_get_nameservers(), ast_endpoint_add_channel(), coreshowchannelmap_add_to_map(), event_session_alloc(), get_languages(), test_cel_peer_strings_match(), and topic_add_subscription().

206 {
207  char *ao2_add;
208 
209  /* The ao2_add object is immutable so it doesn't need a lock of its own. */
210  ao2_add = ao2_alloc_options(strlen(add) + 1, NULL, AO2_ALLOC_OPT_LOCK_NOLOCK);
211  if (!ao2_add) {
212  return -1;
213  }
214  strcpy(ao2_add, add);/* Safe */
215 
216  ao2_link(str_container, ao2_add);
217  ao2_ref(ao2_add, -1);
218  return 0;
219 }
#define ao2_ref(o, delta)
Reference/unreference an object and return the old refcount.
Definition: astobj2.h:459
#define ao2_link(container, obj)
Add an object to a container.
Definition: astobj2.h:1532
struct ao2_container* ast_str_container_alloc_options ( enum ao2_alloc_opts  opts,
int  buckets 
)

Allocates a hash container for bare strings.

Since
12
Parameters
optsOptions to be provided to the container
bucketsThe number of buckets to use for the hash container
Returns
AO2 container for strings
Return values
NULLif allocation failed

Definition at line 200 of file strings.c.

References ao2_container_alloc_hash.

Referenced by action_coreshowchannelmap(), and ast_dns_get_nameservers().

201 {
202  return ao2_container_alloc_hash(opts, 0, buckets, str_hash, str_sort, str_cmp);
203 }
#define ao2_container_alloc_hash(ao2_options, container_options, n_buckets, hash_fn, sort_fn, cmp_fn)
Allocate and initialize a hash container with the desired number of buckets.
Definition: astobj2.h:1303
void ast_str_container_remove ( struct ao2_container str_container,
const char *  remove 
)

Removes a string from a string container allocated by ast_str_container_alloc.

Since
12
Parameters
str_containerThe container from which to remove a string
removeThe string to remove from the container

Definition at line 221 of file strings.c.

References OBJ_NODATA, OBJ_SEARCH_KEY, and OBJ_UNLINK.

Referenced by endpoint_cache_clear(), and test_cel_peer_strings_match().

222 {
223  ao2_find(str_container, remove, OBJ_SEARCH_KEY | OBJ_NODATA | OBJ_UNLINK);
224 }
The arg parameter is a search key, but is not an object.
Definition: astobj2.h:1101
static force_inline int attribute_pure ast_str_hash ( const char *  str)
static

Compute a hash value on a string.

This famous hash algorithm was written by Dan Bernstein and is commonly used.

http://www.cse.yorku.ca/~oz/hash.html

Definition at line 1259 of file strings.h.

References ast_str_hash_restrict().

Referenced by alias_hash_cb(), app_hash(), ast_event_append_ie_str(), ast_get_namedgroups(), ast_sorcery_object_id_hash(), bridges_channel_hash_fn(), bridges_hash(), control_hash(), event_session_hash(), jingle_add_ice_udp_candidates_to_transport(), jingle_endpoint_hash(), jingle_session_hash(), message_subscription_hash_cb(), peer_hash_cb(), pvt_cause_hash_fn(), sorcery_memory_hash(), uid_hold_hash_fn(), user_hash_cb(), and xmpp_buddy_hash().

1260 {
1261  unsigned int hash = 5381;
1262 
1263  while (*str) {
1264  hash = hash * 33 ^ (unsigned char) *str++;
1265  }
1266 
1267  return ast_str_hash_restrict(hash);
1268 }
static force_inline int attribute_pure ast_str_hash_restrict(unsigned int hash)
Restrict hash value range.
Definition: strings.h:1246
static force_inline int ast_str_hash_add ( const char *  str,
int  seed 
)
static

Compute a hash value on a string.

Parameters
[in]strThe string to add to the hash
[in]seedThe hash value to start with

This version of the function is for when you need to compute a string hash of more than one string.

This famous hash algorithm was written by Dan Bernstein and is commonly used.

See also
http://www.cse.yorku.ca/~oz/hash.html

Definition at line 1285 of file strings.h.

References ast_str_hash_restrict().

1286 {
1287  unsigned int hash = (unsigned int) seed;
1288 
1289  while (*str) {
1290  hash = hash * 33 ^ (unsigned char) *str++;
1291  }
1292 
1293  return ast_str_hash_restrict(hash);
1294 }
static force_inline int attribute_pure ast_str_hash_restrict(unsigned int hash)
Restrict hash value range.
Definition: strings.h:1246
static force_inline int attribute_pure ast_str_hash_restrict ( unsigned int  hash)
static

Restrict hash value range.

Hash values used all over asterisk are expected to be non-negative (signed) int values. This function restricts an unsigned int hash value to the positive half of the (signed) int values.

Definition at line 1246 of file strings.h.

Referenced by ast_sip_get_distributor_serializer(), ast_str_case_hash(), ast_str_hash(), and ast_str_hash_add().

1247 {
1248  return (int) (hash & (unsigned int) INT_MAX);
1249 }
int ast_str_set ( struct ast_str **  buf,
ssize_t  max_len,
const char *  fmt,
  ... 
)
inline

Set a dynamic string using variable arguments.

Note
Care should be taken when using this function. The function can result in reallocating the ast_str. If a pointer to the ast_str is passed by value to a function that calls ast_str_set(), then the original ast_str pointer may be invalidated due to a reallocation.
Parameters
bufThis is the address of a pointer to a struct ast_str which should have been retrieved using ast_str_thread_get. It will need to be updated in the case that the buffer has to be reallocated to accomodate a longer string than what it currently has space for.
max_lenThis is the maximum length to allow the string buffer to grow to. If this is set to 0, then there is no maximum length. If set to -1, we are bound to the current maximum length.
fmtThis is the format string (printf style)
Returns
The return value of this function is the same as that of the printf family of functions.

All the rest is the same as ast_str_set_va()

Definition at line 1113 of file strings.h.

References ast_str_append_va().

Referenced by __queues_show(), add_hintdevice(), add_ice_to_stream(), ast_extension_state2(), ast_http_auth(), ast_http_create_response(), ast_http_error(), ast_http_send(), ast_json_ipaddr(), ast_manager_build_bridge_state_string_prefix(), ast_manager_build_channel_state_string_prefix(), ast_parse_digest(), ast_realtime_encode_chunk(), ast_regex_string_to_regex_pattern(), ast_sched_report(), ast_sockaddr_stringify_fmt(), ast_sounds_get_index_for_file(), ast_str_encode_mime(), ast_str_expr(), ast_str_get_encoded_str(), ast_str_get_hint(), ast_str_quote(), ast_str_retrieve_variable(), ast_stream_create_resolved(), ast_strings_match(), ast_xmldoc_regenerate_doc_item(), astman_send_response_full(), destroy_curl(), destroy_odbc(), get_languages(), handle_missing_table(), init_queue(), leave_voicemail(), make_email_file(), manager_build_parked_call_string(), parking_lot_cfg_create_extensions(), print_queue(), process_description_file(), process_text_line(), queue_set_param(), realtime_curl(), realtime_multi_curl(), realtime_multi_odbc(), realtime_odbc(), realtime_sqlite3_destroy(), realtime_sqlite3_helper(), realtime_sqlite3_store(), realtime_sqlite3_update(), realtime_sqlite3_update2(), stasis_app_control_snoop(), store_curl(), store_odbc(), update_curl(), update_odbc(), and websocket_client_parse_uri().

1129 {
int ast_str_set_va ( struct ast_str **  buf,
ssize_t  max_len,
const char *  fmt,
va_list  ap 
)
inline

Set a dynamic string from a va_list.

Parameters
bufThis is the address of a pointer to a struct ast_str. If it is retrieved using ast_str_thread_get, the struct ast_threadstorage pointer will need to be updated in the case that the buffer has to be reallocated to accommodate a longer string than what it currently has space for.
max_lenThis is the maximum length to allow the string buffer to grow to. If this is set to 0, then there is no maximum length.
fmtThis is the format string (printf style)
apThis is the va_list
Returns
The return value of this function is the same as that of the printf family of functions.

Example usage (the first part is only for thread-local storage)

1 AST_THREADSTORAGE(my_str, my_str_init);
2 #define MY_STR_INIT_SIZE 128
3 ...
4 void my_func(const char *fmt, ...)
5 {
6  struct ast_str *buf;
7  va_list ap;
8 
9  if (!(buf = ast_str_thread_get(&my_str, MY_STR_INIT_SIZE)))
10  return;
11  ...
12  va_start(fmt, ap);
13  ast_str_set_va(&buf, 0, fmt, ap);
14  va_end(ap);
15 
16  printf("This is the string we just built: %s\n", buf->str);
17  ...
18 }
Note
Care should be taken when using this function. The function can result in reallocating the ast_str. If a pointer to the ast_str is passed by value to a function that calls ast_str_set_va(), then the original ast_str pointer may be invalidated due to a reallocation.

Definition at line 1030 of file strings.h.

Referenced by ast_str_append_escapecommas(), ast_xmldoc_query(), astman_append(), and astman_send_error_va().

1045 {
size_t ast_str_size ( const struct ast_str buf)
inline

Returns the current maximum length (without reallocation) of the current buffer.

Parameters
bufA pointer to the ast_str structure.
Returns
Current maximum length of the buffer.

Definition at line 742 of file strings.h.

Referenced by ast_func_read(), ast_func_read2(), ast_odbc_ast_str_SQLGetData(), ast_str_get_encoded_str(), realtime_multi_odbc(), and realtime_odbc().

751 {
size_t ast_str_strlen ( const struct ast_str buf)
inline
struct ast_str * ast_str_thread_get ( struct ast_threadstorage ts,
size_t  init_len 
)

Retrieve a thread locally stored dynamic string.

Parameters
tsThis is a pointer to the thread storage structure declared by using the AST_THREADSTORAGE macro. If declared with AST_THREADSTORAGE(my_buf, my_buf_init), then this argument would be (&my_buf).
init_lenThis is the initial length of the thread's dynamic string. The current length may be bigger if previous operations in this thread have caused it to increase.
Returns
This function will return the thread locally stored dynamic string associated with the thread storage management variable passed as the first argument. The result will be NULL in the case of a memory allocation error.

Example usage:

1 AST_THREADSTORAGE(my_str, my_str_init);
2 #define MY_STR_INIT_SIZE 128
3 ...
4 void my_func(const char *fmt, ...)
5 {
6  struct ast_str *buf;
7 
8  if (!(buf = ast_str_thread_get(&my_str, MY_STR_INIT_SIZE)))
9  return;
10  ...
11 }

Definition at line 909 of file strings.h.

References ast_str::__AST_STR_LEN, ast_str::__AST_STR_TS, and ast_str::__AST_STR_USED.

Referenced by acf_odbc_write(), add_hintdevice(), ast_extension_state2(), ast_odbc_print_errors(), ast_sockaddr_stringify_fmt(), astman_append(), astman_send_error_va(), astman_send_response_full(), destroy_curl(), destroy_odbc(), handle_showchan(), realtime_curl(), realtime_multi_curl(), realtime_multi_odbc(), realtime_odbc(), store_curl(), store_odbc(), update2_odbc(), update_curl(), and update_odbc().

914 {
static force_inline char* ast_str_to_lower ( char *  str)
static

Convert a string to all lower-case.

Parameters
strThe string to be converted to lower case
Return values
strthe char* passed in for convenience

Definition at line 1321 of file strings.h.

Referenced by ast_ari_endpoints_refer_to_endpoint(), ast_ari_endpoints_send_message_to_endpoint(), and ast_uuid_to_str().

1322 {
1323  char *str_orig = str;
1324  if (!str) {
1325  return str;
1326  }
1327 
1328  for (; *str; ++str) {
1329  *str = tolower(*str);
1330  }
1331 
1332  return str_orig;
1333 }
static force_inline char* ast_str_to_upper ( char *  str)
static

Convert a string to all upper-case.

Parameters
strThe string to be converted to upper case
Return values
strthe char* passed in for convenience

Definition at line 1342 of file strings.h.

Referenced by ast_rtp_engine_load_format().

1343 {
1344  char *str_orig = str;
1345  if (!str) {
1346  return str;
1347  }
1348 
1349  for (; *str; ++str) {
1350  *str = toupper(*str);
1351  }
1352 
1353  return str_orig;
1354 }
void ast_str_trim_blanks ( struct ast_str buf)
inline

Trims trailing whitespace characters from an ast_str string.

Parameters
bufA pointer to the ast_str string.

Definition at line 719 of file strings.h.

Referenced by process_text_line().

727 {
char * ast_str_truncate ( struct ast_str buf,
ssize_t  len 
)
inline

Truncates the enclosed string to the given length.

Parameters
bufA pointer to the ast_str structure.
lenMaximum length of the string. If len is larger than the current maximum length, things will explode. If it is negative at most -len characters will be trimmed off the end.
Returns
A pointer to the resulting string.

Definition at line 786 of file strings.h.

References ast_str::__AST_STR_LEN.

Referenced by ast_regex_string_to_regex_pattern(), and pjsip_acf_dial_contacts_read().

807 {
void ast_str_update ( struct ast_str buf)
inline

Update the length of the buffer, after using ast_str merely as a buffer.

Parameters
bufA pointer to the ast_str string.

Definition at line 703 of file strings.h.

Referenced by ast_func_read2(), ast_odbc_ast_str_SQLGetData(), ast_str_get_encoded_str(), realtime_multi_odbc(), and realtime_odbc().

711 {
int ast_strings_equal ( const char *  str1,
const char *  str2 
)

Compare strings for equality checking for NULL.

Since
16.3.0

This function considers NULL values as non-strings, thus a false condition. This means that it will return false if one, or both of the given values are NULL (i.e. two NULLs are not equal strings).

Parameters
str1The string to compare to str2
str2The string to compare to str1
Return values
trueif valid strings and equal.
falseotherwise.

Definition at line 238 of file strings.c.

239 {
240  if (!str1 || !str2) {
241  return 0;
242  }
243 
244  return str1 == str2 || !strcmp(str1, str2);
245 }
int ast_strings_match ( const char *  left,
const char *  op,
const char *  right 
)

Compares 2 strings using realtime-style operators.

Since
13.9.0
Parameters
leftThe left side of the equation
opThe operator to apply
rightThe right side of the equation
Return values
1matches
0doesn't match

Operators: "=", "!=", "<", "<=", ">", ">=": If both left and right can be converted to float, then they will be compared as such. Otherwise the result will be derived from strcmp(left, right). "regex": The right value will be compiled as a regular expression and matched against the left value. "like": Any '' character in the right value will be converted to '.*' and the resulting string will be handled as a regex. NULL , "": If the right value starts and ends with a '/' then it will be processed as a regex. Otherwise, same as "=".

Definition at line 247 of file strings.c.

References ast_str_append(), ast_str_buffer(), ast_str_set(), and ast_strdupa.

Referenced by ast_variables_match().

248 {
249  char *internal_op = (char *)op;
250  char *internal_right = (char *)right;
251  double left_num;
252  double right_num;
253  int scan_numeric = 0;
254 
255  if (!(left && right)) {
256  return 0;
257  }
258 
259  if (ast_strlen_zero(op)) {
260  if (ast_strlen_zero(left) && ast_strlen_zero(right)) {
261  return 1;
262  }
263 
264  if (strlen(right) >= 2 && right[0] == '/' && right[strlen(right) - 1] == '/') {
265  internal_op = "regex";
266  internal_right = ast_strdupa(right);
267  /* strip the leading and trailing '/' */
268  internal_right++;
269  internal_right[strlen(internal_right) - 1] = '\0';
270  goto regex;
271  } else {
272  internal_op = "=";
273  goto equals;
274  }
275  }
276 
277  if (!strcasecmp(op, "like")) {
278  char *tok;
279  struct ast_str *buffer = ast_str_alloca(128);
280 
281  if (!strchr(right, '%')) {
282  return !strcmp(left, right);
283  } else {
284  internal_op = "regex";
285  internal_right = ast_strdupa(right);
286  tok = strsep(&internal_right, "%");
287  ast_str_set(&buffer, 0, "^%s", tok);
288 
289  while ((tok = strsep(&internal_right, "%"))) {
290  ast_str_append(&buffer, 0, ".*%s", tok);
291  }
292  ast_str_append(&buffer, 0, "%s", "$");
293 
294  internal_right = ast_str_buffer(buffer);
295  /* fall through to regex */
296  }
297  }
298 
299 regex:
300  if (!strcasecmp(internal_op, "regex")) {
301  regex_t expression;
302  int rc;
303 
304  if (regcomp(&expression, internal_right, REG_EXTENDED | REG_NOSUB)) {
305  return 0;
306  }
307 
308  rc = regexec(&expression, left, 0, NULL, 0);
309  regfree(&expression);
310  return !rc;
311  }
312 
313 equals:
314  scan_numeric = (sscanf(left, "%lf", &left_num) > 0 && sscanf(internal_right, "%lf", &right_num) > 0);
315 
316  if (internal_op[0] == '=') {
317  if (ast_strlen_zero(left) && ast_strlen_zero(internal_right)) {
318  return 1;
319  }
320 
321  if (scan_numeric) {
322  return (left_num == right_num);
323  } else {
324  return (!strcmp(left, internal_right));
325  }
326  }
327 
328  if (internal_op[0] == '!' && internal_op[1] == '=') {
329  if (scan_numeric) {
330  return (left_num != right_num);
331  } else {
332  return !!strcmp(left, internal_right);
333  }
334  }
335 
336  if (internal_op[0] == '<') {
337  if (scan_numeric) {
338  if (internal_op[1] == '=') {
339  return (left_num <= right_num);
340  } else {
341  return (left_num < right_num);
342  }
343  } else {
344  if (internal_op[1] == '=') {
345  return strcmp(left, internal_right) <= 0;
346  } else {
347  return strcmp(left, internal_right) < 0;
348  }
349  }
350  }
351 
352  if (internal_op[0] == '>') {
353  if (scan_numeric) {
354  if (internal_op[1] == '=') {
355  return (left_num >= right_num);
356  } else {
357  return (left_num > right_num);
358  }
359  } else {
360  if (internal_op[1] == '=') {
361  return strcmp(left, internal_right) >= 0;
362  } else {
363  return strcmp(left, internal_right) > 0;
364  }
365  }
366  }
367 
368  return 0;
369 }
char * ast_str_buffer(const struct ast_str *buf)
Returns the string buffer within the ast_str buf.
Definition: strings.h:761
int ast_str_append(struct ast_str **buf, ssize_t max_len, const char *fmt,...)
Append to a thread local dynamic string.
Definition: strings.h:1139
int ast_str_set(struct ast_str **buf, ssize_t max_len, const char *fmt,...)
Set a dynamic string using variable arguments.
Definition: strings.h:1113
#define ast_strdupa(s)
duplicate a string in memory from the stack
Definition: astmm.h:298
Support for dynamic strings.
Definition: strings.h:623
char * ast_strip ( char *  s)
inline

Strip leading/trailing whitespace from a string.

Parameters
sThe string to be stripped (will be modified).
Returns
The stripped string.

This functions strips all leading and trailing whitespace characters from the input string, and returns a pointer to the resulting string. The string is modified in place.

Definition at line 223 of file strings.h.

Referenced by aqm_exec(), ast_ari_channels_create(), ast_callerid_parse(), ast_format_cap_update_by_allow_disallow(), ast_get_namedgroups(), ast_playtones_start(), ast_strip_quoted(), ast_strsep(), ast_strsep_quoted(), ast_variable_list_from_quoted_string(), ast_vector_string_split(), build_calendar(), build_profile(), config_text_file_load(), dial_exec_full(), function_amiclient(), pjsip_acf_dial_contacts_read(), process_text_line(), realtime_multi_odbc(), realtime_odbc(), reload_single_member(), restrictedFile(), and store_tone_zone_ring_cadence().

254 {
char* ast_strip_quoted ( char *  s,
const char *  beg_quotes,
const char *  end_quotes 
)

Strip leading/trailing whitespace and quotes from a string.

Parameters
sThe string to be stripped (will be modified).
beg_quotesThe list of possible beginning quote characters.
end_quotesThe list of matching ending quote characters.
Returns
The stripped string.

This functions strips all leading and trailing whitespace characters from the input string, and returns a pointer to the resulting string. The string is modified in place.

It can also remove beginning and ending quote (or quote-like) characters, in matching pairs. If the first character of the string matches any character in beg_quotes, and the last character of the string is the matching character in end_quotes, then they are removed from the string.

Examples:

1 ast_strip_quoted(buf, "\"", "\"");
2 ast_strip_quoted(buf, "'", "'");
3 ast_strip_quoted(buf, "[{(", "]})");

Definition at line 1818 of file utils.c.

References ast_strip().

Referenced by ast_callerid_parse(), ast_strsep(), ast_strsep_quoted(), hfp_parse_clip(), and parse_dial_string().

1819 {
1820  char *e;
1821  char *q;
1822 
1823  s = ast_strip(s);
1824  if ((q = strchr(beg_quotes, *s)) && *q != '\0') {
1825  e = s + strlen(s) - 1;
1826  if (*e == *(end_quotes + (q - beg_quotes))) {
1827  s++;
1828  *e = '\0';
1829  }
1830  }
1831 
1832  return s;
1833 }
char * ast_strip(char *s)
Strip leading/trailing whitespace from a string.
Definition: strings.h:223
char* ast_strsep ( char **  s,
const char  sep,
uint32_t  flags 
)

Act like strsep but ignore separators inside quotes.

Parameters
sPointer to address of the string to be processed. Will be modified and can't be constant.
sepA single character delimiter.
flagsControls post-processing of the result. AST_STRSEP_TRIM trims all leading and trailing whitespace from the result. If the result containes only whitespace, it'll be passed through unchanged. AST_STRSEP_STRIP does a trim then strips the outermost quotes. You may want to trim again after the strip. Just OR both the TRIM and STRIP flags. AST_STRSEP_UNESCAPE unescapes '\' sequences. AST_STRSEP_ALL does all of the above processing.
Returns
The next token or NULL if done or if there are more than 8 levels of nested quotes. If provided an empty string, will return the empty string.

This function acts like strsep with three exceptions... The separator is a single character instead of a string. Separators inside quotes are treated literally instead of like separators. You can elect to have leading and trailing whitespace and quotes stripped from the result and have '\' sequences unescaped.

Like strsep, ast_strsep maintains no internal state and you can call it recursively using different separators on the same storage.

Also like strsep, for consistent results, consecutive separators are not collapsed so you may get an empty string as a valid result.

Examples:

1 char *mystr = ast_strdupa("abc=def,ghi='zzz=yyy,456',jkl");
2 char *token, *token2, *token3;
3 
4 while((token = ast_strsep(&mystr, ',', AST_STRSEP_STRIP))) {
5  // 1st token will be aaa=def
6  // 2nd token will be ghi='zzz=yyy,456'
7  while((token2 = ast_strsep(&token, '=', AST_STRSEP_STRIP))) {
8  // 1st token2 will be ghi
9  // 2nd token2 will be zzz=yyy,456
10  while((token3 = ast_strsep(&token2, ',', AST_STRSEP_STRIP))) {
11  // 1st token3 will be zzz=yyy
12  // 2nd token3 will be 456
13  // and so on
14  }
15  }
16  // 3rd token will be jkl
17 }
Examples:
app_skel.c.

Definition at line 1835 of file utils.c.

References ast_strip(), ast_strip_quoted(), AST_STRSEP_STRIP, AST_STRSEP_TRIM, AST_STRSEP_UNESCAPE, and ast_unescape_quoted().

Referenced by ast_app_getdata_terminator(), ast_sip_header_to_security_mechanism(), ast_sip_security_mechanism_vector_init(), ast_sip_str_to_security_mechanism(), does_category_match(), handle_updates(), and speech_background().

1836 {
1837  char *st = *iss;
1838  char *is;
1839  int inquote = 0;
1840  int found = 0;
1841  char stack[8];
1842 
1843  if (ast_strlen_zero(st)) {
1844  *iss = NULL;
1845  return st;
1846  }
1847 
1848  memset(stack, 0, sizeof(stack));
1849 
1850  for(is = st; *is; is++) {
1851  if (*is == '\\') {
1852  if (*++is != '\0') {
1853  is++;
1854  } else {
1855  break;
1856  }
1857  }
1858 
1859  if (*is == '\'' || *is == '"') {
1860  if (*is == stack[inquote]) {
1861  stack[inquote--] = '\0';
1862  } else {
1863  if (++inquote >= sizeof(stack)) {
1864  return NULL;
1865  }
1866  stack[inquote] = *is;
1867  }
1868  }
1869 
1870  if (*is == sep && !inquote) {
1871  *is = '\0';
1872  found = 1;
1873  *iss = is + 1;
1874  break;
1875  }
1876  }
1877  if (!found) {
1878  *iss = NULL;
1879  }
1880 
1881  if (flags & AST_STRSEP_STRIP) {
1882  st = ast_strip_quoted(st, "'\"", "'\"");
1883  }
1884 
1885  if (flags & AST_STRSEP_TRIM) {
1886  char *trimmed = ast_strip(st);
1887  if (!ast_strlen_zero(trimmed)) {
1888  st = trimmed;
1889  }
1890  }
1891 
1892  if (flags & AST_STRSEP_UNESCAPE) {
1893  ast_unescape_quoted(st);
1894  }
1895 
1896  return st;
1897 }
char * ast_strip_quoted(char *s, const char *beg_quotes, const char *end_quotes)
Strip leading/trailing whitespace and quotes from a string.
Definition: utils.c:1818
char * ast_strip(char *s)
Strip leading/trailing whitespace from a string.
Definition: strings.h:223
void ast_unescape_quoted(char *quote_str)
Unescape quotes in a string.
Definition: utils.c:842
char* ast_strsep_quoted ( char **  s,
const char  sep,
const char  quote,
uint32_t  flags 
)

Like ast_strsep() except you can specify a specific quote character.

Parameters
sPointer to address of the string to be processed. Will be modified and can't be constant.
sepA single character delimiter.
quoteThe quote character
flagsControls post-processing of the result. AST_STRSEP_TRIM trims all leading and trailing whitespace from the result. AST_STRSEP_STRIP does a trim then strips the outermost quotes. You may want to trim again after the strip. Just OR both the TRIM and STRIP flags. AST_STRSEP_UNESCAPE unescapes '\' sequences. AST_STRSEP_ALL does all of the above processing.
Returns
The next token or NULL if done or if there are more than 8 levels of nested quotes. If provided an empty string, will return the empty string.

Definition at line 1899 of file utils.c.

References ast_strip(), ast_strip_quoted(), AST_STRSEP_STRIP, AST_STRSEP_TRIM, AST_STRSEP_UNESCAPE, and ast_unescape_quoted().

Referenced by ast_variable_list_from_quoted_string().

1900 {
1901  char *st = *iss;
1902  char *is;
1903  int inquote = 0;
1904  int found = 0;
1905  char stack[8];
1906  const char qstr[] = { quote };
1907 
1908  if (ast_strlen_zero(st)) {
1909  *iss = NULL;
1910  return st;
1911  }
1912 
1913  memset(stack, 0, sizeof(stack));
1914 
1915  for(is = st; *is; is++) {
1916  if (*is == '\\') {
1917  if (*++is != '\0') {
1918  is++;
1919  } else {
1920  break;
1921  }
1922  }
1923 
1924  if (*is == quote) {
1925  if (*is == stack[inquote]) {
1926  stack[inquote--] = '\0';
1927  } else {
1928  if (++inquote >= sizeof(stack)) {
1929  return NULL;
1930  }
1931  stack[inquote] = *is;
1932  }
1933  }
1934 
1935  if (*is == sep && !inquote) {
1936  *is = '\0';
1937  found = 1;
1938  *iss = is + 1;
1939  break;
1940  }
1941  }
1942  if (!found) {
1943  *iss = NULL;
1944  }
1945 
1946  if (flags & AST_STRSEP_STRIP) {
1947  st = ast_strip_quoted(st, qstr, qstr);
1948  }
1949 
1950  if (flags & AST_STRSEP_TRIM) {
1951  char *trimmed = ast_strip(st);
1952  if (!ast_strlen_zero(trimmed)) {
1953  st = trimmed;
1954  }
1955  }
1956 
1957  if (flags & AST_STRSEP_UNESCAPE) {
1958  ast_unescape_quoted(st);
1959  }
1960 
1961  return st;
1962 }
char * ast_strip_quoted(char *s, const char *beg_quotes, const char *end_quotes)
Strip leading/trailing whitespace and quotes from a string.
Definition: utils.c:1818
char * ast_strip(char *s)
Strip leading/trailing whitespace from a string.
Definition: strings.h:223
void ast_unescape_quoted(char *quote_str)
Unescape quotes in a string.
Definition: utils.c:842
char * ast_tech_to_upper ( char *  dev_str)
inline

Convert the tech portion of a device string to upper case.

Return values
dev_strthe char* passed in for convenience

Definition at line 1236 of file strings.h.

Referenced by ast_endpoint_latest_snapshot(), pvt_cause_cmp_fn(), and pvt_cause_hash_fn().

1247 {
char* ast_to_camel_case_delim ( const char *  s,
const char *  delim 
)

Attempts to convert the given string to camel case using the specified delimiter.

note - returned string needs to be freed

Parameters
sthe string to convert
delimdelimiter to parse out
Returns
The string converted to "CamelCase"
Since
12

Definition at line 2397 of file utils.c.

References ast_copy_string(), and ast_strdup.

2398 {
2399  char *res = ast_strdup(s);
2400  char *front, *back, *buf = res;
2401  int size;
2402 
2403  front = strtok_r(buf, delim, &back);
2404 
2405  while (front) {
2406  size = strlen(front);
2407  *front = toupper(*front);
2408  ast_copy_string(buf, front, size + 1);
2409  buf += size;
2410  front = strtok_r(NULL, delim, &back);
2411  }
2412 
2413  return res;
2414 }
#define ast_strdup(str)
A wrapper for strdup()
Definition: astmm.h:241
void ast_copy_string(char *dst, const char *src, size_t size)
Size-limited null-terminating string copy.
Definition: strings.h:425
char * ast_trim_blanks ( char *  str)
inline

Trims trailing whitespace characters from a string.

Parameters
strthe input string
Returns
a pointer to the modified string

Definition at line 186 of file strings.h.

Referenced by ast_get_namedgroups(), ast_http_header_parse(), ast_skip_nonblanks(), curl_header_cb(), do_say(), process_description_file(), and xml_translate().

195 {
int attribute_pure ast_true ( const char *  val)

Make sure something is true. Determine if a string containing a boolean value is "true". This function checks to see whether a string passed to it is an indication of an "true" value. It checks to see if the string is "yes", "true", "y", "t", "on" or "1".

Return values
-1if "true".
0otherwise, like NULL pointer.
Examples:
app_skel.c.

Definition at line 2199 of file utils.c.

Referenced by acf_faxopt_write(), action_status(), apply_general_options(), apply_option(), ast_ari_bridges_add_channel_cb(), ast_ari_bridges_record_cb(), ast_ari_channels_record_cb(), ast_ari_endpoints_refer_cb(), ast_ari_endpoints_refer_to_endpoint_cb(), ast_bridge_timelimit(), ast_jb_read_conf(), ast_rtp_dtls_cfg_parse(), ast_tls_read_conf(), bool_handler_fn(), boolflag_handler_fn(), build_calendar(), build_peer(), build_user(), custom_bitfield_handler(), encoding_format_handler(), func_mute_write(), init_logger_chain(), is_variable_true(), load_config(), manager_mute_mixmonitor(), mbl_load_adapter(), mbl_load_device(), new_realtime_sqlite3_db(), pbx_load_users(), permit_dtmf_interrupt(), pjsip_acf_moh_passthrough_write(), profile_set_param(), queue_rules_set_global_params(), queue_set_global_params(), queue_set_param(), reload_followme(), reload_single_member(), rt_handle_member_record(), rtp_reload(), run_agi(), set_config(), and strings_to_mask().

2200 {
2201  if (ast_strlen_zero(s))
2202  return 0;
2203 
2204  /* Determine if this is a true value */
2205  if (!strcasecmp(s, "yes") ||
2206  !strcasecmp(s, "true") ||
2207  !strcasecmp(s, "y") ||
2208  !strcasecmp(s, "t") ||
2209  !strcasecmp(s, "1") ||
2210  !strcasecmp(s, "on"))
2211  return -1;
2212 
2213  return 0;
2214 }
char* ast_unescape_c ( char *  s)

Convert some C escape sequences.

(\b\f\n\r\t) 

into the equivalent characters. The string to be converted (will be modified).

Returns
The converted string.

Definition at line 1983 of file utils.c.

Referenced by ast_parse_digest().

1984 {
1985  char c, *ret, *dst;
1986 
1987  if (src == NULL)
1988  return NULL;
1989  for (ret = dst = src; (c = *src++); *dst++ = c ) {
1990  if (c != '\\')
1991  continue; /* copy char at the end of the loop */
1992  switch ((c = *src++)) {
1993  case '\0': /* special, trailing '\' */
1994  c = '\\';
1995  break;
1996  case 'b': /* backspace */
1997  c = '\b';
1998  break;
1999  case 'f': /* form feed */
2000  c = '\f';
2001  break;
2002  case 'n':
2003  c = '\n';
2004  break;
2005  case 'r':
2006  c = '\r';
2007  break;
2008  case 't':
2009  c = '\t';
2010  break;
2011  }
2012  /* default, use the char literally */
2013  }
2014  *dst = '\0';
2015  return ret;
2016 }
char* ast_unescape_semicolon ( char *  s)

Strip backslash for "escaped" semicolons, the string to be stripped (will be modified).

Returns
The stripped string.

Definition at line 1964 of file utils.c.

1965 {
1966  char *e;
1967  char *work = s;
1968 
1969  while ((e = strchr(work, ';'))) {
1970  if ((e > work) && (*(e-1) == '\\')) {
1971  memmove(e - 1, e, strlen(e) + 1);
1972  work = e;
1973  } else {
1974  work = e + 1;
1975  }
1976  }
1977 
1978  return s;
1979 }