Asterisk - The Open Source Telephony Project  18.5.0
Data Structures | Macros | Enumerations | Functions | Variables
utils.h File Reference

Utility functions. More...

#include "asterisk/network.h"
#include <time.h>
#include <unistd.h>
#include <string.h>
#include "asterisk/lock.h"
#include "asterisk/logger.h"
#include "asterisk/localtime.h"
#include "asterisk/stringfields.h"
#include "asterisk/strings.h"
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
 

Macros

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

Enumerations

enum  ast_fd_flag_operation { AST_FD_FLAG_SET, AST_FD_FLAG_CLEAR }
 

Functions

void DO_CRASH_NORETURN __ast_assert_failed (int condition, const char *condition_str, const char *file, int line, const char *function)
 
int __ast_fd_set_flags (int fd, int flags, enum ast_fd_flag_operation op, const char *file, int lineno, const char *function)
 
static void force_inline _ast_assert (int condition, const char *condition_str, const char *file, int line, const char *function)
 
int ast_background_stacksize (void)
 
int ast_base64decode (unsigned char *dst, const char *src, int max)
 Decode data from base64. More...
 
char * ast_base64decode_string (const char *src)
 Same as ast_base64decode, but does the math for you and returns a decoded string. More...
 
int ast_base64encode (char *dst, const unsigned char *src, int srclen, int max)
 Encode data in base64. More...
 
int ast_base64encode_full (char *dst, const unsigned char *src, int srclen, int max, int linebreaks)
 encode text to BASE64 coding More...
 
char * ast_base64encode_string (const char *src)
 Same as ast_base64encode, but does hte math for you and returns an encoded string. More...
 
int ast_base64url_decode (unsigned char *dst, const char *src, int max)
 Decode data from base64 URL. More...
 
char * ast_base64url_decode_string (const char *src)
 Decode string from base64 URL. More...
 
int ast_base64url_encode (char *dst, const unsigned char *src, int srclen, int max)
 Encode data in base64 URL. More...
 
int ast_base64url_encode_full (char *dst, const unsigned char *src, int srclen, int max, int linebreaks)
 Same as ast_base64encode_full but for base64 URL. More...
 
char * ast_base64url_encode_string (const char *src)
 Encode string in base64 URL. More...
 
int ast_careful_fwrite (FILE *f, int fd, const char *s, size_t len, int timeoutms)
 Write data to a file stream with a timeout. More...
 
int ast_carefulwrite (int fd, char *s, int len, int timeoutms)
 Try to write string, but wait no more than ms milliseconds before timing out. More...
 
int ast_check_ipv6 (void)
 Test that an OS supports IPv6 Networking. More...
 
int ast_compare_versions (const char *version1, const char *version2)
 Compare 2 major.minor.patch.extra version strings. More...
 
char * ast_crypt (const char *key, const char *salt)
 Asterisk wrapper around crypt(3). More...
 
char * ast_crypt_encrypt (const char *key)
 Asterisk wrapper around crypt(3) for encrypting passwords. More...
 
int ast_crypt_validate (const char *key, const char *expected)
 Asterisk wrapper around crypt(3) for validating passwords. More...
 
void DO_CRASH_NORETURN ast_do_crash (void)
 Force a crash if DO_CRASH is defined. More...
 
int ast_eid_cmp (const struct ast_eid *eid1, const struct ast_eid *eid2)
 Compare two EIDs. More...
 
int ast_eid_is_empty (const struct ast_eid *eid)
 Check if EID is empty. More...
 
char * ast_eid_to_str (char *s, int maxlen, struct ast_eid *eid)
 Convert an EID to a string. More...
 
void ast_enable_packet_fragmentation (int sock)
 Disable PMTU discovery on a socket. More...
 
char * ast_escape_quoted (const char *string, char *outbuf, int buflen)
 Escape characters found in a quoted string. More...
 
char * ast_escape_semicolons (const char *string, char *outbuf, int buflen)
 Escape semicolons found in a string. More...
 
int ast_file_is_readable (const char *filename)
 Test that a file exists and is readable by the effective user. More...
 
int ast_get_tid (void)
 Get current thread ID. More...
 
struct hostent * ast_gethostbyname (const char *host, struct ast_hostent *hp)
 Thread-safe gethostbyname function to use in Asterisk. More...
 
void ast_md5_hash (char *output, const char *input)
 Produces MD5 hash based on input string. More...
 
int ast_mkdir (const char *path, int mode)
 Recursively create directory path. More...
 
int ast_parse_digest (const char *digest, struct ast_http_digest *d, int request, int pedantic)
 Parse digest authorization header. More...
 
char * ast_process_quotes_and_slashes (char *start, char find, char replace_with)
 Process a string to find and replace characters. More...
 
int ast_pthread_create_detached_stack (pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *), void *data, size_t stacksize, const char *file, const char *caller, int line, const char *start_fn)
 
int ast_pthread_create_stack (pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *), void *data, size_t stacksize, const char *file, const char *caller, int line, const char *start_fn)
 
long int ast_random (void)
 
void ast_register_thread (char *name)
 
void ast_replace_subargument_delimiter (char *s)
 Replace '^' in a string with ','. More...
 
int ast_safe_mkdir (const char *base_path, const char *path, int mode)
 Recursively create directory path, but only if it resolves within the given base_path. More...
 
void ast_set_default_eid (struct ast_eid *eid)
 Fill in an ast_eid with the default eid of this machine. More...
 
void ast_sha1_hash (char *output, const char *input)
 Produces SHA1 hash based on input string. More...
 
void ast_sha1_hash_uint (uint8_t *digest, const char *input)
 Produces SHA1 hash based on input string, stored in uint8_t array. More...
 
static force_inline void ast_slinear_saturated_add (short *input, short *value)
 
static force_inline void ast_slinear_saturated_divide (short *input, short *value)
 
static force_inline void ast_slinear_saturated_divide_float (short *input, float *value)
 
static force_inline void ast_slinear_saturated_multiply (short *input, short *value)
 
static force_inline void ast_slinear_saturated_multiply_float (short *input, float *value)
 
static force_inline void ast_slinear_saturated_subtract (short *input, short *value)
 
int ast_str_to_eid (struct ast_eid *eid, const char *s)
 Convert a string into an EID. More...
 
int ast_thread_is_user_interface (void)
 Indicates whether the current thread is a user interface. More...
 
int ast_thread_user_interface_set (int is_user_interface)
 Set the current thread's user interface status. More...
 
void ast_unescape_quoted (char *quote_str)
 Unescape quotes in a string. More...
 
void ast_unregister_thread (void *id)
 
void ast_uri_decode (char *s, struct ast_flags spec)
 Decode URI, URN, URL (overwrite string) More...
 
char * ast_uri_encode (const char *string, char *outbuf, int buflen, struct ast_flags spec)
 Turn text string to URI-encoded XX version. More...
 
int ast_utils_init (void)
 
char * ast_utils_which (const char *binary, char *fullpath, size_t fullpath_size)
 Resolve a binary to a full pathname. More...
 
int ast_wait_for_input (int fd, int ms)
 
int ast_wait_for_output (int fd, int ms)
 
int ast_xml_escape (const char *string, char *outbuf, size_t buflen)
 Escape reserved characters for use in XML. More...
 

Variables

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

Detailed Description

Utility functions.

Definition in file utils.h.

Macro Definition Documentation

◆ ARRAY_IN_BOUNDS

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

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

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

Definition at line 658 of file utils.h.

Referenced by ast_sip_auth_type_to_str(), ast_sip_overload_trigger_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().

◆ ARRAY_LEN

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

Definition at line 639 of file utils.h.

◆ ast_align_for

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

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

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

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

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

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

Definition at line 758 of file utils.h.

Referenced by __ast_string_field_ptr_build_va().

◆ ast_alignof

#define ast_alignof (   type)    __alignof__(type)

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

Parameters
type
Returns
The number of bytes required for alignment.

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

Definition at line 738 of file utils.h.

Referenced by __ast_string_field_alloc_space(), and __ast_string_field_ptr_build_va().

◆ ast_assert

#define ast_assert (   a)    _ast_assert(a, # a, __FILE__, __LINE__, __PRETTY_FUNCTION__)
Examples:
/usr/src/asterisk-18.5.0/include/asterisk/strings.h, and /usr/src/asterisk-18.5.0/main/app.c.

Definition at line 695 of file utils.h.

Referenced by __after_bridge_set_goto(), __ao2_find(), __ao2_global_obj_ref(), __ao2_global_obj_replace(), __ao2_ref(), __ao2_weakproxy_alloc(), __ao2_weakproxy_find(), __ast_calloc_with_stringfields(), __ast_fd_set_flags(), __ast_format_cap_append(), __ast_named_lock_get(), __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_string_fields_cmp(), __ast_string_fields_copy(), ack_ticks(), action_dahdishowchannels(), add_hints(), add_static_payload(), agents_post_apply_config(), announce_request(), ao2_container_check(), ao2_container_dump(), ao2_container_stats(), app_control_continue(), app_control_redirect(), app_create(), app_dtor(), app_exec(), app_handle_subscriptions(), 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_add_log(), ast_ari_asterisk_delete_log(), ast_ari_asterisk_get_global_var(), ast_ari_asterisk_get_module(), ast_ari_asterisk_load_module(), ast_ari_asterisk_ping(), ast_ari_asterisk_reload_module(), ast_ari_asterisk_rotate_log(), ast_ari_asterisk_set_global_var(), ast_ari_asterisk_unload_module(), ast_ari_bridges_record(), ast_ari_callback(), ast_ari_channels_continue_in_dialplan(), ast_ari_channels_external_media(), 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_ari_websocket_events_event_websocket_established(), ast_begins_with(), ast_bridge_add_channel(), ast_bridge_channel_restore_formats(), ast_bridge_depart(), ast_bridge_get_snapshot_by_uniqueid(), ast_bridge_join(), ast_bridge_merge(), ast_bridge_publish_merge(), ast_bridge_publish_state(), ast_bridge_set_after_callback(), ast_bridge_set_remb_estimated_bitrate(), ast_bridge_set_remb_send_interval(), ast_brige_set_remb_behavior(), ast_cc_is_recall(), ast_cdr_serialize_variables(), ast_channel_destructor(), ast_channel_forward_endpoint(), ast_channel_get_cc_config_params(), ast_channel_get_default_stream(), ast_channel_get_duration_ms(), ast_channel_get_stream_topology(), ast_channel_get_up_time_ms(), ast_channel_internal_oldest_linkedid(), ast_channel_internal_setup_topics(), ast_channel_internal_swap_stream_topology(), ast_channel_linkedid(), ast_channel_nativeformats_set(), ast_channel_publish_dial_forward(), ast_channel_publish_dial_internal(), ast_channel_publish_snapshot(), ast_channel_publish_varset(), ast_channel_request_stream_topology_change(), ast_channel_set_stream_topology(), 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_stream_topology_changed(), ast_channel_stream_topology_changed_externally(), ast_channel_tech_set(), ast_channel_uniqueid(), ast_cli_completion_vector(), ast_data_buffer_alloc(), ast_data_buffer_cache_adjust(), ast_data_buffer_count(), ast_data_buffer_free(), ast_data_buffer_get(), ast_data_buffer_max(), ast_data_buffer_put(), ast_data_buffer_remove(), ast_data_buffer_remove_head(), ast_data_buffer_resize(), ast_datastores_add(), 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_query_set_add(), ast_dns_query_set_resolve_async(), ast_dns_srv_get_host(), ast_dns_srv_get_port(), ast_dns_srv_get_priority(), ast_dns_srv_get_weight(), ast_dns_txt_get_count(), ast_dns_txt_get_strings(), 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_get_extension_for_mime_type(), ast_hangup(), ast_http_body_discard(), ast_http_get_auth(), ast_http_get_contents(), ast_http_send(), ast_iostream_set_exclusive_input(), ast_iostream_set_timeout_disable(), ast_iostream_set_timeout_idle_inactivity(), ast_iostream_set_timeout_inactivity(), ast_iostream_set_timeout_sequence(), ast_json_to_ast_variables(), ast_json_typename(), ast_json_typeof(), ast_manager_event_blob_create(), ast_msg_data_alloc(), ast_msg_data_dup(), ast_msg_data_get_attribute(), ast_msg_data_get_length(), ast_msg_data_get_source_type(), ast_msg_data_queue_frame(), ast_multi_channel_blob_create(), ast_multi_object_blob_create(), ast_mwi_blob_create(), ast_pbx_outgoing_exten_predial(), ast_publish_device_state_full(), ast_register_thread(), ast_res_pjsip_find_or_create_contact_status(), ast_rtcp_read(), ast_rtp_codecs_payloads_xover(), ast_rtp_ice_turn_request(), ast_rtp_on_ice_tx_pkt(), ast_rtp_read(), ast_search_dns_ex(), ast_serializer_pool_create(), ast_serializer_shutdown_group_join(), ast_set_read_format(), ast_set_write_format(), ast_set_write_format_interleaved_stereo(), ast_sip_auth_vector_init(), ast_sip_create_request(), ast_sip_get_contact_short_status_label(), ast_sip_get_contact_status_label(), ast_sip_identify_endpoint(), 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_register_supplement_with_module(), ast_sip_session_suspend(), ast_sip_subscription_get_dialog(), ast_sip_subscription_get_endpoint(), ast_sip_subscription_get_serializer(), ast_sip_transport_monitor_register_replace(), ast_sip_transport_monitor_unregister(), ast_sip_transport_monitor_unregister_all(), ast_sorcery_init(), ast_sorcery_is_object_field_registered(), ast_sorcery_object_id_hash(), ast_stream_get_format_count(), ast_stream_get_formats(), ast_stream_get_group(), ast_stream_get_name(), ast_stream_get_position(), ast_stream_get_rtp_codecs(), ast_stream_get_state(), ast_stream_get_type(), ast_stream_set_formats(), ast_stream_set_group(), ast_stream_set_rtp_codecs(), ast_stream_set_state(), ast_stream_set_type(), ast_stream_topology_append_stream(), ast_stream_topology_clone(), ast_stream_topology_del_stream(), ast_stream_topology_equal(), ast_stream_topology_get_active_count(), ast_stream_topology_get_count(), ast_stream_topology_get_first_stream_by_type(), ast_stream_topology_get_formats_by_type(), ast_stream_topology_get_stream(), ast_stream_topology_set_stream(), ast_taskprocessor_build_name(), ast_taskprocessor_name_append(), AST_TEST_DEFINE(), ast_udptl_read(), ast_utf8_copy_string(), ast_uuid_to_str(), ast_variable_list_append_hint(), ast_vector_string_split(), ast_xml_escape(), async_callback(), attended_transfer_monitor_thread(), authenticate(), autohint_cmp(), autohint_hash_cb(), base_process_parked_channel(), base_process_party_a(), bridge_action_bridge(), 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_impart_add(), bridge_channel_internal_push_full(), 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_parking_push(), bridge_publish_state_from_blob(), bridge_stasis_moving(), bridge_state_process_party_b(), bridge_topics_destroy(), bridges_channel_hash_fn(), bridges_channel_sort_fn(), bridges_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_all_cmp_fn(), cdr_all_hash_fn(), cdr_all_unlink(), cdr_master_cmp_fn(), cdr_master_hash_fn(), cdr_object_alloc(), cdr_object_create_public_records(), cdr_object_finalize_party_b(), cdr_object_party_b_left_bridge_cb(), cdr_object_update_party_b_userfield_cb(), cdr_read_callback(), cdr_write_callback(), 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_role_hash_cb(), channel_set_default_streams(), channel_snapshot_hash_cb(), channel_snapshot_uniqueid_hash_cb(), check_callback_sanity(), cli_aor_print_body(), cli_aor_print_header(), cli_channel_print_body(), cli_channel_print_header(), cli_channelstats_print_body(), cli_channelstats_print_header(), cli_complete_subscription_callid(), cli_contact_print_body(), cli_contact_print_header(), cli_endpoint_print_body(), cli_endpoint_print_header(), cli_list_subscriptions_inout(), cli_print_body(), cli_print_header(), cli_show_module_options(), cli_show_module_type(), cli_show_module_types(), cli_show_modules(), cli_show_subscription_inout(), cli_show_subscriptions_inout(), cli_unid_print_body(), cli_unid_print_header(), codec_cmp(), confbridge_publish_manager_event(), conference_bridge_hash_cb(), consumer_exec(), consumer_exec_sync(), consumer_should_stay(), consumer_wait_for(), consumer_wait_for_completion(), contact_alloc(), control_dispatch_all(), control_hash(), control_swap_channel_in_bridge(), control_wait(), copy_state_to_transport(), corosync_node_cmp_fn(), corosync_node_hash_fn(), create_callno_pools(), create_dialog_uas(), 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(), dialog_associations_cmp(), dialog_associations_hash(), digest_check_auth(), digest_create_request_with_auth(), dns_find_record(), dns_naptr_alloc(), dns_srv_alloc(), dsn_hash(), endpoint_cache_clear(), endpoint_dtor(), endpoint_publish_snapshot(), endpoint_snapshot_dtor(), evaluate_history_entry(), event_session_dtor(), event_session_hash(), event_session_update_websocket(), expression_token_alloc(), exten_state_publisher_cmp(), exten_state_publisher_hash(), extension_is_compatible(), featuregroup_hash(), features_pre_apply_config(), filename_parse(), find_bridge(), find_channel_control(), find_control(), find_route(), format_cap_replace(), format_cmp_cb(), format_hash_cb(), forwards_create_endpoint(), forwards_dtor(), forwards_sort(), framein(), get_allowed_field(), get_park_common_datastore_copy(), get_rdnis(), get_unused_callno(), handle_bridge_enter_message(), handle_bridge_leave_message(), handle_channel_snapshot_update_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(), header_identify_match_check(), hep_queue_cb(), hintdevice_cmp_multiple(), hintdevice_hash_cb(), holding_bridge_join(), ht_new(), iax2_codec_pref_best_bitfield2cap(), iax2_codec_pref_from_bitfield(), iax2_codec_pref_prepend(), ident_to_str(), internal_bridge_after_cb(), internal_state_cmp(), internal_state_hash(), iostream_dtor(), jb_get_and_deliver(), load_dlopen(), log_attended_transfer(), logger_queue_start(), manager_notify_channel(), manager_notify_endpoint(), manager_notify_uri(), mark_object_as_stale_in_cache(), meetme_stasis_cb(), menu_hash_cb(), message_subscription_hash_cb(), module_load_helper_on_file(), module_matches_helper_type(), moh_post_start(), moh_post_stop(), monitored_transport_hash_fn(), mwi_create_state(), 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_rtp_bridge_framehook_attach(), native_rtp_bridge_join(), native_rtp_bridge_start(), native_rtp_bridge_stop(), native_start(), native_stop(), 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_hash_fn(), participant_entertainment_start(), participant_entertainment_stop(), participant_idle_mode_setup(), payload_helper_cb(), pending_members_cmp(), pending_members_hash(), permanent_uri_sort_fn(), pj2ast_rtp_ice_role(), play_on_channel(), playback_publish(), print_frame(), proc_session_timer(), process_config(), process_options(), prometheus_metric_type_to_string(), pthread_timer_ack(), publish_cluster_discovery_to_stasis(), publish_corosync_ping_to_stasis(), publish_dahdichannel(), publish_device_state_to_stasis(), publish_expire(), publish_load_message_type(), 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(), remove_excess_contacts(), remove_from_cache(), remove_oldest_from_cache(), replace_callno(), resamp_new(), resolution_thread(), route_table_add(), router_dtor(), rtcp_debug_test_addr(), rx_data_to_ast_msg(), safe_mkdir(), say_parking_space(), sched_settime(), 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(), session_media_set_handler(), set_dial_masquerade(), set_format(), set_ice_components(), set_softmix_bridge_data(), set_target_uri(), setup_invocation_test(), single_state_process_party_b(), sip_cc_agent_init(), sip_cc_monitor_unsuspend(), sip_create_publication(), sip_options_aor_dtor(), sip_options_contact_status_notify_task(), sip_outbound_registration_regc_alloc(), sip_outbound_registration_response_cb(), softmix_bridge_write(), sorcery_memory_cache_create(), sorcery_memory_cache_hash(), sorcery_memory_cache_retrieve_id(), sorcery_memory_cache_thrash_retrieve(), sorcery_memory_cache_thrash_update(), sorcery_memory_cached_object_hash(), stasis_app_exec(), stasis_app_message_handler(), 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_accept_formatters(), 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_formatters_default(), stasis_publish_sync(), stasis_state_callback_all(), stasis_state_callback_subscribed(), stasis_sub_hash(), stasis_subscription_accept_formatters(), stasis_subscription_accept_message_type(), stasis_subscription_decline_message_type(), state_alloc(), state_dtor(), state_id_by_topic(), statsd_init(), stream_periodic_frames(), sub_endpoint_update_handler(), subscription_dtor(), subscription_statistics_cmp(), subscription_statistics_hash(), suspects_hash(), t38_change_state(), test_cel_init_cb(), test_handler(), test_is_media_state_equal(), topic_dtor(), topic_pool_entry_cmp(), topic_pool_entry_hash(), topic_statistics_cmp(), topic_statistics_hash(), tos_handler(), transport_state2str(), transport_state_callback(), transport_state_cmp(), transport_state_hash(), uas_use_sips_contact(), uid_hold_hash_fn(), uid_hold_sort_fn(), update2_odbc(), update_create(), user_hash_cb(), user_sort_cmp(), wait_bridge_hash_fn(), wait_bridge_sort_fn(), worker_set_state(), ws_safe_read(), and xmldoc_update_config_option().

◆ ast_assert_return

#define ast_assert_return (   a,
  ... 
)

◆ AST_BACKGROUND_STACKSIZE

#define AST_BACKGROUND_STACKSIZE   ast_background_stacksize()

Definition at line 546 of file utils.h.

◆ ast_clear_flag

#define ast_clear_flag (   p,
  flag 
)
Examples:
/usr/src/asterisk-18.5.0/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(), agent_logout(), analog_ss_thread(), app_exec(), ast_audiohook_set_mute(), ast_autoservice_stop(), ast_cdr_clear_property(), ast_cdr_fork(), ast_channel_clear_flag(), ast_channel_publish_snapshot(), ast_channel_stage_snapshot_done(), ast_jb_conf_default(), ast_jb_destroy(), ast_jb_put(), ast_sendtext_data(), ast_settimeout_full(), ast_speech_start(), AST_TEST_DEFINE(), ast_tls_read_conf(), ast_translate(), ast_unreal_hangup(), ast_waitfor_nandfds(), ast_write_stream(), asterisk_daemon(), audiohook_list_set_hook_rate(), bridge_basic_change_personality(), bridge_channel_internal_push_full(), bridge_p2p_rtp_write(), change_hold_state(), change_spy_mode(), channel_do_masquerade(), chanspy_exec(), check_for_nat(), check_pendings(), 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_or_trace(), 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_asterisk_conf(), 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(), remb_behavior_handler(), res_sdp_crypto_parse_offer(), reset_transaction(), rtp_raw_write(), set_config(), set_config_flags(), set_peer_nat(), setup_dahdi_int(), sip_call(), sip_dtmfmode(), sip_endpoint_apply_handler(), sip_hangup(), sip_parse_nat_option(), sip_reload(), sip_set_rtp_peer(), socket_process_helper(), speech_background(), update_call_counter(), update_connectedline(), and video_mode_handler().

◆ ast_clear_flag64

#define ast_clear_flag64 (   p,
  flag 
)

◆ ast_clear_flag_nonstd

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

Definition at line 180 of file utils.h.

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

◆ ast_copy_flags

#define ast_copy_flags (   dest,
  src,
  flagz 
)

◆ ast_copy_flags64

#define ast_copy_flags64 (   dest,
  src,
  flagz 
)

◆ ast_copy_flags_nonstd

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

Definition at line 184 of file utils.h.

◆ ast_fd_clear_flags

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

Clear flags on the given file descriptor.

Since
13.19

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

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

Definition at line 1025 of file utils.h.

Referenced by ast_tcptls_client_start(), and ast_tcptls_server_root().

◆ ast_fd_set_flags

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

Set flags on the given file descriptor.

Since
13.19

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

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

Definition at line 1009 of file utils.h.

Referenced by __ast_fd_set_flags(), ast_alertpipe_init(), ast_iostream_nonblock(), cops_connect(), dahdi_translate(), ices_exec(), launch_script(), listener(), mkif(), and websocket_echo_callback().

◆ AST_FLAGS_ALL

#define AST_FLAGS_ALL   UINT_MAX

◆ ast_make_room_for

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

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

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

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

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

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

Definition at line 781 of file utils.h.

Referenced by __ast_string_field_alloc_space(), and __ast_string_field_ptr_build_va().

◆ ast_pipe_nonblock

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

Create a non-blocking pipe.

Since
13.25

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

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

Definition at line 1060 of file utils.h.

Referenced by __ast_fd_set_flags(), mohalloc(), and pthread_timer_open().

◆ ast_pthread_create

#define ast_pthread_create (   a,
  b,
  c,
  d 
)
Value:
0, __FILE__, __FUNCTION__, __LINE__, #c)
static struct test_val d
static struct test_val c
static struct test_val b
int ast_pthread_create_stack(pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *), void *data, size_t stacksize, const char *file, const char *caller, int line, const char *start_fn)
Definition: main/utils.c:1446
static struct test_val a

Definition at line 559 of file utils.h.

Referenced by accept_thread(), ast_dial_run(), AST_TEST_DEFINE(), bridge_impart_internal(), bridge_manager_create(), build_calendar(), default_listener_start(), handle_call_outgoing(), init_logger(), keepalive_global_loaded(), load_module(), restart_monitor(), setsubstate(), setup_dahdi_int(), sla_load_config(), softmix_bridge_create(), sorcery_memory_cache_thrash_start(), start_poll_thread(), unbound_resolver_start(), and worker_thread_start().

◆ ast_pthread_create_background

#define ast_pthread_create_background (   a,
  b,
  c,
  d 
)
Value:
__FILE__, __FUNCTION__, __LINE__, #c)
static struct test_val d
static struct test_val c
static struct test_val b
int ast_pthread_create_stack(pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *), void *data, size_t stacksize, const char *file, const char *caller, int line, const char *start_fn)
Definition: main/utils.c:1446
#define AST_BACKGROUND_STACKSIZE
Definition: utils.h:546
static struct test_val a
Examples:
/usr/src/asterisk-18.5.0/main/app.c.

Definition at line 567 of file utils.h.

Referenced by add_notify(), ast_autoservice_start(), ast_device_state_engine_init(), ast_makesocket(), ast_safe_fork(), ast_sched_start_thread(), ast_tcptls_server_start(), AST_TEST_DEFINE(), astdb_init(), calendar_event_notify(), cdr_enable_batch_mode(), conf_run(), config_load(), db_start_batch(), do_monitor(), do_reload(), expiration_global_loaded(), find_idle_thread(), init_app_class(), init_timing_thread(), load_module(), local_ast_moh_start(), mbl_load_adapter(), ooh323c_start_stack_thread(), restart_monitor(), restart_pktc_thread(), smdi_load(), start_monitor(), start_network_thread(), start_stream(), and xmpp_client_config_post_apply().

◆ ast_pthread_create_detached

#define ast_pthread_create_detached (   a,
  b,
  c,
  d 
)
Value:
0, __FILE__, __FUNCTION__, __LINE__, #c)
static struct test_val d
int ast_pthread_create_detached_stack(pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *), void *data, size_t stacksize, const char *file, const char *caller, int line, const char *start_fn)
Definition: main/utils.c:1494
static struct test_val c
static struct test_val b
static struct test_val a

Definition at line 563 of file utils.h.

Referenced by __analog_handle_event(), action_originate(), analog_handle_init_event(), analog_ss_thread_start(), ari_bridges_play_new(), ari_channels_handle_originate_with_id(), ast_ari_bridges_record(), ast_ari_channels_create(), ast_pbx_start(), asterisk_daemon(), bridge_impart_internal(), bridge_moh_create(), dahdi_handle_event(), do_monitor(), dundi_answer_entity(), dundi_answer_query(), dundi_prop_precache(), feature_attended_transfer(), handle_hd_hf(), handle_init_event(), launch_service(), mwi_thread(), naptr_resolve(), pbx_outgoing_attempt(), query_set_resolve(), recurring_resolve(), spawn_dp_lookup(), srv_resolve(), and test_resolve().

◆ ast_pthread_create_detached_background

#define ast_pthread_create_detached_background (   a,
  b,
  c,
  d 
)
Value:
__FILE__, __FUNCTION__, __LINE__, #c)
static struct test_val d
int ast_pthread_create_detached_stack(pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *), void *data, size_t stacksize, const char *file, const char *caller, int line, const char *start_fn)
Definition: main/utils.c:1494
static struct test_val c
static struct test_val b
#define AST_BACKGROUND_STACKSIZE
Definition: utils.h:546
static struct test_val a

Definition at line 572 of file utils.h.

Referenced by ast_tcptls_server_root(), cc_generic_agent_recall(), cdr_submit_batch(), conf_run(), do_hook(), launch_monitor_thread(), listener(), load_module(), meetme_menu_admin_extended(), ooh323c_start_call_thread(), sip_pickup(), sip_prepare_socket(), sla_handle_dial_state_event(), sla_station_exec(), and stasis_app_control_snoop().

◆ ast_random_double

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

Returns a random number between 0.0 and 1.0, inclusive.

Since
12

Definition at line 599 of file utils.h.

Referenced by ast_statsd_log_string(), gen_salt_char(), and sip_options_determine_initial_qualify_time().

◆ ast_set2_flag

#define ast_set2_flag (   p,
  value,
  flag 
)

◆ ast_set2_flag64

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

◆ ast_set2_flag_nonstd

#define ast_set2_flag_nonstd (   p,
  value,
  flag 
)

Definition at line 189 of file utils.h.

◆ ast_set_flag

#define ast_set_flag (   p,
  flag 
)
Examples:
/usr/src/asterisk-18.5.0/main/app.c.

Definition at line 70 of file utils.h.

Referenced by __analog_ss_thread(), __ast_channel_internal_alloc(), __ast_http_load(), __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_cdr_set_property(), ast_channel_defer_dtmf(), ast_channel_destructor(), ast_channel_set_flag(), ast_channel_snapshot_create(), ast_channel_snapshot_invalidate_segment(), 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_rtp_change_source(), ast_rtp_interpret(), ast_rtp_local_bridge(), ast_rtp_read(), ast_rtp_stop(), ast_rtp_update_source(), ast_settimeout_full(), ast_sip_call_codec_str_to_pref(), ast_speech_change_state(), AST_TEST_DEFINE(), ast_tls_read_conf(), ast_unreal_channel_push_to_bridge(), ast_unreal_new_channels(), ast_waitfor_nandfds(), asterisk_daemon(), audiohook_list_set_hook_rate(), 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_object_create_and_append(), cdr_read_callback(), change_hold_state(), change_spy_mode(), channel_do_masquerade(), chanspy_exec(), check_for_nat(), check_peer_ok(), check_user_full(), check_via(), 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(), 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_or_trace(), 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_asterisk_conf(), 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(), register_verify(), reload_config(), remb_behavior_handler(), res_sdp_crypto_parse_offer(), res_sdp_srtp_get_attr(), rtp_raw_write(), 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_endpoint_apply_handler(), 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(), test_write_frames(), 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_allocate_dh(), vm_execmain(), and volume_write().

◆ ast_set_flag64

#define ast_set_flag64 (   p,
  flag 
)

◆ ast_set_flag_nonstd

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

Definition at line 176 of file utils.h.

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

◆ ast_set_flags_to

#define ast_set_flags_to (   p,
  flag,
  value 
)

◆ ast_set_flags_to64

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

◆ ast_socket_nonblock

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

Create a non-blocking socket.

Since
13.25

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

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

Definition at line 1043 of file utils.h.

Referenced by __ast_fd_set_flags(), ast_audiosocket_connect(), ast_tcptls_server_start(), ast_udptl_new_with_bindaddr(), create_new_socket(), and launch_netscript().

◆ AST_STACKSIZE

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

Definition at line 540 of file utils.h.

Referenced by ast_background_stacksize(), and ast_pthread_create_stack().

◆ AST_STACKSIZE_LOW

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

Definition at line 541 of file utils.h.

Referenced by ast_background_stacksize().

◆ ast_test_flag

#define ast_test_flag (   p,
  flag 
)

Definition at line 63 of file utils.h.

Referenced by __ast_frisolate(), __ast_pbx_run(), __ast_queue_frame(), __ast_read(), __sip_alloc(), __ssl_setup(), __transmit_response(), _macro_exec(), _sip_show_peer(), _sip_show_peers_one(), acf_odbc_read(), 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(), append_vmu_info_astman(), ast_async_goto(), ast_audiohook_attach(), ast_audiohook_write_frame(), ast_autoservice_start(), ast_bridge_channel_playfile(), ast_bridge_join(), ast_bridge_publish_enter(), ast_bridge_publish_leave(), ast_bridge_publish_merge(), ast_bridge_setup_after_goto(), ast_bridge_snapshot_create(), ast_bridge_transfer_acquire_bridge(), ast_bridge_transfer_attended(), ast_bridge_transfer_blind(), ast_call(), ast_can_pickup(), ast_cdr_engine_term(), ast_cdr_fork(), ast_channel_defer_dtmf(), ast_channel_destructor(), ast_channel_end_dtmf(), ast_channel_move(), ast_channel_publish_snapshot(), ast_channel_snapshot_create(), ast_channel_yank(), ast_config_internal_load(), ast_explicit_goto(), 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_multicast_rtp_options_get_format(), ast_pbx_h_exten_run(), ast_pbx_run_args(), ast_pbx_start(), ast_raw_answer_with_stream_topology(), ast_readstring_full(), ast_sendtext_data(), ast_setstate(), ast_settimeout_full(), ast_softhangup_nolock(), ast_streamfile(), AST_TEST_DEFINE(), ast_transfer_protocol(), ast_translate(), ast_unreal_hangup(), ast_unreal_indicate(), ast_uri_decode(), ast_uri_encode(), ast_waitfordigit_full(), ast_write_stream(), attempt_thread(), audiohook_read_frame_both(), audiohook_read_frame_helper(), audiosocket_request(), 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_full(), bridge_config_set_limits(), bridge_dissolve_check_stolen(), bridge_do_merge(), bridge_exec(), bridge_impart_internal(), 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_create_and_append(), cdr_object_pick_party_a(), cdr_read_callback(), cdr_submit_batch(), cdr_toggle_runtime_options(), cel_channel_state_change(), change_hold_state(), channel_do_masquerade(), channel_newexten(), channel_read_rtp(), channel_snapshot_bridge_create(), channel_spy(), channel_state(), 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_handle_inactive_waitmarked(), conf_handle_only_person(), conf_handle_second_active(), conf_handle_talker_cb(), conf_mute_moh_inactive_waitmarked(), conf_mute_only_active(), conf_rec_name(), conf_send_event_to_participants(), conf_update_user_mute(), confbridge_exec(), confbridge_handle_atxfer(), config_text_file_load(), configure_rtcp(), connectedline_write(), controlplayback_exec(), copy_via_headers(), create_addr_from_peer(), create_jb(), destroy_trans(), detect_write(), dial_state_process_party_b(), dialog_initialize_rtp(), dictate_exec(), directory_exec(), disa_exec(), display_nat_warning(), distributor(), 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(), endpoint_cache_clear(), 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_channel_snapshot_update_message(), 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_cdr_flag_set(), is_state_change_valid(), join_conference_bridge(), kick_conference_participant(), launch_monitor_thread(), leave_marked(), leave_voicemail(), limits_interval_playback(), load_dynamic_module(), load_module(), local_alloc(), local_ast_moh_start(), local_devicestate(), main(), make_email_file(), manager_bridge_kick(), 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(), module_vector_cmp(), moh_files_alloc(), moh_scan_files(), multicast_rtp_new(), 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_a_ice(), process_sdp_o(), process_text_line(), publish_local_bridge_message(), queue_exec(), read_exec(), read_mf_exec(), read_sf_exec(), readexten_exec(), realtime_peer(), realtime_switch_common(), receivefax_exec(), record_dtmf_response(), record_exec(), redirecting_write(), reload_config(), reload_handler(), reload_module(), reload_queues(), reload_single_queue(), remove_from_queue(), reqprep(), res_sdp_crypto_parse_offer(), res_sdp_srtp_get_attr(), resetcdr_exec(), respprep(), retrans_pkt(), retrydial_exec(), return_exec(), rtp_raw_write(), search_directory_sub(), select_entry(), select_item_pause(), send_conf_stasis(), 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_ice_components(), 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(), should_trigger_dtmf_emulating(), 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_pvt_dtor(), 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(), start_resource_attempt(), start_spying(), sub_channel_update_handler(), 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(), unicast_rtp_request(), unreal_queue_indicate(), update_call_counter(), update_connectedline(), update_peer(), update_redirecting(), update_registry(), updates(), use_reason_header(), vm_exec(), vm_execmain(), vm_instructions_en(), vm_instructions_ja(), vm_intro(), vm_newuser_setup(), volume_callback(), wait_exec(), 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().

◆ ast_test_flag64

#define ast_test_flag64 (   p,
  flag 
)

◆ ast_test_flag_nonstd

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

◆ AST_URI_ALPHANUM

#define AST_URI_ALPHANUM   (1 << 0)

Definition at line 339 of file utils.h.

Referenced by ast_uri_encode().

◆ AST_URI_LEGACY_SPACE

#define AST_URI_LEGACY_SPACE   (1 << 2)

Definition at line 342 of file utils.h.

Referenced by ast_uri_decode(), and ast_uri_encode().

◆ AST_URI_MARK

#define AST_URI_MARK   (1 << 1)

Definition at line 340 of file utils.h.

Referenced by ast_uri_encode().

◆ AST_URI_SIP_USER_UNRESERVED

#define AST_URI_SIP_USER_UNRESERVED   (1 << 20)

Definition at line 344 of file utils.h.

Referenced by ast_uri_encode().

◆ AST_URI_UNRESERVED

#define AST_URI_UNRESERVED   (AST_URI_ALPHANUM | AST_URI_MARK)

Definition at line 341 of file utils.h.

◆ DO_CRASH_NORETURN

#define DO_CRASH_NORETURN

Definition at line 688 of file utils.h.

Referenced by _ast_assert().

◆ IN_BOUNDS

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

Checks to see if value is within the given bounds.

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

Definition at line 649 of file utils.h.

◆ localtime_r

#define localtime_r   __dont_use_localtime_r_use_ast_localtime_instead__

Definition at line 496 of file utils.h.

◆ MAX

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

◆ MIN

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

◆ RAII_VAR

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

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

Resource Allocation Is Initialization (RAII) variable declaration.

Since
11.0
Parameters
vartypeThe type of the variable
varnameThe name of the variable
initvalThe initial value of the variable
dtorThe destructor function of type' void func(vartype *)'
void mything_cleanup(struct mything *t)
{
if (t) {
ast_free(t->stuff);
}
}
void do_stuff(const char *name)
{
RAII_VAR(struct mything *, thing, mything_alloc(name), mything_cleanup);
...
}
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:
/usr/src/asterisk-18.5.0/main/app.c.

Definition at line 911 of file utils.h.

Referenced by __analog_ss_thread(), __ast_bucket_scheme_register(), __ast_file_read_dirs(), __ast_http_load(), __ast_register_translator(), __ast_sorcery_apply_config(), __ast_sorcery_apply_default(), __ast_sorcery_object_field_register(), __ast_sorcery_object_register(), __ast_sorcery_object_type_insert_wizard(), __ast_sorcery_object_type_remove_wizard(), __ast_sorcery_remove_wizard_mapping(), __ast_test_suite_event_notify(), __ast_udptl_reload(), __ast_vm_greeter_register(), __ast_vm_register(), __expire_registry(), __features_config_alloc(), __iax2_poke_noanswer(), __stasis_app_register(), __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_bridge(), action_devicestatelist(), action_presencestatelist(), active_channels_to_str(), add_crypto_to_stream(), add_datastore(), add_format_information_cb(), add_header(), add_identity_header(), add_item(), add_sdp(), add_sdp_streams(), admin_exec(), adsi_transmit_message_full(), after_bridge_move_channel(), after_bridge_move_channel_fail(), agent_login_exec(), agent_logoff_request(), agent_request_exec(), agents_post_apply_config(), agi_channel_to_ami(), agi_handle_command(), alloc_security_event_json_object(), ami_registrations_aor(), ami_registrations_endpoints(), ami_show_endpoint(), ami_show_endpoints(), ami_sip_qualify(), analog_publish_channel_alarm_clear(), analog_publish_dnd_state(), analog_ss_thread(), announce_request(), app_create(), app_exec(), app_subscribe(), 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_list(), ast_ari_applications_subscribe(), ast_ari_applications_unsubscribe(), ast_ari_asterisk_delete_object(), ast_ari_asterisk_get_global_var(), ast_ari_asterisk_get_info(), ast_ari_asterisk_get_object(), ast_ari_asterisk_update_object(), ast_ari_bridges_add_channel(), ast_ari_bridges_create(), ast_ari_bridges_create_with_id(), ast_ari_bridges_destroy(), ast_ari_bridges_get(), ast_ari_bridges_list(), ast_ari_bridges_record(), ast_ari_bridges_remove_channel(), ast_ari_bridges_start_moh(), ast_ari_bridges_stop_moh(), ast_ari_callback(), ast_ari_channels_answer(), ast_ari_channels_continue_in_dialplan(), ast_ari_channels_dial(), ast_ari_channels_get_channel_var(), ast_ari_channels_hangup(), ast_ari_channels_hold(), ast_ari_channels_list(), ast_ari_channels_move(), ast_ari_channels_mute(), ast_ari_channels_record(), ast_ari_channels_redirect(), ast_ari_channels_ring(), ast_ari_channels_ring_stop(), ast_ari_channels_rtpstatistics(), ast_ari_channels_send_dtmf(), ast_ari_channels_set_channel_var(), ast_ari_channels_start_moh(), ast_ari_channels_start_silence(), ast_ari_channels_stop_moh(), ast_ari_channels_stop_silence(), ast_ari_channels_unhold(), ast_ari_channels_unmute(), ast_ari_config_validate_user(), ast_ari_endpoints_get(), ast_ari_endpoints_list(), ast_ari_endpoints_list_by_tech(), ast_ari_events_event_websocket_ws_attempted_cb(), ast_ari_events_event_websocket_ws_established_cb(), ast_ari_get_docs(), ast_ari_invoke(), ast_ari_json_format(), ast_ari_playbacks_control(), ast_ari_playbacks_get(), ast_ari_playbacks_stop(), ast_ari_recordings_copy_stored(), ast_ari_recordings_delete_stored(), ast_ari_recordings_get_live(), ast_ari_recordings_get_stored(), ast_ari_recordings_get_stored_file(), ast_ari_recordings_list_stored(), ast_ari_response_created(), ast_ari_response_error(), ast_ari_sounds_list(), ast_ari_websocket_session_create(), ast_ari_websocket_session_read(), ast_ari_websocket_session_write(), ast_bridge_add_channel(), 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_engine_term(), ast_cdr_fork(), ast_cel_backend_register(), ast_cel_create_event_with_time(), ast_cel_fabricate_channel_from_event(), ast_cel_general_config_alloc(), ast_cel_get_config(), ast_cel_track_event(), ast_channel_get_vars(), ast_channel_make_compatible_helper(), ast_channel_move(), ast_delete_mwi_state_full(), ast_destroy_realtime(), ast_dns_resolve_ipv6_and_ipv4(), ast_do_pickup(), ast_endpoint_shutdown(), 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_load_realtime(), ast_load_realtime_all(), ast_load_realtime_multientry(), ast_manager_publish_event(), ast_media_get_description(), ast_media_get_format_cap(), ast_media_get_media(), ast_media_get_variants(), ast_monitor_start(), ast_monitor_stop(), 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_pickup_call(), ast_publish_device_state_full(), ast_queue_hangup_with_cause(), ast_rtcp_calculate_sr_rr_statistics(), ast_rtcp_interpret(), ast_rtcp_write(), ast_rtp_interpret(), 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_auth(), ast_sip_for_each_channel(), ast_sip_for_each_channel_snapshot(), ast_sip_for_each_contact(), ast_sip_initialize_system(), ast_sip_publish_client_alloc_datastore(), ast_sip_session_alloc(), ast_sip_session_alloc_datastore(), ast_sip_session_create_outgoing(), ast_sip_session_register_sdp_handler(), ast_sip_set_tpselector_from_transport_name(), ast_sip_sorcery_object_to_ami(), ast_softhangup(), ast_sorcery_alloc(), ast_sorcery_copy(), ast_sorcery_create(), ast_sorcery_delete(), ast_sorcery_diff(), ast_sorcery_force_reload_object(), ast_sorcery_get_wizard_mapping(), ast_sorcery_get_wizard_mapping_count(), ast_sorcery_is_stale(), 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_prefix(), ast_sorcery_retrieve_by_regex(), ast_sorcery_update(), ast_sorcery_wizard_observer_add(), ast_sorcery_wizard_observer_remove(), ast_speech_new(), ast_stir_shaken_verify(), ast_store_realtime(), AST_TEST_DEFINE(), ast_threadpool_create(), 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_vm_test_swap_table_in(), ast_vm_test_swap_table_out(), ast_xmldoc_build_documentation(), ast_xmldoc_query(), 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_to_ami(), attended_transfer_to_json(), authenticate(), authenticate_api_key(), authenticate_user(), background_detect_exec(), blind_transfer_to_ami(), bridge_agent_hold_deferred_create(), bridge_agent_hold_push(), bridge_builtin_set_limits(), bridge_channel_attended_transfer(), bridge_channel_internal_queue_attended_transfer(), bridge_channel_internal_queue_blind_transfer(), bridge_merge_cb(), bridge_p2p_rtp_write(), bridge_parking_pull(), bridge_parking_push(), bridge_snapshot_update(), bridge_stasis_run_cb(), bridge_timeout(), bucket_alloc(), bucket_file_alloc(), bucket_file_always_revalidate(), bucket_file_expired(), bucket_file_wizard_retrieve(), bucket_wizard_retrieve(), build_ami_notify(), build_cli_notify(), build_nonce(), build_resource_tree(), build_topology(), cache_test_message_create_full(), call_pickup_to_ami(), cb_events(), cdr_detach(), cdr_prop_write(), cdr_read(), 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_with_stream_topology(), chan_pjsip_session_begin(), change_outgoing_sdp_stream_media_address(), 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_get_external_vars(), channel_hangup_handler_cb(), channel_leave_cb(), channel_mixmonitor_mute_cb(), channel_moh_start_cb(), channel_read_pjsip(), channel_replaced_cb(), channel_snapshot_update(), chanspy_exec(), check_cache_aggregate(), check_cache_content(), check_debug(), check_events(), check_retire_linkedid(), check_translation_path(), check_user_full(), cli_complete_notify(), cli_contact_get_container(), 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_gather_contact(), cli_get_container(), cli_notify(), cli_print_body(), cli_qualify(), cli_reload_qualify_endpoint(), cli_show_module_options(), cli_show_module_type(), cli_show_module_types(), cli_show_qualify_endpoint(), cli_unid_print_header(), command_prestart_queue_command(), common_identify(), compare_caller_id(), compare_timestamp(), complete_ari_app(), complete_ari_user(), complete_bridge_profile_name(), complete_confbridge_participant(), complete_menu_name(), complete_user_profile_name(), conf_announce_channel_push(), conf_find_bridge_profile(), conf_find_user_profile(), conf_handle_talker_cb(), conf_run(), conf_set_menu_to_user(), confbridge_handle_atxfer(), confbridge_publish_manager_event(), confbridge_talking_cb(), config_pgsql(), configure_parking_extensions(), consumer_exec(), consumer_exec_sync(), contactstatus_to_ami(), control_list_create(), control_recording(), create_dynamic_lot_full(), create_endpoint_snapshot_message(), create_out_of_dialog_request(), create_outgoing_sdp_stream(), create_sound_blob(), create_unsolicited_mwi_subscriptions(), curl_public_key(), dahdichannel_to_ami(), delete_old_messages(), destroy_pgsql(), dial_trunk(), digest_requires_authentication(), direct_media_mitigate_glare(), dispose_test_lot(), do_waiting(), endpoint_internal_create(), endpoint_publish_snapshot(), event_session_alloc(), expire_register(), export_aoc_vars(), extenspy_exec(), fake_ami(), fax_detect_framehook(), fax_gateway_framehook(), feature_automixmonitor(), feature_automonitor(), featuregroup_handler(), fetch_access_token(), find_bridge(), find_channel_control(), find_control(), find_table(), find_variant(), forkcdr_exec(), format_ami_auth_handler(), format_ami_endpoint(), format_ami_endpoint_transport(), format_ami_endpoints(), frame_set_var(), func_get_parkingslot_channel(), gen_prios(), generate_filenames_json(), generate_or_link_lots_to_configs(), generate_status(), generate_test_parking_lot(), generic_fax_exec(), generic_monitor_devstate_tp_cb(), generic_mute_unmute_helper(), get_account_id(), get_attestation_from_payload(), get_cached_mwi(), get_container(), get_destination(), get_exten_state_sub(), get_feature_ds(), get_languages(), get_media_encryption_type(), get_refer_info(), get_sip_pvt_from_replaces(), global_config_alloc(), handle_aor(), handle_attended_transfer(), handle_auth(), handle_blind_transfer(), handle_call_outgoing(), handle_cli_confbridge_show_bridge_profiles(), handle_cli_confbridge_show_menu(), handle_cli_confbridge_show_menus(), handle_cli_confbridge_show_user_profiles(), handle_cli_show_config(), handle_cli_status(), handle_client_registration(), handle_endpoint(), handle_feature_show(), handle_hangup(), handle_identify(), handle_incoming_sdp(), handle_manager_show_event(), handle_negotiated_sdp_session_media(), handle_new_invite_request(), handle_options(), handle_phoneprov(), handle_recordfile(), handle_registrations(), handle_request_bye(), handle_request_invite(), handle_request_refer(), handle_response_peerpoke(), handle_security_event(), handle_skel_show_config(), handle_skel_show_levels(), handle_soft_key_event_message(), handle_stimulus_message(), handle_updates(), has_voicemail(), hep_queue_cb(), hepv3_config_post_apply(), hepv3_get_uuid_type(), hepv3_is_loaded(), hepv3_send_packet(), http_callback(), httpd_process_request(), incoming_request(), internal_feature_read(), internal_feature_write(), internal_featuremap_write(), invalid_record_test(), is_enabled(), 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(), localnet_to_vl(), log_attended_transfer(), main(), make_channel(), manager_bridge_info(), manager_bridge_kick(), manager_bridge_tech_list(), manager_build_parked_call_string(), manager_jabber_send(), manager_mute_mixmonitor(), manager_park(), manager_parking_status_all_lots(), manager_parking_status_single_lot(), match_to_str(), mb_poll_thread(), media_request_helper(), meetme_stasis_cb(), meetme_stasis_generate_msg(), menu_template_handler(), messaging_app_subscribe_endpoint(), messaging_app_unsubscribe_endpoint(), metermaidstate(), mgcp_hangup(), mgcp_ss(), mixmonitor_exec(), mp3_exec(), msg_send(), multi_user_event_to_ami(), mwi_app_event_cb(), mwi_new_subscribe(), mwi_update_cb(), my_get_sigpvt_bridged_channel(), named_callgroups_to_str(), named_pickupgroups_to_str(), native_rtp_bridge_compatible_check(), negotiate_incoming_sdp_stream(), nocdr_exec(), nominal_async_run(), nominal_sync_run(), nominal_test(), notify_channel(), notify_endpoint(), notify_new_message(), notify_option_handler(), notify_task(), notify_uri(), object_type_loaded_observer(), off_nominal_async_run(), off_nominal_test(), options_on_rx_request(), origin_allowed(), 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(), 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(), playback_create(), playback_publish(), populate_cache(), prepare_bridge_media_channel(), presence_change_common(), presence_state_alloc(), presence_state_cached(), presence_state_event(), process_category(), process_config(), process_description_file(), process_nat(), prometheus_config_post_apply(), prometheus_general_config_get(), prometheus_general_config_set(), publish_acl_change(), publish_app_cdr_message(), publish_async_exec_end(), publish_basic_channel_event(), publish_channel_alarm(), publish_channel_alarm_clear(), publish_chanspy_message(), publish_dahdichannel(), publish_dnd_state(), publish_expire_callback(), publish_format_update(), publish_hangup_handler_message(), publish_load_message_type(), publish_local_bridge_message(), publish_parked_call(), publish_parked_call_failure(), publish_qualify_peer_done(), publish_request_initial(), publish_span_alarm(), publish_span_alarm_clear(), pubsub_on_rx_mwi_notify_request(), pubsub_on_rx_publish_request(), pubsub_on_rx_subscribe_request(), push_notify(), query_set_test(), 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(), read_header(), realtime_ldap_base(), realtime_multi_pgsql(), realtime_pgsql(), rec_request(), 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_aor_core(), register_verify(), registrar_on_rx_request(), remove_all_configured_parking_lot_extensions(), remove_header(), replace(), report_fax_status(), report_receive_fax_status(), report_send_fax_status(), request_channel(), require_client_cert_to_str(), resetcdr_exec(), resolve_refresh_media_states(), retransfer_enter(), return_sorcery_object(), ring_entry(), rna(), root_handler_create(), rtcp_message_handler(), rtcp_report_to_ami(), rtp_write_rtcp_fir(), rtp_write_rtcp_psfb(), run_station(), run_task(), rx_data_to_ast_msg(), safe_mkdir(), scheduler(), 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_conf_stasis_snapshots(), send_device_state(), send_dtmf_begin_event(), send_dtmf_end_event(), send_message(), send_session_timeout(), send_talking_event(), send_unsolicited_mwi_notify(), sendfax_exec(), sendmail(), session_outgoing_nat_hook(), session_refresh_state_get_or_alloc(), session_reinvite_on_rx_request(), session_timeout_to_ami(), set_caps(), set_config_flags(), set_format(), setup_sdes_srtp(), sfu_topologies_on_join(), shared_write(), shutdown_data_create(), sip_options_qualify_contact(), sip_outbound_publish_callback(), sip_outbound_publish_synchronize(), sip_outbound_publisher_init(), sip_outbound_registration_apply(), sip_outbound_registration_regc_alloc(), sip_poke_noanswer(), sip_publisher_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(), snoop_stasis_thread(), socket_process_helper(), sorcery_astdb_create(), sorcery_astdb_retrieve_fields_common(), sorcery_astdb_retrieve_id(), sorcery_astdb_retrieve_prefix(), 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_prefix(), sorcery_config_retrieve_regex(), sorcery_function_read(), sorcery_is_criteria_met(), sorcery_memory_cache_fields_cmp(), sorcery_memory_cache_open(), 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_prefix(), sorcery_realtime_retrieve_regex(), sorcery_realtime_update(), sorcery_reloadable(), spandsp_fax_gateway_start(), speech_background(), split_path(), start_automixmonitor(), start_automonitor(), stasis_app_bridge_playback_channel_add(), stasis_app_control_record(), stasis_app_control_snoop(), stasis_app_exec(), stasis_app_playback_to_json(), stasis_app_recording_options_create(), stasis_app_recording_to_json(), stasis_app_stored_recording_find_by_name(), stasis_app_user_event(), stasis_message_sink_create(), stasis_subscription_statistics_create(), stasis_test_message_create(), stasis_topic_pool_get_topic(), stasis_topic_statistics_create(), statsd_init(), statsmaker(), stir_shaken_incoming_request(), stop_mixmonitor_full(), store_pgsql(), stun_monitor_request(), system_registry_to_ami(), t38_automatic_reject(), t38_interpret_parameters(), t38_state_get_or_alloc(), test_cel_generate_peer_str(), test_cel_generate_peer_str_snapshot(), test_cel_peer_strings_match(), test_create_joint(), test_sub(), test_suite_event_to_ami(), threadpool_alloc(), tls_method_to_str(), transmit_info_dtmf(), transmit_info_with_vidupdate(), transport_apply(), transport_bind_handler(), transport_bind_to_str(), transport_localnet_handler(), transport_protocol_handler(), transport_tls_bool_handler(), transport_tls_file_handler(), transport_tls_method_handler(), try_calling(), try_parking(), two_bridge_attended_transfer(), unistim_send_mwi_to_peer(), unload_module(), update2_pgsql(), update_header(), update_pgsql(), update_registry(), user_alloc(), userevent_exec(), verify_client_to_str(), verify_default_parking_lot(), verify_default_profiles(), verify_server_to_str(), websocket_server_create_impl(), xmldoc_build_list_responses(), xmldoc_get_syntax_config_object(), xmldoc_get_syntax_config_option(), xmldoc_update_config_option(), xmldoc_update_config_type(), 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(), and xmpp_show_clients().

◆ SWAP

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

Enumeration Type Documentation

◆ ast_fd_flag_operation

Enumerator
AST_FD_FLAG_SET 
AST_FD_FLAG_CLEAR 

Definition at line 991 of file utils.h.

991  {
994 };

Function Documentation

◆ __ast_assert_failed()

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

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

References __LOG_ERROR, ast_do_crash(), ast_log, and ast_log_backtrace().

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

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

◆ __ast_fd_set_flags()

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

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

References __LOG_ERROR, ast_assert, AST_FD_FLAG_CLEAR, AST_FD_FLAG_SET, ast_fd_set_flags, ast_log, ast_pipe_nonblock, ast_socket_nonblock, errno, and thr_lock_info::type.

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

◆ _ast_assert()

static void force_inline _ast_assert ( int  condition,
const char *  condition_str,
const char *  file,
int  line,
const char *  function 
)
static

Definition at line 703 of file utils.h.

References __ast_assert_failed(), ast_do_crash(), and DO_CRASH_NORETURN.

704 {
705  if (__builtin_expect(!condition, 1)) {
706  __ast_assert_failed(condition, condition_str, file, line, function);
707  }
708 }
void DO_CRASH_NORETURN __ast_assert_failed(int condition, const char *condition_str, const char *file, int line, const char *function)
Definition: main/utils.c:2564

◆ ast_background_stacksize()

int ast_background_stacksize ( void  )

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

References AST_STACKSIZE, and AST_STACKSIZE_LOW.

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

◆ ast_base64decode()

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

Decode data from base64.

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

Decode data from base64.

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

References b2a.

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

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

◆ ast_base64decode_string()

char* ast_base64decode_string ( const char *  src)

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

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

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

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

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

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

◆ ast_base64encode()

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

Encode data in base64.

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

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

References ast_base64encode_full().

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

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

◆ ast_base64encode_full()

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

encode text to BASE64 coding

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

References base64, and max.

Referenced by ast_base64encode().

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

◆ ast_base64encode_string()

char* ast_base64encode_string ( const char *  src)

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

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

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

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

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

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

◆ ast_base64url_decode()

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

Decode data from base64 URL.

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

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

References b2a_url.

Referenced by ast_base64url_decode_string(), and stir_shaken_verify_signature().

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

◆ ast_base64url_decode_string()

char* ast_base64url_decode_string ( const char *  src)

Decode string from base64 URL.

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

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

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

Referenced by stir_shaken_incoming_request().

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

◆ ast_base64url_encode()

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

Encode data in base64 URL.

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

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

References ast_base64url_encode_full().

Referenced by ast_base64url_encode_string(), and stir_shaken_sign().

517 {
518  return ast_base64url_encode_full(dst, src, srclen, max, 0);
519 }
int ast_base64url_encode_full(char *dst, const unsigned char *src, int srclen, int max, int linebreaks)
Same as ast_base64encode_full but for base64 URL.
Definition: main/utils.c:469
#define max(a, b)
Definition: f2c.h:198

◆ ast_base64url_encode_full()

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

Same as ast_base64encode_full but for base64 URL.

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

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

References base64url, and max.

Referenced by ast_base64url_encode().

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

◆ ast_base64url_encode_string()

char* ast_base64url_encode_string ( const char *  src)

Encode string in base64 URL.

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

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

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

Referenced by add_identity_header().

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

◆ ast_careful_fwrite()

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

Write data to a file stream with a timeout.

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

◆ ast_carefulwrite()

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

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

Note
If you are calling ast_carefulwrite, it is assumed that you are calling it on a file descriptor that DOES have NONBLOCK set. This way, there is only one system call made to do a write, unless we actually have a need to wait. This way, we get better performance.

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

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

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

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

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

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

◆ ast_check_ipv6()

int ast_check_ipv6 ( void  )

Test that an OS supports IPv6 Networking.

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

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

Referenced by load_module().

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

◆ ast_compare_versions()

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

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

Since
13.7.0
Parameters
version1.
version2.
Returns
<0 if version 1 < version 2.
=0 if version 1 = version 2.
>0 if version 1 > version 2.

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

Referenced by transport_apply().

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

◆ ast_crypt()

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

Asterisk wrapper around crypt(3).

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

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

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

Definition at line 121 of file crypt.c.

References ast_begins_with(), ast_strdup, and NULL.

Referenced by ast_crypt_encrypt(), and ast_crypt_validate().

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

◆ ast_crypt_encrypt()

char* ast_crypt_encrypt ( const char *  key)

Asterisk wrapper around crypt(3) for encrypting passwords.

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

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

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

Definition at line 190 of file crypt.c.

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

Referenced by ari_mkpasswd(), and AST_TEST_DEFINE().

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

◆ ast_crypt_validate()

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

Asterisk wrapper around crypt(3) for validating passwords.

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

Definition at line 136 of file crypt.c.

References ast_begins_with(), ast_crypt(), ast_log, AST_MUTEX_DEFINE_STATIC, ast_strdup, lock, LOG_WARNING, NULL, and SCOPED_MUTEX.

Referenced by ast_ari_config_validate_user(), and AST_TEST_DEFINE().

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

◆ ast_do_crash()

void DO_CRASH_NORETURN ast_do_crash ( void  )

Force a crash if DO_CRASH is defined.

Note
If DO_CRASH is not defined then the function returns.
Returns
Nothing

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

Referenced by __ast_assert_failed(), _ast_assert(), ast_optional_api_use(), optional_api_create(), optional_api_user_create(), and sip_route_process_header().

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

◆ ast_eid_cmp()

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

◆ ast_eid_is_empty()

int ast_eid_is_empty ( const struct ast_eid eid)

Check if EID is empty.

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

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

Referenced by load_module(), and set_config().

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

◆ ast_eid_to_str()

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

Convert an EID to a string.

Since
1.6.1

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

References ast_debug, ast_free, ast_log, ast_malloc, ast_set_default_eid(), buf, ast_eid::eid, LOG_WARNING, and NULL.

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

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

◆ ast_enable_packet_fragmentation()

void ast_enable_packet_fragmentation ( int  sock)

Disable PMTU discovery on a socket.

Parameters
sockThe socket to manipulate
Returns
Nothing

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

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

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

References ast_log, and LOG_WARNING.

Referenced by ast_netsock_bindaddr(), and reload_config().

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

◆ ast_escape_quoted()

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

Escape characters found in a quoted string.

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

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

References out, and string.

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

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

◆ ast_escape_semicolons()

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

Escape semicolons found in a string.

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

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

References ast_assert, NULL, out, and string.

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

666 {
667  const char *ptr = string;
668  char *out = outbuf;
669 
670  if (string == NULL || outbuf == NULL) {
671  ast_assert(string != NULL && outbuf != NULL);
672  return NULL;
673  }
674 
675  while (*ptr && out - outbuf < buflen - 1) {
676  if (*ptr == ';') {
677  if (out - outbuf >= buflen - 2) {
678  break;
679  }
680  strcpy(out, "\\;");
681  out += 2;
682  } else {
683  *out = *ptr;
684  out++;
685  }
686  ptr++;
687  }
688 
689  if (buflen) {
690  *out = '\0';
691  }
692 
693  return outbuf;
694 }
#define ast_assert(a)
Definition: utils.h:695
const char * string
Definition: presencestate.c:71
#define NULL
Definition: resample.c:96
FILE * out
Definition: utils/frame.c:33

◆ ast_file_is_readable()

int ast_file_is_readable ( const char *  filename)

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

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

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

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

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

◆ ast_get_tid()

int ast_get_tid ( void  )

Get current thread ID.

Returns
the ID if platform is supported, else -1

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

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

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

◆ ast_gethostbyname()

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

Thread-safe gethostbyname function to use in Asterisk.

Thread-safe gethostbyname function to use in Asterisk.

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

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

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

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

◆ ast_md5_hash()

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

Produces MD5 hash based on input string.

Produces MD5 hash based on input string.

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

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

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

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

◆ ast_mkdir()

int ast_mkdir ( const char *  path,
int  mode 
)

Recursively create directory path.

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

Creates a directory path, creating parent directories as needed.

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

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

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

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

◆ ast_parse_digest()

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

Parse digest authorization header.

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

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

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, str, strsep(), ast_http_digest::uri, and ast_http_digest::username.

Referenced by auth_http_callback().

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

◆ ast_process_quotes_and_slashes()

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

Process a string to find and replace characters.

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

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

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

◆ ast_pthread_create_detached_stack()

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

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

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

1497 {
1498  unsigned char attr_destroy = 0;
1499  int res;
1500 
1501  if (!attr) {
1502  attr = ast_alloca(sizeof(*attr));
1503  pthread_attr_init(attr);
1504  attr_destroy = 1;
1505  }
1506 
1507  if ((errno = pthread_attr_setdetachstate(attr, PTHREAD_CREATE_DETACHED)))
1508  ast_log(LOG_WARNING, "pthread_attr_setdetachstate: %s\n", strerror(errno));
1509 
1510  res = ast_pthread_create_stack(thread, attr, start_routine, data,
1511  stacksize, file, caller, line, start_fn);
1512 
1513  if (attr_destroy)
1514  pthread_attr_destroy(attr);
1515 
1516  return res;
1517 }
pthread_t thread
Definition: app_meetme.c:1089
#define LOG_WARNING
Definition: logger.h:274
#define ast_log
Definition: astobj2.c:42
int ast_pthread_create_stack(pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *), void *data, size_t stacksize, const char *file, const char *caller, int line, const char *start_fn)
Definition: main/utils.c:1446
#define ast_alloca(size)
call __builtin_alloca to ensure we get gcc builtin semantics
Definition: astmm.h:290
int errno

◆ ast_pthread_create_stack()

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

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

References a, 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().

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

◆ ast_random()

long int ast_random ( void  )
Examples:
/usr/src/asterisk-18.5.0/main/app.c.

Definition at line 2064 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(), closefrom(), create_channel_name(), create_local_sdp(), dns_srv_sort(), drop_packets_data_update(), fill_with_garbage(), 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(), moh_files_alloc(), multicast_rtp_new(), ogg_vorbis_rewrite(), osp_create_uuid(), page_exec(), process_weights(), reg_source_db(), registry_authrequest(), reqprep(), reschedule_reinvite(), rtp_allocate_transport(), say_periodic_announcement(), sendmail(), sip_outbound_registration_perform(), socket_read(), sorcery_memory_cache_thrash_retrieve(), sorcery_memory_cache_thrash_update(), start_rtp(), stun_req_id(), test_ao2_find_w_no_flags(), test_ao2_find_w_OBJ_KEY(), test_ao2_find_w_OBJ_PARTIAL_KEY(), test_ao2_find_w_OBJ_POINTER(), test_files_get_one(), transmit_invite(), transmit_register(), transmit_response_using_temp(), try_calling(), try_firmware(), websocket_client_create_key(), and websocket_mask_payload().

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

◆ ast_register_thread()

void ast_register_thread ( char *  name)

Definition at line 414 of file asterisk.c.

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

Referenced by dummy_start().

415 {
416  struct thread_list_t *new = ast_calloc(1, sizeof(*new));
417 
418  if (!new)
419  return;
420 
422  new->id = pthread_self();
423  new->lwp = ast_get_tid();
424  new->name = name; /* steal the allocated memory for the thread name */
426  AST_RWLIST_INSERT_HEAD(&thread_list, new, list);
428 }
#define AST_RWLIST_WRLOCK(head)
Write locks a list.
Definition: linkedlists.h:51
static int multi_thread_safe
Definition: asterisk.c:388
#define AST_RWLIST_UNLOCK(head)
Attempts to unlock a read/write based list.
Definition: linkedlists.h:150
#define ast_assert(a)
Definition: utils.h:695
#define AST_RWLIST_INSERT_HEAD
Definition: linkedlists.h:717
int ast_get_tid(void)
Get current thread ID.
Definition: main/utils.c:2504
static const char name[]
Definition: cdr_mysql.c:74
#define ast_calloc(num, len)
A wrapper for calloc()
Definition: astmm.h:204

◆ ast_replace_subargument_delimiter()

void ast_replace_subargument_delimiter ( char *  s)

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

Parameters
sString within which to replace characters

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

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

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

◆ ast_safe_mkdir()

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

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

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

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

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

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

Referenced by AST_TEST_DEFINE(), and stasis_app_control_record().

2337 {
2338  RAII_VAR(char *, absolute_base_path, NULL, ast_std_free);
2339  RAII_VAR(char *, p, NULL, ast_free);
2340 
2341  if (base_path == NULL || path == NULL) {
2342  errno = EFAULT;
2343  return errno;
2344  }
2345 
2346  p = ast_strdup(path);
2347  if (p == NULL) {
2348  errno = ENOMEM;
2349  return errno;
2350  }
2351 
2352  absolute_base_path = realpath(base_path, NULL);
2353  if (absolute_base_path == NULL) {
2354  return errno;
2355  }
2356 
2357  return safe_mkdir(absolute_base_path, p, mode);
2358 }
void ast_std_free(void *ptr)
Definition: astmm.c:1766
#define ast_strdup(str)
A wrapper for strdup()
Definition: astmm.h:243
#define NULL
Definition: resample.c:96
#define RAII_VAR(vartype, varname, initval, dtor)
Declare a variable that will call a destructor function when it goes out of scope.
Definition: utils.h:911
int errno
#define ast_free(a)
Definition: astmm.h:182
static int safe_mkdir(const char *base_path, char *path, int mode)
Definition: main/utils.c:2266

◆ ast_set_default_eid()

void ast_set_default_eid ( struct ast_eid eid)

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

Since
1.6.1

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

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

Referenced by ast_eid_to_str(), and load_asterisk_conf().

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

◆ ast_sha1_hash()

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

Produces SHA1 hash based on input string.

Produces SHA1 hash based on input string.

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

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

Referenced by add_public_key_to_astdb(), ast_tcptls_server_start(), AST_TEST_DEFINE(), get_path_to_public_key(), handle_call_token(), media_cache_item_sync_to_astdb(), public_key_is_expired(), remove_public_key_from_astdb(), set_public_key_expiration(), sha1(), test_stir_shaken_add_fake_astdb_entry(), xmpp_client_authenticate_digest(), and xmpp_component_authenticate().

265 {
266  struct SHA1Context sha;
267  char *ptr;
268  int x;
269  uint8_t Message_Digest[20];
270 
271  SHA1Reset(&sha);
272 
273  SHA1Input(&sha, (const unsigned char *) input, strlen(input));
274 
275  SHA1Result(&sha, Message_Digest);
276  ptr = output;
277  for (x = 0; x < 20; x++)
278  ptr += sprintf(ptr, "%02hhx", Message_Digest[x]);
279 }
static int input(yyscan_t yyscanner)
Definition: ast_expr2f.c:1584
int SHA1Result(SHA1Context *, uint8_t Message_Digest[SHA1HashSize])
Definition: sha1.c:226
int SHA1Reset(SHA1Context *)
SHA1Reset.
Definition: sha1.c:101
int SHA1Input(SHA1Context *, const uint8_t *bytes, unsigned int bytecount)

◆ ast_sha1_hash_uint()

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

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

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

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

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

Referenced by websocket_combine_key().

283 {
284  struct SHA1Context sha;
285 
286  SHA1Reset(&sha);
287 
288  SHA1Input(&sha, (const unsigned char *) input, strlen(input));
289 
290  SHA1Result(&sha, digest);
291 }
static int input(yyscan_t yyscanner)
Definition: ast_expr2f.c:1584
int SHA1Result(SHA1Context *, uint8_t Message_Digest[SHA1HashSize])
Definition: sha1.c:226
int SHA1Reset(SHA1Context *)
SHA1Reset.
Definition: sha1.c:101
int SHA1Input(SHA1Context *, const uint8_t *bytes, unsigned int bytecount)

◆ ast_slinear_saturated_add()

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

Definition at line 425 of file utils.h.

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

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

◆ ast_slinear_saturated_divide()

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

Definition at line 477 of file utils.h.

References value.

Referenced by ast_frame_adjust_volume(), and audiohook_read_frame_both().

478 {
479  *input /= *value;
480 }
int value
Definition: syslog.c:37
static int input(yyscan_t yyscanner)
Definition: ast_expr2f.c:1584

◆ ast_slinear_saturated_divide_float()

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

Definition at line 482 of file utils.h.

Referenced by ast_frame_adjust_volume_float().

483 {
484  float res = (float) *input / *value;
485  if (res > 32767)
486  *input = 32767;
487  else if (res < -32768)
488  *input = -32768;
489  else
490  *input = (short) res;
491 }
int value
Definition: syslog.c:37
static int input(yyscan_t yyscanner)
Definition: ast_expr2f.c:1584

◆ ast_slinear_saturated_multiply()

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

Definition at line 451 of file utils.h.

Referenced by ast_frame_adjust_volume(), and audiohook_read_frame_both().

452 {
453  int res;
454 
455  res = (int) *input * *value;
456  if (res > 32767)
457  *input = 32767;
458  else if (res < -32768)
459  *input = -32768;
460  else
461  *input = (short) res;
462 }
int value
Definition: syslog.c:37
static int input(yyscan_t yyscanner)
Definition: ast_expr2f.c:1584

◆ ast_slinear_saturated_multiply_float()

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

Definition at line 464 of file utils.h.

Referenced by ast_frame_adjust_volume_float().

465 {
466  float res;
467 
468  res = (float) *input * *value;
469  if (res > 32767)
470  *input = 32767;
471  else if (res < -32768)
472  *input = -32768;
473  else
474  *input = (short) res;
475 }
int value
Definition: syslog.c:37
static int input(yyscan_t yyscanner)
Definition: ast_expr2f.c:1584

◆ ast_slinear_saturated_subtract()

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

Definition at line 438 of file utils.h.

Referenced by softmix_process_write_audio(), and softmix_process_write_binaural_audio().

439 {
440  int res;
441 
442  res = (int) *input - *value;
443  if (res > 32767)
444  *input = 32767;
445  else if (res < -32768)
446  *input = -32768;
447  else
448  *input = (short) res;
449 }
int value
Definition: syslog.c:37
static int input(yyscan_t yyscanner)
Definition: ast_expr2f.c:1584

◆ ast_str_to_eid()

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

Convert a string into an EID.

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

Returns
0 success, non-zero failure
Since
1.6.1

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

References ast_eid::eid.

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

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

◆ ast_thread_is_user_interface()

int ast_thread_is_user_interface ( void  )

Indicates whether the current thread is a user interface.

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

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

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

Referenced by ast_autoservice_start(), and ast_autoservice_stop().

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

◆ ast_thread_user_interface_set()

int ast_thread_user_interface_set ( int  is_user_interface)

Set the current thread's user interface status.

Parameters
is_user_interfaceNon-zero to mark the thread as a user interface.
Returns
0 if successfuly marked current thread.
Non-zero if marking current thread failed.

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

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

Referenced by handle_tcptls_connection().

2982 {
2983  int *thread_user_interface;
2984 
2985  thread_user_interface = ast_threadstorage_get(
2986  &thread_user_interface_tl, sizeof(*thread_user_interface));
2987  if (thread_user_interface == NULL) {
2988  ast_log(LOG_ERROR, "Error setting user interface status for current thread\n");
2989  return -1;
2990  }
2991 
2992  *thread_user_interface = !!is_user_interface;
2993  return 0;
2994 }
void * ast_threadstorage_get(struct ast_threadstorage *ts, size_t init_size)
Retrieve thread storage.
#define NULL
Definition: resample.c:96
#define ast_log
Definition: astobj2.c:42
#define LOG_ERROR
Definition: logger.h:285
static struct ast_threadstorage thread_user_interface_tl
Definition: main/utils.c:2979

◆ ast_unescape_quoted()

void ast_unescape_quoted ( char *  quote_str)

Unescape quotes in a string.

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

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

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

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

◆ ast_unregister_thread()

void ast_unregister_thread ( void *  id)

Definition at line 430 of file asterisk.c.

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

Referenced by dummy_start().

431 {
432  struct thread_list_t *x;
433 
436  if ((void *) x->id == id) {
438  break;
439  }
440  }
443  if (x) {
444  ast_free(x->name);
445  ast_free(x);
446  }
447 }
#define AST_RWLIST_WRLOCK(head)
Write locks a list.
Definition: linkedlists.h:51
#define AST_RWLIST_UNLOCK(head)
Attempts to unlock a read/write based list.
Definition: linkedlists.h:150
#define AST_RWLIST_REMOVE_CURRENT
Definition: linkedlists.h:569
#define AST_RWLIST_TRAVERSE_SAFE_BEGIN
Definition: linkedlists.h:544
#define ast_free(a)
Definition: astmm.h:182
#define AST_RWLIST_TRAVERSE_SAFE_END
Definition: linkedlists.h:616

◆ ast_uri_decode()

void ast_uri_decode ( char *  s,
struct ast_flags  spec 
)

Decode URI, URN, URL (overwrite string)

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

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

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

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

◆ ast_uri_encode()

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

Turn text string to URI-encoded XX version.

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

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

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

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

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

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

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

◆ ast_utils_init()

int ast_utils_init ( void  )

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

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

Referenced by asterisk_daemon().

2370 {
2371  dev_urandom_fd = open("/dev/urandom", O_RDONLY);
2372  base64_init();
2373 #ifdef DEBUG_THREADS
2374 #if !defined(LOW_MEMORY)
2376 #endif
2377 #endif
2379  return 0;
2380 }
static int dev_urandom_fd
Definition: main/utils.c:792
#define ARRAY_LEN(a)
Definition: isdn_lib.c:42
static void base64_init(void)
Definition: main/utils.c:538
#define ast_cli_register_multiple(e, len)
Register multiple commands.
Definition: cli.h:265
int ast_register_cleanup(void(*func)(void))
Register a function to be executed before Asterisk gracefully exits.
Definition: clicompat.c:19
static void utils_shutdown(void)
Definition: main/utils.c:2360
static struct ast_cli_entry utils_cli[]
Definition: main/utils.c:1369

◆ ast_utils_which()

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

Resolve a binary to a full pathname.

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

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

References ast_strdupa, NULL, and strsep().

2523 {
2524  const char *envPATH = getenv("PATH");
2525  char *tpath, *path;
2526  struct stat unused;
2527  if (!envPATH) {
2528  return NULL;
2529  }
2530  tpath = ast_strdupa(envPATH);
2531  while ((path = strsep(&tpath, ":"))) {
2532  snprintf(fullpath, fullpath_size, "%s/%s", path, binary);
2533  if (!stat(fullpath, &unused)) {
2534  return fullpath;
2535  }
2536  }
2537  return NULL;
2538 }
#define NULL
Definition: resample.c:96
#define ast_strdupa(s)
duplicate a string in memory from the stack
Definition: astmm.h:300
char * strsep(char **str, const char *delims)

◆ ast_wait_for_input()

int ast_wait_for_input ( int  fd,
int  ms 
)

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

References ast_poll.

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

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

◆ ast_wait_for_output()

int ast_wait_for_output ( int  fd,
int  ms 
)

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

References ast_poll.

Referenced by ast_iostream_write(), and iostream_read().

1530 {
1531  struct pollfd pfd[1];
1532 
1533  memset(pfd, 0, sizeof(pfd));
1534  pfd[0].fd = fd;
1535  pfd[0].events = POLLOUT;
1536  return ast_poll(pfd, 1, ms);
1537 }
#define ast_poll(a, b, c)
Definition: poll-compat.h:88

◆ ast_xml_escape()

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

Escape reserved characters for use in XML.

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

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

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

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

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

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

Variable Documentation

◆ __unsigned_int_flags_dummy

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

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

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

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

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

◆ __unsigned_int_flags_dummy64

uint64_t __unsigned_int_flags_dummy64

◆ ast_eid_default

struct ast_eid ast_eid_default

◆ ast_uri_http

const struct ast_flags ast_uri_http

◆ ast_uri_http_legacy

const struct ast_flags ast_uri_http_legacy

◆ ast_uri_sip_user

const struct ast_flags ast_uri_sip_user