Asterisk - The Open Source Telephony Project GIT-master-0deac78
Data Structures | Macros | Functions | Variables
utils.c File Reference

Utility functions. More...

#include "asterisk.h"
#include <ctype.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <unistd.h>
#include "asterisk/network.h"
#include "asterisk/ast_version.h"
#include "asterisk/lock.h"
#include "asterisk/io.h"
#include "asterisk/md5.h"
#include "asterisk/sha1.h"
#include "asterisk/cli.h"
#include "asterisk/linkedlists.h"
#include "asterisk/astobj2.h"
#include "asterisk/strings.h"
#include "asterisk/time.h"
#include "asterisk/utils.h"
#include "asterisk/threadstorage.h"
#include "asterisk/config.h"
#include "asterisk/alertpipe.h"
Include dependency graph for utils.c:

Go to the source code of this file.

Data Structures

struct  baseio
 Structure used for base64 encoding. More...
 
struct  thr_arg
 

Macros

#define AST_API_MODULE   /* ensure that inlinable API functions will be built in lock.h if required */
 
#define AST_API_MODULE   /* ensure that inlinable API functions will be built in this module if required */
 
#define AST_API_MODULE   /* ensure that inlinable API functions will be built in this module if required */
 
#define AST_API_MODULE   /* ensure that inlinable API functions will be built in this module if required */
 
#define AST_API_MODULE
 
#define AST_API_MODULE
 
#define AST_API_MODULE
 
#define BASELINELEN   72
 
#define BASEMAXINLINE   256
 
#define ONE_MILLION   1000000
 

Functions

void DO_CRASH_NORETURN __ast_assert_failed (int condition, const char *condition_str, const char *file, int line, const char *function)
 
int __ast_fd_set_flags (int fd, int flags, enum ast_fd_flag_operation op, const char *file, int lineno, const char *function)
 
static void __init_inet_ntoa_buf (void)
 
static void __init_thread_user_interface_tl (void)
 A thread local indicating whether the current thread is a user interface. More...
 
int ast_background_stacksize (void)
 
int ast_base64_encode_file (FILE *inputfile, FILE *outputfile, const char *endl)
 Performs a base 64 encode algorithm on the contents of a File. More...
 
int ast_base64_encode_file_path (const char *filename, FILE *outputfile, const char *endl)
 Performs a base 64 encode algorithm on the contents of a File. More...
 
int ast_base64decode (unsigned char *dst, const char *src, int max)
 decode BASE64 encoded text More...
 
char * ast_base64decode_string (const char *src)
 Decode BASE64 encoded text and return the string. More...
 
int ast_base64encode (char *dst, const unsigned char *src, int srclen, int max)
 Encode data in base64. More...
 
int ast_base64encode_full (char *dst, const unsigned char *src, int srclen, int max, int linebreaks)
 encode text to BASE64 coding More...
 
char * ast_base64encode_string (const char *src)
 Encode to BASE64 and return encoded string. More...
 
int ast_base64url_decode (unsigned char *dst, const char *src, int max)
 Decode data from base64 URL. More...
 
char * ast_base64url_decode_string (const char *src)
 Decode string from base64 URL. More...
 
int ast_base64url_encode (char *dst, const unsigned char *src, int srclen, int max)
 Encode data in base64 URL. More...
 
int ast_base64url_encode_full (char *dst, const unsigned char *src, int srclen, int max, int linebreaks)
 Same as ast_base64encode_full but for base64 URL. More...
 
char * ast_base64url_encode_string (const char *src)
 Encode string in base64 URL. 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_carefulwrite (int fd, char *s, int len, int timeoutms)
 Try to write string, but wait no more than ms milliseconds before timing out. More...
 
int ast_check_command_in_path (const char *cmd)
 Test for the presence of an executable command in $PATH. More...
 
int ast_check_ipv6 (void)
 Test that an OS supports IPv6 Networking. More...
 
int ast_compare_versions (const char *version1, const char *version2)
 Compare 2 major.minor.patch.extra version strings. More...
 
void DO_CRASH_NORETURN ast_do_crash (void)
 Force a crash if DO_CRASH is defined. More...
 
int ast_eid_cmp (const struct ast_eid *eid1, const struct ast_eid *eid2)
 Compare two EIDs. More...
 
int ast_eid_is_empty (const struct ast_eid *eid)
 Check if EID is empty. More...
 
char * ast_eid_to_str (char *s, int maxlen, struct ast_eid *eid)
 Convert an EID to a string. More...
 
void ast_enable_packet_fragmentation (int sock)
 Disable PMTU discovery on a socket. 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...
 
char * ast_escape_quoted (const char *string, char *outbuf, int buflen)
 Escape characters found in a quoted string. More...
 
char * ast_escape_semicolons (const char *string, char *outbuf, int buflen)
 Escape semicolons found in a string. More...
 
int ast_false (const char *s)
 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...
 
int ast_file_is_readable (const char *filename)
 Test that a file exists and is readable by the effective user. More...
 
void ast_format_duration_hh_mm_ss (int duration, char *buf, size_t length)
 Formats a duration into HH:MM:SS. More...
 
int ast_get_tid (void)
 Get current thread ID. More...
 
int ast_get_time_t (const char *src, time_t *dst, time_t _default, int *consumed)
 get values from config variables. More...
 
int ast_get_timeval (const char *src, struct timeval *dst, struct timeval _default, int *consumed)
 get values from config variables. More...
 
struct hostent * ast_gethostbyname (const char *host, struct ast_hostent *hp)
 Re-entrant (thread safe) version of gethostbyname that replaces the standard gethostbyname (which is not thread safe) More...
 
const char * ast_inet_ntoa (struct in_addr ia)
 ast_inet_ntoa: Recursive thread safe replacement of inet_ntoa 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...
 
void ast_md5_hash (char *output, const char *input)
 Produce 32 char MD5 hash of value. More...
 
int ast_mkdir (const char *path, int mode)
 Recursively create directory path. More...
 
int ast_parse_digest (const char *digest, struct ast_http_digest *d, int request, int pedantic)
 Parse digest authorization header. More...
 
char * ast_process_quotes_and_slashes (char *start, char find, char replace_with)
 Process a string to find and replace characters. More...
 
int ast_pthread_create_detached_stack (pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *), void *data, size_t stacksize, const char *file, const char *caller, int line, const char *start_fn)
 
int ast_pthread_create_stack (pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *), void *data, size_t stacksize, const char *file, const char *caller, int line, const char *start_fn)
 
long int ast_random (void)
 
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...
 
int ast_remaining_ms (struct timeval start, int max_ms)
 Calculate remaining milliseconds given a starting timestamp and upper bound. More...
 
void ast_replace_subargument_delimiter (char *s)
 Replace '^' in a string with ','. More...
 
int ast_safe_mkdir (const char *base_path, const char *path, int mode)
 Recursively create directory path, but only if it resolves within the given base_path. More...
 
void ast_set_default_eid (struct ast_eid *eid)
 Fill in an ast_eid with the default eid of this machine. More...
 
void ast_sha1_hash (char *output, const char *input)
 Produce 40 char SHA1 hash of value. More...
 
void ast_sha1_hash_uint (uint8_t *digest, const char *input)
 Produce a 20 byte SHA1 hash of value. More...
 
int ast_str_to_eid (struct ast_eid *eid, const char *s)
 Convert a string into an EID. 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...
 
char * ast_strsep (char **iss, const char sep, uint32_t flags)
 Act like strsep but ignore separators inside quotes. More...
 
char * ast_strsep_quoted (char **iss, const char sep, const char quote, uint32_t flags)
 Like ast_strsep() except you can specify a specific quote character. More...
 
int ast_thread_is_user_interface (void)
 Indicates whether the current thread is a user interface. More...
 
int ast_thread_user_interface_set (int is_user_interface)
 Set the current thread's user interface status. 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...
 
int ast_true (const char *s)
 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...
 
struct timeval ast_tvadd (struct timeval a, struct timeval b)
 Returns the sum of two timevals a + b. More...
 
struct timeval ast_tvsub (struct timeval a, struct timeval b)
 Returns the difference of two timevals a - b. More...
 
char * ast_unescape_c (char *src)
 Convert some C escape sequences. More...
 
void ast_unescape_quoted (char *quote_str)
 Unescape quotes in a string. More...
 
char * ast_unescape_semicolon (char *s)
 Strip backslash for "escaped" semicolons, the string to be stripped (will be modified). More...
 
void ast_uri_decode (char *s, struct ast_flags spec)
 Decode URI, URN, URL (overwrite string) More...
 
char * ast_uri_encode (const char *string, char *outbuf, int buflen, struct ast_flags spec)
 Turn text string to URI-encoded XX version. More...
 
int ast_uri_verify_encoded (const char *string)
 Verify if a string is valid as a URI component. More...
 
int ast_utils_init (void)
 
char * ast_utils_which (const char *binary, char *fullpath, size_t fullpath_size)
 Resolve a binary to a full pathname. More...
 
int ast_wait_for_input (int fd, int ms)
 
int ast_wait_for_output (int fd, int ms)
 
int ast_xml_escape (const char *string, char *const outbuf, const size_t buflen)
 Escape reserved characters for use in XML. More...
 
static void base64_init (void)
 
static void * dummy_start (void *data)
 
static char * escape_alloc (const char *s, size_t *size)
 
static int inbuf (struct baseio *bio, FILE *fi)
 utility used by inchar(), for base_encode() More...
 
static int inchar (struct baseio *bio, FILE *fi)
 utility used by base_encode() More...
 
static int ochar (struct baseio *bio, int c, FILE *so, const char *endl)
 utility used by base_encode() More...
 
static int safe_mkdir (const char *base_path, char *path, int mode)
 
static struct timeval tvfix (struct timeval a)
 
static void utils_shutdown (void)
 
static int wait_for_output (int fd, int timeoutms)
 

Variables

const struct ast_flags ast_uri_http = {AST_URI_UNRESERVED}
 
const struct ast_flags ast_uri_http_legacy = {AST_URI_LEGACY_SPACE | AST_URI_UNRESERVED}
 
const struct ast_flags ast_uri_sip_user = {AST_URI_UNRESERVED | AST_URI_SIP_USER_UNRESERVED}
 
static char b2a [256]
 
static char b2a_url [256]
 
static char base64 [64]
 
static char base64url [64]
 
static int dev_urandom_fd = -1
 
char escape_sequences []
 
static char escape_sequences_map []
 
static struct ast_threadstorage inet_ntoa_buf = { .once = PTHREAD_ONCE_INIT , .key_init = __init_inet_ntoa_buf , .custom_init = NULL , }
 
static ast_mutex_t randomlock = { PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP , NULL, {1, 0} }
 
static struct ast_threadstorage thread_user_interface_tl = { .once = PTHREAD_ONCE_INIT , .key_init = __init_thread_user_interface_tl , .custom_init = NULL , }
 

Detailed Description

Utility functions.

Note
These are important for portability and security, so please use them in favour of other routines. Please consult the CODING GUIDELINES for more information.

Definition in file utils.c.

Macro Definition Documentation

◆ AST_API_MODULE [1/7]

#define AST_API_MODULE   /* ensure that inlinable API functions will be built in lock.h if required */

Definition at line 72 of file utils.c.

◆ AST_API_MODULE [2/7]

#define AST_API_MODULE   /* ensure that inlinable API functions will be built in this module if required */

Definition at line 72 of file utils.c.

◆ AST_API_MODULE [3/7]

#define AST_API_MODULE   /* ensure that inlinable API functions will be built in this module if required */

Definition at line 72 of file utils.c.

◆ AST_API_MODULE [4/7]

#define AST_API_MODULE   /* ensure that inlinable API functions will be built in this module if required */

Definition at line 72 of file utils.c.

◆ AST_API_MODULE [5/7]

#define AST_API_MODULE

Definition at line 72 of file utils.c.

◆ AST_API_MODULE [6/7]

#define AST_API_MODULE

Definition at line 72 of file utils.c.

◆ AST_API_MODULE [7/7]

#define AST_API_MODULE

Definition at line 72 of file utils.c.

◆ BASELINELEN

#define BASELINELEN   72

Line length for Base 64 encoded messages

Definition at line 575 of file utils.c.

◆ BASEMAXINLINE

#define BASEMAXINLINE   256

Buffer size for Base 64 attachment encoding

Definition at line 576 of file utils.c.

◆ ONE_MILLION

#define ONE_MILLION   1000000

Definition at line 2269 of file utils.c.

Function Documentation

◆ __ast_assert_failed()

void DO_CRASH_NORETURN __ast_assert_failed ( int  condition,
const char *  condition_str,
const char *  file,
int  line,
const char *  function 
)

Definition at line 2852 of file utils.c.

2853{
2854 /*
2855 * Attempt to put it into the logger, but hope that at least
2856 * someone saw the message on stderr ...
2857 */
2858 fprintf(stderr, "FRACK!, Failed assertion %s (%d) at line %d in %s of %s\n",
2859 condition_str, condition, line, function, file);
2860 ast_log(__LOG_ERROR, file, line, function, "FRACK!, Failed assertion %s (%d)\n",
2861 condition_str, condition);
2862
2863 /* Generate a backtrace for the assert */
2865
2866 /*
2867 * Give the logger a chance to get the message out, just in case
2868 * we abort(), or Asterisk crashes due to whatever problem just
2869 * happened after we exit ast_assert().
2870 */
2871 usleep(1);
2872 ast_do_crash();
2873}
#define ast_log
Definition: astobj2.c:42
#define __LOG_ERROR
void ast_log_backtrace(void)
Log a backtrace of the current thread's execution stack to the Asterisk log.
Definition: logger.c:2480
void DO_CRASH_NORETURN ast_do_crash(void)
Force a crash if DO_CRASH is defined.
Definition: utils.c:2840

References __LOG_ERROR, ast_do_crash(), ast_log, ast_log_backtrace(), and make_ari_stubs::file.

Referenced by __ao2_container_clone(), __ao2_iterator_next(), __ao2_link(), __ao2_ref(), internal_ao2_traverse(), and log_bad_ao2().

◆ __ast_fd_set_flags()

int __ast_fd_set_flags ( int  fd,
int  flags,
enum ast_fd_flag_operation  op,
const char *  file,
int  lineno,
const char *  function 
)

Definition at line 3186 of file utils.c.

3188{
3189 int f;
3190
3191 f = fcntl(fd, F_GETFL);
3192 if (f == -1) {
3193 ast_log(__LOG_ERROR, file, lineno, function,
3194 "Failed to get fcntl() flags for file descriptor: %s\n", strerror(errno));
3195 return -1;
3196 }
3197
3198 switch (op) {
3199 case AST_FD_FLAG_SET:
3200 if ((f & flags) == flags) {
3201 /* There is nothing to set */
3202 return 0;
3203 }
3204 f |= flags;
3205 break;
3206 case AST_FD_FLAG_CLEAR:
3207 if (!(f & flags)) {
3208 /* There is nothing to clear */
3209 return 0;
3210 }
3211 f &= ~flags;
3212 break;
3213 default:
3214 ast_assert(0);
3215 break;
3216 }
3217
3218 f = fcntl(fd, F_SETFL, f);
3219 if (f == -1) {
3220 ast_log(__LOG_ERROR, file, lineno, function,
3221 "Failed to set fcntl() flags for file descriptor: %s\n", strerror(errno));
3222 return -1;
3223 }
3224
3225 return 0;
3226}
int errno
#define ast_assert(a)
Definition: utils.h:776
@ AST_FD_FLAG_SET
Definition: utils.h:1059
@ AST_FD_FLAG_CLEAR
Definition: utils.h:1060

References __LOG_ERROR, ast_assert, AST_FD_FLAG_CLEAR, AST_FD_FLAG_SET, ast_log, errno, and make_ari_stubs::file.

◆ __init_inet_ntoa_buf()

static void __init_inet_ntoa_buf ( void  )
static

Definition at line 85 of file utils.c.

102{

◆ __init_thread_user_interface_tl()

static void __init_thread_user_interface_tl ( void  )
static

A thread local indicating whether the current thread is a user interface.

Definition at line 3267 of file utils.c.

3270{

◆ ast_background_stacksize()

int ast_background_stacksize ( void  )

Definition at line 1652 of file utils.c.

1653{
1654#if !defined(LOW_MEMORY)
1655 return AST_STACKSIZE;
1656#else
1657 return AST_STACKSIZE_LOW;
1658#endif
1659}
#define AST_STACKSIZE
Definition: utils.h:602
#define AST_STACKSIZE_LOW
Definition: utils.h:603

References AST_STACKSIZE, and AST_STACKSIZE_LOW.

◆ ast_base64_encode_file()

int ast_base64_encode_file ( FILE *  inputfile,
FILE *  outputfile,
const char *  endl 
)

Performs a base 64 encode algorithm on the contents of a File.

Parameters
inputfileA FILE handle to the input file to be encoded. Must be readable. This handle is not automatically closed.
outputfileA FILE handle to the output file to receive the base 64 encoded contents of the input file, identified by filename.
endlThe line ending to use (e.g. either "\n" or "\r\n")
Returns
zero on success, -1 on error.

Definition at line 648 of file utils.c.

649{
650 static const unsigned char dtable[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
651 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
652 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0',
653 '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'};
654 int i, hiteof = 0;
655 struct baseio bio;
656
657 memset(&bio, 0, sizeof(bio));
658 bio.iocp = BASEMAXINLINE;
659
660 while (!hiteof){
661 unsigned char igroup[3], ogroup[4];
662 int c, n;
663
664 memset(igroup, 0, sizeof(igroup));
665
666 for (n = 0; n < 3; n++) {
667 if ((c = inchar(&bio, inputfile)) == EOF) {
668 hiteof = 1;
669 break;
670 }
671
672 igroup[n] = (unsigned char) c;
673 }
674
675 if (n > 0) {
676 ogroup[0]= dtable[igroup[0] >> 2];
677 ogroup[1]= dtable[((igroup[0] & 3) << 4) | (igroup[1] >> 4)];
678 ogroup[2]= dtable[((igroup[1] & 0xF) << 2) | (igroup[2] >> 6)];
679 ogroup[3]= dtable[igroup[2] & 0x3F];
680
681 if (n < 3) {
682 ogroup[3] = '=';
683
684 if (n < 2) {
685 ogroup[2] = '=';
686 }
687 }
688
689 for (i = 0; i < 4; i++) {
690 ochar(&bio, ogroup[i], outputfile, endl);
691 }
692 }
693 }
694
695 if (fputs(endl, outputfile) == EOF) {
696 return 0;
697 }
698
699 return 1;
700}
Structure used for base64 encoding.
Definition: utils.c:579
static struct test_val c
static int inchar(struct baseio *bio, FILE *fi)
utility used by base_encode()
Definition: utils.c:615
#define BASEMAXINLINE
Definition: utils.c:576
static int ochar(struct baseio *bio, int c, FILE *so, const char *endl)
utility used by base_encode()
Definition: utils.c:629

References BASEMAXINLINE, c, inchar(), baseio::iocp, and ochar().

Referenced by ast_base64_encode_file_path().

◆ ast_base64_encode_file_path()

int ast_base64_encode_file_path ( const char *  filename,
FILE *  outputfile,
const char *  endl 
)

Performs a base 64 encode algorithm on the contents of a File.

Parameters
filenameThe path to the file to be encoded. Must be readable, file is opened in read mode.
outputfileA FILE handle to the output file to receive the base 64 encoded contents of the input file, identified by filename.
endlThe line ending to use (e.g. either "\n" or "\r\n")
Returns
zero on success, -1 on error.

Definition at line 702 of file utils.c.

703{
704 FILE *fi;
705 int res;
706
707 if (!(fi = fopen(filename, "rb"))) {
708 ast_log(AST_LOG_WARNING, "Failed to open file: %s: %s\n", filename, strerror(errno));
709 return -1;
710 }
711
712 res = ast_base64_encode_file(fi, outputfile, endl);
713
714 fclose(fi);
715
716 return res;
717}
#define AST_LOG_WARNING
int ast_base64_encode_file(FILE *inputfile, FILE *outputfile, const char *endl)
Performs a base 64 encode algorithm on the contents of a File.
Definition: utils.c:648

References ast_base64_encode_file(), ast_log, AST_LOG_WARNING, and errno.

Referenced by add_email_attachment(), and sendmail().

◆ ast_base64decode()

int ast_base64decode ( unsigned char *  dst,
const char *  src,
int  max 
)

decode BASE64 encoded text

Decode data from base64.

Definition at line 296 of file utils.c.

297{
298 int cnt = 0;
299 unsigned int byte = 0;
300 unsigned int bits = 0;
301 int incnt = 0;
302 while(*src && *src != '=' && (cnt < max)) {
303 /* Shift in 6 bits of input */
304 byte <<= 6;
305 byte |= (b2a[(int)(*src)]) & 0x3f;
306 bits += 6;
307 src++;
308 incnt++;
309 /* If we have at least 8 bits left over, take that character
310 off the top */
311 if (bits >= 8) {
312 bits -= 8;
313 *dst = (byte >> bits) & 0xff;
314 dst++;
315 cnt++;
316 }
317 }
318 /* Don't worry about left over bits, they're extra anyway */
319 return cnt;
320}
#define max(a, b)
Definition: f2c.h:198
static char b2a[256]
Definition: utils.c:82

References b2a, and max.

Referenced by action_messagesend(), aes_helper(), ast_base64decode_string(), ast_check_signature(), ast_http_get_auth(), AST_TEST_DEFINE(), base64_helper(), crypto_init_keys(), custom_presence_callback(), presence_write(), and res_sdp_crypto_parse_offer().

◆ ast_base64decode_string()

char * ast_base64decode_string ( const char *  src)

Decode BASE64 encoded text and return the string.

Same as ast_base64decode, but does the math for you and returns a decoded string.

Definition at line 323 of file utils.c.

324{
325 size_t encoded_len;
326 size_t decoded_len;
327 int padding = 0;
328 unsigned char *decoded_string;
329
330 if (ast_strlen_zero(src)) {
331 return NULL;
332 }
333
334 encoded_len = strlen(src);
335 if (encoded_len > 2 && src[encoded_len - 1] == '=') {
336 padding++;
337 if (src[encoded_len - 2] == '=') {
338 padding++;
339 }
340 }
341
342 decoded_len = (encoded_len / 4 * 3) - padding;
343 decoded_string = ast_malloc(decoded_len + 1);
344 if (!decoded_string) {
345 return NULL;
346 }
347
348 ast_base64decode(decoded_string, src, decoded_len);
349 decoded_string[decoded_len] = '\0';
350
351 return (char *)decoded_string;
352}
#define ast_malloc(len)
A wrapper for malloc()
Definition: astmm.h:191
#define NULL
Definition: resample.c:96
static force_inline int attribute_pure ast_strlen_zero(const char *s)
Definition: strings.h:65
int ast_base64decode(unsigned char *dst, const char *src, int max)
decode BASE64 encoded text
Definition: utils.c:296

References ast_base64decode(), ast_malloc, ast_strlen_zero(), and NULL.

◆ ast_base64encode()

int ast_base64encode ( char *  dst,
const unsigned char *  src,
int  srclen,
int  max 
)

Encode data in base64.

Parameters
dstthe destination buffer
srcthe source data to be encoded
srclenthe number of bytes present in the source buffer
maxthe maximum number of bytes to write into the destination buffer, including the terminating NULL character.

Definition at line 406 of file utils.c.

407{
408 return ast_base64encode_full(dst, src, srclen, max, 0);
409}
int ast_base64encode_full(char *dst, const unsigned char *src, int srclen, int max, int linebreaks)
encode text to BASE64 coding
Definition: utils.c:355

References ast_base64encode_full(), and max.

Referenced by aes_helper(), ast_base64encode_string(), ast_http_create_basic_auth_header(), ast_sign(), AST_TEST_DEFINE(), base64_helper(), build_secret(), crypto_init_keys(), presence_read(), websocket_client_create_key(), websocket_combine_key(), and xmpp_client_authenticate_sasl().

◆ ast_base64encode_full()

int ast_base64encode_full ( char *  dst,
const unsigned char *  src,
int  srclen,
int  max,
int  linebreaks 
)

encode text to BASE64 coding

Definition at line 355 of file utils.c.

356{
357 int cnt = 0;
358 int col = 0;
359 unsigned int byte = 0;
360 int bits = 0;
361 int cntin = 0;
362 /* Reserve space for null byte at end of string */
363 max--;
364 while ((cntin < srclen) && (cnt < max)) {
365 byte <<= 8;
366 byte |= *(src++);
367 bits += 8;
368 cntin++;
369 if ((bits == 24) && (cnt + 4 <= max)) {
370 *dst++ = base64[(byte >> 18) & 0x3f];
371 *dst++ = base64[(byte >> 12) & 0x3f];
372 *dst++ = base64[(byte >> 6) & 0x3f];
373 *dst++ = base64[byte & 0x3f];
374 cnt += 4;
375 col += 4;
376 bits = 0;
377 byte = 0;
378 }
379 if (linebreaks && (cnt < max) && (col == 64)) {
380 *dst++ = '\n';
381 cnt++;
382 col = 0;
383 }
384 }
385 if (bits && (cnt + 4 <= max)) {
386 /* Add one last character for the remaining bits,
387 padding the rest with 0 */
388 byte <<= 24 - bits;
389 *dst++ = base64[(byte >> 18) & 0x3f];
390 *dst++ = base64[(byte >> 12) & 0x3f];
391 if (bits == 16)
392 *dst++ = base64[(byte >> 6) & 0x3f];
393 else
394 *dst++ = '=';
395 *dst++ = '=';
396 cnt += 4;
397 }
398 if (linebreaks && (cnt < max)) {
399 *dst++ = '\n';
400 cnt++;
401 }
402 *dst = '\0';
403 return cnt;
404}
static char base64[64]
Definition: utils.c:80

References base64, and max.

Referenced by ast_base64encode().

◆ ast_base64encode_string()

char * ast_base64encode_string ( const char *  src)

Encode to BASE64 and return encoded string.

Same as ast_base64encode, but does hte math for you and returns an encoded string.

Definition at line 412 of file utils.c.

413{
414 size_t encoded_len;
415 char *encoded_string;
416
417 if (ast_strlen_zero(src)) {
418 return NULL;
419 }
420
421 encoded_len = ((strlen(src) * 4 / 3 + 3) & ~3) + 1;
422 encoded_string = ast_calloc(1, encoded_len);
423
424 ast_base64encode(encoded_string, (const unsigned char *)src, strlen(src), encoded_len);
425
426 return encoded_string;
427}
#define ast_calloc(num, len)
A wrapper for calloc()
Definition: astmm.h:202
int ast_base64encode(char *dst, const unsigned char *src, int srclen, int max)
Encode data in base64.
Definition: utils.c:406

References ast_base64encode(), ast_calloc, ast_strlen_zero(), and NULL.

◆ ast_base64url_decode()

int ast_base64url_decode ( unsigned char *  dst,
const char *  src,
int  max 
)

Decode data from base64 URL.

Parameters
dstThe destination buffer
srcThe source buffer
maxThe maximum number of bytes to write into the destination buffer. Note that this function will not ensure that the destination buffer is NULL terminated. So, in general, this parameter should be sizeof(dst) - 1

Definition at line 429 of file utils.c.

430{
431 int cnt = 0;
432 unsigned int byte = 0;
433 unsigned int bits = 0;
434
435 while (*src && (cnt < max)) {
436 byte <<= 6;
437 byte |= (b2a_url[(int)(*src)]) & 0x3f;
438 bits += 6;
439 src++;
440 if (bits >= 8) {
441 bits -= 8;
442 *dst = (byte >> bits) & 0xff;
443 dst++;
444 cnt++;
445 }
446 }
447 return cnt;
448}
static char b2a_url[256]
Definition: utils.c:83

References b2a_url, and max.

Referenced by ast_base64url_decode_string().

◆ ast_base64url_decode_string()

char * ast_base64url_decode_string ( const char *  src)

Decode string from base64 URL.

Note
The returned string will need to be freed later
Parameters
srcThe source buffer
Return values
NULLon failure
Returns
Decoded string on success

Definition at line 450 of file utils.c.

451{
452 size_t decoded_len;
453 unsigned char *decoded_string;
454
455 if (ast_strlen_zero(src)) {
456 return NULL;
457 }
458
459 decoded_len = strlen(src) * 3 / 4;
460 decoded_string = ast_malloc(decoded_len + 1);
461 if (!decoded_string) {
462 return NULL;
463 }
464
465 ast_base64url_decode(decoded_string, src, decoded_len);
466 decoded_string[decoded_len] = '\0';
467
468 return (char *)decoded_string;
469}
int ast_base64url_decode(unsigned char *dst, const char *src, int max)
Decode data from base64 URL.
Definition: utils.c:429

References ast_base64url_decode(), ast_malloc, ast_strlen_zero(), and NULL.

◆ ast_base64url_encode()

int ast_base64url_encode ( char *  dst,
const unsigned char *  src,
int  srclen,
int  max 
)

Encode data in base64 URL.

Parameters
dstThe destination buffer
srcThe source data to be encoded
srclenThe number of bytes present in the source buffer
maxThe maximum number of bytes to write into the destination buffer, including the terminating NULL character

Definition at line 518 of file utils.c.

519{
520 return ast_base64url_encode_full(dst, src, srclen, max, 0);
521}
int ast_base64url_encode_full(char *dst, const unsigned char *src, int srclen, int max, int linebreaks)
Same as ast_base64encode_full but for base64 URL.
Definition: utils.c:471

References ast_base64url_encode_full(), and max.

Referenced by ast_base64url_encode_string().

◆ ast_base64url_encode_full()

int ast_base64url_encode_full ( char *  dst,
const unsigned char *  src,
int  srclen,
int  max,
int  linebreaks 
)

Same as ast_base64encode_full but for base64 URL.

Parameters
dstThe destination buffer
srcThe source buffer
srclenThe number of bytes present in the source buffer
maxThe maximum number of bytes to write into the destination buffer, including the terminating NULL character.
linebreaksSet to 1 if there should be linebreaks inserted in the result

Definition at line 471 of file utils.c.

472{
473 int cnt = 0;
474 int col = 0;
475 unsigned int byte = 0;
476 int bits = 0;
477 int cntin = 0;
478
479 max--;
480 while ((cntin < srclen) && (cnt < max)) {
481 byte <<= 8;
482 byte |= *(src++);
483 bits += 8;
484 cntin++;
485 if ((bits == 24) && (cnt + 4 <= max)) {
486 *dst++ = base64url[(byte >> 18) & 0x3f];
487 *dst++ = base64url[(byte >> 12) & 0x3f];
488 *dst++ = base64url[(byte >> 6) & 0x3f];
489 *dst++ = base64url[(byte) & 0x3f];
490 cnt += 4;
491 col += 4;
492 bits = 0;
493 byte = 0;
494 }
495 if (linebreaks && (cnt < max) && (col == 64)) {
496 *dst++ = '\n';
497 cnt++;
498 col = 0;
499 }
500 }
501 if (bits && (cnt + 4 <= max)) {
502 byte <<= 24 - bits;
503 *dst++ = base64url[(byte >> 18) & 0x3f];
504 *dst++ = base64url[(byte >> 12) & 0x3f];
505 if (bits == 16) {
506 *dst++ = base64url[(byte >> 6) & 0x3f];
507 }
508 cnt += 4;
509 }
510 if (linebreaks && (cnt < max)) {
511 *dst++ = '\n';
512 cnt++;
513 }
514 *dst = '\0';
515 return cnt;
516}
static char base64url[64]
Definition: utils.c:81

References base64url, and max.

Referenced by ast_base64url_encode().

◆ ast_base64url_encode_string()

char * ast_base64url_encode_string ( const char *  src)

Encode string in base64 URL.

Note
The returned string will need to be freed later
Parameters
srcThe source data to be encoded
Return values
NULLon failure
Returns
Encoded string on success

Definition at line 523 of file utils.c.

524{
525 size_t encoded_len;
526 char *encoded_string;
527
528 if (ast_strlen_zero(src)) {
529 return NULL;
530 }
531
532 encoded_len = ((strlen(src) * 4 / 3 + 3) & ~3) + 1;
533 encoded_string = ast_malloc(encoded_len);
534
535 ast_base64url_encode(encoded_string, (const unsigned char *)src, strlen(src), encoded_len);
536
537 return encoded_string;
538}
int ast_base64url_encode(char *dst, const unsigned char *src, int srclen, int max)
Encode data in base64 URL.
Definition: utils.c:518

References ast_base64url_encode(), ast_malloc, ast_strlen_zero(), and NULL.

◆ ast_build_string()

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 2203 of file utils.c.

2204{
2205 va_list ap;
2206 int result;
2207
2208 va_start(ap, fmt);
2209 result = ast_build_string_va(buffer, space, fmt, ap);
2210 va_end(ap);
2211
2212 return result;
2213}
static PGresult * result
Definition: cel_pgsql.c:84
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:2184

References ast_build_string_va(), and result.

Referenced by ast_fax_caps_to_str(), generate_filenames_string(), handle_speechrecognize(), pp_each_extension_helper(), and pp_each_user_helper().

◆ ast_build_string_va()

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 2184 of file utils.c.

2185{
2186 int result;
2187
2188 if (!buffer || !*buffer || !space || !*space)
2189 return -1;
2190
2191 result = vsnprintf(*buffer, *space, fmt, ap);
2192
2193 if (result < 0)
2194 return -1;
2195 else if (result > *space)
2196 result = *space;
2197
2198 *buffer += result;
2199 *space -= result;
2200 return 0;
2201}

References result.

Referenced by ast_build_string().

◆ ast_carefulwrite()

int ast_carefulwrite ( int  fd,
char *  s,
int  len,
int  timeoutms 
)

Try to write string, but wait no more than ms milliseconds before timing out.

Try to write string, but wait no more than ms milliseconds before timing out.

Note
The code assumes that the file descriptor has NONBLOCK set, so there is only one system call made to do a write, unless we actually have a need to wait. This way, we get better performance. If the descriptor is blocking, all assumptions on the guaranteed detail do not apply anymore.

Definition at line 1807 of file utils.c.

1808{
1809 struct timeval start = ast_tvnow();
1810 int res = 0;
1811 int elapsed = 0;
1812
1813 while (len) {
1814 if (wait_for_output(fd, timeoutms - elapsed)) {
1815 return -1;
1816 }
1817
1818 res = write(fd, s, len);
1819
1820 if (res < 0 && errno != EAGAIN && errno != EINTR) {
1821 /* fatal error from write() */
1822 if (errno == EPIPE) {
1823#ifndef STANDALONE
1824 ast_debug(1, "write() failed due to reading end being closed: %s\n", strerror(errno));
1825#endif
1826 } else {
1827 ast_log(LOG_ERROR, "write() returned error: %s\n", strerror(errno));
1828 }
1829 return -1;
1830 }
1831
1832 if (res < 0) {
1833 /* It was an acceptable error */
1834 res = 0;
1835 }
1836
1837 /* Update how much data we have left to write */
1838 len -= res;
1839 s += res;
1840 res = 0;
1841
1842 elapsed = ast_tvdiff_ms(ast_tvnow(), start);
1843 if (elapsed >= timeoutms) {
1844 /* We've taken too long to write
1845 * This is only an error condition if we haven't finished writing. */
1846 res = len ? -1 : 0;
1847 break;
1848 }
1849 }
1850
1851 return res;
1852}
static int len(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t buflen)
#define ast_debug(level,...)
Log a DEBUG message.
#define LOG_ERROR
int64_t ast_tvdiff_ms(struct timeval end, struct timeval start)
Computes the difference (in milliseconds) between two struct timeval instances.
Definition: time.h:107
struct timeval ast_tvnow(void)
Returns current timeval. Meant to replace calls to gettimeofday().
Definition: time.h:159
static int wait_for_output(int fd, int timeoutms)
Definition: utils.c:1754

References ast_debug, ast_log, ast_tvdiff_ms(), ast_tvnow(), errno, len(), LOG_ERROR, and wait_for_output().

Referenced by ast_agi_send(), ast_cli(), and cleanup_module().

◆ ast_check_command_in_path()

int ast_check_command_in_path ( const char *  cmd)

Test for the presence of an executable command in $PATH.

Parameters
cmdName of command to locate.
Return values
True(non-zero) if command is in $PATH.
False(zero) command not found.

Definition at line 3299 of file utils.c.

3300{
3301 char *token, *saveptr, *path = getenv("PATH");
3302 char filename[PATH_MAX];
3303 int len;
3304
3305 if (path == NULL) {
3306 return 0;
3307 }
3308
3309 path = ast_strdup(path);
3310 if (path == NULL) {
3311 return 0;
3312 }
3313
3314 token = strtok_r(path, ":", &saveptr);
3315 while (token != NULL) {
3316 len = snprintf(filename, sizeof(filename), "%s/%s", token, cmd);
3317 if (len < 0 || len >= sizeof(filename)) {
3318 ast_log(LOG_WARNING, "Path constructed with '%s' too long; skipping\n", token);
3319 continue;
3320 }
3321
3322 if (access(filename, X_OK) == 0) {
3323 ast_free(path);
3324 return 1;
3325 }
3326
3327 token = strtok_r(NULL, ":", &saveptr);
3328 }
3329 ast_free(path);
3330 return 0;
3331}
#define PATH_MAX
Definition: asterisk.h:40
#define ast_free(a)
Definition: astmm.h:180
#define ast_strdup(str)
A wrapper for strdup()
Definition: astmm.h:241
#define LOG_WARNING

References ast_free, ast_log, ast_strdup, len(), LOG_WARNING, NULL, and PATH_MAX.

Referenced by AST_TEST_DEFINE().

◆ ast_check_ipv6()

int ast_check_ipv6 ( void  )

Test that an OS supports IPv6 Networking.

Since
13.14.0
Return values
True(non-zero) if the IPv6 supported.
False(zero) if the OS doesn't support IPv6.

Definition at line 2828 of file utils.c.

2829{
2830 int udp6_socket = socket(AF_INET6, SOCK_DGRAM, 0);
2831
2832 if (udp6_socket < 0) {
2833 return 0;
2834 }
2835
2836 close(udp6_socket);
2837 return 1;
2838}

Referenced by load_module().

◆ ast_compare_versions()

int ast_compare_versions ( const char *  version1,
const char *  version2 
)

Compare 2 major.minor.patch.extra version strings.

Since
13.7.0
Parameters
version1
version2
Return values
negativeif version 1 < version 2.
0if version 1 = version 2.
positiveif version 1 > version 2.

Definition at line 3160 of file utils.c.

3161{
3162 unsigned int major[2] = { 0 };
3163 unsigned int minor[2] = { 0 };
3164 unsigned int patch[2] = { 0 };
3165 unsigned int extra[2] = { 0 };
3166 int res;
3167
3168 sscanf(version1, "%u.%u.%u.%u", &major[0], &minor[0], &patch[0], &extra[0]);
3169 sscanf(version2, "%u.%u.%u.%u", &major[1], &minor[1], &patch[1], &extra[1]);
3170
3171 res = major[0] - major[1];
3172 if (res) {
3173 return res;
3174 }
3175 res = minor[0] - minor[1];
3176 if (res) {
3177 return res;
3178 }
3179 res = patch[0] - patch[1];
3180 if (res) {
3181 return res;
3182 }
3183 return extra[0] - extra[1];
3184}

Referenced by transport_apply().

◆ ast_do_crash()

void DO_CRASH_NORETURN ast_do_crash ( void  )

Force a crash if DO_CRASH is defined.

Note
If DO_CRASH is not defined then the function returns.

Definition at line 2840 of file utils.c.

2841{
2842#if defined(DO_CRASH)
2843 abort();
2844 /*
2845 * Just in case abort() doesn't work or something else super
2846 * silly, and for Qwell's amusement.
2847 */
2848 *((int *) 0) = 0;
2849#endif /* defined(DO_CRASH) */
2850}

Referenced by __ast_assert_failed().

◆ ast_eid_cmp()

int ast_eid_cmp ( const struct ast_eid eid1,
const struct ast_eid eid2 
)

◆ ast_eid_is_empty()

int ast_eid_is_empty ( const struct ast_eid eid)

Check if EID is empty.

Return values
1if the EID is empty
0otherwise
Since
13.12.0

Definition at line 3135 of file utils.c.

3136{
3137 struct ast_eid empty_eid;
3138
3139 memset(&empty_eid, 0, sizeof(empty_eid));
3140 return memcmp(eid, &empty_eid, sizeof(empty_eid)) ? 0 : 1;
3141}
static dundi_eid empty_eid
Definition: pbx_dundi.c:223
An Entity ID is essentially a MAC address, brief and unique.
Definition: utils.h:850
unsigned char eid[6]
Definition: utils.h:851

References ast_eid::eid, and empty_eid.

Referenced by load_module(), and set_config().

◆ ast_eid_to_str()

char * ast_eid_to_str ( char *  s,
int  maxlen,
struct ast_eid eid 
)

Convert an EID to a string.

Since
1.6.1

Definition at line 2875 of file utils.c.

2876{
2877 int x;
2878 char *os = s;
2879 if (maxlen < 18) {
2880 if (s && (maxlen > 0)) {
2881 *s = '\0';
2882 }
2883 } else {
2884 for (x = 0; x < 5; x++) {
2885 sprintf(s, "%02hhx:", eid->eid[x]);
2886 s += 3;
2887 }
2888 sprintf(s, "%02hhx", eid->eid[5]);
2889 }
2890 return os;
2891}

References ast_eid::eid.

Referenced by app_send(), append_transaction(), ast_ari_asterisk_get_info(), ast_ari_asterisk_ping(), ast_set_default_eid(), ast_str_retrieve_variable(), AST_TEST_DEFINE(), asterisk_publication_send_refresh(), asterisk_publisher_devstate_cb(), asterisk_publisher_mwistate_cb(), bridges_scrape_cb(), build_peer(), build_transactions(), cache_lookup(), cache_lookup_internal(), channels_scrape_cb(), check_key(), complete_peer_helper(), cpg_deliver_cb(), destroy_trans(), do_autokill(), do_register(), do_register_expire(), dump_answer(), dump_eid(), dundi_answer_entity(), dundi_lookup_internal(), dundi_lookup_local(), dundi_lookup_thread(), dundi_precache_thread(), dundi_prop_precache(), dundi_query_thread(), dundi_send(), dundi_show_cache(), dundi_show_entityid(), dundi_show_hints(), dundi_show_peer(), dundi_show_peers(), dundi_show_requests(), endpoints_scrape_cb(), handle_command_response(), handle_show_settings(), populate_addr(), prometheus_config_post_apply(), publish_cluster_discovery_to_stasis_full(), publish_device_state_to_stasis(), publish_mwi_to_stasis(), publish_to_corosync(), register_request(), session_send_app_event(), session_send_or_queue(), update_key(), xmpp_pubsub_publish_device_state(), and xmpp_pubsub_publish_mwi().

◆ ast_enable_packet_fragmentation()

void ast_enable_packet_fragmentation ( int  sock)

Disable PMTU discovery on a socket.

Parameters
sockThe socket to manipulate

On Linux, UDP sockets default to sending packets with the Dont Fragment (DF) bit set. This is supposedly done to allow the application to do PMTU discovery, but Asterisk does not do this.

Because of this, UDP packets sent by Asterisk that are larger than the MTU of any hop in the path will be lost. This function can be called on a socket to ensure that the DF bit will not be set.

Definition at line 2505 of file utils.c.

2506{
2507#if defined(HAVE_IP_MTU_DISCOVER)
2508 int val = IP_PMTUDISC_DONT;
2509
2510 if (setsockopt(sock, IPPROTO_IP, IP_MTU_DISCOVER, &val, sizeof(val)))
2511 ast_log(LOG_WARNING, "Unable to disable PMTU discovery. Large UDP packets may fail to be delivered when sent from this socket.\n");
2512#endif /* HAVE_IP_MTU_DISCOVER */
2513}
Definition: ast_expr2.c:325

References ast_log, and LOG_WARNING.

Referenced by ast_netsock_bindaddr().

◆ ast_escape()

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 2070 of file utils.c.

2071{
2072 char *p;
2073 char *c;
2074
2075 if (!dest || !size) {
2076 return dest;
2077 }
2078 if (ast_strlen_zero(s)) {
2079 *dest = '\0';
2080 return dest;
2081 }
2082
2083 if (ast_strlen_zero(to_escape)) {
2084 ast_copy_string(dest, s, size);
2085 return dest;
2086 }
2087
2088 for (p = dest; *s && --size; ++s, ++p) {
2089 /* If in the list of characters to escape then escape it */
2090 if (strchr(to_escape, *s)) {
2091 if (!--size) {
2092 /* Not enough room left for the escape sequence. */
2093 break;
2094 }
2095
2096 /*
2097 * See if the character to escape is part of the standard escape
2098 * sequences. If so we'll have to use its mapped counterpart
2099 * otherwise just use the current character.
2100 */
2101 c = strchr(escape_sequences, *s);
2102 *p++ = '\\';
2104 } else {
2105 *p = *s;
2106 }
2107 }
2108 *p = '\0';
2109
2110 return dest;
2111}
void ast_copy_string(char *dst, const char *src, size_t size)
Size-limited null-terminating string copy.
Definition: strings.h:425
char escape_sequences[]
Definition: utils.c:2058
static char escape_sequences_map[]
Definition: utils.c:2066

References ast_copy_string(), ast_strlen_zero(), c, escape_sequences, and escape_sequences_map.

Referenced by ast_escape_alloc().

◆ ast_escape_alloc()

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 2168 of file utils.c.

2169{
2170 size_t size = 0;
2171 char *dest = escape_alloc(s, &size);
2172
2173 return ast_escape(dest, s, size, to_escape);
2174}
static char * escape_alloc(const char *s, size_t *size)
Definition: utils.c:2154
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:2070

References ast_escape(), and escape_alloc().

◆ ast_escape_c()

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 2113 of file utils.c.

2114{
2115 /*
2116 * Note - This is an optimized version of ast_escape. When looking only
2117 * for escape_sequences a couple of checks used in the generic case can
2118 * be left out thus making it slightly more efficient.
2119 */
2120 char *p;
2121 char *c;
2122
2123 if (!dest || !size) {
2124 return dest;
2125 }
2126 if (ast_strlen_zero(s)) {
2127 *dest = '\0';
2128 return dest;
2129 }
2130
2131 for (p = dest; *s && --size; ++s, ++p) {
2132 /*
2133 * See if the character to escape is part of the standard escape
2134 * sequences. If so use its mapped counterpart.
2135 */
2136 c = strchr(escape_sequences, *s);
2137 if (c) {
2138 if (!--size) {
2139 /* Not enough room left for the escape sequence. */
2140 break;
2141 }
2142
2143 *p++ = '\\';
2145 } else {
2146 *p = *s;
2147 }
2148 }
2149 *p = '\0';
2150
2151 return dest;
2152}

References ast_strlen_zero(), c, escape_sequences, and escape_sequences_map.

Referenced by ast_escape_c_alloc().

◆ ast_escape_c_alloc()

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 2176 of file utils.c.

2177{
2178 size_t size = 0;
2179 char *dest = escape_alloc(s, &size);
2180
2181 return ast_escape_c(dest, s, size);
2182}
char * ast_escape_c(char *dest, const char *s, size_t size)
Escape standard 'C' sequences in the given string.
Definition: utils.c:2113

References ast_escape_c(), and escape_alloc().

Referenced by ast_manager_build_channel_state_string_prefix(), channel_new_callerid(), presence_state_to_ami(), and varset_to_ami().

◆ ast_escape_quoted()

char * ast_escape_quoted ( const char *  string,
char *  outbuf,
int  buflen 
)

Escape characters found in a quoted string.

Note
This function escapes quoted characters based on the 'qdtext' set of allowed characters from RFC 3261 section 25.1.
Parameters
stringstring to be escaped
outbufresulting escaped string
buflensize of output buffer
Returns
a pointer to the escaped string

Definition at line 817 of file utils.c.

818{
819 const char *ptr = string;
820 char *out = outbuf;
821 char *allow = "\t\v !"; /* allow LWS (minus \r and \n) and "!" */
822
823 while (*ptr && out - outbuf < buflen - 1) {
824 if (!(strchr(allow, *ptr))
825 && !(*ptr >= '#' && *ptr <= '[') /* %x23 - %x5b */
826 && !(*ptr >= ']' && *ptr <= '~') /* %x5d - %x7e */
827 && !((unsigned char) *ptr > 0x7f)) { /* UTF8-nonascii */
828
829 if (out - outbuf >= buflen - 2) {
830 break;
831 }
832 out += sprintf(out, "\\%c", (unsigned char) *ptr);
833 } else {
834 *out = *ptr;
835 out++;
836 }
837 ptr++;
838 }
839
840 if (buflen) {
841 *out = '\0';
842 }
843
844 return outbuf;
845}
const char * string
Definition: presencestate.c:74
FILE * out
Definition: utils/frame.c:33

References out, and string.

Referenced by ast_callerid_merge(), ast_sip_modify_id_header(), AST_TEST_DEFINE(), channel_read_pjsip(), create_new_id_hdr(), print_escaped_uri(), and refer_send().

◆ ast_escape_semicolons()

char * ast_escape_semicolons ( const char *  string,
char *  outbuf,
int  buflen 
)

Escape semicolons found in a string.

Parameters
stringstring to be escaped
outbufresulting escaped string
buflensize of output buffer
Returns
a pointer to the escaped string

Definition at line 847 of file utils.c.

848{
849 const char *ptr = string;
850 char *out = outbuf;
851
852 if (string == NULL || outbuf == NULL) {
853 ast_assert(string != NULL && outbuf != NULL);
854 return NULL;
855 }
856
857 while (*ptr && out - outbuf < buflen - 1) {
858 if (*ptr == ';') {
859 if (out - outbuf >= buflen - 2) {
860 break;
861 }
862 strcpy(out, "\\;");
863 out += 2;
864 } else {
865 *out = *ptr;
866 out++;
867 }
868 ptr++;
869 }
870
871 if (buflen) {
872 *out = '\0';
873 }
874
875 return outbuf;
876}

References ast_assert, NULL, out, and string.

Referenced by ast_config_text_file_save2(), handle_cli_dialplan_save(), and test_semi().

◆ ast_false()

int 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 2252 of file utils.c.

2253{
2254 if (ast_strlen_zero(s))
2255 return 0;
2256
2257 /* Determine if this is a false value */
2258 if (!strcasecmp(s, "no") ||
2259 !strcasecmp(s, "false") ||
2260 !strcasecmp(s, "n") ||
2261 !strcasecmp(s, "f") ||
2262 !strcasecmp(s, "0") ||
2263 !strcasecmp(s, "off"))
2264 return -1;
2265
2266 return 0;
2267}

References ast_strlen_zero().

Referenced by acf_faxopt_write(), acf_transaction_write(), action_updateconfig(), actual_load_config(), announce_user_count_all_handler(), aoc_cli_debug_enable(), bool_handler_fn(), boolflag_handler_fn(), build_peer(), build_user(), check_debug(), dahdi_set_dnd(), dahdi_set_mwi(), find_realtime(), function_ooh323_write(), handle_queue_set_member_ringinuse(), hook_write(), init_acf_query(), load_config(), manager_mute_mixmonitor(), manager_queue_member_ringinuse(), parking_feature_flag_cfg(), parse_empty_options(), parse_playtone(), prack_handler(), process_config(), process_dahdi(), read_pjproject_startup_options(), reload_config(), reload_single_member(), rt_handle_member_record(), rtp_reload(), run_agi(), set_config(), sla_build_trunk(), strings_to_mask(), and timers_handler().

◆ ast_file_is_readable()

int ast_file_is_readable ( const char *  filename)

Test that a file exists and is readable by the effective user.

Since
13.7.0
Parameters
filenameFile to test.
Return values
True(non-zero) if the file exists and is readable.
False(zero) if the file either doesn't exists or is not readable.

Definition at line 3143 of file utils.c.

3144{
3145#if defined(HAVE_EACCESS) || defined(HAVE_EUIDACCESS)
3146#if defined(HAVE_EUIDACCESS) && !defined(HAVE_EACCESS)
3147#define eaccess euidaccess
3148#endif
3149 return eaccess(filename, R_OK) == 0;
3150#else
3151 int fd = open(filename, O_RDONLY | O_NONBLOCK);
3152 if (fd < 0) {
3153 return 0;
3154 }
3155 close(fd);
3156 return 1;
3157#endif
3158}

Referenced by add_email_attachment(), as_check_common_config(), ast_media_cache_retrieve(), ast_rtp_dtls_cfg_parse(), retrieve_cert_from_cache(), transport_tls_file_handler(), and vs_check_common_config().

◆ ast_format_duration_hh_mm_ss()

void ast_format_duration_hh_mm_ss ( int  duration,
char *  buf,
size_t  length 
)

Formats a duration into HH:MM:SS.

Since
12
Parameters
durationThe time (in seconds) to format
bufA buffer to hold the formatted string'
lengthThe size of the buffer

Definition at line 2333 of file utils.c.

2334{
2335 int durh, durm, durs;
2336 durh = duration / 3600;
2337 durm = (duration % 3600) / 60;
2338 durs = duration % 60;
2339 snprintf(buf, length, "%02d:%02d:%02d", durh, durm, durs);
2340}
char buf[BUFSIZE]
Definition: eagi_proxy.c:66

References buf.

Referenced by cli_channel_print_body(), cli_channelstats_print_body(), handle_bridge_show_all(), handle_bridge_show_specific(), and stasis_show_topic().

◆ ast_get_tid()

int ast_get_tid ( void  )

Get current thread ID.

Returns
the ID if platform is supported, else -1

Definition at line 2788 of file utils.c.

2789{
2790 int ret = -1;
2791#if defined (__linux) && defined(SYS_gettid)
2792 ret = syscall(SYS_gettid); /* available since Linux 1.4.11 */
2793#elif defined(__sun)
2794 ret = pthread_self();
2795#elif defined(__APPLE__)
2796 ret = mach_thread_self();
2797 mach_port_deallocate(mach_task_self(), ret);
2798#elif defined(__FreeBSD__)
2799 long lwpid;
2800 thr_self(&lwpid);
2801 ret = lwpid;
2802#elif defined(__NetBSD__)
2803 ret = _lwp_self();
2804#elif defined(__OpenBSD__)
2805 ret = getthrid();
2806#endif
2807 return ret;
2808}

Referenced by __ao2_ref(), ast_hangup(), ast_register_thread(), dummy_start(), format_log_message_ap(), and internal_ao2_alloc().

◆ ast_get_time_t()

int ast_get_time_t ( const char *  src,
time_t *  dst,
time_t  _default,
int *  consumed 
)

get values from config variables.

Parse a time (integer) string.

Definition at line 2482 of file utils.c.

2483{
2484 long t;
2485 int scanned;
2486
2487 if (dst == NULL)
2488 return -1;
2489
2490 *dst = _default;
2491
2492 if (ast_strlen_zero(src))
2493 return -1;
2494
2495 /* only integer at the moment, but one day we could accept more formats */
2496 if (sscanf(src, "%30ld%n", &t, &scanned) == 1) {
2497 *dst = t;
2498 if (consumed)
2499 *consumed = scanned;
2500 return 0;
2501 } else
2502 return -1;
2503}

References ast_strlen_zero(), and NULL.

Referenced by cache_lookup_internal(), dundi_show_cache(), dundi_show_hints(), handle_saydatetime(), load_password(), play_message_datetime(), process_clearcache(), realtime_peer(), and sayunixtime_exec().

◆ ast_get_timeval()

int ast_get_timeval ( const char *  src,
struct timeval *  dst,
struct timeval  _default,
int *  consumed 
)

get values from config variables.

Parse a time (float) string.

Definition at line 2455 of file utils.c.

2456{
2457 long double dtv = 0.0;
2458 int scanned;
2459
2460 if (dst == NULL)
2461 return -1;
2462
2463 *dst = _default;
2464
2465 if (ast_strlen_zero(src))
2466 return -1;
2467
2468 /* only integer at the moment, but one day we could accept more formats */
2469 if (sscanf(src, "%30Lf%n", &dtv, &scanned) > 0) {
2470 dst->tv_sec = dtv;
2471 dst->tv_usec = (dtv - dst->tv_sec) * 1000000.0;
2472 if (consumed)
2473 *consumed = scanned;
2474 return 0;
2475 } else
2476 return -1;
2477}

References ast_strlen_zero(), and NULL.

Referenced by acf_strftime(), expiration_str2struct(), persistence_expires_str2struct(), and timeval_str2struct().

◆ ast_gethostbyname()

struct hostent * ast_gethostbyname ( const char *  host,
struct ast_hostent hp 
)

Re-entrant (thread safe) version of gethostbyname that replaces the standard gethostbyname (which is not thread safe)

Thread-safe gethostbyname function to use in Asterisk.

Definition at line 199 of file utils.c.

200{
201#ifndef HAVE_GETHOSTBYNAME_R_5
202 int res;
203#endif
204 int herrno;
205 int dots = 0;
206 const char *s;
207 struct hostent *result = NULL;
208 /* Although it is perfectly legitimate to lookup a pure integer, for
209 the sake of the sanity of people who like to name their peers as
210 integers, we break with tradition and refuse to look up a
211 pure integer */
212 s = host;
213 while (s && *s) {
214 if (*s == '.')
215 dots++;
216 else if (!isdigit(*s))
217 break;
218 s++;
219 }
220 if (!s || !*s) {
221 /* Forge a reply for IP's to avoid octal IP's being interpreted as octal */
222 if (dots != 3)
223 return NULL;
224 memset(hp, 0, sizeof(struct ast_hostent));
225 hp->hp.h_addrtype = AF_INET;
226 hp->hp.h_addr_list = (void *) hp->buf;
227 hp->hp.h_addr = hp->buf + sizeof(void *);
228 /* For AF_INET, this will always be 4 */
229 hp->hp.h_length = 4;
230 if (inet_pton(AF_INET, host, hp->hp.h_addr) > 0)
231 return &hp->hp;
232 return NULL;
233
234 }
235#ifdef HAVE_GETHOSTBYNAME_R_5
236 result = gethostbyname_r(host, &hp->hp, hp->buf, sizeof(hp->buf), &herrno);
237
238 if (!result || !hp->hp.h_addr_list || !hp->hp.h_addr_list[0])
239 return NULL;
240#else
241 res = gethostbyname_r(host, &hp->hp, hp->buf, sizeof(hp->buf), &result, &herrno);
242
243 if (res || !result || !hp->hp.h_addr_list || !hp->hp.h_addr_list[0])
244 return NULL;
245#endif
246 return &hp->hp;
247}
char buf[1024]
Definition: utils.h:228
struct hostent hp
Definition: utils.h:227

References ast_hostent::buf, ast_hostent::hp, NULL, and result.

◆ ast_inet_ntoa()

const char * ast_inet_ntoa ( struct in_addr  ia)

ast_inet_ntoa: Recursive thread safe replacement of inet_ntoa

thread-safe replacement for inet_ntoa().

Definition at line 964 of file utils.c.

965{
966 char *buf;
967
968 if (!(buf = ast_threadstorage_get(&inet_ntoa_buf, INET_ADDRSTRLEN)))
969 return "";
970
971 return inet_ntop(AF_INET, &ia, buf, INET_ADDRSTRLEN);
972}
void * ast_threadstorage_get(struct ast_threadstorage *ts, size_t init_size)
Retrieve thread storage.
static struct ast_threadstorage inet_ntoa_buf
Definition: utils.c:85

References ast_threadstorage_get(), buf, and inet_ntoa_buf.

Referenced by _stun_show_status(), ast_parse_arg(), create_client(), get_defaults(), get_to_address(), handle_cli_rtp_settings(), handle_error(), handle_stun_timeout(), iax_server(), parsing(), phoneprov_callback(), process_request(), reload_config(), rtp_reload(), score_address(), send_raw_client(), send_start_rtp(), send_trunk(), show_main_page(), start_rtp(), stun_monitor_request(), unistim_show_devices(), unistim_show_info(), and unistimsock_read().

◆ ast_join_delim()

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 2414 of file utils.c.

2415{
2416 int x, ofs = 0;
2417 const char *src;
2418
2419 /* Join words into a string */
2420 if (!s)
2421 return;
2422 for (x = 0; ofs < len && x < size && w[x] ; x++) {
2423 if (x > 0)
2424 s[ofs++] = delim;
2425 for (src = w[x]; *src && ofs < len; src++)
2426 s[ofs++] = *src;
2427 }
2428 if (ofs == len)
2429 ofs--;
2430 s[ofs] = '\0';
2431}

References len().

Referenced by ast_sip_auths_to_str().

◆ ast_md5_hash()

void ast_md5_hash ( char *  output,
const char *  input 
)

Produce 32 char MD5 hash of value.

Produces MD5 hash based on input string.

Definition at line 250 of file utils.c.

251{
252 struct MD5Context md5;
253 unsigned char digest[16];
254 char *ptr;
255 int x;
256
257 MD5Init(&md5);
258 MD5Update(&md5, (const unsigned char *) input, strlen(input));
259 MD5Final(digest, &md5);
260 ptr = output;
261 for (x = 0; x < 16; x++)
262 ptr += sprintf(ptr, "%02hhx", digest[x]);
263}
static int input(yyscan_t yyscanner)
Definition: ast_expr2f.c:1570
static int md5(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
Definition: func_md5.c:55
void MD5Update(struct MD5Context *context, unsigned char const *buf, unsigned len)
Definition: md5.c:72
void MD5Init(struct MD5Context *context)
Definition: md5.c:57
void MD5Final(unsigned char digest[MD5_DIGEST_LENGTH], struct MD5Context *context)
Definition: md5.c:120
Definition: md5.h:30

References input(), md5(), MD5Final(), MD5Init(), and MD5Update().

Referenced by __init_manager(), ast_sip_location_create_contact(), AST_TEST_DEFINE(), auth_exec(), auth_http_callback(), build_nonce(), md5(), and permanent_uri_handler().

◆ ast_mkdir()

int ast_mkdir ( const char *  path,
int  mode 
)

Recursively create directory path.

Parameters
pathThe directory path to create
modeThe permissions with which to try to create the directory
Return values
0on success
Returns
error code otherwise

Creates a directory path, creating parent directories as needed.

Definition at line 2515 of file utils.c.

2516{
2517 char *ptr;
2518 int len = strlen(path), count = 0, x, piececount = 0;
2519 char *tmp = ast_strdupa(path);
2520 char **pieces;
2521 char *fullpath = ast_alloca(len + 1);
2522 int res = 0;
2523
2524 for (ptr = tmp; *ptr; ptr++) {
2525 if (*ptr == '/')
2526 count++;
2527 }
2528
2529 /* Count the components to the directory path */
2530 pieces = ast_alloca(count * sizeof(*pieces));
2531 for (ptr = tmp; *ptr; ptr++) {
2532 if (*ptr == '/') {
2533 *ptr = '\0';
2534 pieces[piececount++] = ptr + 1;
2535 }
2536 }
2537
2538 *fullpath = '\0';
2539 for (x = 0; x < piececount; x++) {
2540 /* This looks funky, but the buffer is always ideally-sized, so it's fine. */
2541 strcat(fullpath, "/");
2542 strcat(fullpath, pieces[x]);
2543 res = mkdir(fullpath, mode);
2544 if (res && errno != EEXIST)
2545 return errno;
2546 }
2547 return 0;
2548}
#define ast_alloca(size)
call __builtin_alloca to ensure we get gcc builtin semantics
Definition: astmm.h:288
#define ast_strdupa(s)
duplicate a string in memory from the stack
Definition: astmm.h:298

References ast_alloca, ast_strdupa, errno, and len().

Referenced by ast_file_fdtemp(), ast_logger_rotate_channel(), conf_rec_name(), conf_run(), create_destination_directory(), create_dirpath(), dictate_exec(), filename_parse(), init_logger(), load_module(), reload_logger(), remove_from_queue(), setup_privacy_args(), sms_nextoutgoing(), sms_writefile(), test_vm_api_create_voicemail_folder(), testclient_exec(), testserver_exec(), and write_history().

◆ ast_parse_digest()

int ast_parse_digest ( const char *  digest,
struct ast_http_digest d,
int  request,
int  pedantic 
)

Parse digest authorization header.

Returns
Returns -1 if we have no auth or something wrong with digest.
Note
This function may be used for Digest request and response header. request arg is set to nonzero, if we parse Digest Request. pedantic arg can be set to nonzero if we need to do addition Digest check.

Definition at line 2674 of file utils.c.

2674 {
2675 char *c;
2676 struct ast_str *str = ast_str_create(16);
2677
2678 /* table of recognised keywords, and places where they should be copied */
2679 const struct x {
2680 const char *key;
2681 const ast_string_field *field;
2682 } *i, keys[] = {
2683 { "username=", &d->username },
2684 { "realm=", &d->realm },
2685 { "nonce=", &d->nonce },
2686 { "uri=", &d->uri },
2687 { "domain=", &d->domain },
2688 { "response=", &d->response },
2689 { "cnonce=", &d->cnonce },
2690 { "opaque=", &d->opaque },
2691 /* Special cases that cannot be directly copied */
2692 { "algorithm=", NULL },
2693 { "qop=", NULL },
2694 { "nc=", NULL },
2695 { NULL, 0 },
2696 };
2697
2698 if (ast_strlen_zero(digest) || !d || !str) {
2699 ast_free(str);
2700 return -1;
2701 }
2702
2703 ast_str_set(&str, 0, "%s", digest);
2704
2706
2707 if (strncasecmp(c, "Digest ", strlen("Digest "))) {
2708 ast_log(LOG_WARNING, "Missing Digest.\n");
2709 ast_free(str);
2710 return -1;
2711 }
2712 c += strlen("Digest ");
2713
2714 /* lookup for keys/value pair */
2715 while (c && *c && *(c = ast_skip_blanks(c))) {
2716 /* find key */
2717 for (i = keys; i->key != NULL; i++) {
2718 char *src, *separator;
2719 int unescape = 0;
2720 if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
2721 continue;
2722 }
2723
2724 /* Found. Skip keyword, take text in quotes or up to the separator. */
2725 c += strlen(i->key);
2726 if (*c == '"') {
2727 src = ++c;
2728 separator = "\"";
2729 unescape = 1;
2730 } else {
2731 src = c;
2732 separator = ",";
2733 }
2734 strsep(&c, separator); /* clear separator and move ptr */
2735 if (unescape) {
2736 ast_unescape_c(src);
2737 }
2738 if (i->field) {
2739 ast_string_field_ptr_set(d, i->field, src);
2740 } else {
2741 /* Special cases that require additional processing */
2742 if (!strcasecmp(i->key, "algorithm=")) {
2743 if (strcasecmp(src, "MD5")) {
2744 ast_log(LOG_WARNING, "Digest algorithm: \"%s\" not supported.\n", src);
2745 ast_free(str);
2746 return -1;
2747 }
2748 } else if (!strcasecmp(i->key, "qop=") && !strcasecmp(src, "auth")) {
2749 d->qop = 1;
2750 } else if (!strcasecmp(i->key, "nc=")) {
2751 unsigned long u;
2752 if (sscanf(src, "%30lx", &u) != 1) {
2753 ast_log(LOG_WARNING, "Incorrect Digest nc value: \"%s\".\n", src);
2754 ast_free(str);
2755 return -1;
2756 }
2757 ast_string_field_set(d, nc, src);
2758 }
2759 }
2760 break;
2761 }
2762 if (i->key == NULL) { /* not found, try ',' */
2763 strsep(&c, ",");
2764 }
2765 }
2766 ast_free(str);
2767
2768 /* Digest checkout */
2769 if (ast_strlen_zero(d->realm) || ast_strlen_zero(d->nonce)) {
2770 /* "realm" and "nonce" MUST be always exist */
2771 return -1;
2772 }
2773
2774 if (!request) {
2775 /* Additional check for Digest response */
2776 if (ast_strlen_zero(d->username) || ast_strlen_zero(d->uri) || ast_strlen_zero(d->response)) {
2777 return -1;
2778 }
2779
2780 if (pedantic && d->qop && (ast_strlen_zero(d->cnonce) || ast_strlen_zero(d->nc))) {
2781 return -1;
2782 }
2783 }
2784
2785 return 0;
2786}
const char * str
Definition: app_jack.c:150
char * strsep(char **str, const char *delims)
static int request(void *obj)
Definition: chan_pjsip.c:2619
#define ast_string_field_set(x, field, data)
Set a field to a simple string value.
Definition: stringfields.h:521
const char * ast_string_field
Definition: stringfields.h:190
#define ast_string_field_ptr_set(x, ptr, data)
Set a field to a simple string value.
Definition: stringfields.h:475
char * ast_str_buffer(const struct ast_str *buf)
Returns the string buffer within the ast_str buf.
Definition: strings.h:761
#define ast_str_create(init_len)
Create a malloc'ed dynamic length string.
Definition: strings.h:659
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)
Gets a pointer to the first non-whitespace character in a string.
Definition: strings.h:161
Support for dynamic strings.
Definition: strings.h:623
static struct test_val d
char * ast_unescape_c(char *src)
Convert some C escape sequences.
Definition: utils.c:2019

References ast_free, ast_log, ast_skip_blanks(), ast_str_buffer(), ast_str_create, ast_str_set(), ast_string_field_ptr_set, ast_string_field_set, ast_strlen_zero(), ast_unescape_c(), c, d, LOG_WARNING, NULL, request(), str, and strsep().

Referenced by auth_http_callback().

◆ ast_process_quotes_and_slashes()

char * ast_process_quotes_and_slashes ( char *  start,
char  find,
char  replace_with 
)

Process a string to find and replace characters.

Parameters
startThe string to analyze
findThe character to find
replace_withThe character that will replace the one we are looking for

Definition at line 2388 of file utils.c.

2389{
2390 char *dataPut = start;
2391 int inEscape = 0;
2392 int inQuotes = 0;
2393
2394 for (; *start; start++) {
2395 if (inEscape) {
2396 *dataPut++ = *start; /* Always goes verbatim */
2397 inEscape = 0;
2398 } else {
2399 if (*start == '\\') {
2400 inEscape = 1; /* Do not copy \ into the data */
2401 } else if (*start == '\'') {
2402 inQuotes = 1 - inQuotes; /* Do not copy ' into the data */
2403 } else {
2404 /* Replace , with |, unless in quotes */
2405 *dataPut++ = inQuotes ? *start : ((*start == find) ? replace_with : *start);
2406 }
2407 }
2408 }
2409 if (start != dataPut)
2410 *dataPut = 0;
2411 return dataPut;
2412}

◆ ast_pthread_create_detached_stack()

int ast_pthread_create_detached_stack ( pthread_t *  thread,
pthread_attr_t *  attr,
void *(*)(void *)  start_routine,
void *  data,
size_t  stacksize,
const char *  file,
const char *  caller,
int  line,
const char *  start_fn 
)

Definition at line 1709 of file utils.c.

1712{
1713 unsigned char attr_destroy = 0;
1714 int res;
1715
1716 if (!attr) {
1717 attr = ast_alloca(sizeof(*attr));
1718 pthread_attr_init(attr);
1719 attr_destroy = 1;
1720 }
1721
1722 if ((errno = pthread_attr_setdetachstate(attr, PTHREAD_CREATE_DETACHED)))
1723 ast_log(LOG_WARNING, "pthread_attr_setdetachstate: %s\n", strerror(errno));
1724
1725 res = ast_pthread_create_stack(thread, attr, start_routine, data,
1726 stacksize, file, caller, line, start_fn);
1727
1728 if (attr_destroy)
1729 pthread_attr_destroy(attr);
1730
1731 return res;
1732}
pthread_t thread
Definition: app_sla.c:335
int ast_pthread_create_stack(pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *), void *data, size_t stacksize, const char *file, const char *caller, int line, const char *start_fn)
Definition: utils.c:1661

References ast_alloca, ast_log, ast_pthread_create_stack(), thr_arg::data, errno, make_ari_stubs::file, LOG_WARNING, thr_arg::start_routine, and thread.

◆ ast_pthread_create_stack()

int ast_pthread_create_stack ( pthread_t *  thread,
pthread_attr_t *  attr,
void *(*)(void *)  start_routine,
void *  data,
size_t  stacksize,
const char *  file,
const char *  caller,
int  line,
const char *  start_fn 
)

Definition at line 1661 of file utils.c.

1664{
1665#if !defined(LOW_MEMORY)
1666 struct thr_arg *a;
1667#endif
1668
1669 if (!attr) {
1670 attr = ast_alloca(sizeof(*attr));
1671 pthread_attr_init(attr);
1672 }
1673
1674#if defined(__linux__) || defined(__FreeBSD__)
1675 /* On Linux and FreeBSD , pthread_attr_init() defaults to PTHREAD_EXPLICIT_SCHED,
1676 which is kind of useless. Change this here to
1677 PTHREAD_INHERIT_SCHED; that way the -p option to set realtime
1678 priority will propagate down to new threads by default.
1679 This does mean that callers cannot set a different priority using
1680 PTHREAD_EXPLICIT_SCHED in the attr argument; instead they must set
1681 the priority afterwards with pthread_setschedparam(). */
1682 if ((errno = pthread_attr_setinheritsched(attr, PTHREAD_INHERIT_SCHED)))
1683 ast_log(LOG_WARNING, "pthread_attr_setinheritsched: %s\n", strerror(errno));
1684#endif
1685
1686 if (!stacksize)
1687 stacksize = AST_STACKSIZE;
1688
1689 if ((errno = pthread_attr_setstacksize(attr, stacksize ? stacksize : AST_STACKSIZE)))
1690 ast_log(LOG_WARNING, "pthread_attr_setstacksize: %s\n", strerror(errno));
1691
1692#if !defined(LOW_MEMORY)
1693 if ((a = ast_malloc(sizeof(*a)))) {
1694 a->start_routine = start_routine;
1695 a->data = data;
1697 if (ast_asprintf(&a->name, "%-20s started at [%5d] %s %s()",
1698 start_fn, line, file, caller) < 0) {
1699 a->name = NULL;
1700 }
1701 data = a;
1702 }
1703#endif /* !LOW_MEMORY */
1704
1705 return pthread_create(thread, attr, start_routine, data); /* We're in ast_pthread_create, so it's okay */
1706}
#define ast_asprintf(ret, fmt,...)
A wrapper for asprintf()
Definition: astmm.h:267
#define pthread_create
Definition: lock.h:649
const char * name
void * data
Definition: utils.c:1598
void *(* start_routine)(void *)
Definition: utils.c:1597
static struct test_val a
static void * dummy_start(void *data)
Definition: utils.c:1609

References a, ast_alloca, ast_asprintf, ast_log, ast_malloc, AST_STACKSIZE, thr_arg::data, dummy_start(), errno, make_ari_stubs::file, LOG_WARNING, test_val::name, NULL, pthread_create, thr_arg::start_routine, and thread.

Referenced by ast_pthread_create_detached_stack().

◆ ast_random()

long int ast_random ( void  )

Definition at line 2348 of file utils.c.

2349{
2350 long int res;
2351
2352 if (dev_urandom_fd >= 0) {
2353 int read_res = read(dev_urandom_fd, &res, sizeof(res));
2354 if (read_res > 0) {
2355 long int rm = RAND_MAX;
2356 res = res < 0 ? ~res : res;
2357 rm++;
2358 return res % rm;
2359 }
2360 }
2361
2362 /* XXX - Thread safety really depends on the libc, not the OS.
2363 *
2364 * But... popular Linux libc's (uClibc, glibc, eglibc), all have a
2365 * somewhat thread safe random(3) (results are random, but not
2366 * reproducible). The libc's for other systems (BSD, et al.), not so
2367 * much.
2368 */
2369#ifdef linux
2370 res = random();
2371#else
2373 res = random();
2375#endif
2376 return res;
2377}
#define ast_mutex_unlock(a)
Definition: lock.h:197
#define ast_mutex_lock(a)
Definition: lock.h:196
static int dev_urandom_fd
Definition: utils.c:974
static ast_mutex_t randomlock
Definition: utils.c:2345

References ast_mutex_lock, ast_mutex_unlock, dev_urandom_fd, and randomlock.

Referenced by acf_rand_exec(), action_challenge(), agi_handle_command(), app_exec(), ast_generate_random_string(), ast_lock_path_lockfile(), ast_rtp_change_source(), ast_rtp_new(), AST_TEST_DEFINE(), ast_udptl_new_with_bindaddr(), astobj2_test_1_helper(), auth_http_callback(), authenticate_request(), build_iv(), build_rand_pad(), calc_metric(), calc_rxstamp(), caldav_write_event(), create_channel_name(), create_local_sdp(), dns_srv_sort(), generate_parked_user(), generate_random_string(), generic_http_callback(), get_trans_id(), get_unused_callno(), handle_cli_sched_bench(), iax2_key_rotate(), jingle_add_ice_udp_candidates_to_transport(), jingle_alloc(), jingle_new(), load_module(), make_email_file(), mbl_new(), moh_files_alloc(), moh_files_next(), multicast_rtp_new(), ogg_vorbis_rewrite(), page_exec(), process_weights(), registry_authrequest(), reschedule_reinvite(), rtp_allocate_transport(), say_periodic_announcement(), sendmail(), sip_outbound_registration_perform(), socket_read(), sorcery_memory_cache_thrash_retrieve(), sorcery_memory_cache_thrash_update(), stun_req_id(), test_ao2_find_w_no_flags(), test_ao2_find_w_OBJ_KEY(), test_ao2_find_w_OBJ_PARTIAL_KEY(), test_ao2_find_w_OBJ_POINTER(), test_files_get_one(), try_firmware(), websocket_client_create_key(), and websocket_mask_payload().

◆ ast_regex_string_to_regex_pattern()

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 2215 of file utils.c.

2216{
2217 int regex_len = strlen(regex_string);
2218 int ret = 3;
2219
2220 /* Chop off the leading / if there is one */
2221 if ((regex_len >= 1) && (regex_string[0] == '/')) {
2222 ast_str_set(regex_pattern, 0, "%s", regex_string + 1);
2223 ret -= 2;
2224 }
2225
2226 /* Chop off the ending / if there is one */
2227 if ((regex_len > 1) && (regex_string[regex_len - 1] == '/')) {
2228 ast_str_truncate(*regex_pattern, -1);
2229 ret -= 1;
2230 }
2231
2232 return ret;
2233}
char * ast_str_truncate(struct ast_str *buf, ssize_t len)
Truncates the enclosed string to the given length.
Definition: strings.h:786

References ast_str_set(), and ast_str_truncate().

Referenced by ast_manager_hangup_helper(), mwi_mailbox_delete(), and mwi_mailbox_get().

◆ ast_remaining_ms()

int ast_remaining_ms ( struct timeval  start,
int  max_ms 
)

Calculate remaining milliseconds given a starting timestamp and upper bound.

If the upper bound is negative, then this indicates that there is no upper bound on the amount of time to wait. This will result in a negative return.

Parameters
startWhen timing started being calculated
max_msThe maximum number of milliseconds to wait from start. May be negative.
Returns
The number of milliseconds left to wait for. May be negative.

Definition at line 2317 of file utils.c.

2318{
2319 int ms;
2320
2321 if (max_ms < 0) {
2322 ms = max_ms;
2323 } else {
2324 ms = max_ms - ast_tvdiff_ms(ast_tvnow(), start);
2325 if (ms < 0) {
2326 ms = 0;
2327 }
2328 }
2329
2330 return ms;
2331}

References ast_tvdiff_ms(), and ast_tvnow().

Referenced by __analog_ss_thread(), __ast_answer(), __ast_request_and_dial(), analog_ss_thread(), ast_iostream_write(), ast_recvtext(), ast_stun_request(), ast_waitfordigit_full(), disable_t38(), generic_fax_exec(), iostream_read(), parking_set_duration(), read_mf_digits(), read_sf_digits(), receivefax_t38_init(), record_exec(), safe_sleep_conditional(), scan_exec(), sendfax_t38_init(), SLEEP_SPINNER(), wait_exec(), wait_for_answer(), wait_for_signal_or_hangup(), waitforcond_exec(), and waitforring_exec().

◆ ast_replace_subargument_delimiter()

void ast_replace_subargument_delimiter ( char *  s)

Replace '^' in a string with ','.

Parameters
sString within which to replace characters

Definition at line 2379 of file utils.c.

2380{
2381 for (; *s; s++) {
2382 if (*s == '^') {
2383 *s = ',';
2384 }
2385 }
2386}

Referenced by app_exec(), ast_bridge_set_after_go_on(), dial_exec_full(), originate_exec(), page_exec(), and queue_exec().

◆ ast_safe_mkdir()

int ast_safe_mkdir ( const char *  base_path,
const char *  path,
int  mode 
)

Recursively create directory path, but only if it resolves within the given base_path.

If base_path does not exist, it will not be created and this function returns EPERM.

Parameters
base_path
pathThe directory path to create
modeThe permissions with which to try to create the directory
Return values
0on success
Returns
an error code otherwise

Definition at line 2620 of file utils.c.

2621{
2622 RAII_VAR(char *, absolute_base_path, NULL, ast_std_free);
2623 RAII_VAR(char *, p, NULL, ast_free);
2624
2625 if (base_path == NULL || path == NULL) {
2626 errno = EFAULT;
2627 return errno;
2628 }
2629
2630 p = ast_strdup(path);
2631 if (p == NULL) {
2632 errno = ENOMEM;
2633 return errno;
2634 }
2635
2636 absolute_base_path = realpath(base_path, NULL);
2637 if (absolute_base_path == NULL) {
2638 return errno;
2639 }
2640
2641 return safe_mkdir(absolute_base_path, p, mode);
2642}
void ast_std_free(void *ptr)
Definition: astmm.c:1734
static int safe_mkdir(const char *base_path, char *path, int mode)
Definition: utils.c:2550
#define RAII_VAR(vartype, varname, initval, dtor)
Declare a variable that will call a destructor function when it goes out of scope.
Definition: utils.h:978

References ast_free, ast_std_free(), ast_strdup, errno, NULL, RAII_VAR, and safe_mkdir().

Referenced by AST_TEST_DEFINE(), stasis_app_control_record(), and stasis_app_stored_recording_copy().

◆ ast_set_default_eid()

void ast_set_default_eid ( struct ast_eid eid)

Fill in an ast_eid with the default eid of this machine.

Since
1.6.1

Definition at line 3037 of file utils.c.

3038{
3039 int s;
3040 int i;
3041 struct ifreq *ifr;
3042 struct ifreq *ifrp;
3043 struct ifconf ifc;
3044 char *buf = NULL;
3045 char eid_str[20];
3046 int bufsz, num_interfaces;
3047 unsigned char empty_mac[6] = {0, 0, 0, 0, 0, 0};
3048 unsigned char full_mac[6] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
3049
3050 s = socket(AF_INET, SOCK_STREAM, 0);
3051 if (s < 0) {
3052 ast_log(LOG_WARNING, "Unable to open socket for seeding global EID. "
3053 "You will have to set it manually.\n");
3054 return;
3055 }
3056
3057 ifc.ifc_len = 0;
3058 ifc.ifc_buf = NULL;
3059 if (ioctl(s, SIOCGIFCONF, &ifc) || ifc.ifc_len <= 0) {
3060 ast_log(LOG_WARNING, "No ethernet interface found for seeding global EID. "
3061 "You will have to set it manually.\n");
3062 close(s);
3063 return;
3064 }
3065 bufsz = ifc.ifc_len;
3066
3067 if (!(buf = ast_malloc(bufsz))) {
3068 ast_log(LOG_WARNING, "Unable to allocate memory for seeding global EID. "
3069 "You will have to set it manually.\n");
3070 close(s);
3071 return;
3072 }
3073
3074 ifc.ifc_buf = buf;
3075 if (ioctl(s, SIOCGIFCONF, &ifc) < 0) {
3076 ast_log(LOG_WARNING, "Unable to retrieve ethernet interfaces for seeding global EID. "
3077 "You will have to set it manually.\n");
3078 ast_free(buf);
3079 close(s);
3080 return;
3081 }
3082
3083 ifrp = ifc.ifc_req;
3084 num_interfaces = ifc.ifc_len / sizeof(*ifr);
3085
3086 for (i = 0; i < num_interfaces; i++) {
3087 ifr = &ifrp[i];
3088 if (!ioctl(s, SIOCGIFHWADDR, ifr)) {
3089 unsigned char *hwaddr = (unsigned char *) ifr->ifr_hwaddr.sa_data;
3090
3091 if (!(memcmp(hwaddr, &empty_mac, 6) && memcmp(hwaddr, &full_mac, 6))) {
3092 continue;
3093 }
3094
3095 memcpy(eid, hwaddr, sizeof(*eid));
3096 ast_debug(1, "Seeding global EID '%s' from '%s' using 'siocgifhwaddr'\n",
3097 ast_eid_to_str(eid_str, sizeof(eid_str), eid), ifr->ifr_name);
3098 ast_free(buf);
3099 close(s);
3100 return;
3101 }
3102 }
3103
3104 ast_log(LOG_WARNING, "No ethernet interface found for seeding global EID. "
3105 "You will have to set it manually.\n");
3106 ast_free(buf);
3107 close(s);
3108
3109 return;
3110}
if(!yyg->yy_init)
Definition: ast_expr2f.c:854
char * ast_eid_to_str(char *s, int maxlen, struct ast_eid *eid)
Convert an EID to a string.
Definition: utils.c:2875

References ast_debug, ast_eid_to_str(), ast_free, ast_log, ast_malloc, buf, if(), LOG_WARNING, and NULL.

Referenced by load_asterisk_conf().

◆ ast_sha1_hash()

void ast_sha1_hash ( char *  output,
const char *  input 
)

Produce 40 char SHA1 hash of value.

Produces SHA1 hash based on input string.

Definition at line 266 of file utils.c.

267{
268 struct SHA1Context sha;
269 char *ptr;
270 int x;
271 uint8_t Message_Digest[20];
272
273 SHA1Reset(&sha);
274
275 SHA1Input(&sha, (const unsigned char *) input, strlen(input));
276
277 SHA1Result(&sha, Message_Digest);
278 ptr = output;
279 for (x = 0; x < 20; x++)
280 ptr += sprintf(ptr, "%02hhx", Message_Digest[x]);
281}
int SHA1Result(SHA1Context *, uint8_t Message_Digest[SHA1HashSize])
SHA1Result Returns the resulting 160-bit digest.
Definition: sha1.c:226
int SHA1Input(SHA1Context *, const uint8_t *bytes, unsigned int bytecount)
int SHA1Reset(SHA1Context *)
SHA1Reset.
Definition: sha1.c:101

References input(), SHA1Input(), SHA1Reset(), and SHA1Result().

Referenced by ast_tcptls_server_start(), AST_TEST_DEFINE(), ctx_populate(), handle_call_token(), media_cache_item_sync_to_astdb(), sha1(), xmpp_client_authenticate_digest(), and xmpp_component_authenticate().

◆ ast_sha1_hash_uint()

void ast_sha1_hash_uint ( uint8_t *  digest,
const char *  input 
)

Produce a 20 byte SHA1 hash of value.

Produces SHA1 hash based on input string, stored in uint8_t array.

Definition at line 284 of file utils.c.

285{
286 struct SHA1Context sha;
287
288 SHA1Reset(&sha);
289
290 SHA1Input(&sha, (const unsigned char *) input, strlen(input));
291
292 SHA1Result(&sha, digest);
293}

References input(), SHA1Input(), SHA1Reset(), and SHA1Result().

Referenced by websocket_combine_key().

◆ ast_str_to_eid()

int ast_str_to_eid ( struct ast_eid eid,
const char *  s 
)

Convert a string into an EID.

This function expects an EID in the format: 00:11:22:33:44:55

Return values
0success
non-zerofailure
Since
1.6.1

Definition at line 3113 of file utils.c.

3114{
3115 unsigned int eid_int[6];
3116 int x;
3117
3118 if (sscanf(s, "%2x:%2x:%2x:%2x:%2x:%2x", &eid_int[0], &eid_int[1], &eid_int[2],
3119 &eid_int[3], &eid_int[4], &eid_int[5]) != 6) {
3120 return -1;
3121 }
3122
3123 for (x = 0; x < 6; x++) {
3124 eid->eid[x] = eid_int[x];
3125 }
3126
3127 return 0;
3128}

References ast_eid::eid.

Referenced by asterisk_publication_devicestate_state_change(), asterisk_publication_mwi_state_change(), build_peer(), dundi_do_query(), load_asterisk_conf(), set_config(), and xmpp_pubsub_handle_event().

◆ ast_strip_quoted()

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:

ast_strip_quoted(buf, "\"", "\"");
ast_strip_quoted(buf, "'", "'");
ast_strip_quoted(buf, "[{(", "]})");
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:1854

Definition at line 1854 of file utils.c.

1855{
1856 char *e;
1857 char *q;
1858
1859 s = ast_strip(s);
1860 if ((q = strchr(beg_quotes, *s)) && *q != '\0') {
1861 e = s + strlen(s) - 1;
1862 if (*e == *(end_quotes + (q - beg_quotes))) {
1863 s++;
1864 *e = '\0';
1865 }
1866 }
1867
1868 return s;
1869}
char * ast_strip(char *s)
Strip leading/trailing whitespace from a string.
Definition: strings.h:223

References ast_strip().

Referenced by applicationmap_handler(), ast_callerid_parse(), ast_sip_validate_uri_length(), ast_strsep(), ast_strsep_quoted(), dialog_info_generate_body_content(), hfp_parse_clip(), iftime(), load_values_config(), parse_cookies(), parse_dial_string(), pidf_allocate_body(), set_redirecting_reason(), and xpidf_allocate_body().

◆ ast_strsep()

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:

char *mystr = ast_strdupa("abc=def,ghi='zzz=yyy,456',jkl");
char *token, *token2, *token3;
while((token = ast_strsep(&mystr, ',', AST_STRSEP_STRIP))) {
// 1st token will be aaa=def
// 2nd token will be ghi='zzz=yyy,456'
while((token2 = ast_strsep(&token, '=', AST_STRSEP_STRIP))) {
// 1st token2 will be ghi
// 2nd token2 will be zzz=yyy,456
while((token3 = ast_strsep(&token2, ',', AST_STRSEP_STRIP))) {
// 1st token3 will be zzz=yyy
// 2nd token3 will be 456
// and so on
}
}
// 3rd token will be jkl
}
@ AST_STRSEP_STRIP
Definition: strings.h:255
char * ast_strsep(char **s, const char sep, uint32_t flags)
Act like strsep but ignore separators inside quotes.
Definition: utils.c:1871

Definition at line 1871 of file utils.c.

1872{
1873 char *st = *iss;
1874 char *is;
1875 int inquote = 0;
1876 int found = 0;
1877 char stack[8];
1878
1879 if (ast_strlen_zero(st)) {
1880 *iss = NULL;
1881 return st;
1882 }
1883
1884 memset(stack, 0, sizeof(stack));
1885
1886 for(is = st; *is; is++) {
1887 if (*is == '\\') {
1888 if (*++is != '\0') {
1889 is++;
1890 } else {
1891 break;
1892 }
1893 }
1894
1895 if (*is == '\'' || *is == '"') {
1896 if (*is == stack[inquote]) {
1897 stack[inquote--] = '\0';
1898 } else {
1899 if (++inquote >= sizeof(stack)) {
1900 return NULL;
1901 }
1902 stack[inquote] = *is;
1903 }
1904 }
1905
1906 if (*is == sep && !inquote) {
1907 *is = '\0';
1908 found = 1;
1909 *iss = is + 1;
1910 break;
1911 }
1912 }
1913 if (!found) {
1914 *iss = NULL;
1915 }
1916
1917 if (flags & AST_STRSEP_STRIP) {
1918 st = ast_strip_quoted(st, "'\"", "'\"");
1919 }
1920
1921 if (flags & AST_STRSEP_TRIM) {
1922 char *trimmed = ast_strip(st);
1923 if (!ast_strlen_zero(trimmed)) {
1924 st = trimmed;
1925 }
1926 }
1927
1928 if (flags & AST_STRSEP_UNESCAPE) {
1930 }
1931
1932 return st;
1933}
@ AST_STRSEP_TRIM
Definition: strings.h:256
@ AST_STRSEP_UNESCAPE
Definition: strings.h:257
void ast_unescape_quoted(char *quote_str)
Unescape quotes in a string.
Definition: utils.c:878
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:1854

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

Referenced by action_playback(), action_playback_and_continue(), ast_app_getdata_terminator(), ast_sip_header_to_security_mechanism(), ast_sip_security_mechanism_vector_init(), ast_sip_str_to_security_mechanism(), AST_TEST_DEFINE(), does_category_match(), handle_incoming_request(), handle_updates(), originate_exec(), outbound_websocket_apply(), password_digest_handler(), pbx_builtin_background(), play_files_helper(), playback_exec(), reload_exec(), rfc3329_incoming_response(), session_register_apps(), speech_background(), try_calling(), validate_uri_parameters(), and wizard_apply_handler().

◆ ast_strsep_quoted()

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 1935 of file utils.c.

1936{
1937 char *st = *iss;
1938 char *is;
1939 int inquote = 0;
1940 int found = 0;
1941 char stack[8];
1942 const char qstr[] = { quote };
1943
1944 if (ast_strlen_zero(st)) {
1945 *iss = NULL;
1946 return st;
1947 }
1948
1949 memset(stack, 0, sizeof(stack));
1950
1951 for(is = st; *is; is++) {
1952 if (*is == '\\') {
1953 if (*++is != '\0') {
1954 is++;
1955 } else {
1956 break;
1957 }
1958 }
1959
1960 if (*is == quote) {
1961 if (*is == stack[inquote]) {
1962 stack[inquote--] = '\0';
1963 } else {
1964 if (++inquote >= sizeof(stack)) {
1965 return NULL;
1966 }
1967 stack[inquote] = *is;
1968 }
1969 }
1970
1971 if (*is == sep && !inquote) {
1972 *is = '\0';
1973 found = 1;
1974 *iss = is + 1;
1975 break;
1976 }
1977 }
1978 if (!found) {
1979 *iss = NULL;
1980 }
1981
1982 if (flags & AST_STRSEP_STRIP) {
1983 st = ast_strip_quoted(st, qstr, qstr);
1984 }
1985
1986 if (flags & AST_STRSEP_TRIM) {
1987 char *trimmed = ast_strip(st);
1988 if (!ast_strlen_zero(trimmed)) {
1989 st = trimmed;
1990 }
1991 }
1992
1993 if (flags & AST_STRSEP_UNESCAPE) {
1995 }
1996
1997 return st;
1998}
static int quote(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)

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

Referenced by AST_TEST_DEFINE(), and ast_variable_list_from_quoted_string().

◆ ast_thread_is_user_interface()

int ast_thread_is_user_interface ( void  )

Indicates whether the current thread is a user interface.

Return values
True(non-zero) if thread is a user interface.
False(zero) if thread is not a user interface.

Definition at line 3284 of file utils.c.

3285{
3286 int *thread_user_interface;
3287
3288 thread_user_interface = ast_threadstorage_get(
3289 &thread_user_interface_tl, sizeof(*thread_user_interface));
3290 if (thread_user_interface == NULL) {
3291 ast_log(LOG_ERROR, "Error checking thread's user interface status\n");
3292 /* On error, assume that we are not a user interface thread */
3293 return 0;
3294 }
3295
3296 return *thread_user_interface;
3297}
static struct ast_threadstorage thread_user_interface_tl
Definition: utils.c:3267

References ast_log, ast_threadstorage_get(), LOG_ERROR, NULL, and thread_user_interface_tl.

Referenced by ast_autoservice_start(), and ast_autoservice_stop().

◆ ast_thread_user_interface_set()

int ast_thread_user_interface_set ( int  is_user_interface)

Set the current thread's user interface status.

Parameters
is_user_interfaceNon-zero to mark the thread as a user interface.
Return values
True(non-zero) if marking current thread failed.
False(zero) if successfuly marked current thread.

Definition at line 3269 of file utils.c.

3270{
3271 int *thread_user_interface;
3272
3273 thread_user_interface = ast_threadstorage_get(
3274 &thread_user_interface_tl, sizeof(*thread_user_interface));
3275 if (thread_user_interface == NULL) {
3276 ast_log(LOG_ERROR, "Error setting user interface status for current thread\n");
3277 return -1;
3278 }
3279
3280 *thread_user_interface = !!is_user_interface;
3281 return 0;
3282}

References ast_log, ast_threadstorage_get(), LOG_ERROR, NULL, and thread_user_interface_tl.

Referenced by handle_tcptls_connection().

◆ ast_to_camel_case_delim()

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 2433 of file utils.c.

2434{
2435 char *res = ast_strdup(s);
2436 char *front, *back, *buf = res;
2437 int size;
2438
2439 front = strtok_r(buf, delim, &back);
2440
2441 while (front) {
2442 size = strlen(front);
2443 *front = toupper(*front);
2444 ast_copy_string(buf, front, size + 1);
2445 buf += size;
2446 front = strtok_r(NULL, delim, &back);
2447 }
2448
2449 return res;
2450}

References ast_copy_string(), ast_strdup, buf, and NULL.

◆ ast_true()

int 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.

Definition at line 2235 of file utils.c.

2236{
2237 if (ast_strlen_zero(s))
2238 return 0;
2239
2240 /* Determine if this is a true value */
2241 if (!strcasecmp(s, "yes") ||
2242 !strcasecmp(s, "true") ||
2243 !strcasecmp(s, "y") ||
2244 !strcasecmp(s, "t") ||
2245 !strcasecmp(s, "1") ||
2246 !strcasecmp(s, "on"))
2247 return -1;
2248
2249 return 0;
2250}

References ast_strlen_zero().

Referenced by __ast_http_load(), __init_manager(), acf_curlopt_write(), acf_faxopt_write(), acf_transaction_write(), action_agent_logoff(), action_originate(), action_status(), action_updateconfig(), actual_load_config(), agent_login_channel_config(), analog_call(), announce_user_count_all_handler(), aoc_cli_debug_enable(), 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_TEST_DEFINE(), ast_tls_read_conf(), autopause2int(), bool_handler_fn(), boolflag_handler_fn(), build_calendar(), build_device(), build_peer(), build_user(), cdr_prop_write_callback(), check_debug(), client_bitfield_handler(), custom_bitfield_handler(), customopt_handler(), dahdi_set_dnd(), dahdi_set_mwi(), do_reload(), festival_exec(), func_channel_write_real(), func_mute_write(), function_ooh323_write(), general_pretty_from_str(), geoloc_profile_write(), get_encrypt_methods(), global_bitfield_handler(), handle_exec(), handle_incoming_request(), handle_logger_chanloggroup_filter(), handle_logger_set_level(), handle_queue_set_member_ringinuse(), hook_write(), init_logger_chain(), internal_feature_write(), is_variable_true(), load_asterisk_conf(), load_config(), load_config_meetme(), load_module(), load_moh_classes(), load_odbc_config(), load_users(), loader_config_init(), manager_add_queue_member(), manager_change_priority_caller_on_queue(), manager_dialplan_extension_add(), manager_moduleload(), manager_mute_mixmonitor(), manager_mutestream(), manager_pause_queue_member(), manager_play_dtmf(), manager_queue_member_ringinuse(), manager_send_flash(), mbl_load_adapter(), mbl_load_device(), message_template_build(), moh_parse_options(), new_realtime_sqlite3_db(), odbc_load_module(), parse_config(), parse_empty_options(), parse_general_options(), parse_line(), parse_playtone(), pbx_load_config(), permit_dtmf_interrupt(), pjsip_acf_moh_passthrough_write(), pjsip_set_logger_verbose(), prack_handler(), process_dahdi(), process_echocancel(), process_my_load_module(), profile_set_param(), queue_rules_set_global_params(), queue_set_global_params(), queue_set_param(), realtime_directory(), reload(), reload_config(), reload_followme(), reload_module(), reload_single_member(), rt_handle_member_record(), rtp_reload(), run_agi(), sayunixtime_exec(), search_directory(), set_active(), set_config(), sla_load_config(), smdi_load(), sorcery_config_open(), sorcery_memory_cache_ami_stale_object(), sorcery_memory_cache_open(), speex_write(), stackpeek_read(), strings_to_mask(), tds_load_module(), timers_handler(), transport_tls_bool_handler(), websocket_attempted_cb(), xfer_set(), xmldoc_get_syntax_cmd(), xmldoc_get_syntax_config_object(), xmldoc_get_syntax_fun(), and xmldoc_get_syntax_manager().

◆ ast_tvadd()

struct timeval ast_tvadd ( struct timeval  a,
struct timeval  b 
)

Returns the sum of two timevals a + b.

Definition at line 2289 of file utils.c.

2290{
2291 /* consistency checks to guarantee usec in 0..999999 */
2292 a = tvfix(a);
2293 b = tvfix(b);
2294 a.tv_sec += b.tv_sec;
2295 a.tv_usec += b.tv_usec;
2296 if (a.tv_usec >= ONE_MILLION) {
2297 a.tv_sec++;
2298 a.tv_usec -= ONE_MILLION;
2299 }
2300 return a;
2301}
static struct test_val b
#define ONE_MILLION
Definition: utils.c:2269
static struct timeval tvfix(struct timeval a)
Definition: utils.c:2274

References a, b, ONE_MILLION, and tvfix().

◆ ast_tvsub()

struct timeval ast_tvsub ( struct timeval  a,
struct timeval  b 
)

Returns the difference of two timevals a - b.

Definition at line 2303 of file utils.c.

2304{
2305 /* consistency checks to guarantee usec in 0..999999 */
2306 a = tvfix(a);
2307 b = tvfix(b);
2308 a.tv_sec -= b.tv_sec;
2309 a.tv_usec -= b.tv_usec;
2310 if (a.tv_usec < 0) {
2311 a.tv_sec-- ;
2312 a.tv_usec += ONE_MILLION;
2313 }
2314 return a;
2315}

References a, b, ONE_MILLION, and tvfix().

◆ ast_unescape_c()

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 2019 of file utils.c.

2020{
2021 char c, *ret, *dst;
2022
2023 if (src == NULL)
2024 return NULL;
2025 for (ret = dst = src; (c = *src++); *dst++ = c ) {
2026 if (c != '\\')
2027 continue; /* copy char at the end of the loop */
2028 switch ((c = *src++)) {
2029 case '\0': /* special, trailing '\' */
2030 c = '\\';
2031 break;
2032 case 'b': /* backspace */
2033 c = '\b';
2034 break;
2035 case 'f': /* form feed */
2036 c = '\f';
2037 break;
2038 case 'n':
2039 c = '\n';
2040 break;
2041 case 'r':
2042 c = '\r';
2043 break;
2044 case 't':
2045 c = '\t';
2046 break;
2047 }
2048 /* default, use the char literally */
2049 }
2050 *dst = '\0';
2051 return ret;
2052}

References c, and NULL.

Referenced by ast_parse_digest().

◆ ast_unescape_quoted()

void ast_unescape_quoted ( char *  quote_str)

Unescape quotes in a string.

Parameters
quote_strThe string with quotes to be unescaped
Note
This function mutates the passed-in string.

Definition at line 878 of file utils.c.

879{
880 int esc_pos;
881 int unesc_pos;
882 int quote_str_len = strlen(quote_str);
883
884 for (esc_pos = 0, unesc_pos = 0;
885 esc_pos < quote_str_len;
886 esc_pos++, unesc_pos++) {
887 if (quote_str[esc_pos] == '\\') {
888 /* at least one more char and current is \\ */
889 esc_pos++;
890 if (esc_pos >= quote_str_len) {
891 break;
892 }
893 }
894
895 quote_str[unesc_pos] = quote_str[esc_pos];
896 }
897 quote_str[unesc_pos] = '\0';
898}

Referenced by ast_callerid_parse(), ast_strsep(), ast_strsep_quoted(), and AST_TEST_DEFINE().

◆ ast_unescape_semicolon()

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 2000 of file utils.c.

2001{
2002 char *e;
2003 char *work = s;
2004
2005 while ((e = strchr(work, ';'))) {
2006 if ((e > work) && (*(e-1) == '\\')) {
2007 memmove(e - 1, e, strlen(e) + 1);
2008 work = e;
2009 } else {
2010 work = e + 1;
2011 }
2012 }
2013
2014 return s;
2015}

◆ ast_uri_decode()

void ast_uri_decode ( char *  s,
struct ast_flags  spec 
)

Decode URI, URN, URL (overwrite string)

Note
The ast_uri_http_legacy decode spec flag will cause this function to decode '+' as ' '.
Parameters
sstring to be decoded
specflags describing how the decoding should be performed

Definition at line 762 of file utils.c.

763{
764 char *o;
765 unsigned int tmp;
766
767 for (o = s; *s; s++, o++) {
768 if (ast_test_flag(&spec, AST_URI_LEGACY_SPACE) && *s == '+') {
769 /* legacy mode, decode '+' as space */
770 *o = ' ';
771 } else if (*s == '%' && s[1] != '\0' && s[2] != '\0' && sscanf(s + 1, "%2x", &tmp) == 1) {
772 /* have '%', two chars and correct parsing */
773 *o = tmp;
774 s += 2; /* Will be incremented once more when we break out */
775 } else /* all other cases, just copy */
776 *o = *s;
777 }
778 *o = '\0';
779}
#define ast_test_flag(p, flag)
Definition: utils.h:63
#define AST_URI_LEGACY_SPACE
Definition: utils.h:385

References ast_test_flag, and AST_URI_LEGACY_SPACE.

Referenced by acf_curl_helper(), ast_ari_invoke(), ast_http_parse_post_form(), AST_TEST_DEFINE(), config_curl(), handle_uri(), realtime_curl(), realtime_multi_curl(), and uridecode().

◆ ast_uri_encode()

char * ast_uri_encode ( const char *  string,
char *  outbuf,
int  buflen,
struct ast_flags  spec 
)

Turn text string to URI-encoded XX version.

This function encodes characters according to the rules presented in RFC 2396 and/or RFC 3261 section 19.1.2 and section 25.1.

Outbuf needs to have more memory allocated than the instring to have room for the expansion. Every byte that is converted is replaced by three ASCII characters.

Parameters
stringstring to be converted
outbufresulting encoded string
buflensize of output buffer
specflags describing how the encoding should be performed
Returns
a pointer to the uri encoded string

Definition at line 723 of file utils.c.

724{
725 const char *ptr = string; /* Start with the string */
726 char *out = outbuf;
727 const char *mark = "-_.!~*'()"; /* no encode set, RFC 2396 section 2.3, RFC 3261 sec 25 */
728 const char *user_unreserved = "&=+$,;?/"; /* user-unreserved set, RFC 3261 sec 25 */
729
730 while (*ptr && out - outbuf < buflen - 1) {
731 if (ast_test_flag(&spec, AST_URI_LEGACY_SPACE) && *ptr == ' ') {
732 /* for legacy encoding, encode spaces as '+' */
733 *out = '+';
734 out++;
735 } else if (!(ast_test_flag(&spec, AST_URI_MARK)
736 && strchr(mark, *ptr))
738 && ((*ptr >= '0' && *ptr <= '9')
739 || (*ptr >= 'A' && *ptr <= 'Z')
740 || (*ptr >= 'a' && *ptr <= 'z')))
742 && strchr(user_unreserved, *ptr))) {
743
744 if (out - outbuf >= buflen - 3) {
745 break;
746 }
747 out += sprintf(out, "%%%02hhX", (unsigned char) *ptr);
748 } else {
749 *out = *ptr; /* Continue copying the string */
750 out++;
751 }
752 ptr++;
753 }
754
755 if (buflen) {
756 *out = '\0';
757 }
758
759 return outbuf;
760}
#define AST_URI_MARK
Definition: utils.h:383
#define AST_URI_SIP_USER_UNRESERVED
Definition: utils.h:387
#define AST_URI_ALPHANUM
Definition: utils.h:382

References ast_test_flag, AST_URI_ALPHANUM, AST_URI_LEGACY_SPACE, AST_URI_MARK, AST_URI_SIP_USER_UNRESERVED, out, and string.

Referenced by ast_ari_bridges_record(), ast_ari_channels_record(), AST_TEST_DEFINE(), config_curl(), destroy_curl(), launch_asyncagi(), realtime_curl(), realtime_multi_curl(), require_curl(), store_curl(), update2_curl(), update_curl(), and uriencode().

◆ ast_uri_verify_encoded()

int ast_uri_verify_encoded ( const char *  string)

Verify if a string is valid as a URI component.

This function checks if the string either doesn't need encoding or is already properly URI encoded. Valid characters are 'a-zA-Z0-9.+_-' and 'xx' escape sequences.

Parameters
stringString to be checked
Return values
1if the string is valid
0if the string is not valid

Definition at line 781 of file utils.c.

782{
783 const char *ptr = string;
784 size_t length;
785 char *endl;
786
787 if (!string) {
788 return 0;
789 }
790
791 length = strlen(string);
792 endl = (char *)string + length;
793
794 while (*ptr) {
795 if (*ptr == '%') {
796 unsigned int tmp;
797 /* Make sure there are at least 2 characters left to decode */
798 if (ptr + 2 >= endl) {
799 return 0;
800 }
801 /* Try to parse the next two characters as hex */
802 if (sscanf(ptr + 1, "%2x", &tmp) != 1) {
803 return 0;
804 }
805 /* All good, move past the '%' and the two hex digits */
806 ptr += 3;
807 } else if (!isalnum((unsigned char ) *ptr) && !strchr("-_.+", *ptr)) {
808 return 0;
809 } else {
810 ptr++;
811 }
812 }
813
814 return 1; /* all characters are valid */
815}

References string.

Referenced by validate_uri_parameters().

◆ ast_utils_init()

int ast_utils_init ( void  )

Definition at line 2653 of file utils.c.

2654{
2655 dev_urandom_fd = open("/dev/urandom", O_RDONLY);
2656 base64_init();
2657#ifdef DEBUG_THREADS
2658#if !defined(LOW_MEMORY)
2659 ast_cli_register_multiple(utils_cli, ARRAY_LEN(utils_cli));
2660#endif
2661#endif
2663 return 0;
2664}
int ast_register_cleanup(void(*func)(void))
Register a function to be executed before Asterisk gracefully exits.
Definition: clicompat.c:19
#define ast_cli_register_multiple(e, len)
Register multiple commands.
Definition: cli.h:265
static void utils_shutdown(void)
Definition: utils.c:2644
static void base64_init(void)
Definition: utils.c:540
#define ARRAY_LEN(a)
Definition: utils.h:703

References ARRAY_LEN, ast_cli_register_multiple, ast_register_cleanup(), base64_init(), dev_urandom_fd, and utils_shutdown().

Referenced by asterisk_daemon().

◆ ast_utils_which()

char * ast_utils_which ( const char *  binary,
char *  fullpath,
size_t  fullpath_size 
)

Resolve a binary to a full pathname.

Parameters
binaryName of the executable to resolve
fullpathBuffer to hold the complete pathname
fullpath_sizeSize of fullpath
Return values
NULLbinary was not found or the environment variable PATH is not set
Returns
fullpath

Definition at line 2810 of file utils.c.

2811{
2812 const char *envPATH = getenv("PATH");
2813 char *tpath, *path;
2814 struct stat unused;
2815 if (!envPATH) {
2816 return NULL;
2817 }
2818 tpath = ast_strdupa(envPATH);
2819 while ((path = strsep(&tpath, ":"))) {
2820 snprintf(fullpath, fullpath_size, "%s/%s", path, binary);
2821 if (!stat(fullpath, &unused)) {
2822 return fullpath;
2823 }
2824 }
2825 return NULL;
2826}

References ast_strdupa, NULL, and strsep().

◆ ast_wait_for_input()

int ast_wait_for_input ( int  fd,
int  ms 
)

Definition at line 1734 of file utils.c.

1735{
1736 struct pollfd pfd[1];
1737
1738 memset(pfd, 0, sizeof(pfd));
1739 pfd[0].fd = fd;
1740 pfd[0].events = POLLIN | POLLPRI;
1741 return ast_poll(pfd, 1, ms);
1742}
#define ast_poll(a, b, c)
Definition: poll-compat.h:88

References ast_poll.

Referenced by action_waitevent(), ast_audiosocket_receive_frame_with_hangup(), ast_iostream_wait_for_input(), ast_iostream_write(), ast_tcptls_server_root(), dahdi_test_timer(), get_input(), iostream_read(), moh_class_destructor(), read_from_ws_and_queue(), session_read(), and unbound_resolver_thread().

◆ ast_wait_for_output()

int ast_wait_for_output ( int  fd,
int  ms 
)

Definition at line 1744 of file utils.c.

1745{
1746 struct pollfd pfd[1];
1747
1748 memset(pfd, 0, sizeof(pfd));
1749 pfd[0].fd = fd;
1750 pfd[0].events = POLLOUT;
1751 return ast_poll(pfd, 1, ms);
1752}

References ast_poll.

Referenced by ast_iostream_write(), iostream_read(), and socket_connect().

◆ ast_xml_escape()

int ast_xml_escape ( const char *  string,
char *  outbuf,
size_t  buflen 
)

Escape reserved characters for use in XML.

ast_xml_escape

If outbuf is too short, the output string will be truncated. Regardless, the output will always be null terminated.

Parameters
stringString to be converted
outbufResulting encoded string
buflenSize of output buffer
Return values
0for success
-1if buflen is too short.

Definition at line 900 of file utils.c.

901{
902 char *dst = outbuf;
903 char *end = outbuf + buflen - 1; /* save one for the null terminator */
904
905 /* Handle the case for the empty output buffer */
906 if (buflen == 0) {
907 return -1;
908 }
909
910 /* Escaping rules from http://www.w3.org/TR/REC-xml/#syntax */
911 /* This also prevents partial entities at the end of a string */
912 while (*string && dst < end) {
913 const char *entity = NULL;
914 int len = 0;
915
916 switch (*string) {
917 case '<':
918 entity = "&lt;";
919 len = 4;
920 break;
921 case '&':
922 entity = "&amp;";
923 len = 5;
924 break;
925 case '>':
926 /* necessary if ]]> is in the string; easier to escape them all */
927 entity = "&gt;";
928 len = 4;
929 break;
930 case '\'':
931 /* necessary in single-quoted strings; easier to escape them all */
932 entity = "&apos;";
933 len = 6;
934 break;
935 case '"':
936 /* necessary in double-quoted strings; easier to escape them all */
937 entity = "&quot;";
938 len = 6;
939 break;
940 default:
941 *dst++ = *string++;
942 break;
943 }
944
945 if (entity) {
946 ast_assert(len == strlen(entity));
947 if (end - dst < len) {
948 /* no room for the entity; stop */
949 break;
950 }
951 /* just checked for length; strcpy is fine */
952 strcpy(dst, entity);
953 dst += len;
954 ++string;
955 }
956 }
957 /* Write null terminator */
958 *dst = '\0';
959 /* If any chars are left in string, return failure */
960 return *string == '\0' ? 0 : -1;
961}
char * end
Definition: eagi_proxy.c:73

References ast_assert, end, len(), NULL, and string.

Referenced by ast_http_create_response(), and test_xml().

◆ base64_init()

static void base64_init ( void  )
static

Definition at line 540 of file utils.c.

541{
542 int x;
543 memset(b2a, -1, sizeof(b2a));
544 memset(b2a_url, -1, sizeof(b2a_url));
545 /* Initialize base-64 Conversion table */
546 for (x = 0; x < 26; x++) {
547 /* A-Z */
548 base64[x] = 'A' + x;
549 base64url[x] = 'A' + x;
550 b2a['A' + x] = x;
551 b2a_url['A' + x] = x;
552 /* a-z */
553 base64[x + 26] = 'a' + x;
554 base64url[x + 26] = 'a' + x;
555 b2a['a' + x] = x + 26;
556 b2a_url['a' + x] = x + 26;
557 /* 0-9 */
558 if (x < 10) {
559 base64[x + 52] = '0' + x;
560 base64url[x + 52] = '0' + x;
561 b2a['0' + x] = x + 52;
562 b2a_url['0' + x] = x + 52;
563 }
564 }
565 base64[62] = '+';
566 base64[63] = '/';
567 base64url[62] = '-';
568 base64url[63] = '_';
569 b2a[(int)'+'] = 62;
570 b2a[(int)'/'] = 63;
571 b2a_url[(int)'-'] = 62;
572 b2a_url[(int)'_'] = 63;
573}

References b2a, b2a_url, base64, and base64url.

Referenced by ast_utils_init().

◆ dummy_start()

static void * dummy_start ( void *  data)
static

Definition at line 1609 of file utils.c.

1610{
1611 void *ret;
1612 struct thr_arg a = *((struct thr_arg *) data); /* make a local copy */
1613#ifdef DEBUG_THREADS
1614 struct thr_lock_info *lock_info;
1615 pthread_mutexattr_t mutex_attr;
1616
1617 if (!(lock_info = ast_threadstorage_get(&thread_lock_info, sizeof(*lock_info))))
1618 return NULL;
1619
1620 lock_info->thread_id = pthread_self();
1621 lock_info->lwp = ast_get_tid();
1622 lock_info->thread_name = ast_strdup(a.name);
1623
1624 pthread_mutexattr_init(&mutex_attr);
1625 pthread_mutexattr_settype(&mutex_attr, AST_MUTEX_KIND);
1626 pthread_mutex_init(&lock_info->lock, &mutex_attr);
1627 pthread_mutexattr_destroy(&mutex_attr);
1628
1629 pthread_mutex_lock(&lock_infos_lock.mutex); /* Intentionally not the wrapper */
1630 AST_LIST_INSERT_TAIL(&lock_infos, lock_info, entry);
1631 pthread_mutex_unlock(&lock_infos_lock.mutex); /* Intentionally not the wrapper */
1632#endif /* DEBUG_THREADS */
1633
1634 /* note that even though data->name is a pointer to allocated memory,
1635 we are not freeing it here because ast_register_thread is going to
1636 keep a copy of the pointer and then ast_unregister_thread will
1637 free the memory
1638 */
1639 ast_free(data);
1641 pthread_cleanup_push(ast_unregister_thread, (void *) pthread_self());
1642
1643 ret = a.start_routine(a.data);
1644
1645 pthread_cleanup_pop(1);
1646
1647 return ret;
1648}
static const struct ast_datastore_info lock_info
Definition: func_lock.c:136
#define AST_LIST_INSERT_TAIL(head, elm, field)
Appends a list entry to the tail of a list.
Definition: linkedlists.h:731
#define pthread_mutex_lock
Definition: lock.h:632
#define AST_MUTEX_KIND
Definition: lock.h:84
#define pthread_mutex_unlock
Definition: lock.h:633
#define pthread_mutex_init
Definition: lock.h:635
int ast_get_tid(void)
Get current thread ID.
Definition: utils.c:2788
void ast_register_thread(char *name)
Definition: asterisk.c:421
void ast_unregister_thread(void *id)
Definition: asterisk.c:437

References a, ast_free, ast_get_tid(), AST_LIST_INSERT_TAIL, AST_MUTEX_KIND, ast_register_thread(), ast_strdup, ast_threadstorage_get(), ast_unregister_thread(), thr_arg::data, lock_info, test_val::name, NULL, pthread_mutex_init, pthread_mutex_lock, and pthread_mutex_unlock.

Referenced by ast_pthread_create_stack().

◆ escape_alloc()

static char * escape_alloc ( const char *  s,
size_t *  size 
)
static

Definition at line 2154 of file utils.c.

2155{
2156 if (!s) {
2157 return NULL;
2158 }
2159
2160 /*
2161 * The result string needs to be twice the size of the given
2162 * string just in case every character in it needs to be escaped.
2163 */
2164 *size = strlen(s) * 2 + 1;
2165 return ast_malloc(*size);
2166}

References ast_malloc, and NULL.

Referenced by ast_escape_alloc(), and ast_escape_c_alloc().

◆ inbuf()

static int inbuf ( struct baseio bio,
FILE *  fi 
)
static

utility used by inchar(), for base_encode()

Definition at line 590 of file utils.c.

591{
592 int l;
593
594 if (bio->ateof) {
595 return 0;
596 }
597
598 if ((l = fread(bio->iobuf, 1, BASEMAXINLINE, fi)) != BASEMAXINLINE) {
599 bio->ateof = 1;
600 if (l == 0) {
601 /* Assume EOF */
602 return 0;
603 }
604 }
605
606 bio->iolen = l;
607 bio->iocp = 0;
608
609 return 1;
610}
int iolen
Definition: utils.c:581
unsigned char iobuf[BASEMAXINLINE]
Definition: utils.c:584
int ateof
Definition: utils.c:583
int iocp
Definition: utils.c:580

References baseio::ateof, BASEMAXINLINE, baseio::iobuf, baseio::iocp, and baseio::iolen.

Referenced by analys_(), ast_eivr_getvariable(), ast_eivr_setvariable(), find_sequence(), inchar(), lpfilt_(), netconsole(), preemp_(), term_color(), term_strip(), voicin_(), and vparms_().

◆ inchar()

static int inchar ( struct baseio bio,
FILE *  fi 
)
static

utility used by base_encode()

Definition at line 615 of file utils.c.

616{
617 if (bio->iocp >= bio->iolen) {
618 if (!inbuf(bio, fi)) {
619 return EOF;
620 }
621 }
622
623 return bio->iobuf[bio->iocp++];
624}
static int inbuf(struct baseio *bio, FILE *fi)
utility used by inchar(), for base_encode()
Definition: utils.c:590

References inbuf(), baseio::iobuf, baseio::iocp, and baseio::iolen.

Referenced by ast_base64_encode_file().

◆ ochar()

static int ochar ( struct baseio bio,
int  c,
FILE *  so,
const char *  endl 
)
static

utility used by base_encode()

Definition at line 629 of file utils.c.

630{
631 if (bio->linelength >= BASELINELEN) {
632 if (fputs(endl, so) == EOF) {
633 return -1;
634 }
635
636 bio->linelength = 0;
637 }
638
639 if (putc(((unsigned char) c), so) == EOF) {
640 return -1;
641 }
642
643 bio->linelength++;
644
645 return 1;
646}
int linelength
Definition: utils.c:582
#define BASELINELEN
Definition: utils.c:575

References BASELINELEN, c, and baseio::linelength.

Referenced by ast_base64_encode_file().

◆ safe_mkdir()

static int safe_mkdir ( const char *  base_path,
char *  path,
int  mode 
)
static

Definition at line 2550 of file utils.c.

2551{
2552 RAII_VAR(char *, absolute_path, NULL, ast_std_free);
2553
2554 absolute_path = realpath(path, NULL);
2555
2556 if (absolute_path) {
2557 /* Path exists, but is it in the right place? */
2558 if (!ast_begins_with(absolute_path, base_path)) {
2559 return EPERM;
2560 }
2561
2562 /* It is in the right place! */
2563 return 0;
2564 } else {
2565 /* Path doesn't exist. */
2566
2567 /* The slash terminating the subpath we're checking */
2568 char *path_term = strchr(path, '/');
2569 /* True indicates the parent path is within base_path */
2570 int parent_is_safe = 0;
2571 int res;
2572
2573 while (path_term) {
2574 RAII_VAR(char *, absolute_subpath, NULL, ast_std_free);
2575
2576 /* Truncate the path one past the slash */
2577 char c = *(path_term + 1);
2578 *(path_term + 1) = '\0';
2579 absolute_subpath = realpath(path, NULL);
2580
2581 if (absolute_subpath) {
2582 /* Subpath exists, but is it safe? */
2583 parent_is_safe = ast_begins_with(
2584 absolute_subpath, base_path);
2585 } else if (parent_is_safe) {
2586 /* Subpath does not exist, but parent is safe
2587 * Create it */
2588 res = mkdir(path, mode);
2589 if (res != 0) {
2590 ast_assert(errno != EEXIST);
2591 return errno;
2592 }
2593 } else {
2594 /* Subpath did not exist, parent was not safe
2595 * Fail! */
2596 errno = EPERM;
2597 return errno;
2598 }
2599 /* Restore the path */
2600 *(path_term + 1) = c;
2601 /* Move on to the next slash */
2602 path_term = strchr(path_term + 1, '/');
2603 }
2604
2605 /* Now to build the final path, but only if it's safe */
2606 if (!parent_is_safe) {
2607 errno = EPERM;
2608 return errno;
2609 }
2610
2611 res = mkdir(path, mode);
2612 if (res != 0 && errno != EEXIST) {
2613 return errno;
2614 }
2615
2616 return 0;
2617 }
2618}
static int force_inline attribute_pure ast_begins_with(const char *str, const char *prefix)
Checks whether a string begins with another.
Definition: strings.h:97

References ast_assert, ast_begins_with(), ast_std_free(), c, errno, NULL, and RAII_VAR.

Referenced by ast_safe_mkdir().

◆ tvfix()

static struct timeval tvfix ( struct timeval  a)
static

Definition at line 2274 of file utils.c.

2275{
2276 if (a.tv_usec >= ONE_MILLION) {
2277 ast_log(LOG_WARNING, "warning too large timestamp %ld.%ld\n",
2278 (long)a.tv_sec, (long int) a.tv_usec);
2279 a.tv_sec += a.tv_usec / ONE_MILLION;
2280 a.tv_usec %= ONE_MILLION;
2281 } else if (a.tv_usec < 0) {
2282 ast_log(LOG_WARNING, "warning negative timestamp %ld.%ld\n",
2283 (long)a.tv_sec, (long int) a.tv_usec);
2284 a.tv_usec = 0;
2285 }
2286 return a;
2287}

References a, ast_log, LOG_WARNING, and ONE_MILLION.

Referenced by ast_tvadd(), and ast_tvsub().

◆ utils_shutdown()

static void utils_shutdown ( void  )
static

Definition at line 2644 of file utils.c.

2645{
2646 close(dev_urandom_fd);
2647 dev_urandom_fd = -1;
2648#if defined(DEBUG_THREADS) && !defined(LOW_MEMORY)
2649 ast_cli_unregister_multiple(utils_cli, ARRAY_LEN(utils_cli));
2650#endif
2651}
int ast_cli_unregister_multiple(struct ast_cli_entry *e, int len)
Unregister multiple commands.
Definition: clicompat.c:30

References ARRAY_LEN, ast_cli_unregister_multiple(), and dev_urandom_fd.

Referenced by ast_utils_init().

◆ wait_for_output()

static int wait_for_output ( int  fd,
int  timeoutms 
)
static

Definition at line 1754 of file utils.c.

1755{
1756 struct pollfd pfd = {
1757 .fd = fd,
1758 .events = POLLOUT,
1759 };
1760 int res;
1761 struct timeval start = ast_tvnow();
1762 int elapsed = 0;
1763
1764 /* poll() until the fd is writable without blocking */
1765 while ((res = ast_poll(&pfd, 1, timeoutms - elapsed)) <= 0) {
1766 if (res == 0) {
1767 /* timed out. */
1768#ifndef STANDALONE
1769 ast_debug(1, "Timed out trying to write\n");
1770#endif
1771 return -1;
1772 } else if (res == -1) {
1773 /* poll() returned an error, check to see if it was fatal */
1774
1775 if (errno == EINTR || errno == EAGAIN) {
1776 elapsed = ast_tvdiff_ms(ast_tvnow(), start);
1777 if (elapsed >= timeoutms) {
1778 return -1;
1779 }
1780 /* This was an acceptable error, go back into poll() */
1781 continue;
1782 }
1783
1784 /* Fatal error, bail. */
1785 ast_log(LOG_ERROR, "poll returned error: %s\n", strerror(errno));
1786
1787 return -1;
1788 }
1789 elapsed = ast_tvdiff_ms(ast_tvnow(), start);
1790 if (elapsed >= timeoutms) {
1791 return -1;
1792 }
1793 }
1794
1795 return 0;
1796}

References ast_debug, ast_log, ast_poll, ast_tvdiff_ms(), ast_tvnow(), errno, and LOG_ERROR.

Referenced by ast_carefulwrite().

Variable Documentation

◆ ast_uri_http

const struct ast_flags ast_uri_http = {AST_URI_UNRESERVED}

◆ ast_uri_http_legacy

const struct ast_flags ast_uri_http_legacy = {AST_URI_LEGACY_SPACE | AST_URI_UNRESERVED}

◆ ast_uri_sip_user

const struct ast_flags ast_uri_sip_user = {AST_URI_UNRESERVED | AST_URI_SIP_USER_UNRESERVED}

Definition at line 721 of file utils.c.

Referenced by AST_TEST_DEFINE().

◆ b2a

char b2a[256]
static

Definition at line 82 of file utils.c.

Referenced by ast_base64decode(), and base64_init().

◆ b2a_url

char b2a_url[256]
static

Definition at line 83 of file utils.c.

Referenced by ast_base64url_decode(), and base64_init().

◆ base64

char base64[64]
static

◆ base64url

char base64url[64]
static

Definition at line 81 of file utils.c.

Referenced by ast_base64url_encode_full(), and base64_init().

◆ dev_urandom_fd

int dev_urandom_fd = -1
static

Definition at line 974 of file utils.c.

Referenced by ast_random(), ast_utils_init(), ast_uuid_init(), and utils_shutdown().

◆ escape_sequences

char escape_sequences[]
Initial value:
= {
'\a', '\b', '\f', '\n', '\r', '\t', '\v', '\\', '\'', '\"', '\?', '\0'
}

Definition at line 2058 of file utils.c.

Referenced by ast_escape(), and ast_escape_c().

◆ escape_sequences_map

char escape_sequences_map[]
static
Initial value:
= {
'a', 'b', 'f', 'n', 'r', 't', 'v', '\\', '\'', '"', '?', '\0'
}

Definition at line 2066 of file utils.c.

Referenced by ast_escape(), and ast_escape_c().

◆ inet_ntoa_buf

struct ast_threadstorage inet_ntoa_buf = { .once = PTHREAD_ONCE_INIT , .key_init = __init_inet_ntoa_buf , .custom_init = NULL , }
static

Definition at line 85 of file utils.c.

Referenced by ast_inet_ntoa().

◆ randomlock

ast_mutex_t randomlock = { PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP , NULL, {1, 0} }
static

Definition at line 2345 of file utils.c.

Referenced by ast_random().

◆ thread_user_interface_tl

struct ast_threadstorage thread_user_interface_tl = { .once = PTHREAD_ONCE_INIT , .key_init = __init_thread_user_interface_tl , .custom_init = NULL , }
static

Definition at line 3267 of file utils.c.

Referenced by ast_thread_is_user_interface(), and ast_thread_user_interface_set().