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"

Include dependency graph for utils.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

Defines

#define ARRAY_IN_BOUNDS(v, a)   IN_BOUNDS((int) (v), 0, ARRAY_LEN(a) - 1)
 Checks to see if value is within the bounds of the given array.
#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.
#define ast_alignof(type)   __alignof__(type)
 Return the number of bytes used in the alignment of type.
#define ast_alloca(size)   __builtin_alloca(size)
 call __builtin_alloca to ensure we get gcc builtin semantics
#define ast_asprintf(ret, fmt,...)   _ast_asprintf((ret), __FILE__, __LINE__, __PRETTY_FUNCTION__, fmt, __VA_ARGS__)
 A wrapper for asprintf().
#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().
#define ast_calloc_cache(num, len)   _ast_calloc((num), (len), __FILE__, __LINE__, __PRETTY_FUNCTION__)
 A wrapper for calloc() for use in cache pools.
#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
#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.
#define ast_malloc(len)   _ast_malloc((len), __FILE__, __LINE__, __PRETTY_FUNCTION__)
 A wrapper for malloc().
#define ast_pthread_create(a, b, c, d)
#define ast_pthread_create_background(a, b, c, d)
#define ast_pthread_create_detached(a, b, c, d)
#define ast_pthread_create_detached_background(a, b, c, d)
#define ast_random_double()   (((double)ast_random()) / RAND_MAX)
 Returns a random number between 0.0 and 1.0, inclusive.
#define ast_realloc(p, len)   _ast_realloc((p), (len), __FILE__, __LINE__, __PRETTY_FUNCTION__)
 A wrapper for realloc().
#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().
#define ast_strdupa(s)
 duplicate a string in memory from the stack
#define ast_strndup(str, len)   _ast_strndup((str), (len), __FILE__, __LINE__, __PRETTY_FUNCTION__)
 A wrapper for strndup().
#define ast_test_flag(p, flag)
#define ast_test_flag64(p, flag)
#define ast_test_flag_nonstd(p, flag)   ((p)->flags & (flag))
#define AST_URI_ALPHANUM   (1 << 0)
#define AST_URI_LEGACY_SPACE   (1 << 2)
#define AST_URI_MARK   (1 << 1)
#define AST_URI_SIP_USER_UNRESERVED   (1 << 20)
#define AST_URI_UNRESERVED   (AST_URI_ALPHANUM | AST_URI_MARK)
#define ast_vasprintf(ret, fmt, ap)   _ast_vasprintf((ret), __FILE__, __LINE__, __PRETTY_FUNCTION__, (fmt), (ap))
 A wrapper for vasprintf().
#define DEBUG_CHAOS_RETURN(c, f)
 DEBUG_CHAOS returns failure randomly.
#define IN_BOUNDS(v, min, max)   ((v) >= (min)) && ((v) <= (max))
 Checks to see if value is within the given bounds.
#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.
#define SWAP(a, b)   do { typeof(a) __tmp = (a); (a) = (b); (b) = __tmp; } while (0)

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.
int ast_base64encode (char *dst, const unsigned char *src, int srclen, int max)
 Encode data in base64.
int ast_base64encode_full (char *dst, const unsigned char *src, int srclen, int max, int linebreaks)
 encode text to BASE64 coding
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.
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.
char * ast_crypt (const char *key, const char *salt)
 Asterisk wrapper around crypt(3).
char * ast_crypt_encrypt (const char *key)
int ast_crypt_validate (const char *key, const char *expected)
void ast_do_crash (void)
 Force a crash if DO_CRASH is defined.
int ast_eid_cmp (const struct ast_eid *eid1, const struct ast_eid *eid2)
 Compare two EIDs.
char * ast_eid_to_str (char *s, int maxlen, struct ast_eid *eid)
 Convert an EID to a string.
void ast_enable_packet_fragmentation (int sock)
 Disable PMTU discovery on a socket.
char * ast_escape_quoted (const char *string, char *outbuf, int buflen)
 Escape characters found in a quoted string.
char * ast_escape_semicolons (const char *string, char *outbuf, int buflen)
 Escape semicolons found in a string.
int ast_get_tid (void)
 Get current thread ID.
struct hostent * ast_gethostbyname (const char *host, struct ast_hostent *hp)
 Thread-safe gethostbyname function to use in Asterisk.
void ast_md5_hash (char *output, const char *input)
 Produces MD5 hash based on input string.
int ast_mkdir (const char *path, int mode)
 Recursively create directory path.
int ast_parse_digest (const char *digest, struct ast_http_digest *d, int request, int pedantic)
 Parse digest authorization header.
char * ast_process_quotes_and_slashes (char *start, char find, char replace_with)
 Process a string to find and replace characters.
int ast_pthread_create_detached_stack (pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *), void *data, size_t stacksize, const char *file, const char *caller, int line, const char *start_fn)
int ast_pthread_create_stack (pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *), void *data, size_t stacksize, const char *file, const char *caller, int line, const char *start_fn)
long int ast_random (void)
void ast_register_thread (char *name)
void ast_replace_subargument_delimiter (char *s)
 Replace '^' in a string with ','.
int ast_safe_mkdir (const char *base_path, const char *path, int mode)
 Recursively create directory path, but only if it resolves within the given base_path.
void ast_set_default_eid (struct ast_eid *eid)
 Fill in an ast_eid with the default eid of this machine.
void ast_sha1_hash (char *output, const char *input)
 Produces SHA1 hash based on input string.
void ast_sha1_hash_uint (uint8_t *digest, const char *input)
 Produces SHA1 hash based on input string, stored in uint8_t array.
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.
void ast_unescape_quoted (char *quote_str)
 Unescape quotes in a string.
void ast_unregister_thread (void *id)
void ast_uri_decode (char *s, struct ast_flags spec)
 Decode URI, URN, URL (overwrite string).
char * ast_uri_encode (const char *string, char *outbuf, int buflen, struct ast_flags spec)
 Turn text string to URI-encoded XX version.
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.
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.

Variables

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


Detailed Description

Utility functions.

Definition in file utils.h.


Define Documentation

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

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

Parameters:
v the value to check
a the array to bound check
Returns:
0 if value out of bounds, otherwise true (non-zero)

Definition at line 819 of file utils.h.

Referenced by ast_sip_auth_type_to_str(), cli_print_body(), direct_media_glare_mitigation_to_str(), direct_media_method_to_str(), dtlsfingerprint_to_str(), dtlssetup_to_str(), media_encryption_to_str(), t38udptl_ec_to_str(), tls_method_to_str(), and transport_protocol_to_str().

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

Definition at line 800 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:
offset The value that should be increased.
type The 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 899 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 879 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:
size The 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.
Examples:
/tmp/asterisk-trunk/trunk/main/app.c.

Definition at line 741 of file utils.h.

Referenced by __analog_handle_event(), _while_exec(), acf_vm_info(), add_hints(), ael2_semantic_check(), after_bridge_move_channel(), alsa_card_init(), aMYSQL_set(), append_mailbox(), ast_bucket_alloc(), ast_bucket_file_alloc(), ast_dsp_process(), ast_dsp_silence_noise_with_energy(), ast_event_append_ie_str(), 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_sip_cli_print_sorcery_objectset(), ast_sorcery_object_fields_register(), AST_TEST_DEFINE(), ast_unlock_path_flock(), ast_unlock_path_lockfile(), ast_unreal_new_channels(), ast_waitfor_nandfds(), ast_websocket_write(), ast_writefile(), astman_append_json(), bridge_channel_queue_action_data_sync(), bridge_merge(), bridge_merge_locked(), bucket_file_wizard_retrieve(), bucket_wizard_retrieve(), callerid_feed(), callerid_feed_jp(), CB_ADD_LEN(), chan_pjsip_incoming_response(), config_module(), control_streamfile(), cpeid_exec(), create_addr_from_peer(), create_new_id_hdr(), cut_internal(), db_open(), decode_frame(), device_state_cb(), dictate_exec(), digest_check_auth(), dns_naptr_sort(), does_category_match(), dundi_decrypt(), dundi_encrypt(), dundi_precache_internal(), dynamic_dtmf_hook_trip(), encrypt_frame(), festival_exec(), filename_parse(), find_aor(), find_by_channel(), find_database(), find_table(), framehook_list_push_event(), func_mchan_read(), function_fieldnum_helper(), function_fieldqty_helper(), handle_cli_config_reload(), handle_cli_mobile_search(), handle_command_response(), handle_incoming(), import_helper(), inprocess_count(), jingle_action_session_terminate(), listfilter(), lua_get_variable(), lua_get_variable_value(), lua_read_extensions_file(), modify_id_header(), payload_helper_playfile(), pbx_builtin_importvar(), pbx_load_module(), pbx_substitute_variables_helper_full(), play_mailbox_owner(), presence_state_cb(), read_header(), record_file(), refer_blind_callback(), refer_incoming_refer_request(), registrar_on_rx_request(), replace(), rx_task(), set_bridge_peer_vars_multiparty(), set_outbound_authentication_credentials(), setenv(), shared_read(), shared_write(), shift_pop(), sip_addheader(), sms_generate(), socket_process_helper(), sort_internal(), spy_sayname(), start_automixmonitor(), start_automonitor(), state_notify_build_xml(), static_callback(), strcasestr(), strreplace(), test_semi(), try_firmware(), unshift_push(), vm_change_password(), vm_delete(), vm_msg_forward(), vm_msg_move(), vm_msg_remove(), vm_play_folder_name_gr(), and websocket_combine_key().

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

#define ast_assert ( a   ) 

Examples:
/tmp/asterisk-trunk/trunk/main/app.c.

Definition at line 857 of file utils.h.

Referenced by __after_bridge_set_goto(), __ao2_container_clone(), __ao2_container_clone_debug(), __ao2_find(), __ao2_find_debug(), __ao2_global_obj_ref(), __ao2_global_obj_release(), __ao2_global_obj_replace(), __ao2_lock(), __ao2_ref_debug(), __ao2_trylock(), __ao2_unlink(), __ao2_unlink_debug(), __ao2_unlock(), __ast_format_cap_append(), __ast_format_cap_append_debug(), __ast_play_and_record(), __ast_register_translator(), __ast_sorcery_object_field_register(), __ast_sorcery_open(), __ast_sorcery_wizard_register(), __ast_string_field_alloc_space(), __ast_string_field_ptr_build_va(), _ast_odbc_request_obj2(), ack_ticks(), add_hints(), agents_post_apply_config(), announce_request(), ao2_container_check(), ao2_container_dump(), ao2_container_stats(), ao2_object_get_lockaddr(), app_control_continue(), app_control_redirect(), app_create(), app_dtor(), app_exec(), app_hash(), app_shutdown(), append_json_single(), application_tuple_alloc(), ari_bridges_handle_play(), ari_channels_handle_play(), ari_channels_handle_snoop_channel(), ast_ari_asterisk_get_global_var(), ast_ari_asterisk_set_global_var(), ast_ari_bridges_record(), ast_ari_callback(), ast_ari_channels_continue_in_dialplan(), ast_ari_channels_get(), ast_ari_channels_get_channel_var(), ast_ari_channels_record(), ast_ari_channels_set_channel_var(), ast_ari_invoke(), ast_ari_playbacks_stop(), ast_ari_remove_handler(), ast_ari_validate_date(), ast_begins_with(), ast_bridge_add_channel(), ast_bridge_channel_restore_formats(), ast_bridge_depart(), ast_bridge_join(), ast_bridge_merge(), ast_bridge_publish_merge(), ast_bridge_publish_state(), ast_bridge_set_after_callback(), ast_bridge_snapshot_get_latest(), ast_cc_is_recall(), ast_cdr_serialize_variables(), ast_channel_destructor(), ast_channel_forward_endpoint(), ast_channel_get_cc_config_params(), ast_channel_get_duration(), ast_channel_get_up_time(), ast_channel_internal_oldest_linkedid(), ast_channel_internal_setup_topics(), ast_channel_linkedid(), ast_channel_publish_dial_forward(), ast_channel_publish_dial_internal(), ast_channel_publish_snapshot(), ast_channel_publish_varset(), ast_channel_snapshot_caller_id_equal(), ast_channel_snapshot_cep_equal(), ast_channel_snapshot_connected_line_equal(), ast_channel_snapshot_get_latest(), ast_channel_snapshot_get_latest_by_name(), ast_channel_uniqueid(), ast_db_get(), ast_dns_naptr_get_flags(), ast_dns_naptr_get_order(), ast_dns_naptr_get_preference(), ast_dns_naptr_get_regexp(), ast_dns_naptr_get_replacement(), ast_dns_naptr_get_service(), ast_dns_srv_get_host(), ast_dns_srv_get_port(), ast_dns_srv_get_priority(), ast_dns_srv_get_weight(), ast_endpoint_add_channel(), ast_endpoint_latest_snapshot(), ast_endpoint_set_max_channels(), ast_endpoint_set_state(), ast_endpoint_snapshot_create(), ast_endpoint_snapshot_to_json(), ast_ends_with(), ast_escape_semicolons(), ast_format_cache_set(), ast_format_cap_get_best_by_type(), ast_format_cap_get_compatible_format(), ast_format_cap_get_format(), ast_format_cap_iscompatible_format(), ast_format_cap_remove(), ast_get_chan_applicationmap(), ast_get_chan_featuremap_config(), ast_get_chan_features_general_config(), ast_get_chan_features_pickup_config(), ast_get_chan_features_xfer_config(), ast_hangup(), ast_http_body_discard(), ast_http_get_auth(), ast_http_get_contents(), ast_http_send(), ast_json_free(), ast_json_to_ast_variables(), ast_json_typename(), ast_json_typeof(), ast_manager_event_blob_create(), ast_multi_channel_blob_create(), ast_multi_object_blob_create(), ast_mwi_blob_create(), ast_mwi_create(), ast_pbx_outgoing_exten(), ast_publish_channel_state(), ast_publish_device_state_full(), ast_register_thread(), ast_rtcp_read(), ast_rtp_read(), ast_sched_del(), ast_sem_getvalue(), ast_sem_post(), ast_sem_timedwait(), ast_sem_wait(), ast_set_read_format(), ast_set_write_format(), ast_sip_auth_vector_init(), ast_sip_create_dialog_uas(), ast_sip_identify_endpoint(), ast_sip_publication_add_datastore(), ast_sip_publish_client_add_datastore(), ast_sip_register_cli_formatter(), ast_sip_send_request(), ast_sip_session_add_datastore(), ast_sip_session_defer_termination(), ast_sip_session_suspend(), ast_sip_subscription_add_datastore(), ast_sip_subscription_get_endpoint(), ast_sip_subscription_get_serializer(), ast_sorcery_init(), ast_sorcery_is_object_field_registered(), ast_tcptls_stream_set_exclusive_input(), ast_tcptls_stream_set_timeout_disable(), ast_tcptls_stream_set_timeout_inactivity(), ast_tcptls_stream_set_timeout_sequence(), AST_TEST_DEFINE(), ast_udptl_read(), ast_uuid_to_str(), ast_variable_list_append_hint(), ast_xml_escape(), async_callback(), attended_transfer_bridge(), attended_transfer_monitor_thread(), authenticate(), base_process_bridge_leave(), base_process_dial_end(), base_process_parked_channel(), base_process_party_a(), bridge_action_bridge(), bridge_after_cb(), bridge_agent_hold_push(), bridge_alloc(), bridge_basic_pull(), bridge_basic_push(), bridge_channel_attended_transfer(), bridge_channel_handle_control(), bridge_channel_handle_write(), bridge_channel_internal_push(), bridge_channel_queue_action_data_sync(), bridge_channel_update_accountcodes_joining(), bridge_channel_update_accountcodes_leaving(), bridge_channel_write_frame(), bridge_handle_actions(), bridge_handle_dtmf(), bridge_hash_cb(), bridge_merge_cb(), bridge_merge_inhibit_nolock(), bridge_merge_locked(), bridge_move(), bridge_parking_push(), bridge_publish_state_from_blob(), bridge_snapshot_update(), bridge_stasis_moving(), bridges_channel_hash_fn(), bridges_channel_sort_fn(), bridges_hash(), bucket_file_metadata_hash(), bucket_scheme_hash(), cache_entry_cmp(), cache_entry_create(), cache_entry_dump(), cache_entry_hash(), cache_find(), cache_put(), cache_test_message_create_full(), caching_topic_exec(), call_pickup_to_ami(), cc_generic_agent_start_monitoring(), cc_generic_agent_start_offer_timer(), cc_generic_monitor_cancel_available_timer(), cdr_object_alloc(), cdr_object_channel_cmp_fn(), cdr_object_channel_hash_fn(), cdr_object_create_public_records(), cdr_read_callback(), cel_backend_hash(), cel_channel_linkedid_change(), cel_verify_and_cleanup_cb(), chan_pjsip_get_rtp_peer(), chan_pjsip_get_vrtp_peer(), chan_pjsip_indicate(), channel_dial_cb(), channel_hash(), channel_snapshot_update(), check_callback_sanity(), cli_aor_print_body(), cli_aor_print_header(), cli_channel_print_body(), cli_channel_print_header(), cli_contact_print_body(), cli_contact_print_header(), cli_endpoint_print_body(), cli_endpoint_print_header(), cli_print_body(), cli_print_header(), codec_cmp(), codec_hash(), confbridge_publish_manager_event(), conference_bridge_hash_cb(), consumer_exec(), consumer_exec_sync(), consumer_should_stay(), consumer_wait_for(), consumer_wait_for_completion(), contact_expiration_hash(), control_add_channel_to_bridge(), control_dispatch_all(), control_hash(), control_wait(), create_callno_pools(), create_jb(), create_new_sip_etag(), dahdi_format_to_cached(), dahdi_translate(), datastore_cmp(), datastore_hash(), default_listener_pvt_destroy(), default_listener_shutdown(), default_tps_processing_function(), destroy_bridge(), determine_sip_publish_type(), device_state_alloc(), device_state_subscriptions_cmp(), device_state_subscriptions_hash(), dial_state_process_dial_end(), dial_state_process_party_b(), dialstatus_hash(), dns_find_record(), dns_naptr_alloc(), dns_srv_alloc(), endpoint_cache_clear(), endpoint_cmp(), endpoint_dtor(), endpoint_hash(), endpoint_publish_snapshot(), endpoint_snapshot_dtor(), extension_is_compatible(), featuregroup_hash(), features_pre_apply_config(), find_bridge(), find_channel_control(), find_control(), find_route(), format_cap_replace(), format_cmp_cb(), format_hash_cb(), format_interface_cmp(), format_interface_hash(), forwards_dtor(), forwards_sort(), get_park_common_datastore_copy(), get_unused_callno(), handle_bridge_enter_message(), handle_bridge_leave_message(), handle_channel_cache_message(), handle_cli_confbridge_show_bridge_profile(), handle_conf_user_join(), handle_conf_user_leave(), handle_dial_message(), handle_local_optimization_begin(), handle_new_invite_request(), handle_parked_call_message(), handle_response_publish(), hash_ao2_destroy(), hep_queue_cb(), hold(), holding_bridge_join(), ht_new(), iax2_codec_pref_best_bitfield2cap(), iax2_codec_pref_from_bitfield(), iax2_codec_pref_prepend(), internal_ao2_iterator_next(), internal_ao2_link(), internal_ao2_ref(), internal_ao2_traverse(), INTERNAL_OBJ(), jb_get_and_deliver(), keepalive_transport_hash_fn(), lid_hash(), log_attended_transfer(), logger_queue_start(), manager_notify_uri(), meetme_stasis_cb(), menu_hash_cb(), message_subscription_hash_cb(), moh_post_start(), moh_post_stop(), mwi_sub_hash(), native_bridge_create(), native_bridge_join(), native_bridge_start(), native_bridge_write(), native_chan_changed(), native_request_start(), native_request_stop(), native_start(), native_stop(), object_type_field_hash(), odbc_obj_connect(), one_dtor(), option_handler_parkedfeature(), outbound_publish_state_cmp(), outbound_publish_state_hash(), park_local_transfer(), parked_call_app_exec(), parking_duration_callback(), parking_lot_cfg_create_extensions(), parking_lot_cfg_hash_fn(), participant_entertainment_start(), participant_entertainment_stop(), participant_idle_mode_setup(), payload_helper_cb(), permanent_uri_sort_fn(), play_on_channel(), playback_publish(), print_frame(), process_config(), process_options(), pthread_timer_ack(), publish_corosync_ping_to_stasis(), publish_dahdichannel(), publish_device_state_to_stasis(), publish_expire(), publish_msg(), publish_mwi_to_stasis(), pubsub_on_rx_publish_request(), pubsub_on_rx_subscribe_request(), queue_exec(), queue_stasis_data_destructor(), rb_ao2_destroy(), rb_ao2_insert_node(), rb_delete_fixup(), rb_delete_node(), rb_insert_fixup(), receive_message(), record_file(), recording_publish(), recording_sort(), recurring_resolve(), refer_incoming_invite_request(), regexp_repl_invalid(), registration_state_cmp(), registration_state_hash(), registry_hash_cb(), replace_callno(), resamp_new(), resolution_thread(), ring_entry(), ringing(), route_table_add(), router_dtor(), rx_data_to_ast_msg(), safe_mkdir(), save_dialstatus(), say_parking_space(), sched_qualifies_cmp_fn(), sched_qualifies_hash_fn(), schedule_qualify(), security_event_stasis_cb(), security_event_to_ami_blob(), send_agent_login(), send_agent_logoff(), send_session_timeout(), send_start_msg(), send_start_msg_snapshots(), send_subscription_subscribe(), send_subscription_unsubscribe(), serializer_hash(), session_dtor(), session_media_set_handler(), session_register_app(), set_dial_masquerade(), set_format(), set_target_uri(), setup_invocation_test(), single_state_process_party_b(), sip_cc_agent_init(), sip_cc_monitor_unsuspend(), sip_create_publication(), sip_outbound_registration_response_cb(), softmix_bridge_write(), sorcery_instance_hash(), sorcery_type_hash(), sorcery_wizard_create(), sorcery_wizard_hash(), stasis_app_control_get_snapshot(), stasis_app_exec(), stasis_app_playback_operation(), stasis_cache_dump_all(), stasis_cache_dump_by_eid(), stasis_cache_get_all(), stasis_cache_get_by_eid(), stasis_caching_topic_dtor(), stasis_message_router_add(), stasis_message_router_add_cache_update(), stasis_message_router_publish_sync(), stasis_message_router_remove(), stasis_message_router_remove_cache_update(), stasis_message_router_set_default(), stasis_publish_sync(), stasis_sub_hash(), statsd_init(), stream_periodic_frames(), sub_bridge_update_handler(), sub_channel_update_handler(), sub_endpoint_update_handler(), subscription_dtor(), t38_change_state(), tcptls_stream_dtor(), test_cel_init_cb(), test_handler(), to_json_mem(), topic_dtor(), topic_pool_entry_cmp(), topic_pool_entry_hash(), tos_handler(), uas_use_sips_contact(), uid_hold_hash_fn(), uid_hold_sort_fn(), unhold(), update_create(), user_hash_cb(), wait_bridge_hash_fn(), and wait_bridge_sort_fn().

#define AST_BACKGROUND_STACKSIZE   AST_STACKSIZE

Definition at line 431 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 570 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 598 of file utils.h.

#define ast_clear_flag ( p,
flag   ) 

Examples:
/tmp/asterisk-trunk/trunk/main/app.c.

Definition at line 77 of file utils.h.

Referenced by __analog_ss_thread(), __ast_pbx_run(), __ast_read(), __do_deliver(), __transmit_response(), aco_process_config(), action_redirect(), agent_logout(), analog_ss_thread(), app_exec(), ast_audiohook_set_mute(), ast_autoservice_stop(), ast_bridge_setup_after_goto(), ast_cdr_clear_property(), ast_cdr_fork(), ast_channel_stage_snapshot_done(), ast_channel_undefer_dtmf(), ast_jb_destroy(), ast_jb_put(), ast_readconfig(), ast_rtp_raw_write(), ast_sendtext(), ast_settimeout_full(), ast_speech_start(), AST_TEST_DEFINE(), ast_tls_read_conf(), ast_translate(), ast_unreal_hangup(), ast_waitfor_nandfds(), ast_waitfordigit_full(), ast_write(), bridge_basic_change_personality(), bridge_channel_internal_pull(), bridge_channel_internal_push(), bridge_p2p_rtp_write(), change_hold_state(), change_spy_mode(), channel_do_masquerade(), channel_spy(), chanspy_exec(), check_for_nat(), check_pendings(), common_exec(), conf_announce_channel_depart(), config_function_read(), config_mysql(), 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_cli_debug(), handle_command_response(), handle_common_options(), handle_debug(), handle_exec(), handle_request_bye(), handle_request_invite(), handle_request_refer(), handle_response(), handle_response_notify(), handle_speechrecognize(), handle_t38_options(), init_acf_query(), initialize_udptl(), linear_alloc(), load_config(), load_module(), load_moh_classes(), local_alloc(), local_ast_moh_stop(), local_attended_transfer(), main(), manager_optimize_away(), odbc_load_module(), ooh323_onReceivedSetup(), parse_options(), phone_read(), playtones_alloc(), process_sdp(), register_verify(), reload_config(), reset_transaction(), set_config(), set_config_flags(), set_peer_nat(), setup_dahdi_int(), sip_call(), sip_dtmfmode(), sip_hangup(), sip_parse_nat_option(), sip_reload(), sip_set_rtp_peer(), socket_process_helper(), speech_background(), update_call_counter(), update_connectedline(), video_mode_handler(), and waitstream_core().

#define ast_clear_flag64 ( p,
flag   ) 

#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_flags ( dest,
src,
flagz   ) 

#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_FLAGS_ALL   UINT_MAX

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

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

Parameters:
offset The value that should be increased.
type The 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 922 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 544 of file utils.h.

#define ast_pthread_create ( a,
b,
c,
d   ) 

#define ast_pthread_create_background ( a,
b,
c,
d   ) 

#define ast_pthread_create_detached ( a,
b,
c,
d   ) 

#define ast_pthread_create_detached_background ( a,
b,
c,
d   ) 

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

Returns a random number between 0.0 and 1.0, inclusive.

Since:
12

Definition at line 485 of file utils.h.

Referenced by ast_statsd_log_full(), gen_salt_char(), and qualify_and_schedule_cb().

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

#define ast_set2_flag ( p,
value,
flag   ) 

#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   ) 

Examples:
/tmp/asterisk-trunk/trunk/main/app.c.

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(), agent_login_channel_config(), analog_ss_thread(), announce_request(), app_exec(), apply_peer(), ari_channels_handle_originate_with_id(), ast_audiohook_set_mute(), ast_autoservice_start(), ast_bridge_basic_set_flags(), ast_bridge_features_set_flag(), ast_bridge_timelimit(), ast_call(), ast_call_forward(), ast_cdr_set_property(), ast_channel_defer_dtmf(), ast_channel_destructor(), ast_channel_snapshot_create(), ast_channel_stage_snapshot(), ast_hangup(), ast_http_body_discard(), ast_http_body_read_status(), ast_http_get_contents(), ast_http_request_close_on_completion(), ast_iax2_new(), ast_jb_do_usecheck(), ast_jb_put(), ast_pbx_h_exten_run(), ast_readconfig(), ast_rtp_change_source(), ast_rtp_local_bridge(), ast_rtp_raw_write(), ast_rtp_read(), ast_rtp_stop(), ast_rtp_update_source(), ast_sdp_crypto_process(), ast_settimeout_full(), ast_speech_change_state(), AST_TEST_DEFINE(), ast_tls_read_conf(), ast_unreal_channel_push_to_bridge(), ast_unreal_new_channels(), ast_waitfor_nandfds(), ast_waitfordigit_full(), base_process_parked_channel(), base_process_party_a(), bridge_base_init(), bridge_basic_change_personality(), bridge_exec(), bridge_hook_generic(), bridge_p2p_rtp_write(), build_peer(), cc_generic_agent_init(), cdr_read_callback(), change_hold_state(), change_spy_mode(), channel_do_masquerade(), channel_spy(), chanspy_exec(), check_for_nat(), check_peer_ok(), check_user_full(), check_via(), common_exec(), conf_announce_channel_push(), conf_start_record(), create_addr_from_peer(), create_transaction(), dahdi_new(), dahdiscan_exec(), destroy_trans(), dial_exec_full(), dictate_exec(), directory_exec(), disa_exec(), do_register(), dundi_encrypt(), dundi_lookup_local(), dundi_send(), extensionstate_update(), extenspy_exec(), find_user_realtime(), free_vm_users(), gosub_exec(), gosub_run(), handle_cli_debug(), handle_command_response(), handle_common_options(), handle_debug(), handle_exec(), handle_gosub(), handle_queue_reload(), handle_request_invite(), handle_request_refer(), handle_request_subscribe(), handle_response(), handle_response_invite(), handle_t38_options(), http_request_tracking_setup(), init_acf_query(), init_app_class(), interpret_t38_parameters(), launch_monitor_thread(), leave_voicemail(), linear_alloc(), load_config(), local_alloc(), local_ast_moh_start(), local_attended_transfer(), local_call(), main(), manager_queue_reload(), manager_sipnotify(), media_request_helper(), minivm_greet_exec(), moh_parse_options(), new_outgoing(), odbc_load_module(), onCallCleared(), ooh323_call(), ooh323_hangup(), ooh323_onReceivedSetup(), ooh323_request(), parked_call_retrieve_enable_features(), parse_dtls_attrib(), parse_options(), pbx_outgoing_attempt(), playtones_alloc(), process_cn_rfc3389(), process_sdp(), qualify_peer(), record_exec(), register_verify(), reload_config(), set_bridge_features_on_config(), set_config_flags(), set_feature_flag_from_char(), set_insecure_flags(), set_peer_nat(), set_talk_detect(), single_state_process_dial_begin(), sip_answer(), sip_call(), sip_cc_agent_init(), sip_cc_agent_respond(), sip_cc_monitor_request_cc(), sip_cli_notify(), sip_dtmfmode(), sip_find_peer_full(), sip_hangup(), sip_indicate(), sip_msg_send(), sip_new(), sip_parse_nat_option(), sip_poke_peer(), sip_reinvite_retry(), sip_send_mwi_to_peer(), sip_sendhtml(), sip_set_rtp_peer(), sip_write(), socket_process_helper(), start_spying(), t38_tx_packet_handler(), tonepair_alloc(), transmit_publish(), transmit_register(), transmit_reinvite_with_sdp(), try_calling(), try_merge_optimize_out(), try_swap_optimize_out(), update_call_counter(), update_connectedline(), vm_execmain(), volume_write(), and waitstream_core().

#define ast_set_flag64 ( p,
flag   ) 

#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   ) 

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

Referenced by ast_pthread_create_stack().

#define ast_std_calloc   calloc

Definition at line 515 of file utils.h.

#define ast_std_free   free

#define ast_std_malloc   malloc

Definition at line 514 of file utils.h.

#define ast_std_realloc   realloc

Definition at line 516 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 639 of file utils.h.

#define ast_strdupa (  ) 

duplicate a string in memory from the stack

Parameters:
s The string to duplicate
This macro will duplicate the given string. It returns a pointer to the stack allocatted memory for the new string.
Examples:
/tmp/asterisk-trunk/trunk/main/app.c.

Definition at line 751 of file utils.h.

Referenced by __analog_ss_thread(), __ast_channel_alloc_ap(), __ast_play_and_record(), __dahdi_exception(), _ast_device_state(), _build_port_config(), _iax2_show_peers_one(), _macro_exec(), _parse(), _sip_show_peers_one(), _while_exec(), acf_isexten_exec(), acf_jabberreceive_read(), acf_meetme_info(), acf_odbc_write(), acf_vm_info(), aco_process_var(), action_bridge(), action_dialplan_exec(), action_messagesend(), action_playback(), action_playback_and_continue(), action_status(), actual_load_config(), add_extension(), add_menu_entry(), add_peer_mailboxes(), add_realm_authentication(), add_redirect(), add_transferer_role(), add_var(), add_vm_recipients_from_string(), admin_exec(), advanced_options(), aelsub_exec(), agent_alert(), agent_function_read(), agent_login_channel_config(), agent_login_exec(), agent_request_exec(), agi_exec_full(), agi_handle_command(), ami_sip_qualify(), aMYSQL_clear(), aMYSQL_connect(), aMYSQL_disconnect(), aMYSQL_fetch(), aMYSQL_nextresult(), aMYSQL_query(), aMYSQL_set(), analog_exception(), analog_ss_thread(), answer_exec_enable(), app_exec(), append_mailbox(), append_mailbox_mapping(), append_var_and_value_to_filter(), applicationmap_handler(), apply_options(), apps_handler(), aqm_exec(), ari_channels_handle_originate_with_id(), array(), ast_app_getdata(), ast_append_acl(), ast_append_ha(), ast_ari_channels_redirect(), ast_ari_endpoints_send_message_to_endpoint(), ast_ari_invoke(), ast_bridge_channel_playfile(), ast_bridge_set_after_go_on(), ast_bridge_setup_after_goto(), ast_bridge_timelimit(), ast_bridge_transfer_attended(), ast_bucket_alloc(), ast_bucket_file_alloc(), ast_build_timing(), ast_callerid_split(), ast_cdr_setvar(), ast_channel_connected_line_macro(), ast_channel_connected_line_sub(), ast_channel_redirecting_macro(), ast_channel_redirecting_sub(), ast_channel_yank(), ast_config_hook_unregister(), ast_control_tone(), ast_data_iterator_init(), ast_do_pickup(), ast_eivr_senddtmf(), ast_eivr_setvariable(), ast_el_add_history(), ast_format_cap_update_by_allow_disallow(), ast_format_str_reduce(), ast_func_read(), ast_func_read2(), ast_func_write(), ast_get_chan_applicationmap(), ast_get_group(), ast_get_namedgroups(), ast_ha_join(), ast_iax2_new(), ast_mkdir(), ast_monitor_change_fname(), ast_monitor_start(), ast_msg_send(), ast_multi_channel_blob_get_channels(), ast_ouraddrfor(), ast_parse_arg(), ast_pickup_call(), ast_playtones_start(), ast_presence_state_helper(), ast_register_file_version(), ast_rtcp_read(), ast_rtcp_write_report(), ast_rtp_engine_load_format(), ast_sdp_crypto_process(), ast_sip_auth_vector_init(), ast_sip_for_each_aor(), ast_sip_location_retrieve_contact_and_aor_from_list(), ast_sip_sanitize_xml(), ast_sockaddr_parse(), ast_sockaddr_resolve(), ast_str_retrieve_variable(), AST_TEST_DEFINE(), ast_utils_which(), ast_websocket_uri_cb(), ast_writefile(), asterisk_publication_mailboxstate(), astman_send_error_va(), asyncgoto_exec(), attended_transfer_bridge(), attended_transfer_properties_alloc(), auth_exec(), authenticate_reply(), authenticate_verify(), background_detect_exec(), bridge_agent_hold_push(), bridge_check_monitor(), bridge_exec(), bridge_parking_push(), bridgewait_exec(), bucket_file_wizard_retrieve(), bucket_wizard_retrieve(), build_channels(), build_mapping(), build_peer(), build_profile(), build_radius_record(), build_user(), cache_get_callno_locked(), callerid_read(), callerid_write(), cb_events(), cdr_object_get_by_name(), cdr_prop_write_callback(), cdr_read_callback(), cdr_write_callback(), cel_track_app(), celgenuserevent_exec(), chanavail_exec(), change_callid_pvt(), channel_admin_exec(), channel_do_masquerade(), channel_read_pjsip(), channel_spy(), chanspy_exec(), check_access(), check_blacklist(), check_bridge_play_sound(), check_day(), check_dow(), check_for_nat(), check_month(), check_nonce(), check_peer_ok(), check_switch_expr(), check_timerange(), check_user_full(), cli_display_named_acl(), cli_odbc_read(), cli_odbc_write(), cli_qualify_contacts(), comeback_goto(), complete_meetmecmd_list(), complete_meetmecmd_mute_kick(), conf_exec(), conf_run(), conf_start_moh(), confbridge_exec(), config_function_read(), config_module(), connectedline_read(), connectedline_write(), console_transfer(), controlplayback_exec(), count_exec(), create_addr(), create_addr_from_peer(), create_dynamic_lot_full(), create_followme_number(), create_mwi_subscriptions_for_endpoint(), create_parked_subscription_full(), create_queue_member(), create_sound_blob(), create_vmaccount(), cut_internal(), dahdi_call(), 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(), dialog_info_generate_body_content(), dictate_exec(), directory_exec(), disa_exec(), dnsmgr_refresh(), do_immediate_setup(), do_notify(), do_say(), does_category_match(), dtls_handler(), dundi_query_read(), dundi_result_read(), dundifunc_read(), dynamic_dtmf_hook_trip(), enum_query_read(), enum_result_read(), events_handler(), ewscal_write_event(), exec_exec(), execif_exec(), execute_cb(), execute_state_callback(), expand_gosub_args(), extenspy_exec(), feature_automixmonitor(), feature_automonitor(), feature_blind_transfer(), festival_exec(), fileexists_core(), filehelper(), find_aor(), find_body_generator_accept(), find_conf_realtime(), find_database(), find_generic_monitor_instance_list(), find_sdp(), find_table(), find_table_cb(), forkcdr_exec(), forked_invite_init(), forward_message(), func_confbridge_helper(), func_confbridge_info(), function_iaxpeer(), function_ooh323_write(), function_realtime_store(), generate_parked_user(), generic_recall(), get_cid_name(), get_destination(), get_outbound_endpoint(), get_refer_info(), gosub_exec(), gosub_run(), gosubif_exec(), grab_transfer(), h263_parse_sdp_fmtp(), h264_parse_sdp_fmtp(), handle_call_forward(), handle_call_outgoing(), handle_cli_check_permissions(), handle_cli_dialplan_add_extension(), handle_cli_file_convert(), handle_cli_iax2_show_peer(), handle_cli_presencestate_change(), handle_common_options(), handle_debug(), handle_debug_dialplan(), handle_gosub(), handle_mgcp_audit_endpoint(), handle_options(), handle_request_bye(), handle_request_invite(), handle_request_notify(), handle_request_refer(), handle_request_subscribe(), handle_response(), handle_show_dialplan(), handle_t38_options(), handle_updates(), hangupcause_read(), hook_callback(), hook_on(), iax2_call(), iax2_devicestate(), iax2_prov_app(), iax2_request(), iconv_read(), ident_handler(), init_acf_query(), init_jack_data(), insert_penaltychange(), ip_identify_match_handler(), is_prefix(), is_valid_dtmf(), isAnsweringMachine(), isexten_function_read(), ivr_dispatch(), jack_handler(), jb_helper(), jingle_request(), json_array_from_list(), launch_ha_netscript(), launch_monitor_thread(), launch_netscript(), leave_voicemail(), limits_interval_playback(), list_item_handler(), load_channelvars(), load_config(), local_alloc(), local_call(), local_devicestate(), localnet_to_vl(), log_exec(), lua_get_variable_value(), lua_pbx_exec(), lua_set_variable_value(), macroif_exec(), main(), make_components(), make_email_file(), man_do_variable_value(), manager_bridges_list(), manager_dialplan_extension_add(), manager_dialplan_extension_remove(), manager_mixmonitor(), match_to_var_list(), mbl_call(), mbl_devicestate(), mbl_request(), mbl_sendsms_exec(), mbl_status_exec(), meetmemute(), message_received_handler(), messagecount(), metermaidstate(), mgcp_devicestate(), mgcp_ss(), 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(), moh_handle_digit(), monitor_dial(), msg_create_from_file(), msg_send_exec(), multicast_rtp_request(), mwi_has_voicemail(), mwi_inboxcount(), mwi_on_aor(), mwi_sub_event_cb(), mwi_to_event(), mwi_validate_for_aor(), my_load_module(), mysql_log(), notify_endpoint(), notify_new_message(), odbc_log(), on_dns_update_mwi(), on_dns_update_peer(), on_dns_update_registry(), on_endpoint(), orig_app(), orig_exten(), origin_allowed(), originate_exec(), ospauth_exec(), ospfinished_exec(), osplookup_exec(), ospnext_exec(), oss_call(), oss_request(), page_exec(), park_and_announce_app_exec(), park_app_exec(), park_app_parse_data(), park_common_setup(), parked_call_app_exec(), parked_user_set_parker_dial_string(), parking_duration_callback(), parking_park_call(), parse_allowed_methods(), parse_cookies(), parse_empty_options(), parse_hint_device(), parse_hint_presence(), 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_saycharacters_case(), pbx_builtin_setvar(), pbx_builtin_setvar_helper(), pbx_builtin_setvar_multiple(), pbx_builtin_waitexten(), pbx_extension_helper(), pbx_find_extension(), pbx_parseable_goto(), pbx_retrieve_variable(), peer_set_srcaddr(), permanent_uri_handler(), persistent_endpoint_contact_observer(), pickup_exec(), pickupchan_exec(), pidf_allocate_body(), pjsip_acf_channel_read(), pjsip_acf_dial_contacts_read(), pjsip_aor_function_read(), pjsip_contact_function_read(), pjsip_endpoint_function_read(), play_files_helper(), play_message(), play_moh_exec(), playback_exec(), pqm_exec(), prep_email_sub_vars(), presence_read(), presence_write(), privacy_exec(), process_dahdi(), process_echocancel(), process_sdp(), process_sdp_a_image(), process_sdp_o(), proxy_from_config(), pvt_cause_cmp_fn(), pvt_cause_hash_fn(), ql_exec(), qualify_and_schedule_all_cb(), queue_exec(), queue_function_queuegetchannel(), queue_mwi_event(), queue_set_param(), rcvfax_exec(), read_exec(), readexten_exec(), realtime_common(), realtime_exec(), realtime_is_object_matching(), realtime_multi_curl(), realtime_multi_ldap(), realtime_multi_mysql(), realtime_multi_odbc(), realtime_multi_pgsql(), realtime_peer(), realtime_update_peer(), realtime_user(), receive_message(), receivefax_exec(), record_exec(), redirecting_read(), redirecting_write(), register_verify(), registrar_on_rx_request(), registry_authrequest(), reload_config(), reload_followme(), reload_single_member(), remoteconsolehandler(), remove_trailing_slash(), report_receive_fax_status(), report_send_fax_status(), request(), resetcdr_exec(), resource_name_match(), retrydial_exec(), rqm_exec(), rtcp_do_debug_ip(), rtp_do_debug_ip(), rx_task(), saycountedadj_exec(), saycountednoun_exec(), sayunixtime_exec(), send_dial_tone(), send_unsolicited_mwi_notify(), senddtmf_exec(), sendfax_exec(), sendmail(), sendurl_exec(), set_bridge_peer_vars_multiparty(), set_hangup_source_and_cause(), set_transfer_variables_all(), set_var_handler(), setup_mixmonitor(), setup_park_common_datastore(), setup_peer_after_bridge_goto(), setup_privacy_args(), setup_stunaddr(), sip_acf_channel_read(), sip_allow_anyrtp_remote(), sip_devicestate(), sip_get_cc_information(), sip_msg_send(), sip_new(), sip_parse_nat_option(), 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_helper(), softhangup_exec(), sorcery_config_open(), sorcery_function_read(), sort_internal(), speech_background(), speech_load(), srv_result_read(), stackpeek_read(), start_automixmonitor(), start_automonitor(), start_moh_exec(), start_monitor_action(), start_monitor_exec(), stasis_app_bridge_create(), stasis_app_stored_recording_copy(), state_notify_build_xml(), stop_mixmonitor_full(), stun_monitor_request(), talk_detect_fn_write(), timezone_add(), transfer_exec(), transmit_invite(), transport_tls_cipher_handler(), try_calling(), try_suggested_sip_codec(), tryexec_exec(), uac_sips_contact(), uas_sips_contact(), unicast_rtp_request(), update_registry(), upqm_exec(), user_event_hook_cb(), userevent_exec(), verbose_exec(), vm_box_exists(), vm_check_password_shell(), vm_exec(), vm_execmain(), vm_playmsgexec(), vm_sayname(), vmauthenticate(), vmsayname_exec(), wait_for_answer(), wait_for_winner(), waitstream_core(), wizard_apply_handler(), xmpp_client_authenticate_sasl(), xmpp_join_exec(), xmpp_leave_exec(), xmpp_send_cb(), xmpp_send_exec(), xmpp_sendgroup_exec(), xmpp_status_exec(), xpidf_allocate_body(), 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 671 of file utils.h.

#define ast_test_flag ( p,
flag   ) 

Definition at line 63 of file utils.h.

Referenced by __ast_pbx_run(), __ast_queue_frame(), __ast_read(), __sip_alloc(), __sip_destroy(), __ssl_setup(), __transmit_response(), _ast_odbc_request_obj2(), _macro_exec(), _sip_show_peer(), _sip_show_peers_one(), acf_odbc_read(), acquire_bridge(), action_bridge(), action_confbridgelist_item(), action_kick_last(), action_login(), action_toggle_mute_participants(), add_codec_to_sdp(), add_rpid(), add_sdp(), add_supported(), agent_alert(), agent_login_exec(), agent_request_exec(), app_exec(), ast_async_goto(), ast_audiohook_write_frame(), ast_autoservice_start(), ast_bridge_channel_playfile(), ast_bridge_impart(), ast_bridge_join(), ast_bridge_setup_after_goto(), ast_bridge_transfer_attended(), ast_bridge_transfer_blind(), ast_call(), ast_can_pickup(), ast_cdr_engine_reload(), ast_cdr_engine_term(), ast_cdr_fork(), ast_cdr_is_enabled(), ast_cdr_serialize_variables(), ast_channel_defer_dtmf(), ast_channel_destructor(), ast_channel_end_dtmf(), ast_channel_move(), ast_channel_publish_snapshot(), ast_config_internal_load(), ast_explicit_goto(), ast_frisolate(), ast_hangup(), ast_http_body_discard(), ast_http_body_read_status(), ast_http_get_contents(), ast_http_send(), ast_indicate_data(), ast_jb_destroy(), ast_jb_do_usecheck(), ast_jb_empty_and_reset(), ast_jb_enable_for_channel(), ast_jb_get_and_deliver(), ast_jb_get_when_to_wakeup(), ast_jb_put(), ast_local_setup_bridge(), ast_local_setup_masquerade(), ast_moh_files_next(), ast_pbx_h_exten_run(), ast_pbx_run_args(), ast_pbx_start(), ast_raw_answer(), ast_readstring_full(), ast_rtp_raw_write(), ast_sdp_srtp_get_attrib(), ast_sendtext(), ast_setstate(), ast_settimeout_full(), ast_softhangup_nolock(), ast_streamfile(), AST_TEST_DEFINE(), ast_transfer(), ast_translate(), ast_unreal_hangup(), ast_unreal_indicate(), ast_uri_decode(), ast_uri_encode(), ast_waitfordigit_full(), ast_write(), attempt_thread(), auth_exec(), authenticate_verify(), base_process_party_a(), bridge_agent_hold_heartbeat(), bridge_agent_hold_push(), bridge_allows_optimization(), bridge_channel_dissolve_check(), bridge_channel_do_callback(), bridge_channel_handle_control(), bridge_channel_handle_interval(), bridge_channel_internal_join(), bridge_channel_internal_pull(), bridge_channel_internal_push(), bridge_config_set_limits(), bridge_dissolve_check_stolen(), bridge_do_merge(), bridge_exec(), bridge_merge_determine_direction(), bridge_merge_locked(), bridge_move_locked(), bridge_p2p_rtp_write(), bridge_reconfigured(), bridge_reconfigured_connected_line_update(), bridge_stasis_pull(), bridge_stasis_push(), bridge_state_process_party_b(), bridge_swap_attended_transfer(), bridges_allow_merge_optimization(), bridges_allow_swap_optimization(), build_path(), build_peer(), build_radius_record(), build_via(), builtin_features_helper(), call_forward_inherit(), cdr_detach(), cdr_object_check_party_a_hangup(), cdr_object_get_billsec(), cdr_object_pick_party_a(), cdr_object_set_disposition(), cdr_read_callback(), cdr_submit_batch(), cdr_toggle_runtime_options(), cel_channel_state_change(), change_hold_state(), channel_data_add_flags(), channel_do_masquerade(), channel_newexten(), channel_spy(), channel_state_change(), chanspy_exec(), check_for_nat(), check_new_cdr_needed(), check_peer_ok(), check_pendings(), check_rtp_timeout(), check_user_full(), close_mailbox(), comedia_string(), common_exec(), complete_sip_peer(), complete_sip_registered_peer(), conf_announce_channel_depart(), conf_handle_inactive_waitmarked(), conf_handle_only_unmarked(), conf_handle_second_active(), conf_handle_talker_cb(), conf_mute_moh_inactive_waitmarked(), conf_mute_only_active(), conf_rec_name(), conf_update_user_mute(), confbridge_exec(), config_text_file_load(), connectedline_write(), controlplayback_exec(), copy_via_headers(), create_addr_from_peer(), create_jb(), destroy_trans(), dial_state_process_party_b(), dial_status_to_disposition(), dialog_initialize_rtp(), dictate_exec(), directory_exec(), disa_exec(), display_nat_warning(), do_directory(), do_monitor(), do_setnat(), dtmf_audiohook_write_list(), dtmf_features_flags_to_string(), 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(), dynamic_dtmf_hook_trip(), eivr_comm(), enable_dsp_detect(), execute_cb(), execute_menu_entry(), expire_register(), extensionstate_update(), extenspy_exec(), fax_gateway_framehook(), finalized_state_process_party_a(), find_cache(), find_or_create(), find_user(), find_user_realtime(), findmeexec(), force_rport_string(), forward_message(), free_user(), func_confbridge_info(), function_sippeer(), generic_mute_unmute_helper(), get_destination(), get_insecure_variable_from_config(), get_insecure_variable_from_sipregs(), get_rpid(), get_sip_pvt_from_replaces(), gosub_exec(), gosub_run(), got_optimized_out(), handle_cli_confbridge_list_item(), handle_cli_debug(), handle_cli_moh_show_classes(), handle_cli_status(), handle_cli_submit(), handle_cli_wait_fullybooted(), handle_command_response(), handle_conf_user_join(), handle_conf_user_leave(), 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_message(), handle_response_notify(), handle_show_settings(), handle_skinny_show_settings(), handle_speechrecognize(), handle_tcptls_connection(), handle_video_on_exit(), handle_video_on_join(), hint_read(), hook_event_cb(), hook_remove_match(), hooks_remove_heap(), httpd_process_request(), iax2_write(), initialize_udptl(), initreqprep(), interpret_t38_parameters(), is_state_change_valid(), join_conference_bridge(), kick_conference_participant(), leave_marked(), leave_voicemail(), limits_interval_playback(), load_module(), load_resource(), local_alloc(), local_ast_moh_start(), local_devicestate(), main(), make_email_file(), manager_list_voicemail_users(), manager_mixmonitor(), match_nat_options(), match_req_to_dialog(), minivm_accmess_exec(), minivm_account_func_read(), minivm_greet_exec(), minivm_notify_exec(), minivm_record_exec(), mixmonitor_exec(), mixmonitor_save_prep(), mixmonitor_thread(), mod_load_cmp(), moh_files_alloc(), moh_scan_files(), multicast_rtp_write(), notify_new_message(), odbc_load_module(), onCallCleared(), onCallEstablished(), ooh323_destroy(), ooh323_get_rtp_peer(), ooh323_hangup(), ooh323_indicate(), ooh323_new(), ooh323_write(), optimize_lock_chan_stack(), optimize_lock_peer_stack(), page_exec(), park_app_parse_data(), parse_moved_contact(), parse_register_contact(), pbx_builtin_background(), pbx_builtin_waitexten(), peer_ipcmp_cb_full(), pickupchan_exec(), play_mailbox_owner(), play_message(), play_record_review(), post_cdr(), precache_transactions(), process_cn_rfc3389(), process_crypto(), process_options(), process_sdp(), process_sdp_a_audio(), process_sdp_o(), process_text_line(), publish_local_bridge_message(), queue_exec(), read_exec(), readexten_exec(), realtime_peer(), realtime_switch_common(), receivefax_exec(), record_dtmf_response(), record_exec(), redirecting_write(), reload_config(), reload_handler(), reload_queues(), reload_single_queue(), remove_from_queue(), reqprep(), resetcdr_exec(), respprep(), retrans_pkt(), retrydial_exec(), return_exec(), search_directory_sub(), select_entry(), select_item_pause(), send_join_event(), send_leave_event(), send_mute_event(), send_request(), send_unmute_event(), sendfax_exec(), sendmail(), sendurl_exec(), serialize_showchan(), set_address_from_contact(), set_config_flags(), set_peer_nat(), set_pvt_allowed_methods(), set_rec_filename(), set_t38_capabilities(), setup_mixmonitor_ds(), setup_peer_after_bridge_goto(), setup_profile_bridge(), setup_profile_caller(), setup_profile_paged(), should_skip_dtmf(), show_channels_cb(), sip_allow_anyrtp_remote(), 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_vrtp_peer(), sip_hangup(), sip_indicate(), sip_nat_mode(), sip_new(), sip_parse_nat_option(), sip_peer_hold(), sip_prune_realtime(), sip_queryoption(), sip_read(), sip_real_dst(), sip_request_call(), sip_rtp_read(), sip_send_mwi_to_peer(), sip_senddigit_begin(), sip_senddigit_end(), sip_sendhtml(), sip_set_rtp_peer(), sip_setoption(), sip_show_channel(), sip_show_settings(), sip_show_users(), sip_write(), sla_trunk_exec(), smart_bridge_operation(), smdi_msg_find(), sms_exec(), snapshot_cep_changed(), snapshot_is_dialed(), socket_process_helper(), socket_process_meta(), softhangup_exec(), spawn_mp3(), speech_background(), speech_read(), spy_generate(), start_monitor_exec(), transition_to_marked(), 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(), try_merge_optimize_out(), try_swap_optimize_out(), unreal_queue_indicate(), update_call_counter(), update_connectedline(), update_peer(), update_redirecting(), update_registry(), vm_exec(), vm_execmain(), vm_instructions_en(), vm_instructions_ja(), vm_intro(), vm_newuser(), volume_callback(), wait_for_winner(), waitstream_core(), xmpp_action_hook(), xmpp_cli_purge_pubsub_nodes(), xmpp_client_authenticate(), xmpp_client_config_post_apply(), xmpp_client_reconnect(), xmpp_client_send_message(), xmpp_client_set_group_presence(), xmpp_client_thread(), xmpp_config_prelink(), xmpp_connect_hook(), xmpp_join_exec(), xmpp_leave_exec(), xmpp_log_hook(), xmpp_pak_message(), xmpp_pak_presence(), xmpp_pak_s10n(), xmpp_pubsub_build_publish_skeleton(), xmpp_pubsub_handle_error(), xmpp_pubsub_publish_device_state(), xmpp_pubsub_subscribe(), xmpp_roster_hook(), xmpp_send_stream_header(), and xmpp_sendgroup_exec().

#define ast_test_flag64 ( p,
flag   ) 

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

#define AST_URI_ALPHANUM   (1 << 0)

Definition at line 253 of file utils.h.

Referenced by ast_uri_encode().

#define AST_URI_LEGACY_SPACE   (1 << 2)

Definition at line 256 of file utils.h.

Referenced by ast_uri_decode(), and ast_uri_encode().

#define AST_URI_MARK   (1 << 1)

Definition at line 254 of file utils.h.

Referenced by ast_uri_encode().

#define AST_URI_SIP_USER_UNRESERVED   (1 << 20)

Definition at line 258 of file utils.h.

Referenced by ast_uri_encode().

#define AST_URI_UNRESERVED   (AST_URI_ALPHANUM | AST_URI_MARK)

Definition at line 255 of file utils.h.

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

#define DEBUG_CHAOS_RETURN ( c,
f   ) 

DEBUG_CHAOS returns failure randomly.

DEBUG_CHAOS_RETURN(failure); can be used to fake failure of functions such as memory allocation, for the purposes of testing failure handling.

Definition at line 509 of file utils.h.

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

Checks to see if value is within the given bounds.

Parameters:
v the value to check
min minimum lower bound (inclusive)
max maximum upper bound (inclusive)
Returns:
0 if value out of bounds, otherwise true (non-zero)

Definition at line 810 of file utils.h.

#define localtime_r   __dont_use_localtime_r_use_ast_localtime_instead__

Definition at line 386 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 532 of file utils.h.

Referenced by _ast_asprintf().

#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   ) 

Value:

auto void _dtor_ ## varname (vartype * v);                                 \
    void _dtor_ ## varname (vartype * v) { dtor(*v); }                         \
    vartype varname __attribute__((cleanup(_dtor_ ## varname))) = (initval)
Declare a variable that will call a destructor function when it goes out of scope.

Resource Allocation Is Initialization (RAII) variable declaration.

Since:
11.0
Parameters:
vartype The type of the variable
varname The name of the variable
initval The initial value of the variable
dtor The 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);
 }
Examples:
/tmp/asterisk-trunk/trunk/main/app.c.

Definition at line 1050 of file utils.h.

Referenced by __allocate_taskprocessor(), __analog_ss_thread(), __ast_bucket_scheme_register(), __ast_http_load(), __ast_manager_event_multichan(), __ast_play_and_record(), __ast_register_translator(), __ast_sorcery_apply_config(), __ast_sorcery_apply_default(), __ast_sorcery_apply_wizard_mapping(), __ast_sorcery_object_field_register(), __ast_sorcery_object_register(), __ast_udptl_reload(), __ast_vm_greeter_register(), __ast_vm_register(), __expire_registry(), __features_config_alloc(), __iax2_poke_noanswer(), __test_cel_generate_peer_str(), _skinny_show_lines(), acf_jabberreceive_read(), acf_jabberstatus_read(), acl_on_rx_msg(), aco_process_var(), aco_set_defaults(), action_agents(), action_blind_transfer(), action_bridge(), action_coreshowchannels(), action_devicestatelist(), action_presencestatelist(), active_channels_to_str(), add_crypto_to_stream(), add_datastore(), add_format_information_cb(), add_header(), add_item(), add_mwi_datastore(), add_sdp(), add_sdp_streams(), add_session_media(), add_transferer_role(), admin_exec(), adsi_transmit_message_full(), after_bridge_move_channel(), after_bridge_move_channel_fail(), agent_login_exec(), agent_login_to_ami(), agent_logoff_request(), agent_logoff_to_ami(), agent_request_exec(), agents_post_apply_config(), agi_channel_to_ami(), agi_handle_command(), alloc_security_event_json_object(), alloc_variant(), ami_outbound_registration_task(), ami_register(), ami_registrations_aor(), ami_registrations_endpoints(), ami_show_endpoint(), ami_show_endpoints(), ami_show_outbound_registrations(), ami_sip_qualify(), ami_unregister(), analog_publish_channel_alarm_clear(), analog_publish_dnd_state(), analog_ss_thread(), announce_request(), anonymous_identify(), app_control_dial(), app_create(), app_exec(), app_handle_subscriptions(), app_is_subscribed_bridge_id(), app_is_subscribed_channel_id(), app_is_subscribed_endpoint_id(), app_send(), app_send_command_on_condition(), app_subscribe(), app_subscribe_bridge(), app_subscribe_channel(), app_subscribe_endpoint(), app_to_json(), app_update(), append_channel_vars(), append_event(), append_expected_event(), append_expected_event_snapshot(), applicationmap_handler(), apply_negotiated_sdp_stream(), ari_bridges_handle_play(), ari_bridges_play_found(), ari_bridges_play_helper(), ari_bridges_play_new(), ari_channels_handle_originate_with_id(), ari_channels_handle_play(), ari_channels_handle_snoop_channel(), ari_mkpasswd(), ari_show(), ari_show_user(), ari_show_users(), assign_uuid(), ast_ari_add_handler(), ast_ari_applications_get_cb(), ast_ari_applications_list(), ast_ari_applications_list_cb(), ast_ari_applications_subscribe(), ast_ari_applications_subscribe_cb(), ast_ari_applications_unsubscribe(), ast_ari_applications_unsubscribe_cb(), ast_ari_asterisk_get_global_var(), ast_ari_asterisk_get_global_var_cb(), ast_ari_asterisk_get_info(), ast_ari_asterisk_get_info_cb(), ast_ari_asterisk_set_global_var_cb(), ast_ari_bridges_add_channel(), ast_ari_bridges_add_channel_cb(), ast_ari_bridges_create(), ast_ari_bridges_create_cb(), ast_ari_bridges_create_with_id(), ast_ari_bridges_create_with_id_cb(), ast_ari_bridges_destroy(), ast_ari_bridges_destroy_cb(), ast_ari_bridges_get(), ast_ari_bridges_get_cb(), ast_ari_bridges_list(), ast_ari_bridges_list_cb(), ast_ari_bridges_play_cb(), ast_ari_bridges_play_with_id_cb(), ast_ari_bridges_record(), ast_ari_bridges_record_cb(), ast_ari_bridges_remove_channel(), ast_ari_bridges_remove_channel_cb(), ast_ari_bridges_start_moh(), ast_ari_bridges_start_moh_cb(), ast_ari_bridges_stop_moh(), ast_ari_bridges_stop_moh_cb(), ast_ari_callback(), ast_ari_channels_answer(), ast_ari_channels_answer_cb(), ast_ari_channels_continue_in_dialplan(), ast_ari_channels_continue_in_dialplan_cb(), ast_ari_channels_get(), ast_ari_channels_get_cb(), ast_ari_channels_get_channel_var(), ast_ari_channels_get_channel_var_cb(), ast_ari_channels_hangup(), ast_ari_channels_hangup_cb(), ast_ari_channels_hold(), ast_ari_channels_hold_cb(), ast_ari_channels_list(), ast_ari_channels_list_cb(), ast_ari_channels_mute(), ast_ari_channels_mute_cb(), ast_ari_channels_originate_cb(), ast_ari_channels_originate_with_id_cb(), ast_ari_channels_play_cb(), ast_ari_channels_play_with_id_cb(), ast_ari_channels_record(), ast_ari_channels_record_cb(), ast_ari_channels_redirect(), ast_ari_channels_redirect_cb(), ast_ari_channels_ring(), ast_ari_channels_ring_cb(), ast_ari_channels_ring_stop(), ast_ari_channels_ring_stop_cb(), ast_ari_channels_send_dtmf(), ast_ari_channels_send_dtmf_cb(), ast_ari_channels_set_channel_var(), ast_ari_channels_set_channel_var_cb(), ast_ari_channels_snoop_channel_cb(), ast_ari_channels_snoop_channel_with_id_cb(), ast_ari_channels_start_moh(), ast_ari_channels_start_moh_cb(), ast_ari_channels_start_silence(), ast_ari_channels_start_silence_cb(), ast_ari_channels_stop_moh(), ast_ari_channels_stop_moh_cb(), ast_ari_channels_stop_silence(), ast_ari_channels_stop_silence_cb(), ast_ari_channels_unhold(), ast_ari_channels_unhold_cb(), ast_ari_channels_unmute(), ast_ari_channels_unmute_cb(), ast_ari_config_validate_user(), ast_ari_device_states_delete_cb(), ast_ari_device_states_get_cb(), ast_ari_device_states_list_cb(), ast_ari_device_states_update_cb(), ast_ari_endpoints_get(), ast_ari_endpoints_get_cb(), ast_ari_endpoints_list(), ast_ari_endpoints_list_by_tech(), ast_ari_endpoints_list_by_tech_cb(), ast_ari_endpoints_list_cb(), ast_ari_endpoints_send_message_cb(), ast_ari_endpoints_send_message_to_endpoint_cb(), ast_ari_events_event_websocket_ws_cb(), ast_ari_events_user_event_cb(), ast_ari_get_docs(), ast_ari_invoke(), ast_ari_json_format(), ast_ari_mailboxes_delete_cb(), ast_ari_mailboxes_get_cb(), ast_ari_mailboxes_list_cb(), ast_ari_mailboxes_update_cb(), ast_ari_playbacks_control(), ast_ari_playbacks_control_cb(), ast_ari_playbacks_get(), ast_ari_playbacks_get_cb(), ast_ari_playbacks_stop(), ast_ari_playbacks_stop_cb(), ast_ari_recordings_cancel_cb(), ast_ari_recordings_copy_stored(), ast_ari_recordings_copy_stored_cb(), ast_ari_recordings_delete_stored(), ast_ari_recordings_delete_stored_cb(), ast_ari_recordings_get_live(), ast_ari_recordings_get_live_cb(), ast_ari_recordings_get_stored(), ast_ari_recordings_get_stored_cb(), ast_ari_recordings_list_stored(), ast_ari_recordings_list_stored_cb(), ast_ari_recordings_mute_cb(), ast_ari_recordings_pause_cb(), ast_ari_recordings_stop_cb(), ast_ari_recordings_unmute_cb(), ast_ari_recordings_unpause_cb(), ast_ari_remove_handler(), ast_ari_response_error(), ast_ari_sounds_get_cb(), ast_ari_sounds_list(), ast_ari_sounds_list_cb(), ast_ari_websocket_events_event_websocket(), ast_ari_websocket_session_create(), ast_ari_websocket_session_read(), ast_ari_websocket_session_write(), ast_bridge_add_channel(), ast_bridge_blob_create(), ast_bridge_merge_message_to_json(), ast_bridge_publish_attended_transfer(), ast_bridge_publish_enter(), ast_bridge_publish_leave(), ast_bridge_publish_merge(), ast_bridge_publish_state(), ast_bridge_snapshot_create(), ast_bridge_snapshot_get_latest(), ast_bridge_snapshot_to_json(), ast_bridge_transfer_attended(), ast_bridge_transfer_blind(), ast_bucket_alloc(), ast_bucket_file_alloc(), ast_bucket_file_copy(), ast_bucket_file_json(), ast_bucket_file_metadata_set(), ast_bucket_file_metadata_unset(), ast_bucket_json(), ast_cdr_clear_property(), ast_cdr_engine_reload(), ast_cdr_engine_term(), ast_cdr_fork(), ast_cdr_get_config(), ast_cdr_getvar(), ast_cdr_is_enabled(), ast_cdr_reset(), ast_cdr_serialize_variables(), ast_cdr_set_config(), ast_cdr_set_property(), ast_cdr_setuserfield(), ast_cel_backend_register(), ast_cel_create_event(), ast_cel_fabricate_channel_from_event(), ast_cel_general_config_alloc(), ast_cel_get_config(), ast_cel_track_event(), ast_channel_blob_create(), ast_channel_blob_create_from_cache(), ast_channel_data_add_structure(), ast_channel_get_manager_vars(), ast_channel_get_vars(), ast_channel_make_compatible_helper(), ast_channel_publish_dial_internal(), ast_channel_publish_snapshot(), ast_channel_snapshot_get_latest(), ast_channel_snapshot_get_latest_by_name(), ast_channel_snapshot_to_json(), ast_channel_suppress(), ast_complete_channels(), ast_delete_mwi_state_full(), ast_destroy_realtime(), ast_do_pickup(), ast_endpoint_blob_create(), ast_endpoint_blob_publish(), ast_endpoint_latest_snapshot(), ast_endpoint_shutdown(), ast_endpoint_snapshot_create(), ast_endpoint_snapshot_to_json(), ast_get_builtin_feature(), ast_get_chan_applicationmap(), ast_get_chan_featuremap_config(), ast_get_chan_features_general_config(), ast_get_chan_features_pickup_config(), ast_get_chan_features_xfer_config(), ast_get_feature(), ast_http_get_json(), ast_http_get_post_vars(), ast_json_party_id(), ast_load_realtime(), ast_load_realtime_all(), ast_load_realtime_multientry(), ast_manager_event_blob_create(), ast_manager_publish_event(), ast_media_get_description(), ast_media_get_format_cap(), ast_media_get_media(), ast_media_get_variants(), ast_media_index_create(), ast_monitor_start(), ast_monitor_stop(), ast_multi_channel_blob_add_channel(), ast_multi_channel_blob_create(), ast_multi_channel_blob_get_channels(), ast_multi_object_blob_create(), ast_multi_object_blob_single_channel_publish(), ast_mwi_blob_create(), ast_mwi_create(), ast_named_acl_find(), ast_parked_call_payload_create(), ast_parking_blind_transfer_park(), ast_parking_is_exten_park(), ast_parking_park_bridge_channel(), ast_parking_park_call(), ast_parking_provider_registered(), ast_parking_register_bridge_features(), ast_parking_unregister_bridge_features(), ast_phoneprov_add_extension(), ast_pickup_call(), ast_publish_channel_state(), ast_publish_device_state_full(), ast_publish_mwi_state_full(), ast_queue_hangup_with_cause(), ast_request(), ast_rtcp_read(), ast_rtcp_write_report(), ast_rtp_publish_rtcp_message(), ast_rtp_read(), ast_safe_mkdir(), ast_set_hangupsource(), ast_sip_cli_traverse_objects(), ast_sip_default_outbound_endpoint(), ast_sip_for_each_aor(), ast_sip_for_each_auth(), ast_sip_for_each_channel(), ast_sip_for_each_channel_snapshot(), ast_sip_for_each_contact(), ast_sip_initialize_system(), ast_sip_location_add_contact(), ast_sip_location_retrieve_first_aor_contact(), ast_sip_publish_client_alloc_datastore(), ast_sip_publish_client_get(), ast_sip_session_alloc(), ast_sip_session_alloc_datastore(), ast_sip_session_create_outgoing(), ast_sip_session_register_sdp_handler(), ast_sip_sorcery_object_to_ami(), ast_sip_subscription_alloc_datastore(), ast_softhangup(), ast_sorcery_alloc(), ast_sorcery_copy(), ast_sorcery_create(), ast_sorcery_delete(), ast_sorcery_diff(), ast_sorcery_load_object(), ast_sorcery_object_fields_register(), ast_sorcery_object_set_copy_handler(), ast_sorcery_object_set_diff_handler(), ast_sorcery_object_set_extended(), ast_sorcery_objectset_apply(), ast_sorcery_objectset_create2(), ast_sorcery_objectset_json_create(), ast_sorcery_observer_add(), ast_sorcery_observer_remove(), ast_sorcery_reload_object(), ast_sorcery_retrieve_by_fields(), ast_sorcery_retrieve_by_id(), ast_sorcery_retrieve_by_regex(), ast_sorcery_update(), ast_sorcery_wizard_observer_add(), ast_sorcery_wizard_observer_remove(), ast_sounds_reindex(), ast_speech_new(), ast_statsd_log_full(), ast_store_realtime(), ast_system_publish_registry(), AST_TEST_DEFINE(), ast_threadpool_create(), ast_threadpool_serializer(), ast_translator_best_choice(), ast_udptl_new_with_bindaddr(), ast_unreal_channel_push_to_bridge(), ast_unreal_new_channels(), ast_update2_realtime(), ast_update_realtime(), ast_xmpp_client_find(), asterisk_publication_devicestate_state_change(), asterisk_publication_mwi_state_change(), asterisk_publication_new(), asterisk_start_devicestate_publishing(), asterisk_start_mwi_publishing(), asterisk_stop_devicestate_publishing(), asterisk_stop_mwi_publishing(), attach_barge(), attempt_transfer(), attended_transfer_bridge(), attended_transfer_properties_alloc(), attended_transfer_to_ami(), attended_transfer_to_json(), authenticate(), authenticate_api_key(), authenticate_user(), background_detect_exec(), base_process_party_a(), blind_transfer_to_ami(), bridge_agent_hold_deferred_create(), bridge_agent_hold_push(), bridge_builtin_set_limits(), bridge_candidate_add_to_cdr(), bridge_candidate_process(), bridge_channel_attended_transfer(), bridge_channel_internal_queue_attended_transfer(), bridge_channel_internal_queue_blind_transfer(), bridge_merge_cb(), bridge_merge_message_create(), bridge_moh_create(), bridge_move(), bridge_p2p_rtp_write(), bridge_parking_pull(), bridge_parking_push(), bridge_publish_state_from_blob(), bridge_show_specific_print_channel(), bridge_snapshot_update(), bridge_stasis_moving(), bridge_stasis_run_cb(), bucket_alloc(), bucket_file_alloc(), bucket_file_wizard_retrieve(), bucket_wizard_retrieve(), build_ami_notify(), build_cli_notify(), build_nonce(), build_resource_tree(), cache_test_message_create_full(), call_pickup_to_ami(), cb_events(), cc_publish(), cc_publish_available(), cc_publish_callerrecalling(), cc_publish_callerstartmonitoring(), cc_publish_callerstopmonitoring(), cc_publish_failure(), cc_publish_monitorfailed(), cc_publish_offertimerstart(), cc_publish_recallcomplete(), cc_publish_requestacknowledged(), cc_publish_requested(), cdr_detach(), cdr_object_alloc(), cdr_object_check_party_a_answer(), cdr_object_check_party_a_hangup(), cdr_object_dispatch(), cdr_object_get_billsec(), cdr_object_set_disposition(), cdr_object_transition_state(), cdr_prop_write(), cdr_read(), cdr_submit_batch(), cdr_toggle_runtime_options(), cdr_write(), cel_bridge_enter_cb(), cel_bridge_leave_cb(), cel_config_alloc(), cel_linkedid_ref(), cel_parking_cb(), cel_report_event(), cel_track_app(), cel_verify_and_cleanup_cb(), celgenuserevent_exec(), chan_pjsip_add_hold(), chan_pjsip_devicestate(), chan_pjsip_get_hold(), chan_pjsip_incoming_request(), chan_pjsip_new(), chan_pjsip_request(), chan_pjsip_session_begin(), channel_blob_to_json(), channel_chanspy_start_cb(), channel_chanspy_stop_cb(), channel_dial_cb(), channel_dtmf_begin_cb(), channel_dtmf_end_cb(), channel_enter_cb(), channel_fax_cb(), channel_hangup_handler_cb(), channel_hangup_request_cb(), channel_id_sanitizer(), channel_leave_cb(), channel_moh_start_cb(), channel_read_pjsip(), channel_replaced_cb(), channel_snapshot_update(), chanspy_exec(), charge_to_json(), check_cache_aggregate(), check_debug(), check_events(), check_new_cdr_needed(), check_retire_linkedid(), check_translation_path(), check_user_full(), cli_aor_get_container(), cli_aor_print_body(), cli_aor_print_header(), cli_channel_get_container(), cli_channel_retrieve_by_id(), cli_complete_endpoint(), cli_complete_notify(), cli_complete_registration(), cli_contact_get_container(), cli_contact_print_body(), cli_display_named_acl(), cli_display_named_acl_list(), cli_display_parking_lot(), cli_endpoint_get_container(), cli_endpoint_print_body(), cli_endpoint_print_child_body(), cli_endpoint_print_child_header(), cli_get_container(), cli_notify(), cli_print_body(), cli_qualify(), cli_qualify_contacts(), cli_register(), cli_show_channel(), cli_unregister(), command_prestart_queue_command(), complete_ari_user(), complete_bridge_profile_name(), complete_bridge_stasis(), complete_confbridge_participant(), complete_menu_name(), complete_user_profile_name(), conf_alloc(), conf_announce_channel_push(), conf_find_bridge_profile(), conf_find_user_profile(), conf_handle_talker_cb(), conf_run(), conf_set_menu_to_user(), confbridge_publish_manager_event(), confbridge_talking_cb(), config_pgsql(), configure_parking_extensions(), consumer_exec(), consumer_exec_sync(), contacts_to_str(), container_to_json_array(), control_create(), control_dispatch_all(), control_list_create(), control_recording(), create_bridge_snapshot_message(), create_channel_snapshot_message(), create_dynamic_lot_full(), create_endpoint_snapshot_message(), create_jb(), create_local_sdp(), create_mwi_subscriptions(), create_mwi_subscriptions_for_endpoint(), create_out_of_dialog_request(), create_outgoing_sdp_stream(), create_sound_blob(), dahdichannel_to_ami(), delete_old_messages(), destroy_bridge(), destroy_pgsql(), dial_state_process_bridge_enter(), dial_status_to_disposition(), dial_trunk(), digest_check_auth(), digest_lookup(), digest_requires_authentication(), direct_media_mitigate_glare(), do_waiting(), endpoint_internal_create(), endpoint_publish_snapshot(), expire_register(), export_aoc_vars(), extenspy_exec(), fake_ami(), fax_detect_framehook(), fax_gateway_framehook(), feature_automixmonitor(), feature_automonitor(), featuregroup_handler(), finalized_state_process_party_a(), find_aor(), find_bridge(), find_channel_control(), find_control(), find_recording(), find_table(), find_variant(), forkcdr_exec(), format_ami_aor_handler(), format_ami_auth_handler(), format_ami_endpoint(), format_ami_endpoint_identify(), format_ami_endpoint_transport(), format_ami_endpoints(), forwards_create(), forwards_create_bridge(), forwards_create_channel(), forwards_create_endpoint(), frame_set_var(), generate_filenames_json(), generate_or_link_lots_to_configs(), generate_status(), generic_fax_exec(), generic_monitor_devstate_tp_cb(), generic_mute_unmute_helper(), get_account_id(), get_cached_mwi(), get_destination(), get_exten_state_sub(), get_feature_ds(), get_languages(), get_media_encryption_type(), get_message_count(), get_outbound_endpoint(), get_refer_info(), get_state(), global_config_alloc(), grab_transfer(), handle_aor(), handle_attended_transfer(), handle_auth(), handle_blind_transfer(), handle_bridge_enter_message(), handle_bridge_leave_message(), handle_bridge_pairings(), handle_bridge_show_all(), handle_bridge_show_specific(), handle_call_outgoing(), handle_chanlist(), handle_channel_cache_message(), handle_channelstatus(), handle_cli_confbridge_show_bridge_profiles(), handle_cli_confbridge_show_menu(), handle_cli_confbridge_show_menus(), handle_cli_confbridge_show_user_profiles(), handle_cli_debug(), handle_cli_show_config(), handle_cli_sound_show(), handle_cli_sounds_show(), handle_cli_status(), handle_cli_submit(), handle_client_registration(), handle_client_state_destruction(), handle_dial_message(), handle_endpoint(), handle_feature_show(), handle_hangup(), handle_identify(), handle_incoming_sdp(), handle_invite_replaces(), handle_negotiated_sdp(), handle_negotiated_sdp_session_media(), handle_new_invite_request(), handle_options(), handle_parked_call_message(), handle_parking_bridge_enter_message(), handle_phoneprov(), handle_recordfile(), handle_registration_response(), handle_registrations(), handle_request_bye(), handle_request_invite(), handle_request_refer(), handle_response_peerpoke(), handle_security_event(), handle_show_named_acl_cmd(), handle_skel_show_config(), handle_skel_show_levels(), handle_soft_key_event_message(), handle_standard_bridge_enter_message(), handle_stimulus_message(), has_voicemail(), hep_queue_cb(), hepv3_config_post_apply(), hepv3_send_packet(), hold(), httpd_process_request(), incoming_request(), internal_feature_read(), internal_feature_write(), internal_featuremap_write(), internal_stasis_subscribe(), invalid_record_test(), ip_identify(), is_enabled(), is_subscribed_device_state(), isAnsweringMachine(), jack_str(), jingle_endpoint_state_find_or_create(), jingle_request(), join_queue(), json_array_from_list(), key_main_page(), launch_asyncagi(), leave_queue(), line_identify(), load_config(), load_endpoint(), load_module(), local_attended_transfer(), local_channel_optimization_blob(), local_message_to_ami(), local_optimization_finished_cb(), local_optimization_started_cb(), localnet_to_str(), log_attended_transfer(), manager_bridge_info(), manager_bridge_kick(), manager_bridge_tech_list(), manager_bridges_list(), manager_build_parked_call_string(), manager_default_msg_cb(), manager_generic_msg_cb(), manager_jabber_send(), manager_park(), manager_parking_status_all_lots(), manager_parking_status_single_lot(), match_to_str(), media_index_update(), media_info_alloc(), media_request_helper(), media_variant_alloc(), meetme_stasis_cb(), meetme_stasis_generate_msg(), menu_template_handler(), message_received_handler(), messaging_app_subscribe_endpoint(), messaging_app_unsubscribe_endpoint(), metermaidstate(), mgcp_hangup(), mgcp_ss(), mp3_exec(), msg_send(), multi_user_event_to_ami(), multi_user_event_to_json(), mwi_app_event_cb(), mwi_new_subscribe(), mwi_on_aor(), mwi_subscribe_single(), mwi_subscription_shutdown(), mwi_to_ami(), mwi_update_cb(), my_get_sigpvt_bridged_channel(), named_callgroups_to_str(), named_pickupgroups_to_str(), nat_on_tx_message(), native_rtp_bridge_compatible(), native_rtp_bridge_framehook_detach(), native_rtp_bridge_start(), native_rtp_bridge_stop(), native_rtp_framehook(), negotiate_incoming_sdp_stream(), new_invite(), nocdr_exec(), nominal_test(), notify_endpoint(), notify_new_message(), notify_option_handler(), notify_task(), notify_uri(), object_type_loaded_observer(), off_nominal_test(), options_on_rx_request(), origin_allowed(), outbound_auth(), outgoing_request(), pack_channel_into_message(), park_and_announce_app_exec(), park_app_exec(), park_application_setup(), park_common_setup(), parked_call_app_exec(), parked_call_message_response(), parked_call_payload_from_failure(), parked_call_payload_from_parked_user(), parker_parked_call_message_response(), parking_blind_transfer_park(), parking_config_alloc(), parking_dynamic_lots_enabled(), parking_lot_cfg_create_extensions(), parking_lot_retrieve_parked_user(), parking_lot_search_context_extension_inuse(), parking_park_bridge_channel(), parking_park_call(), parse_register_contact(), path_outgoing_request(), path_outgoing_response(), pbx_outgoing_attempt(), pbx_outgoing_exec(), peerstatus_to_ami(), persistent_endpoint_find_or_create(), persistent_endpoint_update_state(), phase_e_handler(), pjsip_acf_dial_contacts_read(), pjsip_aor_function_read(), pjsip_contact_function_read(), pjsip_endpoint_function_read(), play_on_channel(), play_on_channel_in_bridge(), play_sound(), playback_create(), playback_publish(), populate_cache(), post_cdr(), prepare_bridge_media_channel(), prepare_bridge_moh_channel(), presence_state_alloc(), presence_state_cached(), presence_state_event(), process_category(), process_config(), process_description_file(), process_file(), process_media_file(), publish_acl_change(), publish_app_cdr_message(), publish_async_exec_end(), publish_basic_channel_event(), publish_cache_clear(), publish_channel_alarm(), publish_channel_alarm_clear(), publish_chanspy_message(), publish_dahdichannel(), publish_dnd_state(), publish_expire_callback(), publish_format_update(), publish_fully_booted(), publish_hangup_handler_message(), publish_local_bridge_message(), publish_parked_call(), publish_parked_call_failure(), publish_qualify_peer_done(), publish_reload_message(), publish_request_initial(), publish_span_alarm(), publish_span_alarm_clear(), pubsub_on_rx_publish_request(), pubsub_on_rx_subscribe_request(), push_notify(), qualify_contact(), queue_channel_to_ami(), queue_member_to_ami(), queue_multi_channel_to_ami(), queue_publish_member_blob(), queue_publish_multi_channel_blob(), queue_publish_multi_channel_snapshot_blob(), queued_set_size(), read_header(), realtime_exec(), realtime_ldap_base(), realtime_multi_pgsql(), realtime_pgsql(), rec_request(), recall_pull(), recalling_enter(), receivefax_exec(), record_abandoned(), record_exec(), recording_alloc(), recording_publish(), refer_incoming_attended_request(), refer_incoming_invite_request(), refer_incoming_refer_request(), refer_progress_notify(), register_verify(), registrar_on_rx_request(), registrar_validate_contacts(), remove_all_configured_parking_lot_extensions(), remove_header(), replace(), report_fax_status(), report_receive_fax_status(), report_send_fax_status(), request(), resetcdr_exec(), retransfer_enter(), ring_entry(), ringing(), rna(), root_handler_create(), rtcp_message_handler(), rtcp_report_to_ami(), rtcp_report_to_json(), run_station(), rx_data_to_ast_msg(), rx_task(), s_to_json(), safe_mkdir(), scan(), scan_dir(), scan_file(), sdp_requires_deferral(), security_event_to_ami_blob(), send_agent_complete(), send_agent_login(), send_agent_logoff(), send_bridge_info_item_cb(), send_bridge_list_item_cb(), send_call_pickup_stasis_message(), send_conf_stasis(), send_device_state(), send_dtmf_begin_event(), send_dtmf_end_event(), send_session_timeout(), send_start_msg(), send_start_msg_snapshots(), send_talking_event(), send_unsolicited_mwi_notify(), sendfax_exec(), sendtext(), session_create(), session_outgoing_nat_hook(), session_reinvite_on_rx_request(), session_timeout_to_ami(), set_caps(), set_config_flags(), set_format(), setup_bridge_features_dynamic(), setup_sdes_srtp(), shared_write(), show_sound_info_cb(), shutdown_data_create(), simple_bridge_channel_event(), single_state_bridge_enter_comparison(), single_state_process_bridge_enter(), single_state_process_dial_begin(), sip_aor_to_ami(), sip_get_tpselector_from_endpoint(), sip_outbound_publish_apply(), sip_outbound_publish_callback(), sip_outbound_publish_client_alloc(), sip_outbound_publish_synchronize(), sip_outbound_registration_apply(), sip_outbound_registration_perform(), sip_outbound_registration_regc_alloc(), sip_outbound_registration_response_cb(), sip_poke_noanswer(), sip_publication_respond(), sip_publish_client_service_queue(), skel_find_or_create_state(), skinny_register(), skinny_session_cleanup(), 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(), smdi_load(), snapshot_cep_changed(), snoop_stasis_thread(), socket_process_helper(), sorcery_astdb_create(), sorcery_astdb_retrieve_fields_common(), sorcery_astdb_retrieve_id(), sorcery_astdb_retrieve_regex(), sorcery_config_fields_cmp(), sorcery_config_internal_load(), sorcery_config_retrieve_fields(), sorcery_config_retrieve_id(), sorcery_config_retrieve_multiple(), sorcery_config_retrieve_regex(), sorcery_function_read(), sorcery_is_criteria_met(), sorcery_memory_delete(), sorcery_memory_fields_cmp(), sorcery_memory_update(), sorcery_realtime_create(), sorcery_realtime_retrieve_fields(), sorcery_realtime_retrieve_id(), sorcery_realtime_retrieve_multiple(), sorcery_realtime_retrieve_regex(), sorcery_realtime_update(), sorcery_reloadable(), spandsp_fax_gateway_start(), speech_background(), split_path(), start_automixmonitor(), start_automonitor(), stasis_app_bridge_moh_channel(), stasis_app_bridge_moh_stop(), stasis_app_bridge_playback_channel_add(), stasis_app_control_get_snapshot(), stasis_app_control_record(), stasis_app_control_snoop(), stasis_app_device_states_to_json(), stasis_app_exec(), stasis_app_get_all(), stasis_app_playback_to_json(), stasis_app_recording_find_by_name(), stasis_app_recording_options_create(), stasis_app_recording_to_json(), stasis_app_register(), stasis_app_send(), stasis_app_send_command_async(), stasis_app_stored_recording_copy(), stasis_app_stored_recording_find_all(), stasis_app_stored_recording_find_by_name(), stasis_app_subscribe_channel(), stasis_app_to_json(), stasis_app_unregister(), stasis_app_user_event(), stasis_caching_topic_create(), stasis_cp_all_create(), stasis_cp_single_create(), stasis_forward_all(), stasis_init(), stasis_message_router_create_internal(), stasis_message_sink_create(), stasis_message_type_declined(), stasis_test_message_create(), stasis_topic_pool_get_topic(), stasis_unsubscribe(), statsd_init(), statsmaker(), store_pgsql(), stun_monitor_request(), sub_bridge_update_handler(), sub_channel_update_handler(), sub_default_handler(), sub_endpoint_update_handler(), submit_scheduled_batch(), subscription_persistence_recreate(), system_registry_to_ami(), t38_automatic_reject(), t38_framehook_read(), t38_framehook_write(), t38_interpret_parameters(), t38_reinvite_response_cb(), t38_state_get_or_alloc(), test_cel_generate_peer_str(), test_cel_generate_peer_str_snapshot(), test_cel_peer_strings_match(), threadpool_alloc(), transfer_pull(), transmit_info_dtmf(), transmit_info_with_vidupdate(), transport_apply(), try_calling(), try_parking(), two_bridge_attended_transfer(), unhold(), unistim_send_mwi_to_peer(), unload_module(), unregister_task(), unsubscribe(), unsubscribe_device_state(), update2_pgsql(), update_file_format_info(), update_header(), update_pgsql(), update_registry(), user_alloc(), userevent_exec(), username_identify(), varset_to_ami(), verify_default_parking_lot(), verify_default_profiles(), wait_for_stimulus(), websocket_server_create_impl(), xmpp_action_hook(), xmpp_cli_create_collection(), xmpp_cli_create_leafnode(), xmpp_cli_delete_pubsub_node(), xmpp_cli_list_pubsub_nodes(), xmpp_cli_purge_pubsub_nodes(), xmpp_client_config_post_apply(), xmpp_client_find_or_create(), xmpp_client_reconnect(), xmpp_client_send_message(), xmpp_client_set_group_presence(), xmpp_client_set_presence(), xmpp_client_thread(), xmpp_component_register_get_hook(), xmpp_component_service_discovery_get_hook(), xmpp_component_service_discovery_items_hook(), xmpp_config_post_apply(), xmpp_config_prelink(), xmpp_connect_hook(), xmpp_init_event_distribution(), xmpp_join_exec(), xmpp_leave_exec(), xmpp_log_hook(), xmpp_pubsub_build_publish_skeleton(), xmpp_pubsub_handle_error(), xmpp_pubsub_iq_create(), xmpp_pubsub_publish_device_state(), xmpp_pubsub_subscribe(), xmpp_roster_hook(), xmpp_send_cb(), xmpp_send_exec(), xmpp_sendgroup_exec(), xmpp_show_buddies(), xmpp_show_clients(), and xmpp_status_exec().

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


Function Documentation

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

Definition at line 914 of file extconf.c.

00930 {

void * _ast_calloc ( size_t  num,
size_t  len,
const char *  file,
int  lineno,
const char *  func 
) [inline]

Definition at line 586 of file utils.h.

00614 {

void * _ast_malloc ( size_t  len,
const char *  file,
int  lineno,
const char *  func 
) [inline]

Definition at line 560 of file utils.h.

00575 {

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

Definition at line 625 of file utils.h.

00644 {

char * _ast_strdup ( const char *  str,
const char *  file,
int  lineno,
const char *  func 
) [inline]

Definition at line 657 of file utils.h.

00676 {

char * _ast_strndup ( const char *  str,
size_t  len,
const char *  file,
int  lineno,
const char *  func 
) [inline]

Definition at line 689 of file utils.h.

00719 {

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

Definition at line 730 of file utils.h.

00753 {                                                                \

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

Decode data from base64.

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

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

Referenced by action_messagesend(), aes_helper(), ast_check_signature(), ast_http_get_auth(), ast_sdp_crypto_alloc(), ast_sdp_crypto_process(), AST_TEST_DEFINE(), base64_helper(), custom_presence_callback(), osp_validate_token(), and presence_write().

00289 {
00290    int cnt = 0;
00291    unsigned int byte = 0;
00292    unsigned int bits = 0;
00293    int incnt = 0;
00294    while(*src && *src != '=' && (cnt < max)) {
00295       /* Shift in 6 bits of input */
00296       byte <<= 6;
00297       byte |= (b2a[(int)(*src)]) & 0x3f;
00298       bits += 6;
00299       src++;
00300       incnt++;
00301       /* If we have at least 8 bits left over, take that character
00302          off the top */
00303       if (bits >= 8)  {
00304          bits -= 8;
00305          *dst = (byte >> bits) & 0xff;
00306          dst++;
00307          cnt++;
00308       }
00309    }
00310    /* Don't worry about left over bits, they're extra anyway */
00311    return cnt;
00312 }

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

Encode data in base64.

Parameters:
dst the destination buffer
src the source data to be encoded
srclen the number of bytes present in the source buffer
max the maximum number of bytes to write into the destination buffer, *including* the terminating NULL character.

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

References ast_base64encode_full().

Referenced by aes_helper(), ast_sdp_crypto_alloc(), ast_sign(), AST_TEST_DEFINE(), base64_helper(), build_secret(), osp_check_destination(), presence_read(), websocket_client_create_key(), websocket_combine_key(), and xmpp_client_authenticate_sasl().

00367 {
00368    return ast_base64encode_full(dst, src, srclen, max, 0);
00369 }

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

encode text to BASE64 coding

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

Referenced by ast_base64encode().

00316 {
00317    int cnt = 0;
00318    int col = 0;
00319    unsigned int byte = 0;
00320    int bits = 0;
00321    int cntin = 0;
00322    /* Reserve space for null byte at end of string */
00323    max--;
00324    while ((cntin < srclen) && (cnt < max)) {
00325       byte <<= 8;
00326       byte |= *(src++);
00327       bits += 8;
00328       cntin++;
00329       if ((bits == 24) && (cnt + 4 <= max)) {
00330          *dst++ = base64[(byte >> 18) & 0x3f];
00331          *dst++ = base64[(byte >> 12) & 0x3f];
00332          *dst++ = base64[(byte >> 6) & 0x3f];
00333          *dst++ = base64[byte & 0x3f];
00334          cnt += 4;
00335          col += 4;
00336          bits = 0;
00337          byte = 0;
00338       }
00339       if (linebreaks && (cnt < max) && (col == 64)) {
00340          *dst++ = '\n';
00341          cnt++;
00342          col = 0;
00343       }
00344    }
00345    if (bits && (cnt + 4 <= max)) {
00346       /* Add one last character for the remaining bits,
00347          padding the rest with 0 */
00348       byte <<= 24 - bits;
00349       *dst++ = base64[(byte >> 18) & 0x3f];
00350       *dst++ = base64[(byte >> 12) & 0x3f];
00351       if (bits == 16)
00352          *dst++ = base64[(byte >> 6) & 0x3f];
00353       else
00354          *dst++ = '=';
00355       *dst++ = '=';
00356       cnt += 4;
00357    }
00358    if (linebreaks && (cnt < max)) {
00359       *dst++ = '\n';
00360       cnt++;
00361    }
00362    *dst = '\0';
00363    return cnt;
00364 }

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:
f the file stream to write to
fd the file description to poll on to know when the file stream can be written to without blocking.
s the buffer to write from
len the number of bytes to write
timeoutms The 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:
0 success
-1 error

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

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

Referenced by ast_websocket_close(), ast_websocket_write(), and send_string().

01429 {
01430    struct timeval start = ast_tvnow();
01431    int n = 0;
01432    int elapsed = 0;
01433 
01434    while (len) {
01435       if (wait_for_output(fd, timeoutms - elapsed)) {
01436          /* poll returned a fatal error, so bail out immediately. */
01437          return -1;
01438       }
01439 
01440       /* Clear any errors from a previous write */
01441       clearerr(f);
01442 
01443       n = fwrite(src, 1, len, f);
01444 
01445       if (ferror(f) && errno != EINTR && errno != EAGAIN) {
01446          /* fatal error from fwrite() */
01447          if (!feof(f)) {
01448             /* Don't spam the logs if it was just that the connection is closed. */
01449             ast_log(LOG_ERROR, "fwrite() returned error: %s\n", strerror(errno));
01450          }
01451          n = -1;
01452          break;
01453       }
01454 
01455       /* Update for data already written to the socket */
01456       len -= n;
01457       src += n;
01458 
01459       elapsed = ast_tvdiff_ms(ast_tvnow(), start);
01460       if (elapsed >= timeoutms) {
01461          /* We've taken too long to write
01462           * This is only an error condition if we haven't finished writing. */
01463          n = len ? -1 : 0;
01464          break;
01465       }
01466    }
01467 
01468    errno = 0;
01469    while (fflush(f)) {
01470       if (errno == EAGAIN || errno == EINTR) {
01471          /* fflush() does not appear to reset errno if it flushes
01472           * and reaches EOF at the same time. It returns EOF with
01473           * the last seen value of errno, causing a possible loop.
01474           * Also usleep() to reduce CPU eating if it does loop */
01475          errno = 0;
01476          usleep(1);
01477          continue;
01478       }
01479       if (errno && !feof(f)) {
01480          /* Don't spam the logs if it was just that the connection is closed. */
01481          ast_log(LOG_ERROR, "fflush() returned error: %s\n", strerror(errno));
01482       }
01483       n = -1;
01484       break;
01485    }
01486 
01487    return n < 0 ? -1 : 0;
01488 }

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

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

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

01388 {
01389    struct timeval start = ast_tvnow();
01390    int res = 0;
01391    int elapsed = 0;
01392 
01393    while (len) {
01394       if (wait_for_output(fd, timeoutms - elapsed)) {
01395          return -1;
01396       }
01397 
01398       res = write(fd, s, len);
01399 
01400       if (res < 0 && errno != EAGAIN && errno != EINTR) {
01401          /* fatal error from write() */
01402          ast_log(LOG_ERROR, "write() returned error: %s\n", strerror(errno));
01403          return -1;
01404       }
01405 
01406       if (res < 0) {
01407          /* It was an acceptable error */
01408          res = 0;
01409       }
01410 
01411       /* Update how much data we have left to write */
01412       len -= res;
01413       s += res;
01414       res = 0;
01415 
01416       elapsed = ast_tvdiff_ms(ast_tvnow(), start);
01417       if (elapsed >= timeoutms) {
01418          /* We've taken too long to write
01419           * This is only an error condition if we haven't finished writing. */
01420          res = len ? -1 : 0;
01421          break;
01422       }
01423    }
01424 
01425    return res;
01426 }

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

Asterisk wrapper around crypt(3).

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

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

Parameters:
key User's password to crypt.
salt Salt to crypt with.
Returns:
Crypted password.

NULL on error.

Definition at line 176 of file crypt.c.

References ast_log, LOG_WARNING, and NULL.

Referenced by ast_crypt_encrypt().

00177 {
00178    ast_log(LOG_WARNING,
00179       "crypt() support not available; cannot encrypt password\n");
00180    return NULL;
00181 }

char* ast_crypt_encrypt ( const char *  key  ) 

Definition at line 192 of file crypt.c.

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

Referenced by ari_mkpasswd(), and AST_TEST_DEFINE().

00193 {
00194    char salt[MAX_SALT_LEN] = {};
00195    while (gen_salt(salt, sizeof(salt)) == 0) {
00196       char *crypted = ast_crypt(key, salt);
00197       if (crypted) {
00198          return crypted;
00199       }
00200    }
00201    return NULL;
00202 }

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

Definition at line 183 of file crypt.c.

References ast_log, and LOG_WARNING.

Referenced by ast_ari_config_validate_user(), and AST_TEST_DEFINE().

00184 {
00185    ast_log(LOG_WARNING,
00186       "crypt() support not available; cannot validate password\n");
00187    return 0;
00188 }

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

Referenced by sip_route_process_header().

02658 {
02659 #if defined(DO_CRASH)
02660    abort();
02661    /*
02662     * Just in case abort() doesn't work or something else super
02663     * silly, and for Qwell's amusement.
02664     */
02665    *((int *) 0) = 0;
02666 #endif   /* defined(DO_CRASH) */
02667 }

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 
)

void ast_enable_packet_fragmentation ( int  sock  ) 

Disable PMTU discovery on a socket.

Parameters:
sock The 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 2322 of file main/utils.c.

References ast_log, and LOG_WARNING.

Referenced by ast_netsock_bindaddr(), and reload_config().

02323 {
02324 #if defined(HAVE_IP_MTU_DISCOVER)
02325    int val = IP_PMTUDISC_DONT;
02326 
02327    if (setsockopt(sock, IPPROTO_IP, IP_MTU_DISCOVER, &val, sizeof(val)))
02328       ast_log(LOG_WARNING, "Unable to disable PMTU discovery. Large UDP packets may fail to be delivered when sent from this socket.\n");
02329 #endif /* HAVE_IP_MTU_DISCOVER */
02330 }

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:
string string to be escaped
outbuf resulting escaped string
buflen size of output buffer
Returns:
a pointer to the escaped string

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

References out.

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

00458 {
00459    const char *ptr  = string;
00460    char *out = outbuf;
00461    char *allow = "\t\v !"; /* allow LWS (minus \r and \n) and "!" */
00462 
00463    while (*ptr && out - outbuf < buflen - 1) {
00464       if (!(strchr(allow, *ptr))
00465          && !(*ptr >= '#' && *ptr <= '[') /* %x23 - %x5b */
00466          && !(*ptr >= ']' && *ptr <= '~') /* %x5d - %x7e */
00467          && !((unsigned char) *ptr > 0x7f)) {             /* UTF8-nonascii */
00468 
00469          if (out - outbuf >= buflen - 2) {
00470             break;
00471          }
00472          out += sprintf(out, "\\%c", (unsigned char) *ptr);
00473       } else {
00474          *out = *ptr;
00475          out++;
00476       }
00477       ptr++;
00478    }
00479 
00480    if (buflen) {
00481       *out = '\0';
00482    }
00483 
00484    return outbuf;
00485 }

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

Escape semicolons found in a string.

Parameters:
string string to be escaped
outbuf resulting escaped string
buflen size of output buffer
Returns:
a pointer to the escaped string

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

References ast_assert, NULL, and out.

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

00488 {
00489    const char *ptr = string;
00490    char *out = outbuf;
00491 
00492    if (string == NULL || outbuf == NULL) {
00493       ast_assert(string != NULL && outbuf != NULL);
00494       return NULL;
00495    }
00496 
00497    while (*ptr && out - outbuf < buflen - 1) {
00498       if (*ptr == ';') {
00499          if (out - outbuf >= buflen - 2) {
00500             break;
00501          }
00502          strcpy(out, "\\;");
00503          out += 2;
00504       } else {
00505          *out = *ptr;
00506          out++;
00507       }
00508       ptr++;
00509    }
00510 
00511    if (buflen) {
00512       *out = '\0';
00513    }
00514 
00515    return outbuf;
00516 }

int ast_get_tid ( void   ) 

Get current thread ID.

Returns:
the ID if platform is supported, else -1

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

Referenced by __ao2_alloc_debug(), __ao2_ref_debug(), ast_log_full(), ast_register_thread(), and dummy_start().

02622 {
02623    int ret = -1;
02624 #if defined (__linux) && defined(SYS_gettid)
02625    ret = syscall(SYS_gettid); /* available since Linux 1.4.11 */
02626 #elif defined(__sun)
02627    ret = pthread_self();
02628 #elif defined(__APPLE__)
02629    ret = mach_thread_self();
02630    mach_port_deallocate(mach_task_self(), ret);
02631 #elif defined(__FreeBSD__) && defined(HAVE_SYS_THR_H)
02632    long lwpid;
02633    thr_self(&lwpid); /* available since sys/thr.h creation 2003 */
02634    ret = lwpid;
02635 #endif
02636    return ret;
02637 }

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

Thread-safe gethostbyname function to use in Asterisk.

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

References ast_hostent::buf, gethostbyname_r(), ast_hostent::hp, NULL, and result.

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

00193 {
00194    int res;
00195    int herrno;
00196    int dots = 0;
00197    const char *s;
00198    struct hostent *result = NULL;
00199    /* Although it is perfectly legitimate to lookup a pure integer, for
00200       the sake of the sanity of people who like to name their peers as
00201       integers, we break with tradition and refuse to look up a
00202       pure integer */
00203    s = host;
00204    res = 0;
00205    while (s && *s) {
00206       if (*s == '.')
00207          dots++;
00208       else if (!isdigit(*s))
00209          break;
00210       s++;
00211    }
00212    if (!s || !*s) {
00213       /* Forge a reply for IP's to avoid octal IP's being interpreted as octal */
00214       if (dots != 3)
00215          return NULL;
00216       memset(hp, 0, sizeof(struct ast_hostent));
00217       hp->hp.h_addrtype = AF_INET;
00218       hp->hp.h_addr_list = (void *) hp->buf;
00219       hp->hp.h_addr = hp->buf + sizeof(void *);
00220       /* For AF_INET, this will always be 4 */
00221       hp->hp.h_length = 4;
00222       if (inet_pton(AF_INET, host, hp->hp.h_addr) > 0)
00223          return &hp->hp;
00224       return NULL;
00225 
00226    }
00227 #ifdef HAVE_GETHOSTBYNAME_R_5
00228    result = gethostbyname_r(host, &hp->hp, hp->buf, sizeof(hp->buf), &herrno);
00229 
00230    if (!result || !hp->hp.h_addr_list || !hp->hp.h_addr_list[0])
00231       return NULL;
00232 #else
00233    res = gethostbyname_r(host, &hp->hp, hp->buf, sizeof(hp->buf), &result, &herrno);
00234 
00235    if (res || !result || !hp->hp.h_addr_list || !hp->hp.h_addr_list[0])
00236       return NULL;
00237 #endif
00238    return &hp->hp;
00239 }

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

Produces MD5 hash based on input string.

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

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

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

00243 {
00244    struct MD5Context md5;
00245    unsigned char digest[16];
00246    char *ptr;
00247    int x;
00248 
00249    MD5Init(&md5);
00250    MD5Update(&md5, (const unsigned char *) input, strlen(input));
00251    MD5Final(digest, &md5);
00252    ptr = output;
00253    for (x = 0; x < 16; x++)
00254       ptr += sprintf(ptr, "%02hhx", digest[x]);
00255 }

int ast_mkdir ( const char *  path,
int  mode 
)

Recursively create directory path.

Parameters:
path The directory path to create
mode The 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 2332 of file main/utils.c.

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

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

02333 {
02334    char *ptr;
02335    int len = strlen(path), count = 0, x, piececount = 0;
02336    char *tmp = ast_strdupa(path);
02337    char **pieces;
02338    char *fullpath = ast_alloca(len + 1);
02339    int res = 0;
02340 
02341    for (ptr = tmp; *ptr; ptr++) {
02342       if (*ptr == '/')
02343          count++;
02344    }
02345 
02346    /* Count the components to the directory path */
02347    pieces = ast_alloca(count * sizeof(*pieces));
02348    for (ptr = tmp; *ptr; ptr++) {
02349       if (*ptr == '/') {
02350          *ptr = '\0';
02351          pieces[piececount++] = ptr + 1;
02352       }
02353    }
02354 
02355    *fullpath = '\0';
02356    for (x = 0; x < piececount; x++) {
02357       /* This looks funky, but the buffer is always ideally-sized, so it's fine. */
02358       strcat(fullpath, "/");
02359       strcat(fullpath, pieces[x]);
02360       res = mkdir(fullpath, mode);
02361       if (res && errno != EEXIST)
02362          return errno;
02363    }
02364    return 0;
02365 }

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.
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 2491 of file main/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(), c, ast_http_digest::cnonce, ast_http_digest::domain, LOG_WARNING, ast_http_digest::nc, ast_http_digest::nonce, NULL, 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().

02491                                                                                                {
02492    char *c;
02493    struct ast_str *str = ast_str_create(16);
02494 
02495    /* table of recognised keywords, and places where they should be copied */
02496    const struct x {
02497       const char *key;
02498       const ast_string_field *field;
02499    } *i, keys[] = {
02500       { "username=", &d->username },
02501       { "realm=", &d->realm },
02502       { "nonce=", &d->nonce },
02503       { "uri=", &d->uri },
02504       { "domain=", &d->domain },
02505       { "response=", &d->response },
02506       { "cnonce=", &d->cnonce },
02507       { "opaque=", &d->opaque },
02508       /* Special cases that cannot be directly copied */
02509       { "algorithm=", NULL },
02510       { "qop=", NULL },
02511       { "nc=", NULL },
02512       { NULL, 0 },
02513    };
02514 
02515    if (ast_strlen_zero(digest) || !d || !str) {
02516       ast_free(str);
02517       return -1;
02518    }
02519 
02520    ast_str_set(&str, 0, "%s", digest);
02521 
02522    c = ast_skip_blanks(ast_str_buffer(str));
02523 
02524    if (strncasecmp(c, "Digest ", strlen("Digest "))) {
02525       ast_log(LOG_WARNING, "Missing Digest.\n");
02526       ast_free(str);
02527       return -1;
02528    }
02529    c += strlen("Digest ");
02530 
02531    /* lookup for keys/value pair */
02532    while (c && *c && *(c = ast_skip_blanks(c))) {
02533       /* find key */
02534       for (i = keys; i->key != NULL; i++) {
02535          char *src, *separator;
02536          int unescape = 0;
02537          if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
02538             continue;
02539          }
02540 
02541          /* Found. Skip keyword, take text in quotes or up to the separator. */
02542          c += strlen(i->key);
02543          if (*c == '"') {
02544             src = ++c;
02545             separator = "\"";
02546             unescape = 1;
02547          } else {
02548             src = c;
02549             separator = ",";
02550          }
02551          strsep(&c, separator); /* clear separator and move ptr */
02552          if (unescape) {
02553             ast_unescape_c(src);
02554          }
02555          if (i->field) {
02556             ast_string_field_ptr_set(d, i->field, src);
02557          } else {
02558             /* Special cases that require additional procesing */
02559             if (!strcasecmp(i->key, "algorithm=")) {
02560                if (strcasecmp(src, "MD5")) {
02561                   ast_log(LOG_WARNING, "Digest algorithm: \"%s\" not supported.\n", src);
02562                   ast_free(str);
02563                   return -1;
02564                }
02565             } else if (!strcasecmp(i->key, "qop=") && !strcasecmp(src, "auth")) {
02566                d->qop = 1;
02567             } else if (!strcasecmp(i->key, "nc=")) {
02568                unsigned long u;
02569                if (sscanf(src, "%30lx", &u) != 1) {
02570                   ast_log(LOG_WARNING, "Incorrect Digest nc value: \"%s\".\n", src);
02571                   ast_free(str);
02572                   return -1;
02573                }
02574                ast_string_field_set(d, nc, src);
02575             }
02576          }
02577          break;
02578       }
02579       if (i->key == NULL) { /* not found, try ',' */
02580          strsep(&c, ",");
02581       }
02582    }
02583    ast_free(str);
02584 
02585    /* Digest checkout */
02586    if (ast_strlen_zero(d->realm) || ast_strlen_zero(d->nonce)) {
02587       /* "realm" and "nonce" MUST be always exist */
02588       return -1;
02589    }
02590 
02591    if (!request) {
02592       /* Additional check for Digest response */
02593       if (ast_strlen_zero(d->username) || ast_strlen_zero(d->uri) || ast_strlen_zero(d->response)) {
02594          return -1;
02595       }
02596 
02597       if (pedantic && d->qop && (ast_strlen_zero(d->cnonce) || ast_strlen_zero(d->nc))) {
02598          return -1;
02599       }
02600    }
02601 
02602    return 0;
02603 }

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

Process a string to find and replace characters.

Parameters:
start The string to analyze
find The character to find
replace_with The character that will replace the one we are looking for

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

Referenced by pbx_load_config().

01826 {
01827    char *dataPut = start;
01828    int inEscape = 0;
01829    int inQuotes = 0;
01830 
01831    for (; *start; start++) {
01832       if (inEscape) {
01833          *dataPut++ = *start;       /* Always goes verbatim */
01834          inEscape = 0;
01835       } else {
01836          if (*start == '\\') {
01837             inEscape = 1;      /* Do not copy \ into the data */
01838          } else if (*start == '\'') {
01839             inQuotes = 1 - inQuotes;   /* Do not copy ' into the data */
01840          } else {
01841             /* Replace , with |, unless in quotes */
01842             *dataPut++ = inQuotes ? *start : ((*start == find) ? replace_with : *start);
01843          }
01844       }
01845    }
01846    if (start != dataPut)
01847       *dataPut = 0;
01848    return dataPut;
01849 }

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

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

01292 {
01293    unsigned char attr_destroy = 0;
01294    int res;
01295 
01296    if (!attr) {
01297       attr = ast_alloca(sizeof(*attr));
01298       pthread_attr_init(attr);
01299       attr_destroy = 1;
01300    }
01301 
01302    if ((errno = pthread_attr_setdetachstate(attr, PTHREAD_CREATE_DETACHED)))
01303       ast_log(LOG_WARNING, "pthread_attr_setdetachstate: %s\n", strerror(errno));
01304 
01305    res = ast_pthread_create_stack(thread, attr, start_routine, data,
01306                                   stacksize, file, caller, line, start_fn);
01307 
01308    if (attr_destroy)
01309       pthread_attr_destroy(attr);
01310 
01311    return res;
01312 }

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

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

Referenced by ast_pthread_create_detached_stack().

01244 {
01245 #if !defined(LOW_MEMORY)
01246    struct thr_arg *a;
01247 #endif
01248 
01249    if (!attr) {
01250       attr = ast_alloca(sizeof(*attr));
01251       pthread_attr_init(attr);
01252    }
01253 
01254 #ifdef __linux__
01255    /* On Linux, pthread_attr_init() defaults to PTHREAD_EXPLICIT_SCHED,
01256       which is kind of useless. Change this here to
01257       PTHREAD_INHERIT_SCHED; that way the -p option to set realtime
01258       priority will propagate down to new threads by default.
01259       This does mean that callers cannot set a different priority using
01260       PTHREAD_EXPLICIT_SCHED in the attr argument; instead they must set
01261       the priority afterwards with pthread_setschedparam(). */
01262    if ((errno = pthread_attr_setinheritsched(attr, PTHREAD_INHERIT_SCHED)))
01263       ast_log(LOG_WARNING, "pthread_attr_setinheritsched: %s\n", strerror(errno));
01264 #endif
01265 
01266    if (!stacksize)
01267       stacksize = AST_STACKSIZE;
01268 
01269    if ((errno = pthread_attr_setstacksize(attr, stacksize ? stacksize : AST_STACKSIZE)))
01270       ast_log(LOG_WARNING, "pthread_attr_setstacksize: %s\n", strerror(errno));
01271 
01272 #if !defined(LOW_MEMORY)
01273    if ((a = ast_malloc(sizeof(*a)))) {
01274       a->start_routine = start_routine;
01275       a->data = data;
01276       start_routine = dummy_start;
01277       if (ast_asprintf(&a->name, "%-20s started at [%5d] %s %s()",
01278               start_fn, line, file, caller) < 0) {
01279          a->name = NULL;
01280       }
01281       data = a;
01282    }
01283 #endif /* !LOW_MEMORY */
01284 
01285    return pthread_create(thread, attr, start_routine, data); /* We're in ast_pthread_create, so it's okay */
01286 }

long int ast_random ( void   ) 

Examples:
/tmp/asterisk-trunk/trunk/main/app.c.

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

References ast_mutex_lock, ast_mutex_unlock, and randomlock.

Referenced by __sip_alloc(), acf_rand_exec(), action_challenge(), add_sdp(), agi_handle_command(), app_exec(), ast_generate_random_string(), ast_lock_path_lockfile(), ast_moh_files_next(), ast_rtp_change_source(), ast_rtp_new(), AST_TEST_DEFINE(), ast_udptl_new_with_bindaddr(), astobj2_test_1_helper(), auth_http_callback(), authenticate_request(), build_gateway(), build_iv(), build_localtag_registry(), build_nonce(), build_rand_pad(), build_reply_digest(), calc_metric(), calc_rxstamp(), caldav_write_event(), create_channel_name(), create_local_sdp(), dns_srv_sort(), generate_parked_user(), generate_random_string(), generic_http_callback(), get_trans_id(), get_unused_callno(), handle_cli_sched_bench(), handle_incoming(), handle_response_invite(), iax2_key_rotate(), jingle_add_ice_udp_candidates_to_transport(), jingle_alloc(), jingle_new(), load_module(), make_email_file(), make_our_tag(), mbl_new(), mktemp_internal(), moh_files_alloc(), multicast_rtp_new(), ogg_vorbis_rewrite(), osp_create_uuid(), page_exec(), process_weights(), reg_source_db(), registry_authrequest(), reqprep(), reschedule_reinvite(), say_periodic_announcement(), sendmail(), sip_outbound_registration_perform(), socket_read(), start_rtp(), stun_req_id(), test_ao2_find_w_no_flags(), test_ao2_find_w_OBJ_KEY(), test_ao2_find_w_OBJ_PARTIAL_KEY(), test_ao2_find_w_OBJ_POINTER(), transmit_invite(), transmit_register(), transmit_response_using_temp(), try_calling(), try_firmware(), and websocket_client_create_key().

01786 {
01787    long int res;
01788 
01789    if (dev_urandom_fd >= 0) {
01790       int read_res = read(dev_urandom_fd, &res, sizeof(res));
01791       if (read_res > 0) {
01792          long int rm = RAND_MAX;
01793          res = res < 0 ? ~res : res;
01794          rm++;
01795          return res % rm;
01796       }
01797    }
01798 
01799    /* XXX - Thread safety really depends on the libc, not the OS.
01800     *
01801     * But... popular Linux libc's (uClibc, glibc, eglibc), all have a
01802     * somewhat thread safe random(3) (results are random, but not
01803     * reproducible). The libc's for other systems (BSD, et al.), not so
01804     * much.
01805     */
01806 #ifdef linux
01807    res = random();
01808 #else
01809    ast_mutex_lock(&randomlock);
01810    res = random();
01811    ast_mutex_unlock(&randomlock);
01812 #endif
01813    return res;
01814 }

void ast_register_thread ( char *  name  ) 

Definition at line 568 of file asterisk.c.

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

Referenced by dummy_start().

00569 {
00570    struct thread_list_t *new = ast_calloc(1, sizeof(*new));
00571 
00572    if (!new)
00573       return;
00574 
00575    ast_assert(multi_thread_safe);
00576    new->id = pthread_self();
00577    new->lwp = ast_get_tid();
00578    new->name = name; /* steal the allocated memory for the thread name */
00579    AST_RWLIST_WRLOCK(&thread_list);
00580    AST_RWLIST_INSERT_HEAD(&thread_list, new, list);
00581    AST_RWLIST_UNLOCK(&thread_list);
00582 }

void ast_replace_subargument_delimiter ( char *  s  ) 

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

Parameters:
s String within which to replace characters

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

Referenced by app_exec(), ast_bridge_set_after_go_on(), ast_dial_prerun(), begin_dial(), dial_exec_full(), handle_call_forward(), and page_exec().

01817 {
01818    for (; *s; s++) {
01819       if (*s == '^') {
01820          *s = ',';
01821       }
01822    }
01823 }

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

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

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

Parameters:
path The directory path to create
mode The permissions with which to try to create the directory
Returns:
0 on success or an error code otherwise

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

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

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

02438 {
02439    RAII_VAR(char *, absolute_base_path, NULL, ast_std_free);
02440    RAII_VAR(char *, p, NULL, ast_free);
02441 
02442    if (base_path == NULL || path == NULL) {
02443       errno = EFAULT;
02444       return errno;
02445    }
02446 
02447    p = ast_strdup(path);
02448    if (p == NULL) {
02449       errno = ENOMEM;
02450       return errno;
02451    }
02452 
02453    absolute_base_path = realpath(base_path, NULL);
02454    if (absolute_base_path == NULL) {
02455       return errno;
02456    }
02457 
02458    return safe_mkdir(absolute_base_path, p, mode);
02459 }

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

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

Referenced by ast_readconfig().

02713 {
02714 #if defined(SIOCGIFHWADDR) && defined(HAVE_STRUCT_IFREQ_IFR_IFRU_IFRU_HWADDR)
02715    int s, x = 0;
02716    char eid_str[20];
02717    struct ifreq ifr;
02718    static const unsigned int MAXIF = 10;
02719 
02720    s = socket(AF_INET, SOCK_STREAM, 0);
02721    if (s < 0) {
02722       return;
02723    }
02724    for (x = 0; x < MAXIF; x++) {
02725       static const char *prefixes[] = { "eth", "em" };
02726       unsigned int i;
02727 
02728       for (i = 0; i < ARRAY_LEN(prefixes); i++) {
02729          memset(&ifr, 0, sizeof(ifr));
02730          snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s%d", prefixes[i], x);
02731          if (!ioctl(s, SIOCGIFHWADDR, &ifr)) {
02732             break;
02733          }
02734       }
02735 
02736       if (i == ARRAY_LEN(prefixes)) {
02737          /* Try pciX#[1..N] */
02738          for (i = 0; i < MAXIF; i++) {
02739             memset(&ifr, 0, sizeof(ifr));
02740             snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "pci%d#%u", x, i);
02741             if (!ioctl(s, SIOCGIFHWADDR, &ifr)) {
02742                break;
02743             }
02744          }
02745          if (i == MAXIF) {
02746             continue;
02747          }
02748       }
02749 
02750       memcpy(eid, ((unsigned char *)&ifr.ifr_hwaddr) + 2, sizeof(*eid));
02751       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);
02752       close(s);
02753       return;
02754    }
02755    close(s);
02756 #else
02757 #if defined(ifa_broadaddr) && !defined(SOLARIS)
02758    char eid_str[20];
02759    struct ifaddrs *ifap;
02760 
02761    if (getifaddrs(&ifap) == 0) {
02762       struct ifaddrs *p;
02763       for (p = ifap; p; p = p->ifa_next) {
02764          if ((p->ifa_addr->sa_family == AF_LINK) && !(p->ifa_flags & IFF_LOOPBACK) && (p->ifa_flags & IFF_RUNNING)) {
02765             struct sockaddr_dl* sdp = (struct sockaddr_dl*) p->ifa_addr;
02766             memcpy(&(eid->eid), sdp->sdl_data + sdp->sdl_nlen, 6);
02767             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);
02768             freeifaddrs(ifap);
02769             return;
02770          }
02771       }
02772       freeifaddrs(ifap);
02773    }
02774 #endif
02775 #endif
02776    ast_debug(1, "No ethernet interface found for seeding global EID. You will have to set it manually.\n");
02777 }

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

Produces SHA1 hash based on input string.

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

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

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

00259 {
00260    struct SHA1Context sha;
00261    char *ptr;
00262    int x;
00263    uint8_t Message_Digest[20];
00264 
00265    SHA1Reset(&sha);
00266 
00267    SHA1Input(&sha, (const unsigned char *) input, strlen(input));
00268 
00269    SHA1Result(&sha, Message_Digest);
00270    ptr = output;
00271    for (x = 0; x < 20; x++)
00272       ptr += sprintf(ptr, "%02hhx", Message_Digest[x]);
00273 }

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

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

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

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

Referenced by websocket_combine_key().

00277 {
00278         struct SHA1Context sha;
00279 
00280         SHA1Reset(&sha);
00281 
00282         SHA1Input(&sha, (const unsigned char *) input, strlen(input));
00283 
00284         SHA1Result(&sha, digest);
00285 }

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

Definition at line 339 of file utils.h.

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

00340 {
00341    int res;
00342 
00343    res = (int) *input + *value;
00344    if (res > 32767)
00345       *input = 32767;
00346    else if (res < -32768)
00347       *input = -32768;
00348    else
00349       *input = (short) res;
00350 }

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

Definition at line 378 of file utils.h.

Referenced by ast_frame_adjust_volume(), and audiohook_read_frame_both().

00379 {
00380    *input /= *value;
00381 }

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

Definition at line 365 of file utils.h.

Referenced by ast_frame_adjust_volume(), and audiohook_read_frame_both().

00366 {
00367    int res;
00368 
00369    res = (int) *input * *value;
00370    if (res > 32767)
00371       *input = 32767;
00372    else if (res < -32768)
00373       *input = -32768;
00374    else
00375       *input = (short) res;
00376 }

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

Definition at line 352 of file utils.h.

Referenced by softmix_process_write_audio().

00353 {
00354    int res;
00355 
00356    res = (int) *input - *value;
00357    if (res > 32767)
00358       *input = 32767;
00359    else if (res < -32768)
00360       *input = -32768;
00361    else
00362       *input = (short) res;
00363 }

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

References ast_eid::eid.

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

02780 {
02781    unsigned int eid_int[6];
02782    int x;
02783 
02784    if (sscanf(s, "%2x:%2x:%2x:%2x:%2x:%2x", &eid_int[0], &eid_int[1], &eid_int[2],
02785        &eid_int[3], &eid_int[4], &eid_int[5]) != 6) {
02786          return -1;
02787    }
02788 
02789    for (x = 0; x < 6; x++) {
02790       eid->eid[x] = eid_int[x];
02791    }
02792 
02793    return 0;
02794 }

void ast_unescape_quoted ( char *  quote_str  ) 

Unescape quotes in a string.

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

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

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

00519 {
00520    int esc_pos;
00521    int unesc_pos;
00522    int quote_str_len = strlen(quote_str);
00523 
00524    for (esc_pos = 0, unesc_pos = 0;
00525       esc_pos < quote_str_len;
00526       esc_pos++, unesc_pos++) {
00527       if (quote_str[esc_pos] == '\\') {
00528          /* at least one more char and current is \\ */
00529          esc_pos++;
00530          if (esc_pos >= quote_str_len) {
00531             break;
00532          }
00533       }
00534 
00535       quote_str[unesc_pos] = quote_str[esc_pos];
00536    }
00537    quote_str[unesc_pos] = '\0';
00538 }

void ast_unregister_thread ( void *  id  ) 

Definition at line 584 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, thread_list_t::id, ast_atexit::list, and thread_list_t::name.

Referenced by dummy_start().

00585 {
00586    struct thread_list_t *x;
00587 
00588    AST_RWLIST_WRLOCK(&thread_list);
00589    AST_RWLIST_TRAVERSE_SAFE_BEGIN(&thread_list, x, list) {
00590       if ((void *) x->id == id) {
00591          AST_RWLIST_REMOVE_CURRENT(list);
00592          break;
00593       }
00594    }
00595    AST_RWLIST_TRAVERSE_SAFE_END;
00596    AST_RWLIST_UNLOCK(&thread_list);
00597    if (x) {
00598       ast_free(x->name);
00599       ast_free(x);
00600    }
00601 }

void ast_uri_decode ( char *  s,
struct ast_flags  spec 
)

Decode URI, URN, URL (overwrite string).

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

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

References ast_test_flag, AST_URI_LEGACY_SPACE, and tmp().

Referenced by acf_curl_helper(), ast_ari_invoke(), ast_http_get_post_vars(), AST_TEST_DEFINE(), config_curl(), get_destination(), get_name_and_number(), get_refer_info(), handle_request_invite(), handle_uri(), parse_moved_contact(), realtime_curl(), realtime_multi_curl(), sip_new(), sip_uri_cmp(), and uridecode().

00439 {
00440    char *o;
00441    unsigned int tmp;
00442 
00443    for (o = s; *s; s++, o++) {
00444       if (ast_test_flag(&spec, AST_URI_LEGACY_SPACE) && *s == '+') {
00445          /* legacy mode, decode '+' as space */
00446          *o = ' ';
00447       } else if (*s == '%' && s[1] != '\0' && s[2] != '\0' && sscanf(s + 1, "%2x", &tmp) == 1) {
00448          /* have '%', two chars and correct parsing */
00449          *o = tmp;
00450          s += 2;  /* Will be incremented once more when we break out */
00451       } else /* all other cases, just copy */
00452          *o = *s;
00453    }
00454    *o = '\0';
00455 }

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

Turn text string to URI-encoded XX version.

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

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

Parameters:
string string to be converted
outbuf resulting encoded string
buflen size of output buffer
spec flags describing how the encoding should be performed
Returns:
a pointer to the uri encoded string

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

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

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

00400 {
00401    const char *ptr  = string; /* Start with the string */
00402    char *out = outbuf;
00403    const char *mark = "-_.!~*'()"; /* no encode set, RFC 2396 section 2.3, RFC 3261 sec 25 */
00404    const char *user_unreserved = "&=+$,;?/"; /* user-unreserved set, RFC 3261 sec 25 */
00405 
00406    while (*ptr && out - outbuf < buflen - 1) {
00407       if (ast_test_flag(&spec, AST_URI_LEGACY_SPACE) && *ptr == ' ') {
00408          /* for legacy encoding, encode spaces as '+' */
00409          *out = '+';
00410          out++;
00411       } else if (!(ast_test_flag(&spec, AST_URI_MARK)
00412             && strchr(mark, *ptr))
00413          && !(ast_test_flag(&spec, AST_URI_ALPHANUM)
00414             && ((*ptr >= '0' && *ptr <= '9')
00415             || (*ptr >= 'A' && *ptr <= 'Z')
00416             || (*ptr >= 'a' && *ptr <= 'z')))
00417          && !(ast_test_flag(&spec, AST_URI_SIP_USER_UNRESERVED)
00418             && strchr(user_unreserved, *ptr))) {
00419 
00420          if (out - outbuf >= buflen - 3) {
00421             break;
00422          }
00423          out += sprintf(out, "%%%02hhX", (unsigned char) *ptr);
00424       } else {
00425          *out = *ptr;   /* Continue copying the string */
00426          out++;
00427       }
00428       ptr++;
00429    }
00430 
00431    if (buflen) {
00432       *out = '\0';
00433    }
00434 
00435    return outbuf;
00436 }

int ast_utils_init ( void   ) 

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

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

Referenced by main().

02471 {
02472    dev_urandom_fd = open("/dev/urandom", O_RDONLY);
02473    base64_init();
02474 #ifdef DEBUG_THREADS
02475 #if !defined(LOW_MEMORY)
02476    ast_cli_register_multiple(utils_cli, ARRAY_LEN(utils_cli));
02477 #endif
02478 #endif
02479    ast_register_cleanup(utils_shutdown);
02480    return 0;
02481 }

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

Resolve a binary to a full pathname.

Parameters:
binary Name of the executable to resolve
fullpath Buffer to hold the complete pathname
fullpath_size Size of fullpath
Return values:
NULL binary was not found or the environment variable PATH is not set
Returns:
fullpath

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

References ast_strdupa, NULL, and strsep().

02640 {
02641    const char *envPATH = getenv("PATH");
02642    char *tpath, *path;
02643    struct stat unused;
02644    if (!envPATH) {
02645       return NULL;
02646    }
02647    tpath = ast_strdupa(envPATH);
02648    while ((path = strsep(&tpath, ":"))) {
02649       snprintf(fullpath, fullpath_size, "%s/%s", path, binary);
02650       if (!stat(fullpath, &unused)) {
02651          return fullpath;
02652       }
02653    }
02654    return NULL;
02655 }

int ast_wait_for_input ( int  fd,
int  ms 
)

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

References ast_poll.

Referenced by action_waitevent(), ast_ari_websocket_session_read(), ast_tcptls_server_root(), dahdi_test_timer(), get_input(), moh_class_destructor(), sip_tcptls_read(), sip_websocket_callback(), tcptls_stream_read(), tcptls_stream_write(), unbound_resolver_thread(), websocket_cb(), websocket_echo_callback(), and ws_safe_read().

01315 {
01316    struct pollfd pfd[1];
01317 
01318    memset(pfd, 0, sizeof(pfd));
01319    pfd[0].fd = fd;
01320    pfd[0].events = POLLIN | POLLPRI;
01321    return ast_poll(pfd, 1, ms);
01322 }

int ast_wait_for_output ( int  fd,
int  ms 
)

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

References ast_poll.

Referenced by tcptls_stream_read(), and tcptls_stream_write().

01325 {
01326    struct pollfd pfd[1];
01327 
01328    memset(pfd, 0, sizeof(pfd));
01329    pfd[0].fd = fd;
01330    pfd[0].events = POLLOUT;
01331    return ast_poll(pfd, 1, ms);
01332 }

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:
string String to be converted
outbuf Resulting encoded string
buflen Size of output buffer
Returns:
0 for success

-1 if buflen is too short.

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

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

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

00541 {
00542    char *dst = outbuf;
00543    char *end = outbuf + buflen - 1; /* save one for the null terminator */
00544 
00545    /* Handle the case for the empty output buffer */
00546    if (buflen == 0) {
00547       return -1;
00548    }
00549 
00550    /* Escaping rules from http://www.w3.org/TR/REC-xml/#syntax */
00551    /* This also prevents partial entities at the end of a string */
00552    while (*string && dst < end) {
00553       const char *entity = NULL;
00554       int len = 0;
00555 
00556       switch (*string) {
00557       case '<':
00558          entity = "&lt;";
00559          len = 4;
00560          break;
00561       case '&':
00562          entity = "&amp;";
00563          len = 5;
00564          break;
00565       case '>':
00566          /* necessary if ]]> is in the string; easier to escape them all */
00567          entity = "&gt;";
00568          len = 4;
00569          break;
00570       case '\'':
00571          /* necessary in single-quoted strings; easier to escape them all */
00572          entity = "&apos;";
00573          len = 6;
00574          break;
00575       case '"':
00576          /* necessary in double-quoted strings; easier to escape them all */
00577          entity = "&quot;";
00578          len = 6;
00579          break;
00580       default:
00581          *dst++ = *string++;
00582          break;
00583       }
00584 
00585       if (entity) {
00586          ast_assert(len == strlen(entity));
00587          if (end - dst < len) {
00588             /* no room for the entity; stop */
00589             break;
00590          }
00591          /* just checked for length; strcpy is fine */
00592          strcpy(dst, entity);
00593          dst += len;
00594          ++string;
00595       }
00596    }
00597    /* Write null terminator */
00598    *dst = '\0';
00599    /* If any chars are left in string, return failure */
00600    return *string == '\0' ? 0 : -1;
00601 }


Variable Documentation

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.
 


Generated on Thu Apr 16 06:34:38 2015 for Asterisk - The Open Source Telephony Project by  doxygen 1.5.6