Asterisk - The Open Source Telephony Project  GIT-master-b91fb3c
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_estimated_bitrate(), ast_bridge_set_remb_send_interval(), ast_brige_set_remb_behavior(), ast_cc_is_recall(), ast_cdr_serialize_variables(), ast_channel_destructor(), ast_channel_forward_endpoint(), ast_channel_get_cc_config_params(), ast_channel_get_default_stream(), ast_channel_get_duration_ms(), ast_channel_get_stream_topology(), ast_channel_get_up_time_ms(), ast_channel_internal_oldest_linkedid(), ast_channel_internal_setup_topics(), ast_channel_internal_swap_stream_topology(), ast_channel_linkedid(), ast_channel_nativeformats_set(), ast_channel_publish_dial_forward(), ast_channel_publish_dial_internal(), ast_channel_publish_snapshot(), ast_channel_publish_varset(), ast_channel_request_stream_topology_change(), ast_channel_set_stream_topology(), ast_channel_snapshot_caller_id_equal(), ast_channel_snapshot_cep_equal(), ast_channel_snapshot_connected_line_equal(), ast_channel_snapshot_get_latest(), ast_channel_snapshot_get_latest_by_name(), ast_channel_stream_topology_changed(), ast_channel_stream_topology_changed_externally(), ast_channel_tech_set(), ast_channel_uniqueid(), ast_cli_completion_vector(), ast_data_buffer_alloc(), ast_data_buffer_cache_adjust(), ast_data_buffer_count(), ast_data_buffer_free(), ast_data_buffer_get(), ast_data_buffer_max(), ast_data_buffer_put(), ast_data_buffer_remove(), ast_data_buffer_remove_head(), ast_data_buffer_resize(), ast_datastores_add(), ast_db_get(), ast_dns_naptr_get_flags(), ast_dns_naptr_get_order(), ast_dns_naptr_get_preference(), ast_dns_naptr_get_regexp(), ast_dns_naptr_get_replacement(), ast_dns_naptr_get_service(), ast_dns_query_set_add(), ast_dns_query_set_resolve_async(), ast_dns_srv_get_host(), ast_dns_srv_get_port(), ast_dns_srv_get_priority(), ast_dns_srv_get_weight(), ast_dns_txt_get_count(), ast_dns_txt_get_strings(), ast_endpoint_add_channel(), ast_endpoint_latest_snapshot(), ast_endpoint_set_max_channels(), ast_endpoint_set_state(), ast_endpoint_snapshot_create(), ast_endpoint_snapshot_to_json(), ast_ends_with(), ast_escape_semicolons(), ast_format_cache_set(), ast_format_cap_get_best_by_type(), ast_format_cap_get_compatible_format(), ast_format_cap_get_format(), ast_format_cap_iscompatible_format(), ast_format_cap_remove(), ast_get_chan_applicationmap(), ast_get_chan_featuremap_config(), ast_get_chan_features_general_config(), ast_get_chan_features_pickup_config(), ast_get_chan_features_xfer_config(), ast_get_extension_for_mime_type(), ast_hangup(), ast_http_body_discard(), ast_http_get_auth(), ast_http_get_contents(), ast_http_send(), ast_iostream_set_exclusive_input(), ast_iostream_set_timeout_disable(), ast_iostream_set_timeout_idle_inactivity(), ast_iostream_set_timeout_inactivity(), ast_iostream_set_timeout_sequence(), ast_json_to_ast_variables(), ast_json_typename(), ast_json_typeof(), ast_manager_event_blob_create(), ast_msg_data_alloc(), ast_msg_data_dup(), ast_msg_data_get_attribute(), ast_msg_data_get_length(), ast_msg_data_get_source_type(), ast_msg_data_queue_frame(), ast_multi_channel_blob_create(), ast_multi_object_blob_create(), ast_mwi_blob_create(), ast_pbx_outgoing_exten_predial(), ast_publish_device_state_full(), ast_register_thread(), ast_res_pjsip_find_or_create_contact_status(), ast_rtcp_read(), ast_rtp_codecs_payloads_xover(), ast_rtp_read(), ast_search_dns_ex(), ast_serializer_pool_create(), ast_serializer_shutdown_group_join(), ast_set_read_format(), ast_set_write_format(), ast_set_write_format_interleaved_stereo(), ast_sip_auth_vector_init(), ast_sip_create_request(), ast_sip_get_contact_short_status_label(), ast_sip_get_contact_status_label(), ast_sip_identify_endpoint(), ast_sip_publish_client_add_datastore(), ast_sip_register_cli_formatter(), ast_sip_send_request(), ast_sip_session_add_datastore(), ast_sip_session_defer_termination(), ast_sip_session_register_supplement_with_module(), ast_sip_session_suspend(), ast_sip_subscription_get_dialog(), ast_sip_subscription_get_endpoint(), ast_sip_subscription_get_serializer(), ast_sip_transport_monitor_register_replace(), ast_sip_transport_monitor_unregister(), ast_sip_transport_monitor_unregister_all(), ast_sorcery_init(), ast_sorcery_is_object_field_registered(), ast_sorcery_object_id_hash(), ast_stream_get_format_count(), ast_stream_get_formats(), ast_stream_get_group(), ast_stream_get_name(), ast_stream_get_position(), ast_stream_get_rtp_codecs(), ast_stream_get_state(), ast_stream_get_type(), ast_stream_set_formats(), ast_stream_set_group(), ast_stream_set_rtp_codecs(), ast_stream_set_state(), ast_stream_set_type(), ast_stream_topology_append_stream(), ast_stream_topology_clone(), ast_stream_topology_del_stream(), ast_stream_topology_equal(), ast_stream_topology_get_active_count(), ast_stream_topology_get_count(), ast_stream_topology_get_first_stream_by_type(), ast_stream_topology_get_formats_by_type(), ast_stream_topology_get_stream(), ast_stream_topology_set_stream(), ast_taskprocessor_build_name(), ast_taskprocessor_name_append(), AST_TEST_DEFINE(), ast_udptl_read(), ast_utf8_copy_string(), ast_uuid_to_str(), ast_variable_list_append_hint(), ast_vector_string_split(), ast_xml_escape(), async_callback(), attended_transfer_monitor_thread(), authenticate(), autohint_cmp(), autohint_hash_cb(), base_process_parked_channel(), base_process_party_a(), bridge_action_bridge(), bridge_agent_hold_push(), bridge_alloc(), bridge_basic_pull(), bridge_basic_push(), bridge_channel_attended_transfer(), bridge_channel_handle_control(), bridge_channel_handle_write(), bridge_channel_impart_add(), bridge_channel_internal_push_full(), bridge_channel_queue_action_data_sync(), bridge_channel_update_accountcodes_joining(), bridge_channel_update_accountcodes_leaving(), bridge_channel_write_frame(), bridge_handle_actions(), bridge_handle_dtmf(), bridge_hash_cb(), bridge_merge_cb(), bridge_merge_inhibit_nolock(), bridge_merge_locked(), bridge_parking_push(), bridge_publish_state_from_blob(), bridge_stasis_moving(), bridge_state_process_party_b(), bridge_topics_destroy(), bridges_channel_hash_fn(), bridges_channel_sort_fn(), bridges_hash(), cache_entry_cmp(), cache_entry_create(), cache_entry_dump(), cache_entry_hash(), cache_find(), cache_put(), cache_test_message_create_full(), caching_topic_exec(), call_pickup_to_ami(), cc_generic_agent_start_monitoring(), cc_generic_agent_start_offer_timer(), cc_generic_monitor_cancel_available_timer(), cdr_all_cmp_fn(), cdr_all_hash_fn(), cdr_all_unlink(), cdr_master_cmp_fn(), cdr_master_hash_fn(), cdr_object_alloc(), cdr_object_create_public_records(), cdr_object_finalize_party_b(), cdr_object_party_b_left_bridge_cb(), cdr_object_update_party_b_userfield_cb(), cdr_read_callback(), cdr_write_callback(), cel_channel_linkedid_change(), cel_verify_and_cleanup_cb(), chan_pjsip_get_rtp_peer(), chan_pjsip_get_vrtp_peer(), chan_pjsip_indicate(), channel_dial_cb(), channel_hash(), channel_role_hash_cb(), channel_set_default_streams(), channel_snapshot_hash_cb(), channel_snapshot_uniqueid_hash_cb(), check_callback_sanity(), cli_aor_print_body(), cli_aor_print_header(), cli_channel_print_body(), cli_channel_print_header(), cli_channelstats_print_body(), cli_channelstats_print_header(), cli_complete_subscription_callid(), cli_contact_print_body(), cli_contact_print_header(), cli_endpoint_print_body(), cli_endpoint_print_header(), cli_list_subscriptions_inout(), cli_print_body(), cli_print_header(), cli_show_module_options(), cli_show_module_type(), cli_show_module_types(), cli_show_modules(), cli_show_subscription_inout(), cli_show_subscriptions_inout(), cli_unid_print_body(), cli_unid_print_header(), codec_cmp(), confbridge_publish_manager_event(), conference_bridge_hash_cb(), consumer_exec(), consumer_exec_sync(), consumer_should_stay(), consumer_wait_for(), consumer_wait_for_completion(), contact_alloc(), control_dispatch_all(), control_hash(), control_swap_channel_in_bridge(), control_wait(), copy_state_to_transport(), corosync_node_cmp_fn(), corosync_node_hash_fn(), create_callno_pools(), create_dialog_uas(), create_jb(), create_new_sip_etag(), dahdi_format_to_cached(), dahdi_translate(), datastore_cmp(), datastore_hash(), default_listener_pvt_destroy(), default_listener_shutdown(), default_tps_processing_function(), destroy_bridge(), determine_sip_publish_type(), device_state_alloc(), device_state_subscriptions_cmp(), device_state_subscriptions_hash(), dial_state_process_dial_end(), dial_state_process_party_b(), dialog_associations_cmp(), dialog_associations_hash(), digest_check_auth(), digest_create_request_with_auth(), dns_find_record(), dns_naptr_alloc(), dns_srv_alloc(), dsn_hash(), endpoint_cache_clear(), endpoint_dtor(), endpoint_publish_snapshot(), endpoint_snapshot_dtor(), evaluate_history_entry(), event_session_dtor(), event_session_hash(), event_session_update_websocket(), expression_token_alloc(), exten_state_publisher_cmp(), exten_state_publisher_hash(), extension_is_compatible(), featuregroup_hash(), features_pre_apply_config(), filename_parse(), find_bridge(), find_channel_control(), find_control(), find_route(), format_cap_replace(), format_cmp_cb(), format_hash_cb(), forwards_create_endpoint(), forwards_dtor(), forwards_sort(), 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(), session_outgoing_nat_hook(), set_dial_masquerade(), set_format(), set_ice_components(), set_softmix_bridge_data(), set_target_uri(), setup_invocation_test(), single_state_process_party_b(), sip_cc_agent_init(), sip_cc_monitor_unsuspend(), sip_create_publication(), sip_options_aor_dtor(), sip_options_contact_status_notify_task(), sip_outbound_registration_regc_alloc(), sip_outbound_registration_response_cb(), softmix_bridge_write(), sorcery_memory_cache_create(), sorcery_memory_cache_hash(), sorcery_memory_cache_retrieve_id(), sorcery_memory_cache_thrash_retrieve(), sorcery_memory_cache_thrash_update(), sorcery_memory_cached_object_hash(), stasis_app_exec(), stasis_app_message_handler(), stasis_app_playback_operation(), stasis_cache_dump_all(), stasis_cache_dump_by_eid(), stasis_cache_get_all(), stasis_cache_get_by_eid(), stasis_caching_topic_dtor(), stasis_message_router_accept_formatters(), stasis_message_router_add(), stasis_message_router_add_cache_update(), stasis_message_router_publish_sync(), stasis_message_router_remove(), stasis_message_router_remove_cache_update(), stasis_message_router_set_formatters_default(), stasis_publish_sync(), stasis_state_callback_all(), stasis_state_callback_subscribed(), stasis_sub_hash(), stasis_subscription_accept_formatters(), stasis_subscription_accept_message_type(), stasis_subscription_decline_message_type(), state_alloc(), state_dtor(), state_id_by_topic(), statsd_init(), stream_periodic_frames(), sub_endpoint_update_handler(), subscription_dtor(), 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:1317
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:1317
#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:1365
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:1365
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_with_stream_topology(), 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_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(), resolve_refresh_media_states(), retransfer_enter(), return_sorcery_object(), ring_entry(), rna(), root_handler_create(), rtcp_message_handler(), rtcp_report_to_ami(), rtp_write_rtcp_fir(), rtp_write_rtcp_psfb(), run_station(), run_task(), rx_data_to_ast_msg(), safe_mkdir(), scheduler(), sdp_requires_deferral(), security_event_to_ami_blob(), send_agent_complete(), send_agent_login(), send_agent_logoff(), send_bridge_info_item_cb(), send_bridge_list_item_cb(), send_call_pickup_stasis_message(), send_conf_stasis(), send_conf_stasis_snapshots(), send_device_state(), send_dtmf_begin_event(), send_dtmf_end_event(), send_message(), send_session_timeout(), send_talking_event(), send_unsolicited_mwi_notify(), sendfax_exec(), sendmail(), session_outgoing_nat_hook(), session_refresh_state_get_or_alloc(), session_reinvite_on_rx_request(), session_timeout_to_ami(), set_caps(), set_config_flags(), set_format(), setup_sdes_srtp(), sfu_topologies_on_join(), shared_write(), shutdown_data_create(), sip_options_qualify_contact(), sip_outbound_publish_callback(), sip_outbound_publish_synchronize(), sip_outbound_publisher_init(), sip_outbound_registration_apply(), sip_outbound_registration_regc_alloc(), sip_poke_noanswer(), sip_publisher_service_queue(), skel_find_or_create_state(), skinny_register(), skinny_session_cleanup(), sla_add_trunk_to_station(), sla_build_station(), sla_build_trunk(), sla_check_station_delay(), sla_handle_dial_state_event(), sla_state(), sla_station_exec(), sla_trunk_exec(), smdi_load(), snoop_stasis_thread(), socket_process_helper(), sorcery_astdb_create(), sorcery_astdb_retrieve_fields_common(), sorcery_astdb_retrieve_id(), sorcery_astdb_retrieve_prefix(), sorcery_astdb_retrieve_regex(), sorcery_config_fields_cmp(), sorcery_config_internal_load(), sorcery_config_retrieve_fields(), sorcery_config_retrieve_id(), sorcery_config_retrieve_multiple(), sorcery_config_retrieve_prefix(), sorcery_config_retrieve_regex(), sorcery_function_read(), sorcery_is_criteria_met(), sorcery_memory_cache_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_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 2435 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().

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

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

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

References AST_STACKSIZE, and AST_STACKSIZE_LOW.

1309 {
1310 #if !defined(LOW_MEMORY)
1311  return AST_STACKSIZE;
1312 #else
1313  return AST_STACKSIZE_LOW;
1314 #endif
1315 }
#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 and IS NULL terminated
Parameters
srcThe source buffer
Return values
NULLon failure
Decodedstring on success

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

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

References ast_base64decode(), ast_malloc, 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_malloc(decoded_len + 1);
335  if (!decoded_string) {
336  return NULL;
337  }
338 
339  ast_base64decode(decoded_string, src, decoded_len);
340  decoded_string[decoded_len] = '\0';
341 
342  return (char *)decoded_string;
343 }
#define NULL
Definition: resample.c:96
#define ast_malloc(len)
A wrapper for malloc()
Definition: astmm.h:193
int ast_base64decode(unsigned char *dst, const char *src, int max)
decode BASE64 encoded text
Definition: main/utils.c:287
#define ast_strlen_zero(a)
Definition: muted.c:73

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

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

References base64, and max.

Referenced by ast_base64encode().

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

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

Referenced by add_identity_header().

404 {
405  size_t encoded_len;
406  char *encoded_string;
407 
408  if (ast_strlen_zero(src)) {
409  return NULL;
410  }
411 
412  encoded_len = ((strlen(src) * 4 / 3 + 3) & ~3) + 1;
413  encoded_string = ast_calloc(1, encoded_len);
414 
415  ast_base64encode(encoded_string, (const unsigned char *)src, strlen(src), encoded_len);
416 
417  return encoded_string;
418 }
int ast_base64encode(char *dst, const unsigned char *src, int srclen, int max)
Encode data in base64.
Definition: main/utils.c:397
#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 1463 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().

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

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

Referenced by load_module().

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

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

Referenced by transport_apply().

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

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

Referenced by __ast_assert_failed(), and sip_route_process_header().

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

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

Referenced by load_module(), and set_config().

2719 {
2720  struct ast_eid empty_eid;
2721 
2722  memset(&empty_eid, 0, sizeof(empty_eid));
2723  return memcmp(eid, &empty_eid, sizeof(empty_eid)) ? 0 : 1;
2724 }
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 2458 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().

2459 {
2460  int x;
2461  char *os = s;
2462  if (maxlen < 18) {
2463  if (s && (maxlen > 0)) {
2464  *s = '\0';
2465  }
2466  } else {
2467  for (x = 0; x < 5; x++) {
2468  sprintf(s, "%02hhx:", eid->eid[x]);
2469  s += 3;
2470  }
2471  sprintf(s, "%02hhx", eid->eid[5]);
2472  }
2473  return os;
2474 }
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 2092 of file main/utils.c.

References ast_log, and LOG_WARNING.

Referenced by ast_netsock_bindaddr(), and reload_config().

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

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

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

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

◆ ast_get_tid()

int ast_get_tid ( void  )

Get current thread ID.

Returns
the ID if platform is supported, else -1

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

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

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

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

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

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

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

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

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

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

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

◆ ast_random()

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

Definition at line 1935 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().

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

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

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

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

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

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

2697 {
2698  unsigned int eid_int[6];
2699  int x;
2700 
2701  if (sscanf(s, "%2x:%2x:%2x:%2x:%2x:%2x", &eid_int[0], &eid_int[1], &eid_int[2],
2702  &eid_int[3], &eid_int[4], &eid_int[5]) != 6) {
2703  return -1;
2704  }
2705 
2706  for (x = 0; x < 6; x++) {
2707  eid->eid[x] = eid_int[x];
2708  }
2709 
2710  return 0;
2711 }
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 2867 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().

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

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

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

Referenced by handle_tcptls_connection().

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

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

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

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

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

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

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

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

Referenced by asterisk_daemon().

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

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

References ast_strdupa, NULL, and strsep().

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

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

References ast_poll.

Referenced by ast_iostream_write(), and iostream_read().

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

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