Sat Aug 6 00:40:06 2011

Asterisk developer's documentation


utils.h File Reference

Utility functions. More...

#include "asterisk/compat.h"
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <limits.h>
#include <time.h>
#include <unistd.h>
#include "asterisk/lock.h"
#include "asterisk/strings.h"
#include "asterisk/logger.h"
#include "asterisk/compiler.h"
#include "asterisk/localtime.h"

Go to the source code of this file.

Data Structures

struct  ast_flags
struct  ast_hostent

Defines

#define ARRAY_LEN(a)   (sizeof(a) / sizeof(a[0]))
#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_flag_nonstd(p, flag)
#define ast_copy_flags(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_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_flag_nonstd(p, value, flag)
#define ast_set_flag(p, flag)
#define ast_set_flag_nonstd(p, flag)
#define ast_set_flags_to(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_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 inet_ntoa   __dont__use__inet_ntoa__use__ast_inet_ntoa__instead__
#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 * _ast_calloc (size_t num, size_t len, const char *file, int lineno, const char *func)
void * _ast_malloc (size_t len, const char *file, int lineno, const char *func)
void * _ast_realloc (void *p, size_t len, const char *file, int lineno, const char *func)
char * _ast_strdup (const char *str, const char *file, int lineno, const char *func)
char * _ast_strndup (const char *str, size_t len, const char *file, int lineno, const char *func)
int _ast_vasprintf (char **ret, const char *file, int lineno, const char *func, const char *fmt, va_list ap)
int ast_base64decode (unsigned char *dst, const char *src, int max)
 decode BASE64 encoded text
int ast_base64encode (char *dst, const unsigned char *src, int srclen, int max)
int ast_base64encode_full (char *dst, const unsigned char *src, int srclen, int max, int linebreaks)
 encode text to BASE64 coding
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)
 Re-entrant (thread safe) version of gethostbyname that replaces the standard gethostbyname (which is not thread safe).
const char * ast_inet_ntoa (struct in_addr ia)
 thread-safe replacement for inet_ntoa().
void ast_md5_hash (char *output, char *input)
 Produce 32 char MD5 hash of value.
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_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)
 Produce 40 char SHA1 hash of value.
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)
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 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.
int ast_utils_init (void)
char * ast_utils_which (const char *binary, char *fullpath, size_t fullpath_size)
 Resolve a binary to a full pathname.
int ast_wait_for_input (int fd, int ms)
static force_inline int inaddrcmp (const struct sockaddr_in *sin1, const struct sockaddr_in *sin2)

Variables

unsigned int __unsigned_int_flags_dummy


Detailed Description

Utility functions.

Definition in file utils.h.


Define Documentation

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

Definition at line 537 of file utils.h.

Referenced by __unload_module(), action_events(), ast_cli_netstats(), ast_codec_pref_prepend(), ast_test_init(), astobj2_init(), bearer2str(), cache_get_callno_locked(), cb_events(), check_blacklist(), complete_dpreply(), fac2str(), find_cache(), iax2_show_channels(), iax_frame_subclass2str(), lintog722_sample(), load_module(), parkandannounce_exec(), parse_naptr(), show_license(), show_warranty(), ss_thread(), udptl_rx_packet(), 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 473 of file utils.h.

#define ast_assert (  ) 

Definition at line 563 of file utils.h.

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

#define AST_BACKGROUND_STACKSIZE   AST_STACKSIZE

Definition at line 270 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 356 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 381 of file utils.h.

#define ast_clear_flag ( p,
flag   ) 

Definition at line 84 of file utils.h.

Referenced by __ast_read(), __do_deliver(), aji_filter_roster(), aji_pruneregister(), 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_hangup(), ast_jb_destroy(), ast_jb_put(), ast_rtp_stop(), ast_sendtext(), ast_speech_start(), ast_waitfor_nandfds(), ast_waitfordigit_full(), ast_write(), authenticate_verify(), bridge_p2p_loop(), build_peer(), build_user(), builtin_atxfer(), change_hold_state(), chanspy_exec(), check_goto_on_transfer(), check_pendings(), common_exec(), create_addr(), dahdi_read(), dictate_exec(), do_parking_thread(), dundi_lookup_local(), extenspy_exec(), find_conf_realtime(), forward_message(), handle_common_options(), handle_exec(), handle_request_bye(), handle_request_invite(), handle_request_refer(), handle_response(), iax2_destroy_helper(), init_acf_query(), linear_alloc(), local_ast_moh_stop(), local_attended_transfer(), local_hangup(), main(), park_call_full(), phone_read(), playtones_alloc(), process_sdp(), register_verify(), reset_transaction(), set_config(), set_config_destroy(), set_config_flags(), sip_dtmfmode(), sip_hangup(), sip_no_debug(), sip_no_debug_deprecated(), socket_process(), speech_background(), ss_thread(), update_call_counter(), wait_for_answer(), and waitstream_core().

#define ast_clear_flag_nonstd ( p,
flag   ) 

Value:

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

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

Referenced by __find_callno(), add_features_datastores(), agent_read(), aji_create_client(), aji_filter_roster(), ast_cdr_reset(), ast_cdr_specialized_reset(), ast_frdup(), ast_frisolate(), build_peer(), build_user(), builtin_atxfer(), cache_lookup_internal(), check_access(), check_user_full(), create_addr(), create_addr_from_peer(), dundi_lookup_local(), feature_interpret(), framein(), iax2_request(), park_exec(), populate_defaults(), register_verify(), set_peer_defaults(), sip_alloc(), sip_poke_peer(), transmit_response_using_temp(), vm_exec(), 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 133 of file utils.h.

#define AST_FLAGS_ALL   UINT_MAX

Definition at line 145 of file utils.h.

Referenced by add_features_datastores(), aji_create_client(), ast_app_parse_options(), ast_cdr_reset(), ast_cdr_specialized_reset(), builtin_atxfer(), cache_lookup_internal(), chanspy_exec(), check_goto_on_transfer(), dundi_lookup_local(), extenspy_exec(), feature_interpret(), 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 317 of file utils.h.

#define ast_free_ptr   ast_free

Definition at line 318 of file utils.h.

Referenced by add_extensions(), do_parking_thread(), handle_context_add_extension(), handle_context_add_extension_deprecated(), park_call_full(), pbx_load_config(), pbx_load_users(), 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 333 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 280 of file utils.h.

Referenced by accept_thread(), action_originate(), ast_bridge_call_thread_launch(), ast_dial_run(), ast_pbx_outgoing_app(), ast_pbx_outgoing_exten(), ast_pbx_start(), dahdi_handle_event(), dundi_answer_entity(), dundi_answer_query(), find_idle_thread(), function_autopatchup(), handle_enbloc_call_message(), handle_hd_hf(), handle_init_event(), handle_offhook_message(), handle_soft_key_event_message(), handle_stimulus_message(), launch_service(), load_module(), local_dtmf_helper(), main(), rpt_master(), rpt_telemetry(), setup_dahdi(), show_console(), sla_load_config(), spawn_dp_lookup(), and start_network_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 285 of file utils.h.

Referenced by accept_thread(), aji_reload(), ast_autoservice_start(), ast_cdr_submit_batch(), ast_device_state_engine_init(), ast_makesocket(), conf_run(), do_reload(), http_root(), http_server_start(), iax_park(), init_app_class(), launch_monitor_thread(), listener(), load_module(), pri_dchannel(), reload_config(), restart_monitor(), sip_park(), sla_handle_dial_state_event(), sla_station_exec(), and start_network_thread().

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

#define ast_set2_flag ( p,
value,
flag   ) 

Definition at line 101 of file utils.h.

Referenced by _macro_exec(), aji_create_client(), aji_load_config(), apply_option(), apply_outgoing(), ast_bridge_call(), ast_jb_read_conf(), ast_plc_reload(), ast_rtp_setdtmf(), ast_rtp_setdtmfcompensate(), ast_rtp_setstun(), ast_translate(), build_peer(), build_user(), check_access(), do_reload(), find_user(), handle_common_options(), load_config(), load_module(), pbx_load_config(), set_config(), and sip_alloc().

#define ast_set2_flag_nonstd ( p,
value,
flag   ) 

Definition at line 138 of file utils.h.

#define ast_set_flag ( p,
flag   ) 

Definition at line 77 of file utils.h.

Referenced by __ast_pbx_run(), __ast_read(), __ast_request_and_dial(), __sip_autodestruct(), __sip_reliable_xmit(), _macro_exec(), action_redirect(), 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_generic_bridge(), ast_hangup(), ast_jb_do_usecheck(), ast_jb_put(), ast_rtp_bridge(), ast_rtp_new_init(), ast_rtp_raw_write(), ast_rtp_read(), ast_speech_change_state(), ast_waitfor_nandfds(), ast_waitfordigit_full(), asyncgoto_exec(), authenticate_reply(), authenticate_request(), bridge_p2p_rtp_write(), build_peer(), build_user(), builtin_atxfer(), builtin_blindtransfer(), change_hold_state(), chanspy_exec(), check_access(), check_availability(), check_bridge(), check_user_full(), check_via(), common_exec(), conf_exec(), connect_link(), create_addr_from_peer(), create_transaction(), decrypt_frame(), dictate_exec(), do_parking_thread(), do_register(), dundi_encrypt(), dundi_lookup_local(), dundi_send(), extenspy_exec(), find_call(), find_user_realtime(), free_vm_users(), handle_common_options(), handle_exec(), handle_invite_replaces(), handle_request(), handle_request_invite(), handle_request_refer(), handle_request_subscribe(), handle_response(), handle_response_invite(), handle_response_peerpoke(), handle_response_refer(), handle_response_register(), iax2_predestroy(), iax2_provision(), iax2_prune_realtime(), init_acf_query(), init_app_class(), init_files_class(), init_outgoing(), launch_monitor_thread(), leave_voicemail(), linear_alloc(), local_alloc(), local_ast_moh_start(), local_attended_transfer(), local_call(), main(), nocdr_exec(), notify_extenstate_update(), park_call_full(), park_exec(), peer_delme_cb(), playtones_alloc(), post_cdr(), process_rfc3389(), process_sdp(), pvt_destructor(), qualify_peer(), register_verify(), retrans_pkt(), rpt(), rpt_call(), rpt_tele_thread(), run_station(), set_bridge_features_on_config(), set_config(), set_config_flags(), set_insecure_flags(), sip_alreadygone(), sip_answer(), sip_call(), sip_do_debug(), sip_do_debug_deprecated(), sip_do_debug_ip(), sip_do_debug_peer(), sip_dtmfmode(), sip_handle_t38_reinvite(), sip_hangup(), sip_indicate(), sip_poke_peer(), sip_read(), sip_reg_timeout(), sip_reinvite_retry(), sip_request_call(), sip_send_mwi_to_peer(), sip_set_rtp_peer(), sip_set_udptl_peer(), sip_write(), sipsock_read(), sla_station_exec(), sla_trunk_exec(), socket_process(), ss_thread(), start_spying(), temp_peer(), tonepair_alloc(), transmit_register(), transmit_reinvite_with_sdp(), transmit_reinvite_with_t38_sdp(), transmit_response_using_temp(), try_calling(), update_call_counter(), user_delme_cb(), vm_exec(), vm_execmain(), and waitstream_core().

#define ast_set_flag_nonstd ( p,
flag   ) 

Value:

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

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

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

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

Definition at line 265 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 419 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 511 of file utils.h.

Referenced by __ast_play_and_record(), __login_exec(), __verboser(), _macro_exec(), _while_exec(), acf_channel_read(), acf_odbc_write(), action_agents(), action_getvar(), action_setvar(), add_agent(), admin_exec(), advanced_options(), aelsub_exec(), agent_logoff_maintenance(), aji_send_exec(), aji_status_exec(), answer_exec_enable(), app_exec(), append_mailbox(), append_mailbox_mapping(), apply_options(), aqm_exec(), array(), ast_aji_get_client(), ast_bridge_call(), ast_callerid_split(), ast_cdr_fork(), ast_device_state(), ast_extension_state2(), ast_filehelper(), ast_format_str_reduce(), ast_get_group(), ast_monitor_start(), ast_netsock_bind(), ast_parse_allow_disallow(), ast_parseable_goto(), ast_playtones_start(), ast_register_file_version(), ast_utils_which(), ast_writefile(), astman_get_variables(), asyncgoto_exec(), auth_exec(), authenticate_reply(), authenticate_verify(), background_detect_exec(), build_channels(), build_mapping(), build_peer(), build_user(), builtin_automonitor(), builtin_blindtransfer(), builtin_parkcall(), cache_get_callno_locked(), chanavail_exec(), channel_spy(), chanspy_exec(), check_access(), check_blacklist(), check_day(), check_dow(), check_goto_on_transfer(), check_month(), check_switch_expr(), check_timerange(), check_user_full(), cli_audio_convert(), cli_audio_convert_deprecated(), complete_meetmecmd(), conf_exec(), conf_run(), controlplayback_exec(), count_exec(), create_addr(), create_addr_from_peer(), cut_internal(), dahdi_request(), decrypt_frame(), del_exec(), deltree_exec(), dial_trunk(), dictate_exec(), directory_exec(), disa_exec(), do_message(), do_say(), exec(), exec_exec(), execif_exec(), extenspy_exec(), feature_check(), feature_interpret(), features_alloc(), festival_exec(), fileexists_core(), find_conf_realtime(), find_gtalk(), find_sdp(), findmeexec(), function_agent(), function_autopatchup(), function_iaxpeer(), get_destination(), get_refer_info(), get_wait_interval(), gosubif_exec(), gtalk_action(), gtalk_alloc(), gtalk_create_candidates(), gtalk_digit(), gtalk_invite(), gtalk_invite_response(), gtalk_request(), handle_mfcr2_set_debug(), handle_request_invite(), handle_request_subscribe(), handle_response(), handle_show_dialplan(), handle_statechange(), hasvoicemail_exec(), iax2_call(), iax2_devicestate(), iax2_prov_app(), iax2_request(), ind_load_module(), isAnsweringMachine(), ivr_dispatch(), launch_monitor_thread(), launch_netscript(), load_config(), local_devicestate(), log_exec(), macroif_exec(), main(), masq_park_call(), meetmemute(), metermaidstate(), mgcp_devicestate(), misdn_call(), misdn_request(), mixmonitor_exec(), notify_new_message(), orig_app(), orig_exten(), ospauth_exec(), ospfinished_exec(), osplookup_exec(), ospnext_exec(), page_exec(), park_call_exec(), parkandannounce_exec(), parse_moved_contact(), parse_register_contact(), 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_saydate(), pbx_builtin_saytime(), pbx_builtin_setvar(), pbx_builtin_setvar_helper(), pbx_builtin_waitexten(), pbx_retrieve_variable(), peer_set_srcaddr(), pickup_exec(), play_message(), playback_exec(), pqm_exec(), prep_email_sub_vars(), privacy_exec(), process_dahdi(), process_sdp(), process_sdp_a_audio(), process_sdp_a_video(), ql_exec(), queue_exec(), queue_function_queuemembercount(), queue_set_param(), random_exec(), read_exec(), readfile_exec(), realtime_common(), realtime_exec(), realtime_multi_odbc(), realtime_multi_pgsql(), realtime_update_exec(), record_exec(), register_verify(), registry_authrequest(), reload_followme(), resource_name_match(), retrydial_exec(), rpt_do_stats(), rpt_tele_thread(), rqm_exec(), sayunixtime_exec(), send_tone_telemetry(), senddtmf_exec(), sendimage_exec(), sendmail(), sendtext_exec(), sendurl_exec(), set_config_flags(), setcallerid_exec(), settransfercapability_exec(), sip_devicestate(), sip_new(), sip_sipredirect(), sip_uri_cmp(), sip_uri_headers_cmp(), sip_uri_params_cmp(), sla_add_trunk_to_station(), sla_check_device(), sla_queue_event_conf(), sla_ring_station(), sla_state(), sla_station_exec(), smdi_msg_read(), smdi_msg_retrieve_read(), socket_process(), softhangup_exec(), sort_internal(), speech_background(), speech_load(), start_monitor_action(), start_monitor_exec(), telem_lookup(), transfer_exec(), transmit_invite(), transmit_refer(), tryexec_exec(), update_bridgepeer(), update_registry(), upqm_exec(), userevent_exec(), verbose_exec(), vm_box_exists(), vm_exec(), vm_execmain(), vmauthenticate(), wait_for_winner(), and waitstream_core().

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

#define ast_test_flag ( p,
flag   ) 

Definition at line 70 of file utils.h.

Referenced by __ast_pbx_run(), __ast_queue_frame(), __ast_read(), __do_deliver(), __expire_registry(), __get_from_jb(), __iax2_show_peers(), __sip_ack(), __sip_autodestruct(), __sip_destroy(), __sip_pretend_ack(), __sip_reliable_xmit(), __sip_semi_ack(), __sip_show_channels(), _macro_exec(), _sip_show_peer(), _sip_show_peers(), acf_odbc_read(), add_codec_to_sdp(), add_sdp(), aji_pruneregister(), app_exec(), append_history_full(), ast_answer(), ast_app_options2str(), 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_free(), 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_channel_free(), ast_cli_netstats(), ast_do_masquerade(), 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_moh_files_next(), ast_pickup_call(), ast_quiet_chan(), 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_native_loop(), bridge_p2p_rtp_write(), build_peer(), build_radius_record(), build_user(), build_via(), builtin_atxfer(), callback_dialoptions(), can_pickup(), cdr_read(), cdr_write(), change_hold_state(), channel_spy(), chanspy_exec(), check_access(), check_auth(), check_bridge(), check_pendings(), check_post(), check_user_full(), common_exec(), complete_sip_peer(), complete_sip_user(), conf_exec(), copy_via_headers(), create_addr(), create_addr_from_peer(), create_dtmf_frame(), create_jb(), decrypt_frame(), destroy_association(), destroy_trans(), dictate_exec(), do_monitor(), do_register_auth(), does_peer_need_mwi(), dtmf_audiohook_write_list(), dundi_encrypt(), dundi_exec(), dundi_helper(), dundi_lookup_local(), dundi_lookup_thread(), dundi_precache_thread(), dundi_query_thread(), dundi_rexmit(), dundi_send(), dundifunc_read(), expire_register(), extenspy_exec(), feature_exec_app(), feature_interpret_helper(), find_cache(), find_call(), find_conf_realtime(), find_or_create(), find_user(), find_user_realtime(), forward_message(), free_user(), function_iaxpeer(), function_sippeer(), get_destination(), get_sip_pvt_byid_locked(), handle_cli_wait_fullybooted(), handle_command_response(), handle_exec(), handle_frame(), handle_request(), handle_request_bye(), handle_request_cancel(), handle_request_info(), handle_request_invite(), handle_request_message(), handle_request_refer(), handle_request_register(), handle_request_subscribe(), handle_response(), handle_response_invite(), handle_response_peerpoke(), handle_show_settings(), handle_showchan(), handle_showchan_deprecated(), iax2_call(), iax2_destroy_helper(), iax2_getpeertrunk(), iax2_hangup(), iax2_predestroy(), iax2_prune_realtime(), iax2_request(), iax2_send(), iax2_show_channels(), iax2_show_peer(), iax2_show_users(), iax2_trunk_queue(), iax2_write(), initialize_initreq(), initreqprep(), inspect_module(), leave_voicemail(), load_dynamic_module(), load_resource(), local_hangup(), local_indicate(), local_write(), main(), make_email_file(), mixmonitor_exec(), mixmonitor_thread(), moh_classes_show(), moh_files_alloc(), notify_extenstate_update(), notify_new_message(), p2p_callback_disable(), page_exec(), parse_moved_contact(), parse_register_contact(), pbx_builtin_background(), pbx_builtin_waitexten(), pick_unlocked_cdr(), play_message(), play_record_review(), post_cdr(), precache_transactions(), process_message(), process_rfc2833(), process_rfc3389(), process_sdp(), process_sdp_a_audio(), prune_peers(), prune_users(), read_exec(), realtime_update_peer(), reg_source_db(), register_verify(), remove_from_queue(), reqprep(), respprep(), retrans_pkt(), retrydial_exec(), rpt_master(), schedule_delivery(), send_request(), send_response(), send_trunk(), sendmail(), serialize_showchan(), set_address_from_contact(), set_config(), set_config_flags(), should_skip_dtmf(), sip_addrcmp(), sip_alloc(), sip_destroy_peer(), sip_destroy_user(), sip_do_reload(), sip_dtmfmode(), sip_fixup(), sip_get_rtp_peer(), sip_get_udptl_peer(), sip_get_vrtp_peer(), sip_handle_t38_reinvite(), sip_hangup(), sip_indicate(), sip_nat_mode(), sip_new(), sip_poke_noanswer(), sip_prune_realtime(), sip_read(), sip_real_dst(), sip_reregister(), sip_rtp_read(), sip_scheddestroy(), sip_senddigit_begin(), sip_senddigit_end(), sip_set_rtp_peer(), sip_set_udptl_peer(), sip_show_channel(), sip_show_settings(), sip_show_users(), sip_write(), sipsock_read(), smdi_msg_find(), socket_process(), spawn_mp3(), speech_background(), speech_read(), start_spying(), startmon(), transmit_fake_auth_response(), transmit_notify_with_mwi(), transmit_refer(), transmit_register(), transmit_reinvite_with_sdp(), transmit_reinvite_with_t38_sdp(), transmit_response_using_temp(), transmit_response_with_sdp(), try_calling(), update_call_counter(), update_peer(), update_registry(), valid_priv_reply(), vm_exec(), vm_execmain(), vm_intro(), vm_newuser(), wait_for_answer(), and waitstream_core().

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

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

#define inet_ntoa   __dont__use__inet_ntoa__use__ast_inet_ntoa__instead__

Definition at line 237 of file utils.h.

#define localtime_r   __dont_use_localtime_r_use_ast_localtime_instead__

Definition at line 242 of file utils.h.

Referenced by rpt_localtime().

#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 323 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 1430 of file utils.c.

References MALLOC_FAILURE_MSG, and vasprintf.

01431 {
01432    int res;
01433    va_list ap;
01434 
01435    va_start(ap, fmt);
01436    if ((res = vasprintf(ret, fmt, ap)) == -1) {
01437       MALLOC_FAILURE_MSG;
01438    }
01439    va_end(ap);
01440 
01441    return res;
01442 }

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

Definition at line 369 of file utils.h.

00397 {

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

Definition at line 346 of file utils.h.

00361 {

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

Definition at line 405 of file utils.h.

00424 {

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

Definition at line 434 of file utils.h.

00453 {

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

Definition at line 463 of file utils.h.

00491 {

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

Definition at line 499 of file utils.h.

00513 {                                                                \

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

decode BASE64 encoded text

Definition at line 267 of file utils.c.

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

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

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

Definition at line 345 of file utils.c.

References ast_base64encode_full().

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

00346 {
00347    return ast_base64encode_full(dst, src, srclen, max, 0);
00348 }

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

encode text to BASE64 coding

Definition at line 294 of file utils.c.

Referenced by ast_base64encode().

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

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.

ast_carefulwrite

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.

Definition at line 922 of file utils.c.

References ast_log(), ast_poll, ast_tvdiff_ms(), ast_tvnow(), errno, LOG_DEBUG, LOG_ERROR, and option_debug.

Referenced by agi_debug_cli(), ast_cli(), astman_append(), and process_events().

00923 {
00924    struct timeval start = ast_tvnow();
00925    int res = 0;
00926    int elapsed = 0;
00927 
00928    while (len) {
00929       struct pollfd pfd = {
00930          .fd = fd,
00931          .events = POLLOUT,
00932       };
00933 
00934       /* poll() until the fd is writable without blocking */
00935       while ((res = ast_poll(&pfd, 1, timeoutms - elapsed)) <= 0) {
00936          if (res == 0) {
00937             /* timed out. */
00938             if (option_debug) {
00939                ast_log(LOG_DEBUG, "Timed out trying to write\n");
00940             }
00941             return -1;
00942          } else if (res == -1) {
00943             /* poll() returned an error, check to see if it was fatal */
00944 
00945             if (errno == EINTR || errno == EAGAIN) {
00946                elapsed = ast_tvdiff_ms(ast_tvnow(), start);
00947                if (elapsed > timeoutms) {
00948                   /* We've taken too long to write 
00949                    * This is only an error condition if we haven't finished writing. */
00950                   res = len ? -1 : 0;
00951                   break;
00952                }
00953                /* This was an acceptable error, go back into poll() */
00954                continue;
00955             }
00956 
00957             /* Fatal error, bail. */
00958             ast_log(LOG_ERROR, "poll returned error: %s\n", strerror(errno));
00959 
00960             return -1;
00961          }
00962       }
00963 
00964       res = write(fd, s, len);
00965 
00966       if (res < 0 && errno != EAGAIN && errno != EINTR) {
00967          /* fatal error from write() */
00968          ast_log(LOG_ERROR, "write() returned error: %s\n", strerror(errno));
00969          return -1;
00970       }
00971 
00972       if (res < 0) {
00973          /* It was an acceptable error */
00974          res = 0;
00975       }
00976 
00977       /* Update how much data we have left to write */
00978       len -= res;
00979       s += res;
00980       res = 0;
00981 
00982       elapsed = ast_tvdiff_ms(ast_tvnow(), start);
00983       if (elapsed > timeoutms) {
00984          /* We've taken too long to write 
00985           * This is only an error condition if we haven't finished writing. */
00986          res = len ? -1 : 0;
00987          break;
00988       }
00989    }
00990 
00991    return res;
00992 }

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

References ast_log(), and LOG_WARNING.

Referenced by ast_netsock_bindaddr().

01409 {
01410 #if defined(HAVE_IP_MTU_DISCOVER)
01411    int val = IP_PMTUDISC_DONT;
01412    
01413    if (setsockopt(sock, IPPROTO_IP, IP_MTU_DISCOVER, &val, sizeof(val)))
01414       ast_log(LOG_WARNING, "Unable to disable PMTU discovery. Large UDP packets may fail to be delivered when sent from this socket.\n");
01415 #endif /* HAVE_IP_MTU_DISCOVER */
01416 }

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

Re-entrant (thread safe) version of gethostbyname that replaces the standard gethostbyname (which is not thread safe).

Definition at line 185 of file utils.c.

References hp, and s.

Referenced by __ast_http_load(), __set_address_from_contact(), ast_dnsmgr_lookup(), ast_find_ourip(), ast_get_ip_or_srv(), ast_sip_ouraddrfor(), check_via(), create_addr(), dnsmgr_refresh(), festival_exec(), get_ip_and_port_from_sdp(), gtalk_load_config(), gtalk_update_stun(), iax_template_parse(), launch_netscript(), parse_register_contact(), process_sdp(), process_sdp_c(), process_via(), realtime_peer(), realtime_user(), reload_config(), rtcp_do_debug_ip(), rtcp_do_debug_ip_deprecated(), rtp_do_debug_ip(), set_config(), set_destination(), sip_devicestate(), sip_do_debug_ip(), and udptl_do_debug_ip().

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

const char* ast_inet_ntoa ( struct in_addr  ia  ) 

thread-safe replacement for inet_ntoa().

Note:
It is very important to note that even though this is a thread-safe replacement for inet_ntoa(), it is *not* reentrant. In a single thread, the result from a previous call to this function is no longer valid once it is called again. If the result from multiple calls to this function need to be kept or used at once, then the result must be copied to a local buffer before calling this function again.

Definition at line 433 of file utils.c.

References ast_threadstorage_get(), and inet_ntoa_buf.

Referenced by __attempt_transmit(), __find_callno(), __iax2_show_peers(), __sip_show_channels(), __sip_xmit(), _sip_show_peer(), _sip_show_peers(), accept_thread(), add_sdp(), ast_apply_ha(), ast_netsock_bindaddr(), ast_rtcp_read(), ast_rtcp_write_rr(), ast_rtcp_write_sr(), ast_rtp_raw_write(), ast_rtp_read(), ast_rtp_sendcng(), ast_rtp_senddigit_begin(), ast_rtp_senddigit_continuation(), ast_rtp_senddigit_end_with_duration(), ast_sip_ouraddrfor(), ast_udptl_bridge(), ast_udptl_read(), ast_udptl_write(), authenticate(), bridge_native_loop(), bridge_p2p_rtp_write(), build_callid_pvt(), build_callid_registry(), build_contact(), build_peer(), build_reply_digest(), build_rpid(), build_via(), calltoken_required(), check_access(), check_user_full(), check_via(), copy_via_headers(), create_addr_from_peer(), create_dtmf_frame(), dnsmgr_refresh(), do_message(), dump_addr(), dump_ipaddr(), dundi_rexmit(), dundi_show_peer(), dundi_show_peers(), dundi_show_trans(), dundi_showframe(), dundi_xmit(), external_rtp_create(), find_command(), find_peer(), find_subchannel_and_lock(), function_iaxpeer(), function_sipchaninfo_read(), function_sippeer(), gtalk_create_candidates(), gtalk_update_stun(), handle_call_token(), handle_command_response(), handle_error(), handle_open_receive_channel_ack_message(), handle_request(), handle_request_bye(), handle_request_register(), handle_request_subscribe(), handle_response(), handle_response_refer(), handle_show_http(), handle_showmanconn(), http_server_start(), httpstatus_callback(), iax2_ack_registry(), iax2_prov_app(), iax2_show_callnumber_usage(), iax2_show_channels(), iax2_show_peer(), iax2_show_registry(), iax2_trunk_queue(), iax_server(), iax_showframe(), initreqprep(), load_module(), mgcp_show_endpoints(), mgcpsock_read(), oh323_addrcmp_str(), oh323_call(), oh323_set_rtp_peer(), parse_register_contact(), peercnt_add(), peercnt_modify(), peercnt_remove(), process_message(), process_rfc3389(), process_sdp(), raw_hangup(), realtime_peer(), realtime_update_peer(), realtime_user(), reg_source_db(), register_verify(), registry_rerequest(), reload_config(), resend_response(), retrans_pkt(), rtcp_do_debug_ip(), rtcp_do_debug_ip_deprecated(), rtp_do_debug_ip(), sched_delay_remove(), score_address(), send_packet(), send_request(), send_response(), send_trunk(), session_do(), set_config(), set_destination(), set_peercnt_limit(), setup_incoming_call(), sip_do_debug_ip(), sip_do_debug_peer(), sip_handle_t38_reinvite(), sip_poke_peer(), sip_set_rtp_peer(), sip_set_udptl_peer(), sip_show_channel(), sip_show_settings(), sipsock_read(), skinny_session(), skinny_show_devices(), socket_process(), timing_read(), transmit_notify_with_mwi(), udptl_do_debug_ip(), and update_registry().

00434 {
00435    char *buf;
00436 
00437    if (!(buf = ast_threadstorage_get(&inet_ntoa_buf, INET_ADDRSTRLEN)))
00438       return "";
00439 
00440    return inet_ntop(AF_INET, &ia, buf, INET_ADDRSTRLEN);
00441 }

void ast_md5_hash ( char *  output,
char *  input 
)

Produce 32 char MD5 hash of value.

Definition at line 233 of file utils.c.

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

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

00234 {
00235    struct MD5Context md5;
00236    unsigned char digest[16];
00237    char *ptr;
00238    int x;
00239 
00240    MD5Init(&md5);
00241    MD5Update(&md5, (unsigned char *)input, strlen(input));
00242    MD5Final(digest, &md5);
00243    ptr = output;
00244    for (x = 0; x < 16; x++)
00245       ptr += sprintf(ptr, "%2.2x", digest[x]);
00246 }

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

Referenced by handle_context_add_extension(), handle_context_add_extension_deprecated(), and pbx_load_config().

01159 {
01160    char *dataPut = start;
01161    int inEscape = 0;
01162    int inQuotes = 0;
01163 
01164    for (; *start; start++) {
01165       if (inEscape) {
01166          *dataPut++ = *start;       /* Always goes verbatim */
01167          inEscape = 0;
01168       } else {
01169          if (*start == '\\') {
01170             inEscape = 1;      /* Do not copy \ into the data */
01171          } else if (*start == '\'') {
01172             inQuotes = 1 - inQuotes;   /* Do not copy ' into the data */
01173          } else {
01174             /* Replace , with |, unless in quotes */
01175             *dataPut++ = inQuotes ? *start : ((*start == find) ? replace_with : *start);
01176          }
01177       }
01178    }
01179    if (start != dataPut)
01180       *dataPut = 0;
01181    return dataPut;
01182 }

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

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

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

long int ast_random ( void   ) 

Definition at line 1148 of file utils.c.

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

Referenced by acf_rand_exec(), agent_new(), ast_lock_path(), ast_moh_files_next(), ast_rtp_change_source(), 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(), callno_hash(), dahdi_new(), generate_random_string(), get_trans_id(), gtalk_alloc(), gtalk_create_candidates(), gtalk_new(), handle_response_invite(), iax2_start_transfer(), load_module(), local_new(), make_email_file(), make_our_tag(), moh_files_alloc(), ogg_vorbis_rewrite(), page_exec(), process_message(), process_weights(), random_exec(), reg_source_db(), registry_authrequest(), reqprep(), set_nonce_randdata(), sip_alloc(), socket_read(), start_rtp(), stun_req_id(), transmit_invite(), transmit_register(), transmit_response_using_temp(), and try_firmware().

01149 {
01150    long int res;
01151    ast_mutex_lock(&randomlock);
01152    res = random();
01153    ast_mutex_unlock(&randomlock);
01154    return res;
01155 }

void ast_register_thread ( char *  name  ) 

Definition at line 345 of file asterisk.c.

References ast_calloc, AST_LIST_INSERT_HEAD, AST_LIST_LOCK, AST_LIST_UNLOCK, and ast_atexit::list.

Referenced by dummy_start().

00346 { 
00347    struct thread_list_t *new = ast_calloc(1, sizeof(*new));
00348 
00349    if (!new)
00350       return;
00351    new->id = pthread_self();
00352    new->name = name; /* steal the allocated memory for the thread name */
00353    AST_LIST_LOCK(&thread_list);
00354    AST_LIST_INSERT_HEAD(&thread_list, new, list);
00355    AST_LIST_UNLOCK(&thread_list);
00356 }

void ast_sha1_hash ( char *  output,
char *  input 
)

Produce 40 char SHA1 hash of value.

Definition at line 249 of file utils.c.

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

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

00250 {
00251    struct SHA1Context sha;
00252    char *ptr;
00253    int x;
00254    uint8_t Message_Digest[20];
00255 
00256    SHA1Reset(&sha);
00257    
00258    SHA1Input(&sha, (const unsigned char *) input, strlen(input));
00259 
00260    SHA1Result(&sha, Message_Digest);
00261    ptr = output;
00262    for (x = 0; x < 20; x++)
00263       ptr += sprintf(ptr, "%2.2x", Message_Digest[x]);
00264 }

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

Definition at line 191 of file utils.h.

Referenced by ast_frame_slinear_sum(), and audio_audiohook_write_list().

00192 {
00193    int res;
00194 
00195    res = (int) *input + *value;
00196    if (res > 32767)
00197       *input = 32767;
00198    else if (res < -32767)
00199       *input = -32767;
00200    else
00201       *input = (short) res;
00202 }

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

Definition at line 217 of file utils.h.

Referenced by ast_frame_adjust_volume(), and audiohook_read_frame_both().

00218 {
00219    *input /= *value;
00220 }

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

Definition at line 204 of file utils.h.

Referenced by ast_frame_adjust_volume(), and audiohook_read_frame_both().

00205 {
00206    int res;
00207 
00208    res = (int) *input * *value;
00209    if (res > 32767)
00210       *input = 32767;
00211    else if (res < -32767)
00212       *input = -32767;
00213    else
00214       *input = (short) res;
00215 }

void ast_unregister_thread ( void *  id  ) 

Definition at line 358 of file asterisk.c.

References ast_free, AST_LIST_LOCK, AST_LIST_REMOVE_CURRENT, AST_LIST_TRAVERSE_SAFE_BEGIN, AST_LIST_TRAVERSE_SAFE_END, AST_LIST_UNLOCK, thread_list_t::id, ast_atexit::list, and thread_list_t::name.

Referenced by dummy_start().

00359 {
00360    struct thread_list_t *x;
00361 
00362    AST_LIST_LOCK(&thread_list);
00363    AST_LIST_TRAVERSE_SAFE_BEGIN(&thread_list, x, list) {
00364       if ((void *) x->id == id) {
00365          AST_LIST_REMOVE_CURRENT(&thread_list, list);
00366          break;
00367       }
00368    }
00369    AST_LIST_TRAVERSE_SAFE_END;
00370    AST_LIST_UNLOCK(&thread_list);
00371    if (x) {
00372       ast_free(x->name);
00373       ast_free(x);
00374    }
00375 }

void ast_uri_decode ( char *  s  ) 

Decode URI, URN, URL (overwrite string).

Parameters:
s String to be decoded

Definition at line 416 of file utils.c.

Referenced by check_user_full(), get_also_info(), get_destination(), get_refer_info(), handle_request_invite(), handle_uri(), parse_moved_contact(), register_verify(), sip_new(), and uridecode().

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

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

Turn text string to URI-encoded XX version 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:
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 386 of file utils.c.

Referenced by build_contact(), initreqprep(), and uriencode().

00387 {
00388    char *reserved = ";/?:@&=+$,# "; /* Reserved chars */
00389 
00390    const char *ptr  = string; /* Start with the string */
00391    char *out = outbuf;
00392 
00393    /* If there's no characters to convert, just go through and copy the string */
00394    while (*ptr && out - outbuf < buflen - 1) {
00395       if ((*ptr < 32) || (doreserved && strchr(reserved, *ptr))) {
00396          if (out - outbuf >= buflen - 3) {
00397             break;
00398          }
00399 
00400          out += sprintf(out, "%%%02x", (unsigned char) *ptr);
00401       } else {
00402          *out = *ptr;   /* copy the character */
00403          out++;
00404       }
00405       ptr++;
00406    }
00407 
00408    if (buflen) {
00409       *out = '\0';
00410    }
00411 
00412    return outbuf;
00413 }

int ast_utils_init ( void   ) 

Definition at line 1418 of file utils.c.

References ast_cli_register_multiple(), and base64_init().

Referenced by main().

01419 {
01420    base64_init();
01421 #ifdef DEBUG_THREADS
01422 #if !defined(LOW_MEMORY)
01423    ast_cli_register_multiple(utils_cli, sizeof(utils_cli) / sizeof(utils_cli[0]));
01424 #endif
01425 #endif
01426    return 0;
01427 }

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

Resolve a binary to a full pathname.

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

Definition at line 1445 of file utils.c.

References ast_strdupa.

Referenced by ast_backtrace().

01446 {
01447    const char *envPATH = getenv("PATH");
01448    char *tpath, *path;
01449    struct stat unused;
01450    if (!envPATH) {
01451       return NULL;
01452    }
01453    tpath = ast_strdupa(envPATH);
01454    while ((path = strsep(&tpath, ":"))) {
01455       snprintf(fullpath, fullpath_size, "%s/%s", path, binary);
01456       if (!stat(fullpath, &unused)) {
01457          return fullpath;
01458       }
01459    }
01460    return NULL;
01461 }

int ast_wait_for_input ( int  fd,
int  ms 
)

Definition at line 913 of file utils.c.

References ast_poll.

Referenced by action_waitevent(), http_root(), main(), and moh_class_destructor().

00914 {
00915    struct pollfd pfd[1];
00916    memset(pfd, 0, sizeof(pfd));
00917    pfd[0].fd = fd;
00918    pfd[0].events = POLLIN|POLLPRI;
00919    return ast_poll(pfd, 1, ms);
00920 }

static force_inline int inaddrcmp ( const struct sockaddr_in *  sin1,
const struct sockaddr_in *  sin2 
) [static]

Compares the source address and port of two sockaddr_in

Definition at line 259 of file utils.h.

Referenced by ast_netsock_find(), ast_udptl_bridge(), bridge_native_loop(), find_tpeer(), find_transaction(), handle_command_response(), iax2_ack_registry(), oh323_addrcmp(), parse_register_contact(), registry_rerequest(), sip_addrcmp(), socket_process(), socket_read(), and update_registry().

00260 {
00261    return ((sin1->sin_addr.s_addr != sin2->sin_addr.s_addr) 
00262       || (sin1->sin_port != sin2->sin_port));
00263 }


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.
 


Generated on Sat Aug 6 00:40:06 2011 for Asterisk - the Open Source PBX by  doxygen 1.4.7