Thu Jul 9 13:41:35 2009

Asterisk developer's documentation


utils.h File Reference

Utility functions. More...

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

Go to the source code of this file.

Data Structures

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

Defines

#define ARRAY_LEN(a)   (sizeof(a) / sizeof(0[a]))
#define ast_asprintf(ret, fmt,)   _ast_asprintf((ret), __FILE__, __LINE__, __PRETTY_FUNCTION__, fmt, __VA_ARGS__)
 A wrapper for asprintf().
#define ast_assert(a)
#define AST_BACKGROUND_STACKSIZE   AST_STACKSIZE
#define ast_calloc(num, len)   _ast_calloc((num), (len), __FILE__, __LINE__, __PRETTY_FUNCTION__)
 A wrapper for calloc().
#define ast_calloc_cache(num, len)   _ast_calloc((num), (len), __FILE__, __LINE__, __PRETTY_FUNCTION__)
 A wrapper for calloc() for use in cache pools.
#define ast_clear_flag(p, flag)
#define ast_clear_flag64(p, flag)
#define ast_clear_flag_nonstd(p, flag)
#define ast_copy_flags(dest, src, flagz)
#define ast_copy_flags64(dest, src, flagz)
#define ast_copy_flags_nonstd(dest, src, flagz)
#define AST_FLAGS_ALL   UINT_MAX
#define ast_free   free
 free() wrapper
#define ast_free_ptr   ast_free
#define ast_malloc(len)   _ast_malloc((len), __FILE__, __LINE__, __PRETTY_FUNCTION__)
 A wrapper for malloc().
#define ast_pthread_create(a, b, c, d)
#define ast_pthread_create_background(a, b, c, d)
#define ast_pthread_create_detached(a, b, c, d)
#define ast_pthread_create_detached_background(a, b, c, d)
#define ast_realloc(p, len)   _ast_realloc((p), (len), __FILE__, __LINE__, __PRETTY_FUNCTION__)
 A wrapper for realloc().
#define ast_set2_flag(p, value, flag)
#define ast_set2_flag64(p, value, flag)
#define ast_set2_flag_nonstd(p, value, flag)
#define ast_set_flag(p, flag)
#define ast_set_flag64(p, flag)
#define ast_set_flag_nonstd(p, flag)
#define ast_set_flags_to(p, flag, value)
#define ast_set_flags_to64(p, flag, value)
#define AST_STACKSIZE   (((sizeof(void *) * 8 * 8) - 16) * 1024)
#define ast_strdup(str)   _ast_strdup((str), __FILE__, __LINE__, __PRETTY_FUNCTION__)
 A wrapper for strdup().
#define ast_strdupa(s)
 duplicate a string in memory from the stack
#define ast_strndup(str, len)   _ast_strndup((str), (len), __FILE__, __LINE__, __PRETTY_FUNCTION__)
 A wrapper for strndup().
#define ast_test_flag(p, flag)
#define ast_test_flag64(p, flag)
#define ast_test_flag_nonstd(p, flag)   ((p)->flags & (flag))
#define ast_vasprintf(ret, fmt, ap)   _ast_vasprintf((ret), __FILE__, __LINE__, __PRETTY_FUNCTION__, (fmt), (ap))
 A wrapper for vasprintf().
#define localtime_r   __dont_use_localtime_r_use_ast_localtime_instead__
#define MALLOC_FAILURE_MSG   ast_log(LOG_ERROR, "Memory Allocation Failure in function %s at line %d of %s\n", func, lineno, file);

Functions

int _ast_asprintf (char **ret, const char *file, int lineno, const char *func, const char *fmt,...)
void *attribute_malloc _ast_calloc (size_t num, size_t len, const char *file, int lineno, const char *func)
void *attribute_malloc _ast_malloc (size_t len, const char *file, int lineno, const char *func)
void *attribute_malloc _ast_realloc (void *p, size_t len, const char *file, int lineno, const char *func)
char *attribute_malloc _ast_strdup (const char *str, const char *file, int lineno, const char *func)
char *attribute_malloc _ast_strndup (const char *str, size_t len, const char *file, int lineno, const char *func)
int _ast_vasprintf (char **ret, const char *file, int lineno, const char *func, const char *fmt, va_list ap)
int ast_base64decode (unsigned char *dst, const char *src, int max)
 Decode data from base64.
int ast_base64encode (char *dst, const unsigned char *src, int srclen, int max)
 Encode data in base64.
int ast_base64encode_full (char *dst, const unsigned char *src, int srclen, int max, int linebreaks)
 encode text to BASE64 coding
int ast_careful_fwrite (FILE *f, int fd, const char *s, size_t len, int timeoutms)
 Write data to a file stream with a timeout.
int ast_carefulwrite (int fd, char *s, int len, int timeoutms)
 Try to write string, but wait no more than ms milliseconds before timing out.
void ast_enable_packet_fragmentation (int sock)
 Disable PMTU discovery on a socket.
hostent * ast_gethostbyname (const char *host, struct ast_hostent *hp)
 Thread-safe gethostbyname function to use in Asterisk.
void ast_md5_hash (char *output, char *input)
 Produces MD5 hash based on input string.
int ast_mkdir (const char *path, int mode)
 Recursively create directory path.
char * ast_process_quotes_and_slashes (char *start, char find, char replace_with)
 Process a string to find and replace characters.
int ast_pthread_create_detached_stack (pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *), void *data, size_t stacksize, const char *file, const char *caller, int line, const char *start_fn)
int ast_pthread_create_stack (pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *), void *data, size_t stacksize, const char *file, const char *caller, int line, const char *start_fn)
long int ast_random (void)
void ast_register_thread (char *name)
void ast_sha1_hash (char *output, char *input)
 Produces SHA1 hash based on input string.
static force_inline void ast_slinear_saturated_add (short *input, short *value)
static force_inline void ast_slinear_saturated_divide (short *input, short *value)
static force_inline void ast_slinear_saturated_multiply (short *input, short *value)
static force_inline void ast_slinear_saturated_subtract (short *input, short *value)
void ast_unregister_thread (void *id)
void ast_uri_decode (char *s)
 Decode URI, URN, URL (overwrite string).
char * ast_uri_encode (const char *string, char *outbuf, int buflen, int doreserved)
 Turn text string to URI-encoded XX version.
int ast_utils_init (void)
int ast_wait_for_input (int fd, int ms)

Variables

unsigned int __unsigned_int_flags_dummy
uint64_t __unsigned_int_flags_dummy64


Detailed Description

Utility functions.

Definition in file utils.h.


Define Documentation

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

Definition at line 647 of file utils.h.

Referenced by __ast_cli_generator(), __unload_module(), _sip_show_peer(), alarm2str(), ast_best_codec(), ast_cause2str(), ast_channels_init(), ast_cli_netstats(), ast_codec2str(), ast_codec_choose(), ast_codec_pref_append(), ast_codec_pref_getsize(), ast_codec_pref_prepend(), ast_codec_pref_remove(), ast_codec_pref_setsize(), ast_describe_caller_presentation(), ast_dsp_prog_reset(), ast_dsp_set_call_progress_zone(), ast_expand_codec_alias(), ast_extension_state2str(), ast_get_format_list(), ast_getformatbyname(), ast_getformatname(), ast_getformatname_multiple(), ast_image_init(), ast_named_caller_presentation(), ast_parse_caller_presentation(), ast_rtp_lookup_mime_subtype(), ast_rtp_set_rtpmap_type(), ast_str2cause(), ast_str2tos(), ast_tos2str(), ast_utils_init(), astobj2_init(), authority_to_str(), cache_get_callno_locked(), cb_events(), check_blacklist(), common_exec(), complete_dpreply(), complete_ulimit(), conf_exec(), convert_attribute_name_from_ldap(), convert_attribute_name_to_ldap(), dump_cause(), dundi_eid_zero(), dundi_query_read(), event2str(), fill_rxgain(), fill_txgain(), find_alias(), find_cache(), find_sip_method(), find_subscription_type(), ftype2mtype(), get_perm(), geteventbyname(), getjustifybyname(), handle_cli_iax2_show_cache(), handle_cli_iax2_show_channels(), handle_cli_ulimit(), handle_input(), handle_jack_audio(), iax_provflags2str(), iax_str2flags(), jack_status_to_str(), jb_choose_impl(), lin16tog722_sample(), lintog722_sample(), load_module(), main(), make_trunk(), milliwatt_generate(), minivm_accmess_exec(), minivm_greet_exec(), minivm_notify_exec(), minivm_record_exec(), parkandannounce_exec(), parse_naptr(), parse_sip_options(), pbx_retrieve_variable(), process_echocancel(), process_opcode(), process_returncode(), queue_voice_frame(), resample_frame(), rotate_file(), sip_show_channel(), slin16_to_slin8_sample(), slin8_to_slin16_sample(), ss_thread(), str2desc(), str2limit(), strings_to_mask(), subscription_type2str(), unload_module(), and update_max_trunk().

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

A wrapper for asprintf().

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

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

Definition at line 571 of file utils.h.

#define ast_assert (  ) 

Definition at line 673 of file utils.h.

Referenced by ast_hangup(), ast_rtcp_read(), ast_rtp_read(), ast_sched_del(), ast_udptl_read(), create_jb(), and jb_get_and_deliver().

#define AST_BACKGROUND_STACKSIZE   AST_STACKSIZE

Definition at line 357 of file utils.h.

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

A wrapper for calloc().

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

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

Definition at line 454 of file utils.h.

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

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

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

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

Definition at line 479 of file utils.h.

#define ast_clear_flag ( p,
flag   ) 

Definition at line 75 of file utils.h.

Referenced by __ast_read(), __do_deliver(), aji_filter_roster(), ast_app_parse_options(), ast_autoservice_stop(), ast_bridge_call(), ast_cdr_reset(), ast_cdr_specialized_reset(), ast_channel_bridge(), ast_channel_undefer_dtmf(), ast_deactivate_generator(), ast_dsp_frame_freed(), ast_filestream_frame_freed(), ast_frisolate(), ast_jb_destroy(), ast_jb_put(), ast_rtp_stop(), ast_sendtext(), ast_speech_start(), ast_translate_frame_freed(), ast_waitfor_nandfds(), ast_waitfordigit_full(), ast_write(), authenticate_verify(), bridge_p2p_loop(), build_peer(), build_user(), builtin_atxfer(), chanspy_exec(), check_goto_on_transfer(), check_pendings(), common_exec(), config_text_file_load(), create_addr(), dahdi_read(), dictate_exec(), disa_exec(), do_parking_thread(), dundi_lookup_local(), extenspy_exec(), find_conf(), find_conf_realtime(), forward_message(), handle_common_options(), handle_request_bye(), handle_request_invite(), handle_request_refer(), handle_response(), handle_speechrecognize(), handle_verbose(), iax2_destroy_helper(), init_acf_query(), linear_alloc(), load_config(), load_moh_classes(), local_ast_moh_stop(), local_attended_transfer(), local_hangup(), local_queue_frame(), main(), odbc_load_module(), park_call_full(), parkandannounce_exec(), phone_read(), playtones_alloc(), process_sdp(), register_verify(), reload_config(), reset_transaction(), set_config(), set_config_destroy(), set_config_flags(), setup_dahdi(), sip_dtmfmode(), sip_hangup(), socket_process(), speech_background(), update_call_counter(), and waitstream_core().

#define ast_clear_flag64 ( p,
flag   ) 

Definition at line 132 of file utils.h.

Referenced by do_forward(), and wait_for_answer().

#define ast_clear_flag_nonstd ( p,
flag   ) 

Value:

do { \
               ((p)->flags &= ~(flag)); \
               } while(0)

Definition at line 178 of file utils.h.

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

#define ast_copy_flags ( dest,
src,
flagz   ) 

Definition at line 82 of file utils.h.

Referenced by __find_callno(), add_features_datastores(), agent_read(), aji_create_client(), aji_filter_roster(), ast_call_forward(), ast_cdr_reset(), ast_cdr_specialized_reset(), ast_feature_interpret(), ast_frdup(), ast_frisolate(), build_peer(), build_user(), builtin_atxfer(), cache_lookup_internal(), check_access(), check_peer_ok(), check_user_ok(), create_addr(), create_addr_from_peer(), dundi_lookup_local(), framein(), iax2_request(), minivm_greet_exec(), minivm_record_exec(), park_exec(), populate_defaults(), register_verify(), set_peer_defaults(), sip_alloc(), sip_poke_peer(), transmit_response_using_temp(), and vm_exec().

#define ast_copy_flags64 ( dest,
src,
flagz   ) 

Definition at line 139 of file utils.h.

Referenced by dial_exec_full(), and wait_for_answer().

#define ast_copy_flags_nonstd ( dest,
src,
flagz   ) 

Value:

do { \
               (dest)->flags &= ~(flagz); \
               (dest)->flags |= ((src)->flags & (flagz)); \
               } while (0)

Definition at line 182 of file utils.h.

#define AST_FLAGS_ALL   UINT_MAX

Definition at line 194 of file utils.h.

Referenced by add_features_datastores(), aji_create_client(), ast_app_parse_options(), ast_cdr_reset(), ast_cdr_specialized_reset(), ast_feature_interpret(), builtin_atxfer(), cache_lookup_internal(), chanspy_exec(), check_goto_on_transfer(), dundi_lookup_local(), extenspy_exec(), load_moh_classes(), park_exec(), populate_defaults(), and set_config_flags().

#define ast_free   free

free() wrapper

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

Definition at line 415 of file utils.h.

#define ast_free_ptr   ast_free

Definition at line 416 of file utils.h.

Referenced by do_parking_thread(), handle_cli_dialplan_add_extension(), load_module(), park_call_full(), pbx_load_config(), pbx_load_users(), register_exten(), and register_peer_exten().

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

A wrapper for malloc().

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

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

Definition at line 431 of file utils.h.

#define ast_pthread_create ( a,
b,
c,
 ) 

Value:

ast_pthread_create_stack(a, b, c, d,         \
      0, __FILE__, __FUNCTION__, __LINE__, #c)

Definition at line 371 of file utils.h.

Referenced by accept_thread(), ast_bridge_call_thread_launch(), ast_dial_run(), ast_features_init(), handle_callforward_button(), handle_enbloc_call_message(), handle_offhook_message(), handle_soft_key_event_message(), handle_stimulus_message(), HandleCallOutgoing(), init_logger(), load_module(), load_pbx(), restart_monitor(), setup_dahdi(), show_console(), sla_load_config(), and start_poll_thread().

#define ast_pthread_create_background ( a,
b,
c,
 ) 

Value:

ast_pthread_create_stack(a, b, c, d,         \
      AST_BACKGROUND_STACKSIZE,        \
      __FILE__, __FUNCTION__, __LINE__, #c)

Definition at line 379 of file utils.h.

Referenced by aji_reload(), ast_autoservice_start(), ast_device_state_engine_init(), ast_event_init(), ast_makesocket(), ast_tcptls_server_start(), conf_run(), do_reload(), init_app_class(), load_module(), local_ast_moh_start(), pri_dchannel(), reload_config(), restart_monitor(), sip_prepare_socket(), start_network_thread(), start_stream(), and usbradio_call().

#define ast_pthread_create_detached ( a,
b,
c,
 ) 

Value:

ast_pthread_create_detached_stack(a, b, c, d,      \
      0, __FILE__, __FUNCTION__, __LINE__, #c)

Definition at line 375 of file utils.h.

Referenced by action_originate(), ast_pbx_outgoing_app(), ast_pbx_outgoing_exten(), ast_pbx_start(), dahdi_handle_event(), dundi_answer_entity(), dundi_answer_query(), handle_hd_hf(), handle_init_event(), launch_service(), local_dtmf_helper(), main(), mwi_thread(), rpt_master(), rpt_telemetry(), spawn_dp_lookup(), and start_network_thread().

#define ast_pthread_create_detached_background ( a,
b,
c,
 ) 

Value:

ast_pthread_create_detached_stack(a, b, c, d,      \
      AST_BACKGROUND_STACKSIZE,        \
      __FILE__, __FUNCTION__, __LINE__, #c)

Definition at line 384 of file utils.h.

Referenced by ast_cdr_submit_batch(), ast_tcptls_server_root(), conf_run(), find_idle_thread(), iax_park(), launch_monitor_thread(), listener(), load_module(), sip_park(), sla_handle_dial_state_event(), and sla_station_exec().

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

A wrapper for realloc().

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

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

Definition at line 490 of file utils.h.

#define ast_set2_flag ( p,
value,
flag   ) 

Definition at line 92 of file utils.h.

Referenced by _macro_exec(), aji_create_client(), aji_load_config(), apply_general_options(), apply_option(), apply_outgoing(), ast_bridge_call(), ast_jb_read_conf(), ast_rtp_setdtmf(), ast_rtp_setdtmfcompensate(), ast_rtp_setstun(), ast_translate(), build_peer(), build_user(), check_access(), dial_exec_full(), do_reload(), find_account(), find_user(), handle_common_options(), load_config(), load_module(), load_moh_classes(), local_ast_moh_start(), and set_config().

#define ast_set2_flag64 ( p,
value,
flag   ) 

Definition at line 149 of file utils.h.

Referenced by dial_exec_full().

#define ast_set2_flag_nonstd ( p,
value,
flag   ) 

Definition at line 187 of file utils.h.

#define ast_set_flag ( p,
flag   ) 

Definition at line 68 of file utils.h.

Referenced by __ast_pbx_run(), __ast_read(), __ast_request_and_dial(), _macro_exec(), action_redirect(), aji_load_config(), app_exec(), apply_peer(), ast_app_parse_options(), ast_autoservice_start(), ast_bridge_call(), ast_call(), ast_cdr_detach(), ast_cdr_fork(), ast_cdr_merge(), ast_cdr_reset(), ast_cdr_specialized_reset(), ast_channel_bridge(), ast_channel_defer_dtmf(), ast_do_masquerade(), ast_dsp_process(), ast_generic_bridge(), ast_hangup(), ast_jb_do_usecheck(), ast_jb_put(), ast_readaudio_callback(), ast_readframe(), ast_readvideo_callback(), ast_rtp_bridge(), ast_rtp_new_init(), ast_rtp_raw_write(), ast_rtp_read(), ast_speech_change_state(), ast_trans_frameout(), ast_waitfor_nandfds(), ast_waitfordigit_full(), asyncgoto_exec(), authenticate_reply(), authenticate_request(), bridge_p2p_rtp_write(), build_peer(), build_user(), builtin_atxfer(), builtin_blindtransfer(), cb_extensionstate(), chanspy_exec(), check_access(), check_availability(), check_bridge(), check_peer_ok(), check_user_full(), check_user_ok(), check_via(), common_exec(), conf_exec(), create_addr_from_peer(), create_transaction(), dahdi_decoder_frameout(), dahdi_encoder_frameout(), dahdi_read(), decrypt_frame(), dial_exec_full(), dictate_exec(), disa_exec(), do_parking_thread(), do_register(), do_timelimit(), dundi_encrypt(), dundi_lookup_local(), dundi_send(), extenspy_exec(), find_user_realtime(), free_vm_users(), handle_cli_iax2_prune_realtime(), handle_common_options(), handle_invite_replaces(), handle_request_invite(), handle_request_refer(), handle_request_subscribe(), handle_response(), handle_response_invite(), handle_verbose(), hanguptree(), iax2_predestroy(), iax2_provision(), init_acf_query(), init_app_class(), init_files_class(), init_outgoing(), launch_monitor_thread(), linear_alloc(), load_moh_classes(), local_alloc(), local_ast_moh_start(), local_attended_transfer(), local_call(), local_hangup(), local_queue_frame(), login_exec(), main(), minivm_greet_exec(), nocdr_exec(), odbc_load_module(), park_call_full(), park_exec(), peer_delme_cb(), playtones_alloc(), post_cdr(), process_rfc3389(), process_sdp(), pvt_destructor(), qualify_peer(), record_exec(), register_verify(), run_station(), set_bridge_features_on_config(), set_config(), set_config_flags(), set_insecure_flags(), sip_answer(), sip_call(), sip_dtmfmode(), sip_hangup(), sip_indicate(), sip_poke_peer(), sip_read(), sip_reinvite_retry(), sip_send_mwi_to_peer(), sip_sendhtml(), sip_set_rtp_peer(), sip_set_udptl_peer(), sip_write(), sla_station_exec(), sla_trunk_exec(), socket_process(), start_spying(), tonepair_alloc(), transmit_register(), transmit_reinvite_with_sdp(), try_calling(), update_call_counter(), user_delme_cb(), vm_execmain(), volume_write(), and waitstream_core().

#define ast_set_flag64 ( p,
flag   ) 

Definition at line 125 of file utils.h.

Referenced by ast_app_parse_options64(), and dial_exec_full().

#define ast_set_flag_nonstd ( p,
flag   ) 

Value:

do { \
               ((p)->flags |= (flag)); \
               } while(0)

Definition at line 174 of file utils.h.

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

#define ast_set_flags_to ( p,
flag,
value   ) 

Definition at line 102 of file utils.h.

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

#define ast_set_flags_to64 ( p,
flag,
value   ) 

Definition at line 159 of file utils.h.

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

Definition at line 352 of file utils.h.

Referenced by ast_pthread_create_stack().

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

A wrapper for strdup().

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

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

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

Definition at line 517 of file utils.h.

#define ast_strdupa (  ) 

duplicate a string in memory from the stack

Parameters:
s The string to duplicate
This macro will duplicate the given string. It returns a pointer to the stack allocatted memory for the new string.

Definition at line 611 of file utils.h.

Referenced by __ast_play_and_record(), __verboser(), _ast_device_state(), _build_port_config(), _macro_exec(), _parse(), _while_exec(), acf_channel_read(), acf_odbc_write(), action_agents(), add_agent(), add_peer_mailboxes(), add_redirect(), add_var(), admin_exec(), advanced_options(), agent_logoff_maintenance(), agi_handle_command(), aji_send_exec(), aji_status_exec(), answer_exec_enable(), app_exec(), append_mailbox(), append_mailbox_mapping(), append_var_and_value_to_filter(), apply_options(), aqm_exec(), array(), ast_aji_get_client(), ast_app_getdata(), ast_append_ha(), ast_bridge_call(), ast_callerid_split(), ast_cdr_fork(), ast_eivr_setvariable(), ast_event_check_subscriber(), ast_event_get_cached(), ast_event_new(), ast_feature_interpret(), ast_filehelper(), ast_func_read(), ast_func_write(), ast_get_group(), ast_mkdir(), ast_monitor_change_fname(), ast_monitor_start(), ast_netsock_bind(), ast_parse_allow_disallow(), ast_parse_arg(), ast_playtones_start(), ast_register_file_version(), ast_writefile(), astman_get_variables(), asyncgoto_exec(), attempt_reconnect(), auth_exec(), authenticate_reply(), authenticate_verify(), background_detect_exec(), bridge_exec(), build_channels(), build_device(), build_gateway(), build_mapping(), build_peer(), build_profile(), build_user(), builtin_atxfer(), builtin_automixmonitor(), builtin_automonitor(), cache_get_callno_locked(), callerid_write(), chanavail_exec(), channel_admin_exec(), channel_spy(), chanspy_exec(), check_access(), check_blacklist(), check_goto_on_transfer(), check_peer_ok(), check_user_full(), check_user_ok(), collect_function_digits(), complete_meetmecmd(), conf_exec(), conf_run(), conf_start_moh(), controlplayback_exec(), count_exec(), create_addr(), create_addr_from_peer(), create_vmaccount(), cut_internal(), dahdi_request(), dahdiras_exec(), decrypt_frame(), del_exec(), deltree_exec(), dial_exec_full(), dial_trunk(), dialgroup_refreshdb(), dialgroup_write(), dictate_exec(), directory_exec(), disa_exec(), do_immediate_setup(), do_message(), do_parking_thread(), do_say(), do_timelimit(), dundi_query_read(), dundi_result_read(), enum_query_read(), enum_result_read(), exec_exec(), execif_exec(), extenspy_exec(), features_alloc(), festival_exec(), fileexists_core(), find_conf(), find_conf_realtime(), find_gtalk(), find_sdp(), findmeexec(), function_agent(), function_autopatchup(), function_iaxpeer(), function_ilink(), function_realtime_store(), function_remote(), get_destination(), get_refer_info(), gosub_exec(), gosubif_exec(), gtalk_action(), gtalk_alloc(), gtalk_create_candidates(), gtalk_digit(), gtalk_invite(), gtalk_invite_response(), gtalk_request(), handle_call_forward(), handle_cli_file_convert(), handle_cli_rpt_stats(), handle_options(), handle_request_invite(), handle_request_subscribe(), handle_response(), handle_show_dialplan(), has_voicemail(), httpd_helper_thread(), iax2_call(), iax2_devicestate(), iax2_prov_app(), iax2_request(), iconv_read(), ind_load_module(), init_acf_query(), init_jack_data(), insert_penaltychange(), is_prefix(), is_valid_dtmf(), isAnsweringMachine(), isexten_function_read(), ivr_dispatch(), jingle_request(), launch_monitor_thread(), launch_netscript(), load_config(), local_devicestate(), log_exec(), login_exec(), lua_func_read(), lua_get_variable(), lua_get_variable_value(), lua_pbx_exec(), lua_set_variable_value(), macroif_exec(), main(), make_components(), make_email_file(), masq_park_call(), meetmemute(), metermaidstate(), mgcp_devicestate(), minivm_accmess_exec(), minivm_account_func_read(), minivm_counter_func_read(), minivm_counter_func_write(), minivm_greet_exec(), minivm_notify_exec(), minivm_record_exec(), misdn_call(), misdn_check_l2l1(), misdn_facility_exec(), misdn_request(), misdn_set_opt_exec(), mixmonitor_exec(), moh_handle_digit(), monitor_dial(), notify_message(), notify_new_message(), orig_app(), orig_exten(), ospauth_exec(), ospfinished_exec(), osplookup_exec(), ospnext_exec(), oss_call(), oss_request(), page_exec(), park_call_exec(), parkandannounce_exec(), parse_register_contact(), parse_session_expires(), parse_sip_options(), pbx_builtin_background(), pbx_builtin_execiftime(), pbx_builtin_gotoif(), pbx_builtin_gotoiftime(), pbx_builtin_importvar(), pbx_builtin_pushvar_helper(), pbx_builtin_resetcdr(), pbx_builtin_setvar(), pbx_builtin_setvar_helper(), pbx_builtin_setvar_multiple(), pbx_builtin_waitexten(), pbx_parseable_goto(), pbx_retrieve_variable(), peer_set_srcaddr(), pickup_exec(), pickupchan_exec(), play_message(), play_moh_exec(), playback_exec(), pqm_exec(), prep_email_sub_vars(), privacy_exec(), process_dahdi(), process_echocancel(), process_sdp(), ql_exec(), queue_exec(), queue_mwi_event(), queue_set_param(), rcvfax_exec(), read_exec(), readexten_exec(), readfile_exec(), realtime_common(), realtime_exec(), realtime_multi_curl(), realtime_multi_odbc(), realtime_multi_pgsql(), record_exec(), register_verify(), registry_authrequest(), reload_followme(), replace_cid(), resource_name_match(), retrydial_exec(), rpt_exec(), rpt_tele_thread(), rqm_exec(), sayunixtime_exec(), send_tone_telemetry(), senddtmf_exec(), sendmail(), sendtext_exec(), sendurl_exec(), set_config_flags(), setup_privacy_args(), sip_devicestate(), sip_new(), sip_sipredirect(), sip_uri_cmp(), sip_uri_headers_cmp(), sip_uri_params_cmp(), skinny_devicestate(), sla_add_trunk_to_station(), sla_check_device(), sla_queue_event_conf(), sla_ring_station(), sla_state(), sla_station_exec(), sla_trunk_exec(), smdi_msg_read(), smdi_msg_retrieve_read(), sms_exec(), sndfax_exec(), socket_process(), softhangup_exec(), sort_internal(), speech_background(), speech_load(), start_moh_exec(), start_monitor_action(), start_monitor_exec(), timezone_add(), transfer_exec(), transmit_invite(), transmit_refer(), try_suggested_sip_codec(), tryexec_exec(), unistim_send_mwi_to_peer(), update_bridge_vars(), update_common_options(), update_registry(), upqm_exec(), userevent_exec(), verbose_exec(), vm_box_exists(), vm_exec(), vm_execmain(), vmauthenticate(), wait_for_winner(), waitstream_core(), and zapateller_exec().

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

A wrapper for strndup().

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

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

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

Definition at line 546 of file utils.h.

#define ast_test_flag ( p,
flag   ) 

Definition at line 61 of file utils.h.

Referenced by __ast_pbx_run(), __ast_queue_frame(), __ast_read(), __do_deliver(), __expire_registry(), __frame_free(), __get_from_jb(), __iax2_show_peers(), __sip_destroy(), _macro_exec(), _sip_show_peer(), _sip_show_peers(), acf_odbc_read(), add_agent(), add_codec_to_sdp(), add_sdp(), aji_pruneregister(), app_exec(), ast_audiohook_write_frame(), ast_autoservice_start(), ast_bridge_call(), ast_call(), ast_cdr_answer(), ast_cdr_appenduserfield(), ast_cdr_busy(), ast_cdr_end(), ast_cdr_failed(), ast_cdr_fork(), ast_cdr_init(), ast_cdr_merge(), ast_cdr_noanswer(), ast_cdr_reset(), ast_cdr_setaccount(), ast_cdr_setamaflags(), ast_cdr_setanswer(), ast_cdr_setapp(), ast_cdr_setcid(), ast_cdr_setdestchan(), ast_cdr_setdisposition(), ast_cdr_setuserfield(), ast_cdr_setvar(), ast_cdr_specialized_reset(), ast_cdr_start(), ast_cdr_update(), ast_channel_bridge(), ast_channel_defer_dtmf(), ast_cli_netstats(), ast_closestream(), ast_do_masquerade(), ast_dsp_free(), ast_explicit_goto(), ast_frisolate(), ast_hangup(), ast_indicate_data(), ast_jb_destroy(), ast_jb_do_usecheck(), ast_jb_empty_and_reset(), ast_jb_get_and_deliver(), ast_jb_get_when_to_wakeup(), ast_jb_put(), ast_make_file_from_fd(), ast_moh_files_next(), ast_quiet_chan(), ast_raw_answer(), ast_readstring_full(), ast_rtp_bridge(), ast_rtp_early_bridge(), ast_rtp_getnat(), ast_rtp_make_compatible(), ast_rtp_raw_write(), ast_sendtext(), ast_softhangup_nolock(), ast_streamfile(), ast_transfer(), ast_translate(), ast_waitfordigit_full(), ast_write(), auth_exec(), authenticate_request(), authenticate_verify(), bridge_exec(), bridge_native_loop(), bridge_p2p_rtp_write(), build_peer(), build_radius_record(), build_user(), build_via(), callback_dialoptions(), cb_extensionstate(), cdr_read(), cdr_write(), channel_spy(), chanspy_exec(), check_access(), check_bridge(), check_peer_ok(), check_pendings(), check_post(), check_rtp_timeout(), check_user_full(), check_user_ok(), close_mailbox(), common_exec(), complete_sip_peer(), complete_sip_registered_peer(), complete_sip_user(), conf_exec(), config_text_file_load(), controlplayback_exec(), copy_via_headers(), create_addr(), create_addr_from_peer(), create_jb(), decrypt_frame(), destroy(), destroy_trans(), dial_exec_full(), dictate_exec(), directory_exec(), disa_exec(), do_directory(), dtmf_audiohook_write_list(), dundi_encrypt(), dundi_exec(), dundi_helper(), dundi_lookup_local(), dundi_lookup_thread(), dundi_precache_thread(), dundi_query_read(), dundi_query_thread(), dundi_rexmit(), dundi_send(), dundifunc_read(), eivr_comm(), expire_register(), extenspy_exec(), feature_exec_app(), feature_interpret_helper(), find_cache(), find_call(), find_conf(), find_conf_realtime(), find_or_create(), find_user(), find_user_realtime(), forward_message(), free_user(), function_iaxpeer(), get_destination(), get_insecure_variable_from_config(), get_sip_pvt_byid_locked(), gosub_exec(), handle_cli_iax2_prune_realtime(), handle_cli_iax2_show_channels(), handle_cli_iax2_show_peer(), handle_cli_iax2_show_users(), handle_cli_moh_show_classes(), handle_command_response(), handle_frame(), 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_show_settings(), handle_showchan(), handle_skinny_show_settings(), handle_speechrecognize(), hint_read(), iax2_call(), iax2_destroy_helper(), iax2_getpeertrunk(), iax2_hangup(), iax2_predestroy(), iax2_request(), iax2_send(), iax2_trunk_queue(), iax2_write(), initreqprep(), leave_voicemail(), load_dynamic_module(), load_resource(), local_alloc(), local_ast_moh_start(), local_hangup(), local_queue_frame(), local_write(), log_jitterstats(), main(), make_email_file(), manager_iax2_show_peer_list(), manager_list_voicemail_users(), minivm_accmess_exec(), minivm_account_func_read(), minivm_greet_exec(), minivm_notify_exec(), minivm_record_exec(), mixmonitor_exec(), mixmonitor_thread(), moh_files_alloc(), notify_new_message(), p2p_callback_disable(), page_exec(), parse_moved_contact(), parse_register_contact(), pbx_builtin_background(), pbx_builtin_waitexten(), pick_unlocked_cdr(), play_mailbox_owner(), play_message(), play_record_review(), post_cdr(), precache_transactions(), prepare_cb(), process_cisco_dtmf(), process_rfc2833(), process_rfc3389(), process_sdp(), process_text_line(), prune_peers(), prune_users(), read_exec(), readexten_exec(), record_exec(), reg_source_db(), register_verify(), remove_from_queue(), replace_cid(), reqprep(), respprep(), retrydial_exec(), schedule_delivery(), select_entry(), send_dtmf(), send_request(), send_trunk(), sendmail(), sendurl_exec(), serialize_showchan(), set_address_from_contact(), set_config(), set_config_flags(), should_skip_dtmf(), show_channels_cb(), sip_addrcmp(), sip_alloc(), sip_dtmfmode(), sip_fixup(), sip_get_rtp_peer(), sip_get_trtp_peer(), sip_get_udptl_peer(), sip_get_vrtp_peer(), sip_hangup(), sip_indicate(), sip_nat_mode(), sip_new(), sip_prune_realtime(), sip_queryoption(), sip_read(), sip_real_dst(), sip_rtp_read(), sip_send_mwi_to_peer(), sip_senddigit_begin(), sip_senddigit_end(), sip_sendhtml(), sip_set_rtp_peer(), sip_set_udptl_peer(), sip_show_channel(), sip_show_settings(), sip_show_user(), sip_show_users(), sip_write(), sla_trunk_exec(), sms_exec(), socket_process(), socket_process_meta(), softhangup_exec(), spawn_mp3(), speech_background(), speech_read(), start_spying(), startmon(), transmit_info_with_digit(), transmit_notify_with_mwi(), transmit_refer(), transmit_reinvite_with_sdp(), transmit_response_using_temp(), transmit_response_with_sdp(), try_calling(), update_call_counter(), update_peer(), update_registry(), vm_exec(), vm_execmain(), vm_intro(), vm_newuser(), and waitstream_core().

#define ast_test_flag64 ( p,
flag   ) 

Definition at line 118 of file utils.h.

Referenced by ast_app_options2str64(), dial_exec_full(), do_forward(), retrydial_exec(), setup_privacy_args(), valid_priv_reply(), and wait_for_answer().

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

Definition at line 171 of file utils.h.

Referenced by cache_save_hint(), dundi_lookup_thread(), dundi_precache_thread(), and handle_command_response().

#define ast_vasprintf ( ret,
fmt,
ap   )     _ast_vasprintf((ret), __FILE__, __LINE__, __PRETTY_FUNCTION__, (fmt), (ap))

A wrapper for vasprintf().

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

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

Definition at line 585 of file utils.h.

#define localtime_r   __dont_use_localtime_r_use_ast_localtime_instead__

Definition at line 313 of file utils.h.

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

Definition at line 421 of file utils.h.

Referenced by _ast_asprintf().


Function Documentation

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

Definition at line 1758 of file utils.c.

References MALLOC_FAILURE_MSG, and vasprintf.

01759 {
01760    int res;
01761    va_list ap;
01762 
01763    va_start(ap, fmt);
01764    if ((res = vasprintf(ret, fmt, ap)) == -1) {
01765       MALLOC_FAILURE_MSG;
01766    }
01767    va_end(ap);
01768 
01769    return res;
01770 }

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

Definition at line 467 of file utils.h.

00495 {

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

Definition at line 444 of file utils.h.

00459 {

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

Definition at line 503 of file utils.h.

00522 {

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

Definition at line 532 of file utils.h.

00551 {

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

Definition at line 561 of file utils.h.

00591 {

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

Definition at line 599 of file utils.h.

00613 {                                                                \

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

Decode data from base64.

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

Definition at line 261 of file utils.c.

Referenced by __ast_check_signature(), base64_decode(), and osp_validate_token().

00262 {
00263    int cnt = 0;
00264    unsigned int byte = 0;
00265    unsigned int bits = 0;
00266    int incnt = 0;
00267    while (*src && (cnt < max)) {
00268       /* Shift in 6 bits of input */
00269       byte <<= 6;
00270       byte |= (b2a[(int)(*src)]) & 0x3f;
00271       bits += 6;
00272       src++;
00273       incnt++;
00274       /* If we have at least 8 bits left over, take that character 
00275          off the top */
00276       if (bits >= 8)  {
00277          bits -= 8;
00278          *dst = (byte >> bits) & 0xff;
00279          dst++;
00280          cnt++;
00281       }
00282    }
00283    /* Dont worry about left over bits, they're extra anyway */
00284    return cnt;
00285 }

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

Encode data in base64.

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

Definition at line 339 of file utils.c.

References ast_base64encode_full().

Referenced by __ast_sign(), aji_start_sasl(), base64_encode(), build_secret(), and osp_check_destination().

00340 {
00341    return ast_base64encode_full(dst, src, srclen, max, 0);
00342 }

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

encode text to BASE64 coding

Definition at line 288 of file utils.c.

Referenced by ast_base64encode().

00289 {
00290    int cnt = 0;
00291    int col = 0;
00292    unsigned int byte = 0;
00293    int bits = 0;
00294    int cntin = 0;
00295    /* Reserve space for null byte at end of string */
00296    max--;
00297    while ((cntin < srclen) && (cnt < max)) {
00298       byte <<= 8;
00299       byte |= *(src++);
00300       bits += 8;
00301       cntin++;
00302       if ((bits == 24) && (cnt + 4 <= max)) {
00303          *dst++ = base64[(byte >> 18) & 0x3f];
00304          *dst++ = base64[(byte >> 12) & 0x3f];
00305          *dst++ = base64[(byte >> 6) & 0x3f];
00306          *dst++ = base64[byte & 0x3f];
00307          cnt += 4;
00308          col += 4;
00309          bits = 0;
00310          byte = 0;
00311       }
00312       if (linebreaks && (cnt < max) && (col == 64)) {
00313          *dst++ = '\n';
00314          cnt++;
00315          col = 0;
00316       }
00317    }
00318    if (bits && (cnt + 4 <= max)) {
00319       /* Add one last character for the remaining bits, 
00320          padding the rest with 0 */
00321       byte <<= 24 - bits;
00322       *dst++ = base64[(byte >> 18) & 0x3f];
00323       *dst++ = base64[(byte >> 12) & 0x3f];
00324       if (bits == 16)
00325          *dst++ = base64[(byte >> 6) & 0x3f];
00326       else
00327          *dst++ = '=';
00328       *dst++ = '=';
00329       cnt += 4;
00330    }
00331    if (linebreaks && (cnt < max)) {
00332       *dst++ = '\n';
00333       cnt++;
00334    }
00335    *dst = '\0';
00336    return cnt;
00337 }

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

Write data to a file stream with a timeout.

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

Definition at line 1045 of file utils.c.

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

Referenced by send_string().

01046 {
01047    struct timeval start = ast_tvnow();
01048    int n = 0;
01049    int elapsed = 0;
01050 
01051    while (len) {
01052       if (ast_wait_for_output(fd, timeoutms - elapsed)) {
01053          /* poll returned a fatal error, so bail out immediately. */
01054          return -1;
01055       }
01056 
01057       /* Clear any errors from a previous write */
01058       clearerr(f);
01059 
01060       n = fwrite(src, 1, len, f);
01061 
01062       if (ferror(f) && errno != EINTR && errno != EAGAIN) {
01063          /* fatal error from fwrite() */
01064          if (!feof(f)) {
01065             /* Don't spam the logs if it was just that the connection is closed. */
01066             ast_log(LOG_ERROR, "fwrite() returned error: %s\n", strerror(errno));
01067          }
01068          n = -1;
01069          break;
01070       }
01071 
01072       /* Update for data already written to the socket */
01073       len -= n;
01074       src += n;
01075 
01076       elapsed = ast_tvdiff_ms(ast_tvnow(), start);
01077       if (elapsed >= timeoutms) {
01078          /* We've taken too long to write 
01079           * This is only an error condition if we haven't finished writing. */
01080          n = len ? -1 : 0;
01081          break;
01082       }
01083    }
01084 
01085    while (fflush(f)) {
01086       if (errno == EAGAIN || errno == EINTR) {
01087          continue;
01088       }
01089       if (!feof(f)) {
01090          /* Don't spam the logs if it was just that the connection is closed. */
01091          ast_log(LOG_ERROR, "fflush() returned error: %s\n", strerror(errno));
01092       }
01093       n = -1;
01094       break;
01095    }
01096 
01097    return n < 0 ? -1 : 0;
01098 }

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.

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 1004 of file utils.c.

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

Referenced by ast_agi_send(), and ast_cli().

01005 {
01006    struct timeval start = ast_tvnow();
01007    int res = 0;
01008    int elapsed = 0;
01009 
01010    while (len) {
01011       if (ast_wait_for_output(fd, timeoutms - elapsed)) {
01012          return -1;
01013       }
01014 
01015       res = write(fd, s, len);
01016 
01017       if (res < 0 && errno != EAGAIN && errno != EINTR) {
01018          /* fatal error from write() */
01019          ast_log(LOG_ERROR, "write() returned error: %s\n", strerror(errno));
01020          return -1;
01021       }
01022 
01023       if (res < 0) {
01024          /* It was an acceptable error */
01025          res = 0;
01026       }
01027 
01028       /* Update how much data we have left to write */
01029       len -= res;
01030       s += res;
01031       res = 0;
01032 
01033       elapsed = ast_tvdiff_ms(ast_tvnow(), start);
01034       if (elapsed >= timeoutms) {
01035          /* We've taken too long to write 
01036           * This is only an error condition if we haven't finished writing. */
01037          res = len ? -1 : 0;
01038          break;
01039       }
01040    }
01041 
01042    return res;
01043 }

void ast_enable_packet_fragmentation ( int  sock  ) 

Disable PMTU discovery on a socket.

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

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

Definition at line 1698 of file utils.c.

References ast_log(), and LOG_WARNING.

Referenced by ast_netsock_bindaddr().

01699 {
01700 #if defined(HAVE_IP_MTU_DISCOVER)
01701    int val = IP_PMTUDISC_DONT;
01702    
01703    if (setsockopt(sock, IPPROTO_IP, IP_MTU_DISCOVER, &val, sizeof(val)))
01704       ast_log(LOG_WARNING, "Unable to disable PMTU discovery. Large UDP packets may fail to be delivered when sent from this socket.\n");
01705 #endif /* HAVE_IP_MTU_DISCOVER */
01706 }

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

Thread-safe gethostbyname function to use in Asterisk.

Definition at line 179 of file utils.c.

References hp, and s.

Referenced by __ast_http_load(), __init_manager(), __set_address_from_contact(), ast_dnsmgr_lookup(), ast_find_ourip(), ast_get_ip_or_srv(), ast_parse_arg(), check_via(), create_addr(), dnsmgr_refresh(), festival_exec(), get_ip_and_port_from_sdp(), gtalk_load_config(), gtalk_update_stun(), handle_cli_udptl_debug_deprecated(), handle_cli_udptl_set_debug(), iax_template_parse(), jingle_load_config(), jingle_update_stun(), launch_netscript(), parse_register_contact(), process_sdp(), realtime_peer(), realtime_user(), reload_config(), rtcp_do_debug_ip(), rtp_do_debug_ip(), set_config(), set_destination(), and sip_do_debug_ip().

00180 {
00181    int res;
00182    int herrno;
00183    int dots = 0;
00184    const char *s;
00185    struct hostent *result = NULL;
00186    /* Although it is perfectly legitimate to lookup a pure integer, for
00187       the sake of the sanity of people who like to name their peers as
00188       integers, we break with tradition and refuse to look up a
00189       pure integer */
00190    s = host;
00191    res = 0;
00192    while (s && *s) {
00193       if (*s == '.')
00194          dots++;
00195       else if (!isdigit(*s))
00196          break;
00197       s++;
00198    }
00199    if (!s || !*s) {
00200       /* Forge a reply for IP's to avoid octal IP's being interpreted as octal */
00201       if (dots != 3)
00202          return NULL;
00203       memset(hp, 0, sizeof(struct ast_hostent));
00204       hp->hp.h_addrtype = AF_INET;
00205       hp->hp.h_addr_list = (void *) hp->buf;
00206       hp->hp.h_addr = hp->buf + sizeof(void *);
00207       if (inet_pton(AF_INET, host, hp->hp.h_addr) > 0)
00208          return &hp->hp;
00209       return NULL;
00210       
00211    }
00212 #ifdef HAVE_GETHOSTBYNAME_R_5
00213    result = gethostbyname_r(host, &hp->hp, hp->buf, sizeof(hp->buf), &herrno);
00214 
00215    if (!result || !hp->hp.h_addr_list || !hp->hp.h_addr_list[0])
00216       return NULL;
00217 #else
00218    res = gethostbyname_r(host, &hp->hp, hp->buf, sizeof(hp->buf), &result, &herrno);
00219 
00220    if (res || !result || !hp->hp.h_addr_list || !hp->hp.h_addr_list[0])
00221       return NULL;
00222 #endif
00223    return &hp->hp;
00224 }

void ast_md5_hash ( char *  output,
char *  input 
)

Produces MD5 hash based on input string.

Definition at line 227 of file utils.c.

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

Referenced by build_reply_digest(), check_auth(), and md5().

00228 {
00229    struct MD5Context md5;
00230    unsigned char digest[16];
00231    char *ptr;
00232    int x;
00233 
00234    MD5Init(&md5);
00235    MD5Update(&md5, (unsigned char *)input, strlen(input));
00236    MD5Final(digest, &md5);
00237    ptr = output;
00238    for (x = 0; x < 16; x++)
00239       ptr += sprintf(ptr, "%2.2x", digest[x]);
00240 }

int ast_mkdir ( const char *  path,
int  mode 
)

Recursively create directory path.

Parameters:
path The directory path to create
mode The permissions with which to try to create the directory
Returns:
0 on success or an error code otherwise
Creates a directory path, creating parent directories as needed.

Definition at line 1708 of file utils.c.

References ast_strdupa, errno, and len().

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

01709 {
01710    char *ptr;
01711    int len = strlen(path), count = 0, x, piececount = 0;
01712    char *tmp = ast_strdupa(path);
01713    char **pieces;
01714    char *fullpath = alloca(len + 1);
01715    int res = 0;
01716 
01717    for (ptr = tmp; *ptr; ptr++) {
01718       if (*ptr == '/')
01719          count++;
01720    }
01721 
01722    /* Count the components to the directory path */
01723    pieces = alloca(count * sizeof(*pieces));
01724    for (ptr = tmp; *ptr; ptr++) {
01725       if (*ptr == '/') {
01726          *ptr = '\0';
01727          pieces[piececount++] = ptr + 1;
01728       }
01729    }
01730 
01731    *fullpath = '\0';
01732    for (x = 0; x < piececount; x++) {
01733       /* This looks funky, but the buffer is always ideally-sized, so it's fine. */
01734       strcat(fullpath, "/");
01735       strcat(fullpath, pieces[x]);
01736       res = mkdir(fullpath, mode);
01737       if (res && errno != EEXIST)
01738          return errno;
01739    }
01740    return 0;
01741 }

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

Process a string to find and replace characters.

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

Definition at line 1316 of file utils.c.

01317 {
01318    char *dataPut = start;
01319    int inEscape = 0;
01320    int inQuotes = 0;
01321 
01322    for (; *start; start++) {
01323       if (inEscape) {
01324          *dataPut++ = *start;       /* Always goes verbatim */
01325          inEscape = 0;
01326       } else {
01327          if (*start == '\\') {
01328             inEscape = 1;      /* Do not copy \ into the data */
01329          } else if (*start == '\'') {
01330             inQuotes = 1 - inQuotes;   /* Do not copy ' into the data */
01331          } else {
01332             /* Replace , with |, unless in quotes */
01333             *dataPut++ = inQuotes ? *start : ((*start == find) ? replace_with : *start);
01334          }
01335       }
01336    }
01337    if (start != dataPut)
01338       *dataPut = 0;
01339    return dataPut;
01340 }

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 919 of file utils.c.

References ast_log(), ast_pthread_create_stack(), errno, and LOG_WARNING.

00922 {
00923    unsigned char attr_destroy = 0;
00924    int res;
00925 
00926    if (!attr) {
00927       attr = alloca(sizeof(*attr));
00928       pthread_attr_init(attr);
00929       attr_destroy = 1;
00930    }
00931 
00932    if ((errno = pthread_attr_setdetachstate(attr, PTHREAD_CREATE_DETACHED)))
00933       ast_log(LOG_WARNING, "pthread_attr_setdetachstate: %s\n", strerror(errno));
00934 
00935    res = ast_pthread_create_stack(thread, attr, start_routine, data, 
00936                                   stacksize, file, caller, line, start_fn);
00937 
00938    if (attr_destroy)
00939       pthread_attr_destroy(attr);
00940 
00941    return res;
00942 }

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 870 of file utils.c.

References asprintf, ast_log(), ast_malloc, AST_STACKSIZE, dummy_start(), errno, LOG_WARNING, and pthread_create.

Referenced by ast_pthread_create_detached_stack().

00873 {
00874 #if !defined(LOW_MEMORY)
00875    struct thr_arg *a;
00876 #endif
00877 
00878    if (!attr) {
00879       attr = alloca(sizeof(*attr));
00880       pthread_attr_init(attr);
00881    }
00882 
00883 #ifdef __linux__
00884    /* On Linux, pthread_attr_init() defaults to PTHREAD_EXPLICIT_SCHED,
00885       which is kind of useless. Change this here to
00886       PTHREAD_INHERIT_SCHED; that way the -p option to set realtime
00887       priority will propagate down to new threads by default.
00888       This does mean that callers cannot set a different priority using
00889       PTHREAD_EXPLICIT_SCHED in the attr argument; instead they must set
00890       the priority afterwards with pthread_setschedparam(). */
00891    if ((errno = pthread_attr_setinheritsched(attr, PTHREAD_INHERIT_SCHED)))
00892       ast_log(LOG_WARNING, "pthread_attr_setinheritsched: %s\n", strerror(errno));
00893 #endif
00894 
00895    if (!stacksize)
00896       stacksize = AST_STACKSIZE;
00897 
00898    if ((errno = pthread_attr_setstacksize(attr, stacksize ? stacksize : AST_STACKSIZE)))
00899       ast_log(LOG_WARNING, "pthread_attr_setstacksize: %s\n", strerror(errno));
00900 
00901 #if !defined(LOW_MEMORY)
00902    if ((a = ast_malloc(sizeof(*a)))) {
00903       a->start_routine = start_routine;
00904       a->data = data;
00905       start_routine = dummy_start;
00906       if (asprintf(&a->name, "%-20s started at [%5d] %s %s()",
00907               start_fn, line, file, caller) < 0) {
00908          ast_log(LOG_WARNING, "asprintf() failed: %s\n", strerror(errno));
00909          a->name = NULL;
00910       }
00911       data = a;
00912    }
00913 #endif /* !LOW_MEMORY */
00914 
00915    return pthread_create(thread, attr, start_routine, data); /* We're in ast_pthread_create, so it's okay */
00916 }

long int ast_random ( void   ) 

Definition at line 1292 of file utils.c.

References ast_mutex_lock(), ast_mutex_unlock(), and randomlock.

Referenced by __find_callno(), acf_rand_exec(), action_challenge(), add_sdp(), agent_new(), agi_handle_command(), ast_lock_path_lockfile(), ast_moh_files_next(), ast_rtp_new_init(), ast_rtp_new_with_bindaddr(), ast_udptl_new_with_bindaddr(), authenticate_request(), build_gateway(), build_iv(), build_rand_pad(), build_reply_digest(), calc_metric(), calc_rxstamp(), check_auth(), dahdi_new(), generate_random_string(), get_trans_id(), gtalk_alloc(), gtalk_create_candidates(), gtalk_new(), handle_response_invite(), iax2_start_transfer(), jingle_alloc(), jingle_create_candidates(), jingle_new(), local_new(), make_email_file(), make_our_tag(), moh_files_alloc(), ogg_vorbis_rewrite(), osp_create_uuid(), page_exec(), process_weights(), reg_source_db(), registry_authrequest(), reqprep(), sendmail(), sip_alloc(), socket_read(), start_rtp(), stun_req_id(), transmit_fake_auth_response(), transmit_invite(), transmit_register(), transmit_response_using_temp(), and try_firmware().

01293 {
01294    long int res;
01295 #ifdef HAVE_DEV_URANDOM
01296    if (dev_urandom_fd >= 0) {
01297       int read_res = read(dev_urandom_fd, &res, sizeof(res));
01298       if (read_res > 0) {
01299          long int rm = RAND_MAX;
01300          res = res < 0 ? ~res : res;
01301          rm++;
01302          return res % rm;
01303       }
01304    }
01305 #endif
01306 #ifdef linux
01307    res = random();
01308 #else
01309    ast_mutex_lock(&randomlock);
01310    res = random();
01311    ast_mutex_unlock(&randomlock);
01312 #endif
01313    return res;
01314 }

void ast_register_thread ( char *  name  ) 

Definition at line 349 of file asterisk.c.

References ast_calloc, AST_RWLIST_INSERT_HEAD, AST_RWLIST_UNLOCK, AST_RWLIST_WRLOCK, and ast_atexit::list.

Referenced by dummy_start().

00350 { 
00351    struct thread_list_t *new = ast_calloc(1, sizeof(*new));
00352 
00353    if (!new)
00354       return;
00355    new->id = pthread_self();
00356    new->name = name; /* steal the allocated memory for the thread name */
00357    AST_RWLIST_WRLOCK(&thread_list);
00358    AST_RWLIST_INSERT_HEAD(&thread_list, new, list);
00359    AST_RWLIST_UNLOCK(&thread_list);
00360 }

void ast_sha1_hash ( char *  output,
char *  input 
)

Produces SHA1 hash based on input string.

Definition at line 243 of file utils.c.

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

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

00244 {
00245    struct SHA1Context sha;
00246    char *ptr;
00247    int x;
00248    uint8_t Message_Digest[20];
00249 
00250    SHA1Reset(&sha);
00251    
00252    SHA1Input(&sha, (const unsigned char *) input, strlen(input));
00253 
00254    SHA1Result(&sha, Message_Digest);
00255    ptr = output;
00256    for (x = 0; x < 20; x++)
00257       ptr += sprintf(ptr, "%2.2x", Message_Digest[x]);
00258 }

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

Definition at line 266 of file utils.h.

Referenced by ast_frame_slinear_sum(), and audio_audiohook_write_list().

00267 {
00268    int res;
00269 
00270    res = (int) *input + *value;
00271    if (res > 32767)
00272       *input = 32767;
00273    else if (res < -32767)
00274       *input = -32767;
00275    else
00276       *input = (short) res;
00277 }

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

Definition at line 305 of file utils.h.

Referenced by ast_frame_adjust_volume(), and audiohook_read_frame_both().

00306 {
00307    *input /= *value;
00308 }

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

Definition at line 292 of file utils.h.

Referenced by ast_frame_adjust_volume(), and audiohook_read_frame_both().

00293 {
00294    int res;
00295 
00296    res = (int) *input * *value;
00297    if (res > 32767)
00298       *input = 32767;
00299    else if (res < -32767)
00300       *input = -32767;
00301    else
00302       *input = (short) res;
00303 }

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

Definition at line 279 of file utils.h.

00280 {
00281    int res;
00282 
00283    res = (int) *input - *value;
00284    if (res > 32767)
00285       *input = 32767;
00286    else if (res < -32767)
00287       *input = -32767;
00288    else
00289       *input = (short) res;
00290 }

void ast_unregister_thread ( void *  id  ) 

Definition at line 362 of file asterisk.c.

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

Referenced by dummy_start().

00363 {
00364    struct thread_list_t *x;
00365 
00366    AST_RWLIST_WRLOCK(&thread_list);
00367    AST_RWLIST_TRAVERSE_SAFE_BEGIN(&thread_list, x, list) {
00368       if ((void *) x->id == id) {
00369          AST_RWLIST_REMOVE_CURRENT(list);
00370          break;
00371       }
00372    }
00373    AST_RWLIST_TRAVERSE_SAFE_END;
00374    AST_RWLIST_UNLOCK(&thread_list);
00375    if (x) {
00376       ast_free(x->name);
00377       ast_free(x);
00378    }
00379 }

void ast_uri_decode ( char *  s  ) 

Decode URI, URN, URL (overwrite string).

Parameters:
s String to be decoded

Definition at line 411 of file utils.c.

Referenced by check_user_full(), config_curl(), get_also_info(), get_destination(), get_refer_info(), handle_request_invite(), http_decode(), realtime_curl(), realtime_multi_curl(), register_verify(), sip_new(), and uridecode().

00412 {
00413    char *o;
00414    unsigned int tmp;
00415 
00416    for (o = s; *s; s++, o++) {
00417       if (*s == '%' && strlen(s) > 2 && sscanf(s + 1, "%2x", &tmp) == 1) {
00418          /* have '%', two chars and correct parsing */
00419          *o = tmp;
00420          s += 2;  /* Will be incremented once more when we break out */
00421       } else /* all other cases, just copy */
00422          *o = *s;
00423    }
00424    *o = '\0';
00425 }

char* ast_uri_encode ( const char *  string,
char *  outbuf,
int  buflen,
int  doreserved 
)

Turn text string to URI-encoded XX version.

Note:
At this point, we're converting from ISO-8859-x (8-bit), not UTF8 as in the SIP protocol spec If doreserved == 1 we will convert reserved characters also. RFC 2396, section 2.4 outbuf needs to have more memory allocated than the instring to have room for the expansion. Every char that is converted is replaced by three ASCII characters.
Note: The doreserved option is needed for replaces header in SIP transfers.

Definition at line 380 of file utils.c.

References ast_copy_string().

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

00381 {
00382    char *reserved = ";/?:@&=+$,# "; /* Reserved chars */
00383 
00384    const char *ptr  = string; /* Start with the string */
00385    char *out = NULL;
00386    char *buf = NULL;
00387 
00388    ast_copy_string(outbuf, string, buflen);
00389 
00390    /* If there's no characters to convert, just go through and don't do anything */
00391    while (*ptr) {
00392       if ((*ptr < 32 || (unsigned char) *ptr) > 127 || (doreserved && strchr(reserved, *ptr)) ) {
00393          /* Oops, we need to start working here */
00394          if (!buf) {
00395             buf = outbuf;
00396             out = buf + (ptr - string) ;  /* Set output ptr */
00397          }
00398          out += sprintf(out, "%%%02x", (unsigned char) *ptr);
00399       } else if (buf) {
00400          *out = *ptr;   /* Continue copying the string */
00401          out++;
00402       } 
00403       ptr++;
00404    }
00405    if (buf)
00406       *out = '\0';
00407    return outbuf;
00408 }

int ast_utils_init ( void   ) 

Definition at line 1743 of file utils.c.

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

Referenced by main().

01744 {
01745 #ifdef HAVE_DEV_URANDOM
01746    dev_urandom_fd = open("/dev/urandom", O_RDONLY);
01747 #endif
01748    base64_init();
01749 #ifdef DEBUG_THREADS
01750 #if !defined(LOW_MEMORY)
01751    ast_cli_register_multiple(utils_cli, ARRAY_LEN(utils_cli));
01752 #endif
01753 #endif
01754    return 0;
01755 }

int ast_wait_for_input ( int  fd,
int  ms 
)

Definition at line 944 of file utils.c.

References ast_poll.

Referenced by _sip_tcp_helper_thread(), action_waitevent(), ast_tcptls_server_root(), get_input(), main(), and moh_class_destructor().

00945 {
00946    struct pollfd pfd[1];
00947    memset(pfd, 0, sizeof(pfd));
00948    pfd[0].fd = fd;
00949    pfd[0].events = POLLIN|POLLPRI;
00950    return ast_poll(pfd, 1, ms);
00951 }


Variable Documentation

unsigned int __unsigned_int_flags_dummy

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

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

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

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

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

uint64_t __unsigned_int_flags_dummy64


Generated on Thu Jul 9 13:41:35 2009 for Asterisk - the Open Source PBX by  doxygen 1.4.7