Wed Jan 8 2020 09:50:22

Asterisk developer's documentation


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_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_alloca(size)   __builtin_alloca(size)
 call __builtin_alloca to ensure we get gcc builtin semantics More...
 
#define ast_asprintf(ret, fmt,...)   _ast_asprintf((ret), __FILE__, __LINE__, __PRETTY_FUNCTION__, fmt, __VA_ARGS__)
 A wrapper for asprintf() More...
 
#define ast_assert(a)
 
#define AST_BACKGROUND_STACKSIZE   AST_STACKSIZE
 
#define ast_calloc(num, len)   _ast_calloc((num), (len), __FILE__, __LINE__, __PRETTY_FUNCTION__)
 A wrapper for calloc() More...
 
#define ast_calloc_cache(num, len)   _ast_calloc((num), (len), __FILE__, __LINE__, __PRETTY_FUNCTION__)
 A wrapper for calloc() for use in cache pools. More...
 
#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_FLAGS_ALL   UINT_MAX
 
#define ast_free   free
 free() wrapper More...
 
#define ast_free_ptr   ast_free
 
#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_malloc(len)   _ast_malloc((len), __FILE__, __LINE__, __PRETTY_FUNCTION__)
 A wrapper for malloc() 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_realloc(p, len)   _ast_realloc((p), (len), __FILE__, __LINE__, __PRETTY_FUNCTION__)
 A wrapper for realloc() 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_STACKSIZE   (((sizeof(void *) * 8 * 8) - 16) * 1024)
 
#define ast_std_calloc   calloc
 
#define ast_std_free   free
 
#define ast_std_malloc   malloc
 
#define ast_std_realloc   realloc
 
#define ast_strdup(str)   _ast_strdup((str), __FILE__, __LINE__, __PRETTY_FUNCTION__)
 A wrapper for strdup() More...
 
#define ast_strdupa(s)
 duplicate a string in memory from the stack More...
 
#define ast_strndup(str, len)   _ast_strndup((str), (len), __FILE__, __LINE__, __PRETTY_FUNCTION__)
 A wrapper for strndup() More...
 
#define ast_test_flag(p, flag)
 
#define ast_test_flag64(p, flag)
 
#define ast_test_flag_nonstd(p, flag)   ((p)->flags & (flag))
 
#define ast_vasprintf(ret, fmt, ap)   _ast_vasprintf((ret), __FILE__, __LINE__, __PRETTY_FUNCTION__, (fmt), (ap))
 A wrapper for vasprintf() More...
 
#define localtime_r   __dont_use_localtime_r_use_ast_localtime_instead__
 
#define MALLOC_FAILURE_MSG   ast_log(LOG_ERROR, "Memory Allocation Failure in function %s at line %d of %s\n", func, lineno, file);
 
#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...
 

Functions

int _ast_asprintf (char **ret, const char *file, int lineno, const char *func, const char *fmt,...)
 
void * _ast_calloc (size_t num, size_t len, const char *file, int lineno, const char *func)
 
void * _ast_malloc (size_t len, const char *file, int lineno, const char *func)
 
void * _ast_realloc (void *p, size_t len, const char *file, int lineno, const char *func)
 
char * _ast_strdup (const char *str, const char *file, int lineno, const char *func)
 
char * _ast_strndup (const char *str, size_t len, const char *file, int lineno, const char *func)
 
int _ast_vasprintf (char **ret, const char *file, int lineno, const char *func, const char *fmt, va_list ap)
 
int ast_base64decode (unsigned char *dst, const char *src, int max)
 Decode data from base64. 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...
 
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...
 
void 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...
 
char * ast_eid_to_str (char *s, int maxlen, struct ast_eid *eid)
 
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...
 
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_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...
 
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_multiply (short *input, short *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...
 
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)
 Decode URI, URN, URL (overwrite string) More...
 
char * ast_uri_encode (const char *string, char *outbuf, int buflen, int do_special_char)
 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...
 

Detailed Description

Utility functions.

Definition in file utils.h.

Macro Definition Documentation

#define ARRAY_LEN (   a)    (size_t) (sizeof(a) / sizeof(0[a]))

Definition at line 699 of file utils.h.

#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 780 of file utils.h.

Referenced by __ast_string_field_ptr_build_va().

#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 760 of file utils.h.

Referenced by __ast_string_field_alloc_space(), and __ast_string_field_ptr_build_va().

#define ast_alloca (   size)    __builtin_alloca(size)

call __builtin_alloca to ensure we get gcc builtin semantics

Parameters
sizeThe size of the buffer we want allocated

This macro will attempt to allocate memory from the stack. If it fails you won't get a NULL returned, but a SEGFAULT if you're lucky.

Definition at line 653 of file utils.h.

Referenced by __ast_verbose_ap(), _while_exec(), ael2_semantic_check(), aji_start_sasl(), alsa_card_init(), append_mailbox(), ast_control_streamfile(), ast_dsp_process(), ast_event_append_ie_str(), ast_event_check_subscriber(), ast_event_new(), ast_fileexists(), ast_lock_path_flock(), ast_lock_path_lockfile(), ast_mkdir(), ast_openstream_full(), ast_openvstream(), ast_pthread_create_detached_stack(), ast_pthread_create_stack(), ast_remotecontrol(), ast_say_counted_adjective(), ast_say_counted_noun(), ast_unlock_path_flock(), ast_unlock_path_lockfile(), ast_waitfor_nandfds(), ast_writefile(), astman_append_json(), builtin_automixmonitor(), builtin_automonitor(), callerid_feed(), callerid_feed_jp(), CB_ADD_LEN(), config_module(), cpeid_exec(), create_addr_from_peer(), cut_internal(), decode_frame(), dictate_exec(), dundi_decrypt(), dundi_encrypt(), dundi_precache_internal(), encrypt_frame(), feature_request_and_dial(), festival_exec(), find_table(), func_mchan_read(), function_fieldnum_helper(), function_fieldqty_helper(), handle_cli_config_reload(), handle_command_response(), handle_exec(), import_helper(), inprocess_count(), listfilter(), local_attended_transfer(), lua_get_variable(), lua_get_variable_value(), lua_read_extensions_file(), masquerade_colp_transfer(), mixmonitor_exec(), my_ast_get_channel_by_name_locked(), pbx_builtin_importvar(), pbx_load_module(), pbx_substitute_variables_helper_full(), queue_file(), realtime_exec(), replace(), shared_read(), shared_write(), shift_pop(), sip_addheader(), sms_generate(), socket_process(), sort_internal(), state_notify_build_xml(), static_callback(), try_firmware(), unshift_push(), vm_change_password(), vm_delete(), and vm_play_folder_name_gr().

#define ast_asprintf (   ret,
  fmt,
  ... 
)    _ast_asprintf((ret), __FILE__, __LINE__, __PRETTY_FUNCTION__, fmt, __VA_ARGS__)

A wrapper for asprintf()

ast_asprintf() is a wrapper for asprintf() that will generate an Asterisk log message in the case that the allocation fails.

The arguments and return value are the same as asprintf()

Definition at line 614 of file utils.h.

#define AST_BACKGROUND_STACKSIZE   AST_STACKSIZE

Definition at line 404 of file utils.h.

#define ast_calloc (   num,
  len 
)    _ast_calloc((num), (len), __FILE__, __LINE__, __PRETTY_FUNCTION__)

A wrapper for calloc()

ast_calloc() is a wrapper for calloc() that will generate an Asterisk log message in the case that the allocation fails.

The arguments and return value are the same as calloc()

Definition at line 497 of file utils.h.

#define ast_calloc_cache (   num,
  len 
)    _ast_calloc((num), (len), __FILE__, __LINE__, __PRETTY_FUNCTION__)

A wrapper for calloc() for use in cache pools.

ast_calloc_cache() is a wrapper for calloc() that will generate an Asterisk log message in the case that the allocation fails. When memory debugging is in use, the memory allocated by this function will be marked as 'cache' so it can be distinguished from normal memory allocations.

The arguments and return value are the same as calloc()

Definition at line 522 of file utils.h.

#define ast_clear_flag (   p,
  flag 
)

Definition at line 77 of file utils.h.

Referenced by __analog_ss_thread(), __ast_pbx_run(), __ast_read(), __do_deliver(), __transmit_response(), action_redirect(), aji_create_client(), aji_filter_roster(), aji_load_config(), analog_ss_thread(), ast_audiohook_set_mute(), ast_autoservice_stop(), ast_bridge_call(), ast_cdr_reset(), ast_cdr_specialized_reset(), ast_channel_bridge(), ast_channel_undefer_dtmf(), ast_do_masquerade(), ast_generic_bridge(), ast_jb_destroy(), ast_jb_put(), ast_rtp_raw_write(), ast_sendtext(), ast_settimeout_full(), ast_speech_start(), ast_tls_read_conf(), ast_translate(), ast_waitfor_nandfds(), ast_waitfordigit_full(), ast_write(), bridge_channel_feature(), bridge_p2p_rtp_write(), builtin_atxfer(), change_hold_state(), change_spy_mode(), channel_spy(), chanspy_exec(), check_goto_on_transfer(), check_pendings(), common_exec(), config_function_read(), config_text_file_load(), dahdi_read(), dahdiscan_exec(), deactivate_generator_nolock(), dial_exec_full(), dictate_exec(), disa_exec(), dundi_lookup_local(), extenspy_exec(), forward_message(), handle_command_response(), handle_common_options(), handle_exec(), handle_request_bye(), handle_request_invite(), handle_request_refer(), handle_response(), handle_response_notify(), handle_speechrecognize(), handle_t38_options(), handle_verbose(), init_acf_query(), initialize_udptl(), linear_alloc(), load_config(), load_module(), load_moh_classes(), local_ast_moh_stop(), local_attended_transfer(), local_hangup(), main(), manage_parked_call(), manager_optimize_away(), odbc_load_module(), park_call_full(), parkandannounce_exec(), parse_options(), phone_read(), playtones_alloc(), process_sdp(), register_verify(), reload_config(), reset_transaction(), set_config(), set_config_flags(), setup_dahdi_int(), sip_call(), sip_dtmfmode(), sip_hangup(), sip_reload(), sip_set_rtp_peer(), socket_process(), speech_background(), try_calling(), update_call_counter(), update_connectedline(), and waitstream_core().

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

Definition at line 180 of file utils.h.

Referenced by build_transactions(), cache_lookup_internal(), dundi_lookup_local(), dundi_prop_precache(), and handle_command_response().

#define ast_copy_flags64 (   dest,
  src,
  flagz 
)
#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.

#define ast_free   free

free() wrapper

ast_free_ptr should be used when a function pointer for free() needs to be passed as the argument to a function. Otherwise, astmm will cause seg faults.

Definition at line 461 of file utils.h.

#define ast_free_ptr   ast_free

Definition at line 462 of file utils.h.

#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 803 of file utils.h.

Referenced by __ast_string_field_alloc_space(), and __ast_string_field_ptr_build_va().

#define ast_malloc (   len)    _ast_malloc((len), __FILE__, __LINE__, __PRETTY_FUNCTION__)

A wrapper for malloc()

ast_malloc() is a wrapper for malloc() that will generate an Asterisk log message in the case that the allocation fails.

The argument and return value are the same as malloc()

Definition at line 474 of file utils.h.

#define ast_pthread_create (   a,
  b,
  c,
 
)
Value:
0, __FILE__, __FUNCTION__, __LINE__, #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: utils.c:1182

Definition at line 418 of file utils.h.

Referenced by accept_thread(), ast_bridge_impart(), ast_dial_run(), ast_features_init(), ast_taskprocessor_get(), bridge_call_thread_launch(), bridge_channel_join(), build_calendar(), handle_callforward_button(), handle_enbloc_call_message(), handle_offhook_message(), handle_soft_key_event_message(), handle_stimulus_message(), handle_transfer_button(), HandleCallOutgoing(), init_logger(), load_module(), multiplexed_add_or_remove(), restart_monitor(), setup_dahdi_int(), sla_load_config(), and start_poll_thread().

#define ast_pthread_create_background (   a,
  b,
  c,
 
)
Value:
__FILE__, __FUNCTION__, __LINE__, #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: utils.c:1182
#define AST_BACKGROUND_STACKSIZE
Definition: utils.h:404

Definition at line 426 of file utils.h.

Referenced by add_notify(), aji_reload(), ast_autoservice_start(), ast_device_state_engine_init(), ast_enable_distributed_devstate(), ast_makesocket(), ast_safe_fork(), ast_sched_thread_create(), ast_tcptls_server_start(), astdb_init(), calendar_event_notify(), conf_run(), config_load(), do_monitor(), do_reload(), find_idle_thread(), init_app_class(), init_timing_thread(), load_module(), local_ast_moh_start(), pri_dchannel(), restart_monitor(), restart_pktc_thread(), sig_pri_start_pri(), smdi_load(), start_network_thread(), and start_stream().

#define ast_pthread_create_detached (   a,
  b,
  c,
 
)
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: utils.c:1230

Definition at line 422 of file utils.h.

Referenced by __analog_handle_event(), action_originate(), analog_handle_init_event(), analog_ss_thread_start(), ast_pbx_outgoing_app(), ast_pbx_outgoing_exten(), ast_pbx_start(), dahdi_handle_event(), do_monitor(), dundi_answer_entity(), dundi_answer_query(), dundi_prop_precache(), handle_hd_hf(), handle_init_event(), launch_service(), main(), mwi_thread(), pri_dchannel(), and spawn_dp_lookup().

#define ast_pthread_create_detached_background (   a,
  b,
  c,
 
)
Value:
__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: utils.c:1230
#define AST_BACKGROUND_STACKSIZE
Definition: utils.h:404

Definition at line 431 of file utils.h.

Referenced by ast_cdr_submit_batch(), ast_tcptls_server_root(), cc_generic_agent_recall(), conf_run(), iax_park(), launch_monitor_thread(), listener(), load_module(), meetme_menu_admin_extended(), sip_park(), sip_pickup(), sip_prepare_socket(), sla_handle_dial_state_event(), and sla_station_exec().

#define ast_realloc (   p,
  len 
)    _ast_realloc((p), (len), __FILE__, __LINE__, __PRETTY_FUNCTION__)

A wrapper for realloc()

ast_realloc() is a wrapper for realloc() that will generate an Asterisk log message in the case that the allocation fails.

The arguments and return value are the same as realloc()

Definition at line 533 of file utils.h.

#define ast_set2_flag64 (   p,
  value,
  flag 
)

Definition at line 151 of file utils.h.

Referenced by build_peer(), build_user(), check_access(), dial_exec_full(), and set_config().

#define ast_set2_flag_nonstd (   p,
  value,
  flag 
)

Definition at line 189 of file utils.h.

#define ast_set_flag (   p,
  flag 
)

Definition at line 70 of file utils.h.

Referenced by __analog_ss_thread(), __ast_pbx_run(), __ast_read(), __ast_request_and_dial(), __sip_subscribe_mwi_do(), _macro_exec(), action_redirect(), aji_create_client(), aji_load_config(), analog_ss_thread(), app_exec(), apply_peer(), ast_audiohook_set_mute(), ast_autoservice_start(), ast_bridge_call(), ast_bridge_features_set_flag(), ast_bridge_new(), ast_bridge_timelimit(), ast_call(), ast_cdr_detach(), ast_cdr_fork(), ast_cdr_merge(), ast_cdr_reset(), ast_cdr_specialized_reset(), ast_channel_bridge(), ast_channel_defer_dtmf(), ast_do_masquerade(), ast_do_pickup(), ast_generic_bridge(), ast_hangup(), ast_jb_do_usecheck(), ast_jb_put(), ast_rtp_change_source(), ast_rtp_local_bridge(), ast_rtp_raw_write(), ast_rtp_read(), ast_rtp_stop(), ast_rtp_update_source(), ast_settimeout_full(), ast_speech_change_state(), AST_TEST_DEFINE(), ast_tls_read_conf(), ast_waitfor_nandfds(), ast_waitfordigit_full(), asyncgoto_exec(), bridge_channel_feature(), bridge_exec(), bridge_p2p_rtp_write(), build_peer(), builtin_atxfer(), builtin_blindtransfer(), cb_extensionstate(), cc_generic_agent_init(), change_hold_state(), change_spy_mode(), channel_spy(), chanspy_exec(), check_bridge(), check_peer_ok(), check_user_full(), check_via(), common_exec(), create_addr_from_peer(), create_transaction(), dahdiscan_exec(), destroy_trans(), dial_exec_full(), dictate_exec(), directory_exec(), disa_exec(), do_register(), dundi_encrypt(), dundi_lookup_local(), dundi_send(), extenspy_exec(), find_peer(), find_user_realtime(), free_vm_users(), gosub_run(), handle_command_response(), handle_common_options(), handle_exec(), handle_gosub(), handle_invite_replaces(), handle_queue_reload(), handle_request_invite(), handle_request_refer(), handle_request_subscribe(), handle_response(), handle_response_invite(), handle_t38_options(), handle_verbose(), hangupcalls(), hanguptree(), init_acf_query(), init_app_class(), interpret_t38_parameters(), launch_monitor_thread(), leave_voicemail(), linear_alloc(), load_config(), load_moh_classes(), local_alloc(), local_ast_moh_start(), local_attended_transfer(), local_call(), local_hangup(), login_exec(), main(), manage_parked_call(), manager_queue_reload(), manager_sipnotify(), minivm_greet_exec(), new_outgoing(), nocdr_exec(), odbc_load_module(), park_call_full(), parked_call_exec(), parse_options(), playtones_alloc(), post_cdr(), process_applicationmap_line(), process_cn_rfc3389(), process_crypto(), process_sdp(), qualify_peer(), record_exec(), register_verify(), reload_config(), ring_entry(), set_bridge_features_on_config(), set_config_flags(), set_insecure_flags(), sip_answer(), sip_call(), sip_cc_agent_init(), sip_cc_agent_respond(), sip_cc_monitor_request_cc(), sip_cli_notify(), sip_dtmfmode(), sip_hangup(), sip_indicate(), sip_park_thread(), sip_poke_peer(), sip_reinvite_retry(), sip_send_mwi_to_peer(), sip_sendhtml(), sip_set_rtp_peer(), sip_set_udptl_peer(), sip_write(), socket_process(), start_spying(), tonepair_alloc(), transmit_publish(), transmit_register(), transmit_reinvite_with_sdp(), try_calling(), update_call_counter(), update_connectedline(), vm_execmain(), volume_write(), and waitstream_core().

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

Definition at line 176 of file utils.h.

Referenced by dundi_lookup_internal(), dundi_query_eid_internal(), and handle_command_response().

#define ast_set_flags_to (   p,
  flag,
  value 
)

Definition at line 104 of file utils.h.

#define ast_set_flags_to64 (   p,
  flag,
  value 
)

Definition at line 161 of file utils.h.

Referenced by build_peer(), build_user(), and set_config().

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

Definition at line 399 of file utils.h.

Referenced by ast_pthread_create_stack().

#define ast_std_calloc   calloc

Definition at line 451 of file utils.h.

#define ast_std_free   free

Definition at line 453 of file utils.h.

#define ast_std_malloc   malloc

Definition at line 450 of file utils.h.

#define ast_std_realloc   realloc

Definition at line 452 of file utils.h.

#define ast_strdup (   str)    _ast_strdup((str), __FILE__, __LINE__, __PRETTY_FUNCTION__)

A wrapper for strdup()

ast_strdup() is a wrapper for strdup() that will generate an Asterisk log message in the case that the allocation fails.

ast_strdup(), unlike strdup(), can safely accept a NULL argument. If a NULL argument is provided, ast_strdup will return NULL without generating any kind of error log message.

The argument and return value are the same as strdup()

Definition at line 560 of file utils.h.

#define ast_strdupa (   s)

duplicate a string in memory from the stack

Parameters
sThe string to duplicate

This macro will duplicate the given string. It returns a pointer to stack allocated memory for the new string.

Definition at line 663 of file utils.h.

Referenced by __ast_channel_alloc_ap(), __ast_play_and_record(), __dahdi_exception(), _ast_device_state(), _build_port_config(), _macro_exec(), _parse(), _sip_show_peers_one(), _while_exec(), acf_jabberreceive_read(), acf_meetme_info(), acf_odbc_write(), action_agents(), action_status(), actual_load_config(), add_agent(), add_peer_mailboxes(), add_realm_authentication(), add_redirect(), add_var(), admin_exec(), advanced_options(), aelsub_exec(), agent_hangup(), agi_exec_full(), agi_handle_command(), aji_join_exec(), aji_leave_exec(), aji_send_exec(), aji_sendgroup_exec(), aji_status_exec(), analog_exception(), answer_exec_enable(), app_exec(), append_mailbox(), append_mailbox_mapping(), append_var_and_value_to_filter(), apply_directmedia_ha(), apply_options(), aqm_exec(), array(), ast_aji_get_client(), ast_app_getdata(), ast_append_ha(), ast_async_goto(), ast_bridge_call(), ast_bridge_timelimit(), ast_build_timing(), ast_callerid_split(), ast_cdr_fork(), ast_cdr_setaccount(), ast_cdr_setpeeraccount(), ast_cel_report_event(), ast_channel_connected_line_macro(), ast_channel_redirecting_macro(), ast_channel_set_linkgroup(), ast_data_iterator_init(), ast_do_pickup(), ast_eivr_senddtmf(), ast_eivr_setvariable(), ast_el_add_history(), ast_event_append_ie_str(), ast_event_sub_append_ie_str(), ast_filehelper(), ast_format_str_reduce(), ast_func_read(), ast_func_read2(), ast_func_write(), ast_get_group(), ast_masq_park_call(), ast_masq_park_call_exten(), ast_mkdir(), ast_monitor_change_fname(), ast_monitor_start(), ast_netsock_bind(), ast_ouraddrfor(), ast_park_call_exten(), ast_parse_allow_disallow(), ast_parse_arg(), ast_playtones_start(), ast_register_file_version(), ast_rtp_read(), ast_sockaddr_parse(), ast_sockaddr_resolve(), ast_str_retrieve_variable(), ast_utils_which(), ast_writefile(), asyncgoto_exec(), auth_exec(), authenticate_reply(), authenticate_verify(), background_detect_exec(), bridge_exec(), bridge_play_sounds(), build_channels(), build_gateway(), build_mapping(), build_peer(), build_route(), build_user(), builtin_atxfer(), builtin_automixmonitor(), builtin_automonitor(), cache_get_callno_locked(), callerid_read(), callerid_write(), celgenuserevent_exec(), chanavail_exec(), change_callid_pvt(), channel_admin_exec(), channel_spy(), chanspy_exec(), check_access(), check_blacklist(), check_day(), check_dow(), check_goto_on_transfer(), check_month(), check_peer_ok(), check_switch_expr(), check_timerange(), check_user_full(), cli_odbc_read(), cli_odbc_write(), complete_meetmecmd_list(), complete_meetmecmd_mute_kick(), conf_exec(), conf_run(), conf_start_moh(), confbridge_exec(), config_function_read(), config_line(), config_module(), connectedline_read(), connectedline_write(), controlplayback_exec(), count_exec(), create_addr(), create_addr_from_peer(), create_dynamic_parkinglot(), create_followme_number(), create_queue_member(), create_vmaccount(), cut_internal(), dahdi_accept_r2_call_exec(), dahdi_send_callrerouting_facility_exec(), dahdiras_exec(), dahdiscan_exec(), data_filter_add_nodes(), data_filter_alloc(), data_filter_generate(), data_provider_create(), data_provider_release(), data_result_generate(), data_result_get_node(), data_search_create(), data_search_generate(), data_search_get_node(), decrypt_frame(), del_exec(), deltree_exec(), determine_starting_point(), dial_exec_full(), dial_trunk(), dialgroup_refreshdb(), dialgroup_write(), dictate_exec(), directory_exec(), disa_exec(), dnsmgr_refresh(), do_bridge_masquerade(), do_immediate_setup(), do_notify(), do_say(), dundi_query_read(), dundi_result_read(), dundifunc_read(), enum_query_read(), enum_result_read(), ewscal_write_event(), exec_exec(), execif_exec(), expand_gosub_args(), extenspy_exec(), feature_check(), feature_interpret(), festival_exec(), fileexists_core(), find_conf_realtime(), find_generic_monitor_instance_list(), find_gtalk(), find_sdp(), find_table(), find_table_cb(), forkcdr_exec(), function_agent(), function_iaxpeer(), function_realtime_store(), get_cid_name(), get_destination(), get_refer_info(), gosub_exec(), gosub_run(), gosubif_exec(), gtalk_action(), gtalk_alloc(), gtalk_create_candidates(), gtalk_invite(), gtalk_request(), gtalk_update_externip(), handle_call_forward(), handle_cli_check_permissions(), handle_cli_dialplan_add_extension(), handle_cli_file_convert(), handle_common_options(), handle_debug_dialplan(), handle_gosub(), handle_mfcr2_set_debug(), handle_mgcp_audit_endpoint(), handle_options(), handle_request_invite(), handle_request_notify(), handle_request_refer(), handle_response(), handle_show_dialplan(), handle_t38_options(), handle_verbose(), has_voicemail(), iax2_call(), iax2_devicestate(), iax2_prov_app(), iax2_request(), iconv_read(), init_acf_query(), init_jack_data(), insert_penaltychange(), is_prefix(), is_valid_dtmf(), isAnsweringMachine(), isexten_function_read(), ivr_dispatch(), jingle_request(), launch_ha_netscript(), launch_monitor_thread(), launch_netscript(), leave_voicemail(), load_channelvars(), load_config(), load_dynamic_module(), local_call(), local_devicestate(), log_exec(), logger_print_normal(), login_exec(), lua_get_variable_value(), lua_pbx_exec(), lua_set_variable_value(), macroif_exec(), main(), make_components(), make_email_file(), man_do_variable_value(), manage_parked_call(), match_ie_val(), match_sub_ie_val_to_event(), meetmemute(), metermaidstate(), mgcp_devicestate(), minivm_accmess_exec(), minivm_account_func_read(), minivm_counter_func_read(), minivm_counter_func_write(), minivm_greet_exec(), minivm_mwi_exec(), minivm_notify_exec(), minivm_record_exec(), misdn_call(), misdn_check_l2l1(), misdn_facility_exec(), misdn_request(), misdn_set_opt_exec(), mixmonitor_exec(), mkintf(), moh_handle_digit(), monitor_dial(), multicast_rtp_request(), my_pri_make_cc_dialstring(), notify_message(), notify_new_message(), odbc_log(), on_dns_update_mwi(), on_dns_update_peer(), on_dns_update_registry(), orig_app(), orig_exten(), originate_exec(), ospauth_exec(), ospfinished_exec(), osplookup_exec(), ospnext_exec(), oss_call(), oss_request(), page_exec(), park_call_exec(), park_space_reserve(), parkandannounce_exec(), parked_call_exec(), parse_allowed_methods(), parse_apps(), parse_cookies(), parse_empty_options(), parse_events(), parse_register_contact(), parse_session_expires(), parse_sip_options(), parse_uri_full(), party_id_write(), party_name_write(), party_number_write(), pbx_builtin_answer(), pbx_builtin_background(), pbx_builtin_execiftime(), pbx_builtin_gotoif(), pbx_builtin_gotoiftime(), pbx_builtin_importvar(), pbx_builtin_pushvar_helper(), pbx_builtin_resetcdr(), pbx_builtin_saydate(), pbx_builtin_saytime(), pbx_builtin_setvar(), pbx_builtin_setvar_helper(), pbx_builtin_setvar_multiple(), pbx_builtin_waitexten(), pbx_extension_helper(), pbx_find_extension(), pbx_parseable_goto(), peer_set_srcaddr(), pickup_exec(), pickupchan_exec(), play_message(), play_moh_exec(), playback_exec(), pqm_exec(), prep_email_sub_vars(), privacy_exec(), process_applicationmap_line(), process_dahdi(), process_echocancel(), process_sdp(), process_sdp_a_image(), process_sdp_o(), proxy_from_config(), ql_exec(), queue_exec(), queue_mwi_event(), queue_set_param(), rcvfax_exec(), read_exec(), readexten_exec(), readfile_exec(), realtime_common(), realtime_exec(), realtime_multi_curl(), realtime_multi_ldap(), realtime_multi_odbc(), realtime_multi_pgsql(), receivefax_exec(), record_exec(), redirecting_read(), redirecting_write(), register_verify(), registry_authrequest(), reload_config(), reload_followme(), reload_single_member(), resource_name_match(), retrydial_exec(), rqm_exec(), rtcp_do_debug_ip(), rtp_do_debug_ip(), saycountedadj_exec(), saycountednoun_exec(), sayunixtime_exec(), sdp_crypto_process(), senddtmf_exec(), sendfax_exec(), sendmail(), sendurl_exec(), set_config_flags(), set_hangup_source_and_cause(), setup_privacy_args(), setup_stunaddr(), sig_pri_extract_called_num_subaddr(), sig_pri_msn_match(), sip_acf_channel_read(), sip_devicestate(), sip_get_cc_information(), sip_new(), sip_queue_hangup_cause(), sip_send_mwi_to_peer(), sip_show_settings(), sip_sipredirect(), sip_uri_cmp(), sip_uri_headers_cmp(), sip_uri_params_cmp(), skel_exec(), skinny_devicestate(), sla_add_trunk_to_station(), sla_check_device(), sla_queue_event_conf(), sla_ring_station(), sla_state(), sla_station_exec(), sla_trunk_exec(), smdi_msg_read(), smdi_msg_retrieve_read(), sms_exec(), sndfax_exec(), socket_process(), softhangup_exec(), sort_internal(), speech_background(), speech_load(), srv_result_read(), stackpeek_read(), start_moh_exec(), start_monitor_action(), start_monitor_exec(), state_notify_build_xml(), stun_monitor_request(), timezone_add(), transfer_exec(), transmit_invite(), try_calling(), tryexec_exec(), unistim_send_mwi_to_peer(), update_bridge_vars(), update_common_options(), update_registry(), upqm_exec(), userevent_exec(), verbose_exec(), vm_box_exists(), vm_check_password_shell(), vm_exec(), vm_execmain(), vmauthenticate(), vmsayname_exec(), wait_for_answer(), wait_for_winner(), waitstream_core(), xfer_park_call_helper(), xmldoc_get_syntax_fun(), and zapateller_exec().

#define ast_strndup (   str,
  len 
)    _ast_strndup((str), (len), __FILE__, __LINE__, __PRETTY_FUNCTION__)

A wrapper for strndup()

ast_strndup() is a wrapper for strndup() that will generate an Asterisk log message in the case that the allocation fails.

ast_strndup(), unlike strndup(), can safely accept a NULL argument for the string to duplicate. If a NULL argument is provided, ast_strdup will return NULL without generating any kind of error log message.

The arguments and return value are the same as strndup()

Definition at line 589 of file utils.h.

#define ast_test_flag (   p,
  flag 
)

Definition at line 63 of file utils.h.

Referenced by __ast_channel_masquerade(), __ast_pbx_run(), __ast_queue_frame(), __ast_read(), __sip_destroy(), __ssl_setup(), __transmit_response(), _ast_odbc_request_obj2(), _macro_exec(), _sip_show_peer(), _sip_show_peers_one(), acf_odbc_read(), action_login(), add_agent(), add_codec_to_sdp(), add_rpid(), add_sdp(), aji_build_publish_skeleton(), aji_cli_purge_pubsub_nodes(), aji_create_client(), aji_handle_pubsub_error(), aji_handle_subscribe(), aji_pruneregister(), aji_publish_device_state(), aji_pubsub_subscribe(), app_exec(), ast_audiohook_write_frame(), ast_autoservice_start(), ast_bridge_call(), ast_bridge_end_dtmf(), ast_bridge_merge(), ast_call(), ast_can_pickup(), ast_cdr_answer(), ast_cdr_appenduserfield(), ast_cdr_busy(), ast_cdr_end(), ast_cdr_failed(), ast_cdr_fork(), ast_cdr_init(), ast_cdr_merge(), ast_cdr_noanswer(), ast_cdr_reset(), ast_cdr_setaccount(), ast_cdr_setamaflags(), ast_cdr_setanswer(), ast_cdr_setapp(), ast_cdr_setcid(), ast_cdr_setdestchan(), ast_cdr_setdisposition(), ast_cdr_setpeeraccount(), ast_cdr_setuserfield(), ast_cdr_setvar(), ast_cdr_specialized_reset(), ast_cdr_start(), ast_cdr_update(), ast_channel_bridge(), ast_channel_defer_dtmf(), ast_config_internal_load(), ast_do_masquerade(), ast_explicit_goto(), ast_frisolate(), ast_generic_bridge(), ast_hangup(), ast_indicate_data(), ast_jb_destroy(), ast_jb_do_usecheck(), ast_jb_empty_and_reset(), ast_jb_get_and_deliver(), ast_jb_get_when_to_wakeup(), ast_jb_put(), ast_moh_files_next(), ast_pbx_run_args(), ast_pbx_start(), ast_quiet_chan(), ast_raw_answer(), ast_readstring_full(), ast_rtp_raw_write(), ast_sendtext(), ast_settimeout_full(), ast_softhangup_nolock(), ast_streamfile(), AST_TEST_DEFINE(), ast_transfer(), ast_translate(), ast_waitfordigit_full(), ast_write(), auth_exec(), authenticate_verify(), bridge_channel_join(), bridge_check_dissolve(), bridge_exec(), bridge_p2p_rtp_write(), build_peer(), build_radius_record(), build_via(), builtin_atxfer(), call_forward_inherit(), callback_dialoptions(), cb_extensionstate(), cdr_read(), cdr_write(), change_hold_state(), channel_data_add_flags(), channel_spy(), chanspy_exec(), check_bridge(), check_peer_ok(), check_pendings(), check_post(), check_rtp_timeout(), check_user_full(), close_mailbox(), common_exec(), complete_sip_peer(), complete_sip_registered_peer(), confbridge_exec(), config_text_file_load(), connectedline_write(), controlplayback_exec(), copy_via_headers(), create_addr_from_peer(), create_jb(), destroy_trans(), dial_exec_full(), dialog_initialize_rtp(), dictate_exec(), directory_exec(), disa_exec(), display_nat_warning(), do_directory(), do_setnat(), dtmf_audiohook_write_list(), dundi_encrypt(), dundi_exec(), dundi_helper(), dundi_lookup_local(), dundi_lookup_thread(), dundi_precache_thread(), dundi_query_read(), dundi_query_thread(), dundi_rexmit(), dundi_send(), dundifunc_read(), eivr_comm(), enable_dsp_detect(), execute_cb(), expire_register(), extenspy_exec(), feature_exec_app(), feature_interpret_helper(), find_cache(), find_or_create(), find_user(), find_user_realtime(), forkcdr_exec(), forward_message(), free_user(), function_sippeer(), get_destination(), get_insecure_variable_from_config(), get_insecure_variable_from_sipregs(), get_rpid(), get_sip_pvt_byid_locked(), gosub_exec(), gosub_run(), handle_cli_moh_show_classes(), handle_cli_wait_fullybooted(), handle_command_response(), handle_exec(), handle_frame(), handle_gosub(), handle_incoming(), handle_minivm_show_settings(), handle_options(), handle_request_bye(), handle_request_cancel(), handle_request_info(), handle_request_invite(), handle_request_refer(), handle_request_subscribe(), handle_response(), handle_response_invite(), handle_response_notify(), handle_show_settings(), handle_showchan(), handle_skinny_show_settings(), handle_speechrecognize(), handle_tcptls_connection(), hint_read(), iax2_write(), initialize_udptl(), initreqprep(), interpret_t38_parameters(), is_state_change_valid(), join_conference_bridge(), leave_conference_bridge(), leave_voicemail(), load_dynamic_module(), load_resource(), local_alloc(), local_ast_moh_start(), local_bridgedchannel(), local_call(), local_devicestate(), local_hangup(), local_indicate(), local_write(), main(), make_email_file(), manager_list_voicemail_users(), masq_park_call(), match_req_to_dialog(), menu_callback(), minivm_accmess_exec(), minivm_account_func_read(), minivm_greet_exec(), minivm_notify_exec(), minivm_record_exec(), mixmonitor_exec(), mixmonitor_thread(), mod_load_cmp(), moh_files_alloc(), moh_scan_files(), multicast_rtp_write(), notify_new_message(), odbc_load_module(), page_exec(), park_call_exec(), park_call_full(), park_space_reserve(), parse_moved_contact(), parse_register_contact(), pbx_builtin_background(), pbx_builtin_waitexten(), peer_ipcmp_cb(), pick_unlocked_cdr(), play_mailbox_owner(), play_message(), play_record_review(), post_cdr(), post_join_marked(), post_join_unmarked(), precache_transactions(), process_cn_rfc3389(), process_crypto(), process_sdp(), process_sdp_a_audio(), process_sdp_o(), process_text_line(), read_exec(), readexten_exec(), realtime_peer(), realtime_switch_common(), receivefax_exec(), record_exec(), redirecting_write(), reload_config(), reload_handler(), reload_queues(), reload_single_queue(), remote_bridge_loop(), remove_from_queue(), reqprep(), respprep(), retrans_pkt(), retrydial_exec(), return_exec(), search_directory_sub(), select_entry(), select_item_pause(), send_request(), sendfax_exec(), sendmail(), sendurl_exec(), serialize_showchan(), set_address_from_contact(), set_config_flags(), set_pvt_allowed_methods(), set_t38_capabilities(), should_skip_dtmf(), show_channels_cb(), sig_pri_call(), sip_alloc(), sip_answer(), sip_call(), sip_cc_agent_destructor(), sip_destroy_peer(), sip_dtmfmode(), sip_fixup(), sip_get_rtp_peer(), sip_get_trtp_peer(), sip_get_udptl_peer(), sip_get_vrtp_peer(), sip_hangup(), sip_indicate(), sip_nat_mode(), sip_new(), sip_prune_realtime(), sip_queryoption(), sip_read(), sip_real_dst(), sip_rtp_read(), sip_send_mwi_to_peer(), sip_senddigit_begin(), sip_senddigit_end(), sip_sendhtml(), sip_set_rtp_peer(), sip_set_udptl_peer(), sip_setoption(), sip_show_channel(), sip_show_settings(), sip_show_users(), sip_write(), sla_trunk_exec(), smdi_msg_find(), sms_exec(), socket_process(), socket_process_meta(), softhangup_exec(), spawn_mp3(), speech_background(), speech_read(), spy_generate(), start_spying(), startmon(), transmit_info_with_digit(), transmit_invite(), transmit_notify_with_mwi(), transmit_refer(), transmit_reinvite_with_sdp(), transmit_request_with_auth(), transmit_response_with_sdp(), transmit_state_notify(), try_calling(), update_call_counter(), update_connectedline(), update_peer(), update_redirecting(), update_registry(), vm_exec(), vm_execmain(), vm_instructions_en(), vm_intro(), vm_newuser(), volume_callback(), wait_for_winner(), waitstream_core(), and xfer_park_call_helper().

#define ast_test_flag_nonstd (   p,
  flag 
)    ((p)->flags & (flag))
#define ast_vasprintf (   ret,
  fmt,
  ap 
)    _ast_vasprintf((ret), __FILE__, __LINE__, __PRETTY_FUNCTION__, (fmt), (ap))

A wrapper for vasprintf()

ast_vasprintf() is a wrapper for vasprintf() that will generate an Asterisk log message in the case that the allocation fails.

The arguments and return value are the same as vasprintf()

Definition at line 628 of file utils.h.

#define localtime_r   __dont_use_localtime_r_use_ast_localtime_instead__

Definition at line 359 of file utils.h.

#define MALLOC_FAILURE_MSG   ast_log(LOG_ERROR, "Memory Allocation Failure in function %s at line %d of %s\n", func, lineno, file);

Definition at line 464 of file utils.h.

Referenced by _ast_asprintf().

#define MAX (   a,
 
)    ({ typeof(a) __a = (a); typeof(b) __b = (b); ((__a < __b) ? __b : __a);})
#define MIN (   a,
 
)    ({ typeof(a) __a = (a); typeof(b) __b = (b); ((__a > __b) ? __b : __a);})
#define RAII_VAR (   vartype,
  varname,
  initval,
  dtor 
)
Value:
/* Prototype needed due to http://gcc.gnu.org/bugzilla/show_bug.cgi?id=36774 */ \
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:125

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

Resource Allocation Is Initialization (RAII) variable declaration.

Since
1.8.24.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);
* ...
* }
*
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);
* }
*

Definition at line 915 of file utils.h.

Referenced by check_user_full(), config_pgsql(), destroy_pgsql(), dial_trunk(), find_table(), get_destination(), realtime_multi_pgsql(), realtime_pgsql(), replace(), run_station(), sla_add_trunk_to_station(), sla_build_station(), sla_build_trunk(), sla_check_station_delay(), sla_handle_dial_state_event(), sla_state(), sla_station_exec(), sla_trunk_exec(), store_pgsql(), update2_pgsql(), and update_pgsql().

Function Documentation

int _ast_asprintf ( char **  ret,
const char *  file,
int  lineno,
const char *  func,
const char *  fmt,
  ... 
)

Definition at line 2331 of file utils.c.

References MALLOC_FAILURE_MSG, and vasprintf().

2332 {
2333  int res;
2334  va_list ap;
2335 
2336  va_start(ap, fmt);
2337  if ((res = vasprintf(ret, fmt, ap)) == -1) {
2339  }
2340  va_end(ap);
2341 
2342  return res;
2343 }
int vasprintf(char **strp, const char *fmt, va_list ap)
#define MALLOC_FAILURE_MSG
Definition: utils.h:464
void * _ast_calloc ( size_t  num,
size_t  len,
const char *  file,
int  lineno,
const char *  func 
)
inline

Definition at line 510 of file utils.h.

538 {
void * _ast_malloc ( size_t  len,
const char *  file,
int  lineno,
const char *  func 
)
inline

Definition at line 487 of file utils.h.

502 {
void * _ast_realloc ( void *  p,
size_t  len,
const char *  file,
int  lineno,
const char *  func 
)
inline

Definition at line 546 of file utils.h.

565 {
char * _ast_strdup ( const char *  str,
const char *  file,
int  lineno,
const char *  func 
)
inline

Definition at line 575 of file utils.h.

594 {
char * _ast_strndup ( const char *  str,
size_t  len,
const char *  file,
int  lineno,
const char *  func 
)
inline

Definition at line 604 of file utils.h.

634 {
int _ast_vasprintf ( char **  ret,
const char *  file,
int  lineno,
const char *  func,
const char *  fmt,
va_list  ap 
)
inline

Definition at line 642 of file utils.h.

665 { \
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 279 of file utils.c.

Referenced by aes_helper(), ast_check_signature(), base64_helper(), osp_validate_token(), sdp_crypto_process(), and sdp_crypto_setup().

280 {
281  int cnt = 0;
282  unsigned int byte = 0;
283  unsigned int bits = 0;
284  int incnt = 0;
285  while(*src && *src != '=' && (cnt < max)) {
286  /* Shift in 6 bits of input */
287  byte <<= 6;
288  byte |= (b2a[(int)(*src)]) & 0x3f;
289  bits += 6;
290  src++;
291  incnt++;
292  /* If we have at least 8 bits left over, take that character
293  off the top */
294  if (bits >= 8) {
295  bits -= 8;
296  *dst = (byte >> bits) & 0xff;
297  dst++;
298  cnt++;
299  }
300  }
301  /* Don't worry about left over bits, they're extra anyway */
302  return cnt;
303 }
static char b2a[256]
Definition: utils.c:79
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 357 of file utils.c.

References ast_base64encode_full().

Referenced by aes_helper(), aji_start_sasl(), ast_sign(), base64_helper(), build_secret(), osp_check_destination(), and sdp_crypto_setup().

358 {
359  return ast_base64encode_full(dst, src, srclen, max, 0);
360 }
int ast_base64encode_full(char *dst, const unsigned char *src, int srclen, int max, int linebreaks)
encode text to BASE64 coding
Definition: utils.c:306
int ast_base64encode_full ( char *  dst,
const unsigned char *  src,
int  srclen,
int  max,
int  linebreaks 
)

encode text to BASE64 coding

Definition at line 306 of file utils.c.

Referenced by ast_base64encode().

307 {
308  int cnt = 0;
309  int col = 0;
310  unsigned int byte = 0;
311  int bits = 0;
312  int cntin = 0;
313  /* Reserve space for null byte at end of string */
314  max--;
315  while ((cntin < srclen) && (cnt < max)) {
316  byte <<= 8;
317  byte |= *(src++);
318  bits += 8;
319  cntin++;
320  if ((bits == 24) && (cnt + 4 <= max)) {
321  *dst++ = base64[(byte >> 18) & 0x3f];
322  *dst++ = base64[(byte >> 12) & 0x3f];
323  *dst++ = base64[(byte >> 6) & 0x3f];
324  *dst++ = base64[byte & 0x3f];
325  cnt += 4;
326  col += 4;
327  bits = 0;
328  byte = 0;
329  }
330  if (linebreaks && (cnt < max) && (col == 64)) {
331  *dst++ = '\n';
332  cnt++;
333  col = 0;
334  }
335  }
336  if (bits && (cnt + 4 <= max)) {
337  /* Add one last character for the remaining bits,
338  padding the rest with 0 */
339  byte <<= 24 - bits;
340  *dst++ = base64[(byte >> 18) & 0x3f];
341  *dst++ = base64[(byte >> 12) & 0x3f];
342  if (bits == 16)
343  *dst++ = base64[(byte >> 6) & 0x3f];
344  else
345  *dst++ = '=';
346  *dst++ = '=';
347  cnt += 4;
348  }
349  if (linebreaks && (cnt < max)) {
350  *dst++ = '\n';
351  cnt++;
352  }
353  *dst = '\0';
354  return cnt;
355 }
static char base64[64]
Definition: utils.c:78
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

Definition at line 1369 of file utils.c.

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

Referenced by send_string().

1370 {
1371  struct timeval start = ast_tvnow();
1372  int n = 0;
1373  int elapsed = 0;
1374 
1375  while (len) {
1376  if (wait_for_output(fd, timeoutms - elapsed)) {
1377  /* poll returned a fatal error, so bail out immediately. */
1378  return -1;
1379  }
1380 
1381  /* Clear any errors from a previous write */
1382  clearerr(f);
1383 
1384  n = fwrite(src, 1, len, f);
1385 
1386  if (ferror(f) && errno != EINTR && errno != EAGAIN) {
1387  /* fatal error from fwrite() */
1388  if (!feof(f)) {
1389  /* Don't spam the logs if it was just that the connection is closed. */
1390  ast_log(LOG_ERROR, "fwrite() returned error: %s\n", strerror(errno));
1391  }
1392  n = -1;
1393  break;
1394  }
1395 
1396  /* Update for data already written to the socket */
1397  len -= n;
1398  src += n;
1399 
1400  elapsed = ast_tvdiff_ms(ast_tvnow(), start);
1401  if (elapsed >= timeoutms) {
1402  /* We've taken too long to write
1403  * This is only an error condition if we haven't finished writing. */
1404  n = len ? -1 : 0;
1405  break;
1406  }
1407  }
1408 
1409  errno = 0;
1410  while (fflush(f)) {
1411  if (errno == EAGAIN || errno == EINTR) {
1412  /* fflush() does not appear to reset errno if it flushes
1413  * and reaches EOF at the same time. It returns EOF with
1414  * the last seen value of errno, causing a possible loop.
1415  * Also usleep() to reduce CPU eating if it does loop */
1416  errno = 0;
1417  usleep(1);
1418  continue;
1419  }
1420  if (errno && !feof(f)) {
1421  /* Don't spam the logs if it was just that the connection is closed. */
1422  ast_log(LOG_ERROR, "fflush() returned error: %s\n", strerror(errno));
1423  }
1424  n = -1;
1425  break;
1426  }
1427 
1428  return n < 0 ? -1 : 0;
1429 }
struct timeval ast_tvnow(void)
Returns current timeval. Meant to replace calls to gettimeofday().
Definition: time.h:142
int64_t ast_tvdiff_ms(struct timeval end, struct timeval start)
Computes the difference (in milliseconds) between two struct timeval instances.
Definition: time.h:90
#define LOG_ERROR
Definition: logger.h:155
static int len(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t buflen)
void ast_log(int level, const char *file, int line, const char *function, const char *fmt,...)
Used for sending a log message This is the standard logger function. Probably the only way you will i...
Definition: logger.c:1207
int errno
static struct ast_format f[]
Definition: format_g726.c:181
static int wait_for_output(int fd, int timeoutms)
Definition: utils.c:1275
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 1328 of file utils.c.

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

Referenced by ast_agi_send(), and ast_cli().

1329 {
1330  struct timeval start = ast_tvnow();
1331  int res = 0;
1332  int elapsed = 0;
1333 
1334  while (len) {
1335  if (wait_for_output(fd, timeoutms - elapsed)) {
1336  return -1;
1337  }
1338 
1339  res = write(fd, s, len);
1340 
1341  if (res < 0 && errno != EAGAIN && errno != EINTR) {
1342  /* fatal error from write() */
1343  ast_log(LOG_ERROR, "write() returned error: %s\n", strerror(errno));
1344  return -1;
1345  }
1346 
1347  if (res < 0) {
1348  /* It was an acceptable error */
1349  res = 0;
1350  }
1351 
1352  /* Update how much data we have left to write */
1353  len -= res;
1354  s += res;
1355  res = 0;
1356 
1357  elapsed = ast_tvdiff_ms(ast_tvnow(), start);
1358  if (elapsed >= timeoutms) {
1359  /* We've taken too long to write
1360  * This is only an error condition if we haven't finished writing. */
1361  res = len ? -1 : 0;
1362  break;
1363  }
1364  }
1365 
1366  return res;
1367 }
struct timeval ast_tvnow(void)
Returns current timeval. Meant to replace calls to gettimeofday().
Definition: time.h:142
int64_t ast_tvdiff_ms(struct timeval end, struct timeval start)
Computes the difference (in milliseconds) between two struct timeval instances.
Definition: time.h:90
#define LOG_ERROR
Definition: logger.h:155
static int len(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t buflen)
void ast_log(int level, const char *file, int line, const char *function, const char *fmt,...)
Used for sending a log message This is the standard logger function. Probably the only way you will i...
Definition: logger.c:1207
int errno
static int wait_for_output(int fd, int timeoutms)
Definition: utils.c:1275
void 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 2382 of file utils.c.

2383 {
2384 #if defined(DO_CRASH)
2385  abort();
2386  /*
2387  * Just in case abort() doesn't work or something else super
2388  * silly, and for Qwell's amusement.
2389  */
2390  *((int *) 0) = 0;
2391 #endif /* defined(DO_CRASH) */
2392 }
int ast_eid_cmp ( const struct ast_eid eid1,
const struct ast_eid eid2 
)
char* ast_eid_to_str ( char *  s,
int  maxlen,
struct ast_eid eid 
)

/brief Convert an EID to a string

Since
1.6.1

Definition at line 222 of file netsock.c.

References ast_eid::eid.

Referenced by aji_publish_device_state(), aji_publish_mwi(), append_transaction(), ast_set_default_eid(), ast_str_retrieve_variable(), build_peer(), build_transactions(), cache_lookup(), cache_lookup_internal(), check_key(), complete_peer_helper(), destroy_trans(), do_autokill(), do_register(), do_register_expire(), dump_answer(), dump_eid(), dump_raw_ie(), 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_entityid(), dundi_show_peer(), dundi_show_peers(), dundi_show_requests(), handle_command_response(), handle_show_settings(), populate_addr(), register_request(), and update_key().

223 {
224  int x;
225  char *os = s;
226  if (maxlen < 18) {
227  if (s && (maxlen > 0))
228  *s = '\0';
229  } else {
230  for (x = 0; x < 5; x++) {
231  sprintf(s, "%02x:", (unsigned)eid->eid[x]);
232  s += 3;
233  }
234  sprintf(s, "%02x", (unsigned)eid->eid[5]);
235  }
236  return os;
237 }
unsigned char eid[6]
Definition: utils.h:809
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 2141 of file utils.c.

References ast_log(), and LOG_WARNING.

Referenced by ast_netsock_bindaddr(), and reload_config().

2142 {
2143 #if defined(HAVE_IP_MTU_DISCOVER)
2144  int val = IP_PMTUDISC_DONT;
2145 
2146  if (setsockopt(sock, IPPROTO_IP, IP_MTU_DISCOVER, &val, sizeof(val)))
2147  ast_log(LOG_WARNING, "Unable to disable PMTU discovery. Large UDP packets may fail to be delivered when sent from this socket.\n");
2148 #endif /* HAVE_IP_MTU_DISCOVER */
2149 }
Definition: ast_expr2.c:325
#define LOG_WARNING
Definition: logger.h:144
void ast_log(int level, const char *file, int line, const char *function, const char *fmt,...)
Used for sending a log message This is the standard logger function. Probably the only way you will i...
Definition: logger.c:1207
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

Escape characters found in a quoted string.

Definition at line 431 of file utils.c.

References string.

Referenced by add_diversion_header(), add_rpid(), ast_callerid_merge(), and initreqprep().

432 {
433  const char *ptr = string;
434  char *out = outbuf;
435  char *allow = "\t\v !"; /* allow LWS (minus \r and \n) and "!" */
436 
437  while (*ptr && out - outbuf < buflen - 1) {
438  if (!(strchr(allow, *ptr))
439  && !(*ptr >= '#' && *ptr <= '[') /* %x23 - %x5b */
440  && !(*ptr >= ']' && *ptr <= '~') /* %x5d - %x7e */
441  && !((unsigned char) *ptr > 0x7f)) { /* UTF8-nonascii */
442 
443  if (out - outbuf >= buflen - 2) {
444  break;
445  }
446  out += sprintf(out, "\\%c", (unsigned char) *ptr);
447  } else {
448  *out = *ptr;
449  out++;
450  }
451  ptr++;
452  }
453 
454  if (buflen) {
455  *out = '\0';
456  }
457 
458  return outbuf;
459 }
char string[1]
Definition: utils.c:1722
int ast_get_tid ( void  )

Get current thread ID.

Since
1.8.28.0
Returns
the ID if platform is supported, else -1

Definition at line 2346 of file utils.c.

Referenced by __ao2_alloc_debug(), __ao2_ref_debug(), and ast_log().

2347 {
2348  int ret = -1;
2349 #if defined (__linux) && defined(SYS_gettid)
2350  ret = syscall(SYS_gettid); /* available since Linux 1.4.11 */
2351 #elif defined(__sun)
2352  ret = pthread_self();
2353 #elif defined(__APPLE__)
2354  ret = mach_thread_self();
2355  mach_port_deallocate(mach_task_self(), ret);
2356 #elif defined(__FreeBSD__) && defined(HAVE_SYS_THR_H)
2357  long lwpid;
2358  thr_self(&lwpid); /* available since sys/thr.h creation 2003 */
2359  ret = lwpid;
2360 #endif
2361  return ret;
2362 }
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 195 of file utils.c.

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

Referenced by __ast_http_load(), app_exec(), ast_parse_arg(), build_peer(), config_load(), config_parse_variables(), create_addr(), festival_exec(), gtalk_load_config(), gtalk_update_stun(), iax_template_parse(), jingle_load_config(), jingle_update_stun(), launch_netscript(), process_sdp(), realtime_peer(), realtime_user(), reload_config(), and set_config().

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

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

Referenced by __init_manager(), auth_exec(), auth_http_callback(), build_reply_digest(), check_auth(), and md5().

246 {
247  struct MD5Context md5;
248  unsigned char digest[16];
249  char *ptr;
250  int x;
251 
252  MD5Init(&md5);
253  MD5Update(&md5, (const unsigned char *) input, strlen(input));
254  MD5Final(digest, &md5);
255  ptr = output;
256  for (x = 0; x < 16; x++)
257  ptr += sprintf(ptr, "%2.2x", (unsigned)digest[x]);
258 }
void MD5Final(unsigned char digest[16], struct MD5Context *context)
Definition: md5.c:122
static int input(yyscan_t yyscanner)
Definition: ast_expr2f.c:1575
void MD5Init(struct MD5Context *context)
Definition: md5.c:59
void MD5Update(struct MD5Context *context, unsigned char const *buf, unsigned len)
Definition: md5.c:74
static int md5(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
Definition: func_md5.c:54
Definition: md5.h:26
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 2151 of file utils.c.

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

Referenced by ast_monitor_change_fname(), ast_monitor_start(), conf_run(), create_dirpath(), dictate_exec(), filename_parse(), init_logger(), load_module(), mixmonitor_exec(), record_exec(), reload_logger(), remove_from_queue(), setup_privacy_args(), sms_nextoutgoing(), sms_writefile(), testclient_exec(), testserver_exec(), and write_history().

2152 {
2153  char *ptr;
2154  int len = strlen(path), count = 0, x, piececount = 0;
2155  char *tmp = ast_strdupa(path);
2156  char **pieces;
2157  char *fullpath = ast_alloca(len + 1);
2158  int res = 0;
2159 
2160  for (ptr = tmp; *ptr; ptr++) {
2161  if (*ptr == '/')
2162  count++;
2163  }
2164 
2165  /* Count the components to the directory path */
2166  pieces = ast_alloca(count * sizeof(*pieces));
2167  for (ptr = tmp; *ptr; ptr++) {
2168  if (*ptr == '/') {
2169  *ptr = '\0';
2170  pieces[piececount++] = ptr + 1;
2171  }
2172  }
2173 
2174  *fullpath = '\0';
2175  for (x = 0; x < piececount; x++) {
2176  /* This looks funky, but the buffer is always ideally-sized, so it's fine. */
2177  strcat(fullpath, "/");
2178  strcat(fullpath, pieces[x]);
2179  res = mkdir(fullpath, mode);
2180  if (res && errno != EEXIST)
2181  return errno;
2182  }
2183  return 0;
2184 }
#define ast_alloca(size)
call __builtin_alloca to ensure we get gcc builtin semantics
Definition: utils.h:653
#define ast_strdupa(s)
duplicate a string in memory from the stack
Definition: utils.h:663
static int len(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t buflen)
int errno
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 2216 of file utils.c.

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(), ast_http_digest::cnonce, ast_http_digest::domain, LOG_WARNING, ast_http_digest::nc, ast_http_digest::nonce, ast_http_digest::opaque, ast_http_digest::qop, ast_http_digest::realm, ast_http_digest::response, strsep(), ast_http_digest::uri, and ast_http_digest::username.

Referenced by auth_http_callback().

2216  {
2217  char *c;
2218  struct ast_str *str = ast_str_create(16);
2219 
2220  /* table of recognised keywords, and places where they should be copied */
2221  const struct x {
2222  const char *key;
2223  const ast_string_field *field;
2224  } *i, keys[] = {
2225  { "username=", &d->username },
2226  { "realm=", &d->realm },
2227  { "nonce=", &d->nonce },
2228  { "uri=", &d->uri },
2229  { "domain=", &d->domain },
2230  { "response=", &d->response },
2231  { "cnonce=", &d->cnonce },
2232  { "opaque=", &d->opaque },
2233  /* Special cases that cannot be directly copied */
2234  { "algorithm=", NULL },
2235  { "qop=", NULL },
2236  { "nc=", NULL },
2237  { NULL, 0 },
2238  };
2239 
2240  if (ast_strlen_zero(digest) || !d || !str) {
2241  ast_free(str);
2242  return -1;
2243  }
2244 
2245  ast_str_set(&str, 0, "%s", digest);
2246 
2247  c = ast_skip_blanks(ast_str_buffer(str));
2248 
2249  if (strncasecmp(c, "Digest ", strlen("Digest "))) {
2250  ast_log(LOG_WARNING, "Missing Digest.\n");
2251  ast_free(str);
2252  return -1;
2253  }
2254  c += strlen("Digest ");
2255 
2256  /* lookup for keys/value pair */
2257  while (c && *c && *(c = ast_skip_blanks(c))) {
2258  /* find key */
2259  for (i = keys; i->key != NULL; i++) {
2260  char *src, *separator;
2261  int unescape = 0;
2262  if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
2263  continue;
2264  }
2265 
2266  /* Found. Skip keyword, take text in quotes or up to the separator. */
2267  c += strlen(i->key);
2268  if (*c == '"') {
2269  src = ++c;
2270  separator = "\"";
2271  unescape = 1;
2272  } else {
2273  src = c;
2274  separator = ",";
2275  }
2276  strsep(&c, separator); /* clear separator and move ptr */
2277  if (unescape) {
2278  ast_unescape_c(src);
2279  }
2280  if (i->field) {
2281  ast_string_field_ptr_set(d, i->field, src);
2282  } else {
2283  /* Special cases that require additional procesing */
2284  if (!strcasecmp(i->key, "algorithm=")) {
2285  if (strcasecmp(src, "MD5")) {
2286  ast_log(LOG_WARNING, "Digest algorithm: \"%s\" not supported.\n", src);
2287  ast_free(str);
2288  return -1;
2289  }
2290  } else if (!strcasecmp(i->key, "qop=") && !strcasecmp(src, "auth")) {
2291  d->qop = 1;
2292  } else if (!strcasecmp(i->key, "nc=")) {
2293  unsigned long u;
2294  if (sscanf(src, "%30lx", &u) != 1) {
2295  ast_log(LOG_WARNING, "Incorrect Digest nc value: \"%s\".\n", src);
2296  ast_free(str);
2297  return -1;
2298  }
2299  ast_string_field_set(d, nc, src);
2300  }
2301  }
2302  break;
2303  }
2304  if (i->key == NULL) { /* not found, try ',' */
2305  strsep(&c, ",");
2306  }
2307  }
2308  ast_free(str);
2309 
2310  /* Digest checkout */
2311  if (ast_strlen_zero(d->realm) || ast_strlen_zero(d->nonce)) {
2312  /* "realm" and "nonce" MUST be always exist */
2313  return -1;
2314  }
2315 
2316  if (!request) {
2317  /* Additional check for Digest response */
2319  return -1;
2320  }
2321 
2322  if (pedantic && d->qop && (ast_strlen_zero(d->cnonce) || ast_strlen_zero(d->nc))) {
2323  return -1;
2324  }
2325  }
2326 
2327  return 0;
2328 }
const ast_string_field cnonce
Definition: utils.h:714
#define ast_string_field_ptr_set(x, ptr, data)
Set a field to a simple string value.
Definition: stringfields.h:318
char * strsep(char **str, const char *delims)
#define LOG_WARNING
Definition: logger.h:144
char * ast_str_buffer(const struct ast_str *buf)
Returns the string buffer within the ast_str buf.
Definition: strings.h:497
const ast_string_field opaque
Definition: utils.h:714
const ast_string_field domain
Definition: utils.h:714
struct ast_str * ast_str_create(size_t init_len)
Create a malloc&#39;ed dynamic length string.
Definition: strings.h:420
const char * ast_string_field
Definition: stringfields.h:115
const ast_string_field username
Definition: utils.h:714
const char * str
Definition: app_jack.c:144
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:874
const ast_string_field uri
Definition: utils.h:714
const ast_string_field response
Definition: utils.h:714
static force_inline int attribute_pure ast_strlen_zero(const char *s)
Definition: strings.h:63
The descriptor of a dynamic string XXX storage will be optimized later if needed We use the ts field ...
Definition: strings.h:364
char * ast_skip_blanks(const char *str)
Gets a pointer to the first non-whitespace character in a string.
Definition: strings.h:97
void ast_log(int level, const char *file, int line, const char *function, const char *fmt,...)
Used for sending a log message This is the standard logger function. Probably the only way you will i...
Definition: logger.c:1207
const ast_string_field nc
Definition: utils.h:714
#define ast_free(a)
Definition: astmm.h:97
const ast_string_field realm
Definition: utils.h:714
const ast_string_field nonce
Definition: utils.h:714
char * ast_unescape_c(char *s)
Convert some C escape sequences.
Definition: utils.c:1467
#define ast_string_field_set(x, field, data)
Set a field to a simple string value.
Definition: stringfields.h:344
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 1664 of file utils.c.

1665 {
1666  char *dataPut = start;
1667  int inEscape = 0;
1668  int inQuotes = 0;
1669 
1670  for (; *start; start++) {
1671  if (inEscape) {
1672  *dataPut++ = *start; /* Always goes verbatim */
1673  inEscape = 0;
1674  } else {
1675  if (*start == '\\') {
1676  inEscape = 1; /* Do not copy \ into the data */
1677  } else if (*start == '\'') {
1678  inQuotes = 1 - inQuotes; /* Do not copy ' into the data */
1679  } else {
1680  /* Replace , with |, unless in quotes */
1681  *dataPut++ = inQuotes ? *start : ((*start == find) ? replace_with : *start);
1682  }
1683  }
1684  }
1685  if (start != dataPut)
1686  *dataPut = 0;
1687  return dataPut;
1688 }
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 1230 of file utils.c.

References ast_alloca, ast_log(), ast_pthread_create_stack(), errno, LOG_WARNING, and thr_arg::start_routine.

1233 {
1234  unsigned char attr_destroy = 0;
1235  int res;
1236 
1237  if (!attr) {
1238  attr = ast_alloca(sizeof(*attr));
1239  pthread_attr_init(attr);
1240  attr_destroy = 1;
1241  }
1242 
1243  if ((errno = pthread_attr_setdetachstate(attr, PTHREAD_CREATE_DETACHED)))
1244  ast_log(LOG_WARNING, "pthread_attr_setdetachstate: %s\n", strerror(errno));
1245 
1246  res = ast_pthread_create_stack(thread, attr, start_routine, data,
1247  stacksize, file, caller, line, start_fn);
1248 
1249  if (attr_destroy)
1250  pthread_attr_destroy(attr);
1251 
1252  return res;
1253 }
pthread_t thread
Definition: app_meetme.c:962
#define ast_alloca(size)
call __builtin_alloca to ensure we get gcc builtin semantics
Definition: utils.h:653
#define LOG_WARNING
Definition: logger.h:144
void ast_log(int level, const char *file, int line, const char *function, const char *fmt,...)
Used for sending a log message This is the standard logger function. Probably the only way you will i...
Definition: logger.c:1207
int errno
int ast_pthread_create_stack(pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *), void *data, size_t stacksize, const char *file, const char *caller, int line, const char *start_fn)
Definition: utils.c:1182
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 1182 of file utils.c.

References ast_alloca, ast_asprintf, ast_log(), ast_malloc, AST_STACKSIZE, thr_arg::data, dummy_start(), errno, LOG_WARNING, thr_arg::name, pthread_create, and thr_arg::start_routine.

Referenced by ast_pthread_create_detached_stack().

1185 {
1186 #if !defined(LOW_MEMORY)
1187  struct thr_arg *a;
1188 #endif
1189 
1190  if (!attr) {
1191  attr = ast_alloca(sizeof(*attr));
1192  pthread_attr_init(attr);
1193  }
1194 
1195 #ifdef __linux__
1196  /* On Linux, pthread_attr_init() defaults to PTHREAD_EXPLICIT_SCHED,
1197  which is kind of useless. Change this here to
1198  PTHREAD_INHERIT_SCHED; that way the -p option to set realtime
1199  priority will propagate down to new threads by default.
1200  This does mean that callers cannot set a different priority using
1201  PTHREAD_EXPLICIT_SCHED in the attr argument; instead they must set
1202  the priority afterwards with pthread_setschedparam(). */
1203  if ((errno = pthread_attr_setinheritsched(attr, PTHREAD_INHERIT_SCHED)))
1204  ast_log(LOG_WARNING, "pthread_attr_setinheritsched: %s\n", strerror(errno));
1205 #endif
1206 
1207  if (!stacksize)
1208  stacksize = AST_STACKSIZE;
1209 
1210  if ((errno = pthread_attr_setstacksize(attr, stacksize ? stacksize : AST_STACKSIZE)))
1211  ast_log(LOG_WARNING, "pthread_attr_setstacksize: %s\n", strerror(errno));
1212 
1213 #if !defined(LOW_MEMORY)
1214  if ((a = ast_malloc(sizeof(*a)))) {
1216  a->data = data;
1218  if (ast_asprintf(&a->name, "%-20s started at [%5d] %s %s()",
1219  start_fn, line, file, caller) < 0) {
1220  a->name = NULL;
1221  }
1222  data = a;
1223  }
1224 #endif /* !LOW_MEMORY */
1225 
1226  return pthread_create(thread, attr, start_routine, data); /* We're in ast_pthread_create, so it's okay */
1227 }
pthread_t thread
Definition: app_meetme.c:962
#define AST_STACKSIZE
Definition: utils.h:399
#define ast_alloca(size)
call __builtin_alloca to ensure we get gcc builtin semantics
Definition: utils.h:653
#define LOG_WARNING
Definition: logger.h:144
void *(* start_routine)(void *)
Definition: utils.c:1128
#define ast_asprintf(a, b, c...)
Definition: astmm.h:121
void ast_log(int level, const char *file, int line, const char *function, const char *fmt,...)
Used for sending a log message This is the standard logger function. Probably the only way you will i...
Definition: logger.c:1207
int errno
#define pthread_create
Definition: lock.h:573
static void * dummy_start(void *data)
Definition: utils.c:1140
void * data
Definition: utils.c:1129
char * name
Definition: utils.c:1130
#define ast_malloc(a)
Definition: astmm.h:91
long int ast_random ( void  )

Definition at line 1640 of file utils.c.

References ast_mutex_lock, ast_mutex_unlock, and randomlock.

Referenced by acf_rand_exec(), action_challenge(), add_sdp(), agent_new(), agi_handle_command(), ast_lock_path_lockfile(), ast_moh_files_next(), ast_rtp_change_source(), ast_rtp_new(), ast_udptl_new_with_bindaddr(), auth_http_callback(), authenticate_request(), build_gateway(), build_iv(), build_localtag_registry(), build_rand_pad(), build_reply_digest(), calc_metric(), calc_rxstamp(), caldav_write_event(), callno_hash(), create_channel_name(), generate_exchange_uuid(), generate_random_string(), generic_http_callback(), get_trans_id(), gtalk_alloc(), gtalk_create_candidates(), gtalk_new(), handle_incoming(), handle_response_invite(), iax2_key_rotate(), iax2_start_transfer(), jingle_alloc(), jingle_create_candidates(), jingle_new(), load_module(), make_email_file(), make_our_tag(), moh_files_alloc(), multicast_rtp_new(), ogg_vorbis_rewrite(), osp_create_uuid(), page_exec(), park_space_reserve(), process_weights(), reg_source_db(), registry_authrequest(), reqprep(), say_periodic_announcement(), sendmail(), set_nonce_randdata(), sip_alloc(), socket_read(), start_rtp(), stun_req_id(), transmit_invite(), transmit_register(), transmit_response_using_temp(), try_calling(), and try_firmware().

1641 {
1642  long int res;
1643 #ifdef HAVE_DEV_URANDOM
1644  if (dev_urandom_fd >= 0) {
1645  int read_res = read(dev_urandom_fd, &res, sizeof(res));
1646  if (read_res > 0) {
1647  long int rm = RAND_MAX;
1648  res = res < 0 ? ~res : res;
1649  rm++;
1650  return res % rm;
1651  }
1652  }
1653 #endif
1654 #ifdef linux
1655  res = random();
1656 #else
1658  res = random();
1660 #endif
1661  return res;
1662 }
#define ast_mutex_lock(a)
Definition: lock.h:155
static int dev_urandom_fd
Definition: utils.c:575
static ast_mutex_t randomlock
glibc puts a lock inside random(3), so that the results are thread-safe. BSD libc (and others) do not...
Definition: utils.c:1637
#define ast_mutex_unlock(a)
Definition: lock.h:156
void ast_register_thread ( char *  name)

Definition at line 401 of file asterisk.c.

References ast_assert, ast_calloc, AST_RWLIST_INSERT_HEAD, AST_RWLIST_UNLOCK, AST_RWLIST_WRLOCK, ast_atexit::list, multi_thread_safe, and name.

Referenced by dummy_start().

402 {
403  struct thread_list_t *new = ast_calloc(1, sizeof(*new));
404 
405  if (!new)
406  return;
407 
409  new->id = pthread_self();
410  new->name = name; /* steal the allocated memory for the thread name */
412  AST_RWLIST_INSERT_HEAD(&thread_list, new, list);
414 }
#define AST_RWLIST_WRLOCK(head)
Write locks a list.
Definition: linkedlists.h:51
static int multi_thread_safe
Definition: asterisk.c:298
#define AST_RWLIST_UNLOCK(head)
Attempts to unlock a read/write based list.
Definition: linkedlists.h:150
#define ast_assert(a)
Definition: utils.h:738
#define AST_RWLIST_INSERT_HEAD
Definition: linkedlists.h:703
static const char name[]
#define ast_calloc(a, b)
Definition: astmm.h:82
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 239 of file netsock.c.

References ARRAY_LEN, ast_debug, ast_eid_to_str(), and ast_eid::eid.

Referenced by ast_readconfig().

240 {
241 #if defined(SIOCGIFHWADDR) && defined(HAVE_STRUCT_IFREQ_IFR_IFRU_IFRU_HWADDR)
242  int s, x = 0;
243  char eid_str[20];
244  struct ifreq ifr;
245  static const unsigned int MAXIF = 10;
246 
247  s = socket(AF_INET, SOCK_STREAM, 0);
248  if (s < 0)
249  return;
250  for (x = 0; x < MAXIF; x++) {
251  static const char *prefixes[] = { "eth", "em" };
252  unsigned int i;
253 
254  for (i = 0; i < ARRAY_LEN(prefixes); i++) {
255  memset(&ifr, 0, sizeof(ifr));
256  snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s%d", prefixes[i], x);
257  if (!ioctl(s, SIOCGIFHWADDR, &ifr)) {
258  break;
259  }
260  }
261 
262  if (i == ARRAY_LEN(prefixes)) {
263  /* Try pciX#[1..N] */
264  for (i = 0; i < MAXIF; i++) {
265  memset(&ifr, 0, sizeof(ifr));
266  snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "pci%d#%u", x, i);
267  if (!ioctl(s, SIOCGIFHWADDR, &ifr)) {
268  break;
269  }
270  }
271  if (i == MAXIF) {
272  continue;
273  }
274  }
275 
276  memcpy(eid, ((unsigned char *)&ifr.ifr_hwaddr) + 2, sizeof(*eid));
277  ast_debug(1, "Seeding global EID '%s' from '%s' using 'siocgifhwaddr'\n", ast_eid_to_str(eid_str, sizeof(eid_str), eid), ifr.ifr_name);
278  close(s);
279  return;
280  }
281  close(s);
282 #else
283 #if defined(ifa_broadaddr) && !defined(SOLARIS)
284  char eid_str[20];
285  struct ifaddrs *ifap;
286 
287  if (getifaddrs(&ifap) == 0) {
288  struct ifaddrs *p;
289  for (p = ifap; p; p = p->ifa_next) {
290  if ((p->ifa_addr->sa_family == AF_LINK) && !(p->ifa_flags & IFF_LOOPBACK) && (p->ifa_flags & IFF_RUNNING)) {
291  struct sockaddr_dl* sdp = (struct sockaddr_dl*) p->ifa_addr;
292  memcpy(&(eid->eid), sdp->sdl_data + sdp->sdl_nlen, 6);
293  ast_debug(1, "Seeding global EID '%s' from '%s' using 'getifaddrs'\n", ast_eid_to_str(eid_str, sizeof(eid_str), eid), p->ifa_name);
294  freeifaddrs(ifap);
295  return;
296  }
297  }
298  freeifaddrs(ifap);
299  }
300 #endif
301 #endif
302  ast_debug(1, "No ethernet interface found for seeding global EID. You will have to set it manually.\n");
303 }
#define ARRAY_LEN(a)
Definition: isdn_lib.c:42
char * ast_eid_to_str(char *s, int maxlen, struct ast_eid *eid)
Definition: netsock.c:222
#define ast_debug(level,...)
Log a DEBUG message.
Definition: logger.h:236
unsigned char eid[6]
Definition: utils.h:809
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 261 of file utils.c.

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

Referenced by aji_act_hook(), handle_call_token(), jabber_make_auth(), and sha1().

262 {
263  struct SHA1Context sha;
264  char *ptr;
265  int x;
266  uint8_t Message_Digest[20];
267 
268  SHA1Reset(&sha);
269 
270  SHA1Input(&sha, (const unsigned char *) input, strlen(input));
271 
272  SHA1Result(&sha, Message_Digest);
273  ptr = output;
274  for (x = 0; x < 20; x++)
275  ptr += sprintf(ptr, "%2.2x", (unsigned)Message_Digest[x]);
276 }
static int input(yyscan_t yyscanner)
Definition: ast_expr2f.c:1575
int SHA1Result(SHA1Context *, uint8_t Message_Digest[SHA1HashSize])
Definition: sha1.c:226
int SHA1Reset(SHA1Context *)
SHA1Reset.
Definition: sha1.c:101
int SHA1Input(SHA1Context *, const uint8_t *bytes, unsigned int bytecount)
static force_inline void ast_slinear_saturated_add ( short *  input,
short *  value 
)
static

Definition at line 312 of file utils.h.

Referenced by ast_frame_slinear_sum(), audio_audiohook_write_list(), audiohook_read_frame_both(), and softmix_bridge_thread().

313 {
314  int res;
315 
316  res = (int) *input + *value;
317  if (res > 32767)
318  *input = 32767;
319  else if (res < -32768)
320  *input = -32768;
321  else
322  *input = (short) res;
323 }
int value
Definition: syslog.c:39
static int input(yyscan_t yyscanner)
Definition: ast_expr2f.c:1575
static force_inline void ast_slinear_saturated_divide ( short *  input,
short *  value 
)
static

Definition at line 351 of file utils.h.

References value.

Referenced by ast_frame_adjust_volume(), and audiohook_read_frame_both().

352 {
353  *input /= *value;
354 }
int value
Definition: syslog.c:39
static int input(yyscan_t yyscanner)
Definition: ast_expr2f.c:1575
static force_inline void ast_slinear_saturated_multiply ( short *  input,
short *  value 
)
static

Definition at line 338 of file utils.h.

Referenced by ast_frame_adjust_volume(), and audiohook_read_frame_both().

339 {
340  int res;
341 
342  res = (int) *input * *value;
343  if (res > 32767)
344  *input = 32767;
345  else if (res < -32768)
346  *input = -32768;
347  else
348  *input = (short) res;
349 }
int value
Definition: syslog.c:39
static int input(yyscan_t yyscanner)
Definition: ast_expr2f.c:1575
static force_inline void ast_slinear_saturated_subtract ( short *  input,
short *  value 
)
static

Definition at line 325 of file utils.h.

Referenced by softmix_bridge_thread().

326 {
327  int res;
328 
329  res = (int) *input - *value;
330  if (res > 32767)
331  *input = 32767;
332  else if (res < -32768)
333  *input = -32768;
334  else
335  *input = (short) res;
336 }
int value
Definition: syslog.c:39
static int input(yyscan_t yyscanner)
Definition: ast_expr2f.c:1575
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 305 of file netsock.c.

References ast_eid::eid.

Referenced by aji_handle_pubsub_event(), ast_readconfig(), build_peer(), dundi_do_query(), and set_config().

306 {
307  unsigned int eid_int[6];
308  int x;
309 
310  if (sscanf(s, "%2x:%2x:%2x:%2x:%2x:%2x", &eid_int[0], &eid_int[1], &eid_int[2],
311  &eid_int[3], &eid_int[4], &eid_int[5]) != 6)
312  return -1;
313 
314  for (x = 0; x < 6; x++)
315  eid->eid[x] = eid_int[x];
316 
317  return 0;
318 }
unsigned char eid[6]
Definition: utils.h:809
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 461 of file utils.c.

Referenced by ast_callerid_parse().

462 {
463  int esc_pos;
464  int unesc_pos;
465  int quote_str_len = strlen(quote_str);
466 
467  for (esc_pos = 0, unesc_pos = 0;
468  esc_pos < quote_str_len;
469  esc_pos++, unesc_pos++) {
470  if (quote_str[esc_pos] == '\\') {
471  /* at least one more char and current is \\ */
472  esc_pos++;
473  if (esc_pos >= quote_str_len) {
474  break;
475  }
476  }
477 
478  quote_str[unesc_pos] = quote_str[esc_pos];
479  }
480  quote_str[unesc_pos] = '\0';
481 }
void ast_unregister_thread ( void *  id)

Definition at line 416 of file asterisk.c.

References ast_free, AST_RWLIST_REMOVE_CURRENT, AST_RWLIST_TRAVERSE_SAFE_BEGIN, AST_RWLIST_TRAVERSE_SAFE_END, AST_RWLIST_UNLOCK, AST_RWLIST_WRLOCK, and ast_atexit::list.

Referenced by dummy_start().

417 {
418  struct thread_list_t *x;
419 
422  if ((void *) x->id == id) {
424  break;
425  }
426  }
429  if (x) {
430  ast_free(x->name);
431  ast_free(x);
432  }
433 }
#define AST_RWLIST_WRLOCK(head)
Write locks a list.
Definition: linkedlists.h:51
#define AST_RWLIST_UNLOCK(head)
Attempts to unlock a read/write based list.
Definition: linkedlists.h:150
#define AST_RWLIST_REMOVE_CURRENT
Definition: linkedlists.h:565
#define AST_RWLIST_TRAVERSE_SAFE_BEGIN
Definition: linkedlists.h:542
#define ast_free(a)
Definition: astmm.h:97
#define AST_RWLIST_TRAVERSE_SAFE_END
Definition: linkedlists.h:602
void ast_uri_decode ( char *  s)

Decode URI, URN, URL (overwrite string)

Parameters
sString to be decoded

Decode URI, URN, URL (overwrite string)

Definition at line 484 of file utils.c.

Referenced by acf_curl_helper(), config_curl(), get_destination(), get_name_and_number(), get_refer_info(), handle_request_invite(), http_decode(), parse_moved_contact(), realtime_curl(), realtime_multi_curl(), sip_new(), sip_uri_cmp(), and uridecode().

485 {
486  char *o;
487  unsigned int tmp;
488 
489  for (o = s; *s; s++, o++) {
490  if (*s == '%' && s[1] != '\0' && s[2] != '\0' && sscanf(s + 1, "%2x", &tmp) == 1) {
491  /* have '%', two chars and correct parsing */
492  *o = tmp;
493  s += 2; /* Will be incremented once more when we break out */
494  } else /* all other cases, just copy */
495  *o = *s;
496  }
497  *o = '\0';
498 }
char* ast_uri_encode ( const char *  string,
char *  outbuf,
int  buflen,
int  do_special_char 
)

Turn text string to URI-encoded XX version.

Note
At this point, this function is encoding agnostic; it does not check whether it is fed legal UTF-8. We escape control characters (-), '', and all characters above 0x7F. If do_special_char == 1 we will convert all characters except alnum and the mark set. Outbuf needs to have more memory allocated than the instring to have room for the expansion. Every char that is converted is replaced by three ASCII characters.
Parameters
stringString to be converted
outbufResulting encoded string
buflenSize of output buffer
do_special_charConvert all non alphanum characters execept those in the mark set as defined by rfc 3261 section 25.1
Note
At this point, this function is encoding agnostic; it does not check whether it is fed legal UTF-8. We escape control characters (-), '', and all characters above 0x7F. If do_special_char == 1 we will convert all characters except alnum and mark. Outbuf needs to have more memory allocated than the instring to have room for the expansion. Every char that is converted is replaced by three ASCII characters.

Definition at line 398 of file utils.c.

References string.

Referenced by add_rpid(), build_contact(), config_curl(), destroy_curl(), initreqprep(), launch_asyncagi(), realtime_curl(), realtime_multi_curl(), require_curl(), store_curl(), update2_curl(), update_curl(), and uriencode().

399 {
400  const char *ptr = string; /* Start with the string */
401  char *out = outbuf;
402  const char *mark = "-_.!~*'()"; /* no encode set, RFC 2396 section 2.3, RFC 3261 sec 25 */
403 
404  while (*ptr && out - outbuf < buflen - 1) {
405  if ((const signed char) *ptr < 32 || *ptr == 0x7f || *ptr == '%' ||
406  (do_special_char &&
407  !(*ptr >= '0' && *ptr <= '9') && /* num */
408  !(*ptr >= 'A' && *ptr <= 'Z') && /* ALPHA */
409  !(*ptr >= 'a' && *ptr <= 'z') && /* alpha */
410  !strchr(mark, *ptr))) { /* mark set */
411  if (out - outbuf >= buflen - 3) {
412  break;
413  }
414 
415  out += sprintf(out, "%%%02X", (unsigned) *ptr);
416  } else {
417  *out = *ptr; /* Continue copying the string */
418  out++;
419  }
420  ptr++;
421  }
422 
423  if (buflen) {
424  *out = '\0';
425  }
426 
427  return outbuf;
428 }
char string[1]
Definition: utils.c:1722
int ast_utils_init ( void  )

Definition at line 2193 of file utils.c.

References ARRAY_LEN, ast_cli_register_multiple(), ast_register_atexit(), and base64_init().

Referenced by main().

2194 {
2195 #ifdef HAVE_DEV_URANDOM
2196  dev_urandom_fd = open("/dev/urandom", O_RDONLY);
2197 #endif
2198  base64_init();
2199 #ifdef DEBUG_THREADS
2200 #if !defined(LOW_MEMORY)
2201  ast_cli_register_multiple(utils_cli, ARRAY_LEN(utils_cli));
2202  ast_register_atexit(utils_shutdown);
2203 #endif
2204 #endif
2205  return 0;
2206 }
#define ARRAY_LEN(a)
Definition: isdn_lib.c:42
int ast_register_atexit(void(*func)(void))
Register a function to be executed before Asterisk exits.
Definition: asterisk.c:998
static int dev_urandom_fd
Definition: utils.c:575
static void base64_init(void)
Definition: utils.c:362
int ast_cli_register_multiple(struct ast_cli_entry *e, int len)
Register multiple commands.
Definition: cli.c:2167
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 2364 of file utils.c.

References ast_strdupa, and strsep().

Referenced by ast_bt_get_symbols().

2365 {
2366  const char *envPATH = getenv("PATH");
2367  char *tpath, *path;
2368  struct stat unused;
2369  if (!envPATH) {
2370  return NULL;
2371  }
2372  tpath = ast_strdupa(envPATH);
2373  while ((path = strsep(&tpath, ":"))) {
2374  snprintf(fullpath, fullpath_size, "%s/%s", path, binary);
2375  if (!stat(fullpath, &unused)) {
2376  return fullpath;
2377  }
2378  }
2379  return NULL;
2380 }
char * strsep(char **str, const char *delims)
#define ast_strdupa(s)
duplicate a string in memory from the stack
Definition: utils.h:663
int ast_wait_for_input ( int  fd,
int  ms 
)

Definition at line 1255 of file utils.c.

References ast_poll.

Referenced by action_waitevent(), ast_tcptls_server_root(), dahdi_test_timer(), get_input(), moh_class_destructor(), sip_tcptls_read(), tcptls_stream_read(), and tcptls_stream_write().

1256 {
1257  struct pollfd pfd[1];
1258 
1259  memset(pfd, 0, sizeof(pfd));
1260  pfd[0].fd = fd;
1261  pfd[0].events = POLLIN | POLLPRI;
1262  return ast_poll(pfd, 1, ms);
1263 }
#define ast_poll(a, b, c)
Definition: poll-compat.h:88
int ast_wait_for_output ( int  fd,
int  ms 
)

Definition at line 1265 of file utils.c.

References ast_poll.

Referenced by tcptls_stream_read(), and tcptls_stream_write().

1266 {
1267  struct pollfd pfd[1];
1268 
1269  memset(pfd, 0, sizeof(pfd));
1270  pfd[0].fd = fd;
1271  pfd[0].events = POLLOUT;
1272  return ast_poll(pfd, 1, ms);
1273 }
#define ast_poll(a, b, c)
Definition: poll-compat.h:88
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 500 of file utils.c.

References ast_assert, entity, len(), and string.

Referenced by state_notify_build_xml().

501 {
502  char *dst = outbuf;
503  char *end = outbuf + buflen - 1; /* save one for the null terminator */
504 
505  /* Handle the case for the empty output buffer */
506  if (buflen == 0) {
507  return -1;
508  }
509 
510  /* Escaping rules from http://www.w3.org/TR/REC-xml/#syntax */
511  /* This also prevents partial entities at the end of a string */
512  while (*string && dst < end) {
513  const char *entity = NULL;
514  int len = 0;
515 
516  switch (*string) {
517  case '<':
518  entity = "&lt;";
519  len = 4;
520  break;
521  case '&':
522  entity = "&amp;";
523  len = 5;
524  break;
525  case '>':
526  /* necessary if ]]> is in the string; easier to escape them all */
527  entity = "&gt;";
528  len = 4;
529  break;
530  case '\'':
531  /* necessary in single-quoted strings; easier to escape them all */
532  entity = "&apos;";
533  len = 6;
534  break;
535  case '"':
536  /* necessary in double-quoted strings; easier to escape them all */
537  entity = "&quot;";
538  len = 6;
539  break;
540  default:
541  *dst++ = *string++;
542  break;
543  }
544 
545  if (entity) {
546  ast_assert(len == strlen(entity));
547  if (end - dst < len) {
548  /* no room for the entity; stop */
549  break;
550  }
551  /* just checked for length; strcpy is fine */
552  strcpy(dst, entity);
553  dst += len;
554  ++string;
555  }
556  }
557  /* Write null terminator */
558  *dst = '\0';
559  /* If any chars are left in string, return failure */
560  return *string == '\0' ? 0 : -1;
561 }
static int entity
Definition: isdn_lib.c:259
#define ast_assert(a)
Definition: utils.h:738
static int len(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t buflen)
char string[1]
Definition: utils.c:1722

Variable Documentation

unsigned int __unsigned_int_flags_dummy
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.
uint64_t __unsigned_int_flags_dummy64
struct ast_eid ast_eid_default

Global EID.

This is set in asterisk.conf, or determined automatically by taking the mac address of an Ethernet interface on the system.

Definition at line 192 of file asterisk.c.

Referenced by aji_devstate_cb(), aji_handle_pubsub_event(), aji_mwi_cb(), aji_publish_device_state(), aji_publish_mwi(), ast_event_append_eid(), ast_event_cb(), ast_readconfig(), ast_str_retrieve_variable(), evt_event_deliver_cb(), handle_show_settings(), and set_config().