Sat Apr 26 2014 22:03:20

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"
Include dependency graph for utils.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)   (size_t) (sizeof(a) / sizeof(0[a]))
#define ast_align_for(offset, type)   (((offset + __alignof__(type) - 1) / __alignof__(type)) * __alignof__(type))
 Increase offset so it is a multiple of the required alignment of type.
#define ast_alignof(type)   __alignof__(type)
 Return the number of bytes used in the alignment of type.
#define ast_alloca(size)   __builtin_alloca(size)
 call __builtin_alloca to ensure we get gcc builtin semantics
#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_make_room_for(offset, type)   (((offset + (2 * __alignof__(type) - 1)) / __alignof__(type)) * __alignof__(type))
 Increase offset by the required alignment of type and make sure it is a multiple of said alignment.
#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_std_calloc   calloc
#define ast_std_free   free
#define ast_std_malloc   malloc
#define ast_std_realloc   realloc
#define ast_strdup(str)   _ast_strdup((str), __FILE__, __LINE__, __PRETTY_FUNCTION__)
 A wrapper for strdup()
#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_URI_ALPHANUM   (1 << 0)
#define AST_URI_LEGACY_SPACE   (1 << 2)
#define AST_URI_MARK   (1 << 1)
#define AST_URI_SIP_USER_UNRESERVED   (1 << 20)
#define AST_URI_UNRESERVED   (AST_URI_ALPHANUM | AST_URI_MARK)
#define 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);})
#define SWAP(a, b)   do { typeof(a) __tmp = (a); (a) = (b); (b) = __tmp; } while (0)

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.
void ast_do_crash (void)
 Force a crash if DO_CRASH is defined.
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)
 Convert an EID to a string.
void ast_enable_packet_fragmentation (int sock)
 Disable PMTU discovery on a socket.
char * ast_escape_quoted (const char *string, char *outbuf, int buflen)
 Escape characters found in a quoted string.
int ast_get_tid (void)
 Get current thread ID.
struct 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_replace_subargument_delimiter (char *s)
 Replace '^' in a string with ','.
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.
void ast_sha1_hash_uint (uint8_t *digest, const char *input)
 Produces SHA1 hash based on input string, stored in uint8_t array.
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, struct ast_flags spec)
 Decode URI, URN, URL (overwrite string)
char * ast_uri_encode (const char *string, char *outbuf, int buflen, struct ast_flags spec)
 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)
int ast_xml_escape (const char *string, char *outbuf, size_t buflen)
 Escape reserved characters for use in XML.

Variables

unsigned int __unsigned_int_flags_dummy
uint64_t __unsigned_int_flags_dummy64
struct ast_eid ast_eid_default
 Global EID.
struct ast_flags ast_uri_http
struct ast_flags ast_uri_http_legacy
struct ast_flags ast_uri_sip_user

Detailed Description

Utility functions.

Definition in file utils.h.


Define Documentation

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

Definition at line 712 of file utils.h.

#define ast_align_for (   offset,
  type 
)    (((offset + __alignof__(type) - 1) / __alignof__(type)) * __alignof__(type))

Increase offset so it is a multiple of the required alignment of type.

Parameters:
offsetThe value that should be increased.
typeThe data type that offset should be aligned to.
Returns:
The smallest multiple of alignof(type) larger than or equal to offset.
See also:
ast_make_room_for()

Many systems prefer integers to be stored on aligned on memory locations. This macro will increase an offset so a value of the supplied type can be safely be stored on such a memory location.

Examples: ast_align_for(0x17, int64_t) ==> 0x18 ast_align_for(0x18, int64_t) ==> 0x18 ast_align_for(0x19, int64_t) ==> 0x20

Don't mind the ugliness, the compiler will optimize it.

Definition at line 793 of file utils.h.

Referenced by __ast_string_field_ptr_build_va().

#define ast_alignof (   type)    __alignof__(type)

Return the number of bytes used in the alignment of type.

Parameters:
type
Returns:
The number of bytes required for alignment.

This is really just __alignof__(), but tucked away in this header so we don't have to look at the nasty underscores in the source.

Definition at line 773 of file utils.h.

Referenced by __ast_string_field_alloc_space(), and __ast_string_field_ptr_build_va().

#define ast_alloca (   size)    __builtin_alloca(size)

call __builtin_alloca to ensure we get gcc builtin semantics

Parameters:
sizeThe size of the buffer we want allocated

This macro will attempt to allocate memory from the stack. If it fails you won't get a NULL returned, but a SEGFAULT if you're lucky.

Definition at line 666 of file utils.h.

Referenced by __analog_handle_event(), _while_exec(), ael2_semantic_check(), aji_start_sasl(), alsa_card_init(), append_mailbox(), ast_dsp_process(), ast_dsp_silence_noise_with_energy(), ast_event_append_ie_str(), ast_event_check_subscriber(), ast_event_new(), ast_fileexists(), ast_lock_path_flock(), ast_lock_path_lockfile(), ast_mkdir(), ast_openstream_full(), ast_openvstream(), ast_pthread_create_detached_stack(), ast_pthread_create_stack(), ast_remotecontrol(), ast_say_counted_adjective(), ast_say_counted_noun(), ast_unlock_path_flock(), ast_unlock_path_lockfile(), ast_waitfor_nandfds(), ast_websocket_write(), ast_writefile(), astman_append_json(), builtin_automixmonitor(), builtin_automonitor(), callerid_feed(), callerid_feed_jp(), CB_ADD_LEN(), config_module(), control_streamfile(), cpeid_exec(), create_addr_from_peer(), cut_internal(), dahdi_r2_on_call_disconnect(), db_open(), decode_frame(), dictate_exec(), dundi_decrypt(), dundi_encrypt(), dundi_precache_internal(), encrypt_frame(), feature_request_and_dial(), festival_exec(), filename_parse(), find_table(), func_mchan_read(), function_fieldnum_helper(), function_fieldqty_helper(), handle_cli_config_reload(), handle_command_response(), handle_exec(), handle_incoming(), handle_statechange(), import_helper(), inprocess_count(), jingle_action_session_terminate(), listfilter(), local_attended_transfer(), lua_get_variable(), lua_get_variable_value(), lua_read_extensions_file(), masquerade_colp_transfer(), my_ast_get_channel_by_name_locked(), pbx_builtin_importvar(), pbx_load_module(), pbx_substitute_variables_helper_full(), pri_queue_pvt_cause_data(), queue_file(), realtime_exec(), replace(), shared_read(), shared_write(), shift_pop(), sip_addheader(), sms_generate(), socket_process_helper(), sort_internal(), ss7_queue_pvt_cause_data(), ssl_write(), state_notify_build_xml(), static_callback(), strreplace(), try_firmware(), unshift_push(), vm_change_password(), vm_delete(), vm_msg_forward(), vm_msg_move(), vm_msg_remove(), vm_play_folder_name_gr(), and websocket_callback().

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

Definition at line 411 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 510 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 535 of file utils.h.

#define ast_clear_flag (   p,
  flag 
)

Definition at line 77 of file utils.h.

Referenced by __analog_ss_thread(), __ast_pbx_run(), __ast_read(), __do_deliver(), __transmit_response(), action_redirect(), aji_create_client(), aji_filter_roster(), aji_load_config(), analog_ss_thread(), app_exec(), 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_do_masquerade(), ast_generic_bridge(), ast_jb_destroy(), ast_jb_put(), ast_readconfig(), ast_rtp_raw_write(), ast_sendtext(), ast_settimeout_full(), ast_speech_start(), ast_tls_read_conf(), ast_translate(), 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_for_nat(), check_goto_on_transfer(), check_pendings(), common_exec(), config_function_read(), config_text_file_load(), dahdi_read(), dahdiscan_exec(), dial_exec_full(), dictate_exec(), disa_exec(), dundi_lookup_local(), extenspy_exec(), forward_message(), handle_command_response(), handle_common_options(), handle_debug(), handle_exec(), handle_request_bye(), handle_request_invite(), handle_request_refer(), handle_response(), handle_response_notify(), handle_speechrecognize(), handle_t38_options(), init_acf_query(), initialize_udptl(), internal_deactivate_generator(), linear_alloc(), load_config(), load_module(), load_moh_classes(), local_ast_moh_stop(), local_attended_transfer(), local_hangup(), main(), manage_parked_call(), 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(), set_peer_nat(), setup_dahdi_int(), sip_call(), sip_dtmfmode(), sip_hangup(), sip_parse_nat_option(), sip_reload(), sip_set_rtp_peer(), socket_process_helper(), speech_background(), try_calling(), update_call_counter(), update_connectedline(), and waitstream_core().

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

#define ast_free_ptr   ast_free

Definition at line 475 of file utils.h.

#define ast_make_room_for (   offset,
  type 
)    (((offset + (2 * __alignof__(type) - 1)) / __alignof__(type)) * __alignof__(type))

Increase offset by the required alignment of type and make sure it is a multiple of said alignment.

Parameters:
offsetThe value that should be increased.
typeThe data type that room should be reserved for.
Returns:
The smallest multiple of alignof(type) larger than or equal to offset plus alignof(type).
See also:
ast_align_for()

A use case for this is when prepending length fields of type int to a buffer. If you keep the offset a multiple of the alignment of the integer type, a next block of length+buffer will have the length field automatically aligned.

Examples: ast_make_room_for(0x17, int64_t) ==> 0x20 ast_make_room_for(0x18, int64_t) ==> 0x20 ast_make_room_for(0x19, int64_t) ==> 0x28

Don't mind the ugliness, the compiler will optimize it.

Definition at line 816 of file utils.h.

Referenced by __ast_string_field_alloc_space(), and __ast_string_field_ptr_build_va().

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

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

#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_iax2_new(), ast_jb_do_usecheck(), ast_jb_put(), ast_pbx_h_exten_run(), ast_readconfig(), ast_rtp_change_source(), ast_rtp_local_bridge(), ast_rtp_raw_write(), ast_rtp_read(), ast_rtp_stop(), ast_rtp_update_source(), ast_settimeout_full(), 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(), cc_generic_agent_init(), change_hold_state(), change_spy_mode(), channel_spy(), chanspy_exec(), check_bridge(), check_for_nat(), check_peer_ok(), check_user_full(), check_via(), common_exec(), create_addr_from_peer(), create_transaction(), dahdi_new(), dahdiscan_exec(), destroy_trans(), dial_exec_full(), dictate_exec(), directory_exec(), disa_exec(), do_register(), dundi_encrypt(), dundi_lookup_local(), dundi_send(), extensionstate_update(), extenspy_exec(), find_user_realtime(), free_vm_users(), gosub_run(), handle_command_response(), handle_common_options(), handle_debug(), handle_exec(), handle_gosub(), handle_invite_replaces(), handle_queue_reload(), handle_request_invite(), handle_request_refer(), handle_request_subscribe(), handle_response(), handle_response_invite(), handle_t38_options(), init_acf_query(), init_app_class(), init_files_class(), interpret_t38_parameters(), launch_monitor_thread(), leave_voicemail(), linear_alloc(), load_config(), load_moh_classes(), local_alloc(), local_ast_moh_start(), local_attended_transfer(), local_call(), local_new(), login_exec(), main(), manage_parked_call(), manager_queue_reload(), manager_sipnotify(), minivm_greet_exec(), new_outgoing(), nocdr_exec(), odbc_load_module(), park_call_full(), parked_call_exec(), parse_options(), playtones_alloc(), post_cdr(), process_applicationmap_line(), process_cn_rfc3389(), process_crypto(), process_sdp(), qualify_peer(), record_exec(), register_verify(), reload_config(), sdp_crypto_process(), set_bridge_features_on_config(), set_config_flags(), set_insecure_flags(), set_peer_nat(), sip_answer(), sip_call(), sip_cc_agent_init(), sip_cc_agent_respond(), sip_cc_monitor_request_cc(), sip_cli_notify(), sip_dtmfmode(), sip_find_peer_full(), sip_hangup(), sip_indicate(), sip_msg_send(), sip_new(), sip_park_thread(), sip_parse_nat_option(), 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_helper(), start_spying(), t38_tx_packet_handler(), tonepair_alloc(), transmit_publish(), transmit_register(), transmit_reinvite_with_sdp(), try_calling(), update_call_counter(), update_connectedline(), vm_execmain(), volume_write(), waitstream_core(), and xmpp_config_alloc().

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

Referenced by ast_pthread_create_stack().

#define ast_std_calloc   calloc

Definition at line 464 of file utils.h.

#define ast_std_free   free

Definition at line 466 of file utils.h.

#define ast_std_malloc   malloc

Definition at line 463 of file utils.h.

#define ast_std_realloc   realloc

Definition at line 465 of file utils.h.

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

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

#define ast_test_flag (   p,
  flag 
)

Definition at line 63 of file utils.h.

Referenced by __ast_channel_masquerade(), __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_one(), acf_odbc_read(), action_confbridgelist_item(), action_kick_last(), action_login(), action_toggle_mute_participants(), 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_end_dtmf(), ast_bridge_merge(), ast_call(), ast_can_pickup(), ast_cdr_answer(), ast_cdr_appenduserfield(), ast_cdr_busy(), ast_cdr_congestion(), 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_channel_destructor(), 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_pbx_h_exten_run(), ast_pbx_run_args(), ast_pbx_start(), ast_quiet_chan(), ast_raw_answer(), ast_readstring_full(), ast_rtp_raw_write(), ast_sendtext(), ast_setstate(), ast_settimeout_full(), ast_softhangup_nolock(), ast_streamfile(), AST_TEST_DEFINE(), ast_transfer(), ast_translate(), ast_uri_decode(), ast_uri_encode(), ast_waitfordigit_full(), ast_write(), attempt_thread(), 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(), call_forward_inherit(), callback_dialoptions(), cdr_read(), cdr_write(), change_hold_state(), channel_data_add_flags(), channel_spy(), chanspy_exec(), check_bridge(), check_for_nat(), check_peer_ok(), check_pendings(), check_post(), check_rtp_timeout(), check_user_full(), close_mailbox(), comedia_string(), common_exec(), complete_sip_peer(), complete_sip_registered_peer(), conf_handle_inactive_waitmarked(), conf_handle_only_unmarked(), conf_handle_second_active(), conf_mute_only_active(), conf_update_user_mute(), confbridge_exec(), config_text_file_load(), connectedline_write(), controlplayback_exec(), copy_via_headers(), create_addr_from_peer(), create_jb(), destroy_trans(), dialog_initialize_rtp(), dictate_exec(), directory_exec(), disa_exec(), display_nat_warning(), 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(), execute_menu_entry(), expire_register(), extensionstate_update(), extenspy_exec(), fax_gateway_framehook(), feature_exec_app(), feature_interpret_helper(), find_cache(), find_or_create(), find_user(), find_user_realtime(), findmeexec(), force_rport_string(), forkcdr_exec(), forward_message(), free_user(), func_confbridge_info(), function_sippeer(), get_crypto_attrib(), get_destination(), get_insecure_variable_from_config(), get_insecure_variable_from_sipregs(), get_rpid(), get_sdp_rtp_profile(), get_sip_pvt_byid_locked(), gosub_exec(), gosub_run(), handle_cli_moh_show_classes(), handle_cli_wait_fullybooted(), handle_command_response(), handle_conf_user_join(), handle_conf_user_leave(), handle_exec(), handle_frame(), handle_gosub(), handle_incoming(), handle_minivm_show_settings(), handle_options(), handle_request_bye(), handle_request_cancel(), handle_request_info(), handle_request_invite(), handle_request_refer(), handle_request_subscribe(), handle_response(), handle_response_invite(), handle_response_message(), handle_response_notify(), handle_show_settings(), handle_showchan(), handle_skinny_show_settings(), handle_speechrecognize(), handle_tcptls_connection(), handle_video_on_exit(), handle_video_on_join(), hint_read(), hook_event_cb(), iax2_write(), initialize_udptl(), initreqprep(), interpret_t38_parameters(), is_state_change_valid(), join_conference_bridge(), leave_voicemail(), load_resource(), local_alloc(), local_ast_moh_start(), local_bridgedchannel(), local_call(), local_devicestate(), local_hangup(), local_indicate(), local_write(), main(), make_email_file(), manager_list_voicemail_users(), manager_mixmonitor(), masq_park_call(), match_nat_options(), match_req_to_dialog(), minivm_accmess_exec(), minivm_account_func_read(), minivm_greet_exec(), minivm_notify_exec(), minivm_record_exec(), mixmonitor_exec(), mixmonitor_save_prep(), mixmonitor_thread(), mod_load_cmp(), moh_files_alloc(), moh_scan_files(), multicast_rtp_write(), notify_new_message(), odbc_load_module(), page_exec(), park_call_exec(), park_call_full(), park_space_reserve(), parse_moved_contact(), parse_register_contact(), pbx_builtin_background(), pbx_builtin_waitexten(), peer_ipcmp_cb_full(), pick_unlocked_cdr(), play_mailbox_owner(), play_message(), play_record_review(), post_cdr(), precache_transactions(), process_cn_rfc3389(), process_crypto(), process_sdp(), process_sdp_a_audio(), process_sdp_o(), process_text_line(), queue_exec(), read_exec(), readexten_exec(), realtime_peer(), realtime_switch_common(), receivefax_exec(), record_exec(), redirecting_write(), reload_config(), reload_handler(), reload_queues(), reload_single_queue(), remote_bridge_loop(), remove_from_queue(), reqprep(), respprep(), retrans_pkt(), retrydial_exec(), return_exec(), 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_peer_nat(), set_pvt_allowed_methods(), set_t38_capabilities(), setup_profile_bridge(), setup_profile_caller(), setup_profile_paged(), should_skip_dtmf(), show_channels_cb(), sig_pri_call(), sip_alloc(), sip_allow_anyrtp_remote(), sip_answer(), sip_call(), sip_cc_agent_destructor(), sip_destroy_peer(), sip_dtmfmode(), sip_fixup(), sip_get_rtp_peer(), sip_get_trtp_peer(), sip_get_udptl_peer(), sip_get_vrtp_peer(), sip_hangup(), sip_indicate(), sip_nat_mode(), sip_new(), sip_parse_nat_option(), sip_peer_hold(), sip_prune_realtime(), sip_queryoption(), sip_read(), sip_real_dst(), sip_request_call(), sip_rtp_read(), sip_send_mwi_to_peer(), sip_senddigit_begin(), sip_senddigit_end(), sip_sendhtml(), sip_set_rtp_peer(), sip_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_helper(), 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(), transmit_state_notify(), try_calling(), unistim_quiet_chan(), update_call_counter(), update_connectedline(), update_peer(), update_redirecting(), update_registry(), vm_exec(), vm_execmain(), vm_instructions_en(), vm_intro(), vm_newuser(), volume_callback(), wait_for_winner(), waitstream_core(), xfer_park_call_helper(), xmpp_action_hook(), xmpp_cli_purge_pubsub_nodes(), xmpp_client_authenticate(), xmpp_client_config_post_apply(), xmpp_client_reconnect(), xmpp_client_send_message(), xmpp_client_set_group_presence(), xmpp_client_thread(), xmpp_config_prelink(), xmpp_connect_hook(), xmpp_join_exec(), xmpp_leave_exec(), xmpp_log_hook(), xmpp_pak_message(), xmpp_pak_presence(), xmpp_pak_s10n(), xmpp_pubsub_build_publish_skeleton(), xmpp_pubsub_handle_error(), xmpp_pubsub_publish_device_state(), xmpp_pubsub_subscribe(), xmpp_roster_hook(), xmpp_send_stream_header(), and xmpp_sendgroup_exec().

#define ast_test_flag_nonstd (   p,
  flag 
)    ((p)->flags & (flag))
#define AST_URI_ALPHANUM   (1 << 0)

Definition at line 253 of file utils.h.

Referenced by ast_uri_encode().

#define AST_URI_LEGACY_SPACE   (1 << 2)

Definition at line 256 of file utils.h.

Referenced by ast_uri_decode(), and ast_uri_encode().

#define AST_URI_MARK   (1 << 1)

Definition at line 254 of file utils.h.

Referenced by ast_uri_encode().

#define AST_URI_SIP_USER_UNRESERVED   (1 << 20)

Definition at line 258 of file utils.h.

Referenced by ast_uri_encode().

Definition at line 255 of file utils.h.

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

#define localtime_r   __dont_use_localtime_r_use_ast_localtime_instead__

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

Referenced by _ast_asprintf().

#define MAX (   a,
 
)    ({ typeof(a) __a = (a); typeof(b) __b = (b); ((__a < __b) ? __b : __a);})
#define SWAP (   a,
 
)    do { typeof(a) __tmp = (a); (a) = (b); (b) = __tmp; } while (0)

Function Documentation

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

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

References MALLOC_FAILURE_MSG, and vasprintf.

{
   int res;
   va_list ap;

   va_start(ap, fmt);
   if ((res = vasprintf(ret, fmt, ap)) == -1) {
      MALLOC_FAILURE_MSG;
   }
   va_end(ap);

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

Definition at line 523 of file utils.h.

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

Definition at line 500 of file utils.h.

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

Definition at line 559 of file utils.h.

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

Definition at line 588 of file utils.h.

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

Definition at line 617 of file utils.h.

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

Definition at line 655 of file utils.h.

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

Decode data from base64.

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

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

Referenced by action_messagesend(), aes_helper(), ast_check_signature(), base64_helper(), custom_presence_callback(), h264_format_attr_sdp_parse(), osp_validate_token(), sdp_crypto_process(), and sdp_crypto_setup().

{
   int cnt = 0;
   unsigned int byte = 0;
   unsigned int bits = 0;
   int incnt = 0;
   while(*src && *src != '=' && (cnt < max)) {
      /* Shift in 6 bits of input */
      byte <<= 6;
      byte |= (b2a[(int)(*src)]) & 0x3f;
      bits += 6;
      src++;
      incnt++;
      /* If we have at least 8 bits left over, take that character
         off the top */
      if (bits >= 8)  {
         bits -= 8;
         *dst = (byte >> bits) & 0xff;
         dst++;
         cnt++;
      }
   }
   /* Don't worry about left over bits, they're extra anyway */
   return cnt;
}
int ast_base64encode ( char *  dst,
const unsigned char *  src,
int  srclen,
int  max 
)

Encode data in base64.

Parameters:
dstthe destination buffer
srcthe source data to be encoded
srclenthe number of bytes present in the source buffer
maxthe maximum number of bytes to write into the destination buffer, *including* the terminating NULL character.

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

References ast_base64encode_full().

Referenced by aes_helper(), aji_start_sasl(), ast_sign(), base64_helper(), build_secret(), h264_format_attr_sdp_generate(), osp_check_destination(), presence_read(), sdp_crypto_setup(), websocket_callback(), and xmpp_client_authenticate_sasl().

{
   return ast_base64encode_full(dst, src, srclen, max, 0);
}
int ast_base64encode_full ( char *  dst,
const unsigned char *  src,
int  srclen,
int  max,
int  linebreaks 
)

encode text to BASE64 coding

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

Referenced by ast_base64encode().

{
   int cnt = 0;
   int col = 0;
   unsigned int byte = 0;
   int bits = 0;
   int cntin = 0;
   /* Reserve space for null byte at end of string */
   max--;
   while ((cntin < srclen) && (cnt < max)) {
      byte <<= 8;
      byte |= *(src++);
      bits += 8;
      cntin++;
      if ((bits == 24) && (cnt + 4 <= max)) {
         *dst++ = base64[(byte >> 18) & 0x3f];
         *dst++ = base64[(byte >> 12) & 0x3f];
         *dst++ = base64[(byte >> 6) & 0x3f];
         *dst++ = base64[byte & 0x3f];
         cnt += 4;
         col += 4;
         bits = 0;
         byte = 0;
      }
      if (linebreaks && (cnt < max) && (col == 64)) {
         *dst++ = '\n';
         cnt++;
         col = 0;
      }
   }
   if (bits && (cnt + 4 <= max)) {
      /* Add one last character for the remaining bits,
         padding the rest with 0 */
      byte <<= 24 - bits;
      *dst++ = base64[(byte >> 18) & 0x3f];
      *dst++ = base64[(byte >> 12) & 0x3f];
      if (bits == 16)
         *dst++ = base64[(byte >> 6) & 0x3f];
      else
         *dst++ = '=';
      *dst++ = '=';
      cnt += 4;
   }
   if (linebreaks && (cnt < max)) {
      *dst++ = '\n';
      cnt++;
   }
   *dst = '\0';
   return cnt;
}
int ast_careful_fwrite ( FILE *  f,
int  fd,
const char *  s,
size_t  len,
int  timeoutms 
)

Write data to a file stream with a timeout.

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

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

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

Referenced by send_string().

{
   struct timeval start = ast_tvnow();
   int n = 0;
   int elapsed = 0;

   while (len) {
      if (ast_wait_for_output(fd, timeoutms - elapsed)) {
         /* poll returned a fatal error, so bail out immediately. */
         return -1;
      }

      /* Clear any errors from a previous write */
      clearerr(f);

      n = fwrite(src, 1, len, f);

      if (ferror(f) && errno != EINTR && errno != EAGAIN) {
         /* fatal error from fwrite() */
         if (!feof(f)) {
            /* Don't spam the logs if it was just that the connection is closed. */
            ast_log(LOG_ERROR, "fwrite() returned error: %s\n", strerror(errno));
         }
         n = -1;
         break;
      }

      /* Update for data already written to the socket */
      len -= n;
      src += n;

      elapsed = ast_tvdiff_ms(ast_tvnow(), start);
      if (elapsed >= timeoutms) {
         /* We've taken too long to write
          * This is only an error condition if we haven't finished writing. */
         n = len ? -1 : 0;
         break;
      }
   }

   while (fflush(f)) {
      if (errno == EAGAIN || errno == EINTR) {
         continue;
      }
      if (!feof(f)) {
         /* Don't spam the logs if it was just that the connection is closed. */
         ast_log(LOG_ERROR, "fflush() returned error: %s\n", strerror(errno));
      }
      n = -1;
      break;
   }

   return n < 0 ? -1 : 0;
}
int ast_carefulwrite ( int  fd,
char *  s,
int  len,
int  timeoutms 
)

Try to write string, but wait no more than ms milliseconds before timing out.

Note:
If you are calling ast_carefulwrite, it is assumed that you are calling it on a file descriptor that _DOES_ have NONBLOCK set. This way, there is only one system call made to do a write, unless we actually have a need to wait. This way, we get better performance.

Try to write string, but wait no more than ms milliseconds before timing out.

Note:
The code assumes that the file descriptor has NONBLOCK set, so there is only one system call made to do a write, unless we actually have a need to wait. This way, we get better performance. If the descriptor is blocking, all assumptions on the guaranteed detail do not apply anymore.

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

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

Referenced by ast_agi_send(), ast_cli(), and cleanup_module().

{
   struct timeval start = ast_tvnow();
   int res = 0;
   int elapsed = 0;

   while (len) {
      if (ast_wait_for_output(fd, timeoutms - elapsed)) {
         return -1;
      }

      res = write(fd, s, len);

      if (res < 0 && errno != EAGAIN && errno != EINTR) {
         /* fatal error from write() */
         ast_log(LOG_ERROR, "write() returned error: %s\n", strerror(errno));
         return -1;
      }

      if (res < 0) {
         /* It was an acceptable error */
         res = 0;
      }

      /* Update how much data we have left to write */
      len -= res;
      s += res;
      res = 0;

      elapsed = ast_tvdiff_ms(ast_tvnow(), start);
      if (elapsed >= timeoutms) {
         /* We've taken too long to write
          * This is only an error condition if we haven't finished writing. */
         res = len ? -1 : 0;
         break;
      }
   }

   return res;
}
void ast_do_crash ( void  )

Force a crash if DO_CRASH is defined.

Note:
If DO_CRASH is not defined then the function returns.
Returns:
Nothing

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

{
#if defined(DO_CRASH)
   abort();
   /*
    * Just in case abort() doesn't work or something else super
    * silly, and for Qwell's amusement.
    */
   *((int *) 0) = 0;
#endif   /* defined(DO_CRASH) */
}
void ast_enable_packet_fragmentation ( int  sock)

Disable PMTU discovery on a socket.

Parameters:
sockThe socket to manipulate
Returns:
Nothing

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

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

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

References ast_log(), and LOG_WARNING.

Referenced by ast_netsock_bindaddr(), and reload_config().

{
#if defined(HAVE_IP_MTU_DISCOVER)
   int val = IP_PMTUDISC_DONT;

   if (setsockopt(sock, IPPROTO_IP, IP_MTU_DISCOVER, &val, sizeof(val)))
      ast_log(LOG_WARNING, "Unable to disable PMTU discovery. Large UDP packets may fail to be delivered when sent from this socket.\n");
#endif /* HAVE_IP_MTU_DISCOVER */
}
char* ast_escape_quoted ( const char *  string,
char *  outbuf,
int  buflen 
)

Escape characters found in a quoted string.

Note:
This function escapes quoted characters based on the 'qdtext' set of allowed characters from RFC 3261 section 25.1.
Parameters:
stringstring to be escaped
outbufresulting escaped string
buflensize of output buffer
Returns:
a pointer to the escaped string

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

References string.

Referenced by initreqprep().

{
   const char *ptr  = string;
   char *out = outbuf;
   char *allow = "\t\v !"; /* allow LWS (minus \r and \n) and "!" */

   while (*ptr && out - outbuf < buflen - 1) {
      if (!(strchr(allow, *ptr))
         && !(*ptr >= '#' && *ptr <= '[') /* %x23 - %x5b */
         && !(*ptr >= ']' && *ptr <= '~') /* %x5d - %x7e */
         && !((unsigned char) *ptr > 0x7f)) {             /* UTF8-nonascii */

         if (out - outbuf >= buflen - 2) {
            break;
         }
         out += sprintf(out, "\\%c", (unsigned char) *ptr);
      } else {
         *out = *ptr;
         out++;
      }
      ptr++;
   }

   if (buflen) {
      *out = '\0';
   }

   return outbuf;
}
int ast_get_tid ( void  )

Get current thread ID.

Parameters:
None
Returns:
the ID if platform is supported, else -1

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

Referenced by ast_log_full(), and ast_register_thread().

{
   int ret = -1;
#if defined (__linux) && defined(SYS_gettid)
   ret = syscall(SYS_gettid); /* available since Linux 1.4.11 */
#elif defined(__sun)
   ret = pthread_self();
#elif defined(__APPLE__)
   ret = mach_thread_self();
   mach_port_deallocate(mach_task_self(), ret);
#elif defined(__FreeBSD__) && defined(HAVE_SYS_THR_H)
   long lwpid;
   thr_self(&lwpid); /* available since sys/thr.h creation 2003 */
   ret = lwpid;
#endif
   return ret;
}
struct hostent* ast_gethostbyname ( const char *  host,
struct ast_hostent hp 
) [read]

Thread-safe gethostbyname function to use in Asterisk.

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

References ast_hostent::buf, and ast_hostent::hp.

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

{
   int res;
   int herrno;
   int dots = 0;
   const char *s;
   struct hostent *result = NULL;
   /* Although it is perfectly legitimate to lookup a pure integer, for
      the sake of the sanity of people who like to name their peers as
      integers, we break with tradition and refuse to look up a
      pure integer */
   s = host;
   res = 0;
   while (s && *s) {
      if (*s == '.')
         dots++;
      else if (!isdigit(*s))
         break;
      s++;
   }
   if (!s || !*s) {
      /* Forge a reply for IP's to avoid octal IP's being interpreted as octal */
      if (dots != 3)
         return NULL;
      memset(hp, 0, sizeof(struct ast_hostent));
      hp->hp.h_addrtype = AF_INET;
      hp->hp.h_addr_list = (void *) hp->buf;
      hp->hp.h_addr = hp->buf + sizeof(void *);
      /* For AF_INET, this will always be 4 */
      hp->hp.h_length = 4;
      if (inet_pton(AF_INET, host, hp->hp.h_addr) > 0)
         return &hp->hp;
      return NULL;

   }
#ifdef HAVE_GETHOSTBYNAME_R_5
   result = gethostbyname_r(host, &hp->hp, hp->buf, sizeof(hp->buf), &herrno);

   if (!result || !hp->hp.h_addr_list || !hp->hp.h_addr_list[0])
      return NULL;
#else
   res = gethostbyname_r(host, &hp->hp, hp->buf, sizeof(hp->buf), &result, &herrno);

   if (res || !result || !hp->hp.h_addr_list || !hp->hp.h_addr_list[0])
      return NULL;
#endif
   return &hp->hp;
}
void ast_md5_hash ( char *  output,
const char *  input 
)

Produces MD5 hash based on input string.

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

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

Referenced by __init_manager(), auth_exec(), auth_http_callback(), build_reply_digest(), check_auth(), and md5().

{
   struct MD5Context md5;
   unsigned char digest[16];
   char *ptr;
   int x;

   MD5Init(&md5);
   MD5Update(&md5, (const unsigned char *) input, strlen(input));
   MD5Final(digest, &md5);
   ptr = output;
   for (x = 0; x < 16; x++)
      ptr += sprintf(ptr, "%2.2x", digest[x]);
}
int ast_mkdir ( const char *  path,
int  mode 
)

Recursively create directory path.

Parameters:
pathThe directory path to create
modeThe permissions with which to try to create the directory
Returns:
0 on success or an error code otherwise

Creates a directory path, creating parent directories as needed.

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

References ast_alloca, errno, and len().

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

{
   char *ptr;
   int len = strlen(path), count = 0, x, piececount = 0;
   char *tmp = ast_strdupa(path);
   char **pieces;
   char *fullpath = ast_alloca(len + 1);
   int res = 0;

   for (ptr = tmp; *ptr; ptr++) {
      if (*ptr == '/')
         count++;
   }

   /* Count the components to the directory path */
   pieces = ast_alloca(count * sizeof(*pieces));
   for (ptr = tmp; *ptr; ptr++) {
      if (*ptr == '/') {
         *ptr = '\0';
         pieces[piececount++] = ptr + 1;
      }
   }

   *fullpath = '\0';
   for (x = 0; x < piececount; x++) {
      /* This looks funky, but the buffer is always ideally-sized, so it's fine. */
      strcat(fullpath, "/");
      strcat(fullpath, pieces[x]);
      res = mkdir(fullpath, mode);
      if (res && errno != EEXIST)
         return errno;
   }
   return 0;
}
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 2200 of file main/utils.c.

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

Referenced by auth_http_callback().

                                                                                               {
   char *c;
   struct ast_str *str = ast_str_create(16);

   /* table of recognised keywords, and places where they should be copied */
   const struct x {
      const char *key;
      const ast_string_field *field;
   } *i, keys[] = {
      { "username=", &d->username },
      { "realm=", &d->realm },
      { "nonce=", &d->nonce },
      { "uri=", &d->uri },
      { "domain=", &d->domain },
      { "response=", &d->response },
      { "cnonce=", &d->cnonce },
      { "opaque=", &d->opaque },
      /* Special cases that cannot be directly copied */
      { "algorithm=", NULL },
      { "qop=", NULL },
      { "nc=", NULL },
      { NULL, 0 },
   };

   if (ast_strlen_zero(digest) || !d || !str) {
      ast_free(str);
      return -1;
   }

   ast_str_set(&str, 0, "%s", digest);

   c = ast_skip_blanks(ast_str_buffer(str));

   if (strncasecmp(c, "Digest ", strlen("Digest "))) {
      ast_log(LOG_WARNING, "Missing Digest.\n");
      ast_free(str);
      return -1;
   }
   c += strlen("Digest ");

   /* lookup for keys/value pair */
   while (c && *c && *(c = ast_skip_blanks(c))) {
      /* find key */
      for (i = keys; i->key != NULL; i++) {
         char *src, *separator;
         int unescape = 0;
         if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
            continue;
         }

         /* Found. Skip keyword, take text in quotes or up to the separator. */
         c += strlen(i->key);
         if (*c == '"') {
            src = ++c;
            separator = "\"";
            unescape = 1;
         } else {
            src = c;
            separator = ",";
         }
         strsep(&c, separator); /* clear separator and move ptr */
         if (unescape) {
            ast_unescape_c(src);
         }
         if (i->field) {
            ast_string_field_ptr_set(d, i->field, src);
         } else {
            /* Special cases that require additional procesing */
            if (!strcasecmp(i->key, "algorithm=")) {
               if (strcasecmp(src, "MD5")) {
                  ast_log(LOG_WARNING, "Digest algorithm: \"%s\" not supported.\n", src);
                  ast_free(str);
                  return -1;
               }
            } else if (!strcasecmp(i->key, "qop=") && !strcasecmp(src, "auth")) {
               d->qop = 1;
            } else if (!strcasecmp(i->key, "nc=")) {
               unsigned long u;
               if (sscanf(src, "%30lx", &u) != 1) {
                  ast_log(LOG_WARNING, "Incorrect Digest nc value: \"%s\".\n", src);
                  ast_free(str);
                  return -1;
               }
               ast_string_field_set(d, nc, src);
            }
         }
         break;
      }
      if (i->key == NULL) { /* not found, try ',' */
         strsep(&c, ",");
      }
   }
   ast_free(str);

   /* Digest checkout */
   if (ast_strlen_zero(d->realm) || ast_strlen_zero(d->nonce)) {
      /* "realm" and "nonce" MUST be always exist */
      return -1;
   }

   if (!request) {
      /* Additional check for Digest response */
      if (ast_strlen_zero(d->username) || ast_strlen_zero(d->uri) || ast_strlen_zero(d->response)) {
         return -1;
      }

      if (pedantic && d->qop && (ast_strlen_zero(d->cnonce) || ast_strlen_zero(d->nc))) {
         return -1;
      }
   }

   return 0;
}
char* ast_process_quotes_and_slashes ( char *  start,
char  find,
char  replace_with 
)

Process a string to find and replace characters.

Parameters:
startThe string to analyze
findThe character to find
replace_withThe character that will replace the one we are looking for

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

{
   char *dataPut = start;
   int inEscape = 0;
   int inQuotes = 0;

   for (; *start; start++) {
      if (inEscape) {
         *dataPut++ = *start;       /* Always goes verbatim */
         inEscape = 0;
      } else {
         if (*start == '\\') {
            inEscape = 1;      /* Do not copy \ into the data */
         } else if (*start == '\'') {
            inQuotes = 1 - inQuotes;   /* Do not copy ' into the data */
         } else {
            /* Replace , with |, unless in quotes */
            *dataPut++ = inQuotes ? *start : ((*start == find) ? replace_with : *start);
         }
      }
   }
   if (start != dataPut)
      *dataPut = 0;
   return dataPut;
}
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 1219 of file main/utils.c.

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

{
   unsigned char attr_destroy = 0;
   int res;

   if (!attr) {
      attr = ast_alloca(sizeof(*attr));
      pthread_attr_init(attr);
      attr_destroy = 1;
   }

   if ((errno = pthread_attr_setdetachstate(attr, PTHREAD_CREATE_DETACHED)))
      ast_log(LOG_WARNING, "pthread_attr_setdetachstate: %s\n", strerror(errno));

   res = ast_pthread_create_stack(thread, attr, start_routine, data,
                                  stacksize, file, caller, line, start_fn);

   if (attr_destroy)
      pthread_attr_destroy(attr);

   return res;
}
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 1171 of file main/utils.c.

References ast_alloca, ast_asprintf, ast_log(), ast_malloc, AST_STACKSIZE, thr_arg::data, dummy_start(), errno, LOG_WARNING, thr_arg::name, pthread_create, and thr_arg::start_routine.

Referenced by ast_pthread_create_detached_stack().

{
#if !defined(LOW_MEMORY)
   struct thr_arg *a;
#endif

   if (!attr) {
      attr = ast_alloca(sizeof(*attr));
      pthread_attr_init(attr);
   }

#ifdef __linux__
   /* On Linux, pthread_attr_init() defaults to PTHREAD_EXPLICIT_SCHED,
      which is kind of useless. Change this here to
      PTHREAD_INHERIT_SCHED; that way the -p option to set realtime
      priority will propagate down to new threads by default.
      This does mean that callers cannot set a different priority using
      PTHREAD_EXPLICIT_SCHED in the attr argument; instead they must set
      the priority afterwards with pthread_setschedparam(). */
   if ((errno = pthread_attr_setinheritsched(attr, PTHREAD_INHERIT_SCHED)))
      ast_log(LOG_WARNING, "pthread_attr_setinheritsched: %s\n", strerror(errno));
#endif

   if (!stacksize)
      stacksize = AST_STACKSIZE;

   if ((errno = pthread_attr_setstacksize(attr, stacksize ? stacksize : AST_STACKSIZE)))
      ast_log(LOG_WARNING, "pthread_attr_setstacksize: %s\n", strerror(errno));

#if !defined(LOW_MEMORY)
   if ((a = ast_malloc(sizeof(*a)))) {
      a->start_routine = start_routine;
      a->data = data;
      start_routine = dummy_start;
      if (ast_asprintf(&a->name, "%-20s started at [%5d] %s %s()",
              start_fn, line, file, caller) < 0) {
         a->name = NULL;
      }
      data = a;
   }
#endif /* !LOW_MEMORY */

   return pthread_create(thread, attr, start_routine, data); /* We're in ast_pthread_create, so it's okay */
}
long int ast_random ( void  )

Definition at line 1631 of file main/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(), app_exec(), ast_lock_path_lockfile(), ast_moh_files_next(), ast_rtp_change_source(), ast_rtp_new(), ast_udptl_new_with_bindaddr(), auth_http_callback(), authenticate_request(), build_gateway(), build_iv(), build_localtag_registry(), build_nonce(), build_rand_pad(), build_reply_digest(), calc_metric(), calc_rxstamp(), caldav_write_event(), callno_hash(), create_channel_name(), generate_exchange_uuid(), generate_random_string(), generic_http_callback(), get_trans_id(), gtalk_alloc(), gtalk_create_candidates(), gtalk_new(), handle_incoming(), handle_response_invite(), iax2_key_rotate(), iax2_start_transfer(), jingle_add_ice_udp_candidates_to_transport(), jingle_alloc(), jingle_create_candidates(), jingle_new(), load_module(), 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(), rec_request(), reg_source_db(), registry_authrequest(), reqprep(), say_periodic_announcement(), sendmail(), sip_alloc(), socket_read(), start_rtp(), stun_req_id(), transmit_invite(), transmit_register(), transmit_response_using_temp(), try_calling(), and try_firmware().

{
   long int res;
#ifdef HAVE_DEV_URANDOM
   if (dev_urandom_fd >= 0) {
      int read_res = read(dev_urandom_fd, &res, sizeof(res));
      if (read_res > 0) {
         long int rm = RAND_MAX;
         res = res < 0 ? ~res : res;
         rm++;
         return res % rm;
      }
   }
#endif
#ifdef linux
   res = random();
#else
   ast_mutex_lock(&randomlock);
   res = random();
   ast_mutex_unlock(&randomlock);
#endif
   return res;
}
void ast_register_thread ( char *  name)

Definition at line 423 of file asterisk.c.

References ast_assert, ast_calloc, ast_get_tid(), AST_RWLIST_INSERT_HEAD, AST_RWLIST_UNLOCK, AST_RWLIST_WRLOCK, ast_atexit::list, multi_thread_safe, and name.

Referenced by dummy_start().

{
   struct thread_list_t *new = ast_calloc(1, sizeof(*new));

   if (!new)
      return;

   ast_assert(multi_thread_safe);
   new->id = pthread_self();
   new->lwp = ast_get_tid();
   new->name = name; /* steal the allocated memory for the thread name */
   AST_RWLIST_WRLOCK(&thread_list);
   AST_RWLIST_INSERT_HEAD(&thread_list, new, list);
   AST_RWLIST_UNLOCK(&thread_list);
}

Replace '^' in a string with ','.

Parameters:
sString within which to replace characters

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

Referenced by app_exec(), bridge_exec(), dial_exec_full(), and try_calling().

{
   for (; *s; s++) {
      if (*s == '^') {
         *s = ',';
      }
   }
}
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 226 of file netsock.c.

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

Referenced by ast_readconfig().

{
#if defined(SIOCGIFHWADDR) && defined(HAVE_STRUCT_IFREQ_IFR_IFRU_IFRU_HWADDR)
   int s, x = 0;
   char eid_str[20];
   struct ifreq ifr;
   static const unsigned int MAXIF = 10;

   s = socket(AF_INET, SOCK_STREAM, 0);
   if (s < 0)
      return;
   for (x = 0; x < MAXIF; x++) {
      static const char *prefixes[] = { "eth", "em" };
      unsigned int i;

      for (i = 0; i < ARRAY_LEN(prefixes); i++) {
         memset(&ifr, 0, sizeof(ifr));
         snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s%d", prefixes[i], x);
         if (!ioctl(s, SIOCGIFHWADDR, &ifr)) {
            break;
         }
      }

      if (i == ARRAY_LEN(prefixes)) {
         /* Try pciX#[1..N] */
         for (i = 0; i < MAXIF; i++) {
            memset(&ifr, 0, sizeof(ifr));
            snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "pci%u#%u", x, i);
            if (!ioctl(s, SIOCGIFHWADDR, &ifr)) {
               break;
            }
         }
         if (i == MAXIF) {
            continue;
         }
      }

      memcpy(eid, ((unsigned char *)&ifr.ifr_hwaddr) + 2, sizeof(*eid));
      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);
      close(s);
      return;
   }
   close(s);
#else
#if defined(ifa_broadaddr) && !defined(SOLARIS)
   char eid_str[20];
   struct ifaddrs *ifap;

   if (getifaddrs(&ifap) == 0) {
      struct ifaddrs *p;
      for (p = ifap; p; p = p->ifa_next) {
         if ((p->ifa_addr->sa_family == AF_LINK) && !(p->ifa_flags & IFF_LOOPBACK) && (p->ifa_flags & IFF_RUNNING)) {
            struct sockaddr_dl* sdp = (struct sockaddr_dl*) p->ifa_addr;
            memcpy(&(eid->eid), sdp->sdl_data + sdp->sdl_nlen, 6);
            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);
            freeifaddrs(ifap);
            return;
         }
      }
      freeifaddrs(ifap);
   }
#endif
#endif
   ast_debug(1, "No ethernet interface found for seeding global EID. You will have to set it manually.\n");
}
void ast_sha1_hash ( char *  output,
const char *  input 
)

Produces SHA1 hash based on input string.

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

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

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

{
   struct SHA1Context sha;
   char *ptr;
   int x;
   uint8_t Message_Digest[20];

   SHA1Reset(&sha);

   SHA1Input(&sha, (const unsigned char *) input, strlen(input));

   SHA1Result(&sha, Message_Digest);
   ptr = output;
   for (x = 0; x < 20; x++)
      ptr += sprintf(ptr, "%2.2x", Message_Digest[x]);
}
void ast_sha1_hash_uint ( uint8_t *  digest,
const char *  input 
)

Produces SHA1 hash based on input string, stored in uint8_t array.

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

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

Referenced by websocket_callback().

{
        struct SHA1Context sha;

        SHA1Reset(&sha);

        SHA1Input(&sha, (const unsigned char *) input, strlen(input));

        SHA1Result(&sha, digest);
}
static force_inline void ast_slinear_saturated_add ( short *  input,
short *  value 
) [static]

Definition at line 320 of file utils.h.

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

{
   int res;

   res = (int) *input + *value;
   if (res > 32767)
      *input = 32767;
   else if (res < -32768)
      *input = -32768;
   else
      *input = (short) res;
}
static force_inline void ast_slinear_saturated_divide ( short *  input,
short *  value 
) [static]

Definition at line 359 of file utils.h.

References value.

Referenced by ast_frame_adjust_volume(), and audiohook_read_frame_both().

{
   *input /= *value;
}
static force_inline void ast_slinear_saturated_multiply ( short *  input,
short *  value 
) [static]

Definition at line 346 of file utils.h.

Referenced by ast_frame_adjust_volume(), and audiohook_read_frame_both().

{
   int res;

   res = (int) *input * *value;
   if (res > 32767)
      *input = 32767;
   else if (res < -32768)
      *input = -32768;
   else
      *input = (short) res;
}
static force_inline void ast_slinear_saturated_subtract ( short *  input,
short *  value 
) [static]

Definition at line 333 of file utils.h.

Referenced by softmix_process_write_audio().

{
   int res;

   res = (int) *input - *value;
   if (res > 32767)
      *input = 32767;
   else if (res < -32768)
      *input = -32768;
   else
      *input = (short) res;
}
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 292 of file netsock.c.

References ast_eid::eid.

Referenced by aji_handle_pubsub_event(), ast_readconfig(), build_peer(), dundi_do_query(), set_config(), and xmpp_pubsub_handle_event().

{
   unsigned int eid_int[6];
   int x;

   if (sscanf(s, "%2x:%2x:%2x:%2x:%2x:%2x", &eid_int[0], &eid_int[1], &eid_int[2],
       &eid_int[3], &eid_int[4], &eid_int[5]) != 6)
         return -1;

   for (x = 0; x < 6; x++)
      eid->eid[x] = eid_int[x];

   return 0;
}
void ast_uri_decode ( char *  s,
struct ast_flags  spec 
)

Decode URI, URN, URL (overwrite string)

Note:
The ast_uri_http_legacy decode spec flag will cause this function to decode '+' as ' '.
Parameters:
sstring to be decoded
specflags describing how the decoding should be performed

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

References ast_test_flag, and AST_URI_LEGACY_SPACE.

Referenced by acf_curl_helper(), ast_http_get_post_vars(), config_curl(), get_destination(), get_name_and_number(), get_refer_info(), handle_request_invite(), handle_uri(), parse_moved_contact(), realtime_curl(), realtime_multi_curl(), sip_new(), sip_uri_cmp(), and uridecode().

{
   char *o;
   unsigned int tmp;

   for (o = s; *s; s++, o++) {
      if (ast_test_flag(&spec, AST_URI_LEGACY_SPACE) && *s == '+') {
         /* legacy mode, decode '+' as space */
         *o = ' ';
      } else if (*s == '%' && s[1] != '\0' && s[2] != '\0' && sscanf(s + 1, "%2x", &tmp) == 1) {
         /* have '%', two chars and correct parsing */
         *o = tmp;
         s += 2;  /* Will be incremented once more when we break out */
      } else /* all other cases, just copy */
         *o = *s;
   }
   *o = '\0';
}
char* ast_uri_encode ( const char *  string,
char *  outbuf,
int  buflen,
struct ast_flags  spec 
)

Turn text string to URI-encoded XX version.

This function encodes characters according to the rules presented in RFC 2396 and/or RFC 3261 section 19.1.2 and section 25.1.

Outbuf needs to have more memory allocated than the instring to have room for the expansion. Every byte that is converted is replaced by three ASCII characters.

Parameters:
stringstring to be converted
outbufresulting encoded string
buflensize of output buffer
specflags describing how the encoding should be performed
Returns:
a pointer to the uri encoded string

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

References ast_test_flag, AST_URI_ALPHANUM, AST_URI_LEGACY_SPACE, AST_URI_MARK, AST_URI_SIP_USER_UNRESERVED, and string.

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

{
   const char *ptr  = string; /* Start with the string */
   char *out = outbuf;
   const char *mark = "-_.!~*'()"; /* no encode set, RFC 2396 section 2.3, RFC 3261 sec 25 */
   const char *user_unreserved = "&=+$,;?/"; /* user-unreserved set, RFC 3261 sec 25 */

   while (*ptr && out - outbuf < buflen - 1) {
      if (ast_test_flag(&spec, AST_URI_LEGACY_SPACE) && *ptr == ' ') {
         /* for legacy encoding, encode spaces as '+' */
         *out = '+';
         out++;
      } else if (!(ast_test_flag(&spec, AST_URI_MARK)
            && strchr(mark, *ptr))
         && !(ast_test_flag(&spec, AST_URI_ALPHANUM)
            && ((*ptr >= '0' && *ptr <= '9')
            || (*ptr >= 'A' && *ptr <= 'Z')
            || (*ptr >= 'a' && *ptr <= 'z')))
         && !(ast_test_flag(&spec, AST_URI_SIP_USER_UNRESERVED)
            && strchr(user_unreserved, *ptr))) {

         if (out - outbuf >= buflen - 3) {
            break;
         }
         out += sprintf(out, "%%%02X", (unsigned char) *ptr);
      } else {
         *out = *ptr;   /* Continue copying the string */
         out++;
      }
      ptr++;
   }

   if (buflen) {
      *out = '\0';
   }

   return outbuf;
}
int ast_utils_init ( void  )

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

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

Referenced by main().

{
#ifdef HAVE_DEV_URANDOM
   dev_urandom_fd = open("/dev/urandom", O_RDONLY);
#endif
   base64_init();
#ifdef DEBUG_THREADS
#if !defined(LOW_MEMORY)
   ast_cli_register_multiple(utils_cli, ARRAY_LEN(utils_cli));
#endif
#endif
   ast_register_atexit(utils_shutdown);
   return 0;
}
char* ast_utils_which ( const char *  binary,
char *  fullpath,
size_t  fullpath_size 
)

Resolve a binary to a full pathname.

Parameters:
binaryName of the executable to resolve
fullpathBuffer to hold the complete pathname
fullpath_sizeSize of fullpath
Return values:
NULLbinary was not found or the environment variable PATH is not set
Returns:
fullpath

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

Referenced by ast_bt_get_symbols().

{
   const char *envPATH = getenv("PATH");
   char *tpath, *path;
   struct stat unused;
   if (!envPATH) {
      return NULL;
   }
   tpath = ast_strdupa(envPATH);
   while ((path = strsep(&tpath, ":"))) {
      snprintf(fullpath, fullpath_size, "%s/%s", path, binary);
      if (!stat(fullpath, &unused)) {
         return fullpath;
      }
   }
   return NULL;
}
int ast_wait_for_input ( int  fd,
int  ms 
)

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

References ast_poll.

Referenced by action_waitevent(), ast_tcptls_server_root(), dahdi_test_timer(), get_input(), moh_class_destructor(), sip_tcp_read(), sip_tls_read(), sip_websocket_callback(), websocket_echo_callback(), and ws_safe_read().

{
   struct pollfd pfd[1];
   memset(pfd, 0, sizeof(pfd));
   pfd[0].fd = fd;
   pfd[0].events = POLLIN|POLLPRI;
   return ast_poll(pfd, 1, ms);
}
int ast_xml_escape ( const char *  string,
char *  outbuf,
size_t  buflen 
)

Escape reserved characters for use in XML.

ast_xml_escape If outbuf is too short, the output string will be truncated. Regardless, the output will always be null terminated.

Parameters:
stringString to be converted
outbufResulting encoded string
buflenSize of output buffer
Returns:
0 for success
-1 if buflen is too short.

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

References ast_assert, entity, len(), and string.

Referenced by state_notify_build_xml().

{
   char *dst = outbuf;
   char *end = outbuf + buflen - 1; /* save one for the null terminator */

   /* Handle the case for the empty output buffer */
   if (buflen == 0) {
      return -1;
   }

   /* Escaping rules from http://www.w3.org/TR/REC-xml/#syntax */
   /* This also prevents partial entities at the end of a string */
   while (*string && dst < end) {
      const char *entity = NULL;
      int len = 0;

      switch (*string) {
      case '<':
         entity = "&lt;";
         len = 4;
         break;
      case '&':
         entity = "&amp;";
         len = 5;
         break;
      case '>':
         /* necessary if ]]> is in the string; easier to escape them all */
         entity = "&gt;";
         len = 4;
         break;
      case '\'':
         /* necessary in single-quoted strings; easier to escape them all */
         entity = "&apos;";
         len = 6;
         break;
      case '"':
         /* necessary in double-quoted strings; easier to escape them all */
         entity = "&quot;";
         len = 6;
         break;
      default:
         *dst++ = *string++;
         break;
      }

      if (entity) {
         ast_assert(len == strlen(entity));
         if (end - dst < len) {
            /* no room for the entity; stop */
            break;
         }
         /* just checked for length; strcpy is fine */
         strcpy(dst, entity);
         dst += len;
         ++string;
      }
   }
   /* Write null terminator */
   *dst = '\0';
   /* If any chars are left in string, return failure */
   return *string == '\0' ? 0 : -1;
}

Variable Documentation

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.
 

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

Referenced by acf_curl_helper(), ast_http_get_post_vars(), and handle_uri().