Wed Apr 6 11:30:11 2011

Asterisk developer's documentation


utils.h File Reference

Utility functions. More...

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

Go to the source code of this file.

Data Structures

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

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);
#define MAX(a, b)   ({ typeof(a) __a = (a); typeof(b) __b = (b); ((__a < __b) ? __b : __a);})
#define MIN(a, b)   ({ typeof(a) __a = (a); typeof(b) __b = (b); ((__a > __b) ? __b : __a);})

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 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.
int ast_eid_cmp (const struct ast_eid *eid1, const struct ast_eid *eid2)
 Compare two EIDs.
char * ast_eid_to_str (char *s, int maxlen, struct ast_eid *eid)
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, const char *input)
 Produces MD5 hash based on input string.
int ast_mkdir (const char *path, int mode)
 Recursively create directory path.
int ast_parse_digest (const char *digest, struct ast_http_digest *d, int request, int pedantic)
 Parse digest authorization header.
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_set_default_eid (struct ast_eid *eid)
 Fill in an ast_eid with the default eid of this machine.
void ast_sha1_hash (char *output, const 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)
int ast_str_to_eid (struct ast_eid *eid, const char *s)
 Convert a string into an EID.
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 do_special_char)
 Turn text string to URI-encoded XX version.
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)

Variables

unsigned int __unsigned_int_flags_dummy
uint64_t __unsigned_int_flags_dummy64
ast_eid ast_eid_default
 Global EID.


Detailed Description

Utility functions.

Definition in file utils.h.


Define Documentation

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

Definition at line 657 of file utils.h.

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

#define ast_assert (  ) 

Definition at line 710 of file utils.h.

Referenced by _ast_odbc_request_obj2(), append_ie(), ast_cc_is_recall(), ast_channel_get_cc_config_params(), ast_hangup(), ast_rtcp_read(), ast_rtp_read(), ast_sched_del(), ast_udptl_read(), cc_generic_agent_start_monitoring(), cc_generic_agent_start_offer_timer(), cc_generic_monitor_cancel_available_timer(), check_callback_sanity(), create_jb(), create_new_sip_etag(), determine_sip_publish_type(), find_timer(), handle_response_publish(), jb_get_and_deliver(), pthread_timer_ack(), publish_expire(), read_pipe(), security_event_cb(), sig_pri_call(), sip_cc_agent_init(), and sip_cc_monitor_unsuspend().

#define AST_BACKGROUND_STACKSIZE   AST_STACKSIZE

Definition at line 367 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 464 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 489 of file utils.h.

#define ast_clear_flag ( p,
flag   ) 

Definition at line 77 of file utils.h.

Referenced by __analog_ss_thread(), __ast_read(), __do_deliver(), __transmit_response(), aji_create_client(), aji_filter_roster(), analog_ss_thread(), ast_audiohook_set_mute(), ast_autoservice_stop(), ast_bridge_call(), ast_cdr_reset(), ast_cdr_specialized_reset(), ast_channel_bridge(), ast_channel_undefer_dtmf(), ast_deactivate_generator(), ast_generic_bridge(), ast_jb_destroy(), ast_jb_put(), ast_rtp_raw_write(), ast_sendtext(), ast_speech_start(), ast_tls_read_conf(), ast_waitfor_nandfds(), ast_waitfordigit_full(), ast_write(), bridge_channel_feature(), bridge_p2p_rtp_write(), builtin_atxfer(), change_hold_state(), change_spy_mode(), channel_spy(), chanspy_exec(), check_goto_on_transfer(), check_pendings(), common_exec(), config_function_read(), config_text_file_load(), create_addr_from_peer(), dahdi_read(), dahdiscan_exec(), dial_exec_full(), dictate_exec(), disa_exec(), dundi_lookup_local(), extenspy_exec(), forward_message(), handle_common_options(), handle_exec(), handle_request_bye(), handle_request_invite(), handle_request_refer(), handle_response(), handle_response_notify(), handle_speechrecognize(), handle_t38_options(), handle_verbose(), init_acf_query(), linear_alloc(), load_config(), load_moh_classes(), local_ast_moh_stop(), local_attended_transfer(), local_hangup(), main(), manage_parkinglot(), manager_optimize_away(), odbc_load_module(), park_call_full(), parkandannounce_exec(), parse_options(), phone_read(), playtones_alloc(), process_sdp(), register_verify(), reload_config(), reset_transaction(), set_config(), set_config_flags(), setup_dahdi_int(), sip_alloc(), sip_call(), sip_dtmfmode(), sip_hangup(), socket_process(), speech_background(), update_call_counter(), and waitstream_core().

#define ast_clear_flag64 ( p,
flag   ) 

Definition at line 134 of file utils.h.

Referenced by authenticate_verify(), build_peer(), build_user(), create_addr(), do_forward(), find_conf(), iax2_destroy_helper(), iax2_setoption(), set_config(), set_config_destroy(), and socket_process().

#define ast_clear_flag_nonstd ( p,
flag   ) 

Value:

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

Definition at line 180 of file utils.h.

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

#define ast_copy_flags ( dest,
src,
flagz   ) 

Definition at line 84 of file utils.h.

Referenced by add_features_datastores(), agent_read(), aji_create_client(), aji_filter_roster(), ast_call_forward(), ast_cdr_reset(), ast_cdr_specialized_reset(), ast_frdup(), ast_frisolate(), build_peer(), builtin_atxfer(), cache_lookup_internal(), channel_spy(), check_peer_ok(), create_addr_from_peer(), dundi_lookup_local(), feature_interpret(), framein(), minivm_greet_exec(), minivm_record_exec(), park_exec_full(), 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 141 of file utils.h.

Referenced by __find_callno(), build_peer(), build_user(), check_access(), create_addr(), dial_exec_full(), iax2_request(), 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 184 of file utils.h.

#define AST_FLAGS_ALL   UINT_MAX

Definition at line 196 of file utils.h.

Referenced by add_features_datastores(), aji_create_client(), ast_cdr_reset(), ast_cdr_specialized_reset(), builtin_atxfer(), cache_lookup_internal(), channel_spy(), chanspy_exec(), check_goto_on_transfer(), dahdiscan_exec(), dundi_lookup_local(), extenspy_exec(), feature_interpret(), handle_queue_reload(), load_module(), load_moh_classes(), manager_queue_reload(), park_exec_full(), parse_options(), populate_defaults(), reload(), 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 425 of file utils.h.

#define ast_free_ptr   ast_free

Definition at line 426 of file utils.h.

Referenced by add_extensions(), ast_extension_state(), ast_extension_state_add(), ast_merge_contexts_and_delete(), build_parkinglot(), handle_cli_dialplan_add_extension(), load_module(), manage_parkinglot(), park_call_full(), 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 441 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 381 of file utils.h.

Referenced by accept_thread(), ast_bridge_impart(), ast_dial_run(), ast_features_init(), ast_taskprocessor_get(), bridge_call_thread_launch(), bridge_channel_join(), function_autopatchup(), handle_callforward_button(), handle_enbloc_call_message(), handle_offhook_message(), handle_soft_key_event_message(), handle_stimulus_message(), handle_transfer_button(), HandleCallOutgoing(), init_logger(), load_module(), local_dtmf_helper(), restart_monitor(), rpt_master(), rpt_telemetry(), 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 389 of file utils.h.

Referenced by add_notify(), aji_reload(), ast_autoservice_start(), ast_device_state_engine_init(), ast_enable_distributed_devstate(), ast_makesocket(), ast_sched_thread_create(), ast_tcptls_server_start(), astdb_init(), calendar_event_notify(), conf_run(), config_load(), do_reload(), find_idle_thread(), init_app_class(), init_timing_thread(), load_module(), local_ast_moh_start(), pri_dchannel(), restart_monitor(), restart_pktc_thread(), sip_prepare_socket(), start_network_thread(), start_stream(), store_config(), 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 385 of file utils.h.

Referenced by __analog_handle_event(), action_originate(), analog_handle_init_event(), analog_ss_thread_start(), 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(), main(), mwi_thread(), and spawn_dp_lookup().

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

Referenced by ast_cdr_submit_batch(), ast_tcptls_server_root(), cc_generic_agent_recall(), conf_run(), 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 500 of file utils.h.

#define ast_set2_flag ( p,
value,
flag   ) 

Definition at line 94 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_plc_reload(), ast_tls_read_conf(), ast_translate(), build_peer(), dial_exec_full(), do_reload(), find_account(), find_user(), handle_common_options(), handle_t38_options(), load_config(), load_module(), load_moh_classes(), local_ast_moh_start(), and sip_setoption().

#define ast_set2_flag64 ( p,
value,
flag   ) 

Definition at line 151 of file utils.h.

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

#define ast_set2_flag_nonstd ( p,
value,
flag   ) 

Definition at line 189 of file utils.h.

#define ast_set_flag ( p,
flag   ) 

Definition at line 70 of file utils.h.

Referenced by __analog_ss_thread(), __ast_pbx_run(), __ast_read(), __ast_request_and_dial(), __sip_subscribe_mwi_do(), _macro_exec(), action_redirect(), aji_create_client(), aji_load_config(), analog_ss_thread(), app_exec(), apply_peer(), ast_audiohook_set_mute(), ast_autoservice_start(), ast_bridge_call(), ast_bridge_features_set_flag(), ast_bridge_new(), ast_bridge_timelimit(), 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_change_source(), ast_rtp_local_bridge(), ast_rtp_raw_write(), ast_rtp_read(), ast_rtp_stop(), ast_rtp_update_source(), ast_speech_change_state(), AST_TEST_DEFINE(), ast_tls_read_conf(), ast_waitfor_nandfds(), ast_waitfordigit_full(), asyncgoto_exec(), bridge_channel_feature(), bridge_exec(), bridge_p2p_rtp_write(), build_peer(), builtin_atxfer(), builtin_blindtransfer(), cb_extensionstate(), cc_generic_agent_init(), change_hold_state(), change_spy_mode(), channel_spy(), chanspy_exec(), check_availability(), check_bridge(), check_peer_ok(), check_user_full(), check_via(), common_exec(), connect_link(), create_addr_from_peer(), create_transaction(), dahdi_read(), dahdiscan_exec(), dial_exec_full(), dictate_exec(), directory_exec(), disa_exec(), do_register(), dundi_encrypt(), dundi_lookup_local(), dundi_send(), extenspy_exec(), find_peer(), find_user_realtime(), free_vm_users(), handle_common_options(), handle_exec(), handle_invite_replaces(), handle_queue_reload(), handle_request_invite(), handle_request_refer(), handle_request_subscribe(), handle_response(), handle_response_invite(), handle_t38_options(), handle_verbose(), hangupcalls(), hanguptree(), init_acf_query(), init_app_class(), init_files_class(), init_outgoing(), interpret_t38_parameters(), launch_monitor_thread(), linear_alloc(), load_config(), load_moh_classes(), local_alloc(), local_ast_moh_start(), local_attended_transfer(), local_call(), local_hangup(), login_exec(), main(), manage_parkinglot(), manager_queue_reload(), manager_sipnotify(), minivm_greet_exec(), nocdr_exec(), odbc_load_module(), park_call_full(), park_exec_full(), parse_options(), playtones_alloc(), post_cdr(), process_cn_rfc3389(), process_crypto(), process_sdp(), qualify_peer(), record_exec(), register_verify(), ring_entry(), rpt(), rpt_call(), rpt_exec(), rpt_tele_thread(), set_bridge_features_on_config(), set_config_flags(), set_insecure_flags(), sip_answer(), sip_call(), sip_cc_agent_ack(), sip_cc_agent_init(), sip_cli_notify(), sip_dtmfmode(), sip_hangup(), sip_indicate(), sip_poke_peer(), sip_reinvite_retry(), sip_send_mwi_to_peer(), sip_sendhtml(), sip_set_rtp_peer(), sip_set_udptl_peer(), sip_write(), socket_process(), start_spying(), tonepair_alloc(), transmit_publish(), transmit_register(), transmit_reinvite_with_sdp(), try_calling(), update_call_counter(), update_connectedline(), vm_execmain(), volume_write(), and waitstream_core().

#define ast_set_flag64 ( p,
flag   ) 

Definition at line 127 of file utils.h.

Referenced by authenticate_reply(), authenticate_request(), build_peer(), build_user(), check_access(), conf_run(), decrypt_frame(), dial_exec_full(), handle_cli_iax2_prune_realtime(), iax2_predestroy(), iax2_provision(), iax2_setoption(), iax2_start_transfer(), parse_options(), peer_delme_cb(), pvt_destructor(), run_station(), set_config(), sla_station_exec(), sla_trunk_exec(), socket_process(), and user_delme_cb().

#define ast_set_flag_nonstd ( p,
flag   ) 

Value:

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

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

#define ast_set_flags_to64 ( p,
flag,
value   ) 

Definition at line 161 of file utils.h.

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

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

Definition at line 362 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 527 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 621 of file utils.h.

Referenced by __ast_channel_alloc_ap(), __ast_play_and_record(), _ast_device_state(), _build_port_config(), _macro_exec(), _parse(), _while_exec(), acf_jabberreceive_read(), acf_meetme_info(), acf_odbc_write(), action_agents(), action_status(), add_agent(), add_peer_mailboxes(), add_redirect(), add_var(), admin_exec(), advanced_options(), agi_exec_full(), agi_handle_command(), aji_join_exec(), aji_leave_exec(), aji_send_exec(), aji_sendgroup_exec(), aji_status_exec(), answer_exec_enable(), app_exec(), append_mailbox(), append_mailbox_mapping(), append_var_and_value_to_filter(), apply_directmedia_ha(), apply_options(), aqm_exec(), array(), ast_aji_get_client(), ast_app_getdata(), ast_append_ha(), ast_bridge_call(), ast_bridge_timelimit(), ast_build_timing(), ast_callerid_split(), ast_cdr_fork(), ast_cdr_setaccount(), ast_cdr_setpeeraccount(), ast_cel_report_event(), ast_channel_connected_line_macro(), ast_channel_redirecting_macro(), ast_channel_set_linkgroup(), ast_data_iterator_init(), ast_eivr_senddtmf(), ast_eivr_setvariable(), ast_el_add_history(), ast_filehelper(), ast_format_str_reduce(), ast_func_read(), ast_func_read2(), ast_func_write(), ast_get_group(), ast_hook_send_action(), ast_http_get_cookies(), ast_mkdir(), ast_monitor_change_fname(), ast_monitor_start(), ast_netsock_bind(), ast_ouraddrfor(), ast_parse_allow_disallow(), ast_parse_arg(), ast_pickup_call(), ast_playtones_start(), ast_register_file_version(), ast_rtp_read(), ast_sockaddr_parse(), ast_sockaddr_resolve(), ast_str_retrieve_variable(), ast_utils_which(), ast_writefile(), astman_get_variables(), asyncgoto_exec(), auth_exec(), authenticate_reply(), authenticate_verify(), background_detect_exec(), bridge_exec(), bridge_play_sounds(), build_channels(), build_mapping(), build_peer(), build_profile(), build_user(), builtin_atxfer(), builtin_automixmonitor(), builtin_automonitor(), cache_get_callno_locked(), callerid_read(), callerid_write(), celgenuserevent_exec(), chanavail_exec(), channel_admin_exec(), channel_spy(), chanspy_exec(), check_access(), check_blacklist(), check_day(), check_dow(), check_goto_on_transfer(), check_month(), check_peer_ok(), check_switch_expr(), check_timerange(), check_user_full(), complete_meetmecmd(), conf_exec(), conf_run(), conf_start_moh(), confbridge_exec(), config_function_read(), config_line(), config_module(), connectedline_read(), connectedline_write(), controlplayback_exec(), count_exec(), create_addr(), create_addr_from_peer(), create_followme_number(), create_queue_member(), create_vmaccount(), cut_internal(), dahdi_send_callrerouting_facility_exec(), dahdiras_exec(), dahdiscan_exec(), data_filter_add_nodes(), data_filter_alloc(), data_filter_generate(), data_provider_create(), data_provider_release(), data_result_generate(), data_result_get_node(), data_search_create(), data_search_generate(), data_search_get_node(), decrypt_frame(), del_exec(), deltree_exec(), determine_starting_point(), dial_exec_full(), dial_trunk(), dialgroup_refreshdb(), dialgroup_write(), dictate_exec(), directory_exec(), disa_exec(), dnsmgr_refresh(), do_forward(), do_immediate_setup(), do_message(), do_notify(), do_say(), dundi_query_read(), dundi_result_read(), dundifunc_read(), enum_query_read(), enum_result_read(), ewscal_write_event(), exec_exec(), execif_exec(), extenspy_exec(), feature_interpret(), festival_exec(), fileexists_core(), find_call(), find_conf_realtime(), find_gtalk(), find_sdp(), find_table(), find_table_cb(), findmeexec(), function_agent(), function_iaxpeer(), function_realtime_store(), generic_recall(), get_cid_name(), get_destination(), get_pai(), get_refer_info(), gosub_exec(), gosubif_exec(), gtalk_action(), gtalk_alloc(), gtalk_create_candidates(), gtalk_invite(), gtalk_request(), gtalk_update_externip(), handle_call_forward(), handle_cli_check_permissions(), handle_cli_dialplan_add_extension(), handle_cli_file_convert(), handle_common_options(), handle_debug_dialplan(), handle_mfcr2_set_debug(), handle_mgcp_audit_endpoint(), handle_options(), handle_request_invite(), handle_request_notify(), handle_request_subscribe(), handle_response(), handle_show_dialplan(), handle_t38_options(), handle_verbose(), has_voicemail(), iax2_call(), iax2_devicestate(), iax2_prov_app(), iax2_request(), iconv_read(), init_acf_query(), init_jack_data(), insert_penaltychange(), is_prefix(), is_valid_dtmf(), isAnsweringMachine(), isexten_function_read(), ivr_dispatch(), jingle_request(), launch_ha_netscript(), launch_monitor_thread(), launch_netscript(), leave_voicemail(), load_config(), load_dynamic_module(), local_call(), local_devicestate(), log_exec(), logger_print_normal(), 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(), manage_parkinglot(), 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_mwi_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(), multicast_rtp_request(), my_pri_make_cc_dialstring(), notify_message(), notify_new_message(), odbc_log(), orig_app(), orig_exten(), originate_exec(), ospauth_exec(), ospfinished_exec(), osplookup_exec(), ospnext_exec(), oss_call(), oss_request(), page_exec(), park_call_exec(), park_space_reserve(), parkandannounce_exec(), parse_allowed_methods(), parse_apps(), parse_empty_options(), parse_events(), parse_register_contact(), parse_session_expires(), party_id_write(), party_name_write(), party_number_write(), pbx_builtin_answer(), 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_find_extension(), pbx_parseable_goto(), peer_set_srcaddr(), pickup_exec(), pickupchan_exec(), play_message(), play_moh_exec(), playback_exec(), pqm_exec(), prep_email_sub_vars(), privacy_exec(), process_echocancel(), process_sdp(), process_sdp_o(), 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_ldap(), realtime_multi_odbc(), realtime_multi_pgsql(), receivefax_exec(), record_exec(), redirecting_read(), redirecting_write(), register_verify(), registry_authrequest(), reload_followme(), reload_single_member(), resource_name_match(), retrydial_exec(), rpt_exec(), rqm_exec(), rtcp_do_debug_ip(), rtp_do_debug_ip(), saycountedadj_exec(), saycountednoun_exec(), sayunixtime_exec(), senddtmf_exec(), sendfax_exec(), sendmail(), sendurl_exec(), set_config_flags(), setup_privacy_args(), sig_pri_extract_called_num_subaddr(), sig_pri_msn_match(), sip_alloc(), sip_devicestate(), sip_get_cc_information(), sip_new(), sip_show_settings(), sip_sipredirect(), skel_exec(), 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(), srv_result_read(), start_moh_exec(), start_monitor_action(), start_monitor_exec(), state_notify_build_xml(), stun_monitor_request(), timezone_add(), transfer_exec(), transmit_invite(), transmit_refer(), 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_check_password_shell(), vm_exec(), vm_execmain(), vmauthenticate(), vmsayname_exec(), wait_for_answer(), wait_for_winner(), waitstream_core(), xmldoc_get_syntax_fun(), 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 556 of file utils.h.

#define ast_test_flag ( p,
flag   ) 

Definition at line 63 of file utils.h.

Referenced by __ast_pbx_run(), __ast_queue_frame(), __ast_read(), __sip_destroy(), __ssl_setup(), __transmit_response(), _ast_odbc_request_obj2(), _macro_exec(), _sip_show_peer(), _sip_show_peers(), acf_odbc_read(), action_login(), add_agent(), add_codec_to_sdp(), add_rpid(), add_sdp(), aji_build_publish_skeleton(), aji_cli_purge_pubsub_nodes(), aji_create_client(), aji_handle_pubsub_error(), aji_handle_subscribe(), aji_pruneregister(), aji_publish_device_state(), aji_pubsub_subscribe(), app_exec(), ast_audiohook_write_frame(), ast_autoservice_start(), ast_bridge_call(), ast_bridge_merge(), 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_setpeeraccount(), ast_cdr_setuserfield(), ast_cdr_setvar(), ast_cdr_specialized_reset(), ast_cdr_start(), ast_cdr_update(), ast_channel_bridge(), ast_channel_defer_dtmf(), ast_config_internal_load(), ast_do_masquerade(), ast_explicit_goto(), ast_frisolate(), ast_generic_bridge(), 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_quiet_chan(), ast_raw_answer(), ast_readstring_full(), ast_rtp_raw_write(), ast_sendtext(), ast_softhangup_nolock(), ast_streamfile(), AST_TEST_DEFINE(), ast_transfer(), ast_translate(), ast_waitfordigit_full(), ast_write(), auth_exec(), authenticate_verify(), bridge_channel_join(), bridge_check_dissolve(), bridge_exec(), bridge_p2p_rtp_write(), build_peer(), build_radius_record(), build_via(), builtin_atxfer(), callback_dialoptions(), cb_extensionstate(), cdr_read(), cdr_write(), change_hold_state(), channel_data_add_flags(), channel_spy(), chanspy_exec(), check_bridge(), check_peer_ok(), check_pendings(), check_post(), check_rtp_timeout(), check_user_full(), close_mailbox(), common_exec(), complete_sip_peer(), complete_sip_registered_peer(), confbridge_exec(), config_text_file_load(), connectedline_write(), controlplayback_exec(), copy_via_headers(), create_addr_from_peer(), create_jb(), destroy_trans(), dial_exec_full(), dialog_initialize_rtp(), dictate_exec(), directory_exec(), disa_exec(), do_directory(), do_setnat(), 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(), enable_dsp_detect(), execute_cb(), expire_register(), extenspy_exec(), feature_exec_app(), feature_interpret_helper(), find_cache(), find_or_create(), find_user(), find_user_realtime(), forward_message(), free_user(), function_sippeer(), get_destination(), get_insecure_variable_from_config(), get_rpid(), gosub_exec(), handle_cli_moh_show_classes(), handle_cli_wait_fullybooted(), handle_command_response(), handle_exec(), 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_response_notify(), handle_show_settings(), handle_showchan(), handle_skinny_show_settings(), handle_speechrecognize(), handle_tcptls_connection(), hint_read(), iax2_write(), initreqprep(), interpret_t38_parameters(), is_state_change_valid(), join_conference_bridge(), leave_conference_bridge(), leave_voicemail(), load_dynamic_module(), load_resource(), local_alloc(), local_ast_moh_start(), local_bridgedchannel(), local_call(), local_hangup(), local_indicate(), local_write(), main(), make_email_file(), manager_list_voicemail_users(), match_req_to_dialog(), menu_callback(), minivm_accmess_exec(), minivm_account_func_read(), minivm_greet_exec(), minivm_notify_exec(), minivm_record_exec(), mixmonitor_exec(), mixmonitor_thread(), mod_load_cmp(), moh_files_alloc(), notify_new_message(), odbc_load_module(), page_exec(), park_call_full(), park_space_reserve(), parse_moved_contact(), parse_register_contact(), pbx_builtin_background(), pbx_builtin_waitexten(), peer_ipcmp_cb(), pick_unlocked_cdr(), play_mailbox_owner(), play_message(), play_record_review(), post_cdr(), post_join_marked(), post_join_unmarked(), precache_transactions(), process_cn_rfc3389(), process_crypto(), process_sdp(), process_sdp_a_audio(), process_sdp_o(), process_text_line(), read_exec(), readexten_exec(), realtime_switch_common(), receivefax_exec(), record_exec(), redirecting_write(), register_verify(), reload_config(), reload_handler(), reload_queues(), reload_single_queue(), remove_from_queue(), reqprep(), respprep(), retrans_pkt(), retrydial_exec(), rpt_master(), search_directory_sub(), select_entry(), select_item_pause(), send_request(), sendfax_exec(), sendmail(), sendurl_exec(), serialize_showchan(), set_address_from_contact(), set_config_flags(), set_pvt_allowed_methods(), set_t38_capabilities(), should_skip_dtmf(), show_channels_cb(), sig_pri_call(), sip_alloc(), sip_call(), sip_cc_agent_destructor(), 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_setoption(), sip_show_channel(), sip_show_settings(), sip_show_users(), sip_write(), sla_trunk_exec(), smdi_msg_find(), sms_exec(), socket_process(), socket_process_meta(), softhangup_exec(), spawn_mp3(), speech_background(), speech_read(), spy_generate(), start_spying(), startmon(), transmit_info_with_digit(), transmit_invite(), transmit_notify_with_mwi(), transmit_refer(), transmit_reinvite_with_sdp(), transmit_request_with_auth(), transmit_response_with_sdp(), try_calling(), update_call_counter(), update_connectedline(), update_peer(), update_redirecting(), update_registry(), vm_exec(), vm_execmain(), vm_instructions_en(), vm_intro(), vm_newuser(), and waitstream_core().

#define ast_test_flag64 ( p,
flag   ) 

Definition at line 120 of file utils.h.

Referenced by __do_deliver(), __expire_registry(), __get_from_jb(), __iax2_show_peers(), action_meetmelist(), admin_exec(), ast_app_options2str64(), ast_cli_netstats(), authenticate_reply(), authenticate_request(), authenticate_verify(), build_peer(), build_user(), can_write(), check_access(), complete_iax2_peers(), conf_exec(), conf_run(), decrypt_frame(), dial_exec_full(), do_forward(), find_conf(), function_iaxpeer(), handle_cli_iax2_prune_realtime(), handle_cli_iax2_show_channels(), handle_cli_iax2_show_peer(), handle_cli_iax2_show_users(), iax2_call(), iax2_destroy_helper(), iax2_getpeertrunk(), iax2_hangup(), iax2_indicate(), iax2_predestroy(), iax2_queryoption(), iax2_request(), iax2_send(), iax2_trunk_queue(), iax2_write(), log_jitterstats(), manager_iax2_show_peer_list(), peers_data_provider_get(), prune_peers(), prune_users(), realtime_update_peer(), reg_source_db(), register_verify(), retrydial_exec(), schedule_delivery(), send_trunk(), set_config(), setup_privacy_args(), socket_process(), update_registry(), user_set_kickme_cb(), user_set_muted_cb(), user_set_unmuted_cb(), users_data_provider_get(), valid_priv_reply(), and wait_for_answer().

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

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

#define localtime_r   __dont_use_localtime_r_use_ast_localtime_instead__

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

Referenced by _ast_asprintf().

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

Definition at line 228 of file utils.h.

Referenced by __ast_answer(), handle_mousedown(), handle_response_register(), and sdl_setup().

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

Definition at line 226 of file utils.h.

Referenced by _sip_tcp_helper_thread(), autoanswer_complete(), calculate_local_max_datagram(), h263p_encap(), h264_encap(), interpret_t38_parameters(), and mpeg4_encap().


Function Documentation

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

Definition at line 2070 of file utils.c.

References MALLOC_FAILURE_MSG, and vasprintf.

02071 {
02072    int res;
02073    va_list ap;
02074 
02075    va_start(ap, fmt);
02076    if ((res = vasprintf(ret, fmt, ap)) == -1) {
02077       MALLOC_FAILURE_MSG;
02078    }
02079    va_end(ap);
02080 
02081    return res;
02082 }

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

Definition at line 477 of file utils.h.

00505 {

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

Definition at line 454 of file utils.h.

00469 {

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

Definition at line 513 of file utils.h.

00532 {

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

Definition at line 542 of file utils.h.

00561 {

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

Definition at line 571 of file utils.h.

00601 {

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

Definition at line 609 of file utils.h.

00623 {                                                                \

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

Referenced by aes_helper(), ast_check_signature(), base64_helper(), and osp_validate_token().

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

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

References ast_base64encode_full().

Referenced by aes_helper(), aji_start_sasl(), ast_sign(), base64_helper(), build_secret(), and osp_check_destination().

00344 {
00345    return ast_base64encode_full(dst, src, srclen, max, 0);
00346 }

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

encode text to BASE64 coding

Definition at line 292 of file utils.c.

Referenced by ast_base64encode().

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

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

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

Referenced by send_string().

01158 {
01159    struct timeval start = ast_tvnow();
01160    int n = 0;
01161    int elapsed = 0;
01162 
01163    while (len) {
01164       if (ast_wait_for_output(fd, timeoutms - elapsed)) {
01165          /* poll returned a fatal error, so bail out immediately. */
01166          return -1;
01167       }
01168 
01169       /* Clear any errors from a previous write */
01170       clearerr(f);
01171 
01172       n = fwrite(src, 1, len, f);
01173 
01174       if (ferror(f) && errno != EINTR && errno != EAGAIN) {
01175          /* fatal error from fwrite() */
01176          if (!feof(f)) {
01177             /* Don't spam the logs if it was just that the connection is closed. */
01178             ast_log(LOG_ERROR, "fwrite() returned error: %s\n", strerror(errno));
01179          }
01180          n = -1;
01181          break;
01182       }
01183 
01184       /* Update for data already written to the socket */
01185       len -= n;
01186       src += n;
01187 
01188       elapsed = ast_tvdiff_ms(ast_tvnow(), start);
01189       if (elapsed >= timeoutms) {
01190          /* We've taken too long to write 
01191           * This is only an error condition if we haven't finished writing. */
01192          n = len ? -1 : 0;
01193          break;
01194       }
01195    }
01196 
01197    while (fflush(f)) {
01198       if (errno == EAGAIN || errno == EINTR) {
01199          continue;
01200       }
01201       if (!feof(f)) {
01202          /* Don't spam the logs if it was just that the connection is closed. */
01203          ast_log(LOG_ERROR, "fflush() returned error: %s\n", strerror(errno));
01204       }
01205       n = -1;
01206       break;
01207    }
01208 
01209    return n < 0 ? -1 : 0;
01210 }

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

01117 {
01118    struct timeval start = ast_tvnow();
01119    int res = 0;
01120    int elapsed = 0;
01121 
01122    while (len) {
01123       if (ast_wait_for_output(fd, timeoutms - elapsed)) {
01124          return -1;
01125       }
01126 
01127       res = write(fd, s, len);
01128 
01129       if (res < 0 && errno != EAGAIN && errno != EINTR) {
01130          /* fatal error from write() */
01131          ast_log(LOG_ERROR, "write() returned error: %s\n", strerror(errno));
01132          return -1;
01133       }
01134 
01135       if (res < 0) {
01136          /* It was an acceptable error */
01137          res = 0;
01138       }
01139 
01140       /* Update how much data we have left to write */
01141       len -= res;
01142       s += res;
01143       res = 0;
01144 
01145       elapsed = ast_tvdiff_ms(ast_tvnow(), start);
01146       if (elapsed >= timeoutms) {
01147          /* We've taken too long to write 
01148           * This is only an error condition if we haven't finished writing. */
01149          res = len ? -1 : 0;
01150          break;
01151       }
01152    }
01153 
01154    return res;
01155 }

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

Compare two EIDs.

Returns:
0 if the two are the same, non-zero otherwise
Since:
1.6.1

Definition at line 294 of file netsock.c.

Referenced by aji_devstate_cb(), aji_handle_pubsub_event(), aji_mwi_cb(), ast_event_cb(), build_peer(), build_transactions(), destroy_trans(), dundi_answer_entity(), dundi_answer_query(), dundi_ie_append_eid_appropriately(), dundi_lookup_internal(), dundi_query_thread(), evt_event_deliver_cb(), find_peer(), optimize_transactions(), and register_request().

00295 {
00296    return memcmp(eid1, eid2, sizeof(*eid1));
00297 }

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

/brief Convert an EID to a string

Since:
1.6.1

Definition at line 218 of file netsock.c.

References ast_eid::eid.

Referenced by aji_publish_device_state(), aji_publish_mwi(), append_transaction(), ast_set_default_eid(), ast_str_retrieve_variable(), build_transactions(), cache_lookup(), cache_lookup_internal(), check_key(), complete_peer_helper(), destroy_trans(), do_autokill(), do_register(), do_register_expire(), dump_answer(), dump_eid(), dump_raw_ie(), dundi_answer_entity(), dundi_lookup_internal(), dundi_lookup_local(), dundi_lookup_thread(), dundi_precache_thread(), dundi_prop_precache(), dundi_query_thread(), dundi_send(), dundi_show_entityid(), dundi_show_peer(), dundi_show_peers(), dundi_show_requests(), handle_command_response(), handle_show_settings(), populate_addr(), register_request(), and update_key().

00219 {
00220    int x;
00221    char *os = s;
00222    if (maxlen < 18) {
00223       if (s && (maxlen > 0))
00224          *s = '\0';
00225    } else {
00226       for (x = 0; x < 5; x++) {
00227          sprintf(s, "%02x:", eid->eid[x]);
00228          s += 3;
00229       }
00230       sprintf(s, "%02x", eid->eid[5]);
00231    }
00232    return os;
00233 }

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

References ast_log(), and LOG_WARNING.

Referenced by ast_netsock_bindaddr().

01891 {
01892 #if defined(HAVE_IP_MTU_DISCOVER)
01893    int val = IP_PMTUDISC_DONT;
01894    
01895    if (setsockopt(sock, IPPROTO_IP, IP_MTU_DISCOVER, &val, sizeof(val)))
01896       ast_log(LOG_WARNING, "Unable to disable PMTU discovery. Large UDP packets may fail to be delivered when sent from this socket.\n");
01897 #endif /* HAVE_IP_MTU_DISCOVER */
01898 }

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

Thread-safe gethostbyname function to use in Asterisk.

Definition at line 183 of file utils.c.

References hp.

Referenced by ast_parse_arg(), config_load(), config_parse_variables(), create_addr(), festival_exec(), gtalk_update_stun(), iax_template_parse(), jingle_load_config(), jingle_update_stun(), launch_netscript(), process_sdp(), realtime_peer(), realtime_user(), reload_config(), rpt_exec(), and set_config().

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

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

Produces MD5 hash based on input string.

Definition at line 231 of file utils.c.

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

Referenced by build_reply_digest(), and md5().

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

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

01901 {
01902    char *ptr;
01903    int len = strlen(path), count = 0, x, piececount = 0;
01904    char *tmp = ast_strdupa(path);
01905    char **pieces;
01906    char *fullpath = alloca(len + 1);
01907    int res = 0;
01908 
01909    for (ptr = tmp; *ptr; ptr++) {
01910       if (*ptr == '/')
01911          count++;
01912    }
01913 
01914    /* Count the components to the directory path */
01915    pieces = alloca(count * sizeof(*pieces));
01916    for (ptr = tmp; *ptr; ptr++) {
01917       if (*ptr == '/') {
01918          *ptr = '\0';
01919          pieces[piececount++] = ptr + 1;
01920       }
01921    }
01922 
01923    *fullpath = '\0';
01924    for (x = 0; x < piececount; x++) {
01925       /* This looks funky, but the buffer is always ideally-sized, so it's fine. */
01926       strcat(fullpath, "/");
01927       strcat(fullpath, pieces[x]);
01928       res = mkdir(fullpath, mode);
01929       if (res && errno != EEXIST)
01930          return errno;
01931    }
01932    return 0;
01933 }

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

Parse digest authorization header.

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

Definition at line 1957 of file utils.c.

References ast_free, ast_log(), ast_skip_blanks(), ast_str_buffer(), ast_str_create(), ast_str_set(), ast_string_field_set, ast_strlen_zero(), ast_http_digest::cnonce, LOG_WARNING, ast_http_digest::nc, ast_http_digest::nonce, ast_http_digest::qop, ast_http_digest::realm, ast_http_digest::response, str, ast_http_digest::uri, and ast_http_digest::username.

01957                                                                                                {
01958    int i;
01959    char *c, key[512], val[512], tmp[512];
01960    struct ast_str *str = ast_str_create(16);
01961 
01962    if (ast_strlen_zero(digest) || !d || !str) {
01963       ast_free(str);
01964       return -1;
01965    }
01966 
01967    ast_str_set(&str, 0, "%s", digest);
01968 
01969    c = ast_skip_blanks(ast_str_buffer(str));
01970 
01971    if (strncasecmp(tmp, "Digest ", strlen("Digest "))) {
01972       ast_log(LOG_WARNING, "Missing Digest.\n");
01973       ast_free(str);
01974       return -1;
01975    }
01976    c += strlen("Digest ");
01977 
01978    /* lookup for keys/value pair */
01979    while (*c && *(c = ast_skip_blanks(c))) {
01980       /* find key */
01981       i = 0;
01982       while (*c && *c != '=' && *c != ',' && !isspace(*c)) {
01983          key[i++] = *c++;
01984       }
01985       key[i] = '\0';
01986       c = ast_skip_blanks(c);
01987       if (*c == '=') {
01988          c = ast_skip_blanks(++c);
01989          i = 0;
01990          if (*c == '\"') {
01991             /* in quotes. Skip first and look for last */
01992             c++;
01993             while (*c && *c != '\"') {
01994                if (*c == '\\' && c[1] != '\0') { /* unescape chars */
01995                   c++;
01996                }
01997                val[i++] = *c++;
01998             }
01999          } else {
02000             /* token */
02001             while (*c && *c != ',' && !isspace(*c)) {
02002                val[i++] = *c++;
02003             }
02004          }
02005          val[i] = '\0';
02006       }
02007 
02008       while (*c && *c != ',') {
02009          c++;
02010       }
02011       if (*c) {
02012          c++;
02013       }
02014 
02015       if (!strcasecmp(key, "username")) {
02016          ast_string_field_set(d, username, val);
02017       } else if (!strcasecmp(key, "realm")) {
02018          ast_string_field_set(d, realm, val);
02019       } else if (!strcasecmp(key, "nonce")) {
02020          ast_string_field_set(d, nonce, val);
02021       } else if (!strcasecmp(key, "uri")) {
02022          ast_string_field_set(d, uri, val);
02023       } else if (!strcasecmp(key, "domain")) {
02024          ast_string_field_set(d, domain, val);
02025       } else if (!strcasecmp(key, "response")) {
02026          ast_string_field_set(d, response, val);
02027       } else if (!strcasecmp(key, "algorithm")) {
02028          if (strcasecmp(val, "MD5")) {
02029             ast_log(LOG_WARNING, "Digest algorithm: \"%s\" not supported.\n", val);
02030             return -1;
02031          }
02032       } else if (!strcasecmp(key, "cnonce")) {
02033          ast_string_field_set(d, cnonce, val);
02034       } else if (!strcasecmp(key, "opaque")) {
02035          ast_string_field_set(d, opaque, val);
02036       } else if (!strcasecmp(key, "qop") && !strcasecmp(val, "auth")) {
02037          d->qop = 1;
02038       } else if (!strcasecmp(key, "nc")) {
02039          unsigned long u;
02040          if (sscanf(val, "%30lx", &u) != 1) {
02041             ast_log(LOG_WARNING, "Incorrect Digest nc value: \"%s\".\n", val);
02042             return -1;
02043          }
02044          ast_string_field_set(d, nc, val);
02045       }
02046    }
02047    ast_free(str);
02048 
02049    /* Digest checkout */
02050    if (ast_strlen_zero(d->realm) || ast_strlen_zero(d->nonce)) {
02051       /* "realm" and "nonce" MUST be always exist */
02052       return -1;
02053    }
02054 
02055    if (!request) {
02056       /* Additional check for Digest response */
02057       if (ast_strlen_zero(d->username) || ast_strlen_zero(d->uri) || ast_strlen_zero(d->response)) {
02058          return -1;
02059       }
02060 
02061       if (pedantic && d->qop && (ast_strlen_zero(d->cnonce) || ast_strlen_zero(d->nc))) {
02062          return -1;
02063       }
02064    }
02065 
02066    return 0;
02067 }

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

01429 {
01430    char *dataPut = start;
01431    int inEscape = 0;
01432    int inQuotes = 0;
01433 
01434    for (; *start; start++) {
01435       if (inEscape) {
01436          *dataPut++ = *start;       /* Always goes verbatim */
01437          inEscape = 0;
01438       } else {
01439          if (*start == '\\') {
01440             inEscape = 1;      /* Do not copy \ into the data */
01441          } else if (*start == '\'') {
01442             inQuotes = 1 - inQuotes;   /* Do not copy ' into the data */
01443          } else {
01444             /* Replace , with |, unless in quotes */
01445             *dataPut++ = inQuotes ? *start : ((*start == find) ? replace_with : *start);
01446          }
01447       }
01448    }
01449    if (start != dataPut)
01450       *dataPut = 0;
01451    return dataPut;
01452 }

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

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

01032 {
01033    unsigned char attr_destroy = 0;
01034    int res;
01035 
01036    if (!attr) {
01037       attr = alloca(sizeof(*attr));
01038       pthread_attr_init(attr);
01039       attr_destroy = 1;
01040    }
01041 
01042    if ((errno = pthread_attr_setdetachstate(attr, PTHREAD_CREATE_DETACHED)))
01043       ast_log(LOG_WARNING, "pthread_attr_setdetachstate: %s\n", strerror(errno));
01044 
01045    res = ast_pthread_create_stack(thread, attr, start_routine, data, 
01046                                   stacksize, file, caller, line, start_fn);
01047 
01048    if (attr_destroy)
01049       pthread_attr_destroy(attr);
01050 
01051    return res;
01052 }

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

00983 {
00984 #if !defined(LOW_MEMORY)
00985    struct thr_arg *a;
00986 #endif
00987 
00988    if (!attr) {
00989       attr = alloca(sizeof(*attr));
00990       pthread_attr_init(attr);
00991    }
00992 
00993 #ifdef __linux__
00994    /* On Linux, pthread_attr_init() defaults to PTHREAD_EXPLICIT_SCHED,
00995       which is kind of useless. Change this here to
00996       PTHREAD_INHERIT_SCHED; that way the -p option to set realtime
00997       priority will propagate down to new threads by default.
00998       This does mean that callers cannot set a different priority using
00999       PTHREAD_EXPLICIT_SCHED in the attr argument; instead they must set
01000       the priority afterwards with pthread_setschedparam(). */
01001    if ((errno = pthread_attr_setinheritsched(attr, PTHREAD_INHERIT_SCHED)))
01002       ast_log(LOG_WARNING, "pthread_attr_setinheritsched: %s\n", strerror(errno));
01003 #endif
01004 
01005    if (!stacksize)
01006       stacksize = AST_STACKSIZE;
01007 
01008    if ((errno = pthread_attr_setstacksize(attr, stacksize ? stacksize : AST_STACKSIZE)))
01009       ast_log(LOG_WARNING, "pthread_attr_setstacksize: %s\n", strerror(errno));
01010 
01011 #if !defined(LOW_MEMORY)
01012    if ((a = ast_malloc(sizeof(*a)))) {
01013       a->start_routine = start_routine;
01014       a->data = data;
01015       start_routine = dummy_start;
01016       if (asprintf(&a->name, "%-20s started at [%5d] %s %s()",
01017               start_fn, line, file, caller) < 0) {
01018          ast_log(LOG_WARNING, "asprintf() failed: %s\n", strerror(errno));
01019          a->name = NULL;
01020       }
01021       data = a;
01022    }
01023 #endif /* !LOW_MEMORY */
01024 
01025    return pthread_create(thread, attr, start_routine, data); /* We're in ast_pthread_create, so it's okay */
01026 }

long int ast_random ( void   ) 

Definition at line 1404 of file utils.c.

References ast_mutex_lock, ast_mutex_unlock, and randomlock.

Referenced by acf_rand_exec(), action_challenge(), add_sdp(), agent_new(), agi_handle_command(), ast_lock_path_lockfile(), ast_moh_files_next(), ast_rtp_change_source(), ast_rtp_new(), ast_udptl_new_with_bindaddr(), authenticate_request(), build_iv(), build_rand_pad(), build_reply_digest(), calc_metric(), calc_rxstamp(), caldav_write_event(), callno_hash(), create_channel_name(), generate_exchange_uuid(), generate_random_string(), get_trans_id(), gtalk_alloc(), gtalk_create_candidates(), gtalk_new(), handle_incoming(), handle_response_invite(), iax2_key_rotate(), iax2_start_transfer(), jingle_alloc(), jingle_create_candidates(), jingle_new(), load_module(), local_new(), make_email_file(), make_our_tag(), moh_files_alloc(), multicast_rtp_new(), ogg_vorbis_rewrite(), osp_create_uuid(), page_exec(), park_space_reserve(), process_weights(), reg_source_db(), registry_authrequest(), reqprep(), say_periodic_announcement(), sendmail(), set_nonce_randdata(), sip_alloc(), socket_read(), start_rtp(), stun_req_id(), transmit_invite(), transmit_register(), transmit_response_using_temp(), and try_firmware().

01405 {
01406    long int res;
01407 #ifdef HAVE_DEV_URANDOM
01408    if (dev_urandom_fd >= 0) {
01409       int read_res = read(dev_urandom_fd, &res, sizeof(res));
01410       if (read_res > 0) {
01411          long int rm = RAND_MAX;
01412          res = res < 0 ? ~res : res;
01413          rm++;
01414          return res % rm;
01415       }
01416    }
01417 #endif
01418 #ifdef linux
01419    res = random();
01420 #else
01421    ast_mutex_lock(&randomlock);
01422    res = random();
01423    ast_mutex_unlock(&randomlock);
01424 #endif
01425    return res;
01426 }

void ast_register_thread ( char *  name  ) 

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

00387 { 
00388    struct thread_list_t *new = ast_calloc(1, sizeof(*new));
00389 
00390    if (!new)
00391       return;
00392    new->id = pthread_self();
00393    new->name = name; /* steal the allocated memory for the thread name */
00394    AST_RWLIST_WRLOCK(&thread_list);
00395    AST_RWLIST_INSERT_HEAD(&thread_list, new, list);
00396    AST_RWLIST_UNLOCK(&thread_list);
00397 }

void ast_set_default_eid ( struct ast_eid eid  ) 

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

Since:
1.6.1

Definition at line 235 of file netsock.c.

References ast_debug, ast_eid_to_str(), and ast_eid::eid.

Referenced by ast_readconfig().

00236 {
00237 #if defined(SIOCGIFHWADDR) && defined(HAVE_STRUCT_IFREQ_IFR_IFRU_IFRU_HWADDR)
00238    int s, x = 0;
00239    char eid_str[20];
00240    struct ifreq ifr;
00241 
00242    s = socket(AF_INET, SOCK_STREAM, 0);
00243    if (s < 0)
00244       return;
00245    for (x = 0; x < 10; x++) {
00246       memset(&ifr, 0, sizeof(ifr));
00247       snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "eth%d", x);
00248       if (ioctl(s, SIOCGIFHWADDR, &ifr))
00249          continue;
00250       memcpy(eid, ((unsigned char *)&ifr.ifr_hwaddr) + 2, sizeof(*eid));
00251       ast_debug(1, "Seeding global EID '%s' from '%s' using 'siocgifhwaddr'\n", ast_eid_to_str(eid_str, sizeof(eid_str), eid), ifr.ifr_name);
00252       close(s);
00253       return;
00254    }
00255    close(s);
00256 #else
00257 #if defined(ifa_broadaddr) && !defined(SOLARIS)
00258    char eid_str[20];
00259    struct ifaddrs *ifap;
00260    
00261    if (getifaddrs(&ifap) == 0) {
00262       struct ifaddrs *p;
00263       for (p = ifap; p; p = p->ifa_next) {
00264          if ((p->ifa_addr->sa_family == AF_LINK) && !(p->ifa_flags & IFF_LOOPBACK) && (p->ifa_flags & IFF_RUNNING)) {
00265             struct sockaddr_dl* sdp = (struct sockaddr_dl*) p->ifa_addr;
00266             memcpy(&(eid->eid), sdp->sdl_data + sdp->sdl_nlen, 6);
00267             ast_debug(1, "Seeding global EID '%s' from '%s' using 'getifaddrs'\n", ast_eid_to_str(eid_str, sizeof(eid_str), eid), p->ifa_name);
00268             freeifaddrs(ifap);
00269             return;
00270          }
00271       }
00272       freeifaddrs(ifap);
00273    }
00274 #endif
00275 #endif
00276    ast_debug(1, "No ethernet interface found for seeding global EID. You will have to set it manually.\n");
00277 }

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

Produces SHA1 hash based on input string.

Definition at line 247 of file utils.c.

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

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

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

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

Definition at line 276 of file utils.h.

Referenced by ast_frame_slinear_sum(), audio_audiohook_write_list(), and softmix_bridge_thread().

00277 {
00278    int res;
00279 
00280    res = (int) *input + *value;
00281    if (res > 32767)
00282       *input = 32767;
00283    else if (res < -32767)
00284       *input = -32767;
00285    else
00286       *input = (short) res;
00287 }

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

Definition at line 315 of file utils.h.

Referenced by ast_frame_adjust_volume(), and audiohook_read_frame_both().

00316 {
00317    *input /= *value;
00318 }

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

Definition at line 302 of file utils.h.

Referenced by ast_frame_adjust_volume(), and audiohook_read_frame_both().

00303 {
00304    int res;
00305 
00306    res = (int) *input * *value;
00307    if (res > 32767)
00308       *input = 32767;
00309    else if (res < -32767)
00310       *input = -32767;
00311    else
00312       *input = (short) res;
00313 }

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

Definition at line 289 of file utils.h.

Referenced by softmix_bridge_thread().

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

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

Convert a string into an EID.

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

Returns:
0 success, non-zero failure
Since:
1.6.1

Definition at line 279 of file netsock.c.

References ast_eid::eid.

Referenced by aji_handle_pubsub_event(), dundi_do_query(), and set_config().

00280 {
00281    unsigned int eid_int[6];
00282    int x;
00283 
00284    if (sscanf(s, "%2x:%2x:%2x:%2x:%2x:%2x", &eid_int[0], &eid_int[1], &eid_int[2],
00285        &eid_int[3], &eid_int[4], &eid_int[5]) != 6)
00286          return -1;
00287    
00288    for (x = 0; x < 6; x++)
00289       eid->eid[x] = eid_int[x];
00290 
00291    return 0;
00292 }

void ast_unregister_thread ( void *  id  ) 

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

00400 {
00401    struct thread_list_t *x;
00402 
00403    AST_RWLIST_WRLOCK(&thread_list);
00404    AST_RWLIST_TRAVERSE_SAFE_BEGIN(&thread_list, x, list) {
00405       if ((void *) x->id == id) {
00406          AST_RWLIST_REMOVE_CURRENT(list);
00407          break;
00408       }
00409    }
00410    AST_RWLIST_TRAVERSE_SAFE_END;
00411    AST_RWLIST_UNLOCK(&thread_list);
00412    if (x) {
00413       ast_free(x->name);
00414       ast_free(x);
00415    }
00416 }

void ast_uri_decode ( char *  s  ) 

Decode URI, URN, URL (overwrite string).

Parameters:
s String to be decoded

Definition at line 417 of file utils.c.

Referenced by acf_curl_helper(), config_curl(), get_destination(), get_refer_info(), handle_request_invite(), http_decode(), parse_moved_contact(), realtime_curl(), realtime_multi_curl(), sip_new(), and uridecode().

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

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

Turn text string to URI-encoded XX version.

Note:
At this point, this function is encoding agnostic; it does not check whether it is fed legal UTF-8. We escape control characters (-), '', and all characters above 0x7F. If do_special_char == 1 we will convert all characters except alnum and mark. 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.

Definition at line 384 of file utils.c.

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

00385 {
00386    const char *ptr  = string; /* Start with the string */
00387    char *out = outbuf;
00388    const char *mark = "-_.!~*'()"; /* no encode set, RFC 2396 section 2.3, RFC 3261 sec 25 */
00389 
00390    while (*ptr && out - outbuf < buflen - 1) {
00391       if ((const signed char) *ptr < 32 || *ptr == 0x7f || *ptr == '%' ||
00392             (do_special_char &&
00393             !(*ptr >= '0' && *ptr <= '9') &&      /* num */
00394             !(*ptr >= 'A' && *ptr <= 'Z') &&      /* ALPHA */
00395             !(*ptr >= 'a' && *ptr <= 'z') &&      /* alpha */
00396             !strchr(mark, *ptr))) {               /* mark set */
00397          if (out - outbuf >= buflen - 3) {
00398             break;
00399          }
00400 
00401          out += sprintf(out, "%%%02X", (unsigned char) *ptr);
00402       } else {
00403          *out = *ptr;   /* Continue copying the string */
00404          out++;
00405       }
00406       ptr++;
00407    }
00408 
00409    if (buflen) {
00410       *out = '\0';
00411    }
00412 
00413    return outbuf;
00414 }

int ast_utils_init ( void   ) 

Definition at line 1935 of file utils.c.

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

Referenced by main().

01936 {
01937 #ifdef HAVE_DEV_URANDOM
01938    dev_urandom_fd = open("/dev/urandom", O_RDONLY);
01939 #endif
01940    base64_init();
01941 #ifdef DEBUG_THREADS
01942 #if !defined(LOW_MEMORY)
01943    ast_cli_register_multiple(utils_cli, ARRAY_LEN(utils_cli));
01944 #endif
01945 #endif
01946    return 0;
01947 }

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

References ast_strdupa, and strsep().

Referenced by ast_bt_get_symbols().

02086 {
02087    const char *envPATH = getenv("PATH");
02088    char *tpath, *path;
02089    struct stat unused;
02090    if (!envPATH) {
02091       return NULL;
02092    }
02093    tpath = ast_strdupa(envPATH);
02094    while ((path = strsep(&tpath, ":"))) {
02095       snprintf(fullpath, fullpath_size, "%s/%s", path, binary);
02096       if (!stat(fullpath, &unused)) {
02097          return fullpath;
02098       }
02099    }
02100    return NULL;
02101 }

int ast_wait_for_input ( int  fd,
int  ms 
)

Definition at line 1054 of file utils.c.

References ast_poll.

Referenced by ast_tcptls_server_root(), dahdi_test_timer(), and moh_class_destructor().

01055 {
01056    struct pollfd pfd[1];
01057    memset(pfd, 0, sizeof(pfd));
01058    pfd[0].fd = fd;
01059    pfd[0].events = POLLIN|POLLPRI;
01060    return ast_poll(pfd, 1, ms);
01061 }


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

struct ast_eid ast_eid_default

Global EID.

This is set in asterisk.conf, or determined automatically by taking the mac address of an Ethernet interface on the system.

Definition at line 188 of file asterisk.c.

Referenced by aji_devstate_cb(), aji_handle_pubsub_event(), aji_mwi_cb(), aji_publish_device_state(), aji_publish_mwi(), ast_event_append_eid(), ast_event_cb(), ast_readconfig(), ast_str_retrieve_variable(), evt_event_deliver_cb(), handle_show_settings(), and set_config().


Generated on Wed Apr 6 11:30:11 2011 for Asterisk - The Open Source Telephony Project by  doxygen 1.4.7