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

Utility functions. More...

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

Go to the source code of this file.

Data Structures

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

Macros

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

Enumerations

enum  ast_fd_flag_operation { AST_FD_FLAG_SET, AST_FD_FLAG_CLEAR }
 

Functions

void DO_CRASH_NORETURN __ast_assert_failed (int condition, const char *condition_str, const char *file, int line, const char *function)
 
int __ast_fd_set_flags (int fd, int flags, enum ast_fd_flag_operation op, const char *file, int lineno, const char *function)
 
int ast_background_stacksize (void)
 
int ast_base64decode (unsigned char *dst, const char *src, int max)
 Decode data from base64. More...
 
char * ast_base64decode_string (const char *src)
 Same as ast_base64decode, but does the math for you and returns a decoded string. More...
 
int ast_base64encode (char *dst, const unsigned char *src, int srclen, int max)
 Encode data in base64. More...
 
int ast_base64encode_full (char *dst, const unsigned char *src, int srclen, int max, int linebreaks)
 encode text to BASE64 coding More...
 
char * ast_base64encode_string (const char *src)
 Same as ast_base64encode, but does hte math for you and returns an encoded string. More...
 
int ast_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 598 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 579 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 698 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 678 of file utils.h.

Referenced by __ast_string_field_alloc_space(), and __ast_string_field_ptr_build_va().

◆ ast_assert

#define ast_assert (   a)
Examples:
/tmp/asterisk-shallow/include/asterisk/strings.h, and /tmp/asterisk-shallow/main/app.c.

Definition at line 650 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_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_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_dialog_uas(), 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_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(), 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(), 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(), sip_session_refresh(), 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(), suspects_hash(), t38_change_state(), test_cel_init_cb(), test_handler(), topic_dtor(), topic_pool_entry_cmp(), topic_pool_entry_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,
  ... 
)
Value:
({ \
if (__builtin_expect(!(a), 1)) { \
return __VA_ARGS__; \
}\
})
static struct test_val a

Definition at line 651 of file utils.h.

Referenced by ast_stream_get_metadata(), ast_stream_get_metadata_list(), and ast_stream_set_metadata().

◆ AST_BACKGROUND_STACKSIZE

#define AST_BACKGROUND_STACKSIZE   ast_background_stacksize()

Definition at line 486 of file utils.h.

◆ ast_clear_flag

#define ast_clear_flag (   p,
  flag 
)
Examples:
/tmp/asterisk-shallow/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(), video_mode_handler(), and vmsayname_exec().

◆ 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 965 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 949 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 721 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 1000 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:1316
static struct test_val a

Definition at line 499 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:1316
#define AST_BACKGROUND_STACKSIZE
Definition: utils.h:486
static struct test_val a
Examples:
/tmp/asterisk-shallow/main/app.c.

Definition at line 507 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:1364
static struct test_val c
static struct test_val b
static struct test_val a

Definition at line 503 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:1364
static struct test_val c
static struct test_val b
#define AST_BACKGROUND_STACKSIZE
Definition: utils.h:486
static struct test_val a

Definition at line 512 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 539 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:
/tmp/asterisk-shallow/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(), append_mailbox(), 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(), vmsayname_exec(), 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 983 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 480 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 481 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_mailbox(), 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(), ast_readstring_full(), ast_sendtext_data(), ast_setstate(), ast_settimeout_full(), ast_softhangup_nolock(), ast_streamfile(), ast_transfer(), 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(), 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_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(), 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(), vmsayname_exec(), volume_callback(), wait_for_winner(), waitstream_core(), xmpp_action_hook(), xmpp_cli_purge_pubsub_nodes(), xmpp_client_authenticate(), xmpp_client_config_post_apply(), xmpp_client_reconnect(), xmpp_client_send_message(), xmpp_client_set_group_presence(), xmpp_client_thread(), xmpp_config_prelink(), xmpp_connect_hook(), xmpp_join_exec(), xmpp_leave_exec(), xmpp_log_hook(), xmpp_pak_message(), xmpp_pak_presence(), xmpp_pak_s10n(), xmpp_pubsub_build_publish_skeleton(), xmpp_pubsub_handle_error(), xmpp_pubsub_publish_device_state(), xmpp_pubsub_subscribe(), xmpp_roster_hook(), xmpp_send_stream_header(), and xmpp_sendgroup_exec().

◆ 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 279 of file utils.h.

Referenced by ast_uri_encode().

◆ AST_URI_LEGACY_SPACE

#define AST_URI_LEGACY_SPACE   (1 << 2)

Definition at line 282 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 280 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 284 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 281 of file utils.h.

◆ DO_CRASH_NORETURN

#define DO_CRASH_NORETURN

Definition at line 628 of file utils.h.

◆ IN_BOUNDS

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

Checks to see if value is within the given bounds.

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

Definition at line 589 of file utils.h.

◆ localtime_r

#define localtime_r   __dont_use_localtime_r_use_ast_localtime_instead__

Definition at line 436 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:
/tmp/asterisk-shallow/main/app.c.

Definition at line 851 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_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_list_configuration(), 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_unregister(), 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(), 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_moh_start_cb(), channel_read_pjsip(), channel_replaced_cb(), channel_snapshot_update(), chanspy_exec(), check_cache_aggregate(), 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(), dahdichannel_to_ami(), delete_old_messages(), destroy_pgsql(), dial_trunk(), digest_requires_authentication(), direct_media_mitigate_glare(), 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(), 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_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(), 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_test(), notify_channel(), notify_endpoint(), notify_new_message(), notify_option_handler(), notify_task(), notify_uri(), object_type_loaded_observer(), off_nominal_test(), options_on_rx_request(), origin_allowed(), 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_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_exec(), 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(), 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(), 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_ami_populate(), 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_cb_noop(), stasis_test_message_create(), stasis_topic_pool_get_topic(), statsd_init(), statsmaker(), stir_shaken_incoming_request(), 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(), threadpool_alloc(), tls_method_to_str(), topic_dtor(), 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_cipher_handler(), transport_tls_cipher_to_str(), transport_tls_file_handler(), transport_tls_method_handler(), try_calling(), try_parking(), two_bridge_attended_transfer(), unbound_config_preapply_callback(), 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 931 of file utils.h.

931  {
934 };

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 2434 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(), internal_ao2_traverse(), and log_bad_ao2().

2435 {
2436  /*
2437  * Attempt to put it into the logger, but hope that at least
2438  * someone saw the message on stderr ...
2439  */
2440  fprintf(stderr, "FRACK!, Failed assertion %s (%d) at line %d in %s of %s\n",
2441  condition_str, condition, line, function, file);
2442  ast_log(__LOG_ERROR, file, line, function, "FRACK!, Failed assertion %s (%d)\n",
2443  condition_str, condition);
2444 
2445  /* Generate a backtrace for the assert */
2447 
2448  /*
2449  * Give the logger a chance to get the message out, just in case
2450  * we abort(), or Asterisk crashes due to whatever problem just
2451  * happened after we exit ast_assert().
2452  */
2453  usleep(1);
2454  ast_do_crash();
2455 }
#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:2066
#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:2422

◆ __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 2768 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, and errno.

2770 {
2771  int f;
2772 
2773  f = fcntl(fd, F_GETFL);
2774  if (f == -1) {
2775  ast_log(__LOG_ERROR, file, lineno, function,
2776  "Failed to get fcntl() flags for file descriptor: %s\n", strerror(errno));
2777  return -1;
2778  }
2779 
2780  switch (op) {
2781  case AST_FD_FLAG_SET:
2782  if ((f & flags) == flags) {
2783  /* There is nothing to set */
2784  return 0;
2785  }
2786  f |= flags;
2787  break;
2788  case AST_FD_FLAG_CLEAR:
2789  if (!(f & flags)) {
2790  /* There is nothing to clear */
2791  return 0;
2792  }
2793  f &= ~flags;
2794  break;
2795  default:
2796  ast_assert(0);
2797  break;
2798  }
2799 
2800  f = fcntl(fd, F_SETFL, f);
2801  if (f == -1) {
2802  ast_log(__LOG_ERROR, file, lineno, function,
2803  "Failed to set fcntl() flags for file descriptor: %s\n", strerror(errno));
2804  return -1;
2805  }
2806 
2807  return 0;
2808 }
#define ast_assert(a)
Definition: utils.h:650
#define __LOG_ERROR
Definition: logger.h:284
#define ast_log
Definition: astobj2.c:42
int errno

◆ ast_background_stacksize()

int ast_background_stacksize ( void  )

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

References AST_STACKSIZE, and AST_STACKSIZE_LOW.

1308 {
1309 #if !defined(LOW_MEMORY)
1310  return AST_STACKSIZE;
1311 #else
1312  return AST_STACKSIZE_LOW;
1313 #endif
1314 }
#define AST_STACKSIZE
Definition: utils.h:480
#define AST_STACKSIZE_LOW
Definition: utils.h:481

◆ 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 287 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(), res_sdp_crypto_parse_offer(), and stir_shaken_verify_signature().

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

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

Referenced by stir_shaken_incoming_request().

315 {
316  size_t encoded_len;
317  size_t decoded_len;
318  int padding = 0;
319  unsigned char *decoded_string;
320 
321  if (ast_strlen_zero(src)) {
322  return NULL;
323  }
324 
325  encoded_len = strlen(src);
326  if (encoded_len > 2 && src[encoded_len - 1] == '=') {
327  padding++;
328  if (src[encoded_len - 2] == '=') {
329  padding++;
330  }
331  }
332 
333  decoded_len = (encoded_len / 4 * 3) - padding;
334  decoded_string = ast_calloc(1, decoded_len);
335  if (!decoded_string) {
336  return NULL;
337  }
338 
339  ast_base64decode(decoded_string, src, decoded_len);
340 
341  return (char *)decoded_string;
342 }
#define NULL
Definition: resample.c:96
int ast_base64decode(unsigned char *dst, const char *src, int max)
decode BASE64 encoded text
Definition: main/utils.c:287
#define ast_strlen_zero(a)
Definition: muted.c:73
#define ast_calloc(num, len)
A wrapper for calloc()
Definition: astmm.h:204

◆ 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 396 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(), stir_shaken_sign(), websocket_client_create_key(), websocket_combine_key(), and xmpp_client_authenticate_sasl().

397 {
398  return ast_base64encode_full(dst, src, srclen, max, 0);
399 }
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:345
#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 345 of file main/utils.c.

References base64, and max.

Referenced by ast_base64encode().

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

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

Referenced by add_identity_header().

403 {
404  size_t encoded_len;
405  char *encoded_string;
406 
407  if (ast_strlen_zero(src)) {
408  return NULL;
409  }
410 
411  encoded_len = ((strlen(src) * 4 / 3 + 3) & ~3) + 1;
412  encoded_string = ast_calloc(1, encoded_len);
413 
414  ast_base64encode(encoded_string, (const unsigned char *)src, strlen(src), encoded_len);
415 
416  return encoded_string;
417 }
int ast_base64encode(char *dst, const unsigned char *src, int srclen, int max)
Encode data in base64.
Definition: main/utils.c:396
#define NULL
Definition: resample.c:96
#define ast_strlen_zero(a)
Definition: muted.c:73
#define ast_calloc(num, len)
A wrapper for calloc()
Definition: astmm.h:204

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

1463 {
1464  struct timeval start = ast_tvnow();
1465  int res = 0;
1466  int elapsed = 0;
1467 
1468  while (len) {
1469  if (wait_for_output(fd, timeoutms - elapsed)) {
1470  return -1;
1471  }
1472 
1473  res = write(fd, s, len);
1474 
1475  if (res < 0 && errno != EAGAIN && errno != EINTR) {
1476  /* fatal error from write() */
1477  if (errno == EPIPE) {
1478 #ifndef STANDALONE
1479  ast_debug(1, "write() failed due to reading end being closed: %s\n", strerror(errno));
1480 #endif
1481  } else {
1482  ast_log(LOG_ERROR, "write() returned error: %s\n", strerror(errno));
1483  }
1484  return -1;
1485  }
1486 
1487  if (res < 0) {
1488  /* It was an acceptable error */
1489  res = 0;
1490  }
1491 
1492  /* Update how much data we have left to write */
1493  len -= res;
1494  s += res;
1495  res = 0;
1496 
1497  elapsed = ast_tvdiff_ms(ast_tvnow(), start);
1498  if (elapsed >= timeoutms) {
1499  /* We've taken too long to write
1500  * This is only an error condition if we haven't finished writing. */
1501  res = len ? -1 : 0;
1502  break;
1503  }
1504  }
1505 
1506  return res;
1507 }
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:444
#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:1409

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

Referenced by load_module().

2411 {
2412  int udp6_socket = socket(AF_INET6, SOCK_DGRAM, 0);
2413 
2414  if (udp6_socket < 0) {
2415  return 0;
2416  }
2417 
2418  close(udp6_socket);
2419  return 1;
2420 }

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

Referenced by transport_apply().

2743 {
2744  unsigned int major[2] = { 0 };
2745  unsigned int minor[2] = { 0 };
2746  unsigned int patch[2] = { 0 };
2747  unsigned int extra[2] = { 0 };
2748  int res;
2749 
2750  sscanf(version1, "%u.%u.%u.%u", &major[0], &minor[0], &patch[0], &extra[0]);
2751  sscanf(version2, "%u.%u.%u.%u", &major[1], &minor[1], &patch[1], &extra[1]);
2752 
2753  res = major[0] - major[1];
2754  if (res) {
2755  return res;
2756  }
2757  res = minor[0] - minor[1];
2758  if (res) {
2759  return res;
2760  }
2761  res = patch[0] - patch[1];
2762  if (res) {
2763  return res;
2764  }
2765  return extra[0] - extra[1];
2766 }

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

Referenced by __ast_assert_failed(), and sip_route_process_header().

2423 {
2424 #if defined(DO_CRASH)
2425  abort();
2426  /*
2427  * Just in case abort() doesn't work or something else super
2428  * silly, and for Qwell's amusement.
2429  */
2430  *((int *) 0) = 0;
2431 #endif /* defined(DO_CRASH) */
2432 }

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

Referenced by load_module(), and set_config().

2718 {
2719  struct ast_eid empty_eid;
2720 
2721  memset(&empty_eid, 0, sizeof(empty_eid));
2722  return memcmp(eid, &empty_eid, sizeof(empty_eid)) ? 0 : 1;
2723 }
An Entity ID is essentially a MAC address, brief and unique.
Definition: utils.h:726
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 2457 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(), update_key(), xmpp_pubsub_publish_device_state(), and xmpp_pubsub_publish_mwi().

2458 {
2459  int x;
2460  char *os = s;
2461  if (maxlen < 18) {
2462  if (s && (maxlen > 0)) {
2463  *s = '\0';
2464  }
2465  } else {
2466  for (x = 0; x < 5; x++) {
2467  sprintf(s, "%02hhx:", eid->eid[x]);
2468  s += 3;
2469  }
2470  sprintf(s, "%02hhx", eid->eid[5]);
2471  }
2472  return os;
2473 }
unsigned char eid[6]
Definition: utils.h:727

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

References ast_log, and LOG_WARNING.

Referenced by ast_netsock_bindaddr(), and reload_config().

2092 {
2093 #if defined(HAVE_IP_MTU_DISCOVER)
2094  int val = IP_PMTUDISC_DONT;
2095 
2096  if (setsockopt(sock, IPPROTO_IP, IP_MTU_DISCOVER, &val, sizeof(val)))
2097  ast_log(LOG_WARNING, "Unable to disable PMTU discovery. Large UDP packets may fail to be delivered when sent from this socket.\n");
2098 #endif /* HAVE_IP_MTU_DISCOVER */
2099 }
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 505 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().

506 {
507  const char *ptr = string;
508  char *out = outbuf;
509  char *allow = "\t\v !"; /* allow LWS (minus \r and \n) and "!" */
510 
511  while (*ptr && out - outbuf < buflen - 1) {
512  if (!(strchr(allow, *ptr))
513  && !(*ptr >= '#' && *ptr <= '[') /* %x23 - %x5b */
514  && !(*ptr >= ']' && *ptr <= '~') /* %x5d - %x7e */
515  && !((unsigned char) *ptr > 0x7f)) { /* UTF8-nonascii */
516 
517  if (out - outbuf >= buflen - 2) {
518  break;
519  }
520  out += sprintf(out, "\\%c", (unsigned char) *ptr);
521  } else {
522  *out = *ptr;
523  out++;
524  }
525  ptr++;
526  }
527 
528  if (buflen) {
529  *out = '\0';
530  }
531 
532  return outbuf;
533 }
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 535 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().

536 {
537  const char *ptr = string;
538  char *out = outbuf;
539 
540  if (string == NULL || outbuf == NULL) {
541  ast_assert(string != NULL && outbuf != NULL);
542  return NULL;
543  }
544 
545  while (*ptr && out - outbuf < buflen - 1) {
546  if (*ptr == ';') {
547  if (out - outbuf >= buflen - 2) {
548  break;
549  }
550  strcpy(out, "\\;");
551  out += 2;
552  } else {
553  *out = *ptr;
554  out++;
555  }
556  ptr++;
557  }
558 
559  if (buflen) {
560  *out = '\0';
561  }
562 
563  return outbuf;
564 }
#define ast_assert(a)
Definition: utils.h:650
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 2725 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().

2726 {
2727 #if defined(HAVE_EACCESS) || defined(HAVE_EUIDACCESS)
2728 #if defined(HAVE_EUIDACCESS) && !defined(HAVE_EACCESS)
2729 #define eaccess euidaccess
2730 #endif
2731  return eaccess(filename, R_OK) == 0;
2732 #else
2733  int fd = open(filename, O_RDONLY | O_NONBLOCK);
2734  if (fd < 0) {
2735  return 0;
2736  }
2737  close(fd);
2738  return 1;
2739 #endif
2740 }

◆ ast_get_tid()

int ast_get_tid ( void  )

Get current thread ID.

Returns
the ID if platform is supported, else -1

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

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

2375 {
2376  int ret = -1;
2377 #if defined (__linux) && defined(SYS_gettid)
2378  ret = syscall(SYS_gettid); /* available since Linux 1.4.11 */
2379 #elif defined(__sun)
2380  ret = pthread_self();
2381 #elif defined(__APPLE__)
2382  ret = mach_thread_self();
2383  mach_port_deallocate(mach_task_self(), ret);
2384 #elif defined(__FreeBSD__) && defined(HAVE_SYS_THR_H)
2385  long lwpid;
2386  thr_self(&lwpid); /* available since sys/thr.h creation 2003 */
2387  ret = lwpid;
2388 #endif
2389  return ret;
2390 }

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

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

242 {
243  struct MD5Context md5;
244  unsigned char digest[16];
245  char *ptr;
246  int x;
247 
248  MD5Init(&md5);
249  MD5Update(&md5, (const unsigned char *) input, strlen(input));
250  MD5Final(digest, &md5);
251  ptr = output;
252  for (x = 0; x < 16; x++)
253  ptr += sprintf(ptr, "%02hhx", digest[x]);
254 }
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 2101 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(), 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().

2102 {
2103  char *ptr;
2104  int len = strlen(path), count = 0, x, piececount = 0;
2105  char *tmp = ast_strdupa(path);
2106  char **pieces;
2107  char *fullpath = ast_alloca(len + 1);
2108  int res = 0;
2109 
2110  for (ptr = tmp; *ptr; ptr++) {
2111  if (*ptr == '/')
2112  count++;
2113  }
2114 
2115  /* Count the components to the directory path */
2116  pieces = ast_alloca(count * sizeof(*pieces));
2117  for (ptr = tmp; *ptr; ptr++) {
2118  if (*ptr == '/') {
2119  *ptr = '\0';
2120  pieces[piececount++] = ptr + 1;
2121  }
2122  }
2123 
2124  *fullpath = '\0';
2125  for (x = 0; x < piececount; x++) {
2126  /* This looks funky, but the buffer is always ideally-sized, so it's fine. */
2127  strcat(fullpath, "/");
2128  strcat(fullpath, pieces[x]);
2129  res = mkdir(fullpath, mode);
2130  if (res && errno != EEXIST)
2131  return errno;
2132  }
2133  return 0;
2134 }
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 2260 of file main/utils.c.

References ast_free, ast_log, ast_skip_blanks(), ast_str_buffer(), ast_str_create, ast_str_set(), ast_string_field_ptr_set, ast_string_field_set, ast_strlen_zero, ast_unescape_c(), c, ast_http_digest::cnonce, ast_http_digest::domain, LOG_WARNING, ast_http_digest::nc, ast_http_digest::nonce, NULL, ast_http_digest::opaque, ast_http_digest::qop, ast_http_digest::realm, ast_http_digest::response, strsep(), ast_http_digest::uri, and ast_http_digest::username.

Referenced by auth_http_callback().

2260  {
2261  char *c;
2262  struct ast_str *str = ast_str_create(16);
2263 
2264  /* table of recognised keywords, and places where they should be copied */
2265  const struct x {
2266  const char *key;
2267  const ast_string_field *field;
2268  } *i, keys[] = {
2269  { "username=", &d->username },
2270  { "realm=", &d->realm },
2271  { "nonce=", &d->nonce },
2272  { "uri=", &d->uri },
2273  { "domain=", &d->domain },
2274  { "response=", &d->response },
2275  { "cnonce=", &d->cnonce },
2276  { "opaque=", &d->opaque },
2277  /* Special cases that cannot be directly copied */
2278  { "algorithm=", NULL },
2279  { "qop=", NULL },
2280  { "nc=", NULL },
2281  { NULL, 0 },
2282  };
2283 
2284  if (ast_strlen_zero(digest) || !d || !str) {
2285  ast_free(str);
2286  return -1;
2287  }
2288 
2289  ast_str_set(&str, 0, "%s", digest);
2290 
2291  c = ast_skip_blanks(ast_str_buffer(str));
2292 
2293  if (strncasecmp(c, "Digest ", strlen("Digest "))) {
2294  ast_log(LOG_WARNING, "Missing Digest.\n");
2295  ast_free(str);
2296  return -1;
2297  }
2298  c += strlen("Digest ");
2299 
2300  /* lookup for keys/value pair */
2301  while (c && *c && *(c = ast_skip_blanks(c))) {
2302  /* find key */
2303  for (i = keys; i->key != NULL; i++) {
2304  char *src, *separator;
2305  int unescape = 0;
2306  if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
2307  continue;
2308  }
2309 
2310  /* Found. Skip keyword, take text in quotes or up to the separator. */
2311  c += strlen(i->key);
2312  if (*c == '"') {
2313  src = ++c;
2314  separator = "\"";
2315  unescape = 1;
2316  } else {
2317  src = c;
2318  separator = ",";
2319  }
2320  strsep(&c, separator); /* clear separator and move ptr */
2321  if (unescape) {
2322  ast_unescape_c(src);
2323  }
2324  if (i->field) {
2325  ast_string_field_ptr_set(d, i->field, src);
2326  } else {
2327  /* Special cases that require additional procesing */
2328  if (!strcasecmp(i->key, "algorithm=")) {
2329  if (strcasecmp(src, "MD5")) {
2330  ast_log(LOG_WARNING, "Digest algorithm: \"%s\" not supported.\n", src);
2331  ast_free(str);
2332  return -1;
2333  }
2334  } else if (!strcasecmp(i->key, "qop=") && !strcasecmp(src, "auth")) {
2335  d->qop = 1;
2336  } else if (!strcasecmp(i->key, "nc=")) {
2337  unsigned long u;
2338  if (sscanf(src, "%30lx", &u) != 1) {
2339  ast_log(LOG_WARNING, "Incorrect Digest nc value: \"%s\".\n", src);
2340  ast_free(str);
2341  return -1;
2342  }
2343  ast_string_field_set(d, nc, src);
2344  }
2345  }
2346  break;
2347  }
2348  if (i->key == NULL) { /* not found, try ',' */
2349  strsep(&c, ",");
2350  }
2351  }
2352  ast_free(str);
2353 
2354  /* Digest checkout */
2355  if (ast_strlen_zero(d->realm) || ast_strlen_zero(d->nonce)) {
2356  /* "realm" and "nonce" MUST be always exist */
2357  return -1;
2358  }
2359 
2360  if (!request) {
2361  /* Additional check for Digest response */
2363  return -1;
2364  }
2365 
2366  if (pedantic && d->qop && (ast_strlen_zero(d->cnonce) || ast_strlen_zero(d->nc))) {
2367  return -1;
2368  }
2369  }
2370 
2371  return 0;
2372 }
const ast_string_field cnonce
Definition: utils.h:612
#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:612
const ast_string_field domain
Definition: utils.h:612
const char * ast_string_field
Definition: stringfields.h:190
static struct test_val c
const ast_string_field username
Definition: utils.h:612
const char * str
Definition: app_jack.c:147
#define NULL
Definition: resample.c:96
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:612
#define ast_log
Definition: astobj2.c:42
const ast_string_field response
Definition: utils.h:612
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:612
#define ast_strlen_zero(a)
Definition: muted.c:73
#define ast_free(a)
Definition: astmm.h:182
char * ast_unescape_c(char *src)
Convert some C escape sequences.
Definition: main/utils.c:1605
const ast_string_field realm
Definition: utils.h:612
static int request(void *obj)
Definition: chan_pjsip.c:2626
const ast_string_field nonce
Definition: utils.h:612
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 1974 of file main/utils.c.

1975 {
1976  char *dataPut = start;
1977  int inEscape = 0;
1978  int inQuotes = 0;
1979 
1980  for (; *start; start++) {
1981  if (inEscape) {
1982  *dataPut++ = *start; /* Always goes verbatim */
1983  inEscape = 0;
1984  } else {
1985  if (*start == '\\') {
1986  inEscape = 1; /* Do not copy \ into the data */
1987  } else if (*start == '\'') {
1988  inQuotes = 1 - inQuotes; /* Do not copy ' into the data */
1989  } else {
1990  /* Replace , with |, unless in quotes */
1991  *dataPut++ = inQuotes ? *start : ((*start == find) ? replace_with : *start);
1992  }
1993  }
1994  }
1995  if (start != dataPut)
1996  *dataPut = 0;
1997  return dataPut;
1998 }

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

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

1367 {
1368  unsigned char attr_destroy = 0;
1369  int res;
1370 
1371  if (!attr) {
1372  attr = ast_alloca(sizeof(*attr));
1373  pthread_attr_init(attr);
1374  attr_destroy = 1;
1375  }
1376 
1377  if ((errno = pthread_attr_setdetachstate(attr, PTHREAD_CREATE_DETACHED)))
1378  ast_log(LOG_WARNING, "pthread_attr_setdetachstate: %s\n", strerror(errno));
1379 
1380  res = ast_pthread_create_stack(thread, attr, start_routine, data,
1381  stacksize, file, caller, line, start_fn);
1382 
1383  if (attr_destroy)
1384  pthread_attr_destroy(attr);
1385 
1386  return res;
1387 }
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:1316
#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 1316 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().

1319 {
1320 #if !defined(LOW_MEMORY)
1321  struct thr_arg *a;
1322 #endif
1323 
1324  if (!attr) {
1325  attr = ast_alloca(sizeof(*attr));
1326  pthread_attr_init(attr);
1327  }
1328 
1329 #if defined(__linux__) || defined(__FreeBSD__)
1330  /* On Linux and FreeBSD , pthread_attr_init() defaults to PTHREAD_EXPLICIT_SCHED,
1331  which is kind of useless. Change this here to
1332  PTHREAD_INHERIT_SCHED; that way the -p option to set realtime
1333  priority will propagate down to new threads by default.
1334  This does mean that callers cannot set a different priority using
1335  PTHREAD_EXPLICIT_SCHED in the attr argument; instead they must set
1336  the priority afterwards with pthread_setschedparam(). */
1337  if ((errno = pthread_attr_setinheritsched(attr, PTHREAD_INHERIT_SCHED)))
1338  ast_log(LOG_WARNING, "pthread_attr_setinheritsched: %s\n", strerror(errno));
1339 #endif
1340 
1341  if (!stacksize)
1342  stacksize = AST_STACKSIZE;
1343 
1344  if ((errno = pthread_attr_setstacksize(attr, stacksize ? stacksize : AST_STACKSIZE)))
1345  ast_log(LOG_WARNING, "pthread_attr_setstacksize: %s\n", strerror(errno));
1346 
1347 #if !defined(LOW_MEMORY)
1348  if ((a = ast_malloc(sizeof(*a)))) {
1350  a->data = data;
1352  if (ast_asprintf(&a->name, "%-20s started at [%5d] %s %s()",
1353  start_fn, line, file, caller) < 0) {
1354  a->name = NULL;
1355  }
1356  data = a;
1357  }
1358 #endif /* !LOW_MEMORY */
1359 
1360  return pthread_create(thread, attr, start_routine, data); /* We're in ast_pthread_create, so it's okay */
1361 }
pthread_t thread
Definition: app_meetme.c:1089
#define AST_STACKSIZE
Definition: utils.h:480
#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:1264
int errno
#define pthread_create
Definition: lock.h:640
void *(* start_routine)(void *)
Definition: main/utils.c:1252
void * data
Definition: main/utils.c:1253
char * name
Definition: main/utils.c:1254
static struct test_val a

◆ ast_random()

long int ast_random ( void  )
Examples:
/tmp/asterisk-shallow/main/app.c.

Definition at line 1934 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_sockaddr_from_pj_sockaddr(), 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(), 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().

1935 {
1936  long int res;
1937 
1938  if (dev_urandom_fd >= 0) {
1939  int read_res = read(dev_urandom_fd, &res, sizeof(res));
1940  if (read_res > 0) {
1941  long int rm = RAND_MAX;
1942  res = res < 0 ? ~res : res;
1943  rm++;
1944  return res % rm;
1945  }
1946  }
1947 
1948  /* XXX - Thread safety really depends on the libc, not the OS.
1949  *
1950  * But... popular Linux libc's (uClibc, glibc, eglibc), all have a
1951  * somewhat thread safe random(3) (results are random, but not
1952  * reproducible). The libc's for other systems (BSD, et al.), not so
1953  * much.
1954  */
1955 #ifdef linux
1956  res = random();
1957 #else
1959  res = random();
1961 #endif
1962  return res;
1963 }
static int dev_urandom_fd
Definition: main/utils.c:662
#define ast_mutex_lock(a)
Definition: lock.h:187
static ast_mutex_t randomlock
Definition: main/utils.c:1931
#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:650
#define AST_RWLIST_INSERT_HEAD
Definition: linkedlists.h:717
int ast_get_tid(void)
Get current thread ID.
Definition: main/utils.c:2374
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 1965 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().

1966 {
1967  for (; *s; s++) {
1968  if (*s == '^') {
1969  *s = ',';
1970  }
1971  }
1972 }

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

2207 {
2208  RAII_VAR(char *, absolute_base_path, NULL, ast_std_free);
2209  RAII_VAR(char *, p, NULL, ast_free);
2210 
2211  if (base_path == NULL || path == NULL) {
2212  errno = EFAULT;
2213  return errno;
2214  }
2215 
2216  p = ast_strdup(path);
2217  if (p == NULL) {
2218  errno = ENOMEM;
2219  return errno;
2220  }
2221 
2222  absolute_base_path = realpath(base_path, NULL);
2223  if (absolute_base_path == NULL) {
2224  return errno;
2225  }
2226 
2227  return safe_mkdir(absolute_base_path, p, mode);
2228 }
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:851
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:2136

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

2620 {
2621  int s;
2622  int i;
2623  struct ifreq *ifr;
2624  struct ifreq *ifrp;
2625  struct ifconf ifc;
2626  char *buf = NULL;
2627  char eid_str[20];
2628  int bufsz, num_interfaces;
2629  unsigned char empty_mac[6] = {0, 0, 0, 0, 0, 0};
2630  unsigned char full_mac[6] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
2631 
2632  s = socket(AF_INET, SOCK_STREAM, 0);
2633  if (s < 0) {
2634  ast_log(LOG_WARNING, "Unable to open socket for seeding global EID. "
2635  "You will have to set it manually.\n");
2636  return;
2637  }
2638 
2639  ifc.ifc_len = 0;
2640  ifc.ifc_buf = NULL;
2641  if (ioctl(s, SIOCGIFCONF, &ifc) || ifc.ifc_len <= 0) {
2642  ast_log(LOG_WARNING, "No ethernet interface found for seeding global EID. "
2643  "You will have to set it manually.\n");
2644  close(s);
2645  return;
2646  }
2647  bufsz = ifc.ifc_len;
2648 
2649  if (!(buf = ast_malloc(bufsz))) {
2650  ast_log(LOG_WARNING, "Unable to allocate memory for seeding global EID. "
2651  "You will have to set it manually.\n");
2652  close(s);
2653  return;
2654  }
2655 
2656  ifc.ifc_buf = buf;
2657  if (ioctl(s, SIOCGIFCONF, &ifc) < 0) {
2658  ast_log(LOG_WARNING, "Unable to retrieve ethernet interfaces for seeding global EID. "
2659  "You will have to set it manually.\n");
2660  ast_free(buf);
2661  close(s);
2662  return;
2663  }
2664 
2665  ifrp = ifc.ifc_req;
2666  num_interfaces = ifc.ifc_len / sizeof(*ifr);
2667 
2668  for (i = 0; i < num_interfaces; i++) {
2669  ifr = &ifrp[i];
2670  if (!ioctl(s, SIOCGIFHWADDR, ifr)) {
2671  unsigned char *hwaddr = (unsigned char *) ifr->ifr_hwaddr.sa_data;
2672 
2673  if (!(memcmp(hwaddr, &empty_mac, 6) && memcmp(hwaddr, &full_mac, 6))) {
2674  continue;
2675  }
2676 
2677  memcpy(eid, hwaddr, sizeof(*eid));
2678  ast_debug(1, "Seeding global EID '%s' from '%s' using 'siocgifhwaddr'\n",
2679  ast_eid_to_str(eid_str, sizeof(eid_str), eid), ifr->ifr_name);
2680  ast_free(buf);
2681  close(s);
2682  return;
2683  }
2684  }
2685 
2686  ast_log(LOG_WARNING, "No ethernet interface found for seeding global EID. "
2687  "You will have to set it manually.\n");
2688  ast_free(buf);
2689  close(s);
2690 
2691  return;
2692 }
char * ast_eid_to_str(char *s, int maxlen, struct ast_eid *eid)
Convert an EID to a string.
Definition: main/utils.c:2457
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:444
#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 257 of file main/utils.c.

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

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

258 {
259  struct SHA1Context sha;
260  char *ptr;
261  int x;
262  uint8_t Message_Digest[20];
263 
264  SHA1Reset(&sha);
265 
266  SHA1Input(&sha, (const unsigned char *) input, strlen(input));
267 
268  SHA1Result(&sha, Message_Digest);
269  ptr = output;
270  for (x = 0; x < 20; x++)
271  ptr += sprintf(ptr, "%02hhx", Message_Digest[x]);
272 }
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 275 of file main/utils.c.

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

Referenced by websocket_combine_key().

276 {
277  struct SHA1Context sha;
278 
279  SHA1Reset(&sha);
280 
281  SHA1Input(&sha, (const unsigned char *) input, strlen(input));
282 
283  SHA1Result(&sha, digest);
284 }
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 365 of file utils.h.

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

366 {
367  int res;
368 
369  res = (int) *input + *value;
370  if (res > 32767)
371  *input = 32767;
372  else if (res < -32768)
373  *input = -32768;
374  else
375  *input = (short) res;
376 }
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 417 of file utils.h.

References value.

Referenced by ast_frame_adjust_volume(), and audiohook_read_frame_both().

418 {
419  *input /= *value;
420 }
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 422 of file utils.h.

Referenced by ast_frame_adjust_volume_float().

423 {
424  float res = (float) *input / *value;
425  if (res > 32767)
426  *input = 32767;
427  else if (res < -32768)
428  *input = -32768;
429  else
430  *input = (short) res;
431 }
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 391 of file utils.h.

Referenced by ast_frame_adjust_volume(), and audiohook_read_frame_both().

392 {
393  int res;
394 
395  res = (int) *input * *value;
396  if (res > 32767)
397  *input = 32767;
398  else if (res < -32768)
399  *input = -32768;
400  else
401  *input = (short) res;
402 }
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 404 of file utils.h.

Referenced by ast_frame_adjust_volume_float().

405 {
406  float res;
407 
408  res = (float) *input * *value;
409  if (res > 32767)
410  *input = 32767;
411  else if (res < -32768)
412  *input = -32768;
413  else
414  *input = (short) res;
415 }
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 378 of file utils.h.

Referenced by softmix_process_write_audio(), and softmix_process_write_binaural_audio().

379 {
380  int res;
381 
382  res = (int) *input - *value;
383  if (res > 32767)
384  *input = 32767;
385  else if (res < -32768)
386  *input = -32768;
387  else
388  *input = (short) res;
389 }
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 2695 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().

2696 {
2697  unsigned int eid_int[6];
2698  int x;
2699 
2700  if (sscanf(s, "%2x:%2x:%2x:%2x:%2x:%2x", &eid_int[0], &eid_int[1], &eid_int[2],
2701  &eid_int[3], &eid_int[4], &eid_int[5]) != 6) {
2702  return -1;
2703  }
2704 
2705  for (x = 0; x < 6; x++) {
2706  eid->eid[x] = eid_int[x];
2707  }
2708 
2709  return 0;
2710 }
unsigned char eid[6]
Definition: utils.h:727

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

2867 {
2868  int *thread_user_interface;
2869 
2870  thread_user_interface = ast_threadstorage_get(
2871  &thread_user_interface_tl, sizeof(*thread_user_interface));
2872  if (thread_user_interface == NULL) {
2873  ast_log(LOG_ERROR, "Error checking thread's user interface status\n");
2874  /* On error, assume that we are not a user interface thread */
2875  return 0;
2876  }
2877 
2878  return *thread_user_interface;
2879 }
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:2849

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

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

Referenced by handle_tcptls_connection().

2852 {
2853  int *thread_user_interface;
2854 
2855  thread_user_interface = ast_threadstorage_get(
2856  &thread_user_interface_tl, sizeof(*thread_user_interface));
2857  if (thread_user_interface == NULL) {
2858  ast_log(LOG_ERROR, "Error setting user interface status for current thread\n");
2859  return -1;
2860  }
2861 
2862  *thread_user_interface = !!is_user_interface;
2863  return 0;
2864 }
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:2849

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

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

567 {
568  int esc_pos;
569  int unesc_pos;
570  int quote_str_len = strlen(quote_str);
571 
572  for (esc_pos = 0, unesc_pos = 0;
573  esc_pos < quote_str_len;
574  esc_pos++, unesc_pos++) {
575  if (quote_str[esc_pos] == '\\') {
576  /* at least one more char and current is \\ */
577  esc_pos++;
578  if (esc_pos >= quote_str_len) {
579  break;
580  }
581  }
582 
583  quote_str[unesc_pos] = quote_str[esc_pos];
584  }
585  quote_str[unesc_pos] = '\0';
586 }

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

487 {
488  char *o;
489  unsigned int tmp;
490 
491  for (o = s; *s; s++, o++) {
492  if (ast_test_flag(&spec, AST_URI_LEGACY_SPACE) && *s == '+') {
493  /* legacy mode, decode '+' as space */
494  *o = ' ';
495  } else if (*s == '%' && s[1] != '\0' && s[2] != '\0' && sscanf(s + 1, "%2x", &tmp) == 1) {
496  /* have '%', two chars and correct parsing */
497  *o = tmp;
498  s += 2; /* Will be incremented once more when we break out */
499  } else /* all other cases, just copy */
500  *o = *s;
501  }
502  *o = '\0';
503 }
#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:282

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

448 {
449  const char *ptr = string; /* Start with the string */
450  char *out = outbuf;
451  const char *mark = "-_.!~*'()"; /* no encode set, RFC 2396 section 2.3, RFC 3261 sec 25 */
452  const char *user_unreserved = "&=+$,;?/"; /* user-unreserved set, RFC 3261 sec 25 */
453 
454  while (*ptr && out - outbuf < buflen - 1) {
455  if (ast_test_flag(&spec, AST_URI_LEGACY_SPACE) && *ptr == ' ') {
456  /* for legacy encoding, encode spaces as '+' */
457  *out = '+';
458  out++;
459  } else if (!(ast_test_flag(&spec, AST_URI_MARK)
460  && strchr(mark, *ptr))
461  && !(ast_test_flag(&spec, AST_URI_ALPHANUM)
462  && ((*ptr >= '0' && *ptr <= '9')
463  || (*ptr >= 'A' && *ptr <= 'Z')
464  || (*ptr >= 'a' && *ptr <= 'z')))
466  && strchr(user_unreserved, *ptr))) {
467 
468  if (out - outbuf >= buflen - 3) {
469  break;
470  }
471  out += sprintf(out, "%%%02hhX", (unsigned char) *ptr);
472  } else {
473  *out = *ptr; /* Continue copying the string */
474  out++;
475  }
476  ptr++;
477  }
478 
479  if (buflen) {
480  *out = '\0';
481  }
482 
483  return outbuf;
484 }
#define AST_URI_ALPHANUM
Definition: utils.h:279
#define ast_test_flag(p, flag)
Definition: utils.h:63
const char * string
Definition: presencestate.c:71
#define AST_URI_MARK
Definition: utils.h:280
#define AST_URI_SIP_USER_UNRESERVED
Definition: utils.h:284
FILE * out
Definition: utils/frame.c:33
#define AST_URI_LEGACY_SPACE
Definition: utils.h:282

◆ ast_utils_init()

int ast_utils_init ( void  )

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

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

Referenced by asterisk_daemon().

2240 {
2241  dev_urandom_fd = open("/dev/urandom", O_RDONLY);
2242  base64_init();
2243 #ifdef DEBUG_THREADS
2244 #if !defined(LOW_MEMORY)
2245  ast_cli_register_multiple(utils_cli, ARRAY_LEN(utils_cli));
2246 #endif
2247 #endif
2249  return 0;
2250 }
static int dev_urandom_fd
Definition: main/utils.c:662
#define ARRAY_LEN(a)
Definition: isdn_lib.c:42
static void base64_init(void)
Definition: main/utils.c:419
#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:2230

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

References ast_strdupa, NULL, and strsep().

2393 {
2394  const char *envPATH = getenv("PATH");
2395  char *tpath, *path;
2396  struct stat unused;
2397  if (!envPATH) {
2398  return NULL;
2399  }
2400  tpath = ast_strdupa(envPATH);
2401  while ((path = strsep(&tpath, ":"))) {
2402  snprintf(fullpath, fullpath_size, "%s/%s", path, binary);
2403  if (!stat(fullpath, &unused)) {
2404  return fullpath;
2405  }
2406  }
2407  return NULL;
2408 }
#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 1389 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().

1390 {
1391  struct pollfd pfd[1];
1392 
1393  memset(pfd, 0, sizeof(pfd));
1394  pfd[0].fd = fd;
1395  pfd[0].events = POLLIN | POLLPRI;
1396  return ast_poll(pfd, 1, ms);
1397 }
#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 1399 of file main/utils.c.

References ast_poll.

Referenced by ast_iostream_write(), and iostream_read().

1400 {
1401  struct pollfd pfd[1];
1402 
1403  memset(pfd, 0, sizeof(pfd));
1404  pfd[0].fd = fd;
1405  pfd[0].events = POLLOUT;
1406  return ast_poll(pfd, 1, ms);
1407 }
#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 588 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().

589 {
590  char *dst = outbuf;
591  char *end = outbuf + buflen - 1; /* save one for the null terminator */
592 
593  /* Handle the case for the empty output buffer */
594  if (buflen == 0) {
595  return -1;
596  }
597 
598  /* Escaping rules from http://www.w3.org/TR/REC-xml/#syntax */
599  /* This also prevents partial entities at the end of a string */
600  while (*string && dst < end) {
601  const char *entity = NULL;
602  int len = 0;
603 
604  switch (*string) {
605  case '<':
606  entity = "&lt;";
607  len = 4;
608  break;
609  case '&':
610  entity = "&amp;";
611  len = 5;
612  break;
613  case '>':
614  /* necessary if ]]> is in the string; easier to escape them all */
615  entity = "&gt;";
616  len = 4;
617  break;
618  case '\'':
619  /* necessary in single-quoted strings; easier to escape them all */
620  entity = "&apos;";
621  len = 6;
622  break;
623  case '"':
624  /* necessary in double-quoted strings; easier to escape them all */
625  entity = "&quot;";
626  len = 6;
627  break;
628  default:
629  *dst++ = *string++;
630  break;
631  }
632 
633  if (entity) {
634  ast_assert(len == strlen(entity));
635  if (end - dst < len) {
636  /* no room for the entity; stop */
637  break;
638  }
639  /* just checked for length; strcpy is fine */
640  strcpy(dst, entity);
641  dst += len;
642  ++string;
643  }
644  }
645  /* Write null terminator */
646  *dst = '\0';
647  /* If any chars are left in string, return failure */
648  return *string == '\0' ? 0 : -1;
649 }
static int entity
Definition: isdn_lib.c:259
#define ast_assert(a)
Definition: utils.h:650
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