Asterisk - The Open Source Telephony Project  GIT-master-4a4f1a5
Data Structures | Macros | Enumerations | Functions | Variables
utils.h File Reference

Utility functions. More...

#include "asterisk/network.h"
#include <time.h>
#include <unistd.h>
#include <string.h>
#include "asterisk/lock.h"
#include "asterisk/logger.h"
#include "asterisk/localtime.h"
#include "asterisk/stringfields.h"
#include "asterisk/strings.h"

Go to the source code of this file.

Data Structures

struct  ast_eid
 An Entity ID is essentially a MAC address, brief and unique. More...
 
struct  ast_flags
 Structure used to handle boolean flags. More...
 
struct  ast_flags64
 Structure used to handle a large number of boolean flags == used only in app_dial? More...
 
struct  ast_hostent
 
struct  ast_http_digest
 

Macros

#define ARRAY_IN_BOUNDS(v, a)   IN_BOUNDS((int) (v), 0, ARRAY_LEN(a) - 1)
 Checks to see if value is within the bounds of the given array. More...
 
#define ARRAY_LEN(a)   (size_t) (sizeof(a) / sizeof(0[a]))
 
#define ast_align_for(offset, type)   (((offset + __alignof__(type) - 1) / __alignof__(type)) * __alignof__(type))
 Increase offset so it is a multiple of the required alignment of type. More...
 
#define ast_alignof(type)   __alignof__(type)
 Return the number of bytes used in the alignment of type. More...
 
#define ast_assert(a)
 
#define ast_assert_return(a, ...)
 
#define AST_BACKGROUND_STACKSIZE   ast_background_stacksize()
 
#define ast_clear_flag(p, flag)
 
#define ast_clear_flag64(p, flag)
 
#define ast_clear_flag_nonstd(p, flag)
 
#define ast_copy_flags(dest, src, flagz)
 
#define ast_copy_flags64(dest, src, flagz)
 
#define ast_copy_flags_nonstd(dest, src, flagz)
 
#define ast_fd_clear_flags(fd, flags)    __ast_fd_set_flags((fd), (flags), AST_FD_FLAG_CLEAR, __FILE__, __LINE__, __PRETTY_FUNCTION__)
 Clear flags on the given file descriptor. More...
 
#define ast_fd_set_flags(fd, flags)    __ast_fd_set_flags((fd), (flags), AST_FD_FLAG_SET, __FILE__, __LINE__, __PRETTY_FUNCTION__)
 Set flags on the given file descriptor. More...
 
#define AST_FLAGS_ALL   UINT_MAX
 
#define ast_make_room_for(offset, type)   (((offset + (2 * __alignof__(type) - 1)) / __alignof__(type)) * __alignof__(type))
 Increase offset by the required alignment of type and make sure it is a multiple of said alignment. More...
 
#define ast_pipe_nonblock(filedes)   pipe2((filedes), O_NONBLOCK)
 Create a non-blocking pipe. More...
 
#define ast_pthread_create(a, b, c, d)
 
#define ast_pthread_create_background(a, b, c, d)
 
#define ast_pthread_create_detached(a, b, c, d)
 
#define ast_pthread_create_detached_background(a, b, c, d)
 
#define ast_random_double()   (((double)ast_random()) / RAND_MAX)
 Returns a random number between 0.0 and 1.0, inclusive. More...
 
#define ast_set2_flag(p, value, flag)
 
#define ast_set2_flag64(p, value, flag)
 
#define ast_set2_flag_nonstd(p, value, flag)
 
#define ast_set_flag(p, flag)
 
#define ast_set_flag64(p, flag)
 
#define ast_set_flag_nonstd(p, flag)
 
#define ast_set_flags_to(p, flag, value)
 
#define ast_set_flags_to64(p, flag, value)
 
#define ast_socket_nonblock(domain, type, protocol)   socket((domain), (type) | SOCK_NONBLOCK, (protocol))
 Create a non-blocking socket. More...
 
#define AST_STACKSIZE   (((sizeof(void *) * 8 * 8) - 16) * 1024)
 
#define AST_STACKSIZE_LOW   (((sizeof(void *) * 8 * 2) - 16) * 1024)
 
#define ast_test_flag(p, flag)
 
#define ast_test_flag64(p, flag)
 
#define ast_test_flag_nonstd(p, flag)    ((p)->flags & (flag))
 
#define AST_URI_ALPHANUM   (1 << 0)
 
#define AST_URI_LEGACY_SPACE   (1 << 2)
 
#define AST_URI_MARK   (1 << 1)
 
#define AST_URI_SIP_USER_UNRESERVED   (1 << 20)
 
#define AST_URI_UNRESERVED   (AST_URI_ALPHANUM | AST_URI_MARK)
 
#define DO_CRASH_NORETURN
 
#define IN_BOUNDS(v, min, max)   ((v) >= (min)) && ((v) <= (max))
 Checks to see if value is within the given bounds. More...
 
#define localtime_r   __dont_use_localtime_r_use_ast_localtime_instead__
 
#define MAX(a, b)   ({ typeof(a) __a = (a); typeof(b) __b = (b); ((__a < __b) ? __b : __a);})
 
#define MIN(a, b)   ({ typeof(a) __a = (a); typeof(b) __b = (b); ((__a > __b) ? __b : __a);})
 
#define RAII_VAR(vartype, varname, initval, dtor)
 Declare a variable that will call a destructor function when it goes out of scope. More...
 
#define SWAP(a, b)   do { typeof(a) __tmp = (a); (a) = (b); (b) = __tmp; } while (0)
 

Enumerations

enum  ast_fd_flag_operation { AST_FD_FLAG_SET , AST_FD_FLAG_CLEAR }
 

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)
 
int ast_background_stacksize (void)
 
int ast_base64decode (unsigned char *dst, const char *src, int max)
 Decode data from base64. More...
 
char * ast_base64decode_string (const char *src)
 Same as ast_base64decode, but does the math for you and returns a decoded 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)
 Same as ast_base64encode, but does hte math for you and returns an 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_careful_fwrite (FILE *f, int fd, const char *s, size_t len, int timeoutms)
 Write data to a file stream with a timeout. 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_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...
 
char * ast_crypt (const char *key, const char *salt)
 Asterisk wrapper around crypt(3). More...
 
char * ast_crypt_encrypt (const char *key)
 Asterisk wrapper around crypt(3) for encrypting passwords. More...
 
int ast_crypt_validate (const char *key, const char *expected)
 Asterisk wrapper around crypt(3) for validating passwords. 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_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_file_is_readable (const char *filename)
 Test that a file exists and is readable by the effective user. More...
 
int ast_get_tid (void)
 Get current thread ID. More...
 
struct hostent * ast_gethostbyname (const char *host, struct ast_hostent *hp)
 Thread-safe gethostbyname function to use in Asterisk. More...
 
void ast_md5_hash (char *output, const char *input)
 Produces MD5 hash based on input string. 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)
 
void ast_register_thread (char *name)
 
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)
 Produces SHA1 hash based on input string. More...
 
void ast_sha1_hash_uint (uint8_t *digest, const char *input)
 Produces SHA1 hash based on input string, stored in uint8_t array. More...
 
static force_inline void ast_slinear_saturated_add (short *input, short *value)
 
static force_inline void ast_slinear_saturated_divide (short *input, short *value)
 
static force_inline void ast_slinear_saturated_divide_float (short *input, float *value)
 
static force_inline void ast_slinear_saturated_multiply (short *input, short *value)
 
static force_inline void ast_slinear_saturated_multiply_float (short *input, float *value)
 
static force_inline void ast_slinear_saturated_subtract (short *input, short *value)
 
int ast_str_to_eid (struct ast_eid *eid, const char *s)
 Convert a string into an EID. 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...
 
void ast_unescape_quoted (char *quote_str)
 Unescape quotes in a string. More...
 
void ast_unregister_thread (void *id)
 
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_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 *outbuf, size_t buflen)
 Escape reserved characters for use in XML. More...
 

Variables

unsigned int __unsigned_int_flags_dummy
 
uint64_t __unsigned_int_flags_dummy64
 
struct ast_eid ast_eid_default
 Global EID. More...
 
const struct ast_flags ast_uri_http
 
const struct ast_flags ast_uri_http_legacy
 
const struct ast_flags ast_uri_sip_user
 

Detailed Description

Utility functions.

Definition in file utils.h.

Macro Definition Documentation

◆ ARRAY_IN_BOUNDS

#define ARRAY_IN_BOUNDS (   v,
  a 
)    IN_BOUNDS((int) (v), 0, ARRAY_LEN(a) - 1)

Checks to see if value is within the bounds of the given array.

Parameters
vthe value to check
athe array to bound check
Returns
0 if value out of bounds, otherwise true (non-zero)

Definition at line 658 of file utils.h.

◆ ARRAY_LEN

#define ARRAY_LEN (   a)    (size_t) (sizeof(a) / sizeof(0[a]))
Examples
app_skel.c.

Definition at line 639 of file utils.h.

◆ ast_align_for

#define ast_align_for (   offset,
  type 
)    (((offset + __alignof__(type) - 1) / __alignof__(type)) * __alignof__(type))

Increase offset so it is a multiple of the required alignment of type.

Parameters
offsetThe value that should be increased.
typeThe data type that offset should be aligned to.
Returns
The smallest multiple of alignof(type) larger than or equal to offset.
See also
ast_make_room_for()

Many systems prefer integers to be stored on aligned on memory locations. This macro will increase an offset so a value of the supplied type can be safely be stored on such a memory location.

Examples: ast_align_for(0x17, int64_t) ==> 0x18 ast_align_for(0x18, int64_t) ==> 0x18 ast_align_for(0x19, int64_t) ==> 0x20

Don't mind the ugliness, the compiler will optimize it.

Definition at line 758 of file utils.h.

◆ ast_alignof

#define ast_alignof (   type)    __alignof__(type)

Return the number of bytes used in the alignment of type.

Parameters
type
Returns
The number of bytes required for alignment.

This is really just alignof(), but tucked away in this header so we don't have to look at the nasty underscores in the source.

Definition at line 738 of file utils.h.

◆ ast_assert

#define ast_assert (   a)

Definition at line 710 of file utils.h.

◆ ast_assert_return

#define ast_assert_return (   a,
  ... 
)
Value:
({ \
if (__builtin_expect(!(a), 1)) { \
return __VA_ARGS__; \
}\
})
static struct test_val a

Definition at line 711 of file utils.h.

◆ AST_BACKGROUND_STACKSIZE

#define AST_BACKGROUND_STACKSIZE   ast_background_stacksize()

Definition at line 546 of file utils.h.

◆ ast_clear_flag

#define ast_clear_flag (   p,
  flag 
)

Definition at line 77 of file utils.h.

◆ ast_clear_flag64

#define ast_clear_flag64 (   p,
  flag 
)

Definition at line 134 of file utils.h.

◆ ast_clear_flag_nonstd

#define ast_clear_flag_nonstd (   p,
  flag 
)
Value:
do { \
((p)->flags &= ~(flag)); \
} while(0)
long int flag
Definition: f2c.h:83

Definition at line 180 of file utils.h.

◆ ast_copy_flags

#define ast_copy_flags (   dest,
  src,
  flagz 
)

Definition at line 84 of file utils.h.

◆ ast_copy_flags64

#define ast_copy_flags64 (   dest,
  src,
  flagz 
)

Definition at line 141 of file utils.h.

◆ ast_copy_flags_nonstd

#define ast_copy_flags_nonstd (   dest,
  src,
  flagz 
)
Value:
do { \
(dest)->flags &= ~(flagz); \
(dest)->flags |= ((src)->flags & (flagz)); \
} while (0)

Definition at line 184 of file utils.h.

◆ ast_fd_clear_flags

#define ast_fd_clear_flags (   fd,
  flags 
)     __ast_fd_set_flags((fd), (flags), AST_FD_FLAG_CLEAR, __FILE__, __LINE__, __PRETTY_FUNCTION__)

Clear flags on the given file descriptor.

Since
13.19

If getting or setting flags of the given file descriptor fails, logs an error message.

Parameters
fdFile descriptor to clear flags on
flagsThe flag(s) to clear
Returns
-1 on error
0 if successful

Definition at line 1025 of file utils.h.

◆ ast_fd_set_flags

#define ast_fd_set_flags (   fd,
  flags 
)     __ast_fd_set_flags((fd), (flags), AST_FD_FLAG_SET, __FILE__, __LINE__, __PRETTY_FUNCTION__)

Set flags on the given file descriptor.

Since
13.19

If getting or setting flags of the given file descriptor fails, logs an error message.

Parameters
fdFile descriptor to set flags on
flagsThe flag(s) to set
Returns
-1 on error
0 if successful

Definition at line 1009 of file utils.h.

◆ AST_FLAGS_ALL

#define AST_FLAGS_ALL   UINT_MAX

Definition at line 196 of file utils.h.

◆ ast_make_room_for

#define ast_make_room_for (   offset,
  type 
)    (((offset + (2 * __alignof__(type) - 1)) / __alignof__(type)) * __alignof__(type))

Increase offset by the required alignment of type and make sure it is a multiple of said alignment.

Parameters
offsetThe value that should be increased.
typeThe data type that room should be reserved for.
Returns
The smallest multiple of alignof(type) larger than or equal to offset plus alignof(type).
See also
ast_align_for()

A use case for this is when prepending length fields of type int to a buffer. If you keep the offset a multiple of the alignment of the integer type, a next block of length+buffer will have the length field automatically aligned.

Examples: ast_make_room_for(0x17, int64_t) ==> 0x20 ast_make_room_for(0x18, int64_t) ==> 0x20 ast_make_room_for(0x19, int64_t) ==> 0x28

Don't mind the ugliness, the compiler will optimize it.

Definition at line 781 of file utils.h.

◆ ast_pipe_nonblock

#define ast_pipe_nonblock (   filedes)    pipe2((filedes), O_NONBLOCK)

Create a non-blocking pipe.

Since
13.25

Wrapper around pipe(2) that sets the O_NONBLOCK flag on the resulting file descriptors.

For parameter and return information, see the man page for pipe(2).

Definition at line 1060 of file utils.h.

◆ ast_pthread_create

#define ast_pthread_create (   a,
  b,
  c,
  d 
)
Value:
0, __FILE__, __FUNCTION__, __LINE__, #c)
static struct test_val b
static struct test_val d
static struct test_val c
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: main/utils.c:1446

Definition at line 559 of file utils.h.

◆ ast_pthread_create_background

#define ast_pthread_create_background (   a,
  b,
  c,
  d 
)
Value:
__FILE__, __FUNCTION__, __LINE__, #c)
#define AST_BACKGROUND_STACKSIZE
Definition: utils.h:546

Definition at line 567 of file utils.h.

◆ ast_pthread_create_detached

#define ast_pthread_create_detached (   a,
  b,
  c,
  d 
)
Value:
0, __FILE__, __FUNCTION__, __LINE__, #c)
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)
Definition: main/utils.c:1494

Definition at line 563 of file utils.h.

◆ ast_pthread_create_detached_background

#define ast_pthread_create_detached_background (   a,
  b,
  c,
  d 
)
Value:
__FILE__, __FUNCTION__, __LINE__, #c)

Definition at line 572 of file utils.h.

◆ ast_random_double

#define ast_random_double ( )    (((double)ast_random()) / RAND_MAX)

Returns a random number between 0.0 and 1.0, inclusive.

Since
12

Definition at line 599 of file utils.h.

◆ ast_set2_flag

#define ast_set2_flag (   p,
  value,
  flag 
)

Definition at line 94 of file utils.h.

◆ ast_set2_flag64

#define ast_set2_flag64 (   p,
  value,
  flag 
)

Definition at line 151 of file utils.h.

◆ ast_set2_flag_nonstd

#define ast_set2_flag_nonstd (   p,
  value,
  flag 
)

Definition at line 189 of file utils.h.

◆ ast_set_flag

#define ast_set_flag (   p,
  flag 
)

Definition at line 70 of file utils.h.

◆ ast_set_flag64

#define ast_set_flag64 (   p,
  flag 
)

Definition at line 127 of file utils.h.

◆ ast_set_flag_nonstd

#define ast_set_flag_nonstd (   p,
  flag 
)
Value:
do { \
((p)->flags |= (flag)); \
} while(0)

Definition at line 176 of file utils.h.

◆ ast_set_flags_to

#define ast_set_flags_to (   p,
  flag,
  value 
)

Definition at line 104 of file utils.h.

◆ ast_set_flags_to64

#define ast_set_flags_to64 (   p,
  flag,
  value 
)

Definition at line 161 of file utils.h.

◆ ast_socket_nonblock

#define ast_socket_nonblock (   domain,
  type,
  protocol 
)    socket((domain), (type) | SOCK_NONBLOCK, (protocol))

Create a non-blocking socket.

Since
13.25

Wrapper around socket(2) that sets the O_NONBLOCK flag on the resulting socket.

For parameter and return information, see the man page for socket(2).

Definition at line 1043 of file utils.h.

◆ AST_STACKSIZE

#define AST_STACKSIZE   (((sizeof(void *) * 8 * 8) - 16) * 1024)

Definition at line 540 of file utils.h.

◆ AST_STACKSIZE_LOW

#define AST_STACKSIZE_LOW   (((sizeof(void *) * 8 * 2) - 16) * 1024)

Definition at line 541 of file utils.h.

◆ ast_test_flag

#define ast_test_flag (   p,
  flag 
)
Examples
app_skel.c.

Definition at line 63 of file utils.h.

◆ ast_test_flag64

#define ast_test_flag64 (   p,
  flag 
)

Definition at line 120 of file utils.h.

◆ ast_test_flag_nonstd

#define ast_test_flag_nonstd (   p,
  flag 
)     ((p)->flags & (flag))

Definition at line 173 of file utils.h.

◆ AST_URI_ALPHANUM

#define AST_URI_ALPHANUM   (1 << 0)

Definition at line 339 of file utils.h.

◆ AST_URI_LEGACY_SPACE

#define AST_URI_LEGACY_SPACE   (1 << 2)

Definition at line 342 of file utils.h.

◆ AST_URI_MARK

#define AST_URI_MARK   (1 << 1)

Definition at line 340 of file utils.h.

◆ AST_URI_SIP_USER_UNRESERVED

#define AST_URI_SIP_USER_UNRESERVED   (1 << 20)

Definition at line 344 of file utils.h.

◆ AST_URI_UNRESERVED

#define AST_URI_UNRESERVED   (AST_URI_ALPHANUM | AST_URI_MARK)

Definition at line 341 of file utils.h.

◆ DO_CRASH_NORETURN

#define DO_CRASH_NORETURN

Definition at line 688 of file utils.h.

◆ IN_BOUNDS

#define IN_BOUNDS (   v,
  min,
  max 
)    ((v) >= (min)) && ((v) <= (max))

Checks to see if value is within the given bounds.

Parameters
vthe value to check
minminimum lower bound (inclusive)
maxmaximum upper bound (inclusive)
Returns
0 if value out of bounds, otherwise true (non-zero)

Definition at line 649 of file utils.h.

◆ localtime_r

#define localtime_r   __dont_use_localtime_r_use_ast_localtime_instead__

Definition at line 496 of file utils.h.

◆ MAX

#define MAX (   a,
  b 
)    ({ typeof(a) __a = (a); typeof(b) __b = (b); ((__a < __b) ? __b : __a);})

Definition at line 228 of file utils.h.

◆ MIN

#define MIN (   a,
  b 
)    ({ typeof(a) __a = (a); typeof(b) __b = (b); ((__a > __b) ? __b : __a);})

Definition at line 226 of file utils.h.

◆ RAII_VAR

#define RAII_VAR (   vartype,
  varname,
  initval,
  dtor 
)
Value:
auto void _dtor_ ## varname (vartype * v); \
void _dtor_ ## varname (vartype * v) { dtor(*v); } \
vartype varname __attribute__((cleanup(_dtor_ ## varname))) = (initval)
static void * cleanup(void *unused)
Definition: pbx_realtime.c:124

Declare a variable that will call a destructor function when it goes out of scope.

Resource Allocation Is Initialization (RAII) variable declaration.

Since
11.0
Parameters
vartypeThe type of the variable
varnameThe name of the variable
initvalThe initial value of the variable
dtorThe destructor function of type' void func(vartype *)'
void mything_cleanup(struct mything *t)
{
if (t) {
ast_free(t->stuff);
}
}
void do_stuff(const char *name)
{
RAII_VAR(struct mything *, thing, mything_alloc(name), mything_cleanup);
...
}
#define ast_free(a)
Definition: astmm.h:182
static const char name[]
Definition: format_mp3.c:68
#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:911
Note
This macro is especially useful for working with ao2 objects. A common idiom would be a function that needed to look up an ao2 object and might have several error conditions after the allocation that would normally need to unref the ao2 object. With RAII_VAR, it is possible to just return and leave the cleanup to the destructor function. For example:
void do_stuff(const char *name)
{
RAII_VAR(struct mything *, thing, find_mything(name), ao2_cleanup);
if (!thing) {
return;
}
if (error) {
return;
}
do_stuff_with_thing(thing);
}
#define ao2_cleanup(obj)
Definition: astobj2.h:1958
int error(const char *format,...)
Definition: utils/frame.c:999
Examples
app_skel.c.

Definition at line 911 of file utils.h.

◆ SWAP

#define SWAP (   a,
  b 
)    do { typeof(a) __tmp = (a); (a) = (b); (b) = __tmp; } while (0)

Definition at line 230 of file utils.h.

Enumeration Type Documentation

◆ ast_fd_flag_operation

Enumerator
AST_FD_FLAG_SET 
AST_FD_FLAG_CLEAR 

Definition at line 991 of file utils.h.

991  {
994 };
@ AST_FD_FLAG_SET
Definition: utils.h:992
@ AST_FD_FLAG_CLEAR
Definition: utils.h:993

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 2564 of file main/utils.c.

2565 {
2566  /*
2567  * Attempt to put it into the logger, but hope that at least
2568  * someone saw the message on stderr ...
2569  */
2570  fprintf(stderr, "FRACK!, Failed assertion %s (%d) at line %d in %s of %s\n",
2571  condition_str, condition, line, function, file);
2572  ast_log(__LOG_ERROR, file, line, function, "FRACK!, Failed assertion %s (%d)\n",
2573  condition_str, condition);
2574 
2575  /* Generate a backtrace for the assert */
2577 
2578  /*
2579  * Give the logger a chance to get the message out, just in case
2580  * we abort(), or Asterisk crashes due to whatever problem just
2581  * happened after we exit ast_assert().
2582  */
2583  usleep(1);
2584  ast_do_crash();
2585 }
#define ast_log
Definition: astobj2.c:42
#define __LOG_ERROR
Definition: logger.h:285
void ast_log_backtrace(void)
Log a backtrace of the current thread's execution stack to the Asterisk log.
Definition: logger.c:2241
void DO_CRASH_NORETURN ast_do_crash(void)
Force a crash if DO_CRASH is defined.
Definition: main/utils.c:2552

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 2898 of file main/utils.c.

2900 {
2901  int f;
2902 
2903  f = fcntl(fd, F_GETFL);
2904  if (f == -1) {
2905  ast_log(__LOG_ERROR, file, lineno, function,
2906  "Failed to get fcntl() flags for file descriptor: %s\n", strerror(errno));
2907  return -1;
2908  }
2909 
2910  switch (op) {
2911  case AST_FD_FLAG_SET:
2912  if ((f & flags) == flags) {
2913  /* There is nothing to set */
2914  return 0;
2915  }
2916  f |= flags;
2917  break;
2918  case AST_FD_FLAG_CLEAR:
2919  if (!(f & flags)) {
2920  /* There is nothing to clear */
2921  return 0;
2922  }
2923  f &= ~flags;
2924  break;
2925  default:
2926  ast_assert(0);
2927  break;
2928  }
2929 
2930  f = fcntl(fd, F_SETFL, f);
2931  if (f == -1) {
2932  ast_log(__LOG_ERROR, file, lineno, function,
2933  "Failed to set fcntl() flags for file descriptor: %s\n", strerror(errno));
2934  return -1;
2935  }
2936 
2937  return 0;
2938 }
int errno
#define ast_assert(a)
Definition: utils.h:710

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

◆ ast_background_stacksize()

int ast_background_stacksize ( void  )

Definition at line 1437 of file main/utils.c.

1438 {
1439 #if !defined(LOW_MEMORY)
1440  return AST_STACKSIZE;
1441 #else
1442  return AST_STACKSIZE_LOW;
1443 #endif
1444 }
#define AST_STACKSIZE
Definition: utils.h:540
#define AST_STACKSIZE_LOW
Definition: utils.h:541

References AST_STACKSIZE, and AST_STACKSIZE_LOW.

◆ ast_base64decode()

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

Decode data from base64.

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.

Decode data from base64.

Definition at line 294 of file main/utils.c.

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

References b2a, and max.

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

◆ ast_base64decode_string()

char* ast_base64decode_string ( const char *  src)

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

Note
The returned string will need to be freed later and IS NULL terminated
Parameters
srcThe source buffer
Return values
NULLon failure
Decodedstring on success

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

Definition at line 321 of file main/utils.c.

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

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 404 of file main/utils.c.

405 {
406  return ast_base64encode_full(dst, src, srclen, max, 0);
407 }
int ast_base64encode_full(char *dst, const unsigned char *src, int srclen, int max, int linebreaks)
encode text to BASE64 coding
Definition: main/utils.c:353

References ast_base64encode_full(), and max.

Referenced by ast_base64encode_string(), ast_sign(), AST_TEST_DEFINE(), base64_helper(), build_secret(), crypto_init_keys(), osp_check_destination(), 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 353 of file main/utils.c.

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

References base64, and max.

Referenced by ast_base64encode().

◆ ast_base64encode_string()

char* ast_base64encode_string ( const char *  src)

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

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

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

Definition at line 410 of file main/utils.c.

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

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 427 of file main/utils.c.

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

References b2a_url, and max.

Referenced by ast_base64url_decode_string(), and stir_shaken_verify_signature().

◆ 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
Decodedstring on success

Definition at line 448 of file main/utils.c.

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

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

Referenced by stir_shaken_incoming_request().

◆ 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 516 of file main/utils.c.

517 {
518  return ast_base64url_encode_full(dst, src, srclen, max, 0);
519 }
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: main/utils.c:469

References ast_base64url_encode_full(), and max.

Referenced by ast_base64url_encode_string(), and stir_shaken_sign().

◆ 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 469 of file main/utils.c.

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

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
Encodedstring on success

Definition at line 521 of file main/utils.c.

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

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

Referenced by add_identity_header().

◆ ast_careful_fwrite()

int ast_careful_fwrite ( FILE *  f,
int  fd,
const char *  s,
size_t  len,
int  timeoutms 
)

Write data to a file stream with a timeout.

Parameters
fthe file stream to write to
fdthe file description to poll on to know when the file stream can be written to without blocking.
sthe buffer to write from
lenthe number of bytes to write
timeoutmsThe maximum amount of time to block in this function trying to write, specified in milliseconds.
Note
This function assumes that the associated file stream has been set up as non-blocking.
Return values
0success
-1error

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

Note
If you are calling ast_carefulwrite, it is assumed that you are calling it on a file descriptor that DOES have NONBLOCK set. This way, 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.

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 1592 of file main/utils.c.

1593 {
1594  struct timeval start = ast_tvnow();
1595  int res = 0;
1596  int elapsed = 0;
1597 
1598  while (len) {
1599  if (wait_for_output(fd, timeoutms - elapsed)) {
1600  return -1;
1601  }
1602 
1603  res = write(fd, s, len);
1604 
1605  if (res < 0 && errno != EAGAIN && errno != EINTR) {
1606  /* fatal error from write() */
1607  if (errno == EPIPE) {
1608 #ifndef STANDALONE
1609  ast_debug(1, "write() failed due to reading end being closed: %s\n", strerror(errno));
1610 #endif
1611  } else {
1612  ast_log(LOG_ERROR, "write() returned error: %s\n", strerror(errno));
1613  }
1614  return -1;
1615  }
1616 
1617  if (res < 0) {
1618  /* It was an acceptable error */
1619  res = 0;
1620  }
1621 
1622  /* Update how much data we have left to write */
1623  len -= res;
1624  s += res;
1625  res = 0;
1626 
1627  elapsed = ast_tvdiff_ms(ast_tvnow(), start);
1628  if (elapsed >= timeoutms) {
1629  /* We've taken too long to write
1630  * This is only an error condition if we haven't finished writing. */
1631  res = len ? -1 : 0;
1632  break;
1633  }
1634  }
1635 
1636  return res;
1637 }
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.
Definition: logger.h:453
#define LOG_ERROR
Definition: logger.h:286
static int wait_for_output(int fd, int timeoutms)
Definition: main/utils.c:1539
int64_t ast_tvdiff_ms(struct timeval end, struct timeval start)
Computes the difference (in milliseconds) between two struct timeval instances.
Definition: time.h:98
struct timeval ast_tvnow(void)
Returns current timeval. Meant to replace calls to gettimeofday().
Definition: time.h:150

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

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

◆ ast_check_ipv6()

int ast_check_ipv6 ( void  )

Test that an OS supports IPv6 Networking.

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

Definition at line 2540 of file main/utils.c.

2541 {
2542  int udp6_socket = socket(AF_INET6, SOCK_DGRAM, 0);
2543 
2544  if (udp6_socket < 0) {
2545  return 0;
2546  }
2547 
2548  close(udp6_socket);
2549  return 1;
2550 }

◆ 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.
Returns
<0 if version 1 < version 2.
=0 if version 1 = version 2.
>0 if version 1 > version 2.

Definition at line 2872 of file main/utils.c.

2873 {
2874  unsigned int major[2] = { 0 };
2875  unsigned int minor[2] = { 0 };
2876  unsigned int patch[2] = { 0 };
2877  unsigned int extra[2] = { 0 };
2878  int res;
2879 
2880  sscanf(version1, "%u.%u.%u.%u", &major[0], &minor[0], &patch[0], &extra[0]);
2881  sscanf(version2, "%u.%u.%u.%u", &major[1], &minor[1], &patch[1], &extra[1]);
2882 
2883  res = major[0] - major[1];
2884  if (res) {
2885  return res;
2886  }
2887  res = minor[0] - minor[1];
2888  if (res) {
2889  return res;
2890  }
2891  res = patch[0] - patch[1];
2892  if (res) {
2893  return res;
2894  }
2895  return extra[0] - extra[1];
2896 }

Referenced by transport_apply().

◆ ast_crypt()

char* ast_crypt ( const char *  key,
const char *  salt 
)

Asterisk wrapper around crypt(3).

The interpretation of the salt (which determines the password hashing algorithm) is system specific. Application code should prefer to use ast_crypt_encrypt() or ast_crypt_validate().

The returned string is heap allocated, and should be freed with ast_free().

Parameters
keyUser's password to crypt.
saltSalt to crypt with.
Returns
Crypted password.
NULL on error.

Definition at line 121 of file crypt.c.

122 {
123  struct crypt_data data = {};
124  const char *crypted = crypt_r(key, salt, &data);
125 
126  /* Crypt may return success even if it doesn't recognize the salt. But
127  * in those cases it always mangles the salt in some way.
128  */
129  if (!crypted || !ast_begins_with(crypted, salt)) {
130  return NULL;
131  }
132 
133  return ast_strdup(crypted);
134 }
#define ast_strdup(str)
A wrapper for strdup()
Definition: astmm.h:243
static int force_inline attribute_pure ast_begins_with(const char *str, const char *prefix)
Definition: strings.h:94

References ast_begins_with(), ast_strdup, and NULL.

Referenced by ast_crypt_encrypt().

◆ ast_crypt_encrypt()

char* ast_crypt_encrypt ( const char *  key)

Asterisk wrapper around crypt(3) for encrypting passwords.

This function will generate a random salt and encrypt the given password.

The returned string is heap allocated, and should be freed with ast_free().

Parameters
keyUser's password to crypt.
Returns
Crypted password.
NULL on error.

Definition at line 190 of file crypt.c.

191 {
192  char salt[MAX_SALT_LEN] = {};
193  while (gen_salt(salt, sizeof(salt)) == 0) {
194  char *crypted = ast_crypt(key, salt);
195  if (crypted) {
196  return crypted;
197  }
198  }
199  return NULL;
200 }
static int gen_salt(char *current_salt, size_t maxlen)
Generates a salt to try with crypt.
Definition: crypt.c:72
#define MAX_SALT_LEN
Max length of a salt string.
Definition: crypt.c:43
char * ast_crypt(const char *key, const char *salt)
Asterisk wrapper around crypt(3).
Definition: crypt.c:121

References ast_crypt(), gen_salt(), MAX_SALT_LEN, and NULL.

Referenced by ari_mkpasswd(), and AST_TEST_DEFINE().

◆ ast_crypt_validate()

int ast_crypt_validate ( const char *  key,
const char *  expected 
)

Asterisk wrapper around crypt(3) for validating passwords.

Parameters
keyUser's password to validate.
expectedExpected result from crypt.
Returns
True (non-zero) if key matches expected.
False (zero) if key doesn't match.

Definition at line 136 of file crypt.c.

137 {
138  struct crypt_data data = {};
139  return strcmp(expected, crypt_r(key, expected, &data)) == 0;
140 }

Referenced by ast_ari_config_validate_user(), and AST_TEST_DEFINE().

◆ 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.
Returns
Nothing

Definition at line 2552 of file main/utils.c.

2553 {
2554 #if defined(DO_CRASH)
2555  abort();
2556  /*
2557  * Just in case abort() doesn't work or something else super
2558  * silly, and for Qwell's amusement.
2559  */
2560  *((int *) 0) = 0;
2561 #endif /* defined(DO_CRASH) */
2562 }

Referenced by __ast_assert_failed(), and sip_route_process_header().

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

Returns
1 if the EID is empty, zero otherwise
Since
13.12.0

Definition at line 2847 of file main/utils.c.

2848 {
2849  struct ast_eid empty_eid;
2850 
2851  memset(&empty_eid, 0, sizeof(empty_eid));
2852  return memcmp(eid, &empty_eid, sizeof(empty_eid)) ? 0 : 1;
2853 }
static dundi_eid empty_eid
Definition: pbx_dundi.c:212
An Entity ID is essentially a MAC address, brief and unique.
Definition: utils.h:786
unsigned char eid[6]
Definition: utils.h:787

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 2587 of file main/utils.c.

2588 {
2589  int x;
2590  char *os = s;
2591  if (maxlen < 18) {
2592  if (s && (maxlen > 0)) {
2593  *s = '\0';
2594  }
2595  } else {
2596  for (x = 0; x < 5; x++) {
2597  sprintf(s, "%02hhx:", eid->eid[x]);
2598  s += 3;
2599  }
2600  sprintf(s, "%02hhx", eid->eid[5]);
2601  }
2602  return os;
2603 }

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_publisher_devstate_cb(), asterisk_publisher_mwistate_cb(), build_peer(), build_transactions(), cache_lookup(), cache_lookup_internal(), 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_peer(), dundi_show_peers(), dundi_show_requests(), 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(), 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
Returns
Nothing

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 2221 of file main/utils.c.

2222 {
2223 #if defined(HAVE_IP_MTU_DISCOVER)
2224  int val = IP_PMTUDISC_DONT;
2225 
2226  if (setsockopt(sock, IPPROTO_IP, IP_MTU_DISCOVER, &val, sizeof(val)))
2227  ast_log(LOG_WARNING, "Unable to disable PMTU discovery. Large UDP packets may fail to be delivered when sent from this socket.\n");
2228 #endif /* HAVE_IP_MTU_DISCOVER */
2229 }
#define LOG_WARNING
Definition: logger.h:275
Definition: ast_expr2.c:325

References ast_log, and LOG_WARNING.

Referenced by ast_netsock_bindaddr(), and reload_config().

◆ 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 635 of file main/utils.c.

636 {
637  const char *ptr = string;
638  char *out = outbuf;
639  char *allow = "\t\v !"; /* allow LWS (minus \r and \n) and "!" */
640 
641  while (*ptr && out - outbuf < buflen - 1) {
642  if (!(strchr(allow, *ptr))
643  && !(*ptr >= '#' && *ptr <= '[') /* %x23 - %x5b */
644  && !(*ptr >= ']' && *ptr <= '~') /* %x5d - %x7e */
645  && !((unsigned char) *ptr > 0x7f)) { /* UTF8-nonascii */
646 
647  if (out - outbuf >= buflen - 2) {
648  break;
649  }
650  out += sprintf(out, "\\%c", (unsigned char) *ptr);
651  } else {
652  *out = *ptr;
653  out++;
654  }
655  ptr++;
656  }
657 
658  if (buflen) {
659  *out = '\0';
660  }
661 
662  return outbuf;
663 }
const char * string
Definition: presencestate.c:71
FILE * out
Definition: utils/frame.c:33

References out, and string.

Referenced by add_diversion(), add_rpid(), ast_callerid_merge(), ast_sip_modify_id_header(), AST_TEST_DEFINE(), channel_read_pjsip(), create_new_id_hdr(), initreqprep(), print_escaped_uri(), and receive_message().

◆ 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 665 of file main/utils.c.

666 {
667  const char *ptr = string;
668  char *out = outbuf;
669 
670  if (string == NULL || outbuf == NULL) {
671  ast_assert(string != NULL && outbuf != NULL);
672  return NULL;
673  }
674 
675  while (*ptr && out - outbuf < buflen - 1) {
676  if (*ptr == ';') {
677  if (out - outbuf >= buflen - 2) {
678  break;
679  }
680  strcpy(out, "\\;");
681  out += 2;
682  } else {
683  *out = *ptr;
684  out++;
685  }
686  ptr++;
687  }
688 
689  if (buflen) {
690  *out = '\0';
691  }
692 
693  return outbuf;
694 }

References ast_assert, NULL, out, and string.

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

◆ 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.
Returns
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 2855 of file main/utils.c.

2856 {
2857 #if defined(HAVE_EACCESS) || defined(HAVE_EUIDACCESS)
2858 #if defined(HAVE_EUIDACCESS) && !defined(HAVE_EACCESS)
2859 #define eaccess euidaccess
2860 #endif
2861  return eaccess(filename, R_OK) == 0;
2862 #else
2863  int fd = open(filename, O_RDONLY | O_NONBLOCK);
2864  if (fd < 0) {
2865  return 0;
2866  }
2867  close(fd);
2868  return 1;
2869 #endif
2870 }

Referenced by add_email_attachment(), ast_media_cache_retrieve(), ast_rtp_dtls_cfg_parse(), on_load_ca_file(), on_load_ca_path(), and transport_tls_file_handler().

◆ ast_get_tid()

int ast_get_tid ( void  )

Get current thread ID.

Returns
the ID if platform is supported, else -1

Definition at line 2504 of file main/utils.c.

2505 {
2506  int ret = -1;
2507 #if defined (__linux) && defined(SYS_gettid)
2508  ret = syscall(SYS_gettid); /* available since Linux 1.4.11 */
2509 #elif defined(__sun)
2510  ret = pthread_self();
2511 #elif defined(__APPLE__)
2512  ret = mach_thread_self();
2513  mach_port_deallocate(mach_task_self(), ret);
2514 #elif defined(__FreeBSD__) && defined(HAVE_SYS_THR_H)
2515  long lwpid;
2516  thr_self(&lwpid); /* available since sys/thr.h creation 2003 */
2517  ret = lwpid;
2518 #endif
2519  return ret;
2520 }

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

◆ ast_gethostbyname()

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

Thread-safe gethostbyname function to use in Asterisk.

Thread-safe gethostbyname function to use in Asterisk.

Definition at line 197 of file main/utils.c.

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

References hp, NULL, and result.

Referenced by ast_parse_arg(), config_load(), config_parse_variables(), festival_exec(), iax_template_parse(), process_sdp(), and reload_config().

◆ ast_md5_hash()

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

Produces MD5 hash based on input string.

Produces MD5 hash based on input string.

Definition at line 248 of file main/utils.c.

249 {
250  struct MD5Context md5;
251  unsigned char digest[16];
252  char *ptr;
253  int x;
254 
255  MD5Init(&md5);
256  MD5Update(&md5, (const unsigned char *) input, strlen(input));
257  MD5Final(digest, &md5);
258  ptr = output;
259  for (x = 0; x < 16; x++)
260  ptr += sprintf(ptr, "%02hhx", digest[x]);
261 }
static int input(yyscan_t yyscanner)
Definition: ast_expr2f.c:1584
static int md5(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
Definition: func_md5.c:52
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[16], struct MD5Context *context)
Definition: md5.c:120
Definition: md5.h:26

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(), build_reply_digest(), 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
Returns
0 on success or an error code otherwise

Creates a directory path, creating parent directories as needed.

Definition at line 2231 of file main/utils.c.

2232 {
2233  char *ptr;
2234  int len = strlen(path), count = 0, x, piececount = 0;
2235  char *tmp = ast_strdupa(path);
2236  char **pieces;
2237  char *fullpath = ast_alloca(len + 1);
2238  int res = 0;
2239 
2240  for (ptr = tmp; *ptr; ptr++) {
2241  if (*ptr == '/')
2242  count++;
2243  }
2244 
2245  /* Count the components to the directory path */
2246  pieces = ast_alloca(count * sizeof(*pieces));
2247  for (ptr = tmp; *ptr; ptr++) {
2248  if (*ptr == '/') {
2249  *ptr = '\0';
2250  pieces[piececount++] = ptr + 1;
2251  }
2252  }
2253 
2254  *fullpath = '\0';
2255  for (x = 0; x < piececount; x++) {
2256  /* This looks funky, but the buffer is always ideally-sized, so it's fine. */
2257  strcat(fullpath, "/");
2258  strcat(fullpath, pieces[x]);
2259  res = mkdir(fullpath, mode);
2260  if (res && errno != EEXIST)
2261  return errno;
2262  }
2263  return 0;
2264 }
#define ast_alloca(size)
call __builtin_alloca to ensure we get gcc builtin semantics
Definition: astmm.h:290
#define ast_strdupa(s)
duplicate a string in memory from the stack
Definition: astmm.h:300
static int tmp()
Definition: bt_open.c:389

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

Referenced by ast_logger_rotate_channel(), ast_monitor_change_fname(), ast_monitor_start(), conf_rec_name(), conf_run(), create_destination_directory(), create_dirpath(), create_temp_file(), dictate_exec(), filename_parse(), init_logger(), 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 responce 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 2390 of file main/utils.c.

2390  {
2391  char *c;
2392  struct ast_str *str = ast_str_create(16);
2393 
2394  /* table of recognised keywords, and places where they should be copied */
2395  const struct x {
2396  const char *key;
2397  const ast_string_field *field;
2398  } *i, keys[] = {
2399  { "username=", &d->username },
2400  { "realm=", &d->realm },
2401  { "nonce=", &d->nonce },
2402  { "uri=", &d->uri },
2403  { "domain=", &d->domain },
2404  { "response=", &d->response },
2405  { "cnonce=", &d->cnonce },
2406  { "opaque=", &d->opaque },
2407  /* Special cases that cannot be directly copied */
2408  { "algorithm=", NULL },
2409  { "qop=", NULL },
2410  { "nc=", NULL },
2411  { NULL, 0 },
2412  };
2413 
2414  if (ast_strlen_zero(digest) || !d || !str) {
2415  ast_free(str);
2416  return -1;
2417  }
2418 
2419  ast_str_set(&str, 0, "%s", digest);
2420 
2422 
2423  if (strncasecmp(c, "Digest ", strlen("Digest "))) {
2424  ast_log(LOG_WARNING, "Missing Digest.\n");
2425  ast_free(str);
2426  return -1;
2427  }
2428  c += strlen("Digest ");
2429 
2430  /* lookup for keys/value pair */
2431  while (c && *c && *(c = ast_skip_blanks(c))) {
2432  /* find key */
2433  for (i = keys; i->key != NULL; i++) {
2434  char *src, *separator;
2435  int unescape = 0;
2436  if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
2437  continue;
2438  }
2439 
2440  /* Found. Skip keyword, take text in quotes or up to the separator. */
2441  c += strlen(i->key);
2442  if (*c == '"') {
2443  src = ++c;
2444  separator = "\"";
2445  unescape = 1;
2446  } else {
2447  src = c;
2448  separator = ",";
2449  }
2450  strsep(&c, separator); /* clear separator and move ptr */
2451  if (unescape) {
2452  ast_unescape_c(src);
2453  }
2454  if (i->field) {
2455  ast_string_field_ptr_set(d, i->field, src);
2456  } else {
2457  /* Special cases that require additional processing */
2458  if (!strcasecmp(i->key, "algorithm=")) {
2459  if (strcasecmp(src, "MD5")) {
2460  ast_log(LOG_WARNING, "Digest algorithm: \"%s\" not supported.\n", src);
2461  ast_free(str);
2462  return -1;
2463  }
2464  } else if (!strcasecmp(i->key, "qop=") && !strcasecmp(src, "auth")) {
2465  d->qop = 1;
2466  } else if (!strcasecmp(i->key, "nc=")) {
2467  unsigned long u;
2468  if (sscanf(src, "%30lx", &u) != 1) {
2469  ast_log(LOG_WARNING, "Incorrect Digest nc value: \"%s\".\n", src);
2470  ast_free(str);
2471  return -1;
2472  }
2473  ast_string_field_set(d, nc, src);
2474  }
2475  }
2476  break;
2477  }
2478  if (i->key == NULL) { /* not found, try ',' */
2479  strsep(&c, ",");
2480  }
2481  }
2482  ast_free(str);
2483 
2484  /* Digest checkout */
2485  if (ast_strlen_zero(d->realm) || ast_strlen_zero(d->nonce)) {
2486  /* "realm" and "nonce" MUST be always exist */
2487  return -1;
2488  }
2489 
2490  if (!request) {
2491  /* Additional check for Digest response */
2492  if (ast_strlen_zero(d->username) || ast_strlen_zero(d->uri) || ast_strlen_zero(d->response)) {
2493  return -1;
2494  }
2495 
2496  if (pedantic && d->qop && (ast_strlen_zero(d->cnonce) || ast_strlen_zero(d->nc))) {
2497  return -1;
2498  }
2499  }
2500 
2501  return 0;
2502 }
const char * str
Definition: app_jack.c:147
static int request(void *obj)
Definition: chan_pjsip.c:2560
char * strsep(char **str, const char *delims)
char * ast_unescape_c(char *src)
Convert some C escape sequences.
Definition: main/utils.c:1735
#define ast_string_field_set(x, field, data)
Set a field to a simple string value.
Definition: stringfields.h:514
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:470
char * ast_str_buffer(const struct ast_str *buf)
Returns the string buffer within the ast_str buf.
Definition: strings.h:727
#define ast_str_create(init_len)
Create a malloc'ed dynamic length string.
Definition: strings.h:633
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:1078
char * ast_skip_blanks(const char *str)
Gets a pointer to the first non-whitespace character in a string.
Definition: strings.h:157
The descriptor of a dynamic string XXX storage will be optimized later if needed We use the ts field ...
Definition: strings.h:597

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 2104 of file main/utils.c.

2105 {
2106  char *dataPut = start;
2107  int inEscape = 0;
2108  int inQuotes = 0;
2109 
2110  for (; *start; start++) {
2111  if (inEscape) {
2112  *dataPut++ = *start; /* Always goes verbatim */
2113  inEscape = 0;
2114  } else {
2115  if (*start == '\\') {
2116  inEscape = 1; /* Do not copy \ into the data */
2117  } else if (*start == '\'') {
2118  inQuotes = 1 - inQuotes; /* Do not copy ' into the data */
2119  } else {
2120  /* Replace , with |, unless in quotes */
2121  *dataPut++ = inQuotes ? *start : ((*start == find) ? replace_with : *start);
2122  }
2123  }
2124  }
2125  if (start != dataPut)
2126  *dataPut = 0;
2127  return dataPut;
2128 }

◆ 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 1494 of file main/utils.c.

1497 {
1498  unsigned char attr_destroy = 0;
1499  int res;
1500 
1501  if (!attr) {
1502  attr = ast_alloca(sizeof(*attr));
1503  pthread_attr_init(attr);
1504  attr_destroy = 1;
1505  }
1506 
1507  if ((errno = pthread_attr_setdetachstate(attr, PTHREAD_CREATE_DETACHED)))
1508  ast_log(LOG_WARNING, "pthread_attr_setdetachstate: %s\n", strerror(errno));
1509 
1510  res = ast_pthread_create_stack(thread, attr, start_routine, data,
1511  stacksize, file, caller, line, start_fn);
1512 
1513  if (attr_destroy)
1514  pthread_attr_destroy(attr);
1515 
1516  return res;
1517 }
pthread_t thread
Definition: app_meetme.c:1091
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: main/utils.c:1446

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 1446 of file main/utils.c.

1449 {
1450 #if !defined(LOW_MEMORY)
1451  struct thr_arg *a;
1452 #endif
1453 
1454  if (!attr) {
1455  attr = ast_alloca(sizeof(*attr));
1456  pthread_attr_init(attr);
1457  }
1458 
1459 #if defined(__linux__) || defined(__FreeBSD__)
1460  /* On Linux and FreeBSD , pthread_attr_init() defaults to PTHREAD_EXPLICIT_SCHED,
1461  which is kind of useless. Change this here to
1462  PTHREAD_INHERIT_SCHED; that way the -p option to set realtime
1463  priority will propagate down to new threads by default.
1464  This does mean that callers cannot set a different priority using
1465  PTHREAD_EXPLICIT_SCHED in the attr argument; instead they must set
1466  the priority afterwards with pthread_setschedparam(). */
1467  if ((errno = pthread_attr_setinheritsched(attr, PTHREAD_INHERIT_SCHED)))
1468  ast_log(LOG_WARNING, "pthread_attr_setinheritsched: %s\n", strerror(errno));
1469 #endif
1470 
1471  if (!stacksize)
1472  stacksize = AST_STACKSIZE;
1473 
1474  if ((errno = pthread_attr_setstacksize(attr, stacksize ? stacksize : AST_STACKSIZE)))
1475  ast_log(LOG_WARNING, "pthread_attr_setstacksize: %s\n", strerror(errno));
1476 
1477 #if !defined(LOW_MEMORY)
1478  if ((a = ast_malloc(sizeof(*a)))) {
1479  a->start_routine = start_routine;
1480  a->data = data;
1482  if (ast_asprintf(&a->name, "%-20s started at [%5d] %s %s()",
1483  start_fn, line, file, caller) < 0) {
1484  a->name = NULL;
1485  }
1486  data = a;
1487  }
1488 #endif /* !LOW_MEMORY */
1489 
1490  return pthread_create(thread, attr, start_routine, data); /* We're in ast_pthread_create, so it's okay */
1491 }
#define ast_asprintf(ret, fmt,...)
A wrapper for asprintf()
Definition: astmm.h:269
#define pthread_create
Definition: lock.h:640
static void * dummy_start(void *data)
Definition: main/utils.c:1394
const char * name
void *(* start_routine)(void *)
Definition: main/utils.c:1382
void * data
Definition: main/utils.c:1383

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  )
Examples
app_skel.c.

Definition at line 2064 of file main/utils.c.

2065 {
2066  long int res;
2067 
2068  if (dev_urandom_fd >= 0) {
2069  int read_res = read(dev_urandom_fd, &res, sizeof(res));
2070  if (read_res > 0) {
2071  long int rm = RAND_MAX;
2072  res = res < 0 ? ~res : res;
2073  rm++;
2074  return res % rm;
2075  }
2076  }
2077 
2078  /* XXX - Thread safety really depends on the libc, not the OS.
2079  *
2080  * But... popular Linux libc's (uClibc, glibc, eglibc), all have a
2081  * somewhat thread safe random(3) (results are random, but not
2082  * reproducible). The libc's for other systems (BSD, et al.), not so
2083  * much.
2084  */
2085 #ifdef linux
2086  res = random();
2087 #else
2089  res = random();
2091 #endif
2092  return res;
2093 }
#define ast_mutex_unlock(a)
Definition: lock.h:188
#define ast_mutex_lock(a)
Definition: lock.h:187
static int dev_urandom_fd
Definition: main/utils.c:792
static ast_mutex_t randomlock
Definition: main/utils.c:2061

References ast_mutex_lock, ast_mutex_unlock, dev_urandom_fd, and randomlock.

Referenced by __sip_alloc(), action_challenge(), app_exec(), ast_generate_random_string(), ast_moh_files_next(), 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_gateway(), build_iv(), build_localtag_registry(), build_nonce(), build_rand_pad(), build_reply_digest(), 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_incoming(), handle_response_invite(), iax2_key_rotate(), jingle_add_ice_udp_candidates_to_transport(), jingle_alloc(), jingle_new(), make_email_file(), make_our_tag(), mbl_new(), moh_files_alloc(), multicast_rtp_new(), ogg_vorbis_rewrite(), osp_create_uuid(), page_exec(), process_weights(), reg_source_db(), registry_authrequest(), reqprep(), 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(), start_rtp(), 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(), transmit_invite(), transmit_register(), transmit_response_using_temp(), try_calling(), try_firmware(), websocket_client_create_key(), and websocket_mask_payload().

◆ ast_register_thread()

void ast_register_thread ( char *  name)

Definition at line 414 of file asterisk.c.

415 {
416  struct thread_list_t *new = ast_calloc(1, sizeof(*new));
417 
418  if (!new)
419  return;
420 
422  new->id = pthread_self();
423  new->lwp = ast_get_tid();
424  new->name = name; /* steal the allocated memory for the thread name */
426  AST_RWLIST_INSERT_HEAD(&thread_list, new, list);
428 }
static int multi_thread_safe
Definition: asterisk.c:388
#define AST_RWLIST_WRLOCK(head)
Write locks a list.
Definition: linkedlists.h:52
#define AST_RWLIST_UNLOCK(head)
Attempts to unlock a read/write based list.
Definition: linkedlists.h:151
#define AST_RWLIST_INSERT_HEAD
Definition: linkedlists.h:718
int ast_get_tid(void)
Get current thread ID.
Definition: main/utils.c:2504

References ast_assert, ast_calloc, ast_get_tid(), AST_RWLIST_INSERT_HEAD, AST_RWLIST_UNLOCK, AST_RWLIST_WRLOCK, multi_thread_safe, and name.

Referenced by dummy_start().

◆ 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 2095 of file main/utils.c.

2096 {
2097  for (; *s; s++) {
2098  if (*s == '^') {
2099  *s = ',';
2100  }
2101  }
2102 }

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
pathThe directory path to create
modeThe permissions with which to try to create the directory
Returns
0 on success or an error code otherwise

Definition at line 2336 of file main/utils.c.

2337 {
2338  RAII_VAR(char *, absolute_base_path, NULL, ast_std_free);
2339  RAII_VAR(char *, p, NULL, ast_free);
2340 
2341  if (base_path == NULL || path == NULL) {
2342  errno = EFAULT;
2343  return errno;
2344  }
2345 
2346  p = ast_strdup(path);
2347  if (p == NULL) {
2348  errno = ENOMEM;
2349  return errno;
2350  }
2351 
2352  absolute_base_path = realpath(base_path, NULL);
2353  if (absolute_base_path == NULL) {
2354  return errno;
2355  }
2356 
2357  return safe_mkdir(absolute_base_path, p, mode);
2358 }
void ast_std_free(void *ptr)
Definition: astmm.c:1766
static int safe_mkdir(const char *base_path, char *path, int mode)
Definition: main/utils.c:2266

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 2749 of file main/utils.c.

2750 {
2751  int s;
2752  int i;
2753  struct ifreq *ifr;
2754  struct ifreq *ifrp;
2755  struct ifconf ifc;
2756  char *buf = NULL;
2757  char eid_str[20];
2758  int bufsz, num_interfaces;
2759  unsigned char empty_mac[6] = {0, 0, 0, 0, 0, 0};
2760  unsigned char full_mac[6] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
2761 
2762  s = socket(AF_INET, SOCK_STREAM, 0);
2763  if (s < 0) {
2764  ast_log(LOG_WARNING, "Unable to open socket for seeding global EID. "
2765  "You will have to set it manually.\n");
2766  return;
2767  }
2768 
2769  ifc.ifc_len = 0;
2770  ifc.ifc_buf = NULL;
2771  if (ioctl(s, SIOCGIFCONF, &ifc) || ifc.ifc_len <= 0) {
2772  ast_log(LOG_WARNING, "No ethernet interface found for seeding global EID. "
2773  "You will have to set it manually.\n");
2774  close(s);
2775  return;
2776  }
2777  bufsz = ifc.ifc_len;
2778 
2779  if (!(buf = ast_malloc(bufsz))) {
2780  ast_log(LOG_WARNING, "Unable to allocate memory for seeding global EID. "
2781  "You will have to set it manually.\n");
2782  close(s);
2783  return;
2784  }
2785 
2786  ifc.ifc_buf = buf;
2787  if (ioctl(s, SIOCGIFCONF, &ifc) < 0) {
2788  ast_log(LOG_WARNING, "Unable to retrieve ethernet interfaces for seeding global EID. "
2789  "You will have to set it manually.\n");
2790  ast_free(buf);
2791  close(s);
2792  return;
2793  }
2794 
2795  ifrp = ifc.ifc_req;
2796  num_interfaces = ifc.ifc_len / sizeof(*ifr);
2797 
2798  for (i = 0; i < num_interfaces; i++) {
2799  ifr = &ifrp[i];
2800  if (!ioctl(s, SIOCGIFHWADDR, ifr)) {
2801  unsigned char *hwaddr = (unsigned char *) ifr->ifr_hwaddr.sa_data;
2802 
2803  if (!(memcmp(hwaddr, &empty_mac, 6) && memcmp(hwaddr, &full_mac, 6))) {
2804  continue;
2805  }
2806 
2807  memcpy(eid, hwaddr, sizeof(*eid));
2808  ast_debug(1, "Seeding global EID '%s' from '%s' using 'siocgifhwaddr'\n",
2809  ast_eid_to_str(eid_str, sizeof(eid_str), eid), ifr->ifr_name);
2810  ast_free(buf);
2811  close(s);
2812  return;
2813  }
2814  }
2815 
2816  ast_log(LOG_WARNING, "No ethernet interface found for seeding global EID. "
2817  "You will have to set it manually.\n");
2818  ast_free(buf);
2819  close(s);
2820 
2821  return;
2822 }
if(!yyg->yy_init)
Definition: ast_expr2f.c:868
char buf[BUFSIZE]
Definition: eagi_proxy.c:66
char * ast_eid_to_str(char *s, int maxlen, struct ast_eid *eid)
Convert an EID to a string.
Definition: main/utils.c:2587

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 
)

Produces SHA1 hash based on input string.

Produces SHA1 hash based on input string.

Definition at line 264 of file main/utils.c.

265 {
266  struct SHA1Context sha;
267  char *ptr;
268  int x;
269  uint8_t Message_Digest[20];
270 
271  SHA1Reset(&sha);
272 
273  SHA1Input(&sha, (const unsigned char *) input, strlen(input));
274 
275  SHA1Result(&sha, Message_Digest);
276  ptr = output;
277  for (x = 0; x < 20; x++)
278  ptr += sprintf(ptr, "%02hhx", Message_Digest[x]);
279 }
int SHA1Result(SHA1Context *, uint8_t Message_Digest[SHA1HashSize])
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 add_public_key_to_astdb(), ast_tcptls_server_start(), AST_TEST_DEFINE(), get_path_to_public_key(), handle_call_token(), media_cache_item_sync_to_astdb(), public_key_is_expired(), remove_public_key_from_astdb(), set_public_key_expiration(), sha1(), xmpp_client_authenticate_digest(), and xmpp_component_authenticate().

◆ ast_sha1_hash_uint()

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

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

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

Definition at line 282 of file main/utils.c.

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

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

Referenced by websocket_combine_key().

◆ ast_slinear_saturated_add()

static force_inline void ast_slinear_saturated_add ( short *  input,
short *  value 
)
static

Definition at line 425 of file utils.h.

426 {
427  int res;
428 
429  res = (int) *input + *value;
430  if (res > 32767)
431  *input = 32767;
432  else if (res < -32768)
433  *input = -32768;
434  else
435  *input = (short) res;
436 }
int value
Definition: syslog.c:37

References input(), and value.

Referenced by ast_frame_slinear_sum(), audio_audiohook_write_list(), audiohook_read_frame_both(), binaural_mixing(), and softmix_mixing_loop().

◆ ast_slinear_saturated_divide()

static force_inline void ast_slinear_saturated_divide ( short *  input,
short *  value 
)
static

Definition at line 477 of file utils.h.

478 {
479  *input /= *value;
480 }

References input(), and value.

Referenced by ast_frame_adjust_volume(), and audiohook_read_frame_both().

◆ ast_slinear_saturated_divide_float()

static force_inline void ast_slinear_saturated_divide_float ( short *  input,
float *  value 
)
static

Definition at line 482 of file utils.h.

483 {
484  float res = (float) *input / *value;
485  if (res > 32767)
486  *input = 32767;
487  else if (res < -32768)
488  *input = -32768;
489  else
490  *input = (short) res;
491 }

References input(), and value.

Referenced by ast_frame_adjust_volume_float().

◆ ast_slinear_saturated_multiply()

static force_inline void ast_slinear_saturated_multiply ( short *  input,
short *  value 
)
static

Definition at line 451 of file utils.h.

452 {
453  int res;
454 
455  res = (int) *input * *value;
456  if (res > 32767)
457  *input = 32767;
458  else if (res < -32768)
459  *input = -32768;
460  else
461  *input = (short) res;
462 }

References input(), and value.

Referenced by ast_frame_adjust_volume(), and audiohook_read_frame_both().

◆ ast_slinear_saturated_multiply_float()

static force_inline void ast_slinear_saturated_multiply_float ( short *  input,
float *  value 
)
static

Definition at line 464 of file utils.h.

465 {
466  float res;
467 
468  res = (float) *input * *value;
469  if (res > 32767)
470  *input = 32767;
471  else if (res < -32768)
472  *input = -32768;
473  else
474  *input = (short) res;
475 }

References input(), and value.

Referenced by ast_frame_adjust_volume_float().

◆ ast_slinear_saturated_subtract()

static force_inline void ast_slinear_saturated_subtract ( short *  input,
short *  value 
)
static

Definition at line 438 of file utils.h.

439 {
440  int res;
441 
442  res = (int) *input - *value;
443  if (res > 32767)
444  *input = 32767;
445  else if (res < -32768)
446  *input = -32768;
447  else
448  *input = (short) res;
449 }

References input(), and value.

Referenced by softmix_process_write_audio(), and softmix_process_write_binaural_audio().

◆ 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

Returns
0 success, non-zero failure
Since
1.6.1

Definition at line 2825 of file main/utils.c.

2826 {
2827  unsigned int eid_int[6];
2828  int x;
2829 
2830  if (sscanf(s, "%2x:%2x:%2x:%2x:%2x:%2x", &eid_int[0], &eid_int[1], &eid_int[2],
2831  &eid_int[3], &eid_int[4], &eid_int[5]) != 6) {
2832  return -1;
2833  }
2834 
2835  for (x = 0; x < 6; x++) {
2836  eid->eid[x] = eid_int[x];
2837  }
2838 
2839  return 0;
2840 }

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_thread_is_user_interface()

int ast_thread_is_user_interface ( void  )

Indicates whether the current thread is a user interface.

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

Definition at line 2996 of file main/utils.c.

2997 {
2998  int *thread_user_interface;
2999 
3000  thread_user_interface = ast_threadstorage_get(
3001  &thread_user_interface_tl, sizeof(*thread_user_interface));
3002  if (thread_user_interface == NULL) {
3003  ast_log(LOG_ERROR, "Error checking thread's user interface status\n");
3004  /* On error, assume that we are not a user interface thread */
3005  return 0;
3006  }
3007 
3008  return *thread_user_interface;
3009 }
static struct ast_threadstorage thread_user_interface_tl
Definition: main/utils.c:2979
void * ast_threadstorage_get(struct ast_threadstorage *ts, size_t init_size)
Retrieve thread storage.

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.
Returns
0 if successfuly marked current thread.
Non-zero if marking current thread failed.

Definition at line 2981 of file main/utils.c.

2982 {
2983  int *thread_user_interface;
2984 
2985  thread_user_interface = ast_threadstorage_get(
2986  &thread_user_interface_tl, sizeof(*thread_user_interface));
2987  if (thread_user_interface == NULL) {
2988  ast_log(LOG_ERROR, "Error setting user interface status for current thread\n");
2989  return -1;
2990  }
2991 
2992  *thread_user_interface = !!is_user_interface;
2993  return 0;
2994 }

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

Referenced by handle_tcptls_connection().

◆ 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 696 of file main/utils.c.

697 {
698  int esc_pos;
699  int unesc_pos;
700  int quote_str_len = strlen(quote_str);
701 
702  for (esc_pos = 0, unesc_pos = 0;
703  esc_pos < quote_str_len;
704  esc_pos++, unesc_pos++) {
705  if (quote_str[esc_pos] == '\\') {
706  /* at least one more char and current is \\ */
707  esc_pos++;
708  if (esc_pos >= quote_str_len) {
709  break;
710  }
711  }
712 
713  quote_str[unesc_pos] = quote_str[esc_pos];
714  }
715  quote_str[unesc_pos] = '\0';
716 }

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

◆ ast_unregister_thread()

void ast_unregister_thread ( void *  id)

Definition at line 430 of file asterisk.c.

431 {
432  struct thread_list_t *x;
433 
436  if ((void *) x->id == id) {
438  break;
439  }
440  }
443  if (x) {
444  ast_free(x->name);
445  ast_free(x);
446  }
447 }
#define AST_RWLIST_REMOVE_CURRENT
Definition: linkedlists.h:570
#define AST_RWLIST_TRAVERSE_SAFE_BEGIN
Definition: linkedlists.h:545
#define AST_RWLIST_TRAVERSE_SAFE_END
Definition: linkedlists.h:617

References ast_free, AST_RWLIST_REMOVE_CURRENT, AST_RWLIST_TRAVERSE_SAFE_BEGIN, AST_RWLIST_TRAVERSE_SAFE_END, AST_RWLIST_UNLOCK, and AST_RWLIST_WRLOCK.

Referenced by dummy_start().

◆ 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 616 of file main/utils.c.

617 {
618  char *o;
619  unsigned int tmp;
620 
621  for (o = s; *s; s++, o++) {
622  if (ast_test_flag(&spec, AST_URI_LEGACY_SPACE) && *s == '+') {
623  /* legacy mode, decode '+' as space */
624  *o = ' ';
625  } else if (*s == '%' && s[1] != '\0' && s[2] != '\0' && sscanf(s + 1, "%2x", &tmp) == 1) {
626  /* have '%', two chars and correct parsing */
627  *o = tmp;
628  s += 2; /* Will be incremented once more when we break out */
629  } else /* all other cases, just copy */
630  *o = *s;
631  }
632  *o = '\0';
633 }
#define ast_test_flag(p, flag)
Definition: utils.h:63
#define AST_URI_LEGACY_SPACE
Definition: utils.h:342

References ast_test_flag, AST_URI_LEGACY_SPACE, and tmp().

Referenced by acf_curl_helper(), ast_ari_invoke(), ast_http_get_post_vars(), AST_TEST_DEFINE(), config_curl(), get_name_and_number(), get_refer_info(), handle_request_invite(), handle_uri(), parse_moved_contact(), realtime_curl(), realtime_multi_curl(), sip_new(), sip_uri_cmp(), 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 577 of file main/utils.c.

578 {
579  const char *ptr = string; /* Start with the string */
580  char *out = outbuf;
581  const char *mark = "-_.!~*'()"; /* no encode set, RFC 2396 section 2.3, RFC 3261 sec 25 */
582  const char *user_unreserved = "&=+$,;?/"; /* user-unreserved set, RFC 3261 sec 25 */
583 
584  while (*ptr && out - outbuf < buflen - 1) {
585  if (ast_test_flag(&spec, AST_URI_LEGACY_SPACE) && *ptr == ' ') {
586  /* for legacy encoding, encode spaces as '+' */
587  *out = '+';
588  out++;
589  } else if (!(ast_test_flag(&spec, AST_URI_MARK)
590  && strchr(mark, *ptr))
591  && !(ast_test_flag(&spec, AST_URI_ALPHANUM)
592  && ((*ptr >= '0' && *ptr <= '9')
593  || (*ptr >= 'A' && *ptr <= 'Z')
594  || (*ptr >= 'a' && *ptr <= 'z')))
596  && strchr(user_unreserved, *ptr))) {
597 
598  if (out - outbuf >= buflen - 3) {
599  break;
600  }
601  out += sprintf(out, "%%%02hhX", (unsigned char) *ptr);
602  } else {
603  *out = *ptr; /* Continue copying the string */
604  out++;
605  }
606  ptr++;
607  }
608 
609  if (buflen) {
610  *out = '\0';
611  }
612 
613  return outbuf;
614 }
#define AST_URI_MARK
Definition: utils.h:340
#define AST_URI_SIP_USER_UNRESERVED
Definition: utils.h:344
#define AST_URI_ALPHANUM
Definition: utils.h:339

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

Referenced by add_diversion(), add_rpid(), ast_ari_bridges_record(), ast_ari_channels_record(), AST_TEST_DEFINE(), build_contact(), config_curl(), destroy_curl(), initreqprep(), realtime_curl(), realtime_multi_curl(), require_curl(), store_curl(), update2_curl(), update_curl(), and uriencode().

◆ ast_utils_init()

int ast_utils_init ( void  )

Definition at line 2369 of file main/utils.c.

2370 {
2371  dev_urandom_fd = open("/dev/urandom", O_RDONLY);
2372  base64_init();
2373 #ifdef DEBUG_THREADS
2374 #if !defined(LOW_MEMORY)
2375  ast_cli_register_multiple(utils_cli, ARRAY_LEN(utils_cli));
2376 #endif
2377 #endif
2379  return 0;
2380 }
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: main/utils.c:2360
static void base64_init(void)
Definition: main/utils.c:538
#define ARRAY_LEN(a)
Definition: utils.h:639

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 2522 of file main/utils.c.

2523 {
2524  const char *envPATH = getenv("PATH");
2525  char *tpath, *path;
2526  struct stat unused;
2527  if (!envPATH) {
2528  return NULL;
2529  }
2530  tpath = ast_strdupa(envPATH);
2531  while ((path = strsep(&tpath, ":"))) {
2532  snprintf(fullpath, fullpath_size, "%s/%s", path, binary);
2533  if (!stat(fullpath, &unused)) {
2534  return fullpath;
2535  }
2536  }
2537  return NULL;
2538 }

References ast_strdupa, NULL, and strsep().

◆ ast_wait_for_input()

int ast_wait_for_input ( int  fd,
int  ms 
)

Definition at line 1519 of file main/utils.c.

1520 {
1521  struct pollfd pfd[1];
1522 
1523  memset(pfd, 0, sizeof(pfd));
1524  pfd[0].fd = fd;
1525  pfd[0].events = POLLIN | POLLPRI;
1526  return ast_poll(pfd, 1, ms);
1527 }
#define ast_poll(a, b, c)
Definition: poll-compat.h:88

References ast_poll.

Referenced by action_waitevent(), ast_ari_websocket_session_read(), ast_iostream_wait_for_input(), ast_iostream_write(), ast_tcptls_server_root(), dahdi_test_timer(), get_input(), iostream_read(), moh_class_destructor(), sip_tcptls_read(), sip_websocket_callback(), and unbound_resolver_thread().

◆ ast_wait_for_output()

int ast_wait_for_output ( int  fd,
int  ms 
)

Definition at line 1529 of file main/utils.c.

1530 {
1531  struct pollfd pfd[1];
1532 
1533  memset(pfd, 0, sizeof(pfd));
1534  pfd[0].fd = fd;
1535  pfd[0].events = POLLOUT;
1536  return ast_poll(pfd, 1, ms);
1537 }

References ast_poll.

Referenced by ast_iostream_write(), and iostream_read().

◆ 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
Returns
0 for success
-1 if buflen is too short.

Definition at line 718 of file main/utils.c.

719 {
720  char *dst = outbuf;
721  char *end = outbuf + buflen - 1; /* save one for the null terminator */
722 
723  /* Handle the case for the empty output buffer */
724  if (buflen == 0) {
725  return -1;
726  }
727 
728  /* Escaping rules from http://www.w3.org/TR/REC-xml/#syntax */
729  /* This also prevents partial entities at the end of a string */
730  while (*string && dst < end) {
731  const char *entity = NULL;
732  int len = 0;
733 
734  switch (*string) {
735  case '<':
736  entity = "&lt;";
737  len = 4;
738  break;
739  case '&':
740  entity = "&amp;";
741  len = 5;
742  break;
743  case '>':
744  /* necessary if ]]> is in the string; easier to escape them all */
745  entity = "&gt;";
746  len = 4;
747  break;
748  case '\'':
749  /* necessary in single-quoted strings; easier to escape them all */
750  entity = "&apos;";
751  len = 6;
752  break;
753  case '"':
754  /* necessary in double-quoted strings; easier to escape them all */
755  entity = "&quot;";
756  len = 6;
757  break;
758  default:
759  *dst++ = *string++;
760  break;
761  }
762 
763  if (entity) {
764  ast_assert(len == strlen(entity));
765  if (end - dst < len) {
766  /* no room for the entity; stop */
767  break;
768  }
769  /* just checked for length; strcpy is fine */
770  strcpy(dst, entity);
771  dst += len;
772  ++string;
773  }
774  }
775  /* Write null terminator */
776  *dst = '\0';
777  /* If any chars are left in string, return failure */
778  return *string == '\0' ? 0 : -1;
779 }
char * end
Definition: eagi_proxy.c:73

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

Referenced by ast_http_create_response(), state_notify_build_xml(), and test_xml().

Variable Documentation

◆ __unsigned_int_flags_dummy

unsigned int __unsigned_int_flags_dummy
extern
Note
   Note:
   It is very important to use only unsigned variables to hold
   bit flags, as otherwise you can fall prey to the compiler's
   sign-extension antics if you try to use the top two bits in
   your variable.

   The flag macros below use a set of compiler tricks to verify
   that the caller is using an "unsigned int" variable to hold
   the flags, and nothing else. If the caller uses any other
   type of variable, a warning message similar to this:

   warning: comparison of distinct pointer types lacks cast
   will be generated.

   The "dummy" variable below is used to make these comparisons.

   Also note that at -O2 or above, this type-safety checking
   does _not_ produce any additional object code at all.

◆ __unsigned_int_flags_dummy64

uint64_t __unsigned_int_flags_dummy64
extern

◆ ast_eid_default

struct ast_eid ast_eid_default
extern

◆ ast_uri_http

const struct ast_flags ast_uri_http
extern

◆ ast_uri_http_legacy

const struct ast_flags ast_uri_http_legacy
extern

◆ ast_uri_sip_user

const struct ast_flags ast_uri_sip_user
extern