Asterisk - The Open Source Telephony Project GIT-master-16bbc5e
Loading...
Searching...
No Matches
Data Structures | Macros | Typedefs | Enumerations | Functions | Variables
chan_iax2.c File Reference

Implementation of Inter-Asterisk eXchange Version 2 as specified in RFC 5456. More...

#include "asterisk.h"
#include <sys/mman.h>
#include <dirent.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netinet/in_systm.h>
#include <netinet/ip.h>
#include <sys/time.h>
#include <signal.h>
#include <netdb.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <regex.h>
#include "asterisk/paths.h"
#include "asterisk/lock.h"
#include "asterisk/frame.h"
#include "asterisk/channel.h"
#include "asterisk/module.h"
#include "asterisk/pbx.h"
#include "asterisk/sched.h"
#include "asterisk/io.h"
#include "asterisk/config.h"
#include "asterisk/cli.h"
#include "asterisk/translate.h"
#include "asterisk/md5.h"
#include "asterisk/crypto.h"
#include "asterisk/acl.h"
#include "asterisk/manager.h"
#include "asterisk/callerid.h"
#include "asterisk/app.h"
#include "asterisk/mwi.h"
#include "asterisk/astdb.h"
#include "asterisk/musiconhold.h"
#include "asterisk/features.h"
#include "asterisk/utils.h"
#include "asterisk/causes.h"
#include "asterisk/localtime.h"
#include "asterisk/dnsmgr.h"
#include "asterisk/devicestate.h"
#include "asterisk/stringfields.h"
#include "asterisk/linkedlists.h"
#include "asterisk/astobj2.h"
#include "asterisk/timing.h"
#include "asterisk/taskprocessor.h"
#include "asterisk/test.h"
#include "asterisk/security_events.h"
#include "asterisk/stasis_endpoints.h"
#include "asterisk/bridge.h"
#include "asterisk/stasis.h"
#include "asterisk/stasis_system.h"
#include "asterisk/stasis_channels.h"
#include "asterisk/format_cache.h"
#include "asterisk/format_compatibility.h"
#include "asterisk/format_cap.h"
#include "iax2/include/iax2.h"
#include "iax2/include/firmware.h"
#include "iax2/include/parser.h"
#include "iax2/include/provision.h"
#include "iax2/include/codec_pref.h"
#include "iax2/include/format_compatibility.h"
#include "iax2/include/netsock.h"
#include "jitterbuf.h"

Go to the source code of this file.

Data Structures

struct  active_list
 
struct  addr_range
 
struct  call_number_pool
 
struct  chan_iax2_pvt
 
struct  create_addr_info
 
struct  dpcache
 
struct  dpreq_data
 
struct  dynamic_list
 
struct  iax2_context
 
struct  iax2_dpcache
 
struct  iax2_peer
 
struct  iax2_pkt_buf
 
struct  iax2_registry
 
struct  iax2_thread
 
struct  iax2_trunk_peer
 
struct  iax2_user
 
struct  iax_rr
 
struct  idle_list
 
struct  parsed_dial_string
 
struct  peercnt
 
struct  registrations
 
struct  show_peers_context
 
struct  chan_iax2_pvt::signaling_queue
 
struct  signaling_queue_entry
 
struct  tpeers
 

Macros

#define ACN_FORMAT1   "%-24.25s %4u %4d %4d %5d %3d %5d %4d %6d %4d %4d %5d %3d %5d %4d %6d %s%s %4s%s\n"
 
#define ACN_FORMAT2   "%s %u %d %d %d %d %d %d %d %d %d %d %d %d %d %d %s%s %s%s\n"
 
#define AUTH_METHOD_NAMES_BUFSIZE   19
 
#define CALLNO_ENTRY_GET_CALLNO(a)   ((a) & 0x7FFF)
 
#define CALLNO_ENTRY_IS_VALIDATED(a)   ((a) & 0x8000)
 
#define CALLNO_ENTRY_SET_VALIDATED(a)   ((a) |= 0x8000)
 
#define CALLNO_ENTRY_TO_PTR(a)   ((void *)(unsigned long)(a))
 
#define CALLNO_TO_PTR(a)   ((void *)(unsigned long)(a))
 
#define CALLTOKEN_HASH_FORMAT   "%s%u%d" /* address + port + ts + randomcalldata */
 
#define CALLTOKEN_IE_FORMAT   "%u?%s" /* time + ? + (40 char hash) */
 
#define DEBUG_SCHED_MULTITHREAD
 
#define DEBUG_SUPPORT
 
#define DEFAULT_CONTEXT   "default"
 
#define DEFAULT_DROP   3
 
#define DEFAULT_FREQ_NOTOK   10 * 1000 /* How often to check, if the host is down... */
 
#define DEFAULT_FREQ_OK   60 * 1000 /* How often to check for the host to be up */
 
#define DEFAULT_MAX_THREAD_COUNT   100
 
#define DEFAULT_MAXMS   2000 /* Must be faster than 2 seconds by default */
 
#define DEFAULT_RETRY_TIME   1000
 
#define DEFAULT_THREAD_COUNT   10
 
#define DEFAULT_TRUNKDATA   640 * 10
 
#define FORMAT   "%-15.15s %-20.20s %-15.15s %-15.15s %-5.5s %-5.10s\n"
 
#define FORMAT   "%-45.45s %-6.6s %-10.10s %-45.45s %8d %s\n"
 
#define FORMAT   "%-20.20s %-40.40s %-10.10s %5.5d/%5.5d %5.5d/%5.5d %-5.5dms %-4.4dms %-4.4dms %-6.6s %s%s %3s%s\n"
 
#define FORMAT2   "%-15.15s %-20.20s %-15.15d %-15.15s %-5.5s %-5.10s\n"
 
#define FORMAT2   "%-45.45s %-6.6s %-10.10s %-45.45s %8.8s %s\n"
 
#define FORMAT2   "%-20.20s %-40.40s %-10.10s %-11.11s %-11.11s %-7.7s %-6.6s %-6.6s %s %s %9s\n"
 
#define FORMATB   "%-20.20s %-40.40s %-10.10s %5.5d/%5.5d %5.5d/%5.5d [Native Bridged to ID=%5.5d]\n"
 
#define GAMMA   (0.01)
 
#define IAX2_TRUNK_PREFACE   (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
 
#define IAX_ALLOWFWDOWNLOAD   (uint64_t)(1LLU << 26)
 
#define IAX_ALREADYGONE   (uint64_t)(1LLU << 9)
 
#define IAX_CALLENCRYPTED(pvt)    (ast_test_flag64(pvt, IAX_ENCRYPTED) && ast_test_flag64(pvt, IAX_KEYPOPULATED))
 
#define IAX_CAPABILITY_FULLBANDWIDTH   0xFFFF
 
#define IAX_CAPABILITY_LOWBANDWIDTH
 
#define IAX_CAPABILITY_LOWFREE
 
#define IAX_CAPABILITY_MEDBANDWIDTH
 
#define IAX_CODEC_NOCAP   (uint64_t)(1LLU << 16)
 
#define IAX_CODEC_NOPREFS   (uint64_t)(1LLU << 15)
 
#define IAX_CODEC_USER_FIRST   (uint64_t)(1LLU << 14)
 
#define IAX_DEBUGDIGEST(msg, key)
 
#define IAX_DELAYPBXSTART   (uint64_t)(1LLU << 25)
 
#define IAX_DELME   (uint64_t)(1LLU << 1)
 
#define IAX_DYNAMIC   (uint64_t)(1LLU << 6)
 
#define IAX_ENCRYPTED   (uint64_t)(1LLU << 12)
 
#define IAX_FORCE_ENCRYPT   (uint64_t)(1LLU << 30)
 
#define IAX_HASCALLERID   (uint64_t)(1LLU << 0)
 
#define IAX_IMMEDIATE   (uint64_t)(1LLU << 27)
 
#define IAX_KEYPOPULATED   (uint64_t)(1LLU << 13)
 
#define IAX_MAXAUTHREQ   (uint64_t)(1LLU << 24)
 
#define IAX_NOTRANSFER   (uint64_t)(1LLU << 4)
 
#define IAX_PROVISION   (uint64_t)(1LLU << 10)
 
#define IAX_QUELCH   (uint64_t)(1LLU << 11)
 
#define IAX_RECVCONNECTEDLINE   (uint64_t)(1LLU << 29)
 
#define IAX_RTAUTOCLEAR   (uint64_t)(1LLU << 19)
 
#define IAX_RTCACHEFRIENDS   (uint64_t)(1LLU << 17)
 
#define IAX_RTIGNOREREGEXPIRE   (uint64_t)(1LLU << 21)
 
#define IAX_RTSAVE_SYSNAME   (uint64_t)(1LLU << 8)
 
#define IAX_RTUPDATE   (uint64_t)(1LLU << 18)
 
#define IAX_SENDANI   (uint64_t)(1LLU << 7)
 
#define IAX_SENDCONNECTEDLINE   (uint64_t)(1LLU << 28)
 
#define IAX_SHRINKCALLERID   (uint64_t)(1LLU << 31)
 
#define IAX_TEMPONLY   (uint64_t)(1LLU << 2)
 
#define IAX_TRANSFERMEDIA   (uint64_t)(1LLU << 23)
 
#define IAX_TRUNK   (uint64_t)(1LLU << 3)
 
#define IAX_TRUNKTIMESTAMPS   (uint64_t)(1LLU << 22)
 
#define IAX_USEJITTERBUF   (uint64_t)(1LLU << 5)
 
#define MARK_IAX_SUBCLASS_TX   0x8000
 
#define MAX_JITTER_BUFFER   50
 
#define MAX_PEER_BUCKETS   563
 
#define MAX_RETRY_TIME   10000
 
#define MAX_TIMESTAMP_SKEW   160
 
#define MAX_TRUNK_MTU   1240
 Maximum transmission unit for the UDP packet in the trunk not to be fragmented. This is based on 1516 - ethernet - ip - udp - iax minus one g711 frame = 1240.
 
#define MAX_TRUNKDATA   640 * 200
 
#define MAX_USER_BUCKETS   MAX_PEER_BUCKETS
 
#define MEMORY_SIZE   100
 
#define MIN_JITTER_BUFFER   10
 
#define MIN_RETRY_TIME   100
 
#define MIN_REUSE_TIME   60 /* Don't reuse a call number within 60 seconds */
 
#define PEERS_FORMAT   "%-15.15s %-40.40s %s %-40.40s %-6s%s %s %-11s %-32.32s\n"
 
#define PEERS_FORMAT2   "%-15.15s %-40.40s %s %-40.40s %-9s %s %-11s %-32.32s\n"
 
#define PTR_TO_CALLNO(a)   ((unsigned short)(unsigned long)(a))
 
#define PTR_TO_CALLNO_ENTRY(a)   ((uint16_t)(unsigned long)(a))
 
#define SCHED_MULTITHREADED
 
#define schedule_action(func, data)   __schedule_action(func, data, __PRETTY_FUNCTION__)
 
#define TRUNK_CALL_START   (IAX_MAX_CALLS / 2)
 
#define TS_GAP_FOR_JB_RESYNC   5000
 

Typedefs

typedef uint16_t callno_entry
 

Enumerations

enum  {
  CACHE_FLAG_EXISTS = (1 << 0) , CACHE_FLAG_NONEXISTENT = (1 << 1) , CACHE_FLAG_CANEXIST = (1 << 2) , CACHE_FLAG_PENDING = (1 << 3) ,
  CACHE_FLAG_TIMEOUT = (1 << 4) , CACHE_FLAG_TRANSMITTED = (1 << 5) , CACHE_FLAG_UNKNOWN = (1 << 6) , CACHE_FLAG_MATCHMORE = (1 << 7)
}
 
enum  { NEW_PREVENT = 0 , NEW_ALLOW = 1 , NEW_FORCE = 2 , NEW_ALLOW_CALLTOKEN_VALIDATED = 3 }
 
enum  callno_type { CALLNO_TYPE_NORMAL , CALLNO_TYPE_TRUNK }
 
enum  calltoken_peer_enum { CALLTOKEN_DEFAULT = 0 , CALLTOKEN_YES = 1 , CALLTOKEN_AUTO = 2 , CALLTOKEN_NO = 3 }
 Call token validation settings. More...
 
enum  iax2_state { IAX_STATE_STARTED = (1 << 0) , IAX_STATE_AUTHENTICATED = (1 << 1) , IAX_STATE_TBD = (1 << 2) }
 
enum  iax2_thread_iostate { IAX_IOSTATE_IDLE , IAX_IOSTATE_READY , IAX_IOSTATE_PROCESSING , IAX_IOSTATE_SCHEDREADY }
 
enum  iax2_thread_type { IAX_THREAD_TYPE_POOL , IAX_THREAD_TYPE_DYNAMIC }
 
enum  iax_reg_state {
  REG_STATE_UNREGISTERED = 0 , REG_STATE_REGSENT , REG_STATE_AUTHSENT , REG_STATE_REGISTERED ,
  REG_STATE_REJECTED , REG_STATE_TIMEOUT , REG_STATE_NOAUTH
}
 
enum  iax_transfer_state {
  TRANSFER_NONE = 0 , TRANSFER_BEGIN , TRANSFER_READY , TRANSFER_RELEASED ,
  TRANSFER_PASSTHROUGH , TRANSFER_MBEGIN , TRANSFER_MREADY , TRANSFER_MRELEASED ,
  TRANSFER_MPASSTHROUGH , TRANSFER_MEDIA , TRANSFER_MEDIAPASS
}
 

Functions

static void __attempt_transmit (const void *data)
 
static void __auth_reject (const void *nothing)
 
static void __auto_congest (const void *nothing)
 
static void __auto_hangup (const void *nothing)
 
static int __do_deliver (void *data)
 
static void __expire_registry (const void *data)
 
static int __find_callno (unsigned short callno, unsigned short dcallno, struct ast_sockaddr *addr, int new, int sockfd, int return_locked, int check_dcallno)
 
static void __get_from_jb (const void *p)
 
static void __iax2_do_register_s (const void *data)
 
static void __iax2_poke_noanswer (const void *data)
 
static void __iax2_poke_peer_s (const void *data)
 
static int __iax2_show_peers (int fd, int *total, struct mansession *s, const int argc, const char *const argv[])
 
static void __reg_module (void)
 
static int __schedule_action (void(*func)(const void *data), const void *data, const char *funcname)
 
static int __send_command (struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno, int now, int transfer, int final)
 
static void __send_lagrq (const void *data)
 
static void __send_ping (const void *data)
 
static int __unload_module (void)
 
static void __unreg_module (void)
 
static void _iax2_show_peers_one (int fd, struct mansession *s, struct show_peers_context *cont, struct iax2_peer *peer)
 
static int acf_channel_read (struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen)
 
static int acf_iaxvar_read (struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
 
static int acf_iaxvar_write (struct ast_channel *chan, const char *cmd, char *data, const char *value)
 
static void acl_change_stasis_cb (void *data, struct stasis_subscription *sub, struct stasis_message *message)
 
static void acl_change_stasis_subscribe (void)
 
static void acl_change_stasis_unsubscribe (void)
 
static int add_calltoken_ignore (const char *addr)
 
static void add_empty_calltoken_ie (struct chan_iax2_pvt *pvt, struct iax_ie_data *ied)
 
static int addr_range_cmp_cb (void *obj, void *arg, int flags)
 
static int addr_range_delme_cb (void *obj, void *arg, int flags)
 
static int addr_range_hash_cb (const void *obj, const int flags)
 
static int addr_range_match_address_cb (void *obj, void *arg, int flags)
 
static int apply_context (struct iax2_context *con, const char *context)
 
static int ast_cli_netstats (struct mansession *s, int fd, int limit_fmt)
 
static struct ast_channelast_iax2_new (int callno, int state, iax2_format capability, struct iax2_codec_pref *prefs, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor, unsigned int cachable)
 Create new call, interface with the PBX core.
 
struct ast_moduleAST_MODULE_SELF_SYM (void)
 
static int attempt_transmit (const void *data)
 
static int auth_fail (int callno, int failcode)
 
static char * auth_method_names (int authmethods, char *restrict buf)
 Get names of all auth methods.
 
static int auth_reject (const void *data)
 
static int authenticate (const char *challenge, const char *secret, const char *keyn, int authmethods, struct iax_ie_data *ied, struct ast_sockaddr *addr, struct chan_iax2_pvt *pvt)
 
static int authenticate_reply (struct chan_iax2_pvt *p, struct ast_sockaddr *addr, struct iax_ies *ies, const char *override, const char *okey)
 
static int authenticate_request (int call_num)
 
static int authenticate_verify (struct chan_iax2_pvt *p, struct iax_ies *ies)
 
static int auto_congest (const void *data)
 
static int auto_hangup (const void *data)
 
static void build_callno_limits (struct ast_variable *v)
 
static struct iax2_contextbuild_context (const char *context)
 
static void build_ecx_key (const unsigned char *digest, struct chan_iax2_pvt *pvt)
 
static void build_encryption_keys (const unsigned char *digest, struct chan_iax2_pvt *pvt)
 
static struct iax2_peerbuild_peer (const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly)
 Create peer structure based on configuration.
 
static void build_rand_pad (unsigned char *buf, ssize_t len)
 
static struct iax2_userbuild_user (const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly)
 Create in-memory user structure from configuration.
 
static int cache_get_callno_locked (const char *data)
 
static unsigned int calc_rxstamp (struct chan_iax2_pvt *p, unsigned int offset)
 
static unsigned int calc_timestamp (struct chan_iax2_pvt *p, unsigned int ts, struct ast_frame *f)
 
static unsigned int calc_txpeerstamp (struct iax2_trunk_peer *tpeer, int sampms, struct timeval *now)
 
static int calltoken_required (struct ast_sockaddr *addr, const char *name, int subclass)
 
static int check_access (int callno, struct ast_sockaddr *addr, struct iax_ies *ies)
 
static int check_provisioning (struct ast_sockaddr *addr, int sockfd, char *si, unsigned int ver)
 
static int check_srcaddr (struct ast_sockaddr *addr)
 Check if address can be used as packet source.
 
static void cleanup_thread_list (void *head)
 
static struct ast_formatcodec_choose_from_prefs (struct iax2_codec_pref *pref, struct ast_format_cap *cap)
 
static int complete_dpreply (struct chan_iax2_pvt *pvt, struct iax_ies *ies)
 
static char * complete_iax2_peers (const char *line, const char *word, int pos, int state, uint64_t flags)
 
static char * complete_iax2_unregister (const char *line, const char *word, int pos, int state)
 
static int complete_transfer (int callno, struct iax_ies *ies)
 
static unsigned char compress_subclass (iax2_format subclass)
 
static void construct_rr (struct chan_iax2_pvt *pvt, struct iax_ie_data *iep)
 
static int create_addr (const char *peername, struct ast_channel *c, struct ast_sockaddr *addr, struct create_addr_info *cai)
 
static int create_callno_pools (void)
 
static int decode_frame (ast_aes_decrypt_key *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen)
 
static int decrypt_frame (int callno, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen)
 
static void defer_full_frame (struct iax2_thread *from_here, struct iax2_thread *to_here)
 Queue the last read full frame for processing by a certain thread.
 
static void delete_users (void)
 
static void dp_lookup (int callno, const char *context, const char *callednum, const char *callerid, int skiplock)
 
static void * dp_lookup_thread (void *data)
 
static void encmethods_to_str (int e, struct ast_str **buf)
 
static int encrypt_frame (ast_aes_encrypt_key *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen)
 
static int expire_registry (const void *data)
 
static struct iax2_dpcachefind_cache (struct ast_channel *chan, const char *data, const char *context, const char *exten, int priority)
 
static int find_callno (unsigned short callno, unsigned short dcallno, struct ast_sockaddr *addr, int new, int sockfd, int full_frame)
 
static int find_callno_locked (unsigned short callno, unsigned short dcallno, struct ast_sockaddr *addr, int new, int sockfd, int full_frame)
 
static struct iax2_threadfind_idle_thread (void)
 
static struct iax2_peerfind_peer (const char *name, int realtime)
 
static struct iax2_trunk_peerfind_tpeer (struct ast_sockaddr *addr, int fd)
 
static struct iax2_userfind_user (const char *name)
 
static int firmware_show_callback (struct ast_iax2_firmware_header *header, void *user_data)
 
static unsigned int fix_peerts (struct timeval *rxtrunktime, int callno, unsigned int ts)
 
static void free_context (struct iax2_context *con)
 
static void free_signaling_queue_entry (struct signaling_queue_entry *s)
 
static int function_iaxpeer (struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
 
static int get_auth_methods (const char *value)
 
static int get_encrypt_methods (const char *s)
 
static int get_from_jb (const void *p)
 
static int get_unused_callno (enum callno_type type, int validated, callno_entry *entry)
 
static int handle_call_token (struct ast_iax2_full_hdr *fh, struct iax_ies *ies, struct ast_sockaddr *addr, int fd)
 
static char * handle_cli_iax2_provision (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 
static char * handle_cli_iax2_prune_realtime (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 
static char * handle_cli_iax2_reload (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 
static char * handle_cli_iax2_set_debug (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 
static char * handle_cli_iax2_set_debug_jb (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 
static char * handle_cli_iax2_set_debug_trunk (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 
static char * handle_cli_iax2_set_mtu (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 Set trunk MTU from CLI.
 
static char * handle_cli_iax2_show_cache (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 
static char * handle_cli_iax2_show_callno_limits (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 
static char * handle_cli_iax2_show_channels (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 
static char * handle_cli_iax2_show_firmware (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 
static char * handle_cli_iax2_show_netstats (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 
static char * handle_cli_iax2_show_peer (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 Show one peer in detail.
 
static char * handle_cli_iax2_show_peers (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 
static char * handle_cli_iax2_show_registry (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 
static char * handle_cli_iax2_show_stats (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 
static char * handle_cli_iax2_show_threads (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 
static char * handle_cli_iax2_show_users (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 
static char * handle_cli_iax2_test_losspct (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 
static char * handle_cli_iax2_unregister (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 
static void handle_deferred_full_frames (struct iax2_thread *thread)
 Handle any deferred full frames for this thread.
 
static int handle_error (void)
 
static int iax2_ack_registry (struct iax_ies *ies, struct ast_sockaddr *addr, int callno)
 Acknowledgment received for OUR registration.
 
static int attribute_pure iax2_allow_new (int frametype, int subclass, int inbound)
 
static int iax2_answer (struct ast_channel *c)
 
static int iax2_append_register (const char *hostname, const char *username, const char *secret, const char *porta)
 
static int iax2_call (struct ast_channel *c, const char *dest, int timeout)
 
static int iax2_canmatch (struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
 part of the IAX2 dial plan switch interface
 
static iax2_format iax2_codec_choose (struct iax2_codec_pref *pref, iax2_format formats)
 
static unsigned int iax2_datetime (const char *tz)
 
static int iax2_delete_from_sched (const void *data)
 
static void iax2_destroy (int callno)
 
static void iax2_destroy_helper (struct chan_iax2_pvt *pvt)
 
static int iax2_devicestate (const char *data)
 Part of the device state notification system —.
 
static int iax2_digit_begin (struct ast_channel *c, char digit)
 
static int iax2_digit_end (struct ast_channel *c, char digit, unsigned int duration)
 
static int iax2_do_register (struct iax2_registry *reg)
 
static int iax2_do_register_s (const void *data)
 
static void iax2_dprequest (struct iax2_dpcache *dp, int callno)
 
static void * iax2_dup_variable_datastore (void *)
 
static int iax2_exec (struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
 Execute IAX2 dialplan switch.
 
static int iax2_exists (struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
 Part of the IAX2 switch interface.
 
static int iax2_fixup (struct ast_channel *oldchannel, struct ast_channel *newchan)
 
static void iax2_frame_free (struct iax_frame *fr)
 
static void iax2_free_variable_datastore (void *)
 
const char * iax2_getformatname (iax2_format format)
 iax2 wrapper function for ast_getformatname
 
static const char * iax2_getformatname_multiple (iax2_format format, struct ast_str **codec_buf)
 
static int iax2_getpeername (struct ast_sockaddr addr, char *host, int len)
 
static int iax2_getpeertrunk (struct ast_sockaddr addr)
 
static int iax2_hangup (struct ast_channel *c)
 
static int iax2_indicate (struct ast_channel *c, int condition, const void *data, size_t datalen)
 
static int iax2_is_control_frame_allowed (int subtype)
 
static int iax2_key_rotate (const void *vpvt)
 
static int iax2_lock_callno_unless_destroyed (int callno)
 Acquire the iaxsl[callno] if call exists and not having ongoing hangup.
 
static void iax2_lock_owner (int callno)
 
static int iax2_matchmore (struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
 Part of the IAX2 Switch interface.
 
static int iax2_parse_allow_disallow (struct iax2_codec_pref *pref, iax2_format *formats, const char *list, int allowing)
 
static int iax2_poke_noanswer (const void *data)
 
static int iax2_poke_peer (struct iax2_peer *peer, int heldcall)
 
static int iax2_poke_peer_cb (void *obj, void *arg, int flags)
 
static int iax2_poke_peer_s (const void *data)
 
static int iax2_predestroy (int callno)
 
static void * iax2_process_thread (void *data)
 
static void iax2_process_thread_cleanup (void *data)
 
static int iax2_prov_app (struct ast_channel *chan, const char *data)
 
static int iax2_provision (struct ast_sockaddr *end, int sockfd, const char *dest, const char *template, int force)
 
static void iax2_publish_registry (const char *username, const char *domain, const char *status, const char *cause)
 
static int iax2_queryoption (struct ast_channel *c, int option, void *data, int *datalen)
 
static int iax2_queue_frame (int callno, struct ast_frame *f)
 Queue a frame to a call's owning asterisk channel.
 
static int iax2_queue_hangup (int callno)
 Queue a hangup frame on the ast_channel owner.
 
static int iax2_queue_hold (int callno, const char *musicclass)
 Queue a hold frame on the ast_channel owner.
 
static int iax2_queue_unhold (int callno)
 Queue an unhold frame on the ast_channel owner.
 
static struct ast_frameiax2_read (struct ast_channel *c)
 
static int iax2_register (const char *value, int lineno)
 
static struct ast_channeliax2_request (const char *type, struct ast_format_cap *cap, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor, const char *data, int *cause)
 
static int iax2_sched_add (struct ast_sched_context *sched, int when, ast_sched_cb callback, const void *data)
 
static int iax2_sched_replace (int id, struct ast_sched_context *con, int when, ast_sched_cb callback, const void *data)
 
static int iax2_send (struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final)
 
static int iax2_sendhtml (struct ast_channel *c, int subclass, const char *data, int datalen)
 
static int iax2_sendimage (struct ast_channel *c, struct ast_frame *img)
 
static int iax2_sendtext (struct ast_channel *c, const char *text)
 
static int iax2_setoption (struct ast_channel *c, int option, void *data, int datalen)
 
static int iax2_transfer (struct ast_channel *c, const char *dest)
 
static int iax2_transmit (struct iax_frame *fr)
 
static int iax2_trunk_expired (struct iax2_trunk_peer *tpeer, struct timeval *now)
 
static int iax2_trunk_queue (struct chan_iax2_pvt *pvt, struct iax_frame *fr)
 
static int iax2_vnak (int callno)
 
static int iax2_write (struct ast_channel *c, struct ast_frame *f)
 
static void iax_debug_output (const char *data)
 
static void iax_error_output (const char *data)
 
static void iax_outputframe (struct iax_frame *f, struct ast_iax2_full_hdr *fhi, int rx, struct ast_sockaddr *addr, int datalen)
 
static ast_callid iax_pvt_callid_get (int callno)
 
static void iax_pvt_callid_new (int callno)
 
static void iax_pvt_callid_set (int callno, ast_callid callid)
 
static struct iax_frameiaxfrdup2 (struct iax_frame *fr)
 
static void insert_idle_thread (struct iax2_thread *thread)
 
static int invalid_key (ast_aes_decrypt_key *ecx)
 
static void jb_debug_output (const char *fmt,...)
 
static void jb_error_output (const char *fmt,...)
 
static void jb_warning_output (const char *fmt,...)
 
static int load_module (void)
 Load the module.
 
static int load_objects (void)
 
static void log_jitterstats (unsigned short callno)
 
static int make_trunk (unsigned short callno, int locked)
 
static int manager_iax2_show_netstats (struct mansession *s, const struct message *m)
 
static int manager_iax2_show_peer_list (struct mansession *s, const struct message *m)
 callback to display iax peers in manager format
 
static int manager_iax2_show_peers (struct mansession *s, const struct message *m)
 callback to display iax peers in manager
 
static int manager_iax2_show_registry (struct mansession *s, const struct message *m)
 
static int match (struct ast_sockaddr *addr, unsigned short callno, unsigned short dcallno, const struct chan_iax2_pvt *cur, int check_dcallno)
 
static void memcpy_decrypt (unsigned char *dst, const unsigned char *src, int len, ast_aes_decrypt_key *dcx)
 
static void memcpy_encrypt (unsigned char *dst, const unsigned char *src, int len, ast_aes_encrypt_key *ecx)
 
static void merge_encryption (struct chan_iax2_pvt *p, unsigned int enc)
 
static int network_change_sched_cb (const void *data)
 
static void network_change_stasis_cb (void *data, struct stasis_subscription *sub, struct stasis_message *message)
 
static void network_change_stasis_subscribe (void)
 
static void network_change_stasis_unsubscribe (void)
 
static void * network_thread (void *ignore)
 
static struct chan_iax2_pvtnew_iax (struct ast_sockaddr *addr, const char *host)
 
static void parse_dial_string (char *data, struct parsed_dial_string *pds)
 Parses an IAX dial string into its component parts.
 
static int peer_cmp_cb (void *obj, void *arg, int flags)
 
static int peer_delme_cb (void *obj, void *arg, int flags)
 
static void peer_destructor (void *obj)
 
static int peer_hash_cb (const void *obj, const int flags)
 
static struct iax2_peerpeer_ref (struct iax2_peer *peer)
 
static int peer_set_sock_cb (void *obj, void *arg, int flags)
 
static int peer_set_srcaddr (struct iax2_peer *peer, const char *srcaddr)
 Parse the "sourceaddress" value, lookup in netsock list and set peer's sockfd. Defaults to defaultsockfd if not found.
 
static int peer_status (struct iax2_peer *peer, char *status, int statuslen)
 peer_status: Report Peer status in character string
 
static struct iax2_peerpeer_unref (struct iax2_peer *peer)
 
static int peercnt_add (struct ast_sockaddr *addr)
 
static int peercnt_cmp_cb (void *obj, void *arg, int flags)
 
static int peercnt_hash_cb (const void *obj, const int flags)
 
static void peercnt_modify (unsigned char reg, uint16_t limit, struct ast_sockaddr *sockaddr)
 
static void peercnt_remove (struct peercnt *peercnt)
 
static int peercnt_remove_by_addr (struct ast_sockaddr *addr)
 
static int peercnt_remove_cb (const void *obj)
 
static void poke_all_peers (void)
 
static int prune_addr_range_cb (void *obj, void *arg, int flags)
 
static void prune_peers (void)
 
static void prune_users (void)
 
static int pvt_cmp_cb (void *obj, void *arg, int flags)
 
static void pvt_destructor (void *obj)
 
static int pvt_hash_cb (const void *obj, const int flags)
 
static int queue_signalling (struct chan_iax2_pvt *pvt, struct ast_frame *f)
 All frames other than that of type AST_FRAME_IAX must be held until we have received a destination call number.
 
static int raw_hangup (struct ast_sockaddr *addr, unsigned short src, unsigned short dst, int sockfd)
 
static struct iax2_peerrealtime_peer (const char *peername, struct ast_sockaddr *addr)
 
static void realtime_update_peer (const char *peername, struct ast_sockaddr *sockaddr, time_t regtime)
 
static struct iax2_userrealtime_user (const char *username, struct ast_sockaddr *addr)
 
static void reg_source_db (struct iax2_peer *p)
 
static void register_peer_exten (struct iax2_peer *peer, int onoff)
 
static int register_verify (int callno, struct ast_sockaddr *addr, struct iax_ies *ies)
 Verify inbound registration.
 
static int registry_authrequest (int callno)
 
static int registry_rerequest (struct iax_ies *ies, int callno, struct ast_sockaddr *addr)
 
static char * regstate2str (int regstate)
 
static int reload (void)
 
static int reload_config (int forced_reload)
 
static void remove_by_peercallno (struct chan_iax2_pvt *pvt)
 
static void remove_by_transfercallno (struct chan_iax2_pvt *pvt)
 
static int replace_callno (const void *obj)
 
static void requirecalltoken_mark_auto (const char *name, int subclass)
 
static void resend_with_token (int callno, struct iax_frame *f, const char *newtoken)
 
static void save_osptoken (struct iax_frame *fr, struct iax_ies *ies)
 
static void save_rr (struct iax_frame *fr, struct iax_ies *ies)
 
static void sched_delay_remove (struct ast_sockaddr *addr, callno_entry entry)
 
static int schedule_delivery (struct iax_frame *fr, int updatehistory, int fromtrunk, unsigned int *tsout)
 
static int scheduled_destroy (const void *vid)
 
static int send_apathetic_reply (unsigned short callno, unsigned short dcallno, struct ast_sockaddr *addr, int command, int ts, unsigned char seqno, int sockfd, struct iax_ie_data *ied)
 
static int send_command (struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int)
 
static int send_command_final (struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int)
 
static int send_command_immediate (struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int)
 
static int send_command_locked (unsigned short callno, char, int, unsigned int, const unsigned char *, int, int)
 
static int send_command_transfer (struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int)
 
static int send_lagrq (const void *data)
 
static int send_packet (struct iax_frame *f)
 
static int send_ping (const void *data)
 
static void send_signaling (struct chan_iax2_pvt *pvt)
 This function must be called once we are sure the other side has given us a call number. All signaling is held here until that point.
 
static int send_trunk (struct iax2_trunk_peer *tpeer, struct timeval *now)
 
static int set_config (const char *config_file, int reload, int forced)
 Load configuration.
 
static void set_config_destroy (void)
 
static void set_hangup_source_and_cause (int callno, unsigned char causecode)
 
static void set_peercnt_limit (struct peercnt *peercnt)
 
static int set_peercnt_limit_all_cb (void *obj, void *arg, int flags)
 
static void signal_condition (ast_mutex_t *lock, ast_cond_t *cond)
 
static int socket_process (struct iax2_thread *thread)
 
static int socket_process_helper (struct iax2_thread *thread)
 
static int socket_process_meta (int packet_len, struct ast_iax2_meta_hdr *meta, struct ast_sockaddr *addr, int sockfd, struct iax_frame *fr)
 
static int socket_read (int *id, int fd, short events, void *cbdata)
 
static void spawn_dp_lookup (int callno, const char *context, const char *callednum, const char *callerid)
 
static int start_network_thread (void)
 
static void stop_stuff (int callno)
 
static void store_by_peercallno (struct chan_iax2_pvt *pvt)
 
static void store_by_transfercallno (struct chan_iax2_pvt *pvt)
 
static int timing_read (int *id, int fd, short events, void *cbdata)
 
static int transfercallno_pvt_cmp_cb (void *obj, void *arg, int flags)
 
static int transfercallno_pvt_hash_cb (const void *obj, const int flags)
 
static int transmit_frame (void *data)
 
static int transmit_trunk (struct iax_frame *f, struct ast_sockaddr *addr, int sockfd)
 
static int try_transfer (struct chan_iax2_pvt *pvt, struct iax_ies *ies)
 
static iax2_format uncompress_subclass (unsigned char csub)
 
static void unlink_peer (struct iax2_peer *peer)
 
static int unload_module (void)
 
static void unwrap_timestamp (struct iax_frame *fr)
 
static void update_jbsched (struct chan_iax2_pvt *pvt)
 
static int update_packet (struct iax_frame *f)
 
static int update_registry (struct ast_sockaddr *addr, int callno, char *devtype, int fd, unsigned short refresh)
 
static int user_cmp_cb (void *obj, void *arg, int flags)
 
static int user_delme_cb (void *obj, void *arg, int flags)
 
static void user_destructor (void *obj)
 
static int user_hash_cb (const void *obj, const int flags)
 
static struct iax2_useruser_unref (struct iax2_user *user)
 
static void vnak_retransmit (int callno, int last)
 
static int wait_for_peercallno (struct chan_iax2_pvt *pvt)
 

Variables

static struct ast_module_info __mod_info = { .name = AST_MODULE, .flags = AST_MODFLAG_LOAD_ORDER , .description = "Inter Asterisk eXchange (Ver 2)" , .key = ASTERISK_GPL_KEY , .buildopt_sum = AST_BUILDOPT_SUM, .support_level = AST_MODULE_SUPPORT_CORE, .load = load_module, .unload = unload_module, .reload = reload, .load_pri = AST_MODPRI_CHANNEL_DRIVER, .requires = "dnsmgr", .optional_modules = "res_crypto", }
 
static char accountcode [AST_MAX_ACCOUNT_CODE]
 
static struct stasis_subscriptionacl_change_sub
 
static struct active_list active_list = AST_LIST_HEAD_INIT_VALUE
 
static int adsi = 0
 
static int amaflags = 0
 
static const struct ast_module_infoast_module_info = &__mod_info
 
static const char * auth_method_labels []
 Name of effective auth method.
 
static int authdebug = 0
 
static int autokill = 0
 
static struct ao2_containercallno_limits
 
static struct call_number_pool callno_pool
 
static ast_mutex_t callno_pool_lock = AST_MUTEX_INIT_VALUE
 
static struct call_number_pool callno_pool_trunk
 
static struct ao2_containercalltoken_ignores
 
static struct ast_cli_entry cli_iax2 []
 
static struct ast_sockaddr debugaddr
 
static uint16_t DEFAULT_MAXCALLNO_LIMIT = 2048
 
static uint16_t DEFAULT_MAXCALLNO_LIMIT_NONVAL = 8192
 
static char default_parkinglot [AST_MAX_CONTEXT]
 
static int defaultsockfd = -1
 
static int delayreject = 0
 
static struct dpcache dpcache = AST_LIST_HEAD_INIT_VALUE
 
static struct dynamic_list dynamic_list = AST_LIST_HEAD_INIT_VALUE
 
struct { 
 
   struct iax_frame *   first 
 
   struct iax_frame *   last 
 
frame_queue [IAX_MAX_CALLS
 a list of frames that may need to be retransmitted
 
static int global_max_trunk_mtu
 
static uint16_t global_maxcallno
 
static uint16_t global_maxcallno_nonval
 
static int global_rtautoclear = 120
 
static struct ast_flags64 globalflags = { 0 }
 
static int iax2_authmethods = 0
 
static iax2_format iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH
 
static int iax2_encryption = 0
 
static int(* iax2_regfunk )(const char *username, int onoff) = NULL
 
static struct ast_switch iax2_switch
 
static struct ast_channel_tech iax2_tech
 
static const struct ast_datastore_info iax2_variable_datastore_info
 
static struct ao2_containeriax_peercallno_pvts
 Another container of iax2_pvt structures.
 
static struct ao2_containeriax_transfercallno_pvts
 Another container of iax2_pvt structures.
 
static int iaxactivethreadcount = 0
 
static int iaxcompat = 0
 
static int iaxdebug = 0
 
static int iaxdefaultdpcache =10 * 60
 
static int iaxdefaulttimeout = 5
 
static int iaxdynamicthreadcount = 0
 
static int iaxdynamicthreadnum = 0
 
static int iaxmaxthreadcount = DEFAULT_MAX_THREAD_COUNT
 
static struct ast_custom_function iaxpeer_function
 
static struct chan_iax2_pvtiaxs [IAX_MAX_CALLS]
 an array of iax2 pvt structures
 
static ast_mutex_t iaxsl [ARRAY_LEN(iaxs)]
 chan_iax2_pvt structure locks
 
static int iaxthreadcount = DEFAULT_THREAD_COUNT
 
static int iaxtrunkdebug = 0
 
static struct ast_custom_function iaxvar_function
 
static struct idle_list idle_list = AST_LIST_HEAD_INIT_VALUE
 
static struct io_contextio
 
static int jittertargetextra = 40
 
static int lagrq_time = 10
 
static char language [MAX_LANGUAGE] = ""
 
static int last_authmethod = 0
 
static time_t max_calltoken_delay = 10
 
static int max_reg_expire
 
static int max_retries = 4
 
static int maxauthreq = 3
 
static int maxjitterbuffer =1000
 
static int maxjitterinterps =10
 
static int min_reg_expire
 
static char mohinterpret [MAX_MUSICCLASS]
 
static char mohsuggest [MAX_MUSICCLASS]
 
static struct ast_netsock_listnetsock
 
static pthread_t netthreadid = AST_PTHREADT_NULL
 
static int network_change_sched_id = -1
 
static struct stasis_subscriptionnetwork_change_sub
 
static struct ast_netsock_listoutsock
 
static char * papp = "IAX2Provision"
 
static struct ao2_containerpeercnts
 
static struct ao2_containerpeers
 
static int ping_time = 21
 
static struct iax2_codec_pref prefs_global
 
struct { 
 
   unsigned int   cos 
 
   unsigned int   tos 
 
qos = { 0, 0 } 
 
static int randomcalltokendata
 
static char regcontext [AST_MAX_CONTEXT] = ""
 
static struct registrations registrations = AST_LIST_HEAD_INIT_VALUE
 
static int resyncthreshold =1000
 
static struct ast_sched_contextsched
 
static int srvlookup = 0
 
static const char tdesc [] = "Inter Asterisk eXchange Driver (Ver 2)"
 
static int test_losspct = 0
 
static struct ast_timertimer
 
static uint16_t total_nonval_callno_used = 0
 
static struct tpeers tpeers = AST_LIST_HEAD_INIT_VALUE
 
static struct ast_taskprocessortransmit_processor
 
static int trunk_maxmtu
 
static int trunk_nmaxmtu
 
static int trunk_timed
 
static int trunk_untimed
 
static int trunkfreq = 20
 
static int trunkmaxsize = MAX_TRUNKDATA
 
static struct ao2_containerusers
 

Detailed Description

Implementation of Inter-Asterisk eXchange Version 2 as specified in RFC 5456.

Author
Mark Spencer marks.nosp@m.ter@.nosp@m.digiu.nosp@m.m.co.nosp@m.m
Todo:
Implement musicclass settings for IAX2 devices

Definition in file chan_iax2.c.

Macro Definition Documentation

◆ ACN_FORMAT1

#define ACN_FORMAT1   "%-24.25s %4u %4d %4d %5d %3d %5d %4d %6d %4d %4d %5d %3d %5d %4d %6d %s%s %4s%s\n"

◆ ACN_FORMAT2

#define ACN_FORMAT2   "%s %u %d %d %d %d %d %d %d %d %d %d %d %d %d %d %s%s %s%s\n"

◆ AUTH_METHOD_NAMES_BUFSIZE

#define AUTH_METHOD_NAMES_BUFSIZE   19

Definition at line 444 of file chan_iax2.c.

◆ CALLNO_ENTRY_GET_CALLNO

#define CALLNO_ENTRY_GET_CALLNO (   a)    ((a) & 0x7FFF)

Definition at line 993 of file chan_iax2.c.

◆ CALLNO_ENTRY_IS_VALIDATED

#define CALLNO_ENTRY_IS_VALIDATED (   a)    ((a) & 0x8000)

Definition at line 992 of file chan_iax2.c.

◆ CALLNO_ENTRY_SET_VALIDATED

#define CALLNO_ENTRY_SET_VALIDATED (   a)    ((a) |= 0x8000)

Definition at line 991 of file chan_iax2.c.

◆ CALLNO_ENTRY_TO_PTR

#define CALLNO_ENTRY_TO_PTR (   a)    ((void *)(unsigned long)(a))

Definition at line 989 of file chan_iax2.c.

◆ CALLNO_TO_PTR

#define CALLNO_TO_PTR (   a)    ((void *)(unsigned long)(a))

Definition at line 330 of file chan_iax2.c.

◆ CALLTOKEN_HASH_FORMAT

#define CALLTOKEN_HASH_FORMAT   "%s%u%d" /* address + port + ts + randomcalldata */

◆ CALLTOKEN_IE_FORMAT

#define CALLTOKEN_IE_FORMAT   "%u?%s" /* time + ? + (40 char hash) */

◆ DEBUG_SCHED_MULTITHREAD

#define DEBUG_SCHED_MULTITHREAD

Definition at line 322 of file chan_iax2.c.

◆ DEBUG_SUPPORT

#define DEBUG_SUPPORT

Definition at line 338 of file chan_iax2.c.

◆ DEFAULT_CONTEXT

#define DEFAULT_CONTEXT   "default"

Definition at line 357 of file chan_iax2.c.

◆ DEFAULT_DROP

#define DEFAULT_DROP   3

Definition at line 336 of file chan_iax2.c.

◆ DEFAULT_FREQ_NOTOK

#define DEFAULT_FREQ_NOTOK   10 * 1000 /* How often to check, if the host is down... */

Definition at line 433 of file chan_iax2.c.

◆ DEFAULT_FREQ_OK

#define DEFAULT_FREQ_OK   60 * 1000 /* How often to check for the host to be up */

Definition at line 432 of file chan_iax2.c.

◆ DEFAULT_MAX_THREAD_COUNT

#define DEFAULT_MAX_THREAD_COUNT   100

Definition at line 333 of file chan_iax2.c.

◆ DEFAULT_MAXMS

#define DEFAULT_MAXMS   2000 /* Must be faster than 2 seconds by default */

Definition at line 431 of file chan_iax2.c.

◆ DEFAULT_RETRY_TIME

#define DEFAULT_RETRY_TIME   1000

Definition at line 334 of file chan_iax2.c.

◆ DEFAULT_THREAD_COUNT

#define DEFAULT_THREAD_COUNT   10

Definition at line 332 of file chan_iax2.c.

◆ DEFAULT_TRUNKDATA

#define DEFAULT_TRUNKDATA   640 * 10

40ms, uncompressed linear * 10 channels

Definition at line 747 of file chan_iax2.c.

◆ FORMAT [1/3]

#define FORMAT   "%-15.15s %-20.20s %-15.15s %-15.15s %-5.5s %-5.10s\n"

◆ FORMAT [2/3]

#define FORMAT   "%-45.45s %-6.6s %-10.10s %-45.45s %8d %s\n"

◆ FORMAT [3/3]

#define FORMAT   "%-20.20s %-40.40s %-10.10s %5.5d/%5.5d %5.5d/%5.5d %-5.5dms %-4.4dms %-4.4dms %-6.6s %s%s %3s%s\n"

◆ FORMAT2 [1/3]

#define FORMAT2   "%-15.15s %-20.20s %-15.15d %-15.15s %-5.5s %-5.10s\n"

◆ FORMAT2 [2/3]

#define FORMAT2   "%-45.45s %-6.6s %-10.10s %-45.45s %8.8s %s\n"

◆ FORMAT2 [3/3]

#define FORMAT2   "%-20.20s %-40.40s %-10.10s %-11.11s %-11.11s %-7.7s %-6.6s %-6.6s %s %s %9s\n"

◆ FORMATB

#define FORMATB   "%-20.20s %-40.40s %-10.10s %5.5d/%5.5d %5.5d/%5.5d [Native Bridged to ID=%5.5d]\n"

◆ GAMMA

#define GAMMA   (0.01)

Definition at line 343 of file chan_iax2.c.

◆ IAX2_TRUNK_PREFACE

#define IAX2_TRUNK_PREFACE   (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))

Definition at line 675 of file chan_iax2.c.

◆ IAX_ALLOWFWDOWNLOAD

#define IAX_ALLOWFWDOWNLOAD   (uint64_t)(1LLU << 26)

Allow the FWDOWNL command?

Definition at line 560 of file chan_iax2.c.

◆ IAX_ALREADYGONE

#define IAX_ALREADYGONE   (uint64_t)(1LLU << 9)

Already disconnected

Definition at line 544 of file chan_iax2.c.

◆ IAX_CALLENCRYPTED

#define IAX_CALLENCRYPTED (   pvt)     (ast_test_flag64(pvt, IAX_ENCRYPTED) && ast_test_flag64(pvt, IAX_KEYPOPULATED))

Definition at line 477 of file chan_iax2.c.

479 { \
480 int idx; \
481 char digest[33] = ""; \
482 \
483 if (!iaxdebug) \
484 break; \
485 \
486 for (idx = 0; idx < 16; idx++) \
487 sprintf(digest + (idx << 1), "%02hhx", (unsigned char) key[idx]); \
488 \
489 ast_log(LOG_NOTICE, msg " IAX_COMMAND_RTKEY to rotate key to '%s'\n", digest); \
490 } while(0)
491
492static struct io_context *io;
493static struct ast_sched_context *sched;
494
496
497static int iaxdebug = 0;
498
499static int iaxtrunkdebug = 0;
500
501static int test_losspct = 0;
502#ifdef IAXTESTS
503static int test_late = 0;
504static int test_resync = 0;
505static int test_jit = 0;
506static int test_jitpct = 0;
507#endif /* IAXTESTS */
508
510static char mohinterpret[MAX_MUSICCLASS];
511static char mohsuggest[MAX_MUSICCLASS];
512static int amaflags = 0;
513static int adsi = 0;
514static int delayreject = 0;
515static int iax2_encryption = 0;
516static int iax2_authmethods = 0;
517
518static struct ast_flags64 globalflags = { 0 };
519
520static pthread_t netthreadid = AST_PTHREADT_NULL;
521
522enum iax2_state {
523 IAX_STATE_STARTED = (1 << 0),
524 IAX_STATE_AUTHENTICATED = (1 << 1),
525 IAX_STATE_TBD = (1 << 2),
526};
527
528struct iax2_context {
530 struct iax2_context *next;
531};
532
533
534#define IAX_HASCALLERID (uint64_t)(1LLU << 0) /*!< CallerID has been specified */
535#define IAX_DELME (uint64_t)(1LLU << 1) /*!< Needs to be deleted */
536#define IAX_TEMPONLY (uint64_t)(1LLU << 2) /*!< Temporary (realtime) */
537#define IAX_TRUNK (uint64_t)(1LLU << 3) /*!< Treat as a trunk */
538#define IAX_NOTRANSFER (uint64_t)(1LLU << 4) /*!< Don't native bridge */
539#define IAX_USEJITTERBUF (uint64_t)(1LLU << 5) /*!< Use jitter buffer */
540#define IAX_DYNAMIC (uint64_t)(1LLU << 6) /*!< dynamic peer */
541#define IAX_SENDANI (uint64_t)(1LLU << 7) /*!< Send ANI along with CallerID */
542#define IAX_RTSAVE_SYSNAME (uint64_t)(1LLU << 8) /*!< Save Systname on Realtime Updates */
543#define IAX_ALREADYGONE (uint64_t)(1LLU << 9) /*!< Already disconnected */
544#define IAX_PROVISION (uint64_t)(1LLU << 10) /*!< This is a provisioning request */
545#define IAX_QUELCH (uint64_t)(1LLU << 11) /*!< Whether or not we quelch audio */
546#define IAX_ENCRYPTED (uint64_t)(1LLU << 12) /*!< Whether we should assume encrypted tx/rx */
547#define IAX_KEYPOPULATED (uint64_t)(1LLU << 13) /*!< Whether we have a key populated */
548#define IAX_CODEC_USER_FIRST (uint64_t)(1LLU << 14) /*!< are we willing to let the other guy choose the codec? */
549#define IAX_CODEC_NOPREFS (uint64_t)(1LLU << 15) /*!< Force old behaviour by turning off prefs */
550#define IAX_CODEC_NOCAP (uint64_t)(1LLU << 16) /*!< only consider requested format and ignore capabilities*/
551#define IAX_RTCACHEFRIENDS (uint64_t)(1LLU << 17) /*!< let realtime stay till your reload */
552#define IAX_RTUPDATE (uint64_t)(1LLU << 18) /*!< Send a realtime update */
553#define IAX_RTAUTOCLEAR (uint64_t)(1LLU << 19) /*!< erase me on expire */
554#define IAX_RTIGNOREREGEXPIRE (uint64_t)(1LLU << 21) /*!< When using realtime, ignore registration expiration */
555#define IAX_TRUNKTIMESTAMPS (uint64_t)(1LLU << 22) /*!< Send trunk timestamps */
556#define IAX_TRANSFERMEDIA (uint64_t)(1LLU << 23) /*!< When doing IAX2 transfers, transfer media only */
557#define IAX_MAXAUTHREQ (uint64_t)(1LLU << 24) /*!< Maximum outstanding AUTHREQ restriction is in place */
558#define IAX_DELAYPBXSTART (uint64_t)(1LLU << 25) /*!< Don't start a PBX on the channel until the peer sends us a response, so that we've achieved a three-way handshake with them before sending voice or anything else */
559#define IAX_ALLOWFWDOWNLOAD (uint64_t)(1LLU << 26) /*!< Allow the FWDOWNL command? */
560#define IAX_IMMEDIATE (uint64_t)(1LLU << 27) /*!< Allow immediate off-hook to extension s */
561#define IAX_SENDCONNECTEDLINE (uint64_t)(1LLU << 28) /*!< Allow sending of connected line updates */
562#define IAX_RECVCONNECTEDLINE (uint64_t)(1LLU << 29) /*!< Allow receiving of connected line updates */
563#define IAX_FORCE_ENCRYPT (uint64_t)(1LLU << 30) /*!< Forces call encryption, if encryption not possible hangup */
564#define IAX_SHRINKCALLERID (uint64_t)(1LLU << 31) /*!< Turn on and off caller id shrinking */
565static int global_rtautoclear = 120;
566
567static int reload_config(int forced_reload);
568
569/*!
570 * \brief Call token validation settings.
571 */
573 /*! \brief Default calltoken required unless the ip is in the ignorelist */
575 /*! \brief Require call token validation. */
576 CALLTOKEN_YES = 1,
577 /*! \brief Require call token validation after a successful registration
578 * using call token validation occurs. */
579 CALLTOKEN_AUTO = 2,
580 /*! \brief Do not require call token validation. */
581 CALLTOKEN_NO = 3,
582};
583
584struct iax2_user {
592 AST_STRING_FIELD(inkeys); /*!< Key(s) this user can use to authenticate to us */
596 AST_STRING_FIELD(parkinglot); /*!< Default parkinglot for device */
597 );
598
599 int authmethods;
600 int encmethods;
601 int amaflags;
602 int adsi;
603 uint64_t flags;
605 int maxauthreq; /*!< Maximum allowed outstanding AUTHREQs */
606 int curauthreq; /*!< Current number of outstanding AUTHREQs */
607 struct iax2_codec_pref prefs;
608 struct ast_acl_list *acl;
609 struct iax2_context *contexts;
610 struct ast_variable *vars;
611 enum calltoken_peer_enum calltoken_required; /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
612};
613
614struct iax2_peer {
618 AST_STRING_FIELD(description); /*!< Description of the peer */
621 AST_STRING_FIELD(outkey); /*!< What key we use to talk to this peer */
622
623 AST_STRING_FIELD(regexten); /*!< Extension to register (if regcontext is used) */
624 AST_STRING_FIELD(context); /*!< For transfers only */
625 AST_STRING_FIELD(peercontext); /*!< Context to pass to peer */
626 AST_STRING_FIELD(mailbox); /*!< Mailbox */
629 AST_STRING_FIELD(inkeys); /*!< Key(s) this peer can use to authenticate to us */
630 /* Suggested caller id if registering */
631 AST_STRING_FIELD(cid_num); /*!< Default context (for transfer really) */
632 AST_STRING_FIELD(cid_name); /*!< Default context (for transfer really) */
633 AST_STRING_FIELD(zonetag); /*!< Time Zone */
634 AST_STRING_FIELD(parkinglot); /*!< Default parkinglot for device */
635 );
636 struct iax2_codec_pref prefs;
637 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
638 struct ast_sockaddr addr;
639 int formats;
640 int sockfd; /*!< Socket to use for transmission */
641 struct ast_sockaddr mask;
642 int adsi;
643 uint64_t flags;
644
645 /* Dynamic Registration fields */
646 struct ast_sockaddr defaddr; /*!< Default address if there is one */
647 int authmethods; /*!< Authentication methods (IAX_AUTH_*) */
648 int encmethods; /*!< Encryption methods (IAX_ENCRYPT_*) */
649
650 int expire; /*!< Schedule entry for expiry */
651 int expiry; /*!< How soon to expire */
652 iax2_format capability; /*!< Capability */
653
654 /* Qualification */
655 int callno; /*!< Call number of POKE request */
656 int pokeexpire; /*!< Scheduled qualification-related task (ie iax2_poke_peer_s or iax2_poke_noanswer) */
657 int lastms; /*!< How long last response took (in ms), or -1 for no response */
658 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
659
660 int pokefreqok; /*!< How often to check if the host is up */
661 int pokefreqnotok; /*!< How often to check when the host has been determined to be down */
662 int historicms; /*!< How long recent average responses took */
663 int smoothing; /*!< Sample over how many units to determine historic ms */
664 uint16_t maxcallno; /*!< Max call number limit for this peer. Set on registration */
665
666 struct ast_mwi_subscriber *mwi_event_sub; /*!< This subscription lets pollmailboxes know which mailboxes need to be polled */
667
668 struct ast_acl_list *acl;
669 enum calltoken_peer_enum calltoken_required; /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
670
671 struct ast_endpoint *endpoint; /*!< Endpoint structure for this peer */
672};
673
674#define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
675
676struct iax2_trunk_peer {
678 int sockfd;
679 struct ast_sockaddr addr;
680 struct timeval txtrunktime; /*!< Transmit trunktime */
681 struct timeval rxtrunktime; /*!< Receive trunktime */
682 struct timeval lasttxtime; /*!< Last transmitted trunktime */
683 struct timeval trunkact; /*!< Last trunk activity */
684 unsigned int lastsent; /*!< Last sent time */
685 /* Trunk data and length */
686 unsigned char *trunkdata;
687 unsigned int trunkdatalen;
688 unsigned int trunkdataalloc;
689 int trunkmaxmtu;
690 int trunkerror;
691 int calls;
693};
694
696
697enum iax_reg_state {
705};
706
708 TRANSFER_NONE = 0,
719};
720
721struct iax2_registry {
722 struct ast_sockaddr addr; /*!< Who we connect to for registration purposes */
723 char username[80];
724 char secret[80]; /*!< Password or key name in []'s */
725 int expire; /*!< Sched ID of expiration */
726 int refresh; /*!< How often to refresh */
728 int messages; /*!< Message count, low 8 bits = new, high 8 bits = old */
729 int callno; /*!< Associated call number if applicable */
730 struct ast_sockaddr us; /*!< Who the server thinks we are */
731 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
733 int port;
734 char hostname[];
735};
736
738
739/* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
740#define MIN_RETRY_TIME 100
741#define MAX_RETRY_TIME 10000
742
743#define MAX_JITTER_BUFFER 50
744#define MIN_JITTER_BUFFER 10
745
746#define DEFAULT_TRUNKDATA 640 * 10 /*!< 40ms, uncompressed linear * 10 channels */
747
748#define MAX_TIMESTAMP_SKEW 160 /*!< maximum difference between actual and predicted ts for sending */
749
750/* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
751#define TS_GAP_FOR_JB_RESYNC 5000
752
753/* used for first_iax_message and last_iax_message. If this bit is set it was TX, else RX */
754#define MARK_IAX_SUBCLASS_TX 0x8000
755
758static int iaxdynamicthreadcount = 0;
759static int iaxdynamicthreadnum = 0;
760static int iaxactivethreadcount = 0;
761
762struct iax_rr {
763 int jitter;
764 int losspct;
765 int losscnt;
766 int packets;
767 int delay;
768 int dropped;
769 int ooo;
770};
771
772struct iax2_pvt_ref;
773
774/* We use the high order bit as the validated flag, and the lower 15 as the
775 * actual call number */
776typedef uint16_t callno_entry;
777
778struct chan_iax2_pvt {
779 /*! Socket to send/receive on for this call */
780 int sockfd;
781 /*! ast_callid bound to dialog */
783 /*! Last received voice format */
785 /*! Last received video format */
787 /*! Last sent voice format */
789 /*! Last sent video format */
791 /*! What we are capable of sending */
793 /*! Last received timestamp */
794 unsigned int last;
795 /*! Last sent timestamp - never send the same timestamp twice in a single call */
796 unsigned int lastsent;
797 /*! Timestamp of the last video frame sent */
798 unsigned int lastvsent;
799 /*! Next outgoing timestamp if everything is good */
800 unsigned int nextpred;
801 /*! iax frame subclass that began iax2_pvt entry. 0x8000 bit is set on TX */
803 /*! Last iax frame subclass sent or received for a iax2_pvt. 0x8000 bit is set on TX */
805 /*! True if the last voice we transmitted was not silence/CNG */
806 unsigned int notsilenttx:1;
807 /*! Ping time */
808 unsigned int pingtime;
809 /*! Max time for initial response */
810 int maxtime;
811 /*! Peer Address */
812 struct ast_sockaddr addr;
813 /*! Actual used codec preferences */
814 struct iax2_codec_pref prefs;
815 /*! Requested codec preferences */
816 struct iax2_codec_pref rprefs;
817 /*! Our call number */
818 unsigned short callno;
819 /*! Our callno_entry entry */
821 /*! Peer callno */
822 unsigned short peercallno;
823 /*! Negotiated format, this is only used to remember what format was
824 chosen for an unauthenticated call so that the channel can get
825 created later using the right format. We also use it for
826 authenticated calls to check the format from __get_from_jb. */
828 /*! Peer selected format */
830 /*! Peer capability */
832 /*! timeval that we base our transmission on */
833 struct timeval offset;
834 /*! timeval that we base our delivery on */
835 struct timeval rxcore;
836 /*! The jitterbuffer */
837 jitterbuf *jb;
838 /*! active jb read scheduler id */
839 int jbid;
840 /*! LAG */
841 int lag;
842 /*! Error, as discovered by the manager */
843 int error;
844 /*! Owner if we have one */
845 struct ast_channel *owner;
846 /*! What's our state? */
847 struct ast_flags state;
848 /*! Expiry (optional) */
849 int expiry;
850 /*! Next outgoing sequence number */
851 unsigned char oseqno;
852 /*! Next sequence number they have not yet acknowledged */
853 unsigned char rseqno;
854 /*! Next incoming sequence number */
855 unsigned char iseqno;
856 /*! Last incoming sequence number we have acknowledged */
857 unsigned char aseqno;
858
860 /*! Peer name */
862 /*! Default Context */
864 /*! Caller ID if available */
867 /*! Hidden Caller ID (i.e. ANI) if appropriate */
869 /*! DNID */
871 /*! RDNIS */
873 /*! Requested Extension */
875 /*! Expected Username */
877 /*! Expected Secret */
879 /*! MD5 challenge */
881 /*! Public keys permitted keys for incoming authentication */
883 /*! Private key for outgoing authentication */
885 /*! Preferred language */
887 /*! Hostname/peername for naming purposes */
889
894 /*! received OSP token */
896 /*! Default parkinglot */
898 );
899 /*! AUTHREJ all AUTHREP frames */
900 int authrej;
901 /*! permitted authentication methods */
902 int authmethods;
903 /*! effective authentication method */
904 int eff_auth_method;
905 /*! permitted encryption methods */
906 int encmethods;
907 /*! Encryption AES-128 Key */
909 /*! Decryption AES-128 Key corresponding to ecx */
911 /*! Decryption AES-128 Key used to decrypt peer frames */
913 /*! scheduler id associated with iax_key_rotate
914 * for encrypted calls*/
915 int keyrotateid;
916 /*! 32 bytes of semi-random data */
917 unsigned char semirand[32];
918 /*! Associated registry */
919 struct iax2_registry *reg;
920 /*! Associated peer for poking */
921 struct iax2_peer *peerpoke;
922 /*! IAX_ flags */
923 uint64_t flags;
924 int adsi;
925
926 /*! Transferring status */
928 /*! Transfer identifier */
929 int transferid;
930 /*! Who we are IAX transferring to */
931 struct ast_sockaddr transfer;
932 /*! What's the new call number for the transfer */
933 unsigned short transfercallno;
934 /*! Transfer encrypt AES-128 Key */
936
937 /*! Status of knowledge of peer ADSI capability */
938 int peeradsicpe;
939
940 /*! Callno of native bridge peer. (Valid if nonzero) */
941 unsigned short bridgecallno;
942
943 int pingid; /*!< Transmit PING request */
944 int lagid; /*!< Retransmit lag request */
945 int autoid; /*!< Auto hangup for Dialplan requestor */
946 int authid; /*!< Authentication rejection ID */
947 int authfail; /*!< Reason to report failure */
948 int initid; /*!< Initial peer auto-congest ID (based on qualified peers) */
949 int calling_ton;
950 int calling_tns;
951 int calling_pres;
952 int calling_ani2;
953 int amaflags;
955 /*! variables inherited from the user definition */
956 struct ast_variable *vars;
957 /*! variables transmitted in a NEW packet */
958 struct ast_variable *iaxvars;
959 /*! last received remote rr */
960 struct iax_rr remote_rr;
961 /*! Current base time: (just for stats) */
962 int min;
963 /*! Dropped frame count: (just for stats) */
964 int frames_dropped;
965 /*! received frame count: (just for stats) */
966 int frames_received;
967 /*! Destroying this call initiated. */
969 /*! num bytes used for calltoken ie, even an empty ie should contain 2 */
970 unsigned char calltoken_ie_len;
971 /*! hold all signaling frames from the pbx thread until we have a destination callno */
972 char hold_signaling;
973 /*! frame queue for signaling frames from pbx thread waiting for destination callno */
975};
976
978 struct ast_frame f;
980};
981
982enum callno_type {
985};
986
987#define PTR_TO_CALLNO_ENTRY(a) ((uint16_t)(unsigned long)(a))
988#define CALLNO_ENTRY_TO_PTR(a) ((void *)(unsigned long)(a))
989
990#define CALLNO_ENTRY_SET_VALIDATED(a) ((a) |= 0x8000)
991#define CALLNO_ENTRY_IS_VALIDATED(a) ((a) & 0x8000)
992#define CALLNO_ENTRY_GET_CALLNO(a) ((a) & 0x7FFF)
993
994struct call_number_pool {
995 size_t capacity;
996 size_t available;
998};
999
1001
1002/*! table of available call numbers */
1003static struct call_number_pool callno_pool;
1004
1005/*! table of available trunk call numbers */
1007
1008/*!
1009 * \brief a list of frames that may need to be retransmitted
1010 *
1011 * \note The contents of this list do not need to be explicitly destroyed
1012 * on module unload. This is because all active calls are destroyed, and
1013 * all frames in this queue will get destroyed as a part of that process.
1014 *
1015 * \note Contents protected by the iaxsl[] locks
1016 */
1018
1020
1021static int randomcalltokendata;
1022
1023static time_t max_calltoken_delay = 10;
1024
1025/*!
1026 * This module will get much higher performance when doing a lot of
1027 * user and peer lookups if the number of buckets is increased from 1.
1028 * However, to maintain old behavior for Asterisk 1.4, these are set to
1029 * 1 by default. When using multiple buckets, search order through these
1030 * containers is considered random, so you will not be able to depend on
1031 * the order the entries are specified in iax.conf for matching order. */
1032#ifdef LOW_MEMORY
1033#define MAX_PEER_BUCKETS 17
1034#else
1035#define MAX_PEER_BUCKETS 563
1036#endif
1037static struct ao2_container *peers;
1038
1039#define MAX_USER_BUCKETS MAX_PEER_BUCKETS
1040static struct ao2_container *users;
1041
1042/*! Table containing peercnt objects for every ip address consuming a callno */
1043static struct ao2_container *peercnts;
1044
1045/*! Table containing custom callno limit rules for a range of ip addresses. */
1046static struct ao2_container *callno_limits;
1047
1048/*! Table containing ip addresses not requiring calltoken validation */
1049static struct ao2_container *calltoken_ignores;
1050
1051static uint16_t DEFAULT_MAXCALLNO_LIMIT = 2048;
1052
1053static uint16_t DEFAULT_MAXCALLNO_LIMIT_NONVAL = 8192;
1054
1055static uint16_t global_maxcallno;
1056
1057/*! Total num of call numbers allowed to be allocated without calltoken validation */
1058static uint16_t global_maxcallno_nonval;
1059
1060static uint16_t total_nonval_callno_used = 0;
1061
1062/*! peer connection private, keeps track of all the call numbers
1063 * consumed by a single ip address */
1064struct peercnt {
1065 /*! ip address consuming call numbers */
1066 struct ast_sockaddr addr;
1067 /*! Number of call numbers currently used by this ip address */
1068 uint16_t cur;
1069 /*! Max call numbers allowed for this ip address */
1070 uint16_t limit;
1071 /*! Specifies whether limit is set by a registration or not, if so normal
1072 * limit setting rules do not apply to this address. */
1073 unsigned char reg;
1074};
1075
1076/*! used by both callno_limits and calltoken_ignores containers */
1077struct addr_range {
1078 /*! ip address range for custom callno limit rule */
1079 struct ast_ha ha;
1080 /*! callno limit for this ip address range, only used in callno_limits container */
1081 uint16_t limit;
1082 /*! delete me marker for reloads */
1083 unsigned char delme;
1084};
1085
1086enum {
1087 /*! Extension exists */
1088 CACHE_FLAG_EXISTS = (1 << 0),
1089 /*! Extension is nonexistent */
1090 CACHE_FLAG_NONEXISTENT = (1 << 1),
1091 /*! Extension can exist */
1092 CACHE_FLAG_CANEXIST = (1 << 2),
1093 /*! Waiting to hear back response */
1094 CACHE_FLAG_PENDING = (1 << 3),
1095 /*! Timed out */
1096 CACHE_FLAG_TIMEOUT = (1 << 4),
1097 /*! Request transmitted */
1098 CACHE_FLAG_TRANSMITTED = (1 << 5),
1099 /*! Timeout */
1100 CACHE_FLAG_UNKNOWN = (1 << 6),
1101 /*! Matchmore */
1102 CACHE_FLAG_MATCHMORE = (1 << 7),
1103};
1104
1105struct iax2_dpcache {
1108 struct timeval orig;
1109 struct timeval expiry;
1110 int flags;
1111 unsigned short callno;
1112 int waiters[256];
1115};
1116
1118
1119static void reg_source_db(struct iax2_peer *p);
1120static struct iax2_peer *realtime_peer(const char *peername, struct ast_sockaddr *addr);
1121static struct iax2_user *realtime_user(const char *username, struct ast_sockaddr *addr);
1122
1123static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt);
1124static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags);
1125static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state);
1126
1132};
1133
1134enum iax2_thread_type {
1137};
1138
1139struct iax2_pkt_buf {
1141 size_t len;
1142 unsigned char buf[1];
1143};
1144
1145struct iax2_thread {
1149#ifdef SCHED_MULTITHREADED
1150 void (*schedfunc)(const void *);
1151 const void *scheddata;
1152#endif
1153#ifdef DEBUG_SCHED_MULTITHREAD
1154 char curfunc[80];
1155#endif
1156 int actions;
1157 pthread_t threadid;
1158 int threadnum;
1159 struct ast_sockaddr ioaddr;
1160 unsigned char readbuf[4096];
1161 unsigned char *buf;
1162 ssize_t buf_len;
1163 size_t buf_size;
1164 int iofd;
1165 time_t checktime;
1170 /*! if this thread is processing a full frame,
1171 some information about that frame will be stored
1172 here, so we can avoid dispatching any more full
1173 frames for that callno to other threads */
1174 struct {
1175 unsigned short callno;
1176 struct ast_sockaddr addr;
1177 unsigned char type;
1178 unsigned char csub;
1179 } ffinfo;
1180 /*! Queued up full frames for processing. If more full frames arrive for
1181 * a call which this thread is already processing a full frame for, they
1182 * are queued up here. */
1184 unsigned char stop;
1185};
1186
1187/* Thread lists */
1191
1192static void *iax2_process_thread(void *data);
1193static void iax2_destroy(int callno);
1194
1196{
1200}
1201
1202/*!
1203 * \brief an array of iax2 pvt structures
1204 *
1205 * The container for active chan_iax2_pvt structures is implemented as an
1206 * array for extremely quick direct access to the correct pvt structure
1207 * based on the local call number. The local call number is used as the
1208 * index into the array where the associated pvt structure is stored.
1209 */
1210static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS];
1211
1213{
1214 return iaxs[callno]->callid;
1215}
1216
1218{
1220}
1221
1222static void iax_pvt_callid_new(int callno)
1223{
1225 char buffer[AST_CALLID_BUFFER_LENGTH];
1226 ast_callid_strnprint(buffer, sizeof(buffer), callid);
1228}
1229
1230/*!
1231 * \brief Another container of iax2_pvt structures
1232 *
1233 * Active IAX2 pvt structs are also stored in this container, if they are a part
1234 * of an active call where we know the remote side's call number. The reason
1235 * for this is that incoming media frames do not contain our call number. So,
1236 * instead of having to iterate the entire iaxs array, we use this container to
1237 * look up calls where the remote side is using a given call number.
1238 */
1239static struct ao2_container *iax_peercallno_pvts;
1240
1241/*!
1242 * \brief chan_iax2_pvt structure locks
1243 *
1244 * These locks are used when accessing a pvt structure in the iaxs array.
1245 * The index used here is the same as used in the iaxs array. It is the
1246 * local call number for the associated pvt struct.
1247 */
1249
1250/*!
1251 * \brief Another container of iax2_pvt structures
1252 *
1253 * Active IAX2 pvt structs used during transferring a call are stored here.
1254 */
1256
1257/* Flag to use with trunk calls, keeping these calls high up. It halves our effective use
1258 but keeps the division between trunked and non-trunked better. */
1259#define TRUNK_CALL_START (IAX_MAX_CALLS / 2)
1260
1261/* Debug routines... */
1262static struct ast_sockaddr debugaddr;
1263
1264static void iax_outputframe(struct iax_frame *f, struct ast_iax2_full_hdr *fhi, int rx, struct ast_sockaddr *addr, int datalen)
1265{
1266 if (iaxdebug ||
1267 (addr && !ast_sockaddr_isnull(&debugaddr) &&
1270 !ast_sockaddr_cmp_addr(&debugaddr, addr))) {
1271
1272 if (iaxdebug) {
1273 iax_showframe(f, fhi, rx, addr, datalen);
1274 } else {
1275 iaxdebug = 1;
1276 iax_showframe(f, fhi, rx, addr, datalen);
1277 iaxdebug = 0;
1278 }
1279 }
1280}
1281
1282static void iax_debug_output(const char *data)
1283{
1284 if (iaxdebug)
1285 ast_verbose("%s", data);
1286}
1287
1288static void iax_error_output(const char *data)
1289{
1290 ast_log(LOG_WARNING, "%s", data);
1291}
1292
1293static void __attribute__((format(printf, 1, 2))) jb_error_output(const char *fmt, ...)
1294{
1295 va_list args;
1296 char buf[1024];
1297
1298 va_start(args, fmt);
1299 vsnprintf(buf, sizeof(buf), fmt, args);
1300 va_end(args);
1301
1302 ast_log(LOG_ERROR, "%s", buf);
1303}
1304
1305static void __attribute__((format(printf, 1, 2))) jb_warning_output(const char *fmt, ...)
1306{
1307 va_list args;
1308 char buf[1024];
1309
1310 va_start(args, fmt);
1311 vsnprintf(buf, sizeof(buf), fmt, args);
1312 va_end(args);
1313
1314 ast_log(LOG_WARNING, "%s", buf);
1315}
1316
1317static void __attribute__((format(printf, 1, 2))) jb_debug_output(const char *fmt, ...)
1318{
1319 va_list args;
1320 char buf[1024];
1321
1322 va_start(args, fmt);
1323 vsnprintf(buf, sizeof(buf), fmt, args);
1324 va_end(args);
1325
1326 ast_verbose("%s", buf);
1327}
1328
1329static int expire_registry(const void *data);
1330static int iax2_answer(struct ast_channel *c);
1331static int iax2_call(struct ast_channel *c, const char *dest, int timeout);
1332static int iax2_devicestate(const char *data);
1333static int iax2_digit_begin(struct ast_channel *c, char digit);
1334static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration);
1335static int iax2_do_register(struct iax2_registry *reg);
1336static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
1337static int iax2_hangup(struct ast_channel *c);
1338static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen);
1339static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
1340static int iax2_provision(struct ast_sockaddr *end, int sockfd, const char *dest, const char *template, int force);
1341static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
1342static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
1343static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
1344static int iax2_sendtext(struct ast_channel *c, const char *text);
1345static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
1346static int iax2_queryoption(struct ast_channel *c, int option, void *data, int *datalen);
1347static int iax2_transfer(struct ast_channel *c, const char *dest);
1348static int iax2_write(struct ast_channel *c, struct ast_frame *f);
1349static int iax2_sched_add(struct ast_sched_context *sched, int when, ast_sched_cb callback, const void *data);
1350
1351static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now);
1352static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1353static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1354static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1355static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int);
1356static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
1357static struct ast_channel *iax2_request(const char *type, struct ast_format_cap *cap, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor, const char *data, int *cause);
1358static struct ast_frame *iax2_read(struct ast_channel *c);
1359static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
1360static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
1361static void realtime_update_peer(const char *peername, struct ast_sockaddr *sockaddr, time_t regtime);
1362static void *iax2_dup_variable_datastore(void *);
1363static void prune_peers(void);
1364static void prune_users(void);
1365static void iax2_free_variable_datastore(void *);
1366
1367static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
1368static int decode_frame(ast_aes_decrypt_key *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen);
1369static int encrypt_frame(ast_aes_encrypt_key *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen);
1370static void build_ecx_key(const unsigned char *digest, struct chan_iax2_pvt *pvt);
1371static void build_rand_pad(unsigned char *buf, ssize_t len);
1372static int get_unused_callno(enum callno_type type, int validated, callno_entry *entry);
1373static int replace_callno(const void *obj);
1374static void sched_delay_remove(struct ast_sockaddr *addr, callno_entry entry);
1375static void network_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message);
1376static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message);
1377
1378static struct ast_channel_tech iax2_tech = {
1379 .type = "IAX2",
1380 .description = tdesc,
1381 .properties = AST_CHAN_TP_WANTSJITTER,
1382 .requester = iax2_request,
1383 .devicestate = iax2_devicestate,
1384 .send_digit_begin = iax2_digit_begin,
1385 .send_digit_end = iax2_digit_end,
1386 .send_text = iax2_sendtext,
1387 .send_image = iax2_sendimage,
1388 .send_html = iax2_sendhtml,
1389 .call = iax2_call,
1390 .hangup = iax2_hangup,
1391 .answer = iax2_answer,
1392 .read = iax2_read,
1393 .write = iax2_write,
1394 .write_video = iax2_write,
1395 .indicate = iax2_indicate,
1396 .setoption = iax2_setoption,
1397 .queryoption = iax2_queryoption,
1398 .transfer = iax2_transfer,
1399 .fixup = iax2_fixup,
1400 .func_channel_read = acf_channel_read,
1401};
1402
1403/*!
1404 * \internal
1405 * \brief Obtain the owner channel lock if the owner exists.
1406 *
1407 * \param callno IAX2 call id.
1408 *
1409 * \note Assumes the iaxsl[callno] lock is already obtained.
1410 *
1411 * \note
1412 * IMPORTANT NOTE!!! Any time this function is used, even if
1413 * iaxs[callno] was valid before calling it, it may no longer be
1414 * valid after calling it. This function may unlock and lock
1415 * the mutex associated with this callno, meaning that another
1416 * thread may grab it and destroy the call.
1417 */
1418static void iax2_lock_owner(int callno)
1419{
1420 for (;;) {
1421 if (!iaxs[callno] || !iaxs[callno]->owner) {
1422 /* There is no owner lock to get. */
1423 break;
1424 }
1425 if (!ast_channel_trylock(iaxs[callno]->owner)) {
1426 /* We got the lock */
1427 break;
1428 }
1429 /* Avoid deadlock by pausing and trying again */
1430 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
1431 }
1432}
1433
1434/*!
1435 * \internal
1436 * \brief Check if a control subtype is allowed on the wire.
1437 *
1438 * \param subtype Control frame subtype to check if allowed to/from the wire.
1439 *
1440 * \retval non-zero if allowed.
1441 */
1442static int iax2_is_control_frame_allowed(int subtype)
1443{
1444 enum ast_control_frame_type control = subtype;
1445 int is_allowed;
1446
1447 /*
1448 * Note: If we compare the enumeration type, which does not have any
1449 * negative constants, the compiler may optimize this code away.
1450 * Therefore, we must perform an integer comparison here.
1451 */
1452 if (subtype == -1) {
1453 return -1;
1454 }
1455
1456 /* Default to not allowing control frames to pass. */
1457 is_allowed = 0;
1458
1459 /*
1460 * The switch default is not present in order to take advantage
1461 * of the compiler complaining of a missing enum case.
1462 */
1463 switch (control) {
1464 /*
1465 * These control frames make sense to send/receive across the link.
1466 */
1467 case AST_CONTROL_HANGUP:
1468 case AST_CONTROL_RING:
1470 case AST_CONTROL_ANSWER:
1471 case AST_CONTROL_BUSY:
1475 case AST_CONTROL_FLASH:
1476 case AST_CONTROL_WINK:
1477 case AST_CONTROL_OPTION:
1482 case AST_CONTROL_HOLD:
1483 case AST_CONTROL_UNHOLD:
1488 case AST_CONTROL_AOC:
1490 case AST_CONTROL_MCID:
1491 is_allowed = -1;
1492 break;
1493
1494 /*
1495 * These control frames do not make sense to send/receive across the link.
1496 */
1498 /* The control value is deprecated in favor of AST_CONTROL_T38_PARAMETERS. */
1500 /* Across an IAX link the source is still the same. */
1502 /* A success/fail status report from calling ast_transfer() on this machine. */
1503 case AST_CONTROL_CC:
1504 /* The payload contains pointers that are valid for the sending machine only. */
1506 /* Across an IAX link the source is still the same. */
1508 /* The action can only be done by the sending machine. */
1510 /* This frame would cause the call to unexpectedly hangup. */
1512 /* Only meaningful across a bridge on this machine for direct-media exchange. */
1514 /* Intended only for the sending machine's local channel structure. */
1516 /* Intended only for masquerades when calling ast_indicate_data(). */
1518 /* Intended only for internal stream topology manipulation. */
1520 /* Intended only for internal stream topology change notification. */
1527 case AST_CONTROL_PLAYBACK_BEGIN: /* Only supported by app_dial currently */
1528 /* None of these playback stream control frames should go across the link. */
1533 /* None of these media recording control frames should go across the link. */
1534 break;
1535 }
1536 return is_allowed;
1537}
1538
1539static void network_change_stasis_subscribe(void)
1540{
1541 if (!network_change_sub) {
1546 }
1547}
1548
1549static void network_change_stasis_unsubscribe(void)
1550{
1552}
1553
1554static void acl_change_stasis_subscribe(void)
1555{
1556 if (!acl_change_sub) {
1561 }
1562}
1563
1564static void acl_change_stasis_unsubscribe(void)
1565{
1567}
1568
1569static int network_change_sched_cb(const void *data)
1570{
1571 struct iax2_registry *reg;
1575 iax2_do_register(reg);
1576 }
1578
1579 return 0;
1580}
1581
1582static void network_change_stasis_cb(void *data, struct stasis_subscription *sub,
1583 struct stasis_message *message)
1584{
1585 /* This callback is only concerned with network change messages from the system topic. */
1587 return;
1588 }
1589
1590 ast_verb(1, "IAX, got a network change message, renewing all IAX registrations.\n");
1591 if (network_change_sched_id == -1) {
1593 }
1594}
1595
1596static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub,
1597 struct stasis_message *message)
1598{
1600 return;
1601 }
1602
1603 ast_log(LOG_NOTICE, "Reloading chan_iax2 in response to ACL change event.\n");
1604 reload_config(1);
1605}
1606
1608 .type = "IAX2_VARIABLE",
1609 .duplicate = iax2_dup_variable_datastore,
1611};
1612
1613static void *iax2_dup_variable_datastore(void *old)
1614{
1615 AST_LIST_HEAD(, ast_var_t) *oldlist = old, *newlist;
1616 struct ast_var_t *oldvar, *newvar;
1617
1618 newlist = ast_calloc(sizeof(*newlist), 1);
1619 if (!newlist) {
1620 ast_log(LOG_ERROR, "Unable to duplicate iax2 variables\n");
1621 return NULL;
1622 }
1623
1624 AST_LIST_HEAD_INIT(newlist);
1625 AST_LIST_LOCK(oldlist);
1626 AST_LIST_TRAVERSE(oldlist, oldvar, entries) {
1627 newvar = ast_var_assign(ast_var_name(oldvar), ast_var_value(oldvar));
1628 if (newvar)
1629 AST_LIST_INSERT_TAIL(newlist, newvar, entries);
1630 else
1631 ast_log(LOG_ERROR, "Unable to duplicate iax2 variable '%s'\n", ast_var_name(oldvar));
1632 }
1633 AST_LIST_UNLOCK(oldlist);
1634 return newlist;
1635}
1636
1637static void iax2_free_variable_datastore(void *old)
1638{
1639 AST_LIST_HEAD(, ast_var_t) *oldlist = old;
1640 struct ast_var_t *oldvar;
1641
1642 AST_LIST_LOCK(oldlist);
1643 while ((oldvar = AST_LIST_REMOVE_HEAD(oldlist, entries))) {
1644 ast_free(oldvar);
1645 }
1646 AST_LIST_UNLOCK(oldlist);
1647 AST_LIST_HEAD_DESTROY(oldlist);
1648 ast_free(oldlist);
1649}
1650
1651
1652/* WARNING: insert_idle_thread should only ever be called within the
1653 * context of an iax2_process_thread() thread.
1654 */
1655static void insert_idle_thread(struct iax2_thread *thread)
1656{
1657 if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
1661 } else {
1665 }
1666
1667 return;
1668}
1669
1670static struct iax2_thread *find_idle_thread(void)
1671{
1672 struct iax2_thread *thread = NULL;
1673
1674 /* Pop the head of the idle list off */
1678
1679 /* If we popped a thread off the idle list, just return it */
1680 if (thread) {
1681 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1682 return thread;
1683 }
1684
1685 /* Pop the head of the dynamic list off */
1689
1690 /* If we popped a thread off the dynamic list, just return it */
1691 if (thread) {
1692 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1693 return thread;
1694 }
1695
1696 /* If we can't create a new dynamic thread for any reason, return no thread at all */
1698 return NULL;
1699
1700 /* Set default values */
1704
1705 /* Initialize lock and condition */
1706 ast_mutex_init(&thread->lock);
1707 ast_cond_init(&thread->cond, NULL);
1708 ast_mutex_init(&thread->init_lock);
1709 ast_cond_init(&thread->init_cond, NULL);
1710 ast_mutex_lock(&thread->init_lock);
1711
1712 /* Create thread and send it on it's way */
1714 ast_cond_destroy(&thread->cond);
1715 ast_mutex_destroy(&thread->lock);
1716 ast_mutex_unlock(&thread->init_lock);
1717 ast_cond_destroy(&thread->init_cond);
1718 ast_mutex_destroy(&thread->init_lock);
1720 return NULL;
1721 }
1722
1723 /* this thread is not processing a full frame (since it is idle),
1724 so ensure that the field for the full frame call number is empty */
1725 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1726
1727 /* Wait for the thread to be ready before returning it to the caller */
1728 ast_cond_wait(&thread->init_cond, &thread->init_lock);
1729
1730 /* Done with init_lock */
1731 ast_mutex_unlock(&thread->init_lock);
1732
1733 return thread;
1734}
1735
1736#ifdef SCHED_MULTITHREADED
1737static int __schedule_action(void (*func)(const void *data), const void *data, const char *funcname)
1738{
1739 struct iax2_thread *thread;
1740 static time_t lasterror;
1741 time_t t;
1742
1744 if (thread != NULL) {
1745 thread->schedfunc = func;
1746 thread->scheddata = data;
1747 thread->iostate = IAX_IOSTATE_SCHEDREADY;
1748#ifdef DEBUG_SCHED_MULTITHREAD
1749 ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc));
1750#endif
1751 signal_condition(&thread->lock, &thread->cond);
1752 return 0;
1753 }
1754 time(&t);
1755 if (t != lasterror) {
1756 lasterror = t;
1757 ast_debug(1, "Out of idle IAX2 threads for scheduling! (%s)\n", funcname);
1758 }
1759
1760 return -1;
1761}
1762#define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
1763#endif
1764
1765static int iax2_sched_replace(int id, struct ast_sched_context *con, int when,
1766 ast_sched_cb callback, const void *data)
1767{
1768 return ast_sched_replace(id, con, when, callback, data);
1769}
1770
1771static int iax2_sched_add(struct ast_sched_context *con, int when,
1772 ast_sched_cb callback, const void *data)
1773{
1774 return ast_sched_add(con, when, callback, data);
1775}
1776
1777/*!
1778 * \brief Acquire the iaxsl[callno] if call exists and not having ongoing hangup.
1779 * \param callno Call number to lock.
1780 * \retval 0 If call disappeared or has ongoing hangup procedure.
1781 * \retval 1 If call found and mutex is locked.
1782 */
1784{
1786
1787 /* We acquired the lock; but the call was already destroyed (we came after full hang up procedures)
1788 * or destroy initiated (in middle of hang up procedure. */
1789 if (!iaxs[callno] || iaxs[callno]->destroy_initiated) {
1790 ast_debug(3, "I wanted to lock callno %d, but it is dead or going to die.\n", callno);
1792 return 0;
1793 }
1794
1795 /* Lock acquired, and callno is alive and kicking. */
1796 return 1;
1797}
1798
1799static int send_ping(const void *data);
1800
1801static void __send_ping(const void *data)
1802{
1803 int callno = PTR_TO_CALLNO(data);
1804
1806 ast_debug(3, "Hangup initiated on call %d, aborting __send_ping\n", callno);
1807 return;
1808 }
1809
1810 /* Mark pingid as invalid scheduler id. */
1811 iaxs[callno]->pingid = -1;
1812
1813 /* callno is now locked. */
1814 if (iaxs[callno]->peercallno) {
1815 /* Send PING packet. */
1817
1818 /* Schedule sending next ping. */
1820 }
1821
1823}
1824
1825static int send_ping(const void *data)
1826{
1827#ifdef SCHED_MULTITHREADED
1828 if (schedule_action(__send_ping, data))
1829#endif
1830 __send_ping(data);
1831
1832 return 0;
1833}
1834
1835static void encmethods_to_str(int e, struct ast_str **buf)
1836{
1837 ast_str_set(buf, 0, "(");
1838 if (e & IAX_ENCRYPT_AES128) {
1839 ast_str_append(buf, 0, "aes128");
1840 }
1841 if (e & IAX_ENCRYPT_KEYROTATE) {
1842 ast_str_append(buf, 0, ",keyrotate");
1843 }
1844 if (ast_str_strlen(*buf) > 1) {
1845 ast_str_append(buf, 0, ")");
1846 } else {
1847 ast_str_set(buf, 0, "No");
1848 }
1849}
1850
1851static int get_encrypt_methods(const char *s)
1852{
1853 int e;
1854 if (!strcasecmp(s, "aes128"))
1856 else if (ast_true(s))
1858 else
1859 e = 0;
1860 return e;
1861}
1862
1863static int send_lagrq(const void *data);
1864
1865static void __send_lagrq(const void *data)
1866{
1867 int callno = PTR_TO_CALLNO(data);
1868
1870 ast_debug(3, "Hangup initiated on call %d, aborting __send_lagrq\n", callno);
1871 return;
1872 }
1873
1874 /* Mark lagid as invalid scheduler id. */
1875 iaxs[callno]->lagid = -1;
1876
1877 /* callno is now locked. */
1878 if (iaxs[callno]->peercallno) {
1879 /* Send LAGRQ packet. */
1881
1882 /* Schedule sending next lagrq. */
1884 }
1885
1887}
1888
1889static int send_lagrq(const void *data)
1890{
1891#ifdef SCHED_MULTITHREADED
1892 if (schedule_action(__send_lagrq, data))
1893#endif
1894 __send_lagrq(data);
1895 return 0;
1896}
1897
1898static unsigned char compress_subclass(iax2_format subclass)
1899{
1900 int x;
1901 int power=-1;
1902 /* If it's 64 or smaller, just return it */
1903 if (subclass < IAX_FLAG_SC_LOG)
1904 return subclass;
1905 /* Otherwise find its power */
1906 for (x = 0; x < IAX_MAX_SHIFT; x++) {
1907 if (subclass & (1LL << x)) {
1908 if (power > -1) {
1909 ast_log(LOG_WARNING, "Can't compress subclass %lld\n", (long long) subclass);
1910 return 0;
1911 } else
1912 power = x;
1913 }
1914 }
1915 return power | IAX_FLAG_SC_LOG;
1916}
1917
1918static iax2_format uncompress_subclass(unsigned char csub)
1919{
1920 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
1921 if (csub & IAX_FLAG_SC_LOG) {
1922 /* special case for 'compressed' -1 */
1923 if (csub == 0xff)
1924 return -1;
1925 else
1926 return 1LL << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
1927 }
1928 else
1929 return csub;
1930}
1931
1932static struct ast_format *codec_choose_from_prefs(struct iax2_codec_pref *pref, struct ast_format_cap *cap)
1933{
1934 int x;
1935 struct ast_format *found_format = NULL;
1936
1937 for (x = 0; x < ARRAY_LEN(pref->order); ++x) {
1938 struct ast_format *pref_format;
1939 uint64_t pref_bitfield;
1940
1941 pref_bitfield = iax2_codec_pref_order_value_to_format_bitfield(pref->order[x]);
1942 if (!pref_bitfield) {
1943 break;
1944 }
1945
1946 pref_format = ast_format_compatibility_bitfield2format(pref_bitfield);
1947 if (!pref_format) {
1948 /* The bitfield is not associated with any format. */
1949 continue;
1950 }
1951 found_format = ast_format_cap_get_compatible_format(cap, pref_format);
1952 if (found_format) {
1953 break;
1954 }
1955 }
1956
1957 if (found_format && (ast_format_get_type(found_format) == AST_MEDIA_TYPE_AUDIO)) {
1958 return found_format;
1959 }
1960
1961 ast_debug(4, "Could not find preferred codec - Returning zero codec.\n");
1962 ao2_cleanup(found_format);
1963 return NULL;
1964}
1965
1967{
1968 struct ast_format_cap *cap;
1969 struct ast_format *tmpfmt;
1970 iax2_format format = 0;
1971
1974 tmpfmt = codec_choose_from_prefs(pref, cap);
1975 if (!tmpfmt) {
1976 ao2_ref(cap, -1);
1977 return 0;
1978 }
1979
1981 ao2_ref(tmpfmt, -1);
1982 ao2_ref(cap, -1);
1983 }
1984
1985 return format;
1986}
1987
1988const char *iax2_getformatname(iax2_format format)
1989{
1990 struct ast_format *tmpfmt;
1991
1993 if (!tmpfmt) {
1994 return "Unknown";
1995 }
1996
1997 return ast_format_get_name(tmpfmt);
1998}
1999
2000static const char *iax2_getformatname_multiple(iax2_format format, struct ast_str **codec_buf)
2001{
2003
2004 if (!cap) {
2005 return "(Nothing)";
2006 }
2008 ast_format_cap_get_names(cap, codec_buf);
2009 ao2_ref(cap, -1);
2010
2011 return ast_str_buffer(*codec_buf);
2012}
2013
2014static int iax2_parse_allow_disallow(struct iax2_codec_pref *pref, iax2_format *formats, const char *list, int allowing)
2015{
2016 int res, i;
2017 struct ast_format_cap *cap;
2018
2019 /* We want to add the formats to the cap in the preferred order */
2021 if (!cap || iax2_codec_pref_to_cap(pref, cap)) {
2022 ao2_cleanup(cap);
2023 return 1;
2024 }
2025
2026 res = ast_format_cap_update_by_allow_disallow(cap, list, allowing);
2027
2028 /* Adjust formats bitfield and pref list to match. */
2031
2032 for (i = 0; i < ast_format_cap_count(cap); i++) {
2033 struct ast_format *fmt = ast_format_cap_get_format(cap, i);
2034
2036 ao2_ref(fmt, -1);
2037 }
2038
2039 ao2_ref(cap, -1);
2040
2041 return res;
2042}
2043
2044/*!
2045 * \note The only member of the peer passed here guaranteed to be set is the name field
2046 */
2047static int peer_hash_cb(const void *obj, const int flags)
2048{
2049 const struct iax2_peer *peer = obj;
2050 const char *name = obj;
2051
2052 return ast_str_hash(flags & OBJ_KEY ? name : peer->name);
2053}
2054
2055/*!
2056 * \note The only member of the peer passed here guaranteed to be set is the name field
2057 */
2058static int peer_cmp_cb(void *obj, void *arg, int flags)
2059{
2060 struct iax2_peer *peer = obj, *peer2 = arg;
2061 const char *name = arg;
2062
2063 return !strcmp(peer->name, flags & OBJ_KEY ? name : peer2->name) ?
2064 CMP_MATCH | CMP_STOP : 0;
2065}
2066
2067/*!
2068 * \note The only member of the user passed here guaranteed to be set is the name field
2069 */
2070static int user_hash_cb(const void *obj, const int flags)
2071{
2072 const struct iax2_user *user = obj;
2073 const char *name = obj;
2074
2075 return ast_str_hash(flags & OBJ_KEY ? name : user->name);
2076}
2077
2078/*!
2079 * \note The only member of the user passed here guaranteed to be set is the name field
2080 */
2081static int user_cmp_cb(void *obj, void *arg, int flags)
2082{
2083 struct iax2_user *user = obj, *user2 = arg;
2084 const char *name = arg;
2085
2086 return !strcmp(user->name, flags & OBJ_KEY ? name : user2->name) ?
2087 CMP_MATCH | CMP_STOP : 0;
2088}
2089
2090/*!
2091 * \note This function calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
2092 * so do not call it with a pvt lock held.
2093 */
2094static struct iax2_peer *find_peer(const char *name, int realtime)
2095{
2096 struct iax2_peer *peer = NULL;
2097
2098 peer = ao2_find(peers, name, OBJ_KEY);
2099
2100 /* Now go for realtime if applicable */
2101 if (!peer && realtime) {
2102 peer = realtime_peer(name, NULL);
2103 }
2104 return peer;
2105}
2106
2107static struct iax2_peer *peer_ref(struct iax2_peer *peer)
2108{
2109 ao2_ref(peer, +1);
2110 return peer;
2111}
2112
2113static inline struct iax2_peer *peer_unref(struct iax2_peer *peer)
2114{
2115 ao2_ref(peer, -1);
2116 return NULL;
2117}
2118
2119static struct iax2_user *find_user(const char *name)
2120{
2121 return ao2_find(users, name, OBJ_KEY);
2122}
2123
2124static inline struct iax2_user *user_unref(struct iax2_user *user)
2125{
2126 ao2_ref(user, -1);
2127 return NULL;
2128}
2129
2130static int iax2_getpeername(struct ast_sockaddr addr, char *host, int len)
2131{
2132 struct iax2_peer *peer = NULL;
2133 int res = 0;
2134 struct ao2_iterator i;
2135
2136 i = ao2_iterator_init(peers, 0);
2137 while ((peer = ao2_iterator_next(&i))) {
2138
2139 if (!ast_sockaddr_cmp(&peer->addr, &addr)) {
2140 ast_copy_string(host, peer->name, len);
2141 peer_unref(peer);
2142 res = 1;
2143 break;
2144 }
2145 peer_unref(peer);
2146 }
2148
2149 if (!peer) {
2150 peer = realtime_peer(NULL, &addr);
2151 if (peer) {
2152 ast_copy_string(host, peer->name, len);
2153 peer_unref(peer);
2154 res = 1;
2155 }
2156 }
2157
2158 return res;
2159}
2160
2161/* Call AST_SCHED_DEL on a scheduled task if it is found in scheduler. */
2162static int iax2_delete_from_sched(const void* data)
2163{
2164 int sched_id = (int)(long)data;
2165
2167
2168 return 0;
2169}
2170
2171/*!\note Assumes the lock on the pvt is already held, when
2172 * iax2_destroy_helper() is called. */
2173static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
2174{
2175 /* Decrement AUTHREQ count if needed */
2176 if (ast_test_flag64(pvt, IAX_MAXAUTHREQ)) {
2177 struct iax2_user *user;
2178
2180 if (user) {
2181 ast_atomic_fetchadd_int(&user->curauthreq, -1);
2183 }
2184
2186 }
2187
2188
2189 /* Mark call destroy initiated flag. */
2190 pvt->destroy_initiated = 1;
2191
2192 /*
2193 * Schedule deleting the scheduled (but didn't run yet) PINGs or LAGRQs.
2194 * Already running tasks will be terminated because of destroy_initiated.
2195 *
2196 * Don't call AST_SCHED_DEL from this thread for pingid and lagid because
2197 * it leads to a deadlock between the scheduler thread callback locking
2198 * the callno mutex and this thread which holds the callno mutex one or
2199 * more times. It is better to have another thread delete the scheduled
2200 * callbacks which doesn't lock the callno mutex.
2201 */
2202 iax2_sched_add(sched, 0, iax2_delete_from_sched, (void*)(long)pvt->pingid);
2203 iax2_sched_add(sched, 0, iax2_delete_from_sched, (void*)(long)pvt->lagid);
2204
2205 pvt->pingid = -1;
2206 pvt->lagid = -1;
2207
2208 AST_SCHED_DEL(sched, pvt->autoid);
2209 AST_SCHED_DEL(sched, pvt->authid);
2210 AST_SCHED_DEL(sched, pvt->initid);
2211 AST_SCHED_DEL(sched, pvt->jbid);
2213}
2214
2215static void iax2_frame_free(struct iax_frame *fr)
2216{
2218 iax_frame_free(fr);
2219}
2220
2221static int scheduled_destroy(const void *vid)
2222{
2223 unsigned short callno = PTR_TO_CALLNO(vid);
2224 ast_mutex_lock(&iaxsl[callno]);
2225 if (iaxs[callno]) {
2226 ast_debug(1, "Really destroying %d now...\n", callno);
2227 iax2_destroy(callno);
2228 }
2229 ast_mutex_unlock(&iaxsl[callno]);
2230 return 0;
2231}
2232
2234{
2235 if (s->f.datalen) {
2236 ast_free(s->f.data.ptr);
2237 }
2238 ast_free(s);
2239}
2240
2241/*! \brief This function must be called once we are sure the other side has
2242 * given us a call number. All signaling is held here until that point. */
2243static void send_signaling(struct chan_iax2_pvt *pvt)
2244{
2245 struct signaling_queue_entry *s = NULL;
2246
2247 while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
2248 iax2_send(pvt, &s->f, 0, -1, 0, 0, 0);
2250 }
2251 pvt->hold_signaling = 0;
2252}
2253
2254/*! \brief All frames other than that of type AST_FRAME_IAX must be held until
2255 * we have received a destination call number. */
2256static int queue_signalling(struct chan_iax2_pvt *pvt, struct ast_frame *f)
2257{
2258 struct signaling_queue_entry *qe;
2259
2260 if (f->frametype == AST_FRAME_IAX || !pvt->hold_signaling) {
2261 return 1; /* do not queue this frame */
2262 } else if (!(qe = ast_calloc(1, sizeof(struct signaling_queue_entry)))) {
2263 return -1; /* out of memory */
2264 }
2265
2266 /* copy ast_frame into our queue entry */
2267 qe->f = *f;
2268 if (qe->f.datalen) {
2269 /* if there is data in this frame copy it over as well */
2270 if (!(qe->f.data.ptr = ast_malloc(qe->f.datalen))) {
2272 return -1;
2273 }
2274 memcpy(qe->f.data.ptr, f->data.ptr, qe->f.datalen);
2275 }
2277
2278 return 0;
2279}
2280
2281static void pvt_destructor(void *obj)
2282{
2283 struct chan_iax2_pvt *pvt = obj;
2284 struct iax_frame *cur = NULL;
2285 struct signaling_queue_entry *s = NULL;
2286
2287 ast_mutex_lock(&iaxsl[pvt->callno]);
2288
2290
2292 pvt->callno_entry = 0;
2293
2294 /* Already gone */
2296
2297 AST_LIST_TRAVERSE(&frame_queue[pvt->callno], cur, list) {
2298 /* Cancel any pending transmissions */
2299 cur->retries = -1;
2300 }
2301
2303
2304 while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
2306 }
2307
2308 if (pvt->reg) {
2309 pvt->reg->callno = 0;
2310 }
2311
2312 if (!pvt->owner) {
2313 jb_frame frame;
2314 if (pvt->vars) {
2316 pvt->vars = NULL;
2317 }
2318
2319 while (jb_getall(pvt->jb, &frame) == JB_OK) {
2320 iax2_frame_free(frame.data);
2321 }
2322
2323 jb_destroy(pvt->jb);
2325 }
2326}
2327
2328static struct chan_iax2_pvt *new_iax(struct ast_sockaddr *addr, const char *host)
2329{
2330 struct chan_iax2_pvt *tmp;
2331 jb_conf jbconf;
2332
2333 if (!(tmp = ao2_alloc(sizeof(*tmp), pvt_destructor))) {
2334 return NULL;
2335 }
2336
2337 tmp->pingid = -1;
2338 tmp->lagid = -1;
2339 tmp->autoid = -1;
2340 tmp->authid = -1;
2341 tmp->initid = -1;
2342 tmp->keyrotateid = -1;
2343 tmp->jbid = -1;
2344
2345 if (ast_string_field_init(tmp, 32)) {
2346 ao2_ref(tmp, -1);
2347 tmp = NULL;
2348 return NULL;
2349 }
2350
2351 tmp->prefs = prefs_global;
2352
2353 ast_string_field_set(tmp,exten, "s");
2355
2356 tmp->jb = jb_new();
2361 jb_setconf(tmp->jb,&jbconf);
2362
2364
2365 tmp->hold_signaling = 1;
2367
2368 return tmp;
2369}
2370
2371static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
2372{
2374 if (new) {
2375 size_t afdatalen = new->afdatalen;
2376 memcpy(new, fr, sizeof(*new));
2377 iax_frame_wrap(new, &fr->af);
2378 new->afdatalen = afdatalen;
2379 new->data = NULL;
2380 new->datalen = 0;
2381 new->direction = DIRECTION_INGRESS;
2382 new->retrans = -1;
2383 }
2384 return new;
2385}
2386/* keep these defined in this order. They are used in find_callno to
2387 * determine whether or not a new call number should be allowed. */
2388enum {
2389 /* do not allow a new call number, only search ones in use for match */
2390 NEW_PREVENT = 0,
2391 /* search for match first, then allow a new one to be allocated */
2392 NEW_ALLOW = 1,
2393 /* do not search for match, force a new call number */
2394 NEW_FORCE = 2,
2395 /* do not search for match, force a new call number. Signifies call number
2396 * has been calltoken validated */
2398};
2399
2400static int match(struct ast_sockaddr *addr, unsigned short callno, unsigned short dcallno, const struct chan_iax2_pvt *cur, int check_dcallno)
2401{
2402 if (!ast_sockaddr_cmp(&cur->addr, addr)) {
2403 /* This is the main host */
2404 if ( (cur->peercallno == 0 || cur->peercallno == callno) &&
2405 (check_dcallno ? dcallno == cur->callno : 1) ) {
2406 /* That's us. Be sure we keep track of the peer call number */
2407 return 1;
2408 }
2409 }
2410 if (!ast_sockaddr_cmp(&cur->transfer, addr) && cur->transferring) {
2411 /* We're transferring */
2412 if ((dcallno == cur->callno) || (cur->transferring == TRANSFER_MEDIAPASS && cur->transfercallno == callno))
2413 return 1;
2414 }
2415 return 0;
2416}
2417
2418static int make_trunk(unsigned short callno, int locked)
2419{
2420 int x;
2421 int res= 0;
2422 callno_entry entry;
2423 if (iaxs[callno]->oseqno) {
2424 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
2425 return -1;
2426 }
2427 if (callno >= TRUNK_CALL_START) {
2428 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
2429 return -1;
2430 }
2431
2435 &entry)) {
2436 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
2437 return -1;
2438 }
2439
2440 x = CALLNO_ENTRY_GET_CALLNO(entry);
2441 ast_mutex_lock(&iaxsl[x]);
2442
2443 /*!
2444 * \note We delete these before switching the slot, because if
2445 * they fire in the meantime, they will generate a warning.
2446 */
2447 AST_SCHED_DEL(sched, iaxs[callno]->pingid);
2448 AST_SCHED_DEL(sched, iaxs[callno]->lagid);
2449 iaxs[callno]->lagid = iaxs[callno]->pingid = -1;
2450 iaxs[x] = iaxs[callno];
2451 iaxs[x]->callno = x;
2452
2453 /* since we copied over the pvt from a different callno, make sure the old entry is replaced
2454 * before assigning the new one */
2455 if (iaxs[x]->callno_entry) {
2457 sched,
2458 MIN_REUSE_TIME * 1000,
2461
2462 }
2463 iaxs[x]->callno_entry = entry;
2464
2465 iaxs[callno] = NULL;
2466 /* Update the two timers that should have been started */
2468 ping_time * 1000, send_ping, (void *)(long)x);
2470 lagrq_time * 1000, send_lagrq, (void *)(long)x);
2471
2472 if (locked)
2474 res = x;
2475 if (!locked)
2477
2478 /* We moved this call from a non-trunked to a trunked call */
2479 ast_debug(1, "Made call %d into trunk call %d\n", callno, x);
2480
2481 return res;
2482}
2483
2484static void store_by_transfercallno(struct chan_iax2_pvt *pvt)
2485{
2486 if (!pvt->transfercallno) {
2487 ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
2488 return;
2489 }
2490
2492}
2493
2494static void remove_by_transfercallno(struct chan_iax2_pvt *pvt)
2495{
2496 if (!pvt->transfercallno) {
2497 ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
2498 return;
2499 }
2500
2502}
2503static void store_by_peercallno(struct chan_iax2_pvt *pvt)
2504{
2505 if (!pvt->peercallno) {
2506 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
2507 return;
2508 }
2509
2511}
2512
2513static void remove_by_peercallno(struct chan_iax2_pvt *pvt)
2514{
2515 if (!pvt->peercallno) {
2516 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
2517 return;
2518 }
2519
2521}
2522
2523static int addr_range_delme_cb(void *obj, void *arg, int flags)
2524{
2525 struct addr_range *lim = obj;
2526 lim->delme = 1;
2527 return 0;
2528}
2529
2530static int addr_range_hash_cb(const void *obj, const int flags)
2531{
2532 const struct addr_range *lim = obj;
2533 return abs(ast_sockaddr_hash(&lim->ha.addr));
2534}
2535
2536static int addr_range_cmp_cb(void *obj, void *arg, int flags)
2537{
2538 struct addr_range *lim1 = obj, *lim2 = arg;
2539 return (!(ast_sockaddr_cmp_addr(&lim1->ha.addr, &lim2->ha.addr)) &&
2540 !(ast_sockaddr_cmp_addr(&lim1->ha.netmask, &lim2->ha.netmask))) ?
2541 CMP_MATCH | CMP_STOP : 0;
2542}
2543
2544static int peercnt_hash_cb(const void *obj, const int flags)
2545{
2546 const struct peercnt *peercnt = obj;
2547
2549 return 0;
2550 }
2551 return ast_sockaddr_hash(&peercnt->addr);
2552}
2553
2554static int peercnt_cmp_cb(void *obj, void *arg, int flags)
2555{
2556 struct peercnt *peercnt1 = obj, *peercnt2 = arg;
2557 return !ast_sockaddr_cmp_addr(&peercnt1->addr, &peercnt2->addr) ? CMP_MATCH | CMP_STOP : 0;
2558}
2559
2560static int addr_range_match_address_cb(void *obj, void *arg, int flags)
2561{
2562 struct addr_range *addr_range = obj;
2563 struct ast_sockaddr *addr = arg;
2564 struct ast_sockaddr tmp_addr;
2565
2566 ast_sockaddr_apply_netmask(addr, &addr_range->ha.netmask, &tmp_addr);
2567
2568 if (!ast_sockaddr_cmp_addr(&tmp_addr, &addr_range->ha.addr)) {
2569 return CMP_MATCH | CMP_STOP;
2570 }
2571 return 0;
2572}
2573
2574/*!
2575 * \internal
2576 *
2577 * \brief compares addr to calltoken_ignores table to determine if validation is required.
2578 */
2579static int calltoken_required(struct ast_sockaddr *addr, const char *name, int subclass)
2580{
2581 struct addr_range *addr_range;
2582 struct iax2_peer *peer = NULL;
2583 struct iax2_user *user = NULL;
2584 /* if no username is given, check for guest accounts */
2585 const char *find = S_OR(name, "guest");
2586 int res = 1; /* required by default */
2587 int optional = 0;
2589 /* There are only two cases in which calltoken validation is not required.
2590 * Case 1. sin falls within the list of address ranges specified in the calltoken optional table and
2591 * the peer definition has not set the requirecalltoken option.
2592 * Case 2. Username is a valid peer/user, and that peer has requirecalltoken set either auto or no.
2593 */
2594
2595 /* ----- Case 1 ----- */
2597 ao2_ref(addr_range, -1);
2598 optional = 1;
2599 }
2600
2601 /* ----- Case 2 ----- */
2602 if ((subclass == IAX_COMMAND_NEW) && (user = find_user(find))) {
2603 calltoken_required = user->calltoken_required;
2604 } else if ((subclass == IAX_COMMAND_NEW) && (user = realtime_user(find, addr))) {
2605 calltoken_required = user->calltoken_required;
2606 } else if ((subclass != IAX_COMMAND_NEW) && (peer = find_peer(find, 0))) {
2608 } else if ((subclass != IAX_COMMAND_NEW) && (peer = realtime_peer(find, addr))) {
2610 }
2611
2612 if (peer) {
2613 peer_unref(peer);
2614 }
2615 if (user) {
2617 }
2618
2619 ast_debug(1, "Determining if address %s with username %s requires calltoken validation. Optional = %d calltoken_required = %u \n", ast_sockaddr_stringify_addr(addr), name, optional, calltoken_required);
2621 (optional && (calltoken_required == CALLTOKEN_DEFAULT))) {
2622 res = 0;
2623 }
2624
2625 return res;
2626}
2627
2628/*!
2629 * \internal
2630 *
2631 * \brief set peercnt callno limit.
2632 *
2633 * \details
2634 * First looks in custom definitions. If not found, global limit
2635 * is used. Entries marked as reg already have
2636 * a custom limit set by a registration and are not modified.
2637 */
2638static void set_peercnt_limit(struct peercnt *peercnt)
2639{
2640 uint16_t limit = global_maxcallno;
2641 struct addr_range *addr_range;
2642 struct ast_sockaddr addr;
2643
2644 ast_sockaddr_copy(&addr, &peercnt->addr);
2645
2646 if (peercnt->reg && peercnt->limit) {
2647 return; /* this peercnt has a custom limit set by a registration */
2648 }
2649
2651 limit = addr_range->limit;
2652 ast_debug(1, "custom addr_range %d found for %s\n", limit, ast_sockaddr_stringify(&addr));
2653 ao2_ref(addr_range, -1);
2654 }
2655
2656 peercnt->limit = limit;
2657}
2658
2659/*!
2660 * \internal
2661 * \brief sets limits for all peercnts in table. done on reload to reflect changes in conf.
2662 */
2663static int set_peercnt_limit_all_cb(void *obj, void *arg, int flags)
2664{
2665 struct peercnt *peercnt = obj;
2666
2668 ast_debug(1, "Reset limits for peercnts table\n");
2669
2670 return 0;
2671}
2672
2673/*!
2674 * \internal
2675 * \brief returns match if delme is set.
2676 */
2677static int prune_addr_range_cb(void *obj, void *arg, int flags)
2678{
2679 struct addr_range *addr_range = obj;
2680
2681 return addr_range->delme ? CMP_MATCH : 0;
2682}
2683
2684/*!
2685 * \internal
2686 * \brief modifies peercnt entry in peercnts table. Used to set custom limit or mark a registered ip
2687 */
2688static void peercnt_modify(unsigned char reg, uint16_t limit, struct ast_sockaddr *sockaddr)
2689{
2690 /* this function turns off and on custom callno limits set by peer registration */
2691 struct peercnt *peercnt;
2692 struct peercnt tmp;
2693
2694 ast_sockaddr_copy(&tmp.addr, sockaddr);
2695
2696 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2697 peercnt->reg = reg;
2698 if (limit) {
2699 peercnt->limit = limit;
2700 } else {
2702 }
2703 ast_debug(1, "peercnt entry %s modified limit:%d registered:%d", ast_sockaddr_stringify_addr(sockaddr), peercnt->limit, peercnt->reg);
2704 ao2_ref(peercnt, -1); /* decrement ref from find */
2705 }
2706}
2707
2708/*!
2709 * \internal
2710 * \brief adds an ip to the peercnts table, increments connection count if it already exists
2711 *
2712 * \details First searches for the address in the peercnts table. If found
2713 * the current count is incremented. If not found a new peercnt is allocated
2714 * and linked into the peercnts table with a call number count of 1.
2715 */
2716static int peercnt_add(struct ast_sockaddr *addr)
2717{
2718 struct peercnt *peercnt;
2719 int res = 0;
2720 struct peercnt tmp;
2721
2723
2724 /* Reasoning for peercnts container lock: Two identical ip addresses
2725 * could be added by different threads at the "same time". Without the container
2726 * lock, both threads could alloc space for the same object and attempt
2727 * to link to table. With the lock, one would create the object and link
2728 * to table while the other would find the already created peercnt object
2729 * rather than creating a new one. */
2731 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2733 } else if ((peercnt = ao2_alloc(sizeof(*peercnt), NULL))) {
2735 /* create and set defaults */
2738 /* guarantees it does not go away after unlocking table
2739 * ao2_find automatically adds this */
2741 } else {
2743 return -1;
2744 }
2745
2746 /* check to see if the address has hit its callno limit. If not increment cur. */
2747 if (peercnt->limit > peercnt->cur) {
2748 peercnt->cur++;
2749 ast_debug(1, "ip callno count incremented to %d for %s\n", peercnt->cur, ast_sockaddr_stringify_addr(addr));
2750 } else { /* max num call numbers for this peer has been reached! */
2751 ast_log(LOG_ERROR, "maxcallnumber limit of %d for %s has been reached!\n", peercnt->limit, ast_sockaddr_stringify_addr(addr));
2752 res = -1;
2753 }
2754
2755 /* clean up locks and ref count */
2758 ao2_ref(peercnt, -1); /* decrement ref from find/alloc, only the container ref remains. */
2759
2760 return res;
2761}
2762
2763/*!
2764 * \internal
2765 * \brief decrements a peercnts table entry
2766 */
2767static void peercnt_remove(struct peercnt *peercnt)
2768{
2769 struct ast_sockaddr addr;
2770
2771 ast_sockaddr_copy(&addr, &peercnt->addr);
2772
2773 /*
2774 * Container locked here since peercnt may be unlinked from
2775 * list. If left unlocked, peercnt_add could try and grab this
2776 * entry from the table and modify it at the "same time" this
2777 * thread attempts to unlink it.
2778 */
2780 peercnt->cur--;
2781 ast_debug(1, "ip callno count decremented to %d for %s\n", peercnt->cur, ast_sockaddr_stringify_addr(&addr));
2782 /* if this was the last connection from the peer remove it from table */
2783 if (peercnt->cur == 0) {
2784 ao2_unlink(peercnts, peercnt);/* decrements ref from table, last ref is left to scheduler */
2785 }
2787}
2788
2789/*!
2790 * \internal
2791 * \brief called by scheduler to decrement object
2792 */
2793static int peercnt_remove_cb(const void *obj)
2794{
2795 struct peercnt *peercnt = (struct peercnt *) obj;
2796
2798 ao2_ref(peercnt, -1); /* decrement ref from scheduler */
2799
2800 return 0;
2801}
2802
2803/*!
2804 * \internal
2805 * \brief decrements peercnts connection count, finds by addr
2806 */
2807static int peercnt_remove_by_addr(struct ast_sockaddr *addr)
2808{
2809 struct peercnt *peercnt;
2810 struct peercnt tmp;
2811
2813
2814 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2816 ao2_ref(peercnt, -1); /* decrement ref from find */
2817 }
2818 return 0;
2819}
2820
2821/*!
2822 * \internal
2823 * \brief Create callno_limit entry based on configuration
2824 */
2825static void build_callno_limits(struct ast_variable *v)
2826{
2827 struct addr_range *addr_range = NULL;
2828 struct addr_range tmp;
2829 struct ast_ha *ha;
2830 int limit;
2831 int error;
2832 int found;
2833
2834 for (; v; v = v->next) {
2835 limit = -1;
2836 error = 0;
2837 found = 0;
2838 ha = ast_append_ha("permit", v->name, NULL, &error);
2839
2840 /* check for valid config information */
2841 if (error) {
2842 ast_log(LOG_ERROR, "Call number limit for %s could not be added, Invalid address range\n.", v->name);
2843 continue;
2844 } else if ((sscanf(v->value, "%d", &limit) != 1) || (limit < 0)) {
2845 ast_log(LOG_ERROR, "Call number limit for %s could not be added. Invalid limit %s\n.", v->name, v->value);
2846 ast_free_ha(ha);
2847 continue;
2848 }
2849
2850 ast_copy_ha(ha, &tmp.ha);
2851 /* find or create the addr_range */
2852 if ((addr_range = ao2_find(callno_limits, &tmp, OBJ_POINTER))) {
2854 found = 1;
2855 } else if (!(addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
2856 ast_free_ha(ha);
2857 return; /* out of memory */
2858 }
2859
2860 /* copy over config data into addr_range object */
2861 ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible for each limit */
2862 ast_free_ha(ha); /* cleanup the tmp ha */
2863 addr_range->limit = limit;
2864 addr_range->delme = 0;
2865
2866 /* cleanup */
2867 if (found) {
2869 } else {
2871 }
2872 ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
2873 }
2874}
2875
2876/*!
2877 * \internal
2878 * \brief Create calltoken_ignores entry based on configuration
2879 */
2880static int add_calltoken_ignore(const char *addr)
2881{
2882 struct addr_range tmp;
2883 struct addr_range *addr_range = NULL;
2884 struct ast_ha *ha = NULL;
2885 int error = 0;
2886
2887 if (ast_strlen_zero(addr)) {
2888 ast_log(LOG_WARNING, "invalid calltokenoptional (null)\n");
2889 return -1;
2890 }
2891
2892 ha = ast_append_ha("permit", addr, NULL, &error);
2893
2894 /* check for valid config information */
2895 if (error) {
2896 ast_log(LOG_WARNING, "Error %d creating calltokenoptional entry %s\n", error, addr);
2897 return -1;
2898 }
2899
2900 ast_copy_ha(ha, &tmp.ha);
2901 /* find or create the addr_range */
2904 addr_range->delme = 0;
2906 } else if ((addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
2907 /* copy over config data into addr_range object */
2908 ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible */
2910 } else {
2911 ast_free_ha(ha);
2912 return -1;
2913 }
2914
2915 ast_free_ha(ha);
2916 ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
2917
2918 return 0;
2919}
2920
2921static char *handle_cli_iax2_show_callno_limits(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2922{
2923 struct ao2_iterator i;
2924 struct peercnt *peercnt;
2925 struct ast_sockaddr addr;
2926 int found = 0;
2927
2928 switch (cmd) {
2929 case CLI_INIT:
2930 e->command = "iax2 show callnumber usage";
2931 e->usage =
2932 "Usage: iax2 show callnumber usage [IP address]\n"
2933 " Shows current IP addresses which are consuming iax2 call numbers\n";
2934 return NULL;
2935 case CLI_GENERATE:
2936 return NULL;
2937 case CLI_HANDLER:
2938 if (a->argc < 4 || a->argc > 5)
2939 return CLI_SHOWUSAGE;
2940
2941 if (a->argc == 4) {
2942 ast_cli(a->fd, "%-45s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
2943 }
2944
2946 while ((peercnt = ao2_iterator_next(&i))) {
2947 ast_sockaddr_copy(&addr, &peercnt->addr);
2948
2949 if (a->argc == 5) {
2950 if (!strcasecmp(a->argv[4], ast_sockaddr_stringify(&addr))) {
2951 ast_cli(a->fd, "%-45s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
2952 ast_cli(a->fd, "%-45s %-12d %-12d\n", ast_sockaddr_stringify(&addr), peercnt->cur, peercnt->limit);
2953 ao2_ref(peercnt, -1);
2954 found = 1;
2955 break;
2956 }
2957 } else {
2958 ast_cli(a->fd, "%-45s %-12d %-12d\n", ast_sockaddr_stringify(&addr), peercnt->cur, peercnt->limit);
2959 }
2960 ao2_ref(peercnt, -1);
2961 }
2963
2964 if (a->argc == 4) {
2965 size_t pool_avail = callno_pool.available;
2966 size_t trunk_pool_avail = callno_pool_trunk.available;
2967
2968 ast_cli(a->fd, "\nNon-CallToken Validation Callno Limit: %d\n"
2969 "Non-CallToken Validated Callno Used: %d\n",
2972
2973 ast_cli(a->fd, "Total Available Callno: %zu\n"
2974 "Regular Callno Available: %zu\n"
2975 "Trunk Callno Available: %zu\n",
2976 pool_avail + trunk_pool_avail,
2977 pool_avail,
2978 trunk_pool_avail);
2979 } else if (a->argc == 5 && !found) {
2980 ast_cli(a->fd, "No call number table entries for %s found\n", a->argv[4] );
2981 }
2982
2983
2984 return CLI_SUCCESS;
2985 default:
2986 return NULL;
2987 }
2988}
2989
2990static int get_unused_callno(enum callno_type type, int validated, callno_entry *entry)
2991{
2992 struct call_number_pool *pool = NULL;
2993 callno_entry swap;
2994 size_t choice;
2995
2996 switch (type) {
2997 case CALLNO_TYPE_NORMAL:
2998 pool = &callno_pool;
2999 break;
3000 case CALLNO_TYPE_TRUNK:
3001 pool = &callno_pool_trunk;
3002 break;
3003 default:
3004 ast_assert(0);
3005 break;
3006 }
3007
3008 /* If we fail, make sure this has a defined value */
3009 *entry = 0;
3010
3011 /* We lock here primarily to ensure thread safety of the
3012 * total_nonval_callno_used check and increment */
3014
3015 /* Bail out if we don't have any available call numbers */
3016 if (!pool->available) {
3017 ast_log(LOG_WARNING, "Out of call numbers\n");
3019 return 1;
3020 }
3021
3022 /* Only a certain number of non-validated call numbers should be allocated.
3023 * If there ever is an attack, this separates the calltoken validating users
3024 * from the non-calltoken validating users. */
3027 "NON-CallToken callnumber limit is reached. Current: %d Max: %d\n",
3031 return 1;
3032 }
3033
3034 /* We use a modified Fisher-Yates-Durstenfeld Shuffle to maintain a list of
3035 * available call numbers. The array of call numbers begins as an ordered
3036 * list from 1 -> n, and we keep a running tally of how many remain unclaimed
3037 * - let's call that x. When a call number is needed we pick a random index
3038 * into the array between 0 and x and use that as our call number. In a
3039 * typical FYD shuffle, we would swap the value that we are extracting with
3040 * the number at x, but in our case we swap and don't touch the value at x
3041 * because it is effectively invisible. We rely on the rest of the IAX2 core
3042 * to return the number to us at some point. Finally, we decrement x by 1
3043 * which establishes our new unused range.
3044 *
3045 * When numbers are returned to the pool, we put them just past x and bump x
3046 * by 1 so that this number is now available for re-use. */
3047
3048 choice = ast_random() % pool->available;
3049
3050 *entry = pool->numbers[choice];
3051 swap = pool->numbers[pool->available - 1];
3052
3053 pool->numbers[choice] = swap;
3054 pool->available--;
3055
3056 if (validated) {
3058 } else {
3060 }
3061
3063
3064 return 0;
3065}
3066
3067static int replace_callno(const void *obj)
3068{
3069 callno_entry entry = PTR_TO_CALLNO_ENTRY(obj);
3070 struct call_number_pool *pool;
3071
3072 /* We lock here primarily to ensure thread safety of the
3073 * total_nonval_callno_used check and decrement */
3075
3076 if (!CALLNO_ENTRY_IS_VALIDATED(entry)) {
3079 } else {
3081 "Attempted to decrement total non calltoken validated "
3082 "callnumbers below zero. Callno is: %d\n",
3084 }
3085 }
3086
3088 pool = &callno_pool;
3089 } else {
3090 pool = &callno_pool_trunk;
3091 }
3092
3093 ast_assert(pool->capacity > pool->available);
3094
3095 /* This clears the validated flag */
3096 entry = CALLNO_ENTRY_GET_CALLNO(entry);
3097
3098 pool->numbers[pool->available] = entry;
3099 pool->available++;
3100
3102
3103 return 0;
3104}
3105
3106static int create_callno_pools(void)
3107{
3108 uint16_t i;
3109
3111
3112 /* We start at 2. 0 and 1 are reserved. */
3113 for (i = 2; i < TRUNK_CALL_START; i++) {
3116 }
3117
3118 for (i = TRUNK_CALL_START; i < IAX_MAX_CALLS; i++) {
3121 }
3122
3125
3127
3128 return 0;
3129}
3130
3131/*!
3132 * \internal
3133 * \brief Schedules delayed removal of iax2_pvt call number data
3134 *
3135 * \note After MIN_REUSE_TIME has passed for a destroyed iax2_pvt, the callno is
3136 * available again, and the address from the previous connection must be decremented
3137 * from the peercnts table. This function schedules these operations to take place.
3138 */
3139static void sched_delay_remove(struct ast_sockaddr *addr, callno_entry entry)
3140{
3141 int i;
3142 struct peercnt *peercnt;
3143 struct peercnt tmp;
3144
3146
3147 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
3148 /* refcount is incremented with ao2_find. keep that ref for the scheduler */
3149 ast_debug(1, "schedule decrement of callno used for %s in %d seconds\n", ast_sockaddr_stringify_addr(addr), MIN_REUSE_TIME);
3151 if (i == -1) {
3152 ao2_ref(peercnt, -1);
3153 }
3154 }
3155
3157 sched,
3158 MIN_REUSE_TIME * 1000,
3160 CALLNO_ENTRY_TO_PTR(entry));
3161}
3162
3163/*!
3164 * \internal
3165 * \brief returns whether or not a frame is capable of starting a new IAX2 dialog.
3166 *
3167 * \note For this implementation, inbound pokes should _NOT_ be capable of allocating
3168 * a new callno.
3169 */
3170static inline int attribute_pure iax2_allow_new(int frametype, int subclass, int inbound)
3171{
3172 if (frametype != AST_FRAME_IAX) {
3173 return 0;
3174 }
3175 switch (subclass) {
3176 case IAX_COMMAND_NEW:
3177 case IAX_COMMAND_REGREQ:
3179 case IAX_COMMAND_REGREL:
3180 return 1;
3181 case IAX_COMMAND_POKE:
3182 if (!inbound) {
3183 return 1;
3184 }
3185 break;
3186 }
3187 return 0;
3188}
3189
3190/*!
3191 * \note Calling this function while holding another pvt lock can cause a deadlock.
3192 */
3193static int __find_callno(unsigned short callno, unsigned short dcallno, struct ast_sockaddr *addr, int new, int sockfd, int return_locked, int check_dcallno)
3194{
3195 int res = 0;
3196 int x;
3197 /* this call is calltoken validated as long as it is either NEW_FORCE
3198 * or NEW_ALLOW_CALLTOKEN_VALIDATED */
3199 int validated = (new > NEW_ALLOW) ? 1 : 0;
3200 char host[80];
3201
3202 if (new <= NEW_ALLOW) {
3203 if (callno) {
3204 struct chan_iax2_pvt *pvt;
3205 struct chan_iax2_pvt tmp_pvt = {
3206 .callno = dcallno,
3207 .peercallno = callno,
3208 .transfercallno = callno,
3209 /* hack!! */
3210 .frames_received = check_dcallno,
3211 };
3212
3213 ast_sockaddr_copy(&tmp_pvt.addr, addr);
3214 /* this works for finding normal call numbers not involving transferring */
3215 if ((pvt = ao2_find(iax_peercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
3216 if (return_locked) {
3217 ast_mutex_lock(&iaxsl[pvt->callno]);
3218 }
3219 res = pvt->callno;
3220 ao2_ref(pvt, -1);
3221 pvt = NULL;
3222 return res;
3223 }
3224 /* this searches for transfer call numbers that might not get caught otherwise */
3225 memset(&tmp_pvt.addr, 0, sizeof(tmp_pvt.addr));
3226 ast_sockaddr_copy(&tmp_pvt.transfer, addr);
3227 if ((pvt = ao2_find(iax_transfercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
3228 if (return_locked) {
3229 ast_mutex_lock(&iaxsl[pvt->callno]);
3230 }
3231 res = pvt->callno;
3232 ao2_ref(pvt, -1);
3233 pvt = NULL;
3234 return res;
3235 }
3236 }
3237 /* This will occur on the first response to a message that we initiated,
3238 * such as a PING. */
3239 if (dcallno) {
3240 ast_mutex_lock(&iaxsl[dcallno]);
3241 }
3242 if (callno && dcallno && iaxs[dcallno] && !iaxs[dcallno]->peercallno && match(addr, callno, dcallno, iaxs[dcallno], check_dcallno)) {
3243 iaxs[dcallno]->peercallno = callno;
3244 res = dcallno;
3245 store_by_peercallno(iaxs[dcallno]);
3246 if (!res || !return_locked) {
3247 ast_mutex_unlock(&iaxsl[dcallno]);
3248 }
3249 return res;
3250 }
3251 if (dcallno) {
3252 ast_mutex_unlock(&iaxsl[dcallno]);
3253 }
3254 }
3255 if (!res && (new >= NEW_ALLOW)) {
3256 callno_entry entry;
3257
3258 /* It may seem odd that we look through the peer list for a name for
3259 * this *incoming* call. Well, it is weird. However, users don't
3260 * have an IP address/port number that we can match against. So,
3261 * this is just checking for a peer that has that IP/port and
3262 * assuming that we have a user of the same name. This isn't always
3263 * correct, but it will be changed if needed after authentication. */
3264 if (!iax2_getpeername(*addr, host, sizeof(host)))
3265 snprintf(host, sizeof(host), "%s", ast_sockaddr_stringify(addr));
3266
3267 if (peercnt_add(addr)) {
3268 /* This address has hit its callnumber limit. When the limit
3269 * is reached, the connection is not added to the peercnts table.*/
3270 return 0;
3271 }
3272
3273 if (get_unused_callno(CALLNO_TYPE_NORMAL, validated, &entry)) {
3274 /* since we ran out of space, remove the peercnt
3275 * entry we added earlier */
3277 ast_log(LOG_WARNING, "No more space\n");
3278 return 0;
3279 }
3280 x = CALLNO_ENTRY_GET_CALLNO(entry);
3281 ast_mutex_lock(&iaxsl[x]);
3282
3283 iaxs[x] = new_iax(addr, host);
3284 if (iaxs[x]) {
3285 if (iaxdebug)
3286 ast_debug(1, "Creating new call structure %d\n", x);
3287 iaxs[x]->callno_entry = entry;
3288 iaxs[x]->sockfd = sockfd;
3290 iaxs[x]->peercallno = callno;
3291 iaxs[x]->callno = x;
3294 iaxs[x]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
3295 iaxs[x]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
3296 iaxs[x]->amaflags = amaflags;
3302
3303 if (iaxs[x]->peercallno) {
3305 }
3306 } else {
3307 ast_log(LOG_WARNING, "Out of resources\n");
3310 return 0;
3311 }
3312 if (!return_locked)
3314 res = x;
3315 }
3316 return res;
3317}
3318
3319static int find_callno(unsigned short callno, unsigned short dcallno, struct ast_sockaddr *addr, int new, int sockfd, int full_frame) {
3320 return __find_callno(callno, dcallno, addr, new, sockfd, 0, full_frame);
3321}
3322
3323static int find_callno_locked(unsigned short callno, unsigned short dcallno, struct ast_sockaddr *addr, int new, int sockfd, int full_frame) {
3324
3325 return __find_callno(callno, dcallno, addr, new, sockfd, 1, full_frame);
3326}
3327
3328/*!
3329 * \brief Queue a frame to a call's owning asterisk channel
3330 *
3331 * \pre This function assumes that iaxsl[callno] is locked when called.
3332 *
3333 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3334 * was valid before calling it, it may no longer be valid after calling it.
3335 * This function may unlock and lock the mutex associated with this callno,
3336 * meaning that another thread may grab it and destroy the call.
3337 */
3338static int iax2_queue_frame(int callno, struct ast_frame *f)
3339{
3341 if (iaxs[callno] && iaxs[callno]->owner) {
3344 }
3345 return 0;
3346}
3347
3348/*!
3349 * \brief Queue a hold frame on the ast_channel owner
3350 *
3351 * This function queues a hold frame on the owner of the IAX2 pvt struct that
3352 * is active for the given call number.
3353 *
3354 * \pre Assumes lock for callno is already held.
3355 *
3356 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3357 * was valid before calling it, it may no longer be valid after calling it.
3358 * This function may unlock and lock the mutex associated with this callno,
3359 * meaning that another thread may grab it and destroy the call.
3360 */
3361static int iax2_queue_hold(int callno, const char *musicclass)
3362{
3364 if (iaxs[callno] && iaxs[callno]->owner) {
3365 ast_queue_hold(iaxs[callno]->owner, musicclass);
3367 }
3368 return 0;
3369}
3370
3371/*!
3372 * \brief Queue an unhold frame on the ast_channel owner
3373 *
3374 * This function queues an unhold frame on the owner of the IAX2 pvt struct that
3375 * is active for the given call number.
3376 *
3377 * \pre Assumes lock for callno is already held.
3378 *
3379 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3380 * was valid before calling it, it may no longer be valid after calling it.
3381 * This function may unlock and lock the mutex associated with this callno,
3382 * meaning that another thread may grab it and destroy the call.
3383 */
3384static int iax2_queue_unhold(int callno)
3385{
3387 if (iaxs[callno] && iaxs[callno]->owner) {
3390 }
3391 return 0;
3392}
3393
3394/*!
3395 * \brief Queue a hangup frame on the ast_channel owner
3396 *
3397 * This function queues a hangup frame on the owner of the IAX2 pvt struct that
3398 * is active for the given call number.
3399 *
3400 * \pre Assumes lock for callno is already held.
3401 *
3402 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3403 * was valid before calling it, it may no longer be valid after calling it.
3404 * This function may unlock and lock the mutex associated with this callno,
3405 * meaning that another thread may grab it and destroy the call.
3406 */
3407static int iax2_queue_hangup(int callno)
3408{
3410 if (iaxs[callno] && iaxs[callno]->owner) {
3413 }
3414 return 0;
3415}
3416
3417/*!
3418 * \note This function assumes that iaxsl[callno] is locked when called.
3419 *
3420 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3421 * was valid before calling it, it may no longer be valid after calling it.
3422 * This function calls iax2_queue_frame(), which may unlock and lock the mutex
3423 * associated with this callno, meaning that another thread may grab it and destroy the call.
3424 */
3425static int __do_deliver(void *data)
3426{
3427 /* Just deliver the packet by using queueing. This is called by
3428 the IAX thread with the iaxsl lock held. */
3429 struct iax_frame *fr = data;
3430 fr->retrans = -1;
3433 iax2_queue_frame(fr->callno, &fr->af);
3434 /* Free our iax frame */
3435 iax2_frame_free(fr);
3436 /* And don't run again */
3437 return 0;
3438}
3439
3440static int handle_error(void)
3441{
3442 /* XXX Ideally we should figure out why an error occurred and then abort those
3443 rather than continuing to try. Unfortunately, the published interface does
3444 not seem to work XXX */
3445#if 0
3446 struct sockaddr_in *sin;
3447 int res;
3448 struct msghdr m;
3449 struct sock_extended_err e;
3450 m.msg_name = NULL;
3451 m.msg_namelen = 0;
3452 m.msg_iov = NULL;
3453 m.msg_control = &e;
3454 m.msg_controllen = sizeof(e);
3455 m.msg_flags = 0;
3456 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
3457 if (res < 0)
3458 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
3459 else {
3460 if (m.msg_controllen) {
3461 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
3462 if (sin)
3463 ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(sin->sin_addr));
3464 else
3465 ast_log(LOG_WARNING, "No address detected??\n");
3466 } else {
3467 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
3468 }
3469 }
3470#endif
3471 return 0;
3472}
3473
3474static int transmit_trunk(struct iax_frame *f, struct ast_sockaddr *addr, int sockfd)
3475{
3476 int res;
3477 res = ast_sendto(sockfd, f->data, f->datalen, 0, addr);
3478
3479 if (res < 0) {
3480 ast_debug(1, "Received error: %s\n", strerror(errno));
3481 handle_error();
3482 } else
3483 res = 0;
3484 return res;
3485}
3486
3487static int send_packet(struct iax_frame *f)
3488{
3489 int res;
3490 int callno = f->callno;
3491
3492 /* Don't send if there was an error, but return error instead */
3493 if (!callno || !iaxs[callno] || iaxs[callno]->error)
3494 return -1;
3495
3496 /* Called with iaxsl held */
3497 if (iaxdebug) {
3498 ast_debug(8, "Sending %u on %d/%d to %s\n", f->ts, callno, iaxs[callno]->peercallno, ast_sockaddr_stringify(&iaxs[callno]->addr));
3499 }
3500 if (f->transfer) {
3501 iax_outputframe(f, NULL, 0, &iaxs[callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
3502 res = ast_sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0, &iaxs[callno]->transfer);
3503 } else {
3504 iax_outputframe(f, NULL, 0, &iaxs[callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
3505 res = ast_sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0, &iaxs[callno]->addr);
3506 }
3507 if (res < 0) {
3508 if (iaxdebug)
3509 ast_debug(1, "Received error: %s\n", strerror(errno));
3510 handle_error();
3511 } else
3512 res = 0;
3513
3514 return res;
3515}
3516
3517/*!
3518 * \note Since this function calls iax2_queue_hangup(), the pvt struct
3519 * for the given call number may disappear during its execution.
3520 */
3521static int iax2_predestroy(int callno)
3522{
3523 struct ast_channel *c = NULL;
3524 struct chan_iax2_pvt *pvt = iaxs[callno];
3525
3526 if (!pvt)
3527 return -1;
3528
3529 if (!ast_test_flag64(pvt, IAX_ALREADYGONE)) {
3532 }
3533
3534 if ((c = pvt->owner)) {
3537 pvt->owner = NULL;
3539 }
3540
3541 return 0;
3542}
3543
3544static void iax2_destroy(int callno)
3545{
3546 struct chan_iax2_pvt *pvt = NULL;
3547 struct ast_channel *owner = NULL;
3548
3549retry:
3550 if ((pvt = iaxs[callno])) {
3551#if 0
3552 /* iax2_destroy_helper gets called from this function later on. When
3553 * called twice, we get the (previously) familiar FRACK! errors in
3554 * devmode, from the scheduler. An alternative to this approach is to
3555 * reset the scheduler entries to -1 when they're deleted in
3556 * iax2_destroy_helper(). That approach was previously decided to be
3557 * "wrong" because "the memory is going to be deallocated anyway. Why
3558 * should we be resetting those values?" */
3560#endif
3561 }
3562
3563 owner = pvt ? pvt->owner : NULL;
3564
3565 if (owner) {
3566 if (ast_channel_trylock(owner)) {
3567 ast_debug(3, "Avoiding IAX destroy deadlock\n");
3568 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
3569 goto retry;
3570 }
3571 }
3572
3573 if (!owner) {
3574 iaxs[callno] = NULL;
3575 }
3576
3577 if (pvt) {
3578 if (!owner) {
3579 pvt->owner = NULL;
3580 } else {
3581 /* If there's an owner, prod it to give up */
3582 /* It is ok to use ast_queue_hangup() here instead of iax2_queue_hangup()
3583 * because we already hold the owner channel lock. */
3584 ast_queue_hangup(owner);
3585 }
3586
3587 if (pvt->peercallno) {
3589 }
3590
3591 if (pvt->transfercallno) {
3593 }
3594
3595 if (!owner) {
3596 ao2_ref(pvt, -1);
3597 pvt = NULL;
3598 }
3599 }
3600
3601 if (owner) {
3602 ast_channel_unlock(owner);
3603 }
3604}
3605
3606static int update_packet(struct iax_frame *f)
3607{
3608 /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
3609 struct ast_iax2_full_hdr *fh = f->data;
3610 struct ast_frame af;
3611
3612 /* if frame is encrypted. decrypt before updating it. */
3613 if (f->encmethods) {
3614 decode_frame(&f->mydcx, fh, &af, &f->datalen);
3615 }
3616 /* Mark this as a retransmission */
3617 fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
3618 /* Update iseqno */
3619 f->iseqno = iaxs[f->callno]->iseqno;
3620 fh->iseqno = f->iseqno;
3621
3622 /* Now re-encrypt the frame */
3623 if (f->encmethods) {
3624 /* since this is a retransmit frame, create a new random padding
3625 * before re-encrypting. */
3626 build_rand_pad(f->semirand, sizeof(f->semirand));
3627 encrypt_frame(&f->ecx, fh, f->semirand, &f->datalen);
3628 }
3629 return 0;
3630}
3631
3632static int attempt_transmit(const void *data);
3633static void __attempt_transmit(const void *data)
3634{
3635 /* Attempt to transmit the frame to the remote peer...
3636 Called without iaxsl held. */
3637 struct iax_frame *f = (struct iax_frame *)data;
3638 int freeme = 0;
3639 int callno = f->callno;
3640
3641 /* Make sure this call is still active */
3642 if (callno)
3644 if (callno && iaxs[callno]) {
3645 if (f->retries < 0) {
3646 /* Already ACK'd */
3647 freeme = 1;
3648 } else if (f->retries >= max_retries) {
3649 /* Too many attempts. Record an error. */
3650 if (f->transfer) {
3651 /* Transfer timeout */
3653 } else if (f->final) {
3655 } else {
3656 if (iaxs[callno]->owner) {
3657 ast_log(LOG_WARNING, "Max retries exceeded to host %s on %s (type = %u, subclass = %d, ts=%u, seqno=%d)\n",
3660 f->af.frametype,
3661 f->af.subclass.integer,
3662 f->ts,
3663 f->oseqno);
3664 }
3665 iaxs[callno]->error = ETIMEDOUT;
3666 if (iaxs[callno]->owner) {
3668 /* Hangup the fd */
3669 iax2_queue_frame(callno, &fr); /* XXX */
3670 /* Remember, owner could disappear */
3671 if (iaxs[callno] && iaxs[callno]->owner)
3673 } else {
3674 if (iaxs[callno]->reg) {
3675 memset(&iaxs[callno]->reg->us, 0, sizeof(iaxs[callno]->reg->us));
3676 iaxs[callno]->reg->regstate = REG_STATE_TIMEOUT;
3678 }
3679 iax2_destroy(callno);
3680 }
3681 }
3682 freeme = 1;
3683 } else {
3684 /* Update it if it needs it */
3685 update_packet(f);
3686 /* Attempt transmission */
3687 send_packet(f);
3688 f->retries++;
3689 /* Try again later after 10 times as long */
3690 f->retrytime *= 10;
3691 if (f->retrytime > MAX_RETRY_TIME)
3693 /* Transfer messages max out at one second */
3694 if (f->transfer && (f->retrytime > 1000))
3695 f->retrytime = 1000;
3697 }
3698 } else {
3699 /* Make sure it gets freed */
3700 f->retries = -1;
3701 freeme = 1;
3702 }
3703
3704 if (freeme) {
3705 /* Don't attempt delivery, just remove it from the queue */
3706 AST_LIST_REMOVE(&frame_queue[callno], f, list);
3707 ast_mutex_unlock(&iaxsl[callno]);
3708 f->retrans = -1; /* this is safe because this is the scheduled function */
3709 /* Free the IAX frame */
3710 iax2_frame_free(f);
3711 } else if (callno) {
3712 ast_mutex_unlock(&iaxsl[callno]);
3713 }
3714}
3715
3716static int attempt_transmit(const void *data)
3717{
3718#ifdef SCHED_MULTITHREADED
3720#endif
3722 return 0;
3723}
3724
3725static char *handle_cli_iax2_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3726{
3727 struct iax2_peer *peer = NULL;
3728 struct iax2_user *user = NULL;
3729 static const char * const choices[] = { "all", NULL };
3730 char *cmplt;
3731
3732 switch (cmd) {
3733 case CLI_INIT:
3734 e->command = "iax2 prune realtime";
3735 e->usage =
3736 "Usage: iax2 prune realtime [<peername>|all]\n"
3737 " Prunes object(s) from the cache\n";
3738 return NULL;
3739 case CLI_GENERATE:
3740 if (a->pos == 3) {
3741 cmplt = ast_cli_complete(a->word, choices, a->n);
3742 if (!cmplt)
3743 cmplt = complete_iax2_peers(a->line, a->word, a->pos, a->n - sizeof(choices), IAX_RTCACHEFRIENDS);
3744 return cmplt;
3745 }
3746 return NULL;
3747 }
3748 if (a->argc != 4)
3749 return CLI_SHOWUSAGE;
3750 if (!strcmp(a->argv[3], "all")) {
3751 prune_users();
3752 prune_peers();
3753 ast_cli(a->fd, "Cache flushed successfully.\n");
3754 return CLI_SUCCESS;
3755 }
3756 peer = find_peer(a->argv[3], 0);
3757 user = find_user(a->argv[3]);
3758 if (peer || user) {
3759 if (peer) {
3763 ast_cli(a->fd, "Peer %s was removed from the cache.\n", a->argv[3]);
3764 } else {
3765 ast_cli(a->fd, "Peer %s is not eligible for this operation.\n", a->argv[3]);
3766 }
3767 peer_unref(peer);
3768 }
3769 if (user) {
3772 ast_cli(a->fd, "User %s was removed from the cache.\n", a->argv[3]);
3773 } else {
3774 ast_cli(a->fd, "User %s is not eligible for this operation.\n", a->argv[3]);
3775 }
3778 }
3779 } else {
3780 ast_cli(a->fd, "%s was not found in the cache.\n", a->argv[3]);
3781 }
3782
3783 return CLI_SUCCESS;
3784}
3785
3786static char *handle_cli_iax2_test_losspct(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3787{
3788 switch (cmd) {
3789 case CLI_INIT:
3790 e->command = "iax2 test losspct";
3791 e->usage =
3792 "Usage: iax2 test losspct <percentage>\n"
3793 " For testing, throws away <percentage> percent of incoming packets\n";
3794 return NULL;
3795 case CLI_GENERATE:
3796 return NULL;
3797 }
3798 if (a->argc != 4)
3799 return CLI_SHOWUSAGE;
3800
3801 test_losspct = atoi(a->argv[3]);
3802
3803 return CLI_SUCCESS;
3804}
3805
3806#ifdef IAXTESTS
3807static char *handle_cli_iax2_test_late(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3808{
3809 switch (cmd) {
3810 case CLI_INIT:
3811 e->command = "iax2 test late";
3812 e->usage =
3813 "Usage: iax2 test late <ms>\n"
3814 " For testing, count the next frame as <ms> ms late\n";
3815 return NULL;
3816 case CLI_GENERATE:
3817 return NULL;
3818 }
3819
3820 if (a->argc != 4)
3821 return CLI_SHOWUSAGE;
3822
3823 test_late = atoi(a->argv[3]);
3824
3825 return CLI_SUCCESS;
3826}
3827
3828static char *handle_cli_iax2_test_resync(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3829{
3830 switch (cmd) {
3831 case CLI_INIT:
3832 e->command = "iax2 test resync";
3833 e->usage =
3834 "Usage: iax2 test resync <ms>\n"
3835 " For testing, adjust all future frames by <ms> ms\n";
3836 return NULL;
3837 case CLI_GENERATE:
3838 return NULL;
3839 }
3840
3841 if (a->argc != 4)
3842 return CLI_SHOWUSAGE;
3843
3844 test_resync = atoi(a->argv[3]);
3845
3846 return CLI_SUCCESS;
3847}
3848
3849static char *handle_cli_iax2_test_jitter(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3850{
3851 switch (cmd) {
3852 case CLI_INIT:
3853 e->command = "iax2 test jitter";
3854 e->usage =
3855 "Usage: iax2 test jitter <ms> <pct>\n"
3856 " For testing, simulate maximum jitter of +/- <ms> on <pct>\n"
3857 " percentage of packets. If <pct> is not specified, adds\n"
3858 " jitter to all packets.\n";
3859 return NULL;
3860 case CLI_GENERATE:
3861 return NULL;
3862 }
3863
3864 if (a->argc < 4 || a->argc > 5)
3865 return CLI_SHOWUSAGE;
3866
3867 test_jit = atoi(a->argv[3]);
3868 if (a->argc == 5)
3869 test_jitpct = atoi(a->argv[4]);
3870
3871 return CLI_SUCCESS;
3872}
3873#endif /* IAXTESTS */
3874
3875/*! \brief peer_status: Report Peer status in character string */
3876/* returns 1 if peer is online, -1 if unmonitored */
3877static int peer_status(struct iax2_peer *peer, char *status, int statuslen)
3878{
3879 int res = 0;
3880 if (peer->maxms) {
3881 if (peer->lastms < 0) {
3882 ast_copy_string(status, "UNREACHABLE", statuslen);
3883 } else if (peer->lastms > peer->maxms) {
3884 snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
3885 res = 1;
3886 } else if (peer->lastms) {
3887 snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
3888 res = 1;
3889 } else {
3890 ast_copy_string(status, "UNKNOWN", statuslen);
3891 }
3892 } else {
3893 ast_copy_string(status, "Unmonitored", statuslen);
3894 res = -1;
3895 }
3896 return res;
3897}
3898
3899/*! \brief Show one peer in detail */
3900static char *handle_cli_iax2_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3901{
3902 char status[64];
3903 char cbuf[256];
3904 struct iax2_peer *peer;
3905 struct ast_str *codec_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
3906 struct ast_str *encmethods = ast_str_alloca(256);
3907 int load_realtime = 0;
3908
3909 switch (cmd) {
3910 case CLI_INIT:
3911 e->command = "iax2 show peer";
3912 e->usage =
3913 "Usage: iax2 show peer <name>\n"
3914 " Display details on specific IAX peer\n";
3915 return NULL;
3916 case CLI_GENERATE:
3917 if (a->pos == 3)
3918 return complete_iax2_peers(a->line, a->word, a->pos, a->n, 0);
3919 return NULL;
3920 }
3921
3922 if (a->argc < 4)
3923 return CLI_SHOWUSAGE;
3924
3925 load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? 1 : 0;
3926
3927 peer = find_peer(a->argv[3], load_realtime);
3928 if (peer) {
3929 char *str_addr, *str_defaddr;
3930 char *str_port, *str_defport;
3931
3932 str_addr = ast_strdupa(ast_sockaddr_stringify_addr(&peer->addr));
3933 str_port = ast_strdupa(ast_sockaddr_stringify_port(&peer->addr));
3934 str_defaddr = ast_strdupa(ast_sockaddr_stringify_addr(&peer->defaddr));
3935 str_defport = ast_strdupa(ast_sockaddr_stringify_port(&peer->defaddr));
3936
3937 encmethods_to_str(peer->encmethods, &encmethods);
3938 ast_cli(a->fd, "\n\n");
3939 ast_cli(a->fd, " * Name : %s\n", peer->name);
3940 ast_cli(a->fd, " Description : %s\n", peer->description);
3941 ast_cli(a->fd, " Secret : %s\n", ast_strlen_zero(peer->secret) ? "<Not set>" : "<Set>");
3942 ast_cli(a->fd, " Context : %s\n", peer->context);
3943 ast_cli(a->fd, " Parking lot : %s\n", peer->parkinglot);
3944 ast_cli(a->fd, " Mailbox : %s\n", peer->mailbox);
3945 ast_cli(a->fd, " Dynamic : %s\n", ast_test_flag64(peer, IAX_DYNAMIC) ? "Yes" : "No");
3946 ast_cli(a->fd, " Callnum limit: %d\n", peer->maxcallno);
3947 ast_cli(a->fd, " Calltoken req: %s\n", (peer->calltoken_required == CALLTOKEN_YES) ? "Yes" : ((peer->calltoken_required == CALLTOKEN_AUTO) ? "Auto" : "No"));
3948 ast_cli(a->fd, " Trunk : %s\n", ast_test_flag64(peer, IAX_TRUNK) ? "Yes" : "No");
3949 ast_cli(a->fd, " Encryption : %s\n", peer->encmethods ? ast_str_buffer(encmethods) : "No");
3950 ast_cli(a->fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
3951 ast_cli(a->fd, " Expire : %d\n", peer->expire);
3952 ast_cli(a->fd, " ACL : %s\n", (ast_acl_list_is_empty(peer->acl) ? "No" : "Yes"));
3953 ast_cli(a->fd, " Addr->IP : %s Port %s\n", str_addr ? str_addr : "(Unspecified)", str_port);
3954 ast_cli(a->fd, " Defaddr->IP : %s Port %s\n", str_defaddr, str_defport);
3955 ast_cli(a->fd, " Username : %s\n", peer->username);
3956 ast_cli(a->fd, " Codecs : %s\n", iax2_getformatname_multiple(peer->capability, &codec_buf));
3957
3958 if (iax2_codec_pref_string(&peer->prefs, cbuf, sizeof(cbuf)) < 0) {
3959 strcpy(cbuf, "Error"); /* Safe */
3960 }
3961 ast_cli(a->fd, " Codec Order : %s\n", cbuf);
3962
3963 peer_status(peer, status, sizeof(status));
3964 ast_cli(a->fd, " Status : %s\n", status);
3965 ast_cli(a->fd, " Qualify : every %dms when OK, every %dms when UNREACHABLE (sample smoothing %s)\n", peer->pokefreqok, peer->pokefreqnotok, peer->smoothing ? "On" : "Off");
3966 ast_cli(a->fd, "\n");
3967 peer_unref(peer);
3968 } else {
3969 ast_cli(a->fd, "Peer %s not found.\n", a->argv[3]);
3970 ast_cli(a->fd, "\n");
3971 }
3972
3973 return CLI_SUCCESS;
3974}
3975
3976static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags)
3977{
3978 int which = 0;
3979 struct iax2_peer *peer;
3980 char *res = NULL;
3981 int wordlen = strlen(word);
3982 struct ao2_iterator i;
3983
3984 i = ao2_iterator_init(peers, 0);
3985 while ((peer = ao2_iterator_next(&i))) {
3986 if (!strncasecmp(peer->name, word, wordlen) && ++which > state
3987 && (!flags || ast_test_flag64(peer, flags))) {
3988 res = ast_strdup(peer->name);
3989 peer_unref(peer);
3990 break;
3991 }
3992 peer_unref(peer);
3993 }
3995
3996 return res;
3997}
3998
3999static char *handle_cli_iax2_show_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
4000{
4001 struct iax_frame *cur;
4002 int cnt = 0, dead = 0, final = 0, i = 0;
4003
4004 switch (cmd) {
4005 case CLI_INIT:
4006 e->command = "iax2 show stats";
4007 e->usage =
4008 "Usage: iax2 show stats\n"
4009 " Display statistics on IAX channel driver.\n";
4010 return NULL;
4011 case CLI_GENERATE:
4012 return NULL;
4013 }
4014
4015 if (a->argc != 3)
4016 return CLI_SHOWUSAGE;
4017
4018 for (i = 0; i < ARRAY_LEN(frame_queue); i++) {
4019 ast_mutex_lock(&iaxsl[i]);
4021 if (cur->retries < 0)
4022 dead++;
4023 if (cur->final)
4024 final++;
4025 cnt++;
4026 }
4028 }
4029
4030 ast_cli(a->fd, " IAX Statistics\n");
4031 ast_cli(a->fd, "---------------------\n");
4032 ast_cli(a->fd, "Outstanding frames: %d (%d ingress, %d egress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
4033 ast_cli(a->fd, "%d timed and %d untimed transmits; MTU %d/%d/%d\n", trunk_timed, trunk_untimed,
4035 ast_cli(a->fd, "Packets in transmit queue: %d dead, %d final, %d total\n\n", dead, final, cnt);
4036
4040
4041 return CLI_SUCCESS;
4042}
4043
4044/*! \brief Set trunk MTU from CLI */
4045static char *handle_cli_iax2_set_mtu(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
4046{
4047 int mtuv;
4048
4049 switch (cmd) {
4050 case CLI_INIT:
4051 e->command = "iax2 set mtu";
4052 e->usage =
4053 "Usage: iax2 set mtu <value>\n"
4054 " Set the system-wide IAX IP mtu to <value> bytes net or\n"
4055 " zero to disable. Disabling means that the operating system\n"
4056 " must handle fragmentation of UDP packets when the IAX2 trunk\n"
4057 " packet exceeds the UDP payload size. This is substantially\n"
4058 " below the IP mtu. Try 1240 on ethernets. Must be 172 or\n"
4059 " greater for G.711 samples.\n";
4060 return NULL;
4061 case CLI_GENERATE:
4062 return NULL;
4063 }
4064
4065 if (a->argc != 4)
4066 return CLI_SHOWUSAGE;
4067 if (strncasecmp(a->argv[3], "default", strlen(a->argv[3])) == 0)
4068 mtuv = MAX_TRUNK_MTU;
4069 else
4070 mtuv = atoi(a->argv[3]);
4071
4072 if (mtuv == 0) {
4073 ast_cli(a->fd, "Trunk MTU control disabled (mtu was %d)\n", global_max_trunk_mtu);
4075 return CLI_SUCCESS;
4076 }
4077 if (mtuv < 172 || mtuv > 4000) {
4078 ast_cli(a->fd, "Trunk MTU must be between 172 and 4000\n");
4079 return CLI_SHOWUSAGE;
4080 }
4081 ast_cli(a->fd, "Trunk MTU changed from %d to %d\n", global_max_trunk_mtu, mtuv);
4082 global_max_trunk_mtu = mtuv;
4083 return CLI_SUCCESS;
4084}
4085
4086static char *handle_cli_iax2_show_cache(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
4087{
4088 struct iax2_dpcache *dp = NULL;
4089 char tmp[1024], *pc = NULL;
4090 int s, x, y;
4091 struct timeval now = ast_tvnow();
4092
4093 switch (cmd) {
4094 case CLI_INIT:
4095 e->command = "iax2 show cache";
4096 e->usage =
4097 "Usage: iax2 show cache\n"
4098 " Display currently cached IAX Dialplan results.\n";
4099 return NULL;
4100 case CLI_GENERATE:
4101 return NULL;
4102 }
4103
4105
4106 ast_cli(a->fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
4107
4108 AST_LIST_TRAVERSE(&dpcache, dp, cache_list) {
4109 s = dp->expiry.tv_sec - now.tv_sec;
4110 tmp[0] = '\0';
4111 if (dp->flags & CACHE_FLAG_EXISTS)
4112 strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
4113 if (dp->flags & CACHE_FLAG_NONEXISTENT)
4114 strncat(tmp, "NONEXISTENT|", sizeof(tmp) - strlen(tmp) - 1);
4115 if (dp->flags & CACHE_FLAG_CANEXIST)
4116 strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
4117 if (dp->flags & CACHE_FLAG_PENDING)
4118 strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
4119 if (dp->flags & CACHE_FLAG_TIMEOUT)
4120 strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
4121 if (dp->flags & CACHE_FLAG_TRANSMITTED)
4122 strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
4123 if (dp->flags & CACHE_FLAG_MATCHMORE)
4124 strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
4125 if (dp->flags & CACHE_FLAG_UNKNOWN)
4126 strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
4127 /* Trim trailing pipe */
4128 if (!ast_strlen_zero(tmp)) {
4129 tmp[strlen(tmp) - 1] = '\0';
4130 } else {
4131 ast_copy_string(tmp, "(none)", sizeof(tmp));
4132 }
4133 y = 0;
4134 pc = strchr(dp->peercontext, '@');
4135 if (!pc) {
4136 pc = dp->peercontext;
4137 } else {
4138 pc++;
4139 }
4140 for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
4141 if (dp->waiters[x] > -1)
4142 y++;
4143 }
4144 if (s > 0) {
4145 ast_cli(a->fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
4146 } else {
4147 ast_cli(a->fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
4148 }
4149 }
4150
4152
4153 return CLI_SUCCESS;
4154}
4155
4156static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
4157
4158static void unwrap_timestamp(struct iax_frame *fr)
4159{
4160 /* Video mini frames only encode the lower 15 bits of the session
4161 * timestamp, but other frame types (e.g. audio) encode 16 bits. */
4162 const int ts_shift = (fr->af.frametype == AST_FRAME_VIDEO) ? 15 : 16;
4163 const int lower_mask = (1 << ts_shift) - 1;
4164 const int upper_mask = ~lower_mask;
4165 const int last_upper = iaxs[fr->callno]->last & upper_mask;
4166
4167 if ( (fr->ts & upper_mask) == last_upper ) {
4168 const int x = fr->ts - iaxs[fr->callno]->last;
4169 const int threshold = (ts_shift == 15) ? 25000 : 50000;
4170
4171 if (x < -threshold) {
4172 /* Sudden big jump backwards in timestamp:
4173 What likely happened here is that miniframe timestamp has circled but we haven't
4174 gotten the update from the main packet. We'll just pretend that we did, and
4175 update the timestamp appropriately. */
4176 fr->ts = (last_upper + (1 << ts_shift)) | (fr->ts & lower_mask);
4177 if (iaxdebug)
4178 ast_debug(1, "schedule_delivery: pushed forward timestamp\n");
4179 } else if (x > threshold) {
4180 /* Sudden apparent big jump forwards in timestamp:
4181 What's likely happened is this is an old miniframe belonging to the previous
4182 top 15 or 16-bit timestamp that has turned up out of order.
4183 Adjust the timestamp appropriately. */
4184 fr->ts = (last_upper - (1 << ts_shift)) | (fr->ts & lower_mask);
4185 if (iaxdebug)
4186 ast_debug(1, "schedule_delivery: pushed back timestamp\n");
4187 }
4188 }
4189}
4190
4191static int get_from_jb(const void *p);
4192
4193static void update_jbsched(struct chan_iax2_pvt *pvt)
4194{
4195 int when;
4196
4197 when = ast_tvdiff_ms(ast_tvnow(), pvt->rxcore);
4198
4199 when = jb_next(pvt->jb) - when;
4200
4201 if (when <= 0) {
4202 /* XXX should really just empty until when > 0.. */
4203 when = 1;
4204 }
4205
4206 pvt->jbid = iax2_sched_replace(pvt->jbid, sched, when, get_from_jb,
4207 CALLNO_TO_PTR(pvt->callno));
4208}
4209
4210static void __get_from_jb(const void *p)
4211{
4212 int callno = PTR_TO_CALLNO(p);
4213 struct chan_iax2_pvt *pvt = NULL;
4214 struct iax_frame *fr;
4215 jb_frame frame;
4216 int ret;
4217 long ms;
4218 long next;
4219 struct timeval now = ast_tvnow();
4220 struct ast_format *voicefmt;
4221
4222 /* Make sure we have a valid private structure before going on */
4223 ast_mutex_lock(&iaxsl[callno]);
4224 pvt = iaxs[callno];
4225 if (!pvt) {
4226 /* No go! */
4227 ast_mutex_unlock(&iaxsl[callno]);
4228 return;
4229 }
4230
4231 pvt->jbid = -1;
4232
4233 /* round up a millisecond since ast_sched_runq does; */
4234 /* prevents us from spinning while waiting for our now */
4235 /* to catch up with runq's now */
4236 now.tv_usec += 1000;
4237
4238 ms = ast_tvdiff_ms(now, pvt->rxcore);
4239 if (ms >= (next = jb_next(pvt->jb))) {
4241 if (!voicefmt) {
4242 /* pvt->voiceformat won't be set if we haven't received any voice frames yet.
4243 * In this case, fall back to using the format negotiated during call setup,
4244 * so we don't stall the jitterbuffer completely. */
4246 if (!voicefmt) {
4247 /* As a last resort, we can use pvt->chosenformat.
4248 * This is set when we receive a call (either authenticated or unauthenticated),
4249 * so even if we haven't received any voice frames yet, we can still use the
4250 * right format.
4251 *
4252 * If we have to do this, in most cases, we aren't even processing voice frames
4253 * anyways, it's likely a non-voice frame. In that case, the format doesn't
4254 * really matter so much, because we could just pass 20 to jb_get instead
4255 * of calling ast_format_get_default_ms. However, until jb_get returns,
4256 * we don't actually know what kind of frame it is for sure, so use
4257 * the right format just to be safe. */
4259 }
4260 }
4261 if (!voicefmt) {
4262 /* This should never happen, since we should always be able to have an acceptable format to use. */
4263 ast_log(LOG_ERROR, "No voice, peer, or chosen format available on %s, backlogging frame\n", ast_channel_name(pvt->owner));
4264 goto cleanup; /* Don't crash if there's no voice format */
4265 }
4266 ret = jb_get(pvt->jb, &frame, ms, ast_format_get_default_ms(voicefmt));
4267 switch(ret) {
4268 case JB_OK:
4269 fr = frame.data;
4270 __do_deliver(fr);
4271 /* __do_deliver() can cause the call to disappear */
4272 pvt = iaxs[callno];
4273 break;
4274 case JB_INTERP:
4275 {
4276 struct ast_frame af = { 0, };
4277
4278 /* create an interpolation frame */
4280 af.subclass.format = voicefmt;
4281 af.samples = frame.ms * (ast_format_get_sample_rate(voicefmt) / 1000);
4282 af.src = "IAX2 JB interpolation";
4283 af.delivery = ast_tvadd(pvt->rxcore, ast_samp2tv(next, 1000));
4285
4286 /* queue the frame: For consistency, we would call __do_deliver here, but __do_deliver wants an iax_frame,
4287 * which we'd need to malloc, and then it would free it. That seems like a drag */
4288 if (!ast_test_flag64(iaxs[callno], IAX_ALREADYGONE)) {
4289 iax2_queue_frame(callno, &af);
4290 /* iax2_queue_frame() could cause the call to disappear */
4291 pvt = iaxs[callno];
4292 }
4293 }
4294 break;
4295 case JB_DROP:
4296 iax2_frame_free(frame.data);
4297 break;
4298 case JB_NOFRAME:
4299 case JB_EMPTY:
4300 /* do nothing */
4301 break;
4302 default:
4303 /* shouldn't happen */
4304 break;
4305 }
4306 }
4307cleanup:
4308 if (pvt)
4309 update_jbsched(pvt);
4310 ast_mutex_unlock(&iaxsl[callno]);
4311}
4312
4313static int get_from_jb(const void *data)
4314{
4315#ifdef SCHED_MULTITHREADED
4317#endif
4319 return 0;
4320}
4321
4322/*!
4323 * \note This function assumes fr->callno is locked
4324 *
4325 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
4326 * was valid before calling it, it may no longer be valid after calling it.
4327 */
4328static int schedule_delivery(struct iax_frame *fr, int updatehistory, int fromtrunk, unsigned int *tsout)
4329{
4330 int type, len;
4331 int ret;
4332 int needfree = 0;
4333
4334 /*
4335 * Clear fr->af.data if there is no data in the buffer. Things
4336 * like AST_CONTROL_HOLD without a suggested music class must
4337 * have a NULL pointer.
4338 */
4339 if (!fr->af.datalen) {
4340 memset(&fr->af.data, 0, sizeof(fr->af.data));
4341 }
4342
4343 /* Attempt to recover wrapped timestamps */
4344 unwrap_timestamp(fr);
4345
4346 /* delivery time is sender's sent timestamp converted back into absolute time according to our clock */
4347 if ( !fromtrunk && !ast_tvzero(iaxs[fr->callno]->rxcore))
4348 fr->af.delivery = ast_tvadd(iaxs[fr->callno]->rxcore, ast_samp2tv(fr->ts, 1000));
4349 else {
4350#if 0
4351 ast_debug(1, "schedule_delivery: set delivery to 0 as we don't have an rxcore yet, or frame is from trunk.\n");
4352#endif
4353 fr->af.delivery = ast_tv(0,0);
4354 }
4355
4357 len = 0;
4358
4359 if(fr->af.frametype == AST_FRAME_VOICE) {
4362 } else if(fr->af.frametype == AST_FRAME_CNG) {
4364 }
4365
4366 if ( (!ast_test_flag64(iaxs[fr->callno], IAX_USEJITTERBUF)) ) {
4367 if (tsout)
4368 *tsout = fr->ts;
4369 __do_deliver(fr);
4370 return -1;
4371 }
4372
4373 /* insert into jitterbuffer */
4374 /* TODO: Perhaps we could act immediately if it's not droppable and late */
4375 ret = jb_put(iaxs[fr->callno]->jb, fr, type, len, fr->ts,
4376 calc_rxstamp(iaxs[fr->callno],fr->ts));
4377 if (ret == JB_DROP) {
4378 needfree++;
4379 } else if (ret == JB_SCHED) {
4381 }
4382 if (tsout)
4383 *tsout = fr->ts;
4384 if (needfree) {
4385 /* Free our iax frame */
4386 iax2_frame_free(fr);
4387 return -1;
4388 }
4389 return 0;
4390}
4391
4392static int transmit_frame(void *data)
4393{
4394 struct iax_frame *fr = data;
4395
4397
4398 fr->sentyet = 1;
4399
4400 if (iaxs[fr->callno]) {
4401 send_packet(fr);
4402 }
4403
4404 if (fr->retries < 0) {
4406 /* No retransmit requested */
4407 iax_frame_free(fr);
4408 } else {
4409 /* We need reliable delivery. Schedule a retransmission */
4411 fr->retries++;
4414 }
4415
4416 return 0;
4417}
4418
4419static int iax2_transmit(struct iax_frame *fr)
4420{
4421 fr->sentyet = 0;
4422
4424}
4425
4426static int iax2_digit_begin(struct ast_channel *c, char digit)
4427{
4429}
4430
4431static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration)
4432{
4434}
4435
4436static int iax2_sendtext(struct ast_channel *c, const char *text)
4437{
4438
4440 0, 0, (unsigned char *)text, strlen(text) + 1, -1);
4441}
4442
4443static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
4444{
4446}
4447
4448static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen)
4449{
4450 return send_command_locked(PTR_TO_CALLNO(ast_channel_tech_pvt(c)), AST_FRAME_HTML, subclass, 0, (unsigned char *)data, datalen, -1);
4451}
4452
4453static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
4454{
4455 unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(newchan));
4457 if (iaxs[callno])
4458 iaxs[callno]->owner = newchan;
4459 else
4460 ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n");
4462 return 0;
4463}
4464
4465/*!
4466 * \note This function calls reg_source_db -> iax2_poke_peer -> find_callno,
4467 * so do not call this with a pvt lock held.
4468 */
4469static struct iax2_peer *realtime_peer(const char *peername, struct ast_sockaddr *addr)
4470{
4471 struct ast_variable *var = NULL;
4472 struct ast_variable *tmp;
4473 struct iax2_peer *peer=NULL;
4474 time_t regseconds = 0, nowtime;
4475 int dynamic=0;
4476 char *str_addr, *str_port;
4477
4480
4481 if (peername) {
4482 var = ast_load_realtime("iaxpeers", "name", peername, "host", "dynamic", SENTINEL);
4483 if (!var && !ast_sockaddr_isnull(addr)) {
4484 var = ast_load_realtime("iaxpeers", "name", peername, "host", str_addr, SENTINEL);
4485 }
4486 } else if (!ast_sockaddr_isnull(addr)) {
4487 var = ast_load_realtime("iaxpeers", "ipaddr", str_addr, "port", str_port, SENTINEL);
4488 if (var) {
4489 /* We'll need the peer name in order to build the structure! */
4490 for (tmp = var; tmp; tmp = tmp->next) {
4491 if (!strcasecmp(tmp->name, "name"))
4492 peername = tmp->value;
4493 }
4494 }
4495 }
4496 if (!var && peername) { /* Last ditch effort */
4497 var = ast_load_realtime("iaxpeers", "name", peername, SENTINEL);
4498 /*!\note
4499 * If this one loaded something, then we need to ensure that the host
4500 * field matched. The only reason why we can't have this as a criteria
4501 * is because we only have the IP address and the host field might be
4502 * set as a name (and the reverse PTR might not match).
4503 */
4504 if (var && !ast_sockaddr_isnull(addr)) {
4505 for (tmp = var; tmp; tmp = tmp->next) {
4506 if (!strcasecmp(tmp->name, "host")) {
4507 struct ast_sockaddr *hostaddr = NULL;
4508
4510 || ast_sockaddr_cmp_addr(hostaddr, addr)) {
4511 /* No match */
4513 var = NULL;
4514 }
4515 ast_free(hostaddr);
4516 break;
4517 }
4518 }
4519 }
4520 }
4521 if (!var)
4522 return NULL;
4523
4524 peer = build_peer(peername, var, NULL, ast_test_flag64((&globalflags), IAX_RTCACHEFRIENDS) ? 0 : 1);
4525
4526 if (!peer) {
4528 return NULL;
4529 }
4530
4531 for (tmp = var; tmp; tmp = tmp->next) {
4532 /* Make sure it's not a user only... */
4533 if (!strcasecmp(tmp->name, "type")) {
4534 if (strcasecmp(tmp->value, "friend") &&
4535 strcasecmp(tmp->value, "peer")) {
4536 /* Whoops, we weren't supposed to exist! */
4537 peer = peer_unref(peer);
4538 break;
4539 }
4540 } else if (!strcasecmp(tmp->name, "regseconds")) {
4541 ast_get_time_t(tmp->value, &regseconds, 0, NULL);
4542 } else if (!strcasecmp(tmp->name, "ipaddr")) {
4543 int setport = ast_sockaddr_port(&peer->addr);
4545 ast_log(LOG_WARNING, "Failed to parse sockaddr '%s' for ipaddr of realtime peer '%s'\n", tmp->value, tmp->name);
4546 } else {
4547 ast_sockaddr_parse(&peer->addr, tmp->value, 0);
4548 }
4549 ast_sockaddr_set_port(&peer->addr, setport);
4550 } else if (!strcasecmp(tmp->name, "port")) {
4551 int bindport;
4552 if (ast_parse_arg(tmp->value, PARSE_UINT32 | PARSE_IN_RANGE, &bindport, 0, 65535)) {
4553 bindport = IAX_DEFAULT_PORTNO;
4554 }
4555 ast_sockaddr_set_port(&peer->addr, bindport);
4556 } else if (!strcasecmp(tmp->name, "host")) {
4557 if (!strcasecmp(tmp->value, "dynamic"))
4558 dynamic = 1;
4559 }
4560 }
4561
4563
4566 if (ast_test_flag64(peer, IAX_RTAUTOCLEAR)) {
4567 if (peer->expire > -1) {
4568 if (!AST_SCHED_DEL(sched, peer->expire)) {
4569 peer->expire = -1;
4570 peer_unref(peer);
4571 }
4572 }
4574 if (peer->expire == -1)
4575 peer_unref(peer);
4576 }
4577 ao2_link(peers, peer);
4578 if (ast_test_flag64(peer, IAX_DYNAMIC))
4579 reg_source_db(peer);
4580 } else {
4582 }
4583
4585 time(&nowtime);
4586 if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE) {
4587 memset(&peer->addr, 0, sizeof(peer->addr));
4588 realtime_update_peer(peer->name, &peer->addr, 0);
4589 ast_debug(1, "realtime_peer: Bah, '%s' is expired (%d/%d/%d)!\n",
4590 peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
4591 }
4592 else {
4593 ast_debug(1, "realtime_peer: Registration for '%s' still active (%d/%d/%d)!\n",
4594 peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
4595 }
4596 }
4597
4598 return peer;
4599}
4600
4601static struct iax2_user *realtime_user(const char *username, struct ast_sockaddr *addr)
4602{
4603 struct ast_variable *var;
4604 struct ast_variable *tmp;
4605 struct iax2_user *user=NULL;
4606 char *str_addr, *str_port;
4607
4608 str_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
4609 str_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
4610
4611 var = ast_load_realtime("iaxusers", "name", username, "host", "dynamic", SENTINEL);
4612 if (!var)
4613 var = ast_load_realtime("iaxusers", "name", username, "host", str_addr, SENTINEL);
4614 if (!var && !ast_sockaddr_isnull(addr)) {
4615 var = ast_load_realtime("iaxusers", "name", username, "ipaddr", str_addr, "port", str_port, SENTINEL);
4616 if (!var)
4617 var = ast_load_realtime("iaxusers", "ipaddr", str_addr, "port", str_port, SENTINEL);
4618 }
4619 if (!var) { /* Last ditch effort */
4620 var = ast_load_realtime("iaxusers", "name", username, SENTINEL);
4621 /*!\note
4622 * If this one loaded something, then we need to ensure that the host
4623 * field matched. The only reason why we can't have this as a criteria
4624 * is because we only have the IP address and the host field might be
4625 * set as a name (and the reverse PTR might not match).
4626 */
4627 if (var) {
4628 for (tmp = var; tmp; tmp = tmp->next) {
4629 if (!strcasecmp(tmp->name, "host")) {
4630 struct ast_sockaddr *hostaddr = NULL;
4631
4633 || ast_sockaddr_cmp_addr(hostaddr, addr)) {
4634 /* No match */
4636 var = NULL;
4637 }
4638 ast_free(hostaddr);
4639 break;
4640 }
4641 }
4642 }
4643 }
4644 if (!var)
4645 return NULL;
4646
4647 tmp = var;
4648 while(tmp) {
4649 /* Make sure it's not a peer only... */
4650 if (!strcasecmp(tmp->name, "type")) {
4651 if (strcasecmp(tmp->value, "friend") &&
4652 strcasecmp(tmp->value, "user")) {
4653 return NULL;
4654 }
4655 }
4656 tmp = tmp->next;
4657 }
4658
4660
4662
4663 if (!user)
4664 return NULL;
4665
4669 } else {
4671 }
4672
4673 return user;
4674}
4675
4676static void realtime_update_peer(const char *peername, struct ast_sockaddr *sockaddr, time_t regtime)
4677{
4678 char regseconds[20];
4679 const char *sysname = ast_config_AST_SYSTEM_NAME;
4680 char *syslabel = NULL;
4681 char *port;
4682
4683 if (ast_strlen_zero(sysname)) /* No system name, disable this */
4684 sysname = NULL;
4686 syslabel = "regserver";
4687
4688 snprintf(regseconds, sizeof(regseconds), "%d", (int)regtime);
4689 port = ast_strdupa(ast_sockaddr_stringify_port(sockaddr));
4690 ast_update_realtime("iaxpeers", "name", peername,
4691 "ipaddr", ast_sockaddr_isnull(sockaddr) ? "" : ast_sockaddr_stringify_addr(sockaddr),
4692 "port", ast_sockaddr_isnull(sockaddr) ? "" : port,
4693 "regseconds", regseconds, syslabel, sysname, SENTINEL); /* note syslabel can be NULL */
4694}
4695
4696struct create_addr_info {
4698 uint64_t flags;
4699 struct iax2_codec_pref prefs;
4700 int maxtime;
4701 int encmethods;
4702 int authmethods;
4703 int found;
4704 int sockfd;
4705 int adsi;
4706 char username[80];
4707 char secret[80];
4708 char outkey[80];
4709 char timezone[80];
4710 char cid_num[80];
4711 char cid_name[80];
4716};
4717
4718static int create_addr(const char *peername, struct ast_channel *c, struct ast_sockaddr *addr, struct create_addr_info *cai)
4719{
4720 struct iax2_peer *peer;
4721 int res = -1;
4722
4724 cai->sockfd = defaultsockfd;
4725 cai->maxtime = 0;
4726
4727 if (!(peer = find_peer(peername, 1))) {
4728 struct ast_sockaddr peer_addr;
4729
4730 peer_addr.ss.ss_family = AST_AF_UNSPEC;
4731 cai->found = 0;
4732 if (ast_get_ip_or_srv(&peer_addr, peername, srvlookup ? "_iax._udp" : NULL)) {
4733 ast_log(LOG_WARNING, "No such host: %s\n", peername);
4734 return -1;
4735 }
4736
4737 if (!ast_sockaddr_port(&peer_addr)) {
4739 }
4740
4741 ast_sockaddr_copy(addr, &peer_addr);
4742 /*
4743 * Use The global iax prefs for unknown peer/user.
4744 * However, move the calling channel's native codec to
4745 * the top of the preference list.
4746 */
4747 cai->prefs = prefs_global;
4748 if (c) {
4749 int i;
4750
4751 for (i = 0; i < ast_format_cap_count(ast_channel_nativeformats(c)); i++) {
4752 struct ast_format *format = ast_format_cap_get_format(
4754 iax2_codec_pref_prepend(&cai->prefs, format,
4756 1);
4757 ao2_ref(format, -1);
4758 }
4759 }
4760 return 0;
4761 }
4762
4763 cai->found = 1;
4764
4765 /* if the peer has no address (current or default), return failure */
4766 if (ast_sockaddr_isnull(&peer->addr) && ast_sockaddr_isnull(&peer->defaddr)) {
4767 goto return_unref;
4768 }
4769
4770 /* if the peer is being monitored and is currently unreachable, return failure */
4771 if (peer->maxms && ((peer->lastms > peer->maxms) || (peer->lastms < 0)))
4772 goto return_unref;
4773
4775 cai->maxtime = peer->maxms;
4776 cai->capability = peer->capability;
4777 cai->encmethods = peer->encmethods;
4778 cai->authmethods = peer->authmethods;
4779 cai->sockfd = peer->sockfd;
4780 cai->adsi = peer->adsi;
4781 cai->prefs = peer->prefs;
4782 /* Move the calling channel's native codec to the top of the preference list */
4783 if (c) {
4784 int i;
4785
4786 for (i = 0; i < ast_format_cap_count(ast_channel_nativeformats(c)); i++) {
4787 struct ast_format *tmpfmt = ast_format_cap_get_format(
4789 iax2_codec_pref_prepend(&cai->prefs, tmpfmt,
4791 1);
4792 ao2_ref(tmpfmt, -1);
4793 }
4794 }
4795 ast_copy_string(cai->context, peer->context, sizeof(cai->context));
4796 ast_copy_string(cai->peercontext, peer->peercontext, sizeof(cai->peercontext));
4797 ast_copy_string(cai->username, peer->username, sizeof(cai->username));
4798 ast_copy_string(cai->timezone, peer->zonetag, sizeof(cai->timezone));
4799 ast_copy_string(cai->outkey, peer->outkey, sizeof(cai->outkey));
4800 ast_copy_string(cai->cid_num, peer->cid_num, sizeof(cai->cid_num));
4801 ast_copy_string(cai->cid_name, peer->cid_name, sizeof(cai->cid_name));
4802 ast_copy_string(cai->mohinterpret, peer->mohinterpret, sizeof(cai->mohinterpret));
4803 ast_copy_string(cai->mohsuggest, peer->mohsuggest, sizeof(cai->mohsuggest));
4804 if (ast_strlen_zero(peer->dbsecret)) {
4805 ast_copy_string(cai->secret, peer->secret, sizeof(cai->secret));
4806 } else {
4807 char *family;
4808 char *key = NULL;
4809
4810 family = ast_strdupa(peer->dbsecret);
4811 key = strchr(family, '/');
4812 if (key)
4813 *key++ = '\0';
4814 if (!key || ast_db_get(family, key, cai->secret, sizeof(cai->secret))) {
4815 ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", peer->dbsecret);
4816 goto return_unref;
4817 }
4818 }
4819
4820 if (!ast_sockaddr_isnull(&peer->addr)) {
4821 ast_sockaddr_copy(addr, &peer->addr);
4822 } else {
4823 ast_sockaddr_copy(addr, &peer->defaddr);
4824 }
4825
4826 res = 0;
4827
4828return_unref:
4829 peer_unref(peer);
4830
4831 return res;
4832}
4833
4834static void __auto_congest(const void *nothing)
4835{
4836 int callno = PTR_TO_CALLNO(nothing);
4838 ast_mutex_lock(&iaxsl[callno]);
4839 if (iaxs[callno]) {
4840 iaxs[callno]->initid = -1;
4841 iax2_queue_frame(callno, &f);
4842 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
4843 }
4844 ast_mutex_unlock(&iaxsl[callno]);
4845}
4846
4847static int auto_congest(const void *data)
4848{
4849#ifdef SCHED_MULTITHREADED
4851#endif
4853 return 0;
4854}
4855
4856static unsigned int iax2_datetime(const char *tz)
4857{
4858 struct timeval t = ast_tvnow();
4859 struct ast_tm tm;
4860 unsigned int tmp;
4861 ast_localtime(&t, &tm, ast_strlen_zero(tz) ? NULL : tz);
4862 tmp = (tm.tm_sec >> 1) & 0x1f; /* 5 bits of seconds */
4863 tmp |= (tm.tm_min & 0x3f) << 5; /* 6 bits of minutes */
4864 tmp |= (tm.tm_hour & 0x1f) << 11; /* 5 bits of hours */
4865 tmp |= (tm.tm_mday & 0x1f) << 16; /* 5 bits of day of month */
4866 tmp |= ((tm.tm_mon + 1) & 0xf) << 21; /* 4 bits of month */
4867 tmp |= ((tm.tm_year - 100) & 0x7f) << 25; /* 7 bits of year */
4868 return tmp;
4869}
4870
4871struct parsed_dial_string {
4872 char *username;
4873 char *password;
4874 char *key;
4875 char *peer;
4876 char *port;
4877 char *exten;
4878 char *context;
4879 char *options;
4880};
4881
4882static int send_apathetic_reply(unsigned short callno, unsigned short dcallno,
4883 struct ast_sockaddr *addr, int command, int ts, unsigned char seqno,
4884 int sockfd, struct iax_ie_data *ied)
4885{
4886 struct {
4887 struct ast_iax2_full_hdr f;
4888 struct iax_ie_data ied;
4889 } data;
4890 size_t size = sizeof(struct ast_iax2_full_hdr);
4891
4892 if (ied) {
4893 size += ied->pos;
4894 memcpy(&data.ied, ied->buf, ied->pos);
4895 }
4896
4897 data.f.scallno = htons(0x8000 | callno);
4898 data.f.dcallno = htons(dcallno & ~IAX_FLAG_RETRANS);
4899 data.f.ts = htonl(ts);
4900 data.f.iseqno = seqno;
4901 data.f.oseqno = 0;
4902 data.f.type = AST_FRAME_IAX;
4903 data.f.csub = compress_subclass(command);
4904
4905 iax_outputframe(NULL, &data.f, 0, addr, size - sizeof(struct ast_iax2_full_hdr));
4906
4907 return ast_sendto(sockfd, &data, size, 0, addr);
4908}
4909
4910static void add_empty_calltoken_ie(struct chan_iax2_pvt *pvt, struct iax_ie_data *ied)
4911{
4912 /* first make sure their are two empty bytes left in ied->buf */
4913 if (pvt && ied && (2 < ((int) sizeof(ied->buf) - ied->pos))) {
4914 ied->buf[ied->pos++] = IAX_IE_CALLTOKEN; /* type */
4915 ied->buf[ied->pos++] = 0; /* data size, ZERO in this case */
4916 pvt->calltoken_ie_len = 2;
4917 }
4918}
4919
4920static void resend_with_token(int callno, struct iax_frame *f, const char *newtoken)
4921{
4922 struct chan_iax2_pvt *pvt = iaxs[callno];
4923 int frametype = f->af.frametype;
4924 int subclass = f->af.subclass.integer;
4925 struct {
4926 struct ast_iax2_full_hdr fh;
4927 struct iax_ie_data ied;
4928 } data = {
4929 .ied.buf = { 0 },
4930 .ied.pos = 0,
4931 };
4932 /* total len - header len gives us the frame's IE len */
4933 int ie_data_pos = f->datalen - sizeof(struct ast_iax2_full_hdr);
4934
4935 if (!pvt) {
4936 return; /* this should not be possible if called from socket_process() */
4937 }
4938
4939 /*
4940 * Check to make sure last frame sent is valid for call token resend
4941 * 1. Frame should _NOT_ be encrypted since it starts the IAX dialog
4942 * 2. Frame should _NOT_ already have a destination callno
4943 * 3. Frame must be a valid iax_frame subclass capable of starting dialog
4944 * 4. Pvt must have a calltoken_ie_len which represents the number of
4945 * bytes at the end of the frame used for the previous calltoken ie.
4946 * 5. Pvt's calltoken_ie_len must be _LESS_ than the total IE length
4947 * 6. Total length of f->data must be _LESS_ than size of our data struct
4948 * because f->data must be able to fit within data.
4949 */
4950 if (f->encmethods || f->dcallno || !iax2_allow_new(frametype, subclass, 0)
4951 || !pvt->calltoken_ie_len || (pvt->calltoken_ie_len > ie_data_pos) ||
4952 (f->datalen > sizeof(data))) {
4953
4954 return; /* ignore resend, token was not valid for the dialog */
4955 }
4956
4957 /* token is valid
4958 * 1. Copy frame data over
4959 * 2. Redo calltoken IE, it will always be the last ie in the frame.
4960 * NOTE: Having the ie always be last is not protocol specified,
4961 * it is only an implementation choice. Since we only expect the ie to
4962 * be last for frames we have sent, this can no way be affected by
4963 * another end point.
4964 * 3. Remove frame from queue
4965 * 4. Free old frame
4966 * 5. Clear previous seqnos
4967 * 6. Resend with CALLTOKEN ie.
4968 */
4969
4970 /* ---1.--- */
4971 memcpy(&data, f->data, f->datalen);
4972 data.ied.pos = ie_data_pos;
4973
4974 /* ---2.--- */
4975 /* move to the beginning of the calltoken ie so we can write over it */
4976 data.ied.pos -= pvt->calltoken_ie_len;
4977 iax_ie_append_str(&data.ied, IAX_IE_CALLTOKEN, newtoken);
4978
4979 /* make sure to update token length incase it ever has to be stripped off again */
4980 pvt->calltoken_ie_len = data.ied.pos - ie_data_pos; /* new pos minus old pos tells how big token ie is */
4981
4982 /* ---3.--- */
4983 AST_LIST_REMOVE(&frame_queue[callno], f, list);
4984
4985 /* ---4.--- */
4986 iax2_frame_free(f);
4987
4988 /* ---5.--- */
4989 pvt->oseqno = 0;
4990 pvt->rseqno = 0;
4991 pvt->iseqno = 0;
4992 pvt->aseqno = 0;
4993 if (pvt->peercallno) {
4995 pvt->peercallno = 0;
4996 }
4997
4998 /* ---6.--- */
4999 send_command(pvt, AST_FRAME_IAX, subclass, 0, data.ied.buf, data.ied.pos, -1);
5000}
5001
5002static void requirecalltoken_mark_auto(const char *name, int subclass)
5003{
5004 struct iax2_user *user = NULL;
5005 struct iax2_peer *peer = NULL;
5006
5007 if (ast_strlen_zero(name)) {
5008 return; /* no username given */
5009 }
5010
5011 if ((subclass == IAX_COMMAND_NEW) && (user = find_user(name)) && (user->calltoken_required == CALLTOKEN_AUTO)) {
5012 user->calltoken_required = CALLTOKEN_YES;
5013 } else if ((subclass != IAX_COMMAND_NEW) && (peer = find_peer(name, 1)) && (peer->calltoken_required == CALLTOKEN_AUTO)) {
5015 }
5016
5017 if (peer) {
5018 peer_unref(peer);
5019 }
5020 if (user) {
5022 }
5023}
5024
5025/*!
5026 * \internal
5027 *
5028 * \brief handles calltoken logic for a received iax_frame.
5029 *
5030 * \note frametype must be AST_FRAME_IAX.
5031 *
5032 * \note
5033 * Three different cases are possible here.
5034 * Case 1. An empty calltoken is provided. This means the client supports
5035 * calltokens but has not yet received one from us. In this case
5036 * a full calltoken IE is created and sent in a calltoken fullframe.
5037 * Case 2. A full calltoken is received and must be checked for validity.
5038 * Case 3. No calltoken is received indicating that the client does not
5039 * support calltokens. In this case it is up to the configuration
5040 * to decide how this should be handled (reject or permit without calltoken)
5041 */
5042static int handle_call_token(struct ast_iax2_full_hdr *fh, struct iax_ies *ies,
5043 struct ast_sockaddr *addr, int fd)
5044{
5045#define CALLTOKEN_HASH_FORMAT "%s%u%d" /* address + port + ts + randomcalldata */
5046#define CALLTOKEN_IE_FORMAT "%u?%s" /* time + ? + (40 char hash) */
5047 struct ast_str *buf = ast_str_alloca(256);
5048 time_t t = time(NULL);
5049 char hash[41]; /* 40 char sha1 hash */
5050 int subclass = uncompress_subclass(fh->csub);
5051
5052 /* ----- Case 1 ----- */
5053 if (ies->calltoken && !ies->calltokendata) { /* empty calltoken is provided, client supports calltokens */
5054 struct iax_ie_data ied = {
5055 .buf = { 0 },
5056 .pos = 0,
5057 };
5058
5059 /* create the hash with their address data and our timestamp */
5062
5063 ast_str_set(&buf, 0, CALLTOKEN_IE_FORMAT, (unsigned int) t, hash);
5065 send_apathetic_reply(1, ntohs(fh->scallno), addr, IAX_COMMAND_CALLTOKEN, ntohl(fh->ts), fh->iseqno + 1, fd, &ied);
5066
5067 return 1;
5068
5069 /* ----- Case 2 ----- */
5070 } else if (ies->calltoken && ies->calltokendata) { /* calltoken received, check to see if it is valid */
5071 char *rec_hash = NULL; /* the received hash, make sure it matches with ours. */
5072 char *rec_ts = NULL; /* received timestamp */
5073 unsigned int rec_time; /* received time_t */
5074
5075 /* split the timestamp from the hash data */
5076 rec_hash = strchr((char *) ies->calltokendata, '?');
5077 if (rec_hash) {
5078 *rec_hash++ = '\0';
5079 rec_ts = (char *) ies->calltokendata;
5080 }
5081
5082 /* check that we have valid data before we do any comparisons */
5083 if (!rec_hash || !rec_ts) {
5084 goto reject;
5085 } else if (sscanf(rec_ts, "%u", &rec_time) != 1) {
5086 goto reject;
5087 }
5088
5089 /* create a hash with their address and the _TOKEN'S_ timestamp */
5092
5093 /* compare hashes and then check timestamp delay */
5094 if (strcmp(hash, rec_hash)) {
5095 ast_log(LOG_WARNING, "Address %s failed CallToken hash inspection\n", ast_sockaddr_stringify(addr));
5096 goto reject; /* received hash does not match ours, reject */
5097 } else if ((t < rec_time) || ((t - rec_time) >= max_calltoken_delay)) {
5098 ast_log(LOG_WARNING, "Too much delay in IAX2 calltoken timestamp from address %s\n", ast_sockaddr_stringify(addr));
5099 goto reject; /* too much delay, reject */
5100 }
5101
5102 /* at this point the call token is valid, returning 0
5103 * will allow socket_process to continue as usual */
5104 requirecalltoken_mark_auto(ies->username, subclass);
5105 return 0;
5106
5107 /* ----- Case 3 ----- */
5108 } else { /* calltokens are not supported for this client, how do we respond? */
5109 if (calltoken_required(addr, ies->username, subclass)) {
5110 ast_log(LOG_ERROR, "Call rejected, CallToken Support required. If unexpected, resolve by placing address %s in the calltokenoptional list or setting user %s requirecalltoken=no\n", ast_sockaddr_stringify(addr), S_OR(ies->username, "guest"));
5111 goto reject;
5112 }
5113 return 0; /* calltoken is not required for this addr, so permit it. */
5114 }
5115
5116reject:
5117 /* received frame has failed calltoken inspection, send apathetic reject messages */
5118 if (subclass == IAX_COMMAND_REGREQ || subclass == IAX_COMMAND_REGREL) {
5119 send_apathetic_reply(1, ntohs(fh->scallno), addr, IAX_COMMAND_REGREJ, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
5120 } else {
5121 send_apathetic_reply(1, ntohs(fh->scallno), addr, IAX_COMMAND_REJECT, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
5122 }
5123
5124 return 1;
5125}
5126
5127/*!
5128 * \brief Parses an IAX dial string into its component parts.
5129 * \param data the string to be parsed
5130 * \param pds pointer to a \c struct \c parsed_dial_string to be filled in
5131 *
5132 * This function parses the string and fills the structure
5133 * with pointers to its component parts. The input string
5134 * will be modified.
5135 *
5136 * \note This function supports both plaintext passwords and RSA
5137 * key names; if the password string is formatted as '[keyname]',
5138 * then the keyname will be placed into the key field, and the
5139 * password field will be set to NULL.
5140 *
5141 * \note The dial string format is:
5142 * \verbatim [username[:password]@]peer[:port][/exten[@context]][/options] \endverbatim
5143 */
5144static void parse_dial_string(char *data, struct parsed_dial_string *pds)
5145{
5146 char *outkey = NULL;
5147
5148 if (ast_strlen_zero(data))
5149 return;
5150
5151 pds->peer = strsep(&data, "/");
5152 pds->exten = strsep(&data, "/");
5153 pds->options = data;
5154
5155 if (pds->exten) {
5156 data = pds->exten;
5157 pds->exten = strsep(&data, "@");
5158 pds->context = data;
5159 }
5160
5161 if (strchr(pds->peer, '@')) {
5162 data = pds->peer;
5163 pds->username = strsep(&data, "@");
5164 pds->peer = data;
5165 }
5166
5167 if (pds->username) {
5168 data = pds->username;
5169 pds->username = strsep(&data, ":");
5170 pds->password = strsep(&data, ":");
5171 outkey = data;
5172 }
5173
5174 data = pds->peer;
5175 pds->peer = strsep(&data, ":");
5176 pds->port = data;
5177
5178 /*
5179 * Check for a key name wrapped in [] in the password position.
5180 * If found, move it to the key field instead.
5181 * Also allow for both key and secret to be specified, now that
5182 * encryption is possible with RSA authentication.
5183 */
5184
5185 if (pds->password && (pds->password[0] == '[')) { /* key (then maybe secret) */
5186 pds->key = ast_strip_quoted(pds->password, "[", "]");
5187 if (ast_strlen_zero(outkey)) {
5188 pds->password = NULL;
5189 ast_debug(1, "Outkey (%s), no secret\n", pds->key);
5190 } else {
5191 pds->password = outkey;
5192 ast_debug(1, "Outkey (%s) and secret (%s)\n", pds->key, pds->password);
5193 }
5194 } else if (outkey && (outkey[0] == '[')) { /* secret, then key */
5195 pds->key = ast_strip_quoted(outkey, "[", "]");
5196 if (ast_strlen_zero(pds->password)) {
5197 ast_debug(1, "Outkey (%s), no secret\n", pds->key);
5198 } else {
5199 ast_debug(1, "Outkey (%s) and secret (%s)\n", pds->key, pds->password);
5200 }
5201 }
5202}
5203
5204static int iax2_call(struct ast_channel *c, const char *dest, int timeout)
5205{
5206 struct ast_sockaddr addr;
5207 char *l=NULL, *n=NULL, *tmpstr;
5208 struct iax_ie_data ied;
5209 char *defaultrdest = "s";
5210 unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
5211 struct parsed_dial_string pds;
5212 struct create_addr_info cai;
5213 struct ast_var_t *var;
5215 const char* osp_token_ptr;
5216 unsigned int osp_token_length;
5217 unsigned char osp_block_index;
5218 unsigned int osp_block_length;
5219 unsigned char osp_buffer[256];
5220 char encoded_prefs[32];
5221 iax2_format iax2_tmpfmt;
5222
5224 ast_log(LOG_WARNING, "Channel is already in use (%s)?\n", ast_channel_name(c));
5225 return -1;
5226 }
5227
5228 memset(&cai, 0, sizeof(cai));
5231
5232 memset(&pds, 0, sizeof(pds));
5233 tmpstr = ast_strdupa(dest);
5234 parse_dial_string(tmpstr, &pds);
5235
5236 if (ast_strlen_zero(pds.peer)) {
5237 ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", dest);
5238 return -1;
5239 }
5240 if (!pds.exten) {
5241 pds.exten = defaultrdest;
5242 }
5243 if (create_addr(pds.peer, c, &addr, &cai)) {
5244 ast_log(LOG_WARNING, "No address associated with '%s'\n", pds.peer);
5245 return -1;
5246 }
5247
5250 if (!cai.encmethods) {
5251 ast_log(LOG_WARNING, "Encryption forced for call, but not enabled\n");
5253 return -1;
5254 }
5255 if (((cai.authmethods & IAX_AUTH_RSA) || (cai.authmethods & IAX_AUTH_MD5) || (cai.authmethods & IAX_AUTH_PLAINTEXT)) &&
5257 ast_log(LOG_WARNING, "Call terminated. Encryption forced but no secret provided\n");
5258 return -1;
5259 }
5260 }
5261
5262 if (!pds.username && !ast_strlen_zero(cai.username))
5263 pds.username = cai.username;
5264 if (!pds.password && !ast_strlen_zero(cai.secret))
5265 pds.password = cai.secret;
5266 if (!pds.key && !ast_strlen_zero(cai.outkey))
5267 pds.key = cai.outkey;
5268 if (!pds.context && !ast_strlen_zero(cai.peercontext))
5269 pds.context = cai.peercontext;
5270
5271 /* Keep track of the context for outgoing calls too */
5273
5274 if (pds.port) {
5275 int bindport;
5276 if (ast_parse_arg(pds.port, PARSE_UINT32 | PARSE_IN_RANGE, &bindport, 0, 65535)) {
5277 ast_sockaddr_set_port(&addr, bindport);
5278 }
5279 }
5280
5283
5284 /* Now build request */
5285 memset(&ied, 0, sizeof(ied));
5286
5287 /* On new call, first IE MUST be IAX version of caller */
5290 if (pds.options && strchr(pds.options, 'a')) {
5291 /* Request auto answer */
5293 }
5294
5295 /* WARNING: this breaks down at 190 bits! */
5296 iax2_codec_pref_convert(&cai.prefs, encoded_prefs, sizeof(encoded_prefs), 1);
5297 iax_ie_append_str(&ied, IAX_IE_CODEC_PREFS, encoded_prefs);
5298
5299 if (l) {
5303 } else if (n) {
5306 } else {
5308 }
5309
5311 iax_ie_append_short(&ied, IAX_IE_CALLINGTNS, ast_channel_dialed(c)->transit_network_select);
5313
5314 if (n)
5316 if (ast_test_flag64(iaxs[callno], IAX_SENDANI)
5317 && ast_channel_connected(c)->ani.number.valid
5318 && ast_channel_connected(c)->ani.number.str) {
5320 }
5321
5326 }
5327 if (ast_channel_redirecting(c)->from.number.valid
5328 && !ast_strlen_zero(ast_channel_redirecting(c)->from.number.str)) {
5329 iax_ie_append_str(&ied, IAX_IE_RDNIS, ast_channel_redirecting(c)->from.number.str);
5330 }
5331
5332 if (pds.context)
5334
5335 if (pds.username)
5337
5338 if (cai.encmethods)
5340
5341 ast_mutex_lock(&iaxsl[callno]);
5342
5344 ast_string_field_set(iaxs[callno], context, ast_channel_context(c));
5345
5346 if (pds.username)
5347 ast_string_field_set(iaxs[callno], username, pds.username);
5348
5349 iaxs[callno]->encmethods = cai.encmethods;
5350
5351 iaxs[callno]->adsi = cai.adsi;
5352
5355
5356 if (pds.key)
5357 ast_string_field_set(iaxs[callno], outkey, pds.key);
5358 if (pds.password)
5359 ast_string_field_set(iaxs[callno], secret, pds.password);
5360
5362 iax_ie_append_int(&ied, IAX_IE_FORMAT, (int) iax2_tmpfmt);
5363 iax_ie_append_versioned_uint64(&ied, IAX_IE_FORMAT2, 0, iax2_tmpfmt);
5364
5365 iax_ie_append_int(&ied, IAX_IE_CAPABILITY, (int) iaxs[callno]->capability);
5366 iax_ie_append_versioned_uint64(&ied, IAX_IE_CAPABILITY2, 0, iaxs[callno]->capability);
5369
5370 if (iaxs[callno]->maxtime) {
5371 /* Initialize pingtime and auto-congest time */
5372 iaxs[callno]->pingtime = iaxs[callno]->maxtime / 2;
5373 iaxs[callno]->initid = iax2_sched_add(sched, iaxs[callno]->maxtime * 2, auto_congest, CALLNO_TO_PTR(callno));
5374 } else if (autokill) {
5375 iaxs[callno]->pingtime = autokill / 2;
5377 }
5378
5379 /* Check if there is an OSP token */
5380 osp_token_ptr = pbx_builtin_getvar_helper(c, "IAX2OSPTOKEN");
5381 if (!ast_strlen_zero(osp_token_ptr)) {
5382 if ((osp_token_length = strlen(osp_token_ptr)) <= IAX_MAX_OSPTOKEN_SIZE) {
5383 osp_block_index = 0;
5384 while (osp_token_length > 0) {
5385 osp_block_length = IAX_MAX_OSPBLOCK_SIZE < osp_token_length ? IAX_MAX_OSPBLOCK_SIZE : osp_token_length;
5386 osp_buffer[0] = osp_block_index;
5387 memcpy(osp_buffer + 1, osp_token_ptr, osp_block_length);
5388 iax_ie_append_raw(&ied, IAX_IE_OSPTOKEN, osp_buffer, osp_block_length + 1);
5389 osp_block_index++;
5390 osp_token_ptr += osp_block_length;
5391 osp_token_length -= osp_block_length;
5392 }
5393 } else
5394 ast_log(LOG_WARNING, "OSP token is too long\n");
5395 } else if (iaxdebug)
5396 ast_debug(1, "OSP token is undefined\n");
5397
5398 /* send the command using the appropriate socket for this peer */
5399 iaxs[callno]->sockfd = cai.sockfd;
5400
5401 /* Add remote vars */
5402 if (variablestore) {
5403 AST_LIST_HEAD(, ast_var_t) *variablelist = variablestore->data;
5404 ast_debug(1, "Found an IAX variable store on this channel\n");
5405 AST_LIST_LOCK(variablelist);
5406 AST_LIST_TRAVERSE(variablelist, var, entries) {
5407 char tmp[256];
5408 int i;
5409 ast_debug(1, "Found IAXVAR '%s' with value '%s' (to transmit)\n", ast_var_name(var), ast_var_value(var));
5410 /* Automatically divide the value up into sized chunks */
5411 for (i = 0; i < strlen(ast_var_value(var)); i += 255 - (strlen(ast_var_name(var)) + 1)) {
5412 snprintf(tmp, sizeof(tmp), "%s=%s", ast_var_name(var), ast_var_value(var) + i);
5414 }
5415 }
5416 AST_LIST_UNLOCK(variablelist);
5417 }
5418
5419 /* Transmit the string in a "NEW" request */
5420 add_empty_calltoken_ie(iaxs[callno], &ied); /* this _MUST_ be the last ie added */
5421 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
5422
5423 ast_mutex_unlock(&iaxsl[callno]);
5425
5426 return 0;
5427}
5428
5429static int iax2_hangup(struct ast_channel *c)
5430{
5431 unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
5432 struct iax_ie_data ied;
5433 int alreadygone;
5434 memset(&ied, 0, sizeof(ied));
5435 ast_mutex_lock(&iaxsl[callno]);
5436 if (callno && iaxs[callno]) {
5437 ast_debug(1, "We're hanging up %s now...\n", ast_channel_name(c));
5438 alreadygone = ast_test_flag64(iaxs[callno], IAX_ALREADYGONE);
5439 /* Send the hangup unless we have had a transmission error or are already gone */
5441 if (!iaxs[callno]->error && !alreadygone) {
5442 if (send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1)) {
5443 ast_log(LOG_WARNING, "No final packet could be sent for callno %d\n", callno);
5444 }
5445 if (!iaxs[callno]) {
5446 ast_mutex_unlock(&iaxsl[callno]);
5447 return 0;
5448 }
5449 }
5450 /* Explicitly predestroy it */
5451 iax2_predestroy(callno);
5452 /* If we were already gone to begin with, destroy us now */
5453 if (iaxs[callno] && alreadygone) {
5454 ast_debug(1, "Really destroying %s now...\n", ast_channel_name(c));
5455 iax2_destroy(callno);
5456 } else if (iaxs[callno]) {
5457 if (ast_sched_add(sched, 10000, scheduled_destroy, CALLNO_TO_PTR(callno)) < 0) {
5458 ast_log(LOG_ERROR, "Unable to schedule iax2 callno %d destruction?!! Destroying immediately.\n", callno);
5459 iax2_destroy(callno);
5460 }
5461 }
5462 } else if (ast_channel_tech_pvt(c)) {
5463 /* If this call no longer exists, but the channel still
5464 * references it we need to set the channel's tech_pvt to null
5465 * to avoid ast_channel_free() trying to free it.
5466 */
5468 }
5469 ast_mutex_unlock(&iaxsl[callno]);
5470 ast_verb(3, "Hungup '%s'\n", ast_channel_name(c));
5471 return 0;
5472}
5473
5474/*!
5475 * \note expects the pvt to be locked
5476 */
5477static int wait_for_peercallno(struct chan_iax2_pvt *pvt)
5478{
5479 unsigned short callno = pvt->callno;
5480
5481 if (!pvt->peercallno) {
5482 /* We don't know the remote side's call number, yet. :( */
5483 int count = 10;
5484 while (count-- && pvt && !pvt->peercallno) {
5485 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
5486 pvt = iaxs[callno];
5487 }
5488 if (!pvt || !pvt->peercallno) {
5489 return -1;
5490 }
5491 }
5492
5493 return 0;
5494}
5495
5496static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
5497{
5498 struct ast_option_header *h;
5499 int res;
5500
5501 switch (option) {
5502 case AST_OPTION_TXGAIN:
5503 case AST_OPTION_RXGAIN:
5504 /* these two cannot be sent, because they require a result */
5505 errno = ENOSYS;
5506 return -1;
5507 case AST_OPTION_OPRMODE:
5508 errno = EINVAL;
5509 return -1;
5512 {
5513 unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
5514 ast_mutex_lock(&iaxsl[callno]);
5515 if ((*(int *) data)) {
5517 } else {
5519 }
5520 ast_mutex_unlock(&iaxsl[callno]);
5521 return 0;
5522 }
5523 /* These options are sent to the other side across the network where
5524 * they will be passed to whatever channel is bridged there. Don't
5525 * do anything silly like pass an option that transmits pointers to
5526 * memory on this machine to a remote machine to use */
5528 case AST_OPTION_TDD:
5533 {
5534 unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
5535 struct chan_iax2_pvt *pvt;
5536
5538 pvt = iaxs[callno];
5539
5540 if (wait_for_peercallno(pvt)) {
5542 return -1;
5543 }
5544
5546
5547 if (!(h = ast_malloc(datalen + sizeof(*h)))) {
5548 return -1;
5549 }
5550
5552 h->option = htons(option);
5553 memcpy(h->data, data, datalen);
5555 AST_CONTROL_OPTION, 0, (unsigned char *) h,
5556 datalen + sizeof(*h), -1);
5557 ast_free(h);
5558 return res;
5559 }
5560 default:
5561 return -1;
5562 }
5563
5564 /* Just in case someone does a break instead of a return */
5565 return -1;
5566}
5567
5568static int iax2_queryoption(struct ast_channel *c, int option, void *data, int *datalen)
5569{
5570 switch (option) {
5573 {
5574 unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
5576 *((int *) data) = ast_test_flag64(iaxs[callno], IAX_FORCE_ENCRYPT) ? 1 : 0;
5578 return 0;
5579 }
5580 default:
5581 return -1;
5582 }
5583}
5584
5585static struct ast_frame *iax2_read(struct ast_channel *c)
5586{
5587 ast_debug(1, "I should never be called!\n");
5588 return &ast_null_frame;
5589}
5590
5591static int iax2_key_rotate(const void *vpvt)
5592{
5593 int res = 0;
5594 struct chan_iax2_pvt *pvt = (void *) vpvt;
5595 struct MD5Context md5;
5596 char key[17] = "";
5597 struct iax_ie_data ied = {
5598 .pos = 0,
5599 };
5600
5601 ast_mutex_lock(&iaxsl[pvt->callno]);
5602 pvt->keyrotateid = ast_sched_add(sched, 120000 + (ast_random() % 180001), iax2_key_rotate, vpvt);
5603
5604 snprintf(key, sizeof(key), "%lX", (unsigned long)ast_random());
5605
5606 MD5Init(&md5);
5607 MD5Update(&md5, (unsigned char *) key, strlen(key));
5608 MD5Final((unsigned char *) key, &md5);
5609
5610 IAX_DEBUGDIGEST("Sending", key);
5611
5612 iax_ie_append_raw(&ied, IAX_IE_CHALLENGE, key, 16);
5613
5614 res = send_command(pvt, AST_FRAME_IAX, IAX_COMMAND_RTKEY, 0, ied.buf, ied.pos, -1);
5615
5616 build_ecx_key((unsigned char *) key, pvt);
5617
5619
5620 return res;
5621}
5622
5623#if defined(IAX2_NATIVE_BRIDGING)
5624static int iax2_start_transfer(unsigned short callno0, unsigned short callno1, int mediaonly)
5625{
5626 int res;
5627 struct iax_ie_data ied0;
5628 struct iax_ie_data ied1;
5629 unsigned int transferid = (unsigned int)ast_random();
5630
5631 if (IAX_CALLENCRYPTED(iaxs[callno0]) || IAX_CALLENCRYPTED(iaxs[callno1])) {
5632 ast_debug(1, "transfers are not supported for encrypted calls at this time\n");
5635 return 0;
5636 }
5637
5638 memset(&ied0, 0, sizeof(ied0));
5639 iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &iaxs[callno1]->addr);
5640 iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[callno1]->peercallno);
5641 iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, transferid);
5642
5643 memset(&ied1, 0, sizeof(ied1));
5644 iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &iaxs[callno0]->addr);
5645 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[callno0]->peercallno);
5646 iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, transferid);
5647
5648 res = send_command(iaxs[callno0], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
5649 if (res)
5650 return -1;
5651 res = send_command(iaxs[callno1], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
5652 if (res)
5653 return -1;
5654 iaxs[callno0]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
5655 iaxs[callno1]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
5656 return 0;
5657}
5658#endif /* defined(IAX2_NATIVE_BRIDGING) */
5659
5660#if defined(IAX2_NATIVE_BRIDGING)
5661static void lock_both(unsigned short callno0, unsigned short callno1)
5662{
5663 ast_mutex_lock(&iaxsl[callno0]);
5664 while (ast_mutex_trylock(&iaxsl[callno1])) {
5665 DEADLOCK_AVOIDANCE(&iaxsl[callno0]);
5666 }
5667}
5668#endif /* defined(IAX2_NATIVE_BRIDGING) */
5669
5670#if defined(IAX2_NATIVE_BRIDGING)
5671static void unlock_both(unsigned short callno0, unsigned short callno1)
5672{
5673 ast_mutex_unlock(&iaxsl[callno1]);
5674 ast_mutex_unlock(&iaxsl[callno0]);
5675}
5676#endif /* defined(IAX2_NATIVE_BRIDGING) */
5677
5678#if defined(IAX2_NATIVE_BRIDGING)
5679static enum ast_bridge_result iax2_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc, int timeoutms)
5680{
5681 struct ast_channel *cs[3];
5682 struct ast_channel *who, *other;
5683 int to = -1;
5684 int res = -1;
5685 int transferstarted=0;
5686 struct ast_frame *f;
5687 unsigned short callno0 = PTR_TO_CALLNO(ast_channel_tech_pvt(c0));
5688 unsigned short callno1 = PTR_TO_CALLNO(ast_channel_tech_pvt(c1));
5689 struct timeval waittimer = {0, 0};
5690
5691 /* We currently do not support native bridging if a timeoutms value has been provided */
5692 if (timeoutms > 0) {
5693 return AST_BRIDGE_FAILED;
5694 }
5695
5696 timeoutms = -1;
5697
5698 lock_both(callno0, callno1);
5699 if (!iaxs[callno0] || !iaxs[callno1]) {
5700 unlock_both(callno0, callno1);
5701 return AST_BRIDGE_FAILED;
5702 }
5703 /* Put them in native bridge mode */
5705 iaxs[callno0]->bridgecallno = callno1;
5706 iaxs[callno1]->bridgecallno = callno0;
5707 }
5708 unlock_both(callno0, callno1);
5709
5710 /* If not, try to bridge until we can execute a transfer, if we can */
5711 cs[0] = c0;
5712 cs[1] = c1;
5713 for (/* ever */;;) {
5714 /* Check in case we got masqueraded into */
5715 if ((ast_channel_tech(c0) != &iax2_tech) || (ast_channel_tech(c1) != &iax2_tech)) {
5716 ast_verb(3, "Can't masquerade, we're different...\n");
5717 /* Remove from native mode */
5718 if (ast_channel_tech(c0) == &iax2_tech) {
5719 ast_mutex_lock(&iaxsl[callno0]);
5720 iaxs[callno0]->bridgecallno = 0;
5721 ast_mutex_unlock(&iaxsl[callno0]);
5722 }
5723 if (ast_channel_tech(c1) == &iax2_tech) {
5724 ast_mutex_lock(&iaxsl[callno1]);
5725 iaxs[callno1]->bridgecallno = 0;
5726 ast_mutex_unlock(&iaxsl[callno1]);
5727 }
5729 }
5733
5734 ast_verb(3, "Operating with different codecs [%s] [%s] , can't native bridge...\n",
5737
5738 /* Remove from native mode */
5739 lock_both(callno0, callno1);
5740 if (iaxs[callno0])
5741 iaxs[callno0]->bridgecallno = 0;
5742 if (iaxs[callno1])
5743 iaxs[callno1]->bridgecallno = 0;
5744 unlock_both(callno0, callno1);
5746 }
5747 /* check if transferred and if we really want native bridging */
5748 if (!transferstarted && !ast_test_flag64(iaxs[callno0], IAX_NOTRANSFER) && !ast_test_flag64(iaxs[callno1], IAX_NOTRANSFER)) {
5749 /* Try the transfer */
5750 if (iax2_start_transfer(callno0, callno1, (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1)) ||
5752 ast_log(LOG_WARNING, "Unable to start the transfer\n");
5753 transferstarted = 1;
5754 }
5755 if ((iaxs[callno0]->transferring == TRANSFER_RELEASED) && (iaxs[callno1]->transferring == TRANSFER_RELEASED)) {
5756 /* Call has been transferred. We're no longer involved */
5757 struct timeval now = ast_tvnow();
5758 if (ast_tvzero(waittimer)) {
5759 waittimer = now;
5760 } else if (now.tv_sec - waittimer.tv_sec > IAX_LINGER_TIMEOUT) {
5763 *fo = NULL;
5764 *rc = c0;
5765 res = AST_BRIDGE_COMPLETE;
5766 break;
5767 }
5768 }
5769 to = 1000;
5770 who = ast_waitfor_n(cs, 2, &to);
5771 /* XXX This will need to be updated to calculate
5772 * timeout correctly once timeoutms is allowed to be
5773 * > 0. Right now, this can go badly if the waitfor
5774 * times out in less than a millisecond
5775 */
5776 if (timeoutms > -1) {
5777 timeoutms -= (1000 - to);
5778 if (timeoutms < 0)
5779 timeoutms = 0;
5780 }
5781 if (!who) {
5782 if (!timeoutms) {
5783 res = AST_BRIDGE_RETRY;
5784 break;
5785 }
5786 if (ast_check_hangup(c0) || ast_check_hangup(c1)) {
5787 res = AST_BRIDGE_FAILED;
5788 break;
5789 }
5790 continue;
5791 }
5792 f = ast_read(who);
5793 if (!f) {
5794 *fo = NULL;
5795 *rc = who;
5796 res = AST_BRIDGE_COMPLETE;
5797 break;
5798 }
5799 other = (who == c0) ? c1 : c0; /* the 'other' channel */
5800 if (f->frametype == AST_FRAME_CONTROL) {
5801 switch (f->subclass.integer) {
5806 ast_write(other, f);
5807 break;
5810 break;
5811 default:
5812 *fo = f;
5813 *rc = who;
5814 res = AST_BRIDGE_COMPLETE;
5815 break;
5816 }
5817 if (res == AST_BRIDGE_COMPLETE) {
5818 break;
5819 }
5820 } else if (f->frametype == AST_FRAME_VOICE
5821 || f->frametype == AST_FRAME_TEXT
5822 || f->frametype == AST_FRAME_VIDEO
5823 || f->frametype == AST_FRAME_IMAGE) {
5824 ast_write(other, f);
5825 } else if (f->frametype == AST_FRAME_DTMF) {
5826 /* monitored dtmf take out of the bridge.
5827 * check if we monitor the specific source.
5828 */
5829 int monitored_source = (who == c0) ? AST_BRIDGE_DTMF_CHANNEL_0 : AST_BRIDGE_DTMF_CHANNEL_1;
5830
5831 if (flags & monitored_source) {
5832 *rc = who;
5833 *fo = f;
5834 res = AST_BRIDGE_COMPLETE;
5835 /* Remove from native mode */
5836 break;
5837 }
5838 ast_write(other, f);
5839 }
5840 ast_frfree(f);
5841 /* Swap who gets priority */
5842 cs[2] = cs[0];
5843 cs[0] = cs[1];
5844 cs[1] = cs[2];
5845 }
5846 lock_both(callno0, callno1);
5847 if(iaxs[callno0])
5848 iaxs[callno0]->bridgecallno = 0;
5849 if(iaxs[callno1])
5850 iaxs[callno1]->bridgecallno = 0;
5851 unlock_both(callno0, callno1);
5852 return res;
5853}
5854#endif /* defined(IAX2_NATIVE_BRIDGING) */
5855
5856static int iax2_answer(struct ast_channel *c)
5857{
5858 unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
5859 ast_debug(1, "Answering IAX2 call\n");
5861}
5862
5863static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen)
5864{
5865 unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
5866 struct chan_iax2_pvt *pvt;
5867 int res = 0;
5868
5869 if (iaxdebug)
5870 ast_debug(1, "Indicating condition %d\n", condition);
5871
5873 pvt = iaxs[callno];
5874
5875 if (wait_for_peercallno(pvt)) {
5876 res = -1;
5877 goto done;
5878 }
5879
5880 switch (condition) {
5881 case AST_CONTROL_HOLD:
5882 if (strcasecmp(pvt->mohinterpret, "passthrough")) {
5883 ast_moh_start(c, data, pvt->mohinterpret);
5884 goto done;
5885 }
5886 break;
5887 case AST_CONTROL_UNHOLD:
5888 if (strcasecmp(pvt->mohinterpret, "passthrough")) {
5889 ast_moh_stop(c);
5890 goto done;
5891 }
5892 break;
5896 /* We are not configured to allow sending these updates. */
5897 ast_debug(2, "Callno %d: Config blocked sending control frame %d.\n",
5898 callno, condition);
5899 goto done;
5900 }
5901 break;
5904 res = -1;
5905 goto done;
5906 }
5907
5908 res = send_command(pvt, AST_FRAME_CONTROL, condition, 0, data, datalen, -1);
5909
5910done:
5912
5913 return res;
5914}
5915
5916static int iax2_transfer(struct ast_channel *c, const char *dest)
5917{
5918 unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
5919 struct iax_ie_data ied = { "", };
5920 char tmp[256], *context;
5922 ast_copy_string(tmp, dest, sizeof(tmp));
5923 context = strchr(tmp, '@');
5924 if (context) {
5925 *context = '\0';
5926 context++;
5927 }
5929 if (context)
5931 ast_debug(1, "Transferring '%s' to '%s'\n", ast_channel_name(c), dest);
5933 return send_command_locked(callno, AST_FRAME_IAX, IAX_COMMAND_TRANSFER, 0, ied.buf, ied.pos, -1);
5934}
5935
5936static int iax2_getpeertrunk(struct ast_sockaddr addr)
5937{
5938 struct iax2_peer *peer;
5939 int res = 0;
5940 struct ao2_iterator i;
5941
5942 i = ao2_iterator_init(peers, 0);
5943 while ((peer = ao2_iterator_next(&i))) {
5944
5945 if (!ast_sockaddr_cmp(&peer->addr, &addr)) {
5946 res = ast_test_flag64(peer, IAX_TRUNK);
5947 peer_unref(peer);
5948 break;
5949 }
5950 peer_unref(peer);
5951 }
5953
5954 return res;
5955}
5956
5957/*! \brief Create new call, interface with the PBX core */
5958static struct ast_channel *ast_iax2_new(int callno, int state, iax2_format capability,
5959 struct iax2_codec_pref *prefs, const struct ast_assigned_ids *assignedids,
5960 const struct ast_channel *requestor, unsigned int cachable)
5961{
5962 struct ast_channel *tmp = NULL;
5963 struct chan_iax2_pvt *i;
5964 struct iax2_peer *peer;
5965 struct ast_variable *v = NULL;
5966 struct ast_format_cap *native;
5967 struct ast_format *tmpfmt;
5968 ast_callid callid;
5969 char *peer_name = NULL;
5970
5971 if (!(i = iaxs[callno])) {
5972 ast_log(LOG_WARNING, "No IAX2 pvt found for callno '%d' !\n", callno);
5973 return NULL;
5974 }
5975
5976 if (!capability) {
5977 ast_log(LOG_WARNING, "No formats specified for call to: IAX2/%s-%d\n",
5978 i->host, i->callno);
5979 return NULL;
5980 }
5982 if (!native) {
5983 return NULL;
5984 }
5985 if (iax2_codec_pref_best_bitfield2cap(capability, prefs, native)
5986 || !ast_format_cap_count(native)) {
5987 ast_log(LOG_WARNING, "No requested formats available for call to: IAX2/%s-%d\n",
5988 i->host, i->callno);
5989 ao2_ref(native, -1);
5990 return NULL;
5991 }
5992
5993 if (!ast_strlen_zero(i->peer)) {
5994 peer_name = ast_strdupa(i->peer);
5995 } else if (!ast_strlen_zero(i->host)) {
5996 peer_name = ast_strdupa(i->host);
5997 }
5998
5999 /* Don't hold call lock while making a channel or looking up a peer */
6000 ast_mutex_unlock(&iaxsl[callno]);
6001
6002 if (!ast_strlen_zero(peer_name)) {
6003 peer = find_peer(peer_name, 1);
6004 if (peer && peer->endpoint) {
6006 i->accountcode, i->exten, i->context, assignedids, requestor,
6007 i->amaflags, peer->endpoint, "IAX2/%s-%d", i->host, i->callno);
6008 }
6009 ao2_cleanup(peer);
6010 }
6011
6012 if (!tmp) {
6013 tmp = ast_channel_alloc(1, state, i->cid_num, i->cid_name, i->accountcode,
6014 i->exten, i->context, assignedids, requestor, i->amaflags, "IAX2/%s-%d",
6015 i->host, i->callno);
6016 }
6017
6018 ast_mutex_lock(&iaxsl[callno]);
6019 if (i != iaxs[callno]) {
6020 if (tmp) {
6021 /* unlock and relock iaxsl[callno] to preserve locking order */
6022 ast_mutex_unlock(&iaxsl[callno]);
6023 ast_channel_unlock(tmp);
6024 tmp = ast_channel_release(tmp);
6025 ast_mutex_lock(&iaxsl[callno]);
6026 }
6027 ao2_ref(native, -1);
6028 return NULL;
6029 }
6030 if (!tmp) {
6031 ao2_ref(native, -1);
6032 return NULL;
6033 }
6034
6036
6037 if ((callid = iaxs[callno]->callid)) {
6038 ast_channel_callid_set(tmp, callid);
6039 }
6040
6042
6043 /* We can support any format by default, until we get restricted */
6044 ast_channel_nativeformats_set(tmp, native);
6045 tmpfmt = ast_format_cap_get_format(native, 0);
6046
6047 ast_channel_set_readformat(tmp, tmpfmt);
6048 ast_channel_set_rawreadformat(tmp, tmpfmt);
6049 ast_channel_set_writeformat(tmp, tmpfmt);
6050 ast_channel_set_rawwriteformat(tmp, tmpfmt);
6051
6052 ao2_ref(tmpfmt, -1);
6053 ao2_ref(native, -1);
6054
6056
6057 if (!ast_strlen_zero(i->parkinglot))
6058 ast_channel_parkinglot_set(tmp, i->parkinglot);
6059 /* Don't use ast_set_callerid() here because it will
6060 * generate a NewCallerID event before the NewChannel event */
6061 if (!ast_strlen_zero(i->ani)) {
6064 } else if (!ast_strlen_zero(i->cid_num)) {
6067 }
6069 if (!ast_strlen_zero(i->rdnis)) {
6072 }
6078 if (!ast_strlen_zero(i->language))
6079 ast_channel_language_set(tmp, i->language);
6081 ast_channel_accountcode_set(tmp, i->accountcode);
6082 if (i->amaflags)
6086 if (i->adsi)
6088 else
6090 i->owner = tmp;
6091 i->capability = capability;
6092
6093 if (!cachable) {
6095 }
6096
6097 /* Set inherited variables */
6098 if (i->vars) {
6099 for (v = i->vars ; v ; v = v->next)
6101 }
6102 if (i->iaxvars) {
6103 struct ast_datastore *variablestore;
6104 struct ast_variable *var, *prev = NULL;
6105 AST_LIST_HEAD(, ast_var_t) *varlist;
6106 ast_debug(1, "Loading up the channel with IAXVARs\n");
6107 varlist = ast_calloc(1, sizeof(*varlist));
6109 if (variablestore && varlist) {
6110 variablestore->data = varlist;
6111 variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
6112 AST_LIST_HEAD_INIT(varlist);
6113 for (var = i->iaxvars; var; var = var->next) {
6114 struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
6115 if (prev)
6116 ast_free(prev);
6117 prev = var;
6118 if (!newvar) {
6119 /* Don't abort list traversal, as this would leave i->iaxvars in an inconsistent state. */
6120 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
6121 } else {
6122 AST_LIST_INSERT_TAIL(varlist, newvar, entries);
6123 }
6124 }
6125 if (prev)
6126 ast_free(prev);
6127 i->iaxvars = NULL;
6128 ast_channel_datastore_add(i->owner, variablestore);
6129 } else {
6130 if (variablestore) {
6131 ast_datastore_free(variablestore);
6132 }
6133 if (varlist) {
6134 ast_free(varlist);
6135 }
6136 }
6137 }
6138
6140 ast_channel_unlock(tmp);
6141
6142 if (state != AST_STATE_DOWN) {
6143 if (ast_pbx_start(tmp)) {
6144 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", ast_channel_name(tmp));
6145 /* unlock and relock iaxsl[callno] to preserve locking order */
6146 ast_mutex_unlock(&iaxsl[callno]);
6147 ast_hangup(tmp);
6148 ast_mutex_lock(&iaxsl[callno]);
6149 return NULL;
6150 }
6151 }
6152
6154 return tmp;
6155}
6156
6157static unsigned int calc_txpeerstamp(struct iax2_trunk_peer *tpeer, int sampms, struct timeval *now)
6158{
6159 unsigned long int mssincetx; /* unsigned to handle overflows */
6160 long int ms, pred;
6161
6162 tpeer->trunkact = *now;
6163 mssincetx = ast_tvdiff_ms(*now, tpeer->lasttxtime);
6164 if (mssincetx > 5000 || ast_tvzero(tpeer->txtrunktime)) {
6165 /* If it's been at least 5 seconds since the last time we transmitted on this trunk, reset our timers */
6166 tpeer->txtrunktime = *now;
6167 tpeer->lastsent = 999999;
6168 }
6169 /* Update last transmit time now */
6170 tpeer->lasttxtime = *now;
6171
6172 /* Calculate ms offset */
6173 ms = ast_tvdiff_ms(*now, tpeer->txtrunktime);
6174 /* Predict from last value */
6175 pred = tpeer->lastsent + sampms;
6176 if (labs(ms - pred) < MAX_TIMESTAMP_SKEW)
6177 ms = pred;
6178
6179 /* We never send the same timestamp twice, so fudge a little if we must */
6180 if (ms == tpeer->lastsent)
6181 ms = tpeer->lastsent + 1;
6182 tpeer->lastsent = ms;
6183 return ms;
6184}
6185
6186static unsigned int fix_peerts(struct timeval *rxtrunktime, int callno, unsigned int ts)
6187{
6188 long ms; /* NOT unsigned */
6189 if (ast_tvzero(iaxs[callno]->rxcore)) {
6190 /* Initialize rxcore time if appropriate */
6191 iaxs[callno]->rxcore = ast_tvnow();
6192 /* Round to nearest 20ms so traces look pretty */
6193 iaxs[callno]->rxcore.tv_usec -= iaxs[callno]->rxcore.tv_usec % 20000;
6194 }
6195 /* Calculate difference between trunk and channel */
6196 ms = ast_tvdiff_ms(*rxtrunktime, iaxs[callno]->rxcore);
6197 /* Return as the sum of trunk time and the difference between trunk and real time */
6198 return ms + ts;
6199}
6200
6201static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts, struct ast_frame *f)
6202{
6203 int ms;
6204 int voice = 0;
6205 int genuine = 0;
6206 int adjust;
6207 int rate = 0;
6208 struct timeval *delivery = NULL;
6209
6210
6211 /* What sort of frame do we have?: voice is self-explanatory
6212 "genuine" means an IAX frame - things like LAGRQ/RP, PING/PONG, ACK
6213 non-genuine frames are CONTROL frames [ringing etc], DTMF
6214 The "genuine" distinction is needed because genuine frames must get a clock-based timestamp,
6215 the others need a timestamp slaved to the voice frames so that they go in sequence
6216 */
6217 if (f->frametype == AST_FRAME_VOICE) {
6218 voice = 1;
6219 rate = ast_format_get_sample_rate(f->subclass.format) / 1000;
6220 delivery = &f->delivery;
6221 } else if (f->frametype == AST_FRAME_IAX) {
6222 genuine = 1;
6223 } else if (f->frametype == AST_FRAME_CNG) {
6224 p->notsilenttx = 0;
6225 }
6226
6227 if (ast_tvzero(p->offset)) {
6228 p->offset = ast_tvnow();
6229 /* Round to nearest 20ms for nice looking traces */
6230 p->offset.tv_usec -= p->offset.tv_usec % 20000;
6231 }
6232 /* If the timestamp is specified, just send it as is */
6233 if (ts)
6234 return ts;
6235 /* If we have a time that the frame arrived, always use it to make our timestamp */
6236 if (delivery && !ast_tvzero(*delivery)) {
6237 ms = ast_tvdiff_ms(*delivery, p->offset);
6238 if (ms < 0) {
6239 ms = 0;
6240 }
6241 if (iaxdebug)
6242 ast_debug(3, "calc_timestamp: call %d/%d: Timestamp slaved to delivery time\n", p->callno, iaxs[p->callno]->peercallno);
6243 } else {
6244 ms = ast_tvdiff_ms(ast_tvnow(), p->offset);
6245 if (ms < 0)
6246 ms = 0;
6247 if (voice) {
6248 /* On a voice frame, use predicted values if appropriate */
6249 adjust = (ms - p->nextpred);
6250 if (p->notsilenttx && abs(adjust) <= MAX_TIMESTAMP_SKEW) {
6251 /* Adjust our txcore, keeping voice and non-voice synchronized */
6252 /* AN EXPLANATION:
6253 When we send voice, we usually send "calculated" timestamps worked out
6254 on the basis of the number of samples sent. When we send other frames,
6255 we usually send timestamps worked out from the real clock.
6256 The problem is that they can tend to drift out of step because the
6257 source channel's clock and our clock may not be exactly at the same rate.
6258 We fix this by continuously "tweaking" p->offset. p->offset is "time zero"
6259 for this call. Moving it adjusts timestamps for non-voice frames.
6260 We make the adjustment in the style of a moving average. Each time we
6261 adjust p->offset by 10% of the difference between our clock-derived
6262 timestamp and the predicted timestamp. That's why you see "10000"
6263 below even though IAX2 timestamps are in milliseconds.
6264 The use of a moving average avoids offset moving too radically.
6265 Generally, "adjust" roams back and forth around 0, with offset hardly
6266 changing at all. But if a consistent different starts to develop it
6267 will be eliminated over the course of 10 frames (200-300msecs)
6268 */
6269 if (adjust < 0)
6270 p->offset = ast_tvsub(p->offset, ast_samp2tv(abs(adjust), 10000));
6271 else if (adjust > 0)
6272 p->offset = ast_tvadd(p->offset, ast_samp2tv(adjust, 10000));
6273
6274 if (!p->nextpred) {
6275 p->nextpred = ms; /*f->samples / rate;*/
6276 if (p->nextpred <= p->lastsent)
6277 p->nextpred = p->lastsent + 3;
6278 }
6279 ms = p->nextpred;
6280 } else {
6281 /* in this case, just use the actual
6282 * time, since we're either way off
6283 * (shouldn't happen), or we're ending a
6284 * silent period -- and seed the next
6285 * predicted time. Also, round ms to the
6286 * next multiple of frame size (so our
6287 * silent periods are multiples of
6288 * frame size too) */
6289
6290 if (iaxdebug && abs(adjust) > MAX_TIMESTAMP_SKEW )
6291 ast_debug(1, "predicted timestamp skew (%d) > max (%d), using real ts instead.\n",
6292 abs(adjust), MAX_TIMESTAMP_SKEW);
6293
6294 if (f->samples >= rate) /* check to make sure we don't core dump */
6295 {
6296 int diff = ms % (f->samples / rate);
6297 if (diff)
6298 ms += f->samples/rate - diff;
6299 }
6300
6301 p->nextpred = ms;
6302 p->notsilenttx = 1;
6303 }
6304 } else if ( f->frametype == AST_FRAME_VIDEO ) {
6305 /*
6306 * IAX2 draft 03 says that timestamps MUST be in order.
6307 * It does not say anything about several frames having the same timestamp
6308 * When transporting video, we can have a frame that spans multiple iax packets
6309 * (so called slices), so it would make sense to use the same timestamp for all of
6310 * them
6311 * We do want to make sure that frames don't go backwards though
6312 */
6313 if ( (unsigned int)ms < p->lastsent )
6314 ms = p->lastsent;
6315 } else {
6316 /* On a dataframe, use last value + 3 (to accommodate jitter buffer shrinking) if appropriate unless
6317 it's a genuine frame */
6318 adjust = (ms - p->lastsent);
6319 if (genuine) {
6320 /* genuine (IAX LAGRQ etc) must keep their clock-based stamps */
6321 if (ms <= p->lastsent)
6322 ms = p->lastsent + 3;
6323 } else if (abs(adjust) <= MAX_TIMESTAMP_SKEW) {
6324 /* non-genuine frames (!?) (DTMF, CONTROL) should be pulled into the predicted stream stamps */
6325 ms = p->lastsent + 3;
6326 }
6327 }
6328 }
6329 p->lastsent = ms;
6330 if (voice) {
6331 p->nextpred = p->nextpred + f->samples / rate;
6332 }
6333 return ms;
6334}
6335
6336static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset)
6337{
6338 /* Returns where in "receive time" we are. That is, how many ms
6339 since we received (or would have received) the frame with timestamp 0 */
6340 int ms;
6341#ifdef IAXTESTS
6342 int jit;
6343#endif /* IAXTESTS */
6344 /* Setup rxcore if necessary */
6345 if (ast_tvzero(p->rxcore)) {
6346 p->rxcore = ast_tvnow();
6347 if (iaxdebug)
6348 ast_debug(1, "calc_rxstamp: call=%d: rxcore set to %d.%6.6d - %ums\n",
6349 p->callno, (int)(p->rxcore.tv_sec), (int)(p->rxcore.tv_usec), offset);
6350 p->rxcore = ast_tvsub(p->rxcore, ast_samp2tv(offset, 1000));
6351#if 1
6352 if (iaxdebug)
6353 ast_debug(1, "calc_rxstamp: call=%d: works out as %d.%6.6d\n",
6354 p->callno, (int)(p->rxcore.tv_sec),(int)( p->rxcore.tv_usec));
6355#endif
6356 }
6357
6358 ms = ast_tvdiff_ms(ast_tvnow(), p->rxcore);
6359#ifdef IAXTESTS
6360 if (test_jit) {
6361 if (!test_jitpct || ((100.0 * ast_random() / (RAND_MAX + 1.0)) < test_jitpct)) {
6362 jit = (int)((float)test_jit * ast_random() / (RAND_MAX + 1.0));
6363 if ((int)(2.0 * ast_random() / (RAND_MAX + 1.0)))
6364 jit = -jit;
6365 ms += jit;
6366 }
6367 }
6368 if (test_late) {
6369 ms += test_late;
6370 test_late = 0;
6371 }
6372#endif /* IAXTESTS */
6373 return ms;
6374}
6375
6376static struct iax2_trunk_peer *find_tpeer(struct ast_sockaddr *addr, int fd)
6377{
6378 struct iax2_trunk_peer *tpeer = NULL;
6379
6380 /* Finds and locks trunk peer */
6382
6383 AST_LIST_TRAVERSE(&tpeers, tpeer, list) {
6384 if (!ast_sockaddr_cmp(&tpeer->addr, addr)) {
6385 ast_mutex_lock(&tpeer->lock);
6386 break;
6387 }
6388 }
6389
6390 if (!tpeer) {
6391 if ((tpeer = ast_calloc(1, sizeof(*tpeer)))) {
6392 ast_mutex_init(&tpeer->lock);
6393 tpeer->lastsent = 9999;
6394 ast_sockaddr_copy(&tpeer->addr, addr);
6395 tpeer->trunkact = ast_tvnow();
6396 ast_mutex_lock(&tpeer->lock);
6397 tpeer->sockfd = fd;
6398
6399#ifdef SO_NO_CHECK
6400 setsockopt(tpeer->sockfd, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
6401#endif
6402 ast_debug(1, "Created trunk peer for '%s'\n", ast_sockaddr_stringify(&tpeer->addr));
6404 }
6405 }
6406
6408
6409 return tpeer;
6410}
6411
6412static int iax2_trunk_queue(struct chan_iax2_pvt *pvt, struct iax_frame *fr)
6413{
6414 struct ast_frame *f;
6415 struct iax2_trunk_peer *tpeer;
6416 void *tmp, *ptr;
6417 struct timeval now;
6418 struct ast_iax2_meta_trunk_entry *met;
6419 struct ast_iax2_meta_trunk_mini *mtm;
6420
6421 f = &fr->af;
6422 tpeer = find_tpeer(&pvt->addr, pvt->sockfd);
6423 if (tpeer) {
6424
6425 if (tpeer->trunkdatalen + f->datalen + 4 >= tpeer->trunkdataalloc) {
6426 /* Need to reallocate space */
6427 if (tpeer->trunkdataalloc < trunkmaxsize) {
6428 if (!(tmp = ast_realloc(tpeer->trunkdata, tpeer->trunkdataalloc + DEFAULT_TRUNKDATA + IAX2_TRUNK_PREFACE))) {
6429 ast_mutex_unlock(&tpeer->lock);
6430 return -1;
6431 }
6432
6434 tpeer->trunkdata = tmp;
6435 ast_debug(1, "Expanded trunk '%s' to %u bytes\n", ast_sockaddr_stringify(&tpeer->addr), tpeer->trunkdataalloc);
6436 } else {
6437 ast_log(LOG_WARNING, "Maximum trunk data space exceeded to %s\n", ast_sockaddr_stringify(&tpeer->addr));
6438 ast_mutex_unlock(&tpeer->lock);
6439 return -1;
6440 }
6441 }
6442
6443 /* Append to meta frame */
6444 ptr = tpeer->trunkdata + IAX2_TRUNK_PREFACE + tpeer->trunkdatalen;
6446 mtm = (struct ast_iax2_meta_trunk_mini *)ptr;
6447 mtm->len = htons(f->datalen);
6448 mtm->mini.callno = htons(pvt->callno);
6449 mtm->mini.ts = htons(0xffff & fr->ts);
6450 ptr += sizeof(struct ast_iax2_meta_trunk_mini);
6451 tpeer->trunkdatalen += sizeof(struct ast_iax2_meta_trunk_mini);
6452 } else {
6453 met = (struct ast_iax2_meta_trunk_entry *)ptr;
6454 /* Store call number and length in meta header */
6455 met->callno = htons(pvt->callno);
6456 met->len = htons(f->datalen);
6457 /* Advance pointers/decrease length past trunk entry header */
6458 ptr += sizeof(struct ast_iax2_meta_trunk_entry);
6459 tpeer->trunkdatalen += sizeof(struct ast_iax2_meta_trunk_entry);
6460 }
6461 /* Copy actual trunk data */
6462 memcpy(ptr, f->data.ptr, f->datalen);
6463 tpeer->trunkdatalen += f->datalen;
6464
6465 tpeer->calls++;
6466
6467 /* track the largest mtu we actually have sent */
6468 if (tpeer->trunkdatalen + f->datalen + 4 > trunk_maxmtu)
6469 trunk_maxmtu = tpeer->trunkdatalen + f->datalen + 4 ;
6470
6471 /* if we have enough for a full MTU, ship it now without waiting */
6472 if (global_max_trunk_mtu > 0 && tpeer->trunkdatalen + f->datalen + 4 >= global_max_trunk_mtu) {
6473 now = ast_tvnow();
6474 send_trunk(tpeer, &now);
6475 trunk_untimed ++;
6476 }
6477
6478 ast_mutex_unlock(&tpeer->lock);
6479 }
6480 return 0;
6481}
6482
6483/* IAX2 encryption requires 16 to 32 bytes of random padding to be present
6484 * before the encryption data. This function randomizes that data. */
6485static void build_rand_pad(unsigned char *buf, ssize_t len)
6486{
6487 long tmp;
6488 for (tmp = ast_random(); len > 0; tmp = ast_random()) {
6489 memcpy(buf, (unsigned char *) &tmp, (len > sizeof(tmp)) ? sizeof(tmp) : len);
6490 buf += sizeof(tmp);
6491 len -= sizeof(tmp);
6492 }
6493}
6494
6495static int invalid_key(ast_aes_decrypt_key *ecx)
6496{
6497#ifdef HAVE_OPENSSL
6498 int i;
6499 for (i = 0; i < 60; i++) {
6500 if (ecx->raw[i]) {
6501 return 0; /* stop if we encounter anything non-zero */
6502 }
6503 }
6504 /* if ast_aes_encrypt or ast_aes_decrypt is called, then we'll crash when calling AES_encrypt or AES_decrypt */
6505 return -1;
6506#else
6507 return 0; /* Can't verify, but doesn't matter anyways */
6508#endif
6509}
6510
6511static void build_encryption_keys(const unsigned char *digest, struct chan_iax2_pvt *pvt)
6512{
6513 build_ecx_key(digest, pvt);
6514 ast_aes_set_decrypt_key(digest, &pvt->dcx);
6515}
6516
6517static void build_ecx_key(const unsigned char *digest, struct chan_iax2_pvt *pvt)
6518{
6519 /* it is required to hold the corresponding decrypt key to our encrypt key
6520 * in the pvt struct because queued frames occasionally need to be decrypted and
6521 * re-encrypted when updated for a retransmission */
6522 build_rand_pad(pvt->semirand, sizeof(pvt->semirand));
6523 ast_aes_set_encrypt_key(digest, &pvt->ecx);
6524 ast_aes_set_decrypt_key(digest, &pvt->mydcx);
6525}
6526
6527static void memcpy_decrypt(unsigned char *dst, const unsigned char *src, int len, ast_aes_decrypt_key *dcx)
6528{
6529#if 0
6530 /* Debug with "fake encryption" */
6531 int x;
6532 if (len % 16)
6533 ast_log(LOG_WARNING, "len should be multiple of 16, not %d!\n", len);
6534 for (x=0;x<len;x++)
6535 dst[x] = src[x] ^ 0xff;
6536#else
6537 unsigned char lastblock[16] = { 0 };
6538 int x;
6539 while(len > 0) {
6540 ast_aes_decrypt(src, dst, dcx);
6541 for (x=0;x<16;x++)
6542 dst[x] ^= lastblock[x];
6543 memcpy(lastblock, src, sizeof(lastblock));
6544 dst += 16;
6545 src += 16;
6546 len -= 16;
6547 }
6548#endif
6549}
6550
6551static void memcpy_encrypt(unsigned char *dst, const unsigned char *src, int len, ast_aes_encrypt_key *ecx)
6552{
6553#if 0
6554 /* Debug with "fake encryption" */
6555 int x;
6556 if (len % 16)
6557 ast_log(LOG_WARNING, "len should be multiple of 16, not %d!\n", len);
6558 for (x=0;x<len;x++)
6559 dst[x] = src[x] ^ 0xff;
6560#else
6561 unsigned char curblock[16] = { 0 };
6562 int x;
6563 while(len > 0) {
6564 for (x=0;x<16;x++)
6565 curblock[x] ^= src[x];
6566 ast_aes_encrypt(curblock, dst, ecx);
6567 memcpy(curblock, dst, sizeof(curblock));
6568 dst += 16;
6569 src += 16;
6570 len -= 16;
6571 }
6572#endif
6573}
6574
6575static int decode_frame(ast_aes_decrypt_key *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen)
6576{
6577 int padding;
6578 unsigned char *workspace;
6579
6580 workspace = ast_alloca(*datalen);
6581 memset(f, 0, sizeof(*f));
6582 if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
6583 struct ast_iax2_full_enc_hdr *efh = (struct ast_iax2_full_enc_hdr *)fh;
6584 if (*datalen < 16 + sizeof(struct ast_iax2_full_hdr))
6585 return -1;
6586 /* Decrypt */
6587 memcpy_decrypt(workspace, efh->encdata, *datalen - sizeof(struct ast_iax2_full_enc_hdr), dcx);
6588
6589 padding = 16 + (workspace[15] & 0x0f);
6590 if (iaxdebug)
6591 ast_debug(1, "Decoding full frame with length %d (padding = %d) (15=%02hhx)\n", *datalen, padding, workspace[15]);
6592 if (*datalen < padding + sizeof(struct ast_iax2_full_hdr))
6593 return -1;
6594
6595 *datalen -= padding;
6596 memcpy(efh->encdata, workspace + padding, *datalen - sizeof(struct ast_iax2_full_enc_hdr));
6597 f->frametype = fh->type;
6598 if (f->frametype == AST_FRAME_VIDEO) {
6600 if (!f->subclass.format) {
6602 }
6603 } else if (f->frametype == AST_FRAME_VOICE) {
6605 if (!f->subclass.format) {
6607 }
6608 } else {
6610 }
6611 } else {
6612 struct ast_iax2_mini_enc_hdr *efh = (struct ast_iax2_mini_enc_hdr *)fh;
6613 if (iaxdebug)
6614 ast_debug(5, "Decoding mini with length %d\n", *datalen);
6615 if (*datalen < 16 + sizeof(struct ast_iax2_mini_hdr))
6616 return -1;
6617 /* Decrypt */
6618 memcpy_decrypt(workspace, efh->encdata, *datalen - sizeof(struct ast_iax2_mini_enc_hdr), dcx);
6619 padding = 16 + (workspace[15] & 0x0f);
6620 if (*datalen < padding + sizeof(struct ast_iax2_mini_hdr))
6621 return -1;
6622 *datalen -= padding;
6623 memcpy(efh->encdata, workspace + padding, *datalen - sizeof(struct ast_iax2_mini_enc_hdr));
6624 }
6625 return 0;
6626}
6627
6628static int encrypt_frame(ast_aes_encrypt_key *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen)
6629{
6630 int padding;
6631 unsigned char *workspace;
6632 workspace = ast_alloca(*datalen + 32);
6633 if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
6634 struct ast_iax2_full_enc_hdr *efh = (struct ast_iax2_full_enc_hdr *)fh;
6635 if (iaxdebug)
6636 ast_debug(1, "Encoding full frame %d/%d with length %d\n", fh->type, fh->csub, *datalen);
6637 padding = 16 - ((*datalen - sizeof(struct ast_iax2_full_enc_hdr)) % 16);
6638 padding = 16 + (padding & 0xf);
6639 memcpy(workspace, poo, padding);
6640 memcpy(workspace + padding, efh->encdata, *datalen - sizeof(struct ast_iax2_full_enc_hdr));
6641 workspace[15] &= 0xf0;
6642 workspace[15] |= (padding & 0xf);
6643 if (iaxdebug)
6644 ast_debug(1, "Encoding full frame %d/%d with length %d + %d padding (15=%02hhx)\n", fh->type, fh->csub, *datalen, padding, workspace[15]);
6645 *datalen += padding;
6646 memcpy_encrypt(efh->encdata, workspace, *datalen - sizeof(struct ast_iax2_full_enc_hdr), ecx);
6647 if (*datalen >= 32 + sizeof(struct ast_iax2_full_enc_hdr))
6648 memcpy(poo, workspace + *datalen - 32, 32);
6649 } else {
6650 struct ast_iax2_mini_enc_hdr *efh = (struct ast_iax2_mini_enc_hdr *)fh;
6651 if (iaxdebug)
6652 ast_debug(5, "Encoding mini frame with length %d\n", *datalen);
6653 padding = 16 - ((*datalen - sizeof(struct ast_iax2_mini_enc_hdr)) % 16);
6654 padding = 16 + (padding & 0xf);
6655 memcpy(workspace, poo, padding);
6656 memcpy(workspace + padding, efh->encdata, *datalen - sizeof(struct ast_iax2_mini_enc_hdr));
6657 workspace[15] &= 0xf0;
6658 workspace[15] |= (padding & 0x0f);
6659 *datalen += padding;
6660 memcpy_encrypt(efh->encdata, workspace, *datalen - sizeof(struct ast_iax2_mini_enc_hdr), ecx);
6661 if (*datalen >= 32 + sizeof(struct ast_iax2_mini_enc_hdr))
6662 memcpy(poo, workspace + *datalen - 32, 32);
6663 }
6664 return 0;
6665}
6666
6667static int decrypt_frame(int callno, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen)
6668{
6669 int res=-1;
6671 /* Search for possible keys, given secrets */
6672 struct MD5Context md5;
6673 unsigned char digest[16];
6674 char *tmppw, *stringp;
6675
6676 tmppw = ast_strdupa(iaxs[callno]->secret);
6677 stringp = tmppw;
6678 while ((tmppw = strsep(&stringp, ";"))) {
6679 MD5Init(&md5);
6680 MD5Update(&md5, (unsigned char *)iaxs[callno]->challenge, strlen(iaxs[callno]->challenge));
6681 MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
6682 MD5Final(digest, &md5);
6683 build_encryption_keys(digest, iaxs[callno]);
6684 res = decode_frame(&iaxs[callno]->dcx, fh, f, datalen);
6685 if (!res) {
6687 break;
6688 }
6689 }
6690 } else
6691 res = decode_frame(&iaxs[callno]->dcx, fh, f, datalen);
6692 return res;
6693}
6694
6695static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final)
6696{
6697 /* Queue a packet for delivery on a given private structure. Use "ts" for
6698 timestamp, or calculate if ts is 0. Send immediately without retransmission
6699 or delayed, with retransmission */
6700 struct ast_iax2_full_hdr *fh;
6701 struct ast_iax2_mini_hdr *mh;
6702 struct ast_iax2_video_hdr *vh;
6703 struct {
6704 struct iax_frame fr2;
6705 unsigned char buffer[4096];
6706 } frb;
6707 struct iax_frame *fr;
6708 int res;
6709 int sendmini=0;
6710 unsigned int lastsent;
6711 unsigned int fts;
6712
6713 frb.fr2.afdatalen = sizeof(frb.buffer);
6714
6715 if (!pvt) {
6716 ast_log(LOG_WARNING, "No private structure for packet?\n");
6717 return -1;
6718 }
6719
6720 lastsent = pvt->lastsent;
6721
6722 /* Calculate actual timestamp */
6723 fts = calc_timestamp(pvt, ts, f);
6724
6725 /* Bail here if this is an "interp" frame; we don't want or need to send these placeholders out
6726 * (the endpoint should detect the lost packet itself). But, we want to do this here, so that we
6727 * increment the "predicted timestamps" for voice, if we're predicting */
6728 if(f->frametype == AST_FRAME_VOICE && f->datalen == 0)
6729 return 0;
6730#if 0
6732 "f->frametype %c= AST_FRAME_VOICE, %sencrypted, %srotation scheduled...\n",
6733 *("=!" + (f->frametype == AST_FRAME_VOICE)),
6734 IAX_CALLENCRYPTED(pvt) ? "" : "not ",
6735 pvt->keyrotateid != -1 ? "" : "no "
6736 );
6737#endif
6738 if (pvt->keyrotateid == -1 && f->frametype == AST_FRAME_VOICE && IAX_CALLENCRYPTED(pvt)) {
6739 iax2_key_rotate(pvt);
6740 }
6741
6742 if ((ast_test_flag64(pvt, IAX_TRUNK) ||
6743 (((fts & 0xFFFF0000L) == (lastsent & 0xFFFF0000L)) ||
6744 ((fts & 0xFFFF0000L) == ((lastsent + 0x10000) & 0xFFFF0000L))))
6745 /* High two bytes are the same on timestamp, or sending on a trunk */ &&
6747 /* is a voice frame */ &&
6750 /* is the same type */ ) {
6751 /* Force immediate rather than delayed transmission */
6752 now = 1;
6753 /* Mark that mini-style frame is appropriate */
6754 sendmini = 1;
6755 }
6756 if ( f->frametype == AST_FRAME_VIDEO ) {
6757 /*
6758 * If the lower 15 bits of the timestamp roll over, or if
6759 * the video format changed then send a full frame.
6760 * Otherwise send a mini video frame
6761 */
6762 if (((fts & 0xFFFF8000L) == (pvt->lastvsent & 0xFFFF8000L)) &&
6765 ) {
6766 now = 1;
6767 sendmini = 1;
6768 } else {
6769 now = 0;
6770 sendmini = 0;
6771 }
6772 pvt->lastvsent = fts;
6773 }
6774 if (f->frametype == AST_FRAME_IAX) {
6775 /* 0x8000 marks this message as TX:, this bit will be stripped later */
6777 if (!pvt->first_iax_message) {
6779 }
6780 }
6781 /* Allocate an iax_frame */
6782 if (now) {
6783 fr = &frb.fr2;
6784 } else
6785 fr = iax_frame_new(DIRECTION_OUTGRESS, ast_test_flag64(pvt, IAX_ENCRYPTED) ? f->datalen + 32 : f->datalen, (f->frametype == AST_FRAME_VOICE) || (f->frametype == AST_FRAME_VIDEO));
6786 if (!fr) {
6787 ast_log(LOG_WARNING, "Out of memory\n");
6788 return -1;
6789 }
6790 /* Copy our prospective frame into our immediate or retransmitted wrapper */
6791 iax_frame_wrap(fr, f);
6792
6793 fr->ts = fts;
6794 fr->callno = pvt->callno;
6795 fr->transfer = transfer;
6796 fr->final = final;
6797 fr->encmethods = 0;
6798 if (!sendmini) {
6799 /* We need a full frame */
6800 if (seqno > -1)
6801 fr->oseqno = seqno;
6802 else
6803 fr->oseqno = pvt->oseqno++;
6804 fr->iseqno = pvt->iseqno;
6805 fh = (struct ast_iax2_full_hdr *)(fr->af.data.ptr - sizeof(struct ast_iax2_full_hdr));
6806 fh->scallno = htons(fr->callno | IAX_FLAG_FULL);
6807 fh->ts = htonl(fr->ts);
6808 fh->oseqno = fr->oseqno;
6809 if (transfer) {
6810 fh->iseqno = 0;
6811 } else
6812 fh->iseqno = fr->iseqno;
6813 /* Keep track of the last thing we've acknowledged */
6814 if (!transfer)
6815 pvt->aseqno = fr->iseqno;
6816 fh->type = fr->af.frametype & 0xFF;
6817
6818 if (fr->af.frametype == AST_FRAME_VIDEO) {
6820 tmpfmt |= fr->af.subclass.frame_ending ? 0x1LL : 0;
6821 fh->csub = compress_subclass(tmpfmt | ((tmpfmt & 0x1LL) << 6));
6822 } else if (fr->af.frametype == AST_FRAME_VOICE) {
6824 } else {
6826 }
6827
6828 if (transfer) {
6829 fr->dcallno = pvt->transfercallno;
6830 } else
6831 fr->dcallno = pvt->peercallno;
6832 fh->dcallno = htons(fr->dcallno);
6833 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_full_hdr);
6834 fr->data = fh;
6835 fr->retries = 0;
6836 /* Retry after 2x the ping time has passed */
6837 fr->retrytime = pvt->pingtime * 2;
6838 if (fr->retrytime < MIN_RETRY_TIME)
6840 if (fr->retrytime > MAX_RETRY_TIME)
6842 /* Acks' don't get retried */
6844 fr->retries = -1;
6845 else if (f->frametype == AST_FRAME_VOICE)
6847 else if (f->frametype == AST_FRAME_VIDEO)
6849 if (ast_test_flag64(pvt, IAX_ENCRYPTED)) {
6851 if (fr->transfer)
6852 iax_outputframe(fr, NULL, 2, &pvt->transfer, fr->datalen - sizeof(struct ast_iax2_full_hdr));
6853 else
6854 iax_outputframe(fr, NULL, 2, &pvt->addr, fr->datalen - sizeof(struct ast_iax2_full_hdr));
6855 encrypt_frame(&pvt->ecx, fh, pvt->semirand, &fr->datalen);
6856 fr->encmethods = pvt->encmethods;
6857 fr->ecx = pvt->ecx;
6858 fr->mydcx = pvt->mydcx;
6859 memcpy(fr->semirand, pvt->semirand, sizeof(fr->semirand));
6860 } else
6861 ast_log(LOG_WARNING, "Supposed to send packet encrypted, but no key?\n");
6862 }
6863
6864 if (now) {
6865 res = send_packet(fr);
6866 } else
6867 res = iax2_transmit(fr);
6868 } else {
6869 if (ast_test_flag64(pvt, IAX_TRUNK)) {
6870 iax2_trunk_queue(pvt, fr);
6871 res = 0;
6872 } else if (fr->af.frametype == AST_FRAME_VIDEO) {
6873 /* Video frame have no sequence number */
6874 fr->oseqno = -1;
6875 fr->iseqno = -1;
6876 vh = (struct ast_iax2_video_hdr *)(fr->af.data.ptr - sizeof(struct ast_iax2_video_hdr));
6877 vh->zeros = 0;
6878 vh->callno = htons(0x8000 | fr->callno);
6879 vh->ts = htons((fr->ts & 0x7FFF) | (fr->af.subclass.frame_ending ? 0x8000 : 0));
6880 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_video_hdr);
6881 fr->data = vh;
6882 fr->retries = -1;
6883 res = send_packet(fr);
6884 } else {
6885 /* Mini-frames have no sequence number */
6886 fr->oseqno = -1;
6887 fr->iseqno = -1;
6888 /* Mini frame will do */
6889 mh = (struct ast_iax2_mini_hdr *)(fr->af.data.ptr - sizeof(struct ast_iax2_mini_hdr));
6890 mh->callno = htons(fr->callno);
6891 mh->ts = htons(fr->ts & 0xFFFF);
6892 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_mini_hdr);
6893 fr->data = mh;
6894 fr->retries = -1;
6895 if (pvt->transferring == TRANSFER_MEDIAPASS)
6896 fr->transfer = 1;
6897 if (ast_test_flag64(pvt, IAX_ENCRYPTED)) {
6899 encrypt_frame(&pvt->ecx, (struct ast_iax2_full_hdr *)mh, pvt->semirand, &fr->datalen);
6900 } else
6901 ast_log(LOG_WARNING, "Supposed to send packet encrypted, but no key?\n");
6902 }
6903 res = send_packet(fr);
6904 }
6905 }
6906 return res;
6907}
6908
6909static char *handle_cli_iax2_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
6910{
6911 regex_t regexbuf;
6912 int havepattern = 0;
6913
6914#define FORMAT "%-15.15s %-20.20s %-15.15s %-15.15s %-5.5s %-5.10s\n"
6915#define FORMAT2 "%-15.15s %-20.20s %-15.15d %-15.15s %-5.5s %-5.10s\n"
6916
6917 struct iax2_user *user = NULL;
6918 char auth[90];
6919 char *pstr = "";
6920 struct ao2_iterator i;
6921
6922 switch (cmd) {
6923 case CLI_INIT:
6924 e->command = "iax2 show users [like]";
6925 e->usage =
6926 "Usage: iax2 show users [like <pattern>]\n"
6927 " Lists all known IAX2 users.\n"
6928 " Optional regular expression pattern is used to filter the user list.\n";
6929 return NULL;
6930 case CLI_GENERATE:
6931 return NULL;
6932 }
6933
6934 switch (a->argc) {
6935 case 5:
6936 if (!strcasecmp(a->argv[3], "like")) {
6937 if (regcomp(&regexbuf, a->argv[4], REG_EXTENDED | REG_NOSUB))
6938 return CLI_SHOWUSAGE;
6939 havepattern = 1;
6940 } else
6941 return CLI_SHOWUSAGE;
6942 case 3:
6943 break;
6944 default:
6945 return CLI_SHOWUSAGE;
6946 }
6947
6948 ast_cli(a->fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C","Codec Pref");
6949 i = ao2_iterator_init(users, 0);
6950 for (; (user = ao2_iterator_next(&i)); user_unref(user)) {
6951 if (havepattern && regexec(&regexbuf, user->name, 0, NULL, 0))
6952 continue;
6953
6954 if (!ast_strlen_zero(user->secret)) {
6955 ast_copy_string(auth,user->secret, sizeof(auth));
6956 } else if (!ast_strlen_zero(user->inkeys)) {
6957 snprintf(auth, sizeof(auth), "Key: %-15.15s ", user->inkeys);
6958 } else
6959 ast_copy_string(auth, "-no secret-", sizeof(auth));
6960
6962 pstr = "REQ Only";
6964 pstr = "Disabled";
6965 else
6966 pstr = ast_test_flag64(user, IAX_CODEC_USER_FIRST) ? "Caller" : "Host";
6967
6968 ast_cli(a->fd, FORMAT2, user->name, auth, user->authmethods,
6969 user->contexts ? user->contexts->context : DEFAULT_CONTEXT,
6970 ast_acl_list_is_empty(user->acl) ? "No" : "Yes", pstr);
6971 }
6973
6974 if (havepattern)
6975 regfree(&regexbuf);
6976
6977 return CLI_SUCCESS;
6978#undef FORMAT
6979#undef FORMAT2
6980}
6981
6982struct show_peers_context {
6983 regex_t regexbuf;
6984 int havepattern;
6985 char idtext[256];
6986 int registeredonly;
6987 int peerlist;
6988 int total_peers;
6989 int online_peers;
6990 int offline_peers;
6992};
6993
6994#define PEERS_FORMAT2 "%-15.15s %-40.40s %s %-40.40s %-9s %s %-11s %-32.32s\n"
6995#define PEERS_FORMAT "%-15.15s %-40.40s %s %-40.40s %-6s%s %s %-11s %-32.32s\n"
6996
6997static void _iax2_show_peers_one(int fd, struct mansession *s, struct show_peers_context *cont, struct iax2_peer *peer)
6998{
6999 char name[256] = "";
7000 char status[64];
7001 int retstatus;
7002 struct ast_str *encmethods = ast_str_alloca(256);
7003
7004 char *tmp_host, *tmp_mask, *tmp_port;
7005
7006 tmp_host = ast_strdupa(ast_sockaddr_stringify_addr(&peer->addr));
7007 tmp_mask = ast_strdupa(ast_sockaddr_stringify_addr(&peer->mask));
7008 tmp_port = ast_strdupa(ast_sockaddr_stringify_port(&peer->addr));
7009
7010 if (!ast_strlen_zero(peer->username)) {
7011 snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
7012 } else {
7013 ast_copy_string(name, peer->name, sizeof(name));
7014 }
7015
7016 encmethods_to_str(peer->encmethods, &encmethods);
7017 retstatus = peer_status(peer, status, sizeof(status));
7018 if (retstatus > 0) {
7019 cont->online_peers++;
7020 } else if (!retstatus) {
7021 cont->offline_peers++;
7022 } else {
7023 cont->unmonitored_peers++;
7024 }
7025
7026 if (s) {
7027 if (cont->peerlist) { /* IAXpeerlist */
7028 astman_append(s,
7029 "Event: PeerEntry\r\n%s"
7030 "Channeltype: IAX\r\n",
7031 cont->idtext);
7032 if (!ast_strlen_zero(peer->username)) {
7033 astman_append(s,
7034 "ObjectName: %s\r\n"
7035 "ObjectUsername: %s\r\n",
7036 peer->name,
7037 peer->username);
7038 } else {
7039 astman_append(s,
7040 "ObjectName: %s\r\n",
7041 name);
7042 }
7043 } else { /* IAXpeers */
7044 astman_append(s,
7045 "Event: PeerEntry\r\n%s"
7046 "Channeltype: IAX2\r\n"
7047 "ObjectName: %s\r\n",
7048 cont->idtext,
7049 name);
7050 }
7051 astman_append(s,
7052 "ChanObjectType: peer\r\n"
7053 "IPaddress: %s\r\n",
7054 tmp_host);
7055 if (cont->peerlist) { /* IAXpeerlist */
7056 astman_append(s,
7057 "Mask: %s\r\n"
7058 "Port: %s\r\n",
7059 tmp_mask,
7060 tmp_port);
7061 } else { /* IAXpeers */
7062 astman_append(s,
7063 "IPport: %s\r\n",
7064 tmp_port);
7065 }
7066 astman_append(s,
7067 "Dynamic: %s\r\n"
7068 "Trunk: %s\r\n"
7069 "Encryption: %s\r\n"
7070 "Status: %s\r\n",
7071 ast_test_flag64(peer, IAX_DYNAMIC) ? "yes" : "no",
7072 ast_test_flag64(peer, IAX_TRUNK) ? "yes" : "no",
7073 peer->encmethods ? ast_str_buffer(encmethods) : "no",
7074 status);
7075 if (cont->peerlist) { /* IAXpeerlist */
7076 astman_append(s, "\r\n");
7077 } else { /* IAXpeers */
7078 astman_append(s,
7079 "Description: %s\r\n\r\n",
7080 peer->description);
7081 }
7082 } else {
7084 name,
7085 tmp_host,
7086 ast_test_flag64(peer, IAX_DYNAMIC) ? "(D)" : "(S)",
7087 tmp_mask,
7088 tmp_port,
7089 ast_test_flag64(peer, IAX_TRUNK) ? "(T)" : " ",
7090 peer->encmethods ? "(E)" : " ",
7091 status,
7092 peer->description);
7093 }
7094
7095 cont->total_peers++;
7096}
7097
7098static int __iax2_show_peers(int fd, int *total, struct mansession *s, const int argc, const char * const argv[])
7099{
7100 struct show_peers_context cont = {
7101 .havepattern = 0,
7102 .idtext = "",
7103 .registeredonly = 0,
7104
7105 .peerlist = 0,
7106
7107 .total_peers = 0,
7108 .online_peers = 0,
7109 .offline_peers = 0,
7110 .unmonitored_peers = 0,
7111 };
7112
7113 struct ao2_iterator i;
7114
7115 struct iax2_peer *peer = NULL;
7116
7117 switch (argc) {
7118 case 6:
7119 if (!strcasecmp(argv[3], "registered"))
7120 cont.registeredonly = 1;
7121 else
7122 return RESULT_SHOWUSAGE;
7123 if (!strcasecmp(argv[4], "like")) {
7124 if (regcomp(&cont.regexbuf, argv[5], REG_EXTENDED | REG_NOSUB))
7125 return RESULT_SHOWUSAGE;
7126 cont.havepattern = 1;
7127 } else
7128 return RESULT_SHOWUSAGE;
7129 break;
7130 case 5:
7131 if (!strcasecmp(argv[3], "like")) {
7132 if (regcomp(&cont.regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
7133 return RESULT_SHOWUSAGE;
7134 cont.havepattern = 1;
7135 } else
7136 return RESULT_SHOWUSAGE;
7137 break;
7138 case 4:
7139 if (!strcasecmp(argv[3], "registered")) {
7140 cont.registeredonly = 1;
7141 } else {
7142 return RESULT_SHOWUSAGE;
7143 }
7144 break;
7145 case 3:
7146 break;
7147 default:
7148 return RESULT_SHOWUSAGE;
7149 }
7150
7151
7152 if (!s) {
7153 ast_cli(fd, PEERS_FORMAT2, "Name/Username", "Host", " ", "Mask", "Port", " ", "Status", "Description");
7154 }
7155
7156 i = ao2_iterator_init(peers, 0);
7157 for (; (peer = ao2_iterator_next(&i)); peer_unref(peer)) {
7158
7159 if (cont.registeredonly && ast_sockaddr_isnull(&peer->addr)) {
7160 continue;
7161 }
7162 if (cont.havepattern && regexec(&cont.regexbuf, peer->name, 0, NULL, 0)) {
7163 continue;
7164 }
7165
7166 _iax2_show_peers_one(fd, s, &cont, peer);
7167
7168 }
7170
7171 if (!s) {
7172 ast_cli(fd,"%d iax2 peers [%d online, %d offline, %d unmonitored]\n",
7174 }
7175
7176 if (cont.havepattern) {
7177 regfree(&cont.regexbuf);
7178 }
7179
7180 if (total) {
7181 *total = cont.total_peers;
7182 }
7183
7184 return RESULT_SUCCESS;
7185
7186}
7187#undef PEERS_FORMAT2
7188#undef PEERS_FORMAT
7189
7190static char *handle_cli_iax2_show_threads(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
7191{
7192 struct iax2_thread *thread = NULL;
7193 time_t t;
7194 int threadcount = 0, dynamiccount = 0;
7195 char type;
7196
7197 switch (cmd) {
7198 case CLI_INIT:
7199 e->command = "iax2 show threads";
7200 e->usage =
7201 "Usage: iax2 show threads\n"
7202 " Lists status of IAX helper threads\n";
7203 return NULL;
7204 case CLI_GENERATE:
7205 return NULL;
7206 }
7207 if (a->argc != 3)
7208 return CLI_SHOWUSAGE;
7209
7210 ast_cli(a->fd, "IAX2 Thread Information\n");
7211 time(&t);
7212 ast_cli(a->fd, "Idle Threads:\n");
7215#ifdef DEBUG_SCHED_MULTITHREAD
7216 ast_cli(a->fd, "Thread %d: state=%u, update=%d, actions=%d, func='%s'\n",
7217 thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
7218#else
7219 ast_cli(a->fd, "Thread %d: state=%u, update=%d, actions=%d\n",
7220 thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
7221#endif
7222 threadcount++;
7223 }
7225 ast_cli(a->fd, "Active Threads:\n");
7228 if (thread->type == IAX_THREAD_TYPE_DYNAMIC)
7229 type = 'D';
7230 else
7231 type = 'P';
7232#ifdef DEBUG_SCHED_MULTITHREAD
7233 ast_cli(a->fd, "Thread %c%d: state=%u, update=%d, actions=%d, func='%s'\n",
7234 type, thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
7235#else
7236 ast_cli(a->fd, "Thread %c%d: state=%u, update=%d, actions=%d\n",
7237 type, thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
7238#endif
7239 threadcount++;
7240 }
7242 ast_cli(a->fd, "Dynamic Threads:\n");
7245#ifdef DEBUG_SCHED_MULTITHREAD
7246 ast_cli(a->fd, "Thread %d: state=%u, update=%d, actions=%d, func='%s'\n",
7247 thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
7248#else
7249 ast_cli(a->fd, "Thread %d: state=%u, update=%d, actions=%d\n",
7250 thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
7251#endif
7252 dynamiccount++;
7253 }
7255 ast_cli(a->fd, "%d of %d threads accounted for with %d dynamic threads\n", threadcount, iaxthreadcount, dynamiccount);
7256 return CLI_SUCCESS;
7257}
7258
7259static char *handle_cli_iax2_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
7260{
7261 struct iax2_peer *p;
7262
7263 switch (cmd) {
7264 case CLI_INIT:
7265 e->command = "iax2 unregister";
7266 e->usage =
7267 "Usage: iax2 unregister <peername>\n"
7268 " Unregister (force expiration) an IAX2 peer from the registry.\n";
7269 return NULL;
7270 case CLI_GENERATE:
7271 return complete_iax2_unregister(a->line, a->word, a->pos, a->n);
7272 }
7273
7274 if (a->argc != 3)
7275 return CLI_SHOWUSAGE;
7276
7277 p = find_peer(a->argv[2], 1);
7278 if (p) {
7279 if (p->expire > -1) {
7280 struct iax2_peer *peer;
7281
7282 peer = ao2_find(peers, a->argv[2], OBJ_KEY);
7283 if (peer) {
7284 expire_registry(peer_ref(peer)); /* will release its own reference when done */
7285 peer_unref(peer); /* ref from ao2_find() */
7286 ast_cli(a->fd, "Peer %s unregistered\n", a->argv[2]);
7287 } else {
7288 ast_cli(a->fd, "Peer %s not found\n", a->argv[2]);
7289 }
7290 } else {
7291 ast_cli(a->fd, "Peer %s not registered\n", a->argv[2]);
7292 }
7293 peer_unref(p);
7294 } else {
7295 ast_cli(a->fd, "Peer unknown: %s. Not unregistered\n", a->argv[2]);
7296 }
7297 return CLI_SUCCESS;
7298}
7299
7300static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state)
7301{
7302 int which = 0;
7303 struct iax2_peer *p = NULL;
7304 char *res = NULL;
7305 int wordlen = strlen(word);
7306
7307 /* 0 - iax2; 1 - unregister; 2 - <peername> */
7308 if (pos == 2) {
7309 struct ao2_iterator i = ao2_iterator_init(peers, 0);
7310 while ((p = ao2_iterator_next(&i))) {
7311 if (!strncasecmp(p->name, word, wordlen) &&
7312 ++which > state && p->expire > -1) {
7313 res = ast_strdup(p->name);
7314 peer_unref(p);
7315 break;
7316 }
7317 peer_unref(p);
7318 }
7320 }
7321
7322 return res;
7323}
7324
7325static char *handle_cli_iax2_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
7326{
7327 switch (cmd) {
7328 case CLI_INIT:
7329 e->command = "iax2 show peers";
7330 e->usage =
7331 "Usage: iax2 show peers [registered] [like <pattern>]\n"
7332 " Lists all known IAX2 peers.\n"
7333 " Optional 'registered' argument lists only peers with known addresses.\n"
7334 " Optional regular expression pattern is used to filter the peer list.\n";
7335 return NULL;
7336 case CLI_GENERATE:
7337 return NULL;
7338 }
7339
7340 switch (__iax2_show_peers(a->fd, NULL, NULL, a->argc, a->argv)) {
7341 case RESULT_SHOWUSAGE:
7342 return CLI_SHOWUSAGE;
7343 case RESULT_FAILURE:
7344 return CLI_FAILURE;
7345 default:
7346 return CLI_SUCCESS;
7347 }
7348}
7349
7350static int manager_iax2_show_netstats(struct mansession *s, const struct message *m)
7351{
7352 ast_cli_netstats(s, -1, 0);
7353 astman_append(s, "\r\n");
7354 return RESULT_SUCCESS;
7355}
7356
7358 void *user_data)
7359{
7360 int *fd = user_data;
7361
7362 ast_cli(*fd, "%-15.15s %-15d %-15d\n",
7363 header->devname,
7364 ntohs(header->version),
7365 (int) ntohl(header->datalen));
7366
7367 return 0;
7368}
7369
7370static char *handle_cli_iax2_show_firmware(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
7371{
7372 switch (cmd) {
7373 case CLI_INIT:
7374 e->command = "iax2 show firmware";
7375 e->usage =
7376 "Usage: iax2 show firmware\n"
7377 " Lists all known IAX firmware images.\n";
7378 return NULL;
7379 case CLI_GENERATE:
7380 return NULL;
7381 }
7382
7383 if (a->argc != 3 && a->argc != 4)
7384 return CLI_SHOWUSAGE;
7385
7386 ast_cli(a->fd, "%-15.15s %-15.15s %-15.15s\n", "Device", "Version", "Size");
7387
7389 a->argc == 3 ? NULL : a->argv[3],
7391 (void *) &a->fd);
7392
7393 return CLI_SUCCESS;
7394}
7395
7396/*! \brief callback to display iax peers in manager */
7397static int manager_iax2_show_peers(struct mansession *s, const struct message *m)
7398{
7399 static const char * const a[] = { "iax2", "show", "peers" };
7400 const char *id = astman_get_header(m,"ActionID");
7401 char idtext[256] = "";
7402 int total = 0;
7403
7404 if (!ast_strlen_zero(id))
7405 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
7406
7407 astman_send_listack(s, m, "Peer status list will follow", "start");
7408
7409 /* List the peers in separate manager events */
7410 __iax2_show_peers(-1, &total, s, 3, a);
7411
7412 /* Send final confirmation */
7413 astman_send_list_complete_start(s, m, "PeerlistComplete", total);
7415 return 0;
7416}
7417
7418/*! \brief callback to display iax peers in manager format */
7419static int manager_iax2_show_peer_list(struct mansession *s, const struct message *m)
7420{
7421 struct show_peers_context cont = {
7422 .havepattern = 0,
7423 .idtext = "",
7424 .registeredonly = 0,
7425
7426 .peerlist = 1,
7427
7428 .total_peers = 0,
7429 .online_peers = 0,
7430 .offline_peers = 0,
7431 .unmonitored_peers = 0,
7432 };
7433
7434 struct iax2_peer *peer = NULL;
7435 struct ao2_iterator i;
7436
7437 const char *id = astman_get_header(m,"ActionID");
7438
7439 if (!ast_strlen_zero(id)) {
7440 snprintf(cont.idtext, sizeof(cont.idtext), "ActionID: %s\r\n", id);
7441 }
7442
7443 astman_send_listack(s, m, "IAX Peer status list will follow", "start");
7444
7445 i = ao2_iterator_init(peers, 0);
7446 for (; (peer = ao2_iterator_next(&i)); peer_unref(peer)) {
7447 _iax2_show_peers_one(-1, s, &cont, peer);
7448 }
7450
7451 astman_send_list_complete_start(s, m, "PeerlistComplete", cont.total_peers);
7453
7454 return RESULT_SUCCESS;
7455}
7456
7457
7458static char *regstate2str(int regstate)
7459{
7460 switch(regstate) {
7462 return "Unregistered";
7463 case REG_STATE_REGSENT:
7464 return "Request Sent";
7465 case REG_STATE_AUTHSENT:
7466 return "Auth. Sent";
7468 return "Registered";
7469 case REG_STATE_REJECTED:
7470 return "Rejected";
7471 case REG_STATE_TIMEOUT:
7472 return "Timeout";
7473 case REG_STATE_NOAUTH:
7474 return "No Authentication";
7475 default:
7476 return "Unknown";
7477 }
7478}
7479
7480static char *handle_cli_iax2_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
7481{
7482#define FORMAT2 "%-45.45s %-6.6s %-10.10s %-45.45s %8.8s %s\n"
7483#define FORMAT "%-45.45s %-6.6s %-10.10s %-45.45s %8d %s\n"
7484
7485 struct iax2_registry *reg = NULL;
7486 char host[80];
7487 char perceived[80];
7488 int counter = 0;
7489
7490 switch (cmd) {
7491 case CLI_INIT:
7492 e->command = "iax2 show registry";
7493 e->usage =
7494 "Usage: iax2 show registry\n"
7495 " Lists all registration requests and status.\n";
7496 return NULL;
7497 case CLI_GENERATE:
7498 return NULL;
7499 }
7500 if (a->argc != 3)
7501 return CLI_SHOWUSAGE;
7502 ast_cli(a->fd, FORMAT2, "Host", "dnsmgr", "Username", "Perceived", "Refresh", "State");
7505 snprintf(host, sizeof(host), "%s", ast_sockaddr_stringify(&reg->addr));
7506
7507 snprintf(perceived, sizeof(perceived), "%s", ast_sockaddr_isnull(&reg->us) ? "<Unregistered>" : ast_sockaddr_stringify(&reg->us));
7508
7509 ast_cli(a->fd, FORMAT, host,
7510 (reg->dnsmgr) ? "Y" : "N",
7511 reg->username, perceived, reg->refresh, regstate2str(reg->regstate));
7512 counter++;
7513 }
7515 ast_cli(a->fd, "%d IAX2 registrations.\n", counter);
7516 return CLI_SUCCESS;
7517#undef FORMAT
7518#undef FORMAT2
7519}
7520
7521static int manager_iax2_show_registry(struct mansession *s, const struct message *m)
7522{
7523 const char *id = astman_get_header(m, "ActionID");
7524 struct iax2_registry *reg = NULL;
7525 char idtext[256] = "";
7526 char host[80] = "";
7527 char perceived[80] = "";
7528 int total = 0;
7529
7530 if (!ast_strlen_zero(id))
7531 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
7532
7533 astman_send_listack(s, m, "Registrations will follow", "start");
7534
7537 snprintf(host, sizeof(host), "%s", ast_sockaddr_stringify(&reg->addr));
7538
7539 snprintf(perceived, sizeof(perceived), "%s", ast_sockaddr_isnull(&reg->us) ? "<Unregistered>" : ast_sockaddr_stringify(&reg->us));
7540
7541 astman_append(s,
7542 "Event: RegistryEntry\r\n"
7543 "%s"
7544 "Host: %s\r\n"
7545 "DNSmanager: %s\r\n"
7546 "Username: %s\r\n"
7547 "Perceived: %s\r\n"
7548 "Refresh: %d\r\n"
7549 "State: %s\r\n"
7550 "\r\n", idtext, host, (reg->dnsmgr) ? "Y" : "N", reg->username, perceived,
7551 reg->refresh, regstate2str(reg->regstate));
7552
7553 total++;
7554 }
7556
7557 astman_send_list_complete_start(s, m, "RegistrationsComplete", total);
7559
7560 return 0;
7561}
7562
7563static char *handle_cli_iax2_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
7564{
7565#define FORMAT2 "%-20.20s %-40.40s %-10.10s %-11.11s %-11.11s %-7.7s %-6.6s %-6.6s %s %s %9s\n"
7566#define FORMAT "%-20.20s %-40.40s %-10.10s %5.5d/%5.5d %5.5d/%5.5d %-5.5dms %-4.4dms %-4.4dms %-6.6s %s%s %3s%s\n"
7567#define FORMATB "%-20.20s %-40.40s %-10.10s %5.5d/%5.5d %5.5d/%5.5d [Native Bridged to ID=%5.5d]\n"
7568 int x;
7569 int numchans = 0;
7570 char first_message[10] = { 0, };
7571 char last_message[10] = { 0, };
7572
7573 switch (cmd) {
7574 case CLI_INIT:
7575 e->command = "iax2 show channels";
7576 e->usage =
7577 "Usage: iax2 show channels\n"
7578 " Lists all currently active IAX channels.\n";
7579 return NULL;
7580 case CLI_GENERATE:
7581 return NULL;
7582 }
7583
7584 if (a->argc != 3)
7585 return CLI_SHOWUSAGE;
7586 ast_cli(a->fd, FORMAT2, "Channel", "Peer", "Username", "ID (Lo/Rem)", "Seq (Tx/Rx)", "Lag", "Jitter", "JitBuf", "Format", "FirstMsg", "LastMsg");
7587 for (x = 0; x < ARRAY_LEN(iaxs); x++) {
7588 ast_mutex_lock(&iaxsl[x]);
7589 if (iaxs[x]) {
7590 int lag, jitter, localdelay;
7591 jb_info jbinfo;
7593 jb_getinfo(iaxs[x]->jb, &jbinfo);
7594 jitter = jbinfo.jitter;
7595 localdelay = jbinfo.current - jbinfo.min;
7596 } else {
7597 jitter = -1;
7598 localdelay = 0;
7599 }
7600
7601 iax_frame_subclass2str(iaxs[x]->first_iax_message & ~MARK_IAX_SUBCLASS_TX, first_message, sizeof(first_message));
7602 iax_frame_subclass2str(iaxs[x]->last_iax_message & ~MARK_IAX_SUBCLASS_TX, last_message, sizeof(last_message));
7603 lag = iaxs[x]->remote_rr.delay;
7604 ast_cli(a->fd, FORMAT,
7605 iaxs[x]->owner ? ast_channel_name(iaxs[x]->owner) : "(None)",
7607 S_OR(iaxs[x]->username, "(None)"),
7608 iaxs[x]->callno, iaxs[x]->peercallno,
7609 iaxs[x]->oseqno, iaxs[x]->iseqno,
7610 lag,
7611 jitter,
7612 localdelay,
7613 iax2_getformatname(iaxs[x]->voiceformat),
7614 (iaxs[x]->first_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
7615 first_message,
7616 (iaxs[x]->last_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
7617 last_message);
7618 numchans++;
7619 }
7621 }
7622 ast_cli(a->fd, "%d active IAX channel%s\n", numchans, (numchans != 1) ? "s" : "");
7623 return CLI_SUCCESS;
7624#undef FORMAT
7625#undef FORMAT2
7626#undef FORMATB
7627}
7628
7629static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt)
7630{
7631 int x;
7632 int numchans = 0;
7633 char first_message[10] = { 0, };
7634 char last_message[10] = { 0, };
7635#define ACN_FORMAT1 "%-24.25s %4u %4d %4d %5d %3d %5d %4d %6d %4d %4d %5d %3d %5d %4d %6d %s%s %4s%s\n"
7636#define ACN_FORMAT2 "%s %u %d %d %d %d %d %d %d %d %d %d %d %d %d %d %s%s %s%s\n"
7637 for (x = 0; x < ARRAY_LEN(iaxs); x++) {
7638 ast_mutex_lock(&iaxsl[x]);
7639 if (iaxs[x]) {
7640 int localjitter, localdelay, locallost, locallosspct, localdropped, localooo;
7641 jb_info jbinfo;
7642 iax_frame_subclass2str(iaxs[x]->first_iax_message & ~MARK_IAX_SUBCLASS_TX, first_message, sizeof(first_message));
7643 iax_frame_subclass2str(iaxs[x]->last_iax_message & ~MARK_IAX_SUBCLASS_TX, last_message, sizeof(last_message));
7644
7646 jb_getinfo(iaxs[x]->jb, &jbinfo);
7647 localjitter = jbinfo.jitter;
7648 localdelay = jbinfo.current - jbinfo.min;
7649 locallost = jbinfo.frames_lost;
7650 locallosspct = jbinfo.losspct/1000;
7651 localdropped = jbinfo.frames_dropped;
7652 localooo = jbinfo.frames_ooo;
7653 } else {
7654 localjitter = -1;
7655 localdelay = 0;
7656 locallost = -1;
7657 locallosspct = -1;
7658 localdropped = 0;
7659 localooo = -1;
7660 }
7661 if (s)
7662 astman_append(s, limit_fmt ? ACN_FORMAT1 : ACN_FORMAT2,
7663 iaxs[x]->owner ? ast_channel_name(iaxs[x]->owner) : "(None)",
7664 iaxs[x]->pingtime,
7665 localjitter,
7666 localdelay,
7667 locallost,
7668 locallosspct,
7669 localdropped,
7670 localooo,
7671 iaxs[x]->frames_received/1000,
7672 iaxs[x]->remote_rr.jitter,
7673 iaxs[x]->remote_rr.delay,
7674 iaxs[x]->remote_rr.losscnt,
7675 iaxs[x]->remote_rr.losspct,
7676 iaxs[x]->remote_rr.dropped,
7677 iaxs[x]->remote_rr.ooo,
7678 iaxs[x]->remote_rr.packets/1000,
7679 (iaxs[x]->first_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
7680 first_message,
7681 (iaxs[x]->last_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
7682 last_message);
7683 else
7684 ast_cli(fd, limit_fmt ? ACN_FORMAT1 : ACN_FORMAT2,
7685 iaxs[x]->owner ? ast_channel_name(iaxs[x]->owner) : "(None)",
7686 iaxs[x]->pingtime,
7687 localjitter,
7688 localdelay,
7689 locallost,
7690 locallosspct,
7691 localdropped,
7692 localooo,
7693 iaxs[x]->frames_received/1000,
7694 iaxs[x]->remote_rr.jitter,
7695 iaxs[x]->remote_rr.delay,
7696 iaxs[x]->remote_rr.losscnt,
7697 iaxs[x]->remote_rr.losspct,
7698 iaxs[x]->remote_rr.dropped,
7699 iaxs[x]->remote_rr.ooo,
7700 iaxs[x]->remote_rr.packets/1000,
7701 (iaxs[x]->first_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
7702 first_message,
7703 (iaxs[x]->last_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
7704 last_message);
7705 numchans++;
7706 }
7708 }
7709
7710 return numchans;
7711}
7712
7713static char *handle_cli_iax2_show_netstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
7714{
7715 int numchans = 0;
7716
7717 switch (cmd) {
7718 case CLI_INIT:
7719 e->command = "iax2 show netstats";
7720 e->usage =
7721 "Usage: iax2 show netstats\n"
7722 " Lists network status for all currently active IAX channels.\n";
7723 return NULL;
7724 case CLI_GENERATE:
7725 return NULL;
7726 }
7727 if (a->argc != 3)
7728 return CLI_SHOWUSAGE;
7729 ast_cli(a->fd, " -------- LOCAL --------------------- -------- REMOTE --------------------\n");
7730 ast_cli(a->fd, "Channel RTT Jit Del Lost %% Drop OOO Kpkts Jit Del Lost %% Drop OOO Kpkts FirstMsg LastMsg\n");
7731 numchans = ast_cli_netstats(NULL, a->fd, 1);
7732 ast_cli(a->fd, "%d active IAX channel%s\n", numchans, (numchans != 1) ? "s" : "");
7733 return CLI_SUCCESS;
7734}
7735
7736static char *handle_cli_iax2_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
7737{
7738 switch (cmd) {
7739 case CLI_INIT:
7740 e->command = "iax2 set debug {on|off|peer}";
7741 e->usage =
7742 "Usage: iax2 set debug {on|off|peer peername}\n"
7743 " Enables/Disables dumping of IAX packets for debugging purposes.\n";
7744 return NULL;
7745 case CLI_GENERATE:
7746 if (a->pos == 4 && !strcasecmp(a->argv[3], "peer"))
7747 return complete_iax2_peers(a->line, a->word, a->pos, a->n, 0);
7748 return NULL;
7749 }
7750
7751 if (a->argc < e->args || a->argc > e->args + 1)
7752 return CLI_SHOWUSAGE;
7753
7754 if (!strcasecmp(a->argv[3], "peer")) {
7755 struct iax2_peer *peer;
7756
7757 if (a->argc != e->args + 1)
7758 return CLI_SHOWUSAGE;
7759
7760 peer = find_peer(a->argv[4], 1);
7761
7762 if (!peer) {
7763 ast_cli(a->fd, "IAX2 peer '%s' does not exist\n", a->argv[e->args-1]);
7764 return CLI_FAILURE;
7765 }
7766
7768
7769 ast_cli(a->fd, "IAX2 Debugging Enabled for IP: %s\n", ast_sockaddr_stringify_port(&debugaddr));
7770
7771 ao2_ref(peer, -1);
7772 } else if (!strncasecmp(a->argv[3], "on", 2)) {
7773 iaxdebug = 1;
7774 ast_cli(a->fd, "IAX2 Debugging Enabled\n");
7775 } else {
7776 iaxdebug = 0;
7777 memset(&debugaddr, 0, sizeof(debugaddr));
7778 ast_cli(a->fd, "IAX2 Debugging Disabled\n");
7779 }
7780 return CLI_SUCCESS;
7781}
7782
7783static char *handle_cli_iax2_set_debug_trunk(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
7784{
7785 switch (cmd) {
7786 case CLI_INIT:
7787 e->command = "iax2 set debug trunk {on|off}";
7788 e->usage =
7789 "Usage: iax2 set debug trunk {on|off}\n"
7790 " Enables/Disables debugging of IAX trunking\n";
7791 return NULL;
7792 case CLI_GENERATE:
7793 return NULL;
7794 }
7795
7796 if (a->argc != e->args)
7797 return CLI_SHOWUSAGE;
7798
7799 if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
7800 iaxtrunkdebug = 1;
7801 ast_cli(a->fd, "IAX2 Trunk Debugging Enabled\n");
7802 } else {
7803 iaxtrunkdebug = 0;
7804 ast_cli(a->fd, "IAX2 Trunk Debugging Disabled\n");
7805 }
7806 return CLI_SUCCESS;
7807}
7808
7809static char *handle_cli_iax2_set_debug_jb(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
7810{
7811 switch (cmd) {
7812 case CLI_INIT:
7813 e->command = "iax2 set debug jb {on|off}";
7814 e->usage =
7815 "Usage: iax2 set debug jb {on|off}\n"
7816 " Enables/Disables jitterbuffer debugging information\n";
7817 return NULL;
7818 case CLI_GENERATE:
7819 return NULL;
7820 }
7821
7822 if (a->argc != e->args)
7823 return CLI_SHOWUSAGE;
7824
7825 if (!strncasecmp(a->argv[e->args -1], "on", 2)) {
7827 ast_cli(a->fd, "IAX2 Jitterbuffer Debugging Enabled\n");
7828 } else {
7830 ast_cli(a->fd, "IAX2 Jitterbuffer Debugging Disabled\n");
7831 }
7832 return CLI_SUCCESS;
7833}
7834
7835static int iax2_write(struct ast_channel *c, struct ast_frame *f)
7836{
7837 unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
7838 int res = -1;
7840 if (iaxs[callno]) {
7841 /* If there's an outstanding error, return failure now */
7842 if (!iaxs[callno]->error) {
7844 res = 0;
7845 /* Don't waste bandwidth sending null frames */
7846 else if (f->frametype == AST_FRAME_NULL)
7847 res = 0;
7849 res = 0;
7851 res = 0;
7852 else
7853 /* Simple, just queue for transmission */
7854 res = iax2_send(iaxs[callno], f, 0, -1, 0, 0, 0);
7855 } else {
7856 ast_debug(1, "Write error: %s\n", strerror(errno));
7857 }
7858 }
7859 /* If it's already gone, just return */
7861 return res;
7862}
7863
7864static int __send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno,
7865 int now, int transfer, int final)
7866{
7867 struct ast_frame f = { 0, };
7868 int res = 0;
7869
7870 f.frametype = type;
7871 f.subclass.integer = command;
7872 f.datalen = datalen;
7873 f.src = __FUNCTION__;
7874 f.data.ptr = (void *) data;
7875
7876 if ((res = queue_signalling(i, &f)) <= 0) {
7877 return res;
7878 }
7879
7880 return iax2_send(i, &f, ts, seqno, now, transfer, final);
7881}
7882
7883static int send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno)
7884{
7886 /* Control frame should not go out on the wire. */
7887 ast_debug(2, "Callno %d: Blocked sending control frame %d.\n",
7888 i->callno, command);
7889 return 0;
7890 }
7891 return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 0);
7892}
7893
7894static int send_command_locked(unsigned short callno, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno)
7895{
7896 int res;
7897 ast_mutex_lock(&iaxsl[callno]);
7898 res = send_command(iaxs[callno], type, command, ts, data, datalen, seqno);
7899 ast_mutex_unlock(&iaxsl[callno]);
7900 return res;
7901}
7902
7903/*!
7904 * \note Since this function calls iax2_predestroy() -> iax2_queue_hangup(),
7905 * the pvt struct for the given call number may disappear during its
7906 * execution.
7907 */
7908static int send_command_final(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno)
7909{
7910 int call_num = i->callno;
7911 /* It is assumed that the callno has already been locked */
7913 if (!iaxs[call_num])
7914 return -1;
7915 return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 1);
7916}
7917
7918static int send_command_immediate(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno)
7919{
7920 return __send_command(i, type, command, ts, data, datalen, seqno, 1, 0, 0);
7921}
7922
7923static int send_command_transfer(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen)
7924{
7925 return __send_command(i, type, command, ts, data, datalen, 0, 0, 1, 0);
7926}
7927
7928static int apply_context(struct iax2_context *con, const char *context)
7929{
7930 while(con) {
7931 if (!strcmp(con->context, context) || !strcmp(con->context, "*"))
7932 return -1;
7933 con = con->next;
7934 }
7935 return 0;
7936}
7937
7938
7939static int check_access(int callno, struct ast_sockaddr *addr, struct iax_ies *ies)
7940{
7941 /* Start pessimistic */
7942 int res = -1;
7943 int version = 2;
7944 struct iax2_user *user = NULL, *best = NULL;
7945 int bestscore = 0;
7946 int gotcapability = 0;
7947 struct ast_variable *v = NULL, *tmpvar = NULL;
7948 struct ao2_iterator i;
7949
7950 if (!iaxs[callno])
7951 return res;
7952 if (ies->called_number)
7953 ast_string_field_set(iaxs[callno], exten, ies->called_number);
7954 if (ies->calling_number) {
7957 }
7958 ast_string_field_set(iaxs[callno], cid_num, ies->calling_number);
7959 }
7960 if (ies->calling_name)
7961 ast_string_field_set(iaxs[callno], cid_name, ies->calling_name);
7962 if (ies->calling_ani)
7963 ast_string_field_set(iaxs[callno], ani, ies->calling_ani);
7964 if (ies->dnid)
7965 ast_string_field_set(iaxs[callno], dnid, ies->dnid);
7966 if (ies->rdnis)
7967 ast_string_field_set(iaxs[callno], rdnis, ies->rdnis);
7968 if (ies->called_context)
7969 ast_string_field_set(iaxs[callno], context, ies->called_context);
7970 if (ies->language)
7972 if (ies->username)
7973 ast_string_field_set(iaxs[callno], username, ies->username);
7974 if (ies->calling_ton > -1)
7975 iaxs[callno]->calling_ton = ies->calling_ton;
7976 if (ies->calling_tns > -1)
7977 iaxs[callno]->calling_tns = ies->calling_tns;
7978 if (ies->calling_pres > -1)
7979 iaxs[callno]->calling_pres = ies->calling_pres;
7980 if (ies->calling_ani2 > -1)
7981 iaxs[callno]->calling_ani2 = ies->calling_ani2;
7982 if (ies->format)
7983 iaxs[callno]->peerformat = ies->format;
7984 if (ies->adsicpe)
7985 iaxs[callno]->peeradsicpe = ies->adsicpe;
7986 if (ies->capability) {
7987 gotcapability = 1;
7988 iaxs[callno]->peercapability = ies->capability;
7989 }
7990 if (ies->version)
7991 version = ies->version;
7992
7993 /* Use provided preferences until told otherwise for actual preferences */
7994 if (ies->codec_prefs) {
7995 iax2_codec_pref_convert(&iaxs[callno]->rprefs, ies->codec_prefs, 32, 0);
7996 } else {
7997 memset(&iaxs[callno]->rprefs, 0, sizeof(iaxs[callno]->rprefs));
7998 }
7999 iaxs[callno]->prefs = iaxs[callno]->rprefs;
8000
8001 if (!gotcapability) {
8002 iaxs[callno]->peercapability = iaxs[callno]->peerformat;
8003 }
8004 if (version > IAX_PROTO_VERSION) {
8005 ast_log(LOG_WARNING, "Peer '%s' has too new a protocol version (%d) for me\n",
8007 return res;
8008 }
8009 /* Search the userlist for a compatible entry, and fill in the rest */
8010 i = ao2_iterator_init(users, 0);
8011 while ((user = ao2_iterator_next(&i))) {
8012 if ((ast_strlen_zero(iaxs[callno]->username) || /* No username specified */
8013 !strcmp(iaxs[callno]->username, user->name)) /* Or this username specified */
8014 && (ast_apply_acl(user->acl, addr, "IAX2 user ACL: ") == AST_SENSE_ALLOW) /* Access is permitted from this IP */
8015 && (ast_strlen_zero(iaxs[callno]->context) || /* No context specified */
8016 apply_context(user->contexts, iaxs[callno]->context))) { /* Context is permitted */
8017 if (!ast_strlen_zero(iaxs[callno]->username)) {
8018 /* Exact match, stop right now. */
8019 if (best)
8020 user_unref(best);
8021 best = user;
8022 break;
8023 } else if (ast_strlen_zero(user->secret) && ast_strlen_zero(user->dbsecret) && ast_strlen_zero(user->inkeys)) {
8024 /* No required authentication */
8025 if (user->acl) {
8026 /* There was host authentication and we passed, bonus! */
8027 if (bestscore < 4) {
8028 bestscore = 4;
8029 if (best)
8030 user_unref(best);
8031 best = user;
8032 continue;
8033 }
8034 } else {
8035 /* No host access, but no secret, either, not bad */
8036 if (bestscore < 3) {
8037 bestscore = 3;
8038 if (best)
8039 user_unref(best);
8040 best = user;
8041 continue;
8042 }
8043 }
8044 } else {
8045 if (user->acl) {
8046 /* Authentication, but host access too, eh, it's something.. */
8047 if (bestscore < 2) {
8048 bestscore = 2;
8049 if (best)
8050 user_unref(best);
8051 best = user;
8052 continue;
8053 }
8054 } else {
8055 /* Authentication and no host access... This is our baseline */
8056 if (bestscore < 1) {
8057 bestscore = 1;
8058 if (best)
8059 user_unref(best);
8060 best = user;
8061 continue;
8062 }
8063 }
8064 }
8065 }
8067 }
8069 user = best;
8070 if (!user && !ast_strlen_zero(iaxs[callno]->username)) {
8071 user = realtime_user(iaxs[callno]->username, addr);
8072 if (user && (ast_apply_acl(user->acl, addr, "IAX2 user ACL: ") == AST_SENSE_DENY /* Access is denied from this IP */
8073 || (!ast_strlen_zero(iaxs[callno]->context) && /* No context specified */
8074 !apply_context(user->contexts, iaxs[callno]->context)))) { /* Context is permitted */
8075 user = user_unref(user);
8076 }
8077 }
8078 if (user) {
8079 /* We found our match (use the first) */
8080 /* copy vars */
8081 for (v = user->vars ; v ; v = v->next) {
8082 if ((tmpvar = ast_variable_new(v->name, v->value, v->file))) {
8083 if (ast_variable_list_replace(&iaxs[callno]->vars, tmpvar)) {
8084 tmpvar->next = iaxs[callno]->vars;
8085 iaxs[callno]->vars = tmpvar;
8086 }
8087 }
8088 }
8089 /* If a max AUTHREQ restriction is in place, activate it */
8090 if (user->maxauthreq > 0)
8092 iaxs[callno]->prefs = user->prefs;
8094 iaxs[callno]->encmethods = user->encmethods;
8095 /* Store the requested username if not specified */
8096 if (ast_strlen_zero(iaxs[callno]->username))
8097 ast_string_field_set(iaxs[callno], username, user->name);
8098 /* Store whether this is a trunked call, too, of course, and move if appropriate */
8100 iaxs[callno]->capability = user->capability;
8101 /* And use the default context */
8102 if (ast_strlen_zero(iaxs[callno]->context)) {
8103 if (user->contexts)
8104 ast_string_field_set(iaxs[callno], context, user->contexts->context);
8105 else
8106 ast_string_field_set(iaxs[callno], context, DEFAULT_CONTEXT);
8107 }
8108 /* And any input keys */
8109 ast_string_field_set(iaxs[callno], inkeys, user->inkeys);
8110 /* And the permitted authentication methods */
8111 iaxs[callno]->authmethods = user->authmethods;
8112 iaxs[callno]->adsi = user->adsi;
8113 /* If the user has callerid, override the remote caller id. */
8115 iaxs[callno]->calling_tns = 0;
8116 iaxs[callno]->calling_ton = 0;
8117 ast_string_field_set(iaxs[callno], cid_num, user->cid_num);
8118 ast_string_field_set(iaxs[callno], cid_name, user->cid_name);
8119 ast_string_field_set(iaxs[callno], ani, user->cid_num);
8121 } else if (ast_strlen_zero(iaxs[callno]->cid_num) && ast_strlen_zero(iaxs[callno]->cid_name)) {
8123 } /* else user is allowed to set their own CID settings */
8124 if (!ast_strlen_zero(user->accountcode))
8125 ast_string_field_set(iaxs[callno], accountcode, user->accountcode);
8126 if (!ast_strlen_zero(user->mohinterpret))
8127 ast_string_field_set(iaxs[callno], mohinterpret, user->mohinterpret);
8128 if (!ast_strlen_zero(user->mohsuggest))
8129 ast_string_field_set(iaxs[callno], mohsuggest, user->mohsuggest);
8130 if (!ast_strlen_zero(user->parkinglot))
8131 ast_string_field_set(iaxs[callno], parkinglot, user->parkinglot);
8132 if (user->amaflags)
8133 iaxs[callno]->amaflags = user->amaflags;
8134 if (!ast_strlen_zero(user->language))
8135 ast_string_field_set(iaxs[callno], language, user->language);
8137 /* Keep this check last */
8138 if (!ast_strlen_zero(user->dbsecret)) {
8139 char *family, *key=NULL;
8140 char buf[80];
8141 family = ast_strdupa(user->dbsecret);
8142 key = strchr(family, '/');
8143 if (key) {
8144 *key = '\0';
8145 key++;
8146 }
8147 if (!key || ast_db_get(family, key, buf, sizeof(buf)))
8148 ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", user->dbsecret);
8149 else
8150 ast_string_field_set(iaxs[callno], secret, buf);
8151 } else
8152 ast_string_field_set(iaxs[callno], secret, user->secret);
8153 res = 0;
8154 user = user_unref(user);
8155 } else {
8156 /* user was not found, but we should still fake an AUTHREQ.
8157 * Set authmethods to the last known authmethod used by the system
8158 * Set a fake secret, it's not looked at, just required to attempt authentication.
8159 * Set authrej so the AUTHREP is rejected without even looking at its contents */
8161 ast_string_field_set(iaxs[callno], secret, "badsecret");
8162 iaxs[callno]->authrej = 1;
8163 if (!ast_strlen_zero(iaxs[callno]->username)) {
8164 /* only send the AUTHREQ if a username was specified. */
8165 res = 0;
8166 }
8167 }
8169 return res;
8170}
8171
8172static int raw_hangup(struct ast_sockaddr *addr, unsigned short src, unsigned short dst, int sockfd)
8173{
8174 struct ast_iax2_full_hdr fh;
8175 fh.scallno = htons(src | IAX_FLAG_FULL);
8176 fh.dcallno = htons(dst);
8177 fh.ts = 0;
8178 fh.oseqno = 0;
8179 fh.iseqno = 0;
8180 fh.type = AST_FRAME_IAX;
8182 iax_outputframe(NULL, &fh, 0, addr, 0);
8183
8184 ast_debug(1, "Raw Hangup %s, src=%d, dst=%d\n", ast_sockaddr_stringify(addr), src, dst);
8185 return ast_sendto(sockfd, &fh, sizeof(fh), 0, addr);
8186}
8187
8188static void merge_encryption(struct chan_iax2_pvt *p, unsigned int enc)
8189{
8190 /* Select exactly one common encryption if there are any */
8191 p->encmethods &= enc;
8192 if (p->encmethods) {
8193 if (!(p->encmethods & IAX_ENCRYPT_KEYROTATE)){ /* if key rotation is not supported, turn off keyrotation. */
8194 p->keyrotateid = -2;
8195 }
8198 else
8199 p->encmethods = 0;
8200 }
8201}
8202
8203/*!
8204 * \pre iaxsl[call_num] is locked
8205 *
8206 * \note Since this function calls send_command_final(), the pvt struct for the given
8207 * call number may disappear while executing this function.
8208 */
8209static int authenticate_request(int call_num)
8210{
8211 struct iax_ie_data ied;
8212 int res = -1, authreq_restrict = 0;
8213 char challenge[10];
8214 struct chan_iax2_pvt *p = iaxs[call_num];
8215
8216 memset(&ied, 0, sizeof(ied));
8217
8218 /* If an AUTHREQ restriction is in place, make sure we can send an AUTHREQ back */
8220 struct iax2_user *user;
8221
8223 if (user) {
8224 if (user->curauthreq == user->maxauthreq)
8225 authreq_restrict = 1;
8226 else
8227 user->curauthreq++;
8228 user = user_unref(user);
8229 }
8230 }
8231
8232 /* If the AUTHREQ limit test failed, send back an error */
8233 if (authreq_restrict) {
8234 iax_ie_append_str(&ied, IAX_IE_CAUSE, "Unauthenticated call limit reached");
8237 return 0;
8238 }
8239
8241 if (p->authmethods & (IAX_AUTH_MD5 | IAX_AUTH_RSA)) {
8242 snprintf(challenge, sizeof(challenge), "%d", (int)ast_random());
8244 /* snprintf(p->challenge, sizeof(p->challenge), "%d", (int)ast_random()); */
8246 }
8247 if (p->encmethods)
8249
8251
8252 res = send_command(p, AST_FRAME_IAX, IAX_COMMAND_AUTHREQ, 0, ied.buf, ied.pos, -1);
8253
8254 if (p->encmethods)
8256
8257 return res;
8258}
8259
8260static int authenticate_verify(struct chan_iax2_pvt *p, struct iax_ies *ies)
8261{
8262 char requeststr[256];
8263 char md5secret[256] = "";
8264 char secret[256] = "";
8265 char rsasecret[256] = "";
8266 int res = -1;
8267 int x;
8268 struct iax2_user *user;
8269
8270 if (p->authrej) {
8271 return res;
8272 }
8273
8275 if (user) {
8277 ast_atomic_fetchadd_int(&user->curauthreq, -1);
8279 }
8280 ast_string_field_set(p, host, user->name);
8281 user = user_unref(user);
8282 }
8284 ast_log(LOG_WARNING, "Call Terminated, incoming call is unencrypted while force encrypt is enabled.\n");
8285 return res;
8286 }
8288 return res;
8289 if (ies->password)
8290 ast_copy_string(secret, ies->password, sizeof(secret));
8291 if (ies->md5_result)
8292 ast_copy_string(md5secret, ies->md5_result, sizeof(md5secret));
8293 if (ies->rsa_result)
8294 ast_copy_string(rsasecret, ies->rsa_result, sizeof(rsasecret));
8295 if ((p->authmethods & IAX_AUTH_RSA) && !ast_strlen_zero(rsasecret) && !ast_strlen_zero(p->inkeys)) {
8296 struct ast_key *key;
8297 char *keyn;
8298 char *tmpkey;
8299 char *stringp=NULL;
8300 if (!(tmpkey = ast_strdup(p->inkeys))) {
8301 ast_log(LOG_ERROR, "Unable to create a temporary string for parsing stored 'inkeys'\n");
8302 return res;
8303 }
8304 stringp = tmpkey;
8305 keyn = strsep(&stringp, ":");
8306 while(keyn) {
8307 key = ast_key_get(keyn, AST_KEY_PUBLIC);
8308 if (key && !ast_check_signature(key, p->challenge, rsasecret)) {
8309 res = 0;
8311 break;
8312 } else if (!key) {
8313 ast_log(LOG_WARNING, "Requested inkey '%s' for RSA authentication does not exist\n", keyn);
8314 }
8315 keyn = strsep(&stringp, ":");
8316 }
8317 ast_free(tmpkey);
8318 if (res && authdebug) {
8319 ast_log(LOG_WARNING, "No RSA public keys on file matched incoming call\n");
8320 }
8321 } else if (p->authmethods & IAX_AUTH_MD5) {
8322 struct MD5Context md5;
8323 unsigned char digest[16];
8324 char *tmppw, *stringp;
8325 tmppw = ast_strdupa(p->secret);
8326 stringp = tmppw;
8327 while((tmppw = strsep(&stringp, ";"))) {
8328 MD5Init(&md5);
8329 MD5Update(&md5, (unsigned char *)p->challenge, strlen(p->challenge));
8330 MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
8331 MD5Final(digest, &md5);
8332 /* If they support md5, authenticate with it. */
8333 for (x=0;x<16;x++)
8334 sprintf(requeststr + (x << 1), "%02hhx", digest[x]); /* safe */
8335 if (!strcasecmp(requeststr, md5secret)) {
8336 res = 0;
8338 break;
8339 } else if (authdebug) {
8340 ast_log(LOG_WARNING, "MD5 secret mismatch\n");
8341 }
8342 }
8343 } else if (p->authmethods & IAX_AUTH_PLAINTEXT) {
8344 if (!strcmp(secret, p->secret)) {
8345 res = 0;
8347 } else if (authdebug) {
8348 ast_log(LOG_WARNING, "Plaintext secret mismatch\n");
8349 }
8350 }
8351 return res;
8352}
8353
8354/*! \brief Verify inbound registration */
8355static int register_verify(int callno, struct ast_sockaddr *addr, struct iax_ies *ies)
8356{
8357 char requeststr[256] = "";
8358 char peer[256] = "";
8359 char md5secret[256] = "";
8360 char rsasecret[256] = "";
8361 char secret[256] = "";
8362 struct iax2_peer *p = NULL;
8363 struct ast_key *key;
8364 char *keyn;
8365 int x;
8366 int expire = 0;
8367 int res = -1;
8368
8370 /* iaxs[callno]->peer[0] = '\0'; not necc. any more-- stringfield is pre-inited to null string */
8371 if (ies->username)
8372 ast_copy_string(peer, ies->username, sizeof(peer));
8373 if (ies->password)
8374 ast_copy_string(secret, ies->password, sizeof(secret));
8375 if (ies->md5_result)
8376 ast_copy_string(md5secret, ies->md5_result, sizeof(md5secret));
8377 if (ies->rsa_result)
8378 ast_copy_string(rsasecret, ies->rsa_result, sizeof(rsasecret));
8379 if (ies->refresh)
8380 expire = ies->refresh;
8381
8382 if (ast_strlen_zero(peer)) {
8383 ast_log(LOG_NOTICE, "Empty registration from %s\n", ast_sockaddr_stringify_addr(addr));
8384 return -1;
8385 }
8386
8387 /* SLD: first call to lookup peer during registration */
8388 ast_mutex_unlock(&iaxsl[callno]);
8389 p = find_peer(peer, 1);
8390 ast_mutex_lock(&iaxsl[callno]);
8391 if (!p || !iaxs[callno]) {
8392 if (iaxs[callno]) {
8393 int plaintext = ((last_authmethod & IAX_AUTH_PLAINTEXT) | (iaxs[callno]->authmethods & IAX_AUTH_PLAINTEXT));
8394 /* Anything, as long as it's non-blank */
8395 ast_string_field_set(iaxs[callno], secret, "badsecret");
8396 /* An AUTHREQ must be sent in response to a REGREQ of an invalid peer unless
8397 * 1. A challenge already exists indicating a AUTHREQ was already sent out.
8398 * 2. A plaintext secret is present in ie as result of a previous AUTHREQ requesting it.
8399 * 3. A plaintext secret is present in the ie and the last_authmethod used by a peer happened
8400 * to be plaintext, indicating it is an authmethod used by other peers on the system.
8401 *
8402 * If none of these cases exist, res will be returned as 0 without authentication indicating
8403 * an AUTHREQ needs to be sent out. */
8404
8405 if (ast_strlen_zero(iaxs[callno]->challenge) &&
8406 !(!ast_strlen_zero(secret) && plaintext)) {
8407 /* by setting res to 0, an REGAUTH will be sent */
8408 res = 0;
8409 }
8410 }
8411 if (authdebug && !p)
8412 ast_log(LOG_NOTICE, "No registration for peer '%s' (from %s)\n", peer, ast_sockaddr_stringify_addr(addr));
8413 goto return_unref;
8414 }
8415
8416 if (!ast_test_flag64(p, IAX_DYNAMIC)) {
8417 if (authdebug)
8418 ast_log(LOG_NOTICE, "Peer '%s' is not dynamic (from %s)\n", peer, ast_sockaddr_stringify_addr(addr));
8419 goto return_unref;
8420 }
8421
8422 if (!ast_apply_acl(p->acl, addr, "IAX2 Peer ACL: ")) {
8423 if (authdebug)
8424 ast_log(LOG_NOTICE, "Host %s denied access to register peer '%s'\n", ast_sockaddr_stringify_addr(addr), p->name);
8425 goto return_unref;
8426 }
8427 ast_string_field_set(iaxs[callno], secret, p->secret);
8428 ast_string_field_set(iaxs[callno], inkeys, p->inkeys);
8429 /* Check secret against what we have on file */
8430 if (!ast_strlen_zero(rsasecret) && (p->authmethods & IAX_AUTH_RSA) && !ast_strlen_zero(iaxs[callno]->challenge)) {
8431 if (!ast_strlen_zero(p->inkeys)) {
8432 char *tmpkey;
8433 char *stringp=NULL;
8434 if (!(tmpkey = ast_strdup(p->inkeys))) {
8435 ast_log(LOG_ERROR, "Unable to create a temporary string for parsing stored 'inkeys'\n");
8436 goto return_unref;
8437 }
8438 stringp = tmpkey;
8439 keyn = strsep(&stringp, ":");
8440 while(keyn) {
8441 key = ast_key_get(keyn, AST_KEY_PUBLIC);
8442 if (key && !ast_check_signature(key, iaxs[callno]->challenge, rsasecret)) {
8444 break;
8445 } else if (!key)
8446 ast_log(LOG_WARNING, "requested inkey '%s' does not exist\n", keyn);
8447 keyn = strsep(&stringp, ":");
8448 }
8449 ast_free(tmpkey);
8450 if (!keyn) {
8451 if (authdebug)
8452 ast_log(LOG_NOTICE, "Host %s failed RSA authentication with inkeys '%s'\n", peer, p->inkeys);
8453 goto return_unref;
8454 }
8455 } else {
8456 if (authdebug)
8457 ast_log(LOG_NOTICE, "Host '%s' trying to do RSA authentication, but we have no inkeys\n", peer);
8458 goto return_unref;
8459 }
8460 } else if (!ast_strlen_zero(md5secret) && (p->authmethods & IAX_AUTH_MD5) && !ast_strlen_zero(iaxs[callno]->challenge)) {
8461 struct MD5Context md5;
8462 unsigned char digest[16];
8463 char *tmppw, *stringp;
8464
8465 tmppw = ast_strdupa(p->secret);
8466 stringp = tmppw;
8467 while((tmppw = strsep(&stringp, ";"))) {
8468 MD5Init(&md5);
8469 MD5Update(&md5, (unsigned char *)iaxs[callno]->challenge, strlen(iaxs[callno]->challenge));
8470 MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
8471 MD5Final(digest, &md5);
8472 for (x=0;x<16;x++)
8473 sprintf(requeststr + (x << 1), "%02hhx", digest[x]); /* safe */
8474 if (!strcasecmp(requeststr, md5secret))
8475 break;
8476 }
8477 if (tmppw) {
8479 } else {
8480 if (authdebug)
8481 ast_log(LOG_NOTICE, "Host %s failed MD5 authentication for '%s' (%s != %s)\n", ast_sockaddr_stringify_addr(addr), p->name, requeststr, md5secret);
8482 goto return_unref;
8483 }
8484 } else if (!ast_strlen_zero(secret) && (p->authmethods & IAX_AUTH_PLAINTEXT)) {
8485 /* They've provided a plain text password and we support that */
8486 if (strcmp(secret, p->secret)) {
8487 if (authdebug)
8488 ast_log(LOG_NOTICE, "Host %s did not provide proper plaintext password for '%s'\n", ast_sockaddr_stringify_addr(addr), p->name);
8489 goto return_unref;
8490 } else
8492 } else if (!ast_strlen_zero(iaxs[callno]->challenge) && ast_strlen_zero(md5secret) && ast_strlen_zero(rsasecret)) {
8493 /* if challenge has been sent, but no challenge response if given, reject. */
8494 goto return_unref;
8495 }
8496 ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "IAX2/%s", p->name); /* Activate notification */
8497
8498 /* either Authentication has taken place, or a REGAUTH must be sent before verifying registration */
8499 res = 0;
8500
8501return_unref:
8502 if (iaxs[callno]) {
8503 ast_string_field_set(iaxs[callno], peer, peer);
8504
8505 /* Choose lowest expiry number */
8506 if (expire && (expire < iaxs[callno]->expiry)) {
8507 iaxs[callno]->expiry = expire;
8508 }
8509 }
8510
8511 if (p) {
8512 peer_unref(p);
8513 }
8514 return res;
8515}
8516
8517static int authenticate(const char *challenge, const char *secret, const char *keyn, int authmethods, struct iax_ie_data *ied, struct ast_sockaddr *addr, struct chan_iax2_pvt *pvt)
8518{
8519 int res = -1;
8520 int x;
8521 if (!ast_strlen_zero(keyn)) {
8522 if (!(authmethods & IAX_AUTH_RSA)) {
8523 if (ast_strlen_zero(secret)) {
8524 ast_log(LOG_WARNING, "Asked to authenticate to %s with an RSA key, but they don't allow RSA authentication\n", ast_sockaddr_stringify_addr(addr));
8525 }
8526 } else if (ast_strlen_zero(challenge)) {
8527 ast_log(LOG_WARNING, "No challenge provided for RSA authentication to %s\n", ast_sockaddr_stringify_addr(addr));
8528 } else {
8529 char sig[256];
8530 struct ast_key *key;
8531 key = ast_key_get(keyn, AST_KEY_PRIVATE);
8532 if (!key) {
8533 ast_log(LOG_WARNING, "Unable to find private key '%s'\n", keyn);
8534 } else {
8535 if (ast_sign(key, (char*)challenge, sig)) {
8536 ast_log(LOG_WARNING, "Unable to sign challenge with key\n");
8537 res = -1;
8538 } else {
8540 if (pvt) {
8542 }
8543 res = 0;
8544 }
8545 }
8546
8547 if (pvt && !ast_strlen_zero(secret)) {
8548 struct MD5Context md5;
8549 unsigned char digest[16];
8550
8551 MD5Init(&md5);
8552 MD5Update(&md5, (unsigned char *) challenge, strlen(challenge));
8553 MD5Update(&md5, (unsigned char *) secret, strlen(secret));
8554 MD5Final(digest, &md5);
8555
8556 build_encryption_keys(digest, pvt);
8557 }
8558 }
8559 }
8560 /* Fall back */
8561 if (res && !ast_strlen_zero(secret)) {
8562 if ((authmethods & IAX_AUTH_MD5) && !ast_strlen_zero(challenge)) {
8563 struct MD5Context md5;
8564 unsigned char digest[16];
8565 char digres[128];
8566 MD5Init(&md5);
8567 MD5Update(&md5, (unsigned char *)challenge, strlen(challenge));
8568 MD5Update(&md5, (unsigned char *)secret, strlen(secret));
8569 MD5Final(digest, &md5);
8570 /* If they support md5, authenticate with it. */
8571 for (x=0;x<16;x++)
8572 sprintf(digres + (x << 1), "%02hhx", digest[x]); /* safe */
8573 if (pvt) {
8574 build_encryption_keys(digest, pvt);
8576 }
8578 res = 0;
8579 } else if (authmethods & IAX_AUTH_PLAINTEXT) {
8580 iax_ie_append_str(ied, IAX_IE_PASSWORD, secret);
8581 if (pvt) {
8583 }
8584 res = 0;
8585 } else
8586 ast_log(LOG_WARNING, "No way to send secret to peer '%s' (their methods: %d)\n", ast_sockaddr_stringify_addr(addr), authmethods);
8587 }
8588 return res;
8589}
8590
8591/*!
8592 * \note This function calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
8593 * so do not call this function with a pvt lock held.
8594 */
8595static int authenticate_reply(struct chan_iax2_pvt *p, struct ast_sockaddr *addr, struct iax_ies *ies, const char *override, const char *okey)
8596{
8597 struct iax2_peer *peer = NULL;
8598 /* Start pessimistic */
8599 int res = -1;
8600 int authmethods = 0;
8601 struct iax_ie_data ied;
8602 uint16_t callno = p->callno;
8603
8604 memset(&ied, 0, sizeof(ied));
8605
8606 if (ies->username)
8607 ast_string_field_set(p, username, ies->username);
8608 if (ies->challenge)
8610 if (ies->authmethods)
8611 authmethods = ies->authmethods;
8612 if (authmethods & IAX_AUTH_MD5)
8614 else
8615 p->encmethods = 0;
8616
8617 /* Check for override RSA authentication first */
8618 if (!ast_strlen_zero(override) || !ast_strlen_zero(okey)) {
8619 /* Normal password authentication */
8620 res = authenticate(p->challenge, override, okey, authmethods, &ied, addr, p);
8621 } else {
8622 struct ao2_iterator i = ao2_iterator_init(peers, 0);
8623 while ((peer = ao2_iterator_next(&i))) {
8624 struct ast_sockaddr peer_addr;
8625 struct ast_sockaddr tmp_sockaddr1;
8626 struct ast_sockaddr tmp_sockaddr2;
8627
8628 ast_sockaddr_copy(&peer_addr, &peer->addr);
8629
8630 ast_sockaddr_apply_netmask(addr, &peer->mask, &tmp_sockaddr1);
8631 ast_sockaddr_apply_netmask(&peer_addr, &peer->mask, &tmp_sockaddr2);
8632
8633 if ((ast_strlen_zero(p->peer) || !strcmp(p->peer, peer->name))
8634 /* No peer specified at our end, or this is the peer */
8635 && (ast_strlen_zero(peer->username) || (!strcmp(peer->username, p->username)))
8636 /* No username specified in peer rule, or this is the right username */
8637 && (ast_sockaddr_isnull(&peer_addr) || !(ast_sockaddr_cmp_addr(&tmp_sockaddr1, &tmp_sockaddr2)))
8638 /* No specified host, or this is our host */
8639 ) {
8640 res = authenticate(p->challenge, peer->secret, peer->outkey, authmethods, &ied, addr, p);
8641 if (!res) {
8642 peer_unref(peer);
8643 break;
8644 }
8645 }
8646 peer_unref(peer);
8647 }
8649 if (!peer) {
8650 /* We checked our list and didn't find one. It's unlikely, but possible,
8651 that we're trying to authenticate *to* a realtime peer */
8652 const char *peer_name = ast_strdupa(p->peer);
8653 ast_mutex_unlock(&iaxsl[callno]);
8654 if ((peer = realtime_peer(peer_name, NULL))) {
8655 ast_mutex_lock(&iaxsl[callno]);
8656 if (!(p = iaxs[callno])) {
8657 peer_unref(peer);
8658 return -1;
8659 }
8660 res = authenticate(p->challenge, peer->secret,peer->outkey, authmethods, &ied, addr, p);
8661 peer_unref(peer);
8662 }
8663 if (!peer) {
8664 ast_mutex_lock(&iaxsl[callno]);
8665 if (!(p = iaxs[callno]))
8666 return -1;
8667 }
8668 }
8669 }
8670
8671 if (!(ies->authmethods & (IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT)) && (ies->authmethods & IAX_AUTH_RSA) && ast_strlen_zero(okey)) {
8672 /* If the only thing available is RSA, and we don't have an outkey, we can't do it... */
8673 ast_log(LOG_WARNING, "Call terminated. RSA authentication requires an outkey\n");
8674 return -1;
8675 }
8676
8677 if (ies->encmethods) {
8678 if (ast_strlen_zero(p->secret) &&
8680 ast_log(LOG_WARNING, "Call terminated. Encryption requested by peer but no secret available locally\n");
8681 return -1;
8682 }
8683 /* Don't even THINK about trying to encrypt or decrypt anything if we don't have valid keys, for some reason... */
8684 /* If either of these happens, it's our fault, not the user's. But we should abort rather than crash. */
8688 } else if (ast_test_flag64(iaxs[callno], IAX_FORCE_ENCRYPT)) {
8689 ast_log(LOG_NOTICE, "Call initiated without encryption while forceencryption=yes option is set\n");
8690 return -1; /* if force encryption is yes, and no encryption methods, then return -1 to hangup */
8691 }
8692 if (!res) {
8693 struct ast_datastore *variablestore;
8694 struct ast_variable *var, *prev = NULL;
8695 AST_LIST_HEAD(, ast_var_t) *varlist;
8696 varlist = ast_calloc(1, sizeof(*varlist));
8698 if (variablestore && varlist && p->owner) {
8699 variablestore->data = varlist;
8700 variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
8701 AST_LIST_HEAD_INIT(varlist);
8702 for (var = ies->vars; var; var = var->next) {
8703 struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
8704 if (prev)
8705 ast_free(prev);
8706 prev = var;
8707 if (!newvar) {
8708 /* Don't abort list traversal, as this would leave ies->vars in an inconsistent state. */
8709 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
8710 } else {
8711 AST_LIST_INSERT_TAIL(varlist, newvar, entries);
8712 }
8713 }
8714 if (prev)
8715 ast_free(prev);
8716 ies->vars = NULL;
8717 ast_channel_datastore_add(p->owner, variablestore);
8718 } else {
8719 if (p->owner)
8720 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
8721 if (variablestore)
8722 ast_datastore_free(variablestore);
8723 if (varlist)
8724 ast_free(varlist);
8725 }
8726 }
8727
8728 if (!res)
8729 res = send_command(p, AST_FRAME_IAX, IAX_COMMAND_AUTHREP, 0, ied.buf, ied.pos, -1);
8730 return res;
8731}
8732
8733static int iax2_do_register(struct iax2_registry *reg);
8734
8735static void __iax2_do_register_s(const void *data)
8736{
8737 struct iax2_registry *reg = (struct iax2_registry *)data;
8738
8739 if (ast_sockaddr_isnull(&reg->addr)) {
8740 reg->addr.ss.ss_family = AST_AF_UNSPEC;
8741 ast_dnsmgr_lookup(reg->hostname, &reg->addr, &reg->dnsmgr, srvlookup ? "_iax._udp" : NULL);
8742 if (!ast_sockaddr_port(&reg->addr)) {
8743 ast_sockaddr_set_port(&reg->addr, reg->port);
8744 } else {
8745 reg->port = ast_sockaddr_port(&reg->addr);
8746 }
8747 }
8748
8749 reg->expire = -1;
8750 iax2_do_register(reg);
8751}
8752
8753static int iax2_do_register_s(const void *data)
8754{
8755#ifdef SCHED_MULTITHREADED
8757#endif
8759 return 0;
8760}
8761
8762static int try_transfer(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
8763{
8764 int newcall = 0;
8765 struct iax_ie_data ied;
8766 struct ast_sockaddr new = { {0,} };
8767
8768 memset(&ied, 0, sizeof(ied));
8769 if (!ast_sockaddr_isnull(&ies->apparent_addr)) {
8770 ast_sockaddr_copy(&new, &ies->apparent_addr);
8771 }
8772 if (ies->callno) {
8773 newcall = ies->callno;
8774 }
8775 if (!newcall || ast_sockaddr_isnull(&new)) {
8776 ast_log(LOG_WARNING, "Invalid transfer request\n");
8777 return -1;
8778 }
8779 pvt->transfercallno = newcall;
8780 ast_sockaddr_copy(&pvt->transfer, &new);
8781 pvt->transferid = ies->transferid;
8782 /* only store by transfercallno if this is a new transfer,
8783 * just in case we get a duplicate TXREQ */
8784 if (pvt->transferring == TRANSFER_NONE) {
8786 }
8788
8789 if (ies->transferid) {
8791 }
8793 return 0;
8794}
8795
8796static int complete_dpreply(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
8797{
8798 char exten[256] = "";
8799 int status = CACHE_FLAG_UNKNOWN, expiry = iaxdefaultdpcache, x, matchmore = 0;
8800 struct iax2_dpcache *dp = NULL;
8801
8802 if (ies->called_number)
8803 ast_copy_string(exten, ies->called_number, sizeof(exten));
8804
8805 if (ies->dpstatus & IAX_DPSTATUS_EXISTS)
8807 else if (ies->dpstatus & IAX_DPSTATUS_CANEXIST)
8809 else if (ies->dpstatus & IAX_DPSTATUS_NONEXISTENT)
8811
8812 if (ies->refresh)
8813 expiry = ies->refresh;
8816
8819 if (strcmp(dp->exten, exten))
8820 continue;
8822 dp->callno = 0;
8823 dp->expiry.tv_sec = dp->orig.tv_sec + expiry;
8824 if (dp->flags & CACHE_FLAG_PENDING) {
8825 dp->flags &= ~CACHE_FLAG_PENDING;
8826 dp->flags |= status;
8827 dp->flags |= matchmore;
8828 }
8829 /* Wake up waiters */
8830 for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
8831 if (dp->waiters[x] > -1) {
8832 if (write(dp->waiters[x], "asdf", 4) < 0) {
8833 }
8834 }
8835 }
8836 }
8839
8840 return 0;
8841}
8842
8843static int complete_transfer(int callno, struct iax_ies *ies)
8844{
8845 int peercallno = 0;
8846 struct chan_iax2_pvt *pvt = iaxs[callno];
8847 struct iax_frame *cur;
8848 jb_frame frame;
8849
8850 if (ies->callno)
8851 peercallno = ies->callno;
8852
8853 if (peercallno < 1) {
8854 ast_log(LOG_WARNING, "Invalid transfer request\n");
8855 return -1;
8856 }
8858 /* since a transfer has taken place, the address will change.
8859 * This must be accounted for in the peercnts table. Remove
8860 * the old address and add the new one */
8862 peercnt_add(&pvt->transfer);
8863 /* now copy over the new address */
8864 memcpy(&pvt->addr, &pvt->transfer, sizeof(pvt->addr));
8865 memset(&pvt->transfer, 0, sizeof(pvt->transfer));
8866 /* Reset sequence numbers */
8867 pvt->oseqno = 0;
8868 pvt->rseqno = 0;
8869 pvt->iseqno = 0;
8870 pvt->aseqno = 0;
8871
8872 if (pvt->peercallno) {
8874 }
8875 pvt->peercallno = peercallno;
8876 /*this is where the transferring call switches hash tables */
8879 pvt->svoiceformat = -1;
8880 pvt->voiceformat = 0;
8881 pvt->svideoformat = -1;
8882 pvt->videoformat = 0;
8883 pvt->transfercallno = 0;
8884 memset(&pvt->rxcore, 0, sizeof(pvt->rxcore));
8885 memset(&pvt->offset, 0, sizeof(pvt->offset));
8886 /* reset jitterbuffer */
8887 while(jb_getall(pvt->jb,&frame) == JB_OK)
8888 iax2_frame_free(frame.data);
8889 jb_reset(pvt->jb);
8890 pvt->lag = 0;
8891 pvt->last = 0;
8892 pvt->lastsent = 0;
8893 pvt->nextpred = 0;
8896 /* We must cancel any packets that would have been transmitted
8897 because now we're talking to someone new. It's okay, they
8898 were transmitted to someone that didn't care anyway. */
8899 cur->retries = -1;
8900 }
8901 return 0;
8902}
8903
8904static void iax2_publish_registry(const char *username, const char *domain, const char *status, const char *cause)
8905{
8906 ast_system_publish_registry("IAX2", username, domain, status, cause);
8907}
8908
8909/*! \brief Acknowledgment received for OUR registration */
8910static int iax2_ack_registry(struct iax_ies *ies, struct ast_sockaddr *addr, int callno)
8911{
8912 struct iax2_registry *reg;
8913 /* Start pessimistic */
8914 char peer[256] = "";
8915 char msgstatus[60];
8916 int refresh = 60;
8917 char ourip[256] = "<Unspecified>";
8918 struct ast_sockaddr oldus;
8919 struct ast_sockaddr us;
8920 int oldmsgs;
8921
8922 if (!ast_sockaddr_isnull(&ies->apparent_addr)) {
8923 ast_sockaddr_copy(&us, &ies->apparent_addr);
8924 }
8925 if (ies->username) {
8926 ast_copy_string(peer, ies->username, sizeof(peer));
8927 }
8928 if (ies->refresh) {
8929 refresh = ies->refresh;
8930 }
8931 if (ies->calling_number) {
8932 /* We don't do anything with it really, but maybe we should */
8933 }
8934 reg = iaxs[callno]->reg;
8935 if (!reg) {
8936 ast_log(LOG_WARNING, "Registry acknowledge on unknown registry '%s'\n", peer);
8937 return -1;
8938 }
8939 ast_sockaddr_copy(&oldus, &reg->us);
8940 oldmsgs = reg->messages;
8941 if (ast_sockaddr_cmp(&reg->addr, addr)) {
8942 ast_log(LOG_WARNING, "Received unsolicited registry ack from '%s'\n", ast_sockaddr_stringify(addr));
8943 return -1;
8944 }
8945 ast_sockaddr_copy(&reg->us, &us);
8946 if (ies->msgcount >= 0) {
8947 reg->messages = ies->msgcount & 0xffff; /* only low 16 bits are used in the transmission of the IE */
8948 }
8949 /* always refresh the registration at the interval requested by the server
8950 we are registering to
8951 */
8952 reg->refresh = refresh;
8954 (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
8955 if (ast_sockaddr_cmp(&oldus, &reg->us) || (reg->messages != oldmsgs)) {
8956
8957 if (reg->messages > 255) {
8958 snprintf(msgstatus, sizeof(msgstatus), " with %d new and %d old messages waiting", reg->messages & 0xff, reg->messages >> 8);
8959 } else if (reg->messages > 1) {
8960 snprintf(msgstatus, sizeof(msgstatus), " with %d new messages waiting", reg->messages);
8961 } else if (reg->messages > 0) {
8962 ast_copy_string(msgstatus, " with 1 new message waiting", sizeof(msgstatus));
8963 } else {
8964 ast_copy_string(msgstatus, " with no messages waiting", sizeof(msgstatus));
8965 }
8966
8967 snprintf(ourip, sizeof(ourip), "%s", ast_sockaddr_stringify(&reg->us));
8968
8969 ast_verb(3, "Registered IAX2 to '%s', who sees us as %s%s\n", ast_sockaddr_stringify(addr), ourip, msgstatus);
8970 iax2_publish_registry(reg->username, ast_sockaddr_stringify(addr), "Registered", NULL);
8971 }
8973 return 0;
8974}
8975
8976static int iax2_append_register(const char *hostname, const char *username,
8977 const char *secret, const char *porta)
8978{
8979 struct iax2_registry *reg;
8980
8981 if (!(reg = ast_calloc(1, sizeof(*reg) + strlen(hostname) + 1))) {
8982 return -1;
8983 }
8984
8985 reg->addr.ss.ss_family = AST_AF_UNSPEC;
8986 if (ast_dnsmgr_lookup(hostname, &reg->addr, &reg->dnsmgr, srvlookup ? "_iax._udp" : NULL) < 0) {
8987 ast_free(reg);
8988 return -1;
8989 }
8990
8991 ast_copy_string(reg->username, username, sizeof(reg->username));
8992 strcpy(reg->hostname, hostname); /* Note: This is safe */
8993
8994 if (secret) {
8995 ast_copy_string(reg->secret, secret, sizeof(reg->secret));
8996 }
8997
8998 reg->expire = -1;
9000
9001 reg->port = ast_sockaddr_port(&reg->addr);
9002
9003 if (!porta && !reg->port) {
9004 reg->port = IAX_DEFAULT_PORTNO;
9005 } else if (porta) {
9006 sscanf(porta, "%5d", &reg->port);
9007 }
9008
9009 ast_sockaddr_set_port(&reg->addr, reg->port);
9010
9014
9015 return 0;
9016}
9017
9018static int iax2_register(const char *value, int lineno)
9019{
9020 char copy[256];
9021 char *username, *hostname, *secret;
9022 char *porta;
9023 char *stringp=NULL;
9024
9025 if (!value)
9026 return -1;
9027
9028 ast_copy_string(copy, value, sizeof(copy));
9029 stringp = copy;
9030 username = strsep(&stringp, "@");
9031 hostname = strsep(&stringp, "@");
9032
9033 if (!hostname) {
9034 ast_log(LOG_WARNING, "Format for registration is user[:secret]@host[:port] at line %d\n", lineno);
9035 return -1;
9036 }
9037
9038 stringp = username;
9039 username = strsep(&stringp, ":");
9040 secret = strsep(&stringp, ":");
9041 stringp = hostname;
9042 hostname = strsep(&stringp, ":");
9043 porta = strsep(&stringp, ":");
9044
9045 if (porta && !atoi(porta)) {
9046 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
9047 return -1;
9048 }
9049
9051}
9052
9053
9054static void register_peer_exten(struct iax2_peer *peer, int onoff)
9055{
9056 char multi[256];
9057 char *stringp, *ext;
9059 ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
9060 stringp = multi;
9061 while((ext = strsep(&stringp, "&"))) {
9062 if (onoff) {
9065 "Noop", ast_strdup(peer->name), ast_free_ptr, "IAX2");
9066 } else
9068 }
9069 }
9070}
9071static void prune_peers(void);
9072
9073static void unlink_peer(struct iax2_peer *peer)
9074{
9075 if (peer->expire > -1) {
9076 if (!AST_SCHED_DEL(sched, peer->expire)) {
9077 peer->expire = -1;
9078 peer_unref(peer);
9079 }
9080 }
9081
9082 if (peer->pokeexpire > -1) {
9083 if (!AST_SCHED_DEL(sched, peer->pokeexpire)) {
9084 peer->pokeexpire = -1;
9085 peer_unref(peer);
9086 }
9087 }
9088
9089 ao2_unlink(peers, peer);
9090}
9091
9092static void __expire_registry(const void *data)
9093{
9094 struct iax2_peer *peer = (struct iax2_peer *) data;
9095 RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
9096
9097 if (!peer)
9098 return;
9099 if (peer->expire == -1) {
9100 /* Removed already (possibly through CLI), ignore */
9101 return;
9102 }
9103
9104 peer->expire = -1;
9105
9106 ast_debug(1, "Expiring registration for peer '%s'\n", peer->name);
9108 realtime_update_peer(peer->name, &peer->addr, 0);
9110 blob = ast_json_pack("{s: s, s: s}",
9111 "peer_status", "Unregistered",
9112 "cause", "Expired");
9114 /* modify entry in peercnts table as _not_ registered */
9115 peercnt_modify((unsigned char) 0, 0, &peer->addr);
9116 /* Reset the address */
9117 ast_sockaddr_setnull(&peer->addr);
9118 /* Reset expiry value */
9119 peer->expiry = min_reg_expire;
9120 if (!ast_test_flag64(peer, IAX_TEMPONLY))
9121 ast_db_del("IAX/Registry", peer->name);
9122 register_peer_exten(peer, 0);
9123 ast_devstate_changed(AST_DEVICE_UNAVAILABLE, AST_DEVSTATE_CACHABLE, "IAX2/%s", peer->name); /* Activate notification */
9124 if (iax2_regfunk)
9125 iax2_regfunk(peer->name, 0);
9126
9128 unlink_peer(peer);
9129
9130 peer_unref(peer);
9131}
9132
9133static int expire_registry(const void *data)
9134{
9135#ifdef SCHED_MULTITHREADED
9137#endif
9138 __expire_registry(data);
9139 return 0;
9140}
9141
9142static void reg_source_db(struct iax2_peer *p)
9143{
9144 char data[80];
9145 char *expiry;
9146
9147 if (ast_test_flag64(p, IAX_TEMPONLY) || ast_db_get("IAX/Registry", p->name, data, sizeof(data))) {
9148 return;
9149 }
9150
9151 expiry = strrchr(data, ':');
9152 if (!expiry) {
9153 ast_log(LOG_NOTICE, "IAX/Registry astdb entry missing expiry: '%s'\n", data);
9154 return;
9155 }
9156 *expiry++ = '\0';
9157
9158 if (!ast_sockaddr_parse(&p->addr, data, PARSE_PORT_REQUIRE)) {
9159 ast_log(LOG_NOTICE, "IAX/Registry astdb host:port invalid - '%s'\n", data);
9160 return;
9161 }
9162
9163 p->expiry = atoi(expiry);
9164
9165 ast_verb(3, "Seeding '%s' at %s for %d\n", p->name,
9167
9168 iax2_poke_peer(p, 0);
9169 if (p->expire > -1) {
9170 if (!AST_SCHED_DEL(sched, p->expire)) {
9171 p->expire = -1;
9172 peer_unref(p);
9173 }
9174 }
9175
9176 ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "IAX2/%s", p->name); /* Activate notification */
9177
9178 p->expire = iax2_sched_add(sched, (p->expiry + 10) * 1000, expire_registry, peer_ref(p));
9179 if (p->expire == -1) {
9180 peer_unref(p);
9181 }
9182
9183 if (iax2_regfunk) {
9184 iax2_regfunk(p->name, 1);
9185 }
9186
9187 register_peer_exten(p, 1);
9188}
9189
9190/*!
9191 * \pre iaxsl[callno] is locked
9192 *
9193 * \note Since this function calls send_command_final(), the pvt struct for
9194 * the given call number may disappear while executing this function.
9195 */
9196static int update_registry(struct ast_sockaddr *addr, int callno, char *devtype, int fd, unsigned short refresh)
9197{
9198
9199 /* Called from IAX thread only, with proper iaxsl lock */
9200 struct iax_ie_data ied = {
9201 .pos = 0,
9202 };
9203 struct iax2_peer *p;
9204 int msgcount;
9205 char data[80];
9206 uint16_t version;
9207 const char *peer_name;
9208 int res = -1;
9209 char *str_addr;
9210
9211 peer_name = ast_strdupa(iaxs[callno]->peer);
9212
9213 /* SLD: Another find_peer call during registration - this time when we are really updating our registration */
9215 if (!(p = find_peer(peer_name, 1))) {
9217 ast_log(LOG_WARNING, "No such peer '%s'\n", peer_name);
9218 return -1;
9219 }
9221 if (!iaxs[callno])
9222 goto return_unref;
9223
9225 if (!ast_sockaddr_isnull(addr)) {
9226 time_t nowtime;
9227 time(&nowtime);
9228 realtime_update_peer(peer_name, addr, nowtime);
9229 } else {
9230 realtime_update_peer(peer_name, addr, 0);
9231 }
9232 }
9233
9234 /* treat an unspecified refresh interval as the minimum */
9235 if (!refresh) {
9237 }
9238 if (refresh > max_reg_expire) {
9239 ast_log(LOG_NOTICE, "Restricting registration for peer '%s' to %d seconds (requested %d)\n",
9242 } else if (refresh < min_reg_expire) {
9243 ast_log(LOG_NOTICE, "Restricting registration for peer '%s' to %d seconds (requested %d)\n",
9246 } else {
9247 p->expiry = refresh;
9248 }
9249
9250 if (ast_sockaddr_cmp(&p->addr, addr)) {
9251 RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
9252
9253 if (iax2_regfunk) {
9254 iax2_regfunk(p->name, 1);
9255 }
9256
9257 /* modify entry in peercnts table as _not_ registered */
9258 peercnt_modify((unsigned char) 0, 0, &p->addr);
9259
9260 /* Stash the IP address from which they registered */
9262
9264
9265 snprintf(data, sizeof(data), "%s:%d", ast_sockaddr_stringify(addr), p->expiry);
9266
9268 ast_db_put("IAX/Registry", p->name, data);
9269 ast_verb(3, "Registered IAX2 '%s' (%s) at %s\n",
9270 p->name,
9271 ast_test_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED) ? "AUTHENTICATED" : "UNAUTHENTICATED",
9274 blob = ast_json_pack("{s: s, s: s, s: i}",
9275 "peer_status", "Registered",
9276 "address", str_addr,
9277 "port", ast_sockaddr_port(addr));
9278 register_peer_exten(p, 1);
9279 ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "IAX2/%s", p->name); /* Activate notification */
9280 } else if (!ast_test_flag64(p, IAX_TEMPONLY)) {
9281 ast_verb(3, "Unregistered IAX2 '%s' (%s)\n",
9282 p->name,
9283 ast_test_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED) ? "AUTHENTICATED" : "UNAUTHENTICATED");
9285 blob = ast_json_pack("{s: s}",
9286 "peer_status", "Unregistered");
9287 register_peer_exten(p, 0);
9288 ast_db_del("IAX/Registry", p->name);
9289 ast_devstate_changed(AST_DEVICE_UNAVAILABLE, AST_DEVSTATE_CACHABLE, "IAX2/%s", p->name); /* Activate notification */
9290 }
9291
9293
9294 /* Update the host */
9295 /* Verify that the host is really there */
9297 }
9298
9299 /* modify entry in peercnts table as registered */
9300 if (p->maxcallno) {
9301 peercnt_modify((unsigned char) 1, p->maxcallno, &p->addr);
9302 }
9303
9304 /* Make sure our call still exists, an INVAL at the right point may make it go away */
9305 if (!iaxs[callno]) {
9306 res = -1;
9307 goto return_unref;
9308 }
9309
9310 /* Store socket fd */
9311 p->sockfd = fd;
9312 /* Setup the expiry */
9313 if (p->expire > -1) {
9314 if (!AST_SCHED_DEL(sched, p->expire)) {
9315 p->expire = -1;
9316 peer_unref(p);
9317 }
9318 }
9319
9320 if (p->expiry && !ast_sockaddr_isnull(addr)) {
9321 p->expire = iax2_sched_add(sched, (p->expiry + 10) * 1000, expire_registry, peer_ref(p));
9322 if (p->expire == -1)
9323 peer_unref(p);
9324 }
9327 if (!ast_sockaddr_isnull(addr)) {
9328 struct ast_sockaddr peer_addr;
9329
9330 ast_sockaddr_copy(&peer_addr, &p->addr);
9331
9333 iax_ie_append_addr(&ied, IAX_IE_APPARENT_ADDR, &peer_addr);
9334 if (!ast_strlen_zero(p->mailbox)) {
9335 int new, old;
9336 RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
9337
9339 if (msg) {
9340 struct ast_mwi_state *mwi_state = stasis_message_data(msg);
9341 new = mwi_state->new_msgs;
9342 old = mwi_state->old_msgs;
9343 } else { /* Fall back on checking the mailbox directly */
9344 ast_app_inboxcount(p->mailbox, &new, &old);
9345 }
9346
9347 if (new > 255) {
9348 new = 255;
9349 }
9350 if (old > 255) {
9351 old = 255;
9352 }
9353 msgcount = (old << 8) | new;
9354
9355 iax_ie_append_short(&ied, IAX_IE_MSGCOUNT, msgcount);
9356 }
9360 }
9361 }
9362 if (iax_firmware_get_version(devtype, &version)) {
9364 }
9365
9366 res = 0;
9367
9368return_unref:
9369 peer_unref(p);
9370
9371 return res ? res : send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGACK, 0, ied.buf, ied.pos, -1);
9372}
9373
9374static int registry_authrequest(int callno)
9375{
9376 struct iax_ie_data ied;
9377 struct iax2_peer *p;
9378 char challenge[10];
9379 const char *peer_name;
9380 int sentauthmethod;
9381
9382 peer_name = ast_strdupa(iaxs[callno]->peer);
9383
9384 /* SLD: third call to find_peer in registration */
9386 if ((p = find_peer(peer_name, 1))) {
9388 }
9389
9391 if (!iaxs[callno])
9392 goto return_unref;
9393
9394 memset(&ied, 0, sizeof(ied));
9395 /* The selection of which delayed reject is sent may leak information,
9396 * if it sets a static response. For example, if a host is known to only
9397 * use MD5 authentication, then an RSA response would indicate that the
9398 * peer does not exist, and vice-versa.
9399 * Therefore, we use whatever the last peer used (which may vary over the
9400 * course of a server, which should leak minimal information). */
9401 sentauthmethod = p ? p->authmethods : last_authmethod ? last_authmethod : IAX_AUTH_MD5;
9402 if (!p) {
9403 iaxs[callno]->authmethods = sentauthmethod;
9404 }
9405 iax_ie_append_short(&ied, IAX_IE_AUTHMETHODS, sentauthmethod);
9406 if (sentauthmethod & (IAX_AUTH_RSA | IAX_AUTH_MD5)) {
9407 /* Build the challenge */
9408 snprintf(challenge, sizeof(challenge), "%d", (int)ast_random());
9411 }
9412 iax_ie_append_str(&ied, IAX_IE_USERNAME, peer_name);
9413
9414return_unref:
9415 if (p) {
9416 peer_unref(p);
9417 }
9418
9419 return iaxs[callno] ? send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGAUTH, 0, ied.buf, ied.pos, -1) : -1;
9420}
9421
9422static int registry_rerequest(struct iax_ies *ies, int callno, struct ast_sockaddr *addr)
9423{
9424 struct iax2_registry *reg;
9425 /* Start pessimistic */
9426 struct iax_ie_data ied;
9427 char peer[256] = "";
9428 char challenge[256] = "";
9429 int res;
9430 int authmethods = 0;
9431 if (ies->authmethods)
9432 authmethods = ies->authmethods;
9433 if (ies->username)
9434 ast_copy_string(peer, ies->username, sizeof(peer));
9435 if (ies->challenge)
9437 memset(&ied, 0, sizeof(ied));
9438 reg = iaxs[callno]->reg;
9439 if (reg) {
9440
9441 if (ast_sockaddr_cmp(&reg->addr, addr)) {
9442 ast_log(LOG_WARNING, "Received unsolicited registry authenticate request from '%s'\n", ast_sockaddr_stringify(addr));
9443 return -1;
9444 }
9445 if (ast_strlen_zero(reg->secret)) {
9446 ast_log(LOG_NOTICE, "No secret associated with peer '%s'\n", reg->username);
9448 return -1;
9449 }
9452 if (reg->secret[0] == '[') {
9453 char tmpkey[256];
9454 ast_copy_string(tmpkey, reg->secret + 1, sizeof(tmpkey));
9455 tmpkey[strlen(tmpkey) - 1] = '\0';
9456 res = authenticate(challenge, NULL, tmpkey, authmethods, &ied, addr, NULL);
9457 } else
9458 res = authenticate(challenge, reg->secret, NULL, authmethods, &ied, addr, NULL);
9459 if (!res) {
9461 add_empty_calltoken_ie(iaxs[callno], &ied); /* this _MUST_ be the last ie added */
9462 return send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGREQ, 0, ied.buf, ied.pos, -1);
9463 } else
9464 return -1;
9465 ast_log(LOG_WARNING, "Registry acknowledge on unknown registry '%s'\n", peer);
9466 } else
9467 ast_log(LOG_NOTICE, "Can't reregister without a reg\n");
9468 return -1;
9469}
9470
9471static void stop_stuff(int callno)
9472{
9473 iax2_destroy_helper(iaxs[callno]);
9474}
9475
9476static void __auth_reject(const void *nothing)
9477{
9478 /* Called from IAX thread only, without iaxs lock */
9479 int callno = (int)(long)(nothing);
9480 struct iax_ie_data ied;
9481 ast_mutex_lock(&iaxsl[callno]);
9482 if (iaxs[callno]) {
9483 memset(&ied, 0, sizeof(ied));
9484 if (iaxs[callno]->authfail == IAX_COMMAND_REGREJ) {
9485 iax_ie_append_str(&ied, IAX_IE_CAUSE, "Registration Refused");
9487 } else if (iaxs[callno]->authfail == IAX_COMMAND_REJECT) {
9488 iax_ie_append_str(&ied, IAX_IE_CAUSE, "No authority found");
9490 }
9491 send_command_final(iaxs[callno], AST_FRAME_IAX, iaxs[callno]->authfail, 0, ied.buf, ied.pos, -1);
9492 }
9493 ast_mutex_unlock(&iaxsl[callno]);
9494}
9495
9496static int auth_reject(const void *data)
9497{
9498 int callno = (int)(long)(data);
9499 ast_mutex_lock(&iaxsl[callno]);
9500 if (iaxs[callno])
9501 iaxs[callno]->authid = -1;
9502 ast_mutex_unlock(&iaxsl[callno]);
9503#ifdef SCHED_MULTITHREADED
9504 if (schedule_action(__auth_reject, data))
9505#endif
9506 __auth_reject(data);
9507 return 0;
9508}
9509
9510static int auth_fail(int callno, int failcode)
9511{
9512 /* Schedule sending the authentication failure in one second, to prevent
9513 guessing */
9514 if (iaxs[callno]) {
9515 iaxs[callno]->authfail = failcode;
9516 if (delayreject) {
9517 iaxs[callno]->authid = iax2_sched_replace(iaxs[callno]->authid,
9518 sched, 1000, auth_reject, (void *)(long)callno);
9519 } else
9520 auth_reject((void *)(long)callno);
9521 }
9522 return 0;
9523}
9524
9525static void __auto_hangup(const void *nothing)
9526{
9527 /* Called from IAX thread only, without iaxs lock */
9528 int callno = (int)(long)(nothing);
9529 struct iax_ie_data ied;
9530 ast_mutex_lock(&iaxsl[callno]);
9531 if (iaxs[callno]) {
9532 memset(&ied, 0, sizeof(ied));
9533 iax_ie_append_str(&ied, IAX_IE_CAUSE, "Timeout");
9535 send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1);
9536 }
9537 ast_mutex_unlock(&iaxsl[callno]);
9538}
9539
9540static int auto_hangup(const void *data)
9541{
9542 int callno = (int)(long)(data);
9543 ast_mutex_lock(&iaxsl[callno]);
9544 if (iaxs[callno]) {
9545 iaxs[callno]->autoid = -1;
9546 }
9547 ast_mutex_unlock(&iaxsl[callno]);
9548#ifdef SCHED_MULTITHREADED
9549 if (schedule_action(__auto_hangup, data))
9550#endif
9551 __auto_hangup(data);
9552 return 0;
9553}
9554
9555static void iax2_dprequest(struct iax2_dpcache *dp, int callno)
9556{
9557 struct iax_ie_data ied;
9558 /* Auto-hangup with 30 seconds of inactivity */
9559 iaxs[callno]->autoid = iax2_sched_replace(iaxs[callno]->autoid,
9560 sched, 30000, auto_hangup, (void *)(long)callno);
9561 memset(&ied, 0, sizeof(ied));
9563 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_DPREQ, 0, ied.buf, ied.pos, -1);
9565}
9566
9567static int iax2_vnak(int callno)
9568{
9569 return send_command_immediate(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_VNAK, 0, NULL, 0, iaxs[callno]->iseqno);
9570}
9571
9572static void vnak_retransmit(int callno, int last)
9573{
9574 struct iax_frame *f;
9575
9577 /* Send a copy immediately */
9578 if (((unsigned char) (f->oseqno - last) < 128) &&
9579 (f->retries >= 0)) {
9580 send_packet(f);
9581 }
9582 }
9583}
9584
9585static void __iax2_poke_peer_s(const void *data)
9586{
9587 struct iax2_peer *peer = (struct iax2_peer *)data;
9588 iax2_poke_peer(peer, 0);
9589 peer_unref(peer);
9590}
9591
9592static int iax2_poke_peer_s(const void *data)
9593{
9594 struct iax2_peer *peer = (struct iax2_peer *)data;
9595 peer->pokeexpire = -1;
9596#ifdef SCHED_MULTITHREADED
9598#endif
9599 __iax2_poke_peer_s(data);
9600 return 0;
9601}
9602
9603static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now)
9604{
9605 int res = 0;
9606 struct iax_frame *fr;
9607 struct ast_iax2_meta_hdr *meta;
9608 struct ast_iax2_meta_trunk_hdr *mth;
9609 int calls = 0;
9610
9611 /* Point to frame */
9612 fr = (struct iax_frame *)tpeer->trunkdata;
9613 /* Point to meta data */
9614 meta = (struct ast_iax2_meta_hdr *)fr->afdata;
9615 mth = (struct ast_iax2_meta_trunk_hdr *)meta->data;
9616 if (tpeer->trunkdatalen) {
9617 /* We're actually sending a frame, so fill the meta trunk header and meta header */
9618 meta->zeros = 0;
9619 meta->metacmd = IAX_META_TRUNK;
9621 meta->cmddata = IAX_META_TRUNK_MINI;
9622 else
9623 meta->cmddata = IAX_META_TRUNK_SUPERMINI;
9624 mth->ts = htonl(calc_txpeerstamp(tpeer, trunkfreq, now));
9625 /* And the rest of the ast_iax2 header */
9627 fr->retrans = -1;
9628 fr->transfer = 0;
9629 /* Any appropriate call will do */
9630 fr->data = fr->afdata;
9631 fr->datalen = tpeer->trunkdatalen + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr);
9632 res = transmit_trunk(fr, &tpeer->addr, tpeer->sockfd);
9633 calls = tpeer->calls;
9634#if 0
9635 ast_debug(1, "Trunking %d call chunks in %d bytes to %s:%d, ts=%d\n", calls, fr->datalen, ast_inet_ntoa(tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port), ntohl(mth->ts));
9636#endif
9637 /* Reset transmit trunk side data */
9638 tpeer->trunkdatalen = 0;
9639 tpeer->calls = 0;
9640 }
9641 if (res < 0)
9642 return res;
9643 return calls;
9644}
9645
9646static inline int iax2_trunk_expired(struct iax2_trunk_peer *tpeer, struct timeval *now)
9647{
9648 /* Drop when trunk is about 5 seconds idle */
9649 if (now->tv_sec > tpeer->trunkact.tv_sec + 5)
9650 return 1;
9651 return 0;
9652}
9653
9654static int timing_read(int *id, int fd, short events, void *cbdata)
9655{
9656 int res, processed = 0, totalcalls = 0;
9657 struct iax2_trunk_peer *tpeer = NULL, *drop = NULL;
9658 struct timeval now = ast_tvnow();
9659
9660 if (iaxtrunkdebug) {
9661 ast_verbose("Beginning trunk processing. Trunk queue ceiling is %d bytes per host\n", trunkmaxsize);
9662 }
9663
9664 if (timer) {
9665 if (ast_timer_ack(timer, 1) < 0) {
9666 ast_log(LOG_ERROR, "Timer failed acknowledge\n");
9667 return 0;
9668 }
9669 }
9670
9671 /* For each peer that supports trunking... */
9673 AST_LIST_TRAVERSE_SAFE_BEGIN(&tpeers, tpeer, list) {
9674 processed++;
9675 res = 0;
9676 ast_mutex_lock(&tpeer->lock);
9677 /* We can drop a single tpeer per pass. That makes all this logic
9678 substantially easier */
9679 if (!drop && iax2_trunk_expired(tpeer, &now)) {
9680 /* Take it out of the list, but don't free it yet, because it
9681 could be in use */
9683 drop = tpeer;
9684 } else {
9685 res = send_trunk(tpeer, &now);
9686 trunk_timed++;
9687 if (iaxtrunkdebug) {
9688 ast_verbose(" - Trunk peer (%s) has %d call chunk%s in transit, %u bytes backlogged and has hit a high water mark of %u bytes\n",
9690 res,
9691 (res != 1) ? "s" : "",
9692 tpeer->trunkdatalen,
9693 tpeer->trunkdataalloc);
9694 }
9695 }
9696 totalcalls += res;
9697 res = 0;
9698 ast_mutex_unlock(&tpeer->lock);
9699 }
9702
9703 if (drop) {
9704 ast_mutex_lock(&drop->lock);
9705 /* Once we have this lock, we're sure nobody else is using it or could use it once we release it,
9706 because by the time they could get tpeerlock, we've already grabbed it */
9707 ast_debug(1, "Dropping unused iax2 trunk peer '%s'\n", ast_sockaddr_stringify(&drop->addr));
9708 if (drop->trunkdata) {
9709 ast_free(drop->trunkdata);
9710 drop->trunkdata = NULL;
9711 }
9712 ast_mutex_unlock(&drop->lock);
9713 ast_mutex_destroy(&drop->lock);
9714 ast_free(drop);
9715 }
9716
9717 if (iaxtrunkdebug) {
9718 ast_verbose("Ending trunk processing with %d peers and %d call chunks processed\n", processed, totalcalls);
9719 }
9720 iaxtrunkdebug = 0;
9721
9722 return 1;
9723}
9724
9725struct dpreq_data {
9726 int callno;
9729 char *callerid;
9730};
9731
9732static void dp_lookup(int callno, const char *context, const char *callednum, const char *callerid, int skiplock)
9733{
9734 unsigned short dpstatus = 0;
9735 struct iax_ie_data ied1;
9736 int mm;
9737
9738 memset(&ied1, 0, sizeof(ied1));
9739 mm = ast_matchmore_extension(NULL, context, callednum, 1, callerid);
9740 /* Must be started */
9741 if (ast_exists_extension(NULL, context, callednum, 1, callerid)) {
9742 dpstatus = IAX_DPSTATUS_EXISTS;
9743 } else if (ast_canmatch_extension(NULL, context, callednum, 1, callerid)) {
9744 dpstatus = IAX_DPSTATUS_CANEXIST;
9745 } else {
9746 dpstatus = IAX_DPSTATUS_NONEXISTENT;
9747 }
9748 if (ast_ignore_pattern(context, callednum))
9749 dpstatus |= IAX_DPSTATUS_IGNOREPAT;
9750 if (mm)
9751 dpstatus |= IAX_DPSTATUS_MATCHMORE;
9752 if (!skiplock)
9753 ast_mutex_lock(&iaxsl[callno]);
9754 if (iaxs[callno]) {
9755 iax_ie_append_str(&ied1, IAX_IE_CALLED_NUMBER, callednum);
9756 iax_ie_append_short(&ied1, IAX_IE_DPSTATUS, dpstatus);
9758 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_DPREP, 0, ied1.buf, ied1.pos, -1);
9759 }
9760 if (!skiplock)
9761 ast_mutex_unlock(&iaxsl[callno]);
9762}
9763
9764static void *dp_lookup_thread(void *data)
9765{
9766 /* Look up for dpreq */
9767 struct dpreq_data *dpr = data;
9768 dp_lookup(dpr->callno, dpr->context, dpr->callednum, dpr->callerid, 0);
9769 if (dpr->callerid)
9770 ast_free(dpr->callerid);
9771 ast_free(dpr);
9772 return NULL;
9773}
9774
9775static void spawn_dp_lookup(int callno, const char *context, const char *callednum, const char *callerid)
9776{
9777 pthread_t newthread;
9778 struct dpreq_data *dpr;
9779
9780 if (!(dpr = ast_calloc(1, sizeof(*dpr))))
9781 return;
9782
9783 dpr->callno = callno;
9784 ast_copy_string(dpr->context, context, sizeof(dpr->context));
9785 ast_copy_string(dpr->callednum, callednum, sizeof(dpr->callednum));
9786 if (callerid)
9788 if (ast_pthread_create_detached(&newthread, NULL, dp_lookup_thread, dpr)) {
9789 ast_log(LOG_WARNING, "Unable to start lookup thread!\n");
9790 }
9791}
9792
9793static int check_provisioning(struct ast_sockaddr *addr, int sockfd, char *si, unsigned int ver)
9794{
9795 unsigned int ourver;
9796 char rsi[80];
9797 snprintf(rsi, sizeof(rsi), "si-%s", si);
9798 if (iax_provision_version(&ourver, rsi, 1))
9799 return 0;
9800 ast_debug(1, "Service identifier '%s', we think '%08x', they think '%08x'\n", si, ourver, ver);
9801 if (ourver != ver)
9802 iax2_provision(addr, sockfd, NULL, rsi, 1);
9803 return 0;
9804}
9805
9806static void construct_rr(struct chan_iax2_pvt *pvt, struct iax_ie_data *iep)
9807{
9808 jb_info stats;
9809 jb_getinfo(pvt->jb, &stats);
9810
9811 memset(iep, 0, sizeof(*iep));
9812
9814 if(stats.frames_in == 0) stats.frames_in = 1;
9815 iax_ie_append_int(iep,IAX_IE_RR_LOSS, ((0xff & (stats.losspct/1000)) << 24 | (stats.frames_lost & 0x00ffffff)));
9817 iax_ie_append_short(iep,IAX_IE_RR_DELAY, stats.current - stats.min);
9820}
9821
9822static void save_rr(struct iax_frame *fr, struct iax_ies *ies)
9823{
9824 iaxs[fr->callno]->remote_rr.jitter = ies->rr_jitter;
9825 iaxs[fr->callno]->remote_rr.losspct = ies->rr_loss >> 24;
9826 iaxs[fr->callno]->remote_rr.losscnt = ies->rr_loss & 0xffffff;
9827 iaxs[fr->callno]->remote_rr.packets = ies->rr_pkts;
9828 iaxs[fr->callno]->remote_rr.delay = ies->rr_delay;
9829 iaxs[fr->callno]->remote_rr.dropped = ies->rr_dropped;
9830 iaxs[fr->callno]->remote_rr.ooo = ies->rr_ooo;
9831}
9832
9833static void save_osptoken(struct iax_frame *fr, struct iax_ies *ies)
9834{
9835 int i;
9836 unsigned int length, offset = 0;
9837 char full_osptoken[IAX_MAX_OSPBUFF_SIZE];
9838
9839 for (i = 0; i < IAX_MAX_OSPBLOCK_NUM; i++) {
9840 length = ies->ospblocklength[i];
9841 if (length != 0) {
9842 if (length > IAX_MAX_OSPBLOCK_SIZE) {
9843 /* OSP token block length wrong, clear buffer */
9844 offset = 0;
9845 break;
9846 } else {
9847 memcpy(full_osptoken + offset, ies->osptokenblock[i], length);
9848 offset += length;
9849 }
9850 } else {
9851 break;
9852 }
9853 }
9854 *(full_osptoken + offset) = '\0';
9855 if (strlen(full_osptoken) != offset) {
9856 /* OSP token length wrong, clear buffer */
9857 *full_osptoken = '\0';
9858 }
9859
9860 ast_string_field_set(iaxs[fr->callno], osptoken, full_osptoken);
9861}
9862
9863static void log_jitterstats(unsigned short callno)
9864{
9865 int localjitter = -1, localdelay = 0, locallost = -1, locallosspct = -1, localdropped = 0, localooo = -1, localpackets = -1;
9866 jb_info jbinfo;
9867
9869 if (iaxs[callno] && iaxs[callno]->owner && ast_channel_name(iaxs[callno]->owner)) {
9871 jb_getinfo(iaxs[callno]->jb, &jbinfo);
9872 localjitter = jbinfo.jitter;
9873 localdelay = jbinfo.current - jbinfo.min;
9874 locallost = jbinfo.frames_lost;
9875 locallosspct = jbinfo.losspct/1000;
9876 localdropped = jbinfo.frames_dropped;
9877 localooo = jbinfo.frames_ooo;
9878 localpackets = jbinfo.frames_in;
9879 }
9880 ast_debug(3, "JB STATS:%s ping=%u ljitterms=%d ljbdelayms=%d ltotlost=%d lrecentlosspct=%d ldropped=%d looo=%d lrecvd=%d rjitterms=%d rjbdelayms=%d rtotlost=%d rrecentlosspct=%d rdropped=%d rooo=%d rrecvd=%d\n",
9881 ast_channel_name(iaxs[callno]->owner),
9882 iaxs[callno]->pingtime,
9883 localjitter,
9884 localdelay,
9885 locallost,
9886 locallosspct,
9887 localdropped,
9888 localooo,
9889 localpackets,
9890 iaxs[callno]->remote_rr.jitter,
9897 }
9899}
9900
9901static int socket_process(struct iax2_thread *thread);
9902
9903/*!
9904 * \brief Handle any deferred full frames for this thread
9905 */
9907{
9908 struct iax2_pkt_buf *pkt_buf;
9909
9910 ast_mutex_lock(&thread->lock);
9911
9912 while ((pkt_buf = AST_LIST_REMOVE_HEAD(&thread->full_frames, entry))) {
9913 ast_mutex_unlock(&thread->lock);
9914
9915 thread->buf = pkt_buf->buf;
9916 thread->buf_len = pkt_buf->len;
9917 thread->buf_size = pkt_buf->len + 1;
9918
9920
9921 thread->buf = NULL;
9922 ast_free(pkt_buf);
9923
9924 ast_mutex_lock(&thread->lock);
9925 }
9926
9927 ast_mutex_unlock(&thread->lock);
9928}
9929
9930/*!
9931 * \brief Queue the last read full frame for processing by a certain thread
9932 *
9933 * If there are already any full frames queued, they are sorted
9934 * by sequence number.
9935 */
9936static void defer_full_frame(struct iax2_thread *from_here, struct iax2_thread *to_here)
9937{
9938 struct iax2_pkt_buf *pkt_buf, *cur_pkt_buf;
9939 struct ast_iax2_full_hdr *fh, *cur_fh;
9940
9941 if (!(pkt_buf = ast_calloc(1, sizeof(*pkt_buf) + from_here->buf_len)))
9942 return;
9943
9944 pkt_buf->len = from_here->buf_len;
9945 memcpy(pkt_buf->buf, from_here->buf, pkt_buf->len);
9946
9947 fh = (struct ast_iax2_full_hdr *) pkt_buf->buf;
9948 ast_mutex_lock(&to_here->lock);
9949 AST_LIST_TRAVERSE_SAFE_BEGIN(&to_here->full_frames, cur_pkt_buf, entry) {
9950 cur_fh = (struct ast_iax2_full_hdr *) cur_pkt_buf->buf;
9951 if (fh->oseqno < cur_fh->oseqno) {
9952 AST_LIST_INSERT_BEFORE_CURRENT(pkt_buf, entry);
9953 break;
9954 }
9955 }
9957
9958 if (!cur_pkt_buf)
9959 AST_LIST_INSERT_TAIL(&to_here->full_frames, pkt_buf, entry);
9960
9961 to_here->iostate = IAX_IOSTATE_READY;
9962 ast_cond_signal(&to_here->cond);
9963
9964 ast_mutex_unlock(&to_here->lock);
9965}
9966
9967static int socket_read(int *id, int fd, short events, void *cbdata)
9968{
9969 struct iax2_thread *thread;
9970 time_t t;
9971 static time_t last_errtime = 0;
9972 struct ast_iax2_full_hdr *fh;
9973
9974 if (!(thread = find_idle_thread())) {
9975 time(&t);
9976 if (t != last_errtime) {
9977 last_errtime = t;
9978 ast_debug(1, "Out of idle IAX2 threads for I/O, pausing!\n");
9979 }
9980 usleep(1);
9981 return 1;
9982 }
9983
9984 thread->iofd = fd;
9985 thread->buf_len = ast_recvfrom(fd, thread->readbuf, sizeof(thread->readbuf), 0, &thread->ioaddr);
9986 thread->buf_size = sizeof(thread->readbuf);
9987 thread->buf = thread->readbuf;
9988 if (thread->buf_len < 0) {
9989 if (errno != ECONNREFUSED && errno != EAGAIN)
9990 ast_log(LOG_WARNING, "Error: %s\n", strerror(errno));
9991 handle_error();
9992 thread->iostate = IAX_IOSTATE_IDLE;
9993 signal_condition(&thread->lock, &thread->cond);
9994 return 1;
9995 }
9996 if (test_losspct && ((100.0 * ast_random() / (RAND_MAX + 1.0)) < test_losspct)) { /* simulate random loss condition */
9997 thread->iostate = IAX_IOSTATE_IDLE;
9998 signal_condition(&thread->lock, &thread->cond);
9999 return 1;
10000 }
10001
10002 /* Determine if this frame is a full frame; if so, and any thread is currently
10003 processing a full frame for the same callno from this peer, then drop this
10004 frame (and the peer will retransmit it) */
10005 fh = (struct ast_iax2_full_hdr *) thread->buf;
10006 if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
10007 struct iax2_thread *cur = NULL;
10008 uint16_t callno = ntohs(fh->scallno) & ~IAX_FLAG_FULL;
10009
10012 if ((cur->ffinfo.callno == callno) &&
10013 !ast_sockaddr_cmp_addr(&cur->ffinfo.addr, &thread->ioaddr))
10014 break;
10015 }
10016 if (cur) {
10017 /* we found another thread processing a full frame for this call,
10018 so queue it up for processing later. */
10021 thread->iostate = IAX_IOSTATE_IDLE;
10022 signal_condition(&thread->lock, &thread->cond);
10023 return 1;
10024 } else {
10025 /* this thread is going to process this frame, so mark it */
10026 thread->ffinfo.callno = callno;
10027 ast_sockaddr_copy(&thread->ffinfo.addr, &thread->ioaddr);
10028 thread->ffinfo.type = fh->type;
10029 thread->ffinfo.csub = fh->csub;
10031 }
10033 }
10034
10035 /* Mark as ready and send on its way */
10036 thread->iostate = IAX_IOSTATE_READY;
10037#ifdef DEBUG_SCHED_MULTITHREAD
10038 ast_copy_string(thread->curfunc, "socket_process", sizeof(thread->curfunc));
10039#endif
10040 signal_condition(&thread->lock, &thread->cond);
10041
10042 return 1;
10043}
10044
10045static int socket_process_meta(int packet_len, struct ast_iax2_meta_hdr *meta, struct ast_sockaddr *addr, int sockfd,
10046 struct iax_frame *fr)
10047{
10048 unsigned char metatype;
10049 struct ast_iax2_meta_trunk_mini *mtm;
10050 struct ast_iax2_meta_trunk_hdr *mth;
10051 struct ast_iax2_meta_trunk_entry *mte;
10052 struct iax2_trunk_peer *tpeer;
10053 unsigned int ts;
10054 void *ptr;
10055 struct timeval rxtrunktime;
10056 struct ast_frame f = { 0, };
10057
10058 if (packet_len < sizeof(*meta)) {
10059 ast_log(LOG_WARNING, "Rejecting packet from '%s' that is flagged as a meta frame but is too short\n",
10061 return 1;
10062 }
10063
10064 if (meta->metacmd != IAX_META_TRUNK)
10065 return 1;
10066
10067 if (packet_len < (sizeof(*meta) + sizeof(*mth))) {
10068 ast_log(LOG_WARNING, "midget meta trunk packet received (%d of %d min)\n", packet_len,
10069 (int) (sizeof(*meta) + sizeof(*mth)));
10070 return 1;
10071 }
10072 mth = (struct ast_iax2_meta_trunk_hdr *)(meta->data);
10073 ts = ntohl(mth->ts);
10074 metatype = meta->cmddata;
10075 packet_len -= (sizeof(*meta) + sizeof(*mth));
10076 ptr = mth->data;
10077 tpeer = find_tpeer(addr, sockfd);
10078 if (!tpeer) {
10079 ast_log(LOG_WARNING, "Unable to accept trunked packet from '%s': No matching peer\n",
10081 return 1;
10082 }
10083 tpeer->trunkact = ast_tvnow();
10084 if (!ts || ast_tvzero(tpeer->rxtrunktime))
10085 tpeer->rxtrunktime = tpeer->trunkact;
10086 rxtrunktime = tpeer->rxtrunktime;
10087 ast_mutex_unlock(&tpeer->lock);
10088 while (packet_len >= sizeof(*mte)) {
10089 /* Process channels */
10090 unsigned short callno, trunked_ts, len;
10091
10092 if (metatype == IAX_META_TRUNK_MINI) {
10093 mtm = (struct ast_iax2_meta_trunk_mini *) ptr;
10094 ptr += sizeof(*mtm);
10095 packet_len -= sizeof(*mtm);
10096 len = ntohs(mtm->len);
10097 callno = ntohs(mtm->mini.callno);
10098 trunked_ts = ntohs(mtm->mini.ts);
10099 } else if (metatype == IAX_META_TRUNK_SUPERMINI) {
10100 mte = (struct ast_iax2_meta_trunk_entry *)ptr;
10101 ptr += sizeof(*mte);
10102 packet_len -= sizeof(*mte);
10103 len = ntohs(mte->len);
10104 callno = ntohs(mte->callno);
10105 trunked_ts = 0;
10106 } else {
10107 ast_log(LOG_WARNING, "Unknown meta trunk cmd from '%s': dropping\n", ast_sockaddr_stringify(addr));
10108 break;
10109 }
10110 /* Stop if we don't have enough data */
10111 if (len > packet_len)
10112 break;
10113 fr->callno = find_callno_locked(callno & ~IAX_FLAG_FULL, 0, addr, NEW_PREVENT, sockfd, 0);
10114 if (!fr->callno)
10115 continue;
10116
10117 /* If it's a valid call, deliver the contents. If not, we
10118 drop it, since we don't have a scallno to use for an INVAL */
10119 /* Process as a mini frame */
10120 memset(&f, 0, sizeof(f));
10122 if (!iaxs[fr->callno]) {
10123 /* drop it */
10124 } else if (iaxs[fr->callno]->voiceformat == 0) {
10125 ast_log(LOG_WARNING, "Received trunked frame before first full voice frame\n");
10126 iax2_vnak(fr->callno);
10128 iaxs[fr->callno]->voiceformat))) {
10129 f.datalen = len;
10130 if (f.datalen >= 0) {
10131 if (f.datalen)
10132 f.data.ptr = ptr;
10133 else
10134 f.data.ptr = NULL;
10135 if (trunked_ts)
10136 fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | (trunked_ts & 0xffff);
10137 else
10138 fr->ts = fix_peerts(&rxtrunktime, fr->callno, ts);
10139 /* Don't pass any packets until we're started */
10141 struct iax_frame *duped_fr;
10142
10143 /* Common things */
10144 f.src = "IAX2";
10145 f.mallocd = 0;
10146 f.offset = 0;
10147 if (f.datalen && (f.frametype == AST_FRAME_VOICE))
10149 else
10150 f.samples = 0;
10151 fr->outoforder = 0;
10152 iax_frame_wrap(fr, &f);
10153 duped_fr = iaxfrdup2(fr);
10154 if (duped_fr)
10155 schedule_delivery(duped_fr, 1, 1, &fr->ts);
10156 if (iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts)
10157 iaxs[fr->callno]->last = fr->ts;
10158 }
10159 } else {
10160 ast_log(LOG_ERROR, "Dropping malformed frame (datalen %d?)\n", f.datalen);
10161 }
10162 }
10164 ptr += len;
10165 packet_len -= len;
10166 }
10167
10168 return 1;
10169}
10170
10171static int acf_iaxvar_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
10172{
10173 struct ast_datastore *variablestore;
10174 AST_LIST_HEAD(, ast_var_t) *varlist;
10175 struct ast_var_t *var;
10176
10177 if (!chan) {
10178 ast_log(LOG_WARNING, "No channel was provided to %s function.\n", cmd);
10179 return -1;
10180 }
10181
10183 if (!variablestore) {
10184 *buf = '\0';
10185 return 0;
10186 }
10187 varlist = variablestore->data;
10188
10189 AST_LIST_LOCK(varlist);
10190 AST_LIST_TRAVERSE(varlist, var, entries) {
10191 if (strcmp(var->name, data) == 0) {
10192 ast_copy_string(buf, var->value, len);
10193 break;
10194 }
10195 }
10196 AST_LIST_UNLOCK(varlist);
10197 return 0;
10198}
10199
10200static int acf_iaxvar_write(struct ast_channel *chan, const char *cmd, char *data, const char *value)
10201{
10202 struct ast_datastore *variablestore;
10203 AST_LIST_HEAD(, ast_var_t) *varlist;
10204 struct ast_var_t *var;
10205
10206 if (!chan) {
10207 ast_log(LOG_WARNING, "No channel was provided to %s function.\n", cmd);
10208 return -1;
10209 }
10210
10212 if (!variablestore) {
10214 if (!variablestore) {
10215 ast_log(LOG_ERROR, "Memory allocation error\n");
10216 return -1;
10217 }
10218 varlist = ast_calloc(1, sizeof(*varlist));
10219 if (!varlist) {
10220 ast_datastore_free(variablestore);
10221 ast_log(LOG_ERROR, "Unable to assign new variable '%s'\n", data);
10222 return -1;
10223 }
10224
10225 AST_LIST_HEAD_INIT(varlist);
10226 variablestore->data = varlist;
10227 variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
10228 ast_channel_datastore_add(chan, variablestore);
10229 } else
10230 varlist = variablestore->data;
10231
10232 AST_LIST_LOCK(varlist);
10234 if (strcmp(var->name, data) == 0) {
10237 break;
10238 }
10239 }
10241 var = ast_var_assign(data, value);
10242 if (var)
10243 AST_LIST_INSERT_TAIL(varlist, var, entries);
10244 else
10245 ast_log(LOG_ERROR, "Unable to assign new variable '%s'\n", data);
10246 AST_LIST_UNLOCK(varlist);
10247 return 0;
10248}
10249
10250static struct ast_custom_function iaxvar_function = {
10251 .name = "IAXVAR",
10252 .read = acf_iaxvar_read,
10253 .write = acf_iaxvar_write,
10254};
10255
10256static void set_hangup_source_and_cause(int callno, unsigned char causecode)
10257{
10258 iax2_lock_owner(callno);
10259 if (iaxs[callno] && iaxs[callno]->owner) {
10260 struct ast_channel *owner;
10261 const char *name;
10262
10263 owner = iaxs[callno]->owner;
10264 if (causecode) {
10265 ast_channel_hangupcause_set(owner, causecode);
10266 }
10268 ast_channel_ref(owner);
10269 ast_channel_unlock(owner);
10270 ast_mutex_unlock(&iaxsl[callno]);
10271 ast_set_hangupsource(owner, name, 0);
10272 ast_channel_unref(owner);
10273 ast_mutex_lock(&iaxsl[callno]);
10274 }
10275}
10276
10277static int socket_process_helper(struct iax2_thread *thread)
10278{
10279 struct ast_sockaddr addr;
10280 int res;
10281 int updatehistory=1;
10282 int new = NEW_PREVENT;
10283 int dcallno = 0;
10284 char decrypted = 0;
10285 struct ast_iax2_full_hdr *fh = (struct ast_iax2_full_hdr *)thread->buf;
10286 struct ast_iax2_mini_hdr *mh = (struct ast_iax2_mini_hdr *)thread->buf;
10287 struct ast_iax2_meta_hdr *meta = (struct ast_iax2_meta_hdr *)thread->buf;
10288 struct ast_iax2_video_hdr *vh = (struct ast_iax2_video_hdr *)thread->buf;
10289 struct iax_frame *fr;
10290 struct iax_frame *cur;
10291 struct ast_frame f = { 0, };
10292 struct ast_channel *c = NULL;
10293 struct iax2_dpcache *dp;
10294 struct iax2_peer *peer;
10295 struct iax_ies ies;
10296 struct iax_ie_data ied0, ied1;
10297 iax2_format format;
10298 int fd;
10299 int exists;
10300 int minivid = 0;
10301 char empty[32]=""; /* Safety measure */
10302 struct iax_frame *duped_fr;
10303 char host_pref_buf[128];
10304 char caller_pref_buf[128];
10305 struct iax2_codec_pref pref;
10306 char *using_prefs = "mine";
10307
10308 /* allocate an iax_frame with 4096 bytes of data buffer */
10309 fr = ast_alloca(sizeof(*fr) + 4096);
10310 memset(fr, 0, sizeof(*fr));
10311 fr->afdatalen = 4096; /* From ast_alloca() above */
10312
10313 /* Copy frequently used parameters to the stack */
10314 res = thread->buf_len;
10315 fd = thread->iofd;
10316 ast_sockaddr_copy(&addr, &thread->ioaddr);
10317
10318 if (res < sizeof(*mh)) {
10319 ast_log(LOG_WARNING, "midget packet received (%d of %d min)\n", res, (int) sizeof(*mh));
10320 return 1;
10321 }
10322 if ((vh->zeros == 0) && (ntohs(vh->callno) & 0x8000)) {
10323 if (res < sizeof(*vh)) {
10324 ast_log(LOG_WARNING, "Rejecting packet from '%s' that is flagged as a video frame but is too short\n",
10325 ast_sockaddr_stringify(&addr));
10326 return 1;
10327 }
10328
10329 /* This is a video frame, get call number */
10330 fr->callno = find_callno(ntohs(vh->callno) & ~0x8000, dcallno, &addr, new, fd, 0);
10331 minivid = 1;
10332 } else if ((meta->zeros == 0) && !(ntohs(meta->metacmd) & 0x8000))
10333 return socket_process_meta(res, meta, &addr, fd, fr);
10334
10335#ifdef DEBUG_SUPPORT
10336 if (res >= sizeof(*fh))
10337 iax_outputframe(NULL, fh, 1, &addr, res - sizeof(*fh));
10338#endif
10339 if (ntohs(mh->callno) & IAX_FLAG_FULL) {
10340 if (res < sizeof(*fh)) {
10341 ast_log(LOG_WARNING, "Rejecting packet from '%s' that is flagged as a full frame but is too short\n",
10342 ast_sockaddr_stringify(&addr));
10343 return 1;
10344 }
10345
10346 /* Get the destination call number */
10347 dcallno = ntohs(fh->dcallno) & ~IAX_FLAG_RETRANS;
10348
10349
10350 /* check to make sure this full frame isn't encrypted before we attempt
10351 * to look inside of it. If it is encrypted, decrypt it first. Its ok if the
10352 * callno is not found here, that just means one hasn't been allocated for
10353 * this connection yet. */
10354 if ((dcallno != 1) && (fr->callno = find_callno(ntohs(mh->callno) & ~IAX_FLAG_FULL, dcallno, &addr, NEW_PREVENT, fd, 1))) {
10356 if (iaxs[fr->callno] && ast_test_flag64(iaxs[fr->callno], IAX_ENCRYPTED)) {
10357 if (decrypt_frame(fr->callno, fh, &f, &res)) {
10358 ast_log(LOG_NOTICE, "Packet Decrypt Failed!\n");
10360 return 1;
10361 }
10362 decrypted = 1;
10363 }
10365 }
10366
10367 /* Retrieve the type and subclass */
10368 f.frametype = fh->type;
10369 if (f.frametype == AST_FRAME_VIDEO) {
10371 if (!f.subclass.format) {
10372 return 1;
10373 }
10374 if ((fh->csub >> 6) & 0x1) {
10375 f.subclass.frame_ending = 1;
10376 }
10377 } else if (f.frametype == AST_FRAME_VOICE) {
10379 if (!f.subclass.format) {
10380 return 1;
10381 }
10382 } else {
10384 }
10385
10386 /* Deal with POKE/PONG without allocating a callno */
10388 /* Reply back with a PONG, but don't care about the result. */
10389 send_apathetic_reply(1, ntohs(fh->scallno), &addr, IAX_COMMAND_PONG, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
10390 return 1;
10391 } else if (f.frametype == AST_FRAME_IAX && f.subclass.integer == IAX_COMMAND_ACK && dcallno == 1) {
10392 /* Ignore */
10393 return 1;
10394 }
10395
10396 f.datalen = res - sizeof(*fh);
10397 if (f.datalen) {
10398 if (f.frametype == AST_FRAME_IAX) {
10399 if (iax_parse_ies(&ies, thread->buf + sizeof(struct ast_iax2_full_hdr), f.datalen)) {
10400 char subclass[40];
10401 iax_frame_subclass2str(f.subclass.integer, subclass, sizeof(subclass));
10402 ast_log(LOG_WARNING, "Undecodable %s frame received from '%s'\n", subclass, ast_sockaddr_stringify(&addr));
10404 return 1;
10405 }
10406 f.data.ptr = NULL;
10407 f.datalen = 0;
10408 } else {
10409 f.data.ptr = thread->buf + sizeof(struct ast_iax2_full_hdr);
10410 memset(&ies, 0, sizeof(ies));
10411 }
10412 } else {
10413 if (f.frametype == AST_FRAME_IAX)
10414 f.data.ptr = NULL;
10415 else
10416 f.data.ptr = empty;
10417 memset(&ies, 0, sizeof(ies));
10418 }
10419
10420 if (!dcallno && iax2_allow_new(f.frametype, f.subclass.integer, 1)) {
10421 /* only set NEW_ALLOW if calltoken checks out */
10422 if (handle_call_token(fh, &ies, &addr, fd)) {
10424 return 1;
10425 }
10426
10427 if (ies.calltoken && ies.calltokendata) {
10428 /* if we've gotten this far, and the calltoken ie data exists,
10429 * then calltoken validation _MUST_ have taken place. If calltoken
10430 * data is provided, it is always validated regardless of any
10431 * calltokenoptional or requirecalltoken options */
10433 } else {
10434 new = NEW_ALLOW;
10435 }
10436 }
10437 } else {
10438 /* Don't know anything about it yet */
10440 f.subclass.integer = 0;
10441 memset(&ies, 0, sizeof(ies));
10442 }
10443
10444 if (!fr->callno) {
10445 int check_dcallno = 0;
10446
10447 /*
10448 * We enforce accurate destination call numbers for ACKs. This forces the other
10449 * end to know the destination call number before call setup can complete.
10450 *
10451 * Discussed in the following thread:
10452 * http://lists.digium.com/pipermail/asterisk-dev/2008-May/033217.html
10453 */
10454
10455 if ((ntohs(mh->callno) & IAX_FLAG_FULL) && ((f.frametype == AST_FRAME_IAX) && (f.subclass.integer == IAX_COMMAND_ACK))) {
10456 check_dcallno = 1;
10457 }
10458
10459 if (!(fr->callno = find_callno(ntohs(mh->callno) & ~IAX_FLAG_FULL, dcallno, &addr, new, fd, check_dcallno))) {
10460 ast_debug(1, "Received frame without existent call number (%d)\n", ntohs(mh->callno) & ~IAX_FLAG_FULL);
10462 send_apathetic_reply(1, ntohs(fh->scallno), &addr, IAX_COMMAND_REJECT, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
10464 send_apathetic_reply(1, ntohs(fh->scallno), &addr, IAX_COMMAND_REGREJ, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
10465 } else {
10466 ast_log(LOG_WARNING, "Silently dropping frame without existent call number: %d\n", ntohs(mh->callno) & ~IAX_FLAG_FULL);
10467 }
10469 return 1;
10470 }
10471 }
10472
10473 if (fr->callno > 0) {
10474 ast_callid mount_callid;
10476 if (iaxs[fr->callno] && ((mount_callid = iax_pvt_callid_get(fr->callno)))) {
10477 /* Bind to thread */
10478 ast_callid_threadassoc_add(mount_callid);
10479 }
10480 }
10481
10482 if (!fr->callno || !iaxs[fr->callno]) {
10483 /* A call arrived for a nonexistent destination. Unless it's an "inval"
10484 frame, reply with an inval */
10485 if (ntohs(mh->callno) & IAX_FLAG_FULL) {
10486 /* We can only raw hangup control frames */
10487 if (((f.subclass.integer != IAX_COMMAND_INVAL) &&
10491 (f.frametype != AST_FRAME_IAX))
10492 raw_hangup(&addr, ntohs(fh->dcallno) & ~IAX_FLAG_RETRANS, ntohs(mh->callno) & ~IAX_FLAG_FULL,
10493 fd);
10494 }
10495 if (fr->callno > 0){
10497 }
10499 return 1;
10500 }
10501 if (ast_test_flag64(iaxs[fr->callno], IAX_ENCRYPTED) && !decrypted) {
10502 if (decrypt_frame(fr->callno, fh, &f, &res)) {
10503 ast_log(LOG_WARNING, "Packet Decrypt Failed!\n");
10506 return 1;
10507 }
10508 decrypted = 1;
10509 }
10510
10511#ifdef DEBUG_SUPPORT
10512 if (decrypted) {
10513 iax_outputframe(NULL, fh, 3, &addr, res - sizeof(*fh));
10514 }
10515#endif
10516
10517 if (iaxs[fr->callno]->owner && fh->type == AST_FRAME_IAX &&
10518 (fh->csub == IAX_COMMAND_HANGUP
10519 || fh->csub == IAX_COMMAND_REJECT
10520 || fh->csub == IAX_COMMAND_REGREJ
10521 || fh->csub == IAX_COMMAND_TXREJ)) {
10522 struct ast_control_pvt_cause_code *cause_code;
10523 int data_size = sizeof(*cause_code);
10524 char subclass[40] = "";
10525
10526 /* get subclass text */
10527 iax_frame_subclass2str(fh->csub, subclass, sizeof(subclass));
10528
10529 /* add length of "IAX2 " */
10530 data_size += 5;
10531 /* for IAX hangup frames, add length of () and number */
10532 data_size += 3;
10533 if (ies.causecode > 9) {
10534 data_size++;
10535 }
10536 if (ies.causecode > 99) {
10537 data_size++;
10538 }
10539 /* add length of subclass */
10540 data_size += strlen(subclass);
10541
10542 cause_code = ast_alloca(data_size);
10543 memset(cause_code, 0, data_size);
10545
10546 cause_code->ast_cause = ies.causecode;
10547 snprintf(cause_code->code, data_size - sizeof(*cause_code) + 1, "IAX2 %s(%d)", subclass, ies.causecode);
10548
10550 if (iaxs[fr->callno] && iaxs[fr->callno]->owner) {
10551 ast_queue_control_data(iaxs[fr->callno]->owner, AST_CONTROL_PVT_CAUSE_CODE, cause_code, data_size);
10552 ast_channel_hangupcause_hash_set(iaxs[fr->callno]->owner, cause_code, data_size);
10554 }
10555 if (!iaxs[fr->callno]) {
10558 return 1;
10559 }
10560 }
10561
10562 /* count this frame */
10563 iaxs[fr->callno]->frames_received++;
10564
10565 if (!ast_sockaddr_cmp(&addr, &iaxs[fr->callno]->addr) && !minivid &&
10566 f.subclass.integer != IAX_COMMAND_TXCNT && /* for attended transfer */
10567 f.subclass.integer != IAX_COMMAND_TXACC) { /* for attended transfer */
10568 unsigned short new_peercallno;
10569
10570 new_peercallno = (unsigned short) (ntohs(mh->callno) & ~IAX_FLAG_FULL);
10571 if (new_peercallno && new_peercallno != iaxs[fr->callno]->peercallno) {
10572 if (iaxs[fr->callno]->peercallno) {
10574 }
10575 iaxs[fr->callno]->peercallno = new_peercallno;
10577 }
10578 }
10579 if (ntohs(mh->callno) & IAX_FLAG_FULL) {
10580 if (iaxdebug)
10581 ast_debug(1, "Received packet %d, (%u, %d)\n", fh->oseqno, f.frametype, f.subclass.integer);
10582 /* Check if it's out of order (and not an ACK or INVAL) */
10583 fr->oseqno = fh->oseqno;
10584 fr->iseqno = fh->iseqno;
10585 fr->ts = ntohl(fh->ts);
10586#ifdef IAXTESTS
10587 if (test_resync) {
10588 ast_debug(1, "Simulating frame ts resync, was %u now %u\n", fr->ts, fr->ts + test_resync);
10589 fr->ts += test_resync;
10590 }
10591#endif /* IAXTESTS */
10592#if 0
10593 if ( (ntohs(fh->dcallno) & IAX_FLAG_RETRANS) ||
10594 ( (f.frametype != AST_FRAME_VOICE) && ! (f.frametype == AST_FRAME_IAX &&
10595 (f.subclass == IAX_COMMAND_NEW ||
10598 f.subclass == IAX_COMMAND_REJECT)) ) )
10599#endif
10600 if ((ntohs(fh->dcallno) & IAX_FLAG_RETRANS) || (f.frametype != AST_FRAME_VOICE))
10601 updatehistory = 0;
10602 if ((iaxs[fr->callno]->iseqno != fr->oseqno) &&
10603 (iaxs[fr->callno]->iseqno ||
10605 (f.subclass.integer != IAX_COMMAND_TXREADY) && /* for attended transfer */
10606 (f.subclass.integer != IAX_COMMAND_TXREL) && /* for attended transfer */
10607 (f.subclass.integer != IAX_COMMAND_UNQUELCH ) && /* for attended transfer */
10609 (f.frametype != AST_FRAME_IAX))) {
10610 if (
10614 (f.subclass.integer != IAX_COMMAND_TXREADY) && /* for attended transfer */
10615 (f.subclass.integer != IAX_COMMAND_TXREL) && /* for attended transfer */
10616 (f.subclass.integer != IAX_COMMAND_UNQUELCH ) && /* for attended transfer */
10619 (f.frametype != AST_FRAME_IAX)) {
10620 /* If it's not an ACK packet, it's out of order. */
10621 ast_debug(1, "Packet arrived out of order (expecting %d, got %d) (frametype = %u, subclass = %d)\n",
10622 iaxs[fr->callno]->iseqno, fr->oseqno, f.frametype, f.subclass.integer);
10623 /* Check to see if we need to request retransmission,
10624 * and take sequence number wraparound into account */
10625 if ((unsigned char) (iaxs[fr->callno]->iseqno - fr->oseqno) < 128) {
10626 /* If we've already seen it, ack it XXX There's a border condition here XXX */
10627 if ((f.frametype != AST_FRAME_IAX) ||
10629 ast_debug(1, "Acking anyway\n");
10630 /* XXX Maybe we should handle its ack to us, but then again, it's probably outdated anyway, and if
10631 we have anything to send, we'll retransmit and get an ACK back anyway XXX */
10633 }
10634 } else {
10635 /* Send a VNAK requesting retransmission */
10636 iax2_vnak(fr->callno);
10637 }
10640 return 1;
10641 }
10642 } else {
10643 /* Increment unless it's an ACK or VNAK */
10644 if (((f.subclass.integer != IAX_COMMAND_ACK) &&
10649 (f.frametype != AST_FRAME_IAX))
10650 iaxs[fr->callno]->iseqno++;
10651 }
10652 /* Ensure text frames are NULL-terminated */
10653 if (f.frametype == AST_FRAME_TEXT && thread->buf[res - 1] != '\0') {
10654 if (res < thread->buf_size)
10655 thread->buf[res++] = '\0';
10656 else /* Trims one character from the text message, but that's better than overwriting the end of the buffer. */
10657 thread->buf[res - 1] = '\0';
10658 }
10659
10660 /* Handle implicit ACKing unless this is an INVAL, and only if this is
10661 from the real peer, not the transfer peer */
10662 if (!ast_sockaddr_cmp(&addr, &iaxs[fr->callno]->addr) &&
10664 (f.frametype != AST_FRAME_IAX))) {
10665 unsigned char x;
10666 int call_to_destroy;
10667 /* First we have to qualify that the ACKed value is within our window */
10668 if (iaxs[fr->callno]->rseqno >= iaxs[fr->callno]->oseqno || (fr->iseqno >= iaxs[fr->callno]->rseqno && fr->iseqno < iaxs[fr->callno]->oseqno))
10669 x = fr->iseqno;
10670 else
10671 x = iaxs[fr->callno]->oseqno;
10672 if ((x != iaxs[fr->callno]->oseqno) || (iaxs[fr->callno]->oseqno == fr->iseqno)) {
10673 /* The acknowledgement is within our window. Time to acknowledge everything
10674 that it says to */
10675 for (x=iaxs[fr->callno]->rseqno; x != fr->iseqno; x++) {
10676 /* Ack the packet with the given timestamp */
10677 if (iaxdebug)
10678 ast_debug(1, "Cancelling transmission of packet %d\n", x);
10679 call_to_destroy = 0;
10680 AST_LIST_TRAVERSE(&frame_queue[fr->callno], cur, list) {
10681 /* If it's our call, and our timestamp, mark -1 retries */
10682 if (x == cur->oseqno) {
10683 cur->retries = -1;
10684 /* Destroy call if this is the end */
10685 if (cur->final)
10686 call_to_destroy = fr->callno;
10687 }
10688 }
10689 if (call_to_destroy) {
10690 if (iaxdebug)
10691 ast_debug(1, "Really destroying %d, having been acked on final message\n", call_to_destroy);
10692 ast_mutex_lock(&iaxsl[call_to_destroy]);
10693 iax2_destroy(call_to_destroy);
10694 ast_mutex_unlock(&iaxsl[call_to_destroy]);
10695 }
10696 }
10697 /* Note how much we've received acknowledgement for */
10698 if (iaxs[fr->callno])
10699 iaxs[fr->callno]->rseqno = fr->iseqno;
10700 else {
10701 /* Stop processing now */
10704 return 1;
10705 }
10706 } else {
10707 ast_debug(1, "Received iseqno %d not within window %d->%d\n", fr->iseqno, iaxs[fr->callno]->rseqno, iaxs[fr->callno]->oseqno);
10708 }
10709 }
10710 if (ast_sockaddr_cmp(&addr, &iaxs[fr->callno]->addr) &&
10711 ((f.frametype != AST_FRAME_IAX) ||
10714 /* Only messages we accept from a transfer host are TXACC and TXCNT */
10717 return 1;
10718 }
10719
10720 /* when we receive the first full frame for a new incoming channel,
10721 it is safe to start the PBX on the channel because we have now
10722 completed a 3-way handshake with the peer */
10723 if ((f.frametype == AST_FRAME_VOICE) ||
10724 (f.frametype == AST_FRAME_VIDEO) ||
10725 (f.frametype == AST_FRAME_IAX)) {
10733 return 1;
10734 }
10735 }
10736
10737 if (ies.vars) {
10738 struct ast_datastore *variablestore = NULL;
10739 struct ast_variable *var, *prev = NULL;
10740 AST_LIST_HEAD(, ast_var_t) *varlist;
10741
10743 if (!iaxs[fr->callno]) {
10746 return 1;
10747 }
10748 if ((c = iaxs[fr->callno]->owner)) {
10749 varlist = ast_calloc(1, sizeof(*varlist));
10751
10752 if (variablestore && varlist) {
10753 variablestore->data = varlist;
10754 variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
10755 AST_LIST_HEAD_INIT(varlist);
10756 ast_debug(1, "I can haz IAX vars?\n");
10757 for (var = ies.vars; var; var = var->next) {
10758 struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
10759 if (prev) {
10760 ast_free(prev);
10761 }
10762 prev = var;
10763 if (!newvar) {
10764 /* Don't abort list traversal, as this would leave ies.vars in an inconsistent state. */
10765 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
10766 } else {
10767 AST_LIST_INSERT_TAIL(varlist, newvar, entries);
10768 }
10769 }
10770 if (prev) {
10771 ast_free(prev);
10772 }
10773 ies.vars = NULL;
10774 ast_channel_datastore_add(c, variablestore);
10775 } else {
10776 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
10777 if (variablestore) {
10778 ast_datastore_free(variablestore);
10779 }
10780 if (varlist) {
10781 ast_free(varlist);
10782 }
10783 }
10785 } else {
10786 /* No channel yet, so transfer the variables directly over to the pvt,
10787 * for later inheritance. */
10788 ast_debug(1, "No channel, so populating IAXVARs to the pvt, as an intermediate step.\n");
10789 for (var = ies.vars; var && var->next; var = var->next);
10790 if (var) {
10791 var->next = iaxs[fr->callno]->iaxvars;
10792 iaxs[fr->callno]->iaxvars = ies.vars;
10793 ies.vars = NULL;
10794 }
10795 }
10796 }
10797
10798 if (ies.vars) {
10799 ast_debug(1, "I have IAX variables, but they were not processed\n");
10800 }
10801 }
10802
10803 /* once we receive our first IAX Full Frame that is not CallToken related, send all
10804 * queued signaling frames that were being held. */
10807 }
10808
10809 if (f.frametype == AST_FRAME_VOICE) {
10812 ast_debug(1, "Ooh, voice format changed to '%s'\n", ast_format_get_name(f.subclass.format));
10813 if (iaxs[fr->callno]->owner) {
10815 if (iaxs[fr->callno]) {
10816 if (iaxs[fr->callno]->owner) {
10818 if (native) {
10823 }
10824 ao2_ref(native, -1);
10825 }
10827 }
10828 } else {
10829 ast_debug(1, "Neat, somebody took away the channel at a magical time but i found it!\n");
10830 /* Free remote variables (if any) */
10831 if (ies.vars) {
10833 ast_debug(1, "I can haz iaxvars, but they is no good. :-(\n");
10834 ies.vars = NULL;
10835 }
10837 return 1;
10838 }
10839 }
10840 }
10841 }
10842 if (f.frametype == AST_FRAME_VIDEO) {
10844 ast_debug(1, "Ooh, video format changed to %s\n", ast_format_get_name(f.subclass.format));
10846 }
10847 }
10848 if (f.frametype == AST_FRAME_IAX) {
10850 /* Handle the IAX pseudo frame itself */
10851 if (iaxdebug)
10852 ast_debug(1, "IAX subclass %d received\n", f.subclass.integer);
10853
10854 /* Update last ts unless the frame's timestamp originated with us. */
10855 if (iaxs[fr->callno]->last < fr->ts &&
10859 iaxs[fr->callno]->last = fr->ts;
10860 if (iaxdebug)
10861 ast_debug(1, "For call=%d, set last=%u\n", fr->callno, fr->ts);
10862 }
10864 if (!iaxs[fr->callno]->first_iax_message) {
10866 }
10867 switch(f.subclass.integer) {
10868 case IAX_COMMAND_ACK:
10869 /* Do nothing */
10870 break;
10871 case IAX_COMMAND_QUELCH:
10874 if (ies.musiconhold) {
10875 const char *moh_suggest;
10876
10878 if (!iaxs[fr->callno] || !iaxs[fr->callno]->owner) {
10879 break;
10880 }
10881
10882 /*
10883 * We already hold the owner lock so we do not
10884 * need to check iaxs[fr->callno] after it returns.
10885 */
10886 moh_suggest = iaxs[fr->callno]->mohsuggest;
10887 iax2_queue_hold(fr->callno, moh_suggest);
10889 }
10890 }
10891 break;
10895 if (!iaxs[fr->callno]) {
10896 break;
10897 }
10898
10900 if (!iaxs[fr->callno]->owner) {
10901 break;
10902 }
10903
10904 /*
10905 * We already hold the owner lock so we do not
10906 * need to check iaxs[fr->callno] after it returns.
10907 */
10910 }
10911 break;
10912 case IAX_COMMAND_TXACC:
10913 if (iaxs[fr->callno]->transferring == TRANSFER_BEGIN) {
10914 /* Ack the packet with the given timestamp */
10915 AST_LIST_TRAVERSE(&frame_queue[fr->callno], cur, list) {
10916 /* Cancel any outstanding txcnt's */
10917 if (cur->transfer) {
10918 cur->retries = -1;
10919 }
10920 }
10921 memset(&ied1, 0, sizeof(ied1));
10923 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXREADY, 0, ied1.buf, ied1.pos, -1);
10925 }
10926 break;
10927 case IAX_COMMAND_NEW:
10928 /* Ignore if it's already up */
10930 break;
10931 if (ies.provverpres && ies.serviceident && !(ast_sockaddr_isnull(&addr))) {
10933 check_provisioning(&addr, fd, ies.serviceident, ies.provver);
10935 if (!iaxs[fr->callno]) {
10936 break;
10937 }
10938 }
10939 /* If we're in trunk mode, do it now, and update the trunk number in our frame before continuing */
10940 if (ast_test_flag64(iaxs[fr->callno], IAX_TRUNK)) {
10941 int new_callno;
10942 if ((new_callno = make_trunk(fr->callno, 1)) != -1)
10943 fr->callno = new_callno;
10944 }
10945 /* For security, always ack immediately */
10946 if (delayreject)
10948 if (check_access(fr->callno, &addr, &ies)) {
10949 /* They're not allowed on */
10951 if (authdebug) {
10952 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, who was trying to reach '%s@%s'\n",
10954 }
10955 break;
10956 }
10959 ast_log(LOG_WARNING, "Rejected connect attempt. No secret present while force encrypt enabled.\n");
10960 break;
10961 }
10962 if (strcasecmp(iaxs[fr->callno]->exten, "TBD")) {
10963 const char *context, *exten, *cid_num;
10964
10966 exten = ast_strdupa(iaxs[fr->callno]->exten);
10967 cid_num = ast_strdupa(iaxs[fr->callno]->cid_num);
10968
10969 /* This might re-enter the IAX code and need the lock */
10971 exists = ast_exists_extension(NULL, context, exten, 1, cid_num);
10973
10974 if (!iaxs[fr->callno]) {
10975 break;
10976 }
10977 } else
10978 exists = 0;
10979 /* Get OSP token if it does exist */
10980 save_osptoken(fr, &ies);
10982 if (strcmp(iaxs[fr->callno]->exten, "TBD") && !exists) {
10983 memset(&ied0, 0, sizeof(ied0));
10984 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
10986 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
10987 if (!iaxs[fr->callno]) {
10988 break;
10989 }
10990 if (authdebug) {
10991 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, request '%s@%s' does not exist\n",
10993 }
10994 } else {
10995 /* Select an appropriate format */
10996
10999 using_prefs = "reqonly";
11000 } else {
11001 using_prefs = "disabled";
11002 }
11003 format = iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability;
11004 memset(&pref, 0, sizeof(pref));
11005 strcpy(caller_pref_buf, "disabled");
11006 strcpy(host_pref_buf, "disabled");
11007 } else {
11008 struct ast_format *tmpfmt;
11009 using_prefs = "mine";
11010 /* If the information elements are in here... use them */
11011 if (ies.codec_prefs)
11013 if (iax2_codec_pref_index(&iaxs[fr->callno]->rprefs, 0, &tmpfmt)) {
11014 /* If we are codec_first_choice we let the caller have the 1st shot at picking the codec.*/
11016 pref = iaxs[fr->callno]->rprefs;
11017 using_prefs = "caller";
11018 } else {
11019 pref = iaxs[fr->callno]->prefs;
11020 }
11021 } else
11022 pref = iaxs[fr->callno]->prefs;
11023
11024 format = iax2_codec_choose(&pref, iaxs[fr->callno]->capability & iaxs[fr->callno]->peercapability);
11025 iax2_codec_pref_string(&iaxs[fr->callno]->rprefs, caller_pref_buf, sizeof(caller_pref_buf) - 1);
11026 iax2_codec_pref_string(&iaxs[fr->callno]->prefs, host_pref_buf, sizeof(host_pref_buf) - 1);
11027 }
11028 if (!format) {
11030 format = iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability;
11031 if (!format) {
11032 memset(&ied0, 0, sizeof(ied0));
11033 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
11035 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11036 if (!iaxs[fr->callno]) {
11037 break;
11038 }
11039 if (authdebug) {
11042 struct ast_str *peer_form_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
11043
11045 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested '%s' incompatible with our capability '%s'.\n",
11047 iax2_getformatname_multiple(iaxs[fr->callno]->peerformat, &peer_form_buf),
11049 } else {
11050 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability '%s'/'%s' incompatible with our capability '%s'.\n",
11052 iax2_getformatname_multiple(iaxs[fr->callno]->peerformat, &peer_form_buf),
11055 }
11056 }
11057 } else {
11058 /* Pick one... */
11060 if(!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability))
11061 format = 0;
11062 } else {
11064 using_prefs = ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP) ? "reqonly" : "disabled";
11065 memset(&pref, 0, sizeof(pref));
11067 strcpy(caller_pref_buf,"disabled");
11068 strcpy(host_pref_buf,"disabled");
11069 } else {
11070 struct ast_format *tmpfmt;
11071 using_prefs = "mine";
11072 if (iax2_codec_pref_index(&iaxs[fr->callno]->rprefs, 0, &tmpfmt)) {
11073 /* Do the opposite of what we tried above. */
11075 pref = iaxs[fr->callno]->prefs;
11076 } else {
11077 pref = iaxs[fr->callno]->rprefs;
11078 using_prefs = "caller";
11079 }
11080 format = iax2_codec_choose(&pref, iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
11081 } else /* if no codec_prefs IE do it the old way */
11083 }
11084 }
11085
11086 if (!format) {
11089 struct ast_str *peer_form_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
11090
11091 memset(&ied0, 0, sizeof(ied0));
11092 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
11094 ast_log(LOG_ERROR, "No best format in '%s'???\n", iax2_getformatname_multiple(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability, &cap_buf));
11095 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11096 if (!iaxs[fr->callno]) {
11097 break;
11098 }
11099 if (authdebug) {
11100 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability '%s'/'%s' incompatible with our capability '%s'.\n",
11102 iax2_getformatname_multiple(iaxs[fr->callno]->peerformat, &peer_form_buf),
11105 }
11107 break;
11108 }
11109 }
11110 }
11111 if (format) {
11112 /* No authentication required, let them in */
11113 memset(&ied1, 0, sizeof(ied1));
11114 iax_ie_append_int(&ied1, IAX_IE_FORMAT, format);
11116 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACCEPT, 0, ied1.buf, ied1.pos, -1);
11117 if (strcmp(iaxs[fr->callno]->exten, "TBD")) {
11119 ast_verb(3, "Accepting UNAUTHENTICATED call from %s:\n"
11120 "%srequested format = %s,\n"
11121 "%srequested prefs = %s,\n"
11122 "%sactual format = %s,\n"
11123 "%shost prefs = %s,\n"
11124 "%spriority = %s\n",
11129 caller_pref_buf,
11131 iax2_getformatname(format),
11133 host_pref_buf,
11135 using_prefs);
11136
11137 iaxs[fr->callno]->chosenformat = format;
11138
11139 /* Since this is a new call, we should go ahead and set the callid for it. */
11142 } else {
11144 /* If this is a TBD call, we're ready but now what... */
11145 ast_verb(3, "Accepted unauthenticated TBD call from %s\n", ast_sockaddr_stringify(&addr));
11146 }
11147 }
11148 }
11149 break;
11150 }
11153 else
11154 iaxs[fr->callno]->encmethods = 0;
11155 if (!authenticate_request(fr->callno) && iaxs[fr->callno])
11157 break;
11158 case IAX_COMMAND_DPREQ:
11159 /* Request status in the dialplan */
11162 if (iaxcompat) {
11163 /* Spawn a thread for the lookup */
11165 } else {
11166 /* Just look it up */
11167 dp_lookup(fr->callno, iaxs[fr->callno]->context, ies.called_number, iaxs[fr->callno]->cid_num, 1);
11168 }
11169 }
11170 break;
11171 case IAX_COMMAND_HANGUP:
11173 ast_debug(1, "Immediately destroying %d, having received hangup\n", fr->callno);
11174 /* Set hangup cause according to remote and hangupsource */
11175 if (iaxs[fr->callno]->owner) {
11177 if (!iaxs[fr->callno]) {
11178 break;
11179 }
11180 }
11181
11182 /* Send ack immediately, before we destroy */
11184 iax2_destroy(fr->callno);
11185 break;
11186 case IAX_COMMAND_REJECT:
11187 /* Set hangup cause according to remote and hangup source */
11188 if (iaxs[fr->callno]->owner) {
11190 if (!iaxs[fr->callno]) {
11191 break;
11192 }
11193 }
11194
11196 if (iaxs[fr->callno]->owner && authdebug)
11197 ast_log(LOG_WARNING, "Call rejected by %s: %s\n",
11199 ies.cause ? ies.cause : "<Unknown>");
11200 ast_debug(1, "Immediately destroying %d, having received reject\n",
11201 fr->callno);
11202 }
11203 /* Send ack immediately, before we destroy */
11205 fr->ts, NULL, 0, fr->iseqno);
11207 iaxs[fr->callno]->error = EPERM;
11208 iax2_destroy(fr->callno);
11209 break;
11211 {
11213 if (!iaxs[fr->callno]) {
11214 /* Initiating call went away before we could transfer. */
11215 break;
11216 }
11217 if (iaxs[fr->callno]->owner) {
11218 struct ast_channel *owner = iaxs[fr->callno]->owner;
11219 char *context = ast_strdupa(iaxs[fr->callno]->context);
11220
11221 ast_channel_ref(owner);
11222 ast_channel_unlock(owner);
11224
11225 if (ast_bridge_transfer_blind(1, owner, ies.called_number,
11227 ast_log(LOG_WARNING, "Blind transfer of '%s' to '%s@%s' failed\n",
11228 ast_channel_name(owner), ies.called_number,
11229 context);
11230 }
11231
11232 ast_channel_unref(owner);
11234 }
11235
11236 break;
11237 }
11238 case IAX_COMMAND_ACCEPT:
11239 /* Ignore if call is already up or needs authentication or is a TBD */
11241 break;
11243 /* Send ack immediately, before we destroy */
11245 iax2_destroy(fr->callno);
11246 break;
11247 }
11248 if (ies.format) {
11249 iaxs[fr->callno]->peerformat = ies.format;
11250 } else {
11251 if (iaxs[fr->callno]->owner)
11253 else
11255 }
11256 ast_verb(3, "Call accepted by %s (format %s)\n", ast_sockaddr_stringify(&addr),
11258 if (!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability)) {
11259 memset(&ied0, 0, sizeof(ied0));
11260 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
11262 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11263 if (!iaxs[fr->callno]) {
11264 break;
11265 }
11266 if (authdebug) {
11269
11270 ast_log(LOG_NOTICE, "Rejected call to %s, format %s incompatible with our capability %s.\n",
11274 }
11275 } else {
11277
11280 if (iaxs[fr->callno] && iaxs[fr->callno]->owner && native) {
11282
11283 /* Switch us to use a compatible format */
11285 iaxs[fr->callno]->peerformat, &iaxs[fr->callno]->rprefs,
11286 native);
11288 ast_verb(3, "Format for call is %s\n", ast_format_cap_get_names(ast_channel_nativeformats(iaxs[fr->callno]->owner), &cap_buf));
11289
11290 /* Setup read/write formats properly. */
11296 }
11297
11298 ao2_cleanup(native);
11299 }
11300 if (iaxs[fr->callno]) {
11302 AST_LIST_TRAVERSE(&iaxs[fr->callno]->dpentries, dp, peer_list)
11303 if (!(dp->flags & CACHE_FLAG_TRANSMITTED))
11304 iax2_dprequest(dp, fr->callno);
11306 }
11307 break;
11308 case IAX_COMMAND_POKE:
11309 /* Send back a pong packet with the original timestamp */
11311 break;
11312 case IAX_COMMAND_PING:
11313 {
11314 struct iax_ie_data pingied;
11315 construct_rr(iaxs[fr->callno], &pingied);
11316 /* Send back a pong packet with the original timestamp */
11317 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_PONG, fr->ts, pingied.buf, pingied.pos, -1);
11318 }
11319 break;
11320 case IAX_COMMAND_PONG:
11321 /* Calculate ping time */
11322 iaxs[fr->callno]->pingtime = calc_timestamp(iaxs[fr->callno], 0, &f) - fr->ts;
11323 /* save RR info */
11324 save_rr(fr, &ies);
11325
11326 /* Good time to write jb stats for this call */
11328
11329 if (iaxs[fr->callno]->peerpoke) {
11330 RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
11331 peer = iaxs[fr->callno]->peerpoke;
11332 if ((peer->lastms < 0) || (peer->historicms > peer->maxms)) {
11333 if (iaxs[fr->callno]->pingtime <= peer->maxms) {
11334 ast_log(LOG_NOTICE, "Peer '%s' is now REACHABLE! Time: %u\n", peer->name, iaxs[fr->callno]->pingtime);
11336 blob = ast_json_pack("{s: s, s: I}",
11337 "peer_status", "Reachable",
11338 "time", (ast_json_int_t)iaxs[fr->callno]->pingtime);
11339 ast_devstate_changed(AST_DEVICE_NOT_INUSE, AST_DEVSTATE_CACHABLE, "IAX2/%s", peer->name); /* Activate notification */
11340 }
11341 } else if ((peer->historicms > 0) && (peer->historicms <= peer->maxms)) {
11342 if (iaxs[fr->callno]->pingtime > peer->maxms) {
11343 ast_log(LOG_NOTICE, "Peer '%s' is now TOO LAGGED (%u ms)!\n", peer->name, iaxs[fr->callno]->pingtime);
11345 blob = ast_json_pack("{s: s, s: I}",
11346 "peer_status", "Lagged",
11347 "time", (ast_json_int_t)iaxs[fr->callno]->pingtime);
11348 ast_devstate_changed(AST_DEVICE_UNAVAILABLE, AST_DEVSTATE_CACHABLE, "IAX2/%s", peer->name); /* Activate notification */
11349 }
11350 }
11352 peer->lastms = iaxs[fr->callno]->pingtime;
11353 if (peer->smoothing && (peer->lastms > -1))
11354 peer->historicms = (iaxs[fr->callno]->pingtime + peer->historicms) / 2;
11355 else if (peer->smoothing && peer->lastms < 0)
11356 peer->historicms = (0 + peer->historicms) / 2;
11357 else
11358 peer->historicms = iaxs[fr->callno]->pingtime;
11359
11360 /* Remove scheduled iax2_poke_noanswer */
11361 if (peer->pokeexpire > -1) {
11362 if (!AST_SCHED_DEL(sched, peer->pokeexpire)) {
11363 peer_unref(peer);
11364 peer->pokeexpire = -1;
11365 }
11366 }
11367 /* Schedule the next cycle */
11368 if ((peer->lastms < 0) || (peer->historicms > peer->maxms))
11370 else
11372 if (peer->pokeexpire == -1)
11373 peer_unref(peer);
11374 /* and finally send the ack */
11376 /* And wrap up the qualify call */
11377 iax2_destroy(fr->callno);
11378 peer->callno = 0;
11379 ast_debug(1, "Peer %s: got pong, lastms %d, historicms %d, maxms %d\n", peer->name, peer->lastms, peer->historicms, peer->maxms);
11380 }
11381 break;
11382 case IAX_COMMAND_LAGRQ:
11383 case IAX_COMMAND_LAGRP:
11384 f.src = "LAGRQ";
11385 f.mallocd = 0;
11386 f.offset = 0;
11387 f.samples = 0;
11388 iax_frame_wrap(fr, &f);
11390 /* Received a LAGRQ - echo back a LAGRP */
11392 iax2_send(iaxs[fr->callno], &fr->af, fr->ts, -1, 0, 0, 0);
11393 } else {
11394 /* Received LAGRP in response to our LAGRQ */
11395 unsigned int ts;
11396 /* This is a reply we've been given, actually measure the difference */
11397 ts = calc_timestamp(iaxs[fr->callno], 0, &fr->af);
11398 iaxs[fr->callno]->lag = ts - fr->ts;
11399 if (iaxdebug)
11400 ast_debug(1, "Peer %s lag measured as %dms\n",
11401 ast_sockaddr_stringify(&addr), iaxs[fr->callno]->lag);
11402 }
11403 break;
11406 ast_log(LOG_WARNING, "Call on %s is already up, can't start on it\n", iaxs[fr->callno]->owner ? ast_channel_name(iaxs[fr->callno]->owner) : "<Unknown>");
11407 break;
11408 }
11409 if (authenticate_reply(iaxs[fr->callno], &iaxs[fr->callno]->addr, &ies, iaxs[fr->callno]->secret, iaxs[fr->callno]->outkey)) {
11410 struct ast_frame hangup_fr = { .frametype = AST_FRAME_CONTROL,
11411 .subclass.integer = AST_CONTROL_HANGUP,
11412 };
11414 "I don't know how to authenticate %s to %s\n",
11415 ies.username ? ies.username : "<unknown>", ast_sockaddr_stringify(&addr));
11416 iax2_queue_frame(fr->callno, &hangup_fr);
11417 }
11418 break;
11420 /* For security, always ack immediately */
11421 if (delayreject)
11423 /* Ignore once we've started */
11425 ast_log(LOG_WARNING, "Call on %s is already up, can't start on it\n", iaxs[fr->callno]->owner ? ast_channel_name(iaxs[fr->callno]->owner) : "<Unknown>");
11426 break;
11427 }
11428 if (authenticate_verify(iaxs[fr->callno], &ies)) {
11429 if (authdebug)
11430 ast_log(LOG_WARNING, "Host %s failed to authenticate as %s\n", ast_sockaddr_stringify(&addr),
11431 iaxs[fr->callno]->username);
11432 memset(&ied0, 0, sizeof(ied0));
11434 break;
11435 }
11436 if (strcasecmp(iaxs[fr->callno]->exten, "TBD")) {
11437 /* This might re-enter the IAX code and need the lock */
11439 } else
11440 exists = 0;
11441 if (strcmp(iaxs[fr->callno]->exten, "TBD") && !exists) {
11442 if (authdebug)
11443 ast_log(LOG_WARNING, "Rejected connect attempt from %s, request '%s@%s' does not exist\n",
11445 iaxs[fr->callno]->exten,
11446 iaxs[fr->callno]->context);
11447 memset(&ied0, 0, sizeof(ied0));
11448 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
11450 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11451 if (!iaxs[fr->callno]) {
11452 break;
11453 }
11454 } else {
11455 /* Select an appropriate format */
11458 using_prefs = "reqonly";
11459 } else {
11460 using_prefs = "disabled";
11461 }
11462 format = iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability;
11463 memset(&pref, 0, sizeof(pref));
11464 strcpy(caller_pref_buf, "disabled");
11465 strcpy(host_pref_buf, "disabled");
11466 } else {
11467 struct ast_format *tmpfmt;
11468 using_prefs = "mine";
11469 if (ies.codec_prefs)
11471 if (iax2_codec_pref_index(&iaxs[fr->callno]->rprefs, 0, &tmpfmt)) {
11473 pref = iaxs[fr->callno]->rprefs;
11474 using_prefs = "caller";
11475 } else {
11476 pref = iaxs[fr->callno]->prefs;
11477 }
11478 } else /* if no codec_prefs IE do it the old way */
11479 pref = iaxs[fr->callno]->prefs;
11480 format = iax2_codec_choose(&pref, iaxs[fr->callno]->capability & iaxs[fr->callno]->peercapability);
11481 iax2_codec_pref_string(&iaxs[fr->callno]->rprefs, caller_pref_buf, sizeof(caller_pref_buf) - 1);
11482 iax2_codec_pref_string(&iaxs[fr->callno]->prefs, host_pref_buf, sizeof(host_pref_buf) - 1);
11483 }
11484 if (!format) {
11487 struct ast_str *peer_form_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
11488
11490 ast_debug(1, "We don't do requested format %s, falling back to peer capability '%s'\n",
11493 format = iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability;
11494 }
11495 if (!format) {
11496 if (authdebug) {
11498 ast_log(LOG_WARNING, "Rejected connect attempt from %s, requested '%s' incompatible with our capability '%s'.\n",
11500 iax2_getformatname_multiple(iaxs[fr->callno]->peerformat, &peer_form_buf),
11502 } else {
11503 ast_log(LOG_WARNING, "Rejected connect attempt from %s, requested/capability '%s'/'%s' incompatible with our capability '%s'.\n",
11505 iax2_getformatname_multiple(iaxs[fr->callno]->peerformat, &peer_form_buf),
11508 }
11509 }
11510 memset(&ied0, 0, sizeof(ied0));
11511 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
11513 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11514 if (!iaxs[fr->callno]) {
11515 break;
11516 }
11517 } else {
11518 /* Pick one... */
11520 if(!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability))
11521 format = 0;
11522 } else {
11524 using_prefs = ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP) ? "reqonly" : "disabled";
11525 memset(&pref, 0, sizeof(pref));
11527 ? iaxs[fr->callno]->peerformat
11529 strcpy(caller_pref_buf,"disabled");
11530 strcpy(host_pref_buf,"disabled");
11531 } else {
11532 struct ast_format *tmpfmt;
11533 using_prefs = "mine";
11534 if (iax2_codec_pref_index(&iaxs[fr->callno]->rprefs, 0, &tmpfmt)) {
11535 /* Do the opposite of what we tried above. */
11537 pref = iaxs[fr->callno]->prefs;
11538 } else {
11539 pref = iaxs[fr->callno]->rprefs;
11540 using_prefs = "caller";
11541 }
11542 format = iax2_codec_choose(&pref, iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
11543 } else /* if no codec_prefs IE do it the old way */
11545 }
11546 }
11547 if (!format) {
11550 struct ast_str *peer_form_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
11551
11552 ast_log(LOG_ERROR, "No best format in %s???\n",
11554 if (authdebug) {
11556 ast_log(LOG_WARNING, "Rejected connect attempt from %s, requested '%s' incompatible with our capability '%s'.\n",
11558 iax2_getformatname_multiple(iaxs[fr->callno]->peerformat, &peer_form_buf),
11560 } else {
11561 ast_log(LOG_WARNING, "Rejected connect attempt from %s, requested/capability '%s'/'%s' incompatible with our capability '%s'.\n",
11563 iax2_getformatname_multiple(iaxs[fr->callno]->peerformat, &peer_form_buf),
11566 }
11567 }
11568 memset(&ied0, 0, sizeof(ied0));
11569 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
11571 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11572 if (!iaxs[fr->callno]) {
11573 break;
11574 }
11575 }
11576 }
11577 }
11578 if (format) {
11579 /* Authentication received */
11580 memset(&ied1, 0, sizeof(ied1));
11581 iax_ie_append_int(&ied1, IAX_IE_FORMAT, format);
11583 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACCEPT, 0, ied1.buf, ied1.pos, -1);
11584 if (strcmp(iaxs[fr->callno]->exten, "TBD")) {
11585 char authmethodnames[AUTH_METHOD_NAMES_BUFSIZE];
11587 ast_verb(3, "Accepting AUTHENTICATED call from %s:\n"
11588 "%srequested auth methods = (%s),\n"
11589 "%sactual auth method = %s,\n"
11590 "%sencrypted = %s,\n"
11591 "%srequested format = %s,\n"
11592 "%srequested prefs = %s,\n"
11593 "%sactual format = %s,\n"
11594 "%shost prefs = %s,\n"
11595 "%spriority = %s\n",
11598 auth_method_names(iaxs[fr->callno]->authmethods, authmethodnames),
11602 IAX_CALLENCRYPTED(iaxs[fr->callno]) ? "yes" : "no",
11604 iax2_getformatname(iaxs[fr->callno]->peerformat),
11606 caller_pref_buf,
11608 iax2_getformatname(format),
11610 host_pref_buf,
11612 using_prefs);
11613
11614 /* Unlike unauthenticated calls, we don't need to store
11615 * the chosen format for channel creation.
11616 * However, this is helpful for __get_from_jb. */
11617 iaxs[fr->callno]->chosenformat = format;
11618
11620 c = ast_iax2_new(fr->callno, AST_STATE_RING, format,
11621 &iaxs[fr->callno]->rprefs, NULL, NULL, 1);
11622 if (!c) {
11623 iax2_destroy(fr->callno);
11624 } else if (ies.vars) {
11625 struct ast_datastore *variablestore;
11626 struct ast_variable *var, *prev = NULL;
11627 AST_LIST_HEAD(, ast_var_t) *varlist;
11628 varlist = ast_calloc(1, sizeof(*varlist));
11630 if (variablestore && varlist) {
11631 variablestore->data = varlist;
11632 variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
11633 AST_LIST_HEAD_INIT(varlist);
11634 ast_debug(1, "I can haz IAX vars? w00t\n");
11635 for (var = ies.vars; var; var = var->next) {
11636 struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
11637 if (prev)
11638 ast_free(prev);
11639 prev = var;
11640 if (!newvar) {
11641 /* Don't abort list traversal, as this would leave ies.vars in an inconsistent state. */
11642 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
11643 } else {
11644 AST_LIST_INSERT_TAIL(varlist, newvar, entries);
11645 }
11646 }
11647 if (prev)
11648 ast_free(prev);
11649 ies.vars = NULL;
11650 ast_channel_datastore_add(c, variablestore);
11651 } else {
11652 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
11653 if (variablestore)
11654 ast_datastore_free(variablestore);
11655 if (varlist)
11656 ast_free(varlist);
11657 }
11658 }
11659 } else {
11661 /* If this is a TBD call, we're ready but now what... */
11662 ast_verb(3, "Accepted AUTHENTICATED TBD call from %s\n", ast_sockaddr_stringify(&addr));
11664 goto immediatedial;
11665 }
11666 }
11667 }
11668 }
11669 break;
11670 case IAX_COMMAND_DIAL:
11671immediatedial:
11674 ast_string_field_set(iaxs[fr->callno], exten, ies.called_number ? ies.called_number : "s");
11675 if (!ast_exists_extension(NULL, iaxs[fr->callno]->context, iaxs[fr->callno]->exten, 1, iaxs[fr->callno]->cid_num)) {
11676 if (authdebug)
11677 ast_log(LOG_WARNING, "Rejected dial attempt from %s, request '%s@%s' does not exist\n",
11679 iaxs[fr->callno]->exten,
11680 iaxs[fr->callno]->context);
11681 memset(&ied0, 0, sizeof(ied0));
11682 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
11684 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11685 if (!iaxs[fr->callno]) {
11686 break;
11687 }
11688 } else {
11691 ast_verb(3, "Accepting DIAL from %s, formats = %s\n",
11697 iaxs[fr->callno]->peerformat, &iaxs[fr->callno]->rprefs,
11698 NULL, NULL, 1);
11699 if (!c) {
11700 iax2_destroy(fr->callno);
11701 } else if (ies.vars) {
11702 struct ast_datastore *variablestore;
11703 struct ast_variable *var, *prev = NULL;
11704 AST_LIST_HEAD(, ast_var_t) *varlist;
11705 varlist = ast_calloc(1, sizeof(*varlist));
11707 ast_debug(1, "I can haz IAX vars? w00t\n");
11708 if (variablestore && varlist) {
11709 variablestore->data = varlist;
11710 variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
11711 AST_LIST_HEAD_INIT(varlist);
11712 for (var = ies.vars; var; var = var->next) {
11713 struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
11714 if (prev)
11715 ast_free(prev);
11716 prev = var;
11717 if (!newvar) {
11718 /* Don't abort list traversal, as this would leave ies.vars in an inconsistent state. */
11719 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
11720 } else {
11721 AST_LIST_INSERT_TAIL(varlist, newvar, entries);
11722 }
11723 }
11724 if (prev)
11725 ast_free(prev);
11726 ies.vars = NULL;
11727 ast_channel_datastore_add(c, variablestore);
11728 } else {
11729 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
11730 if (variablestore)
11731 ast_datastore_free(variablestore);
11732 if (varlist)
11733 ast_free(varlist);
11734 }
11735 }
11736 }
11737 }
11738 break;
11739 case IAX_COMMAND_INVAL:
11740 iaxs[fr->callno]->error = ENOTCONN;
11741 ast_debug(1, "Immediately destroying %d, having received INVAL\n", fr->callno);
11742 iax2_destroy(fr->callno);
11743 ast_debug(1, "Destroying call %d\n", fr->callno);
11744 break;
11745 case IAX_COMMAND_VNAK:
11746 ast_debug(1, "Received VNAK: resending outstanding frames\n");
11747 /* Force retransmission */
11748 vnak_retransmit(fr->callno, fr->iseqno);
11749 break;
11750 case IAX_COMMAND_REGREQ:
11751 case IAX_COMMAND_REGREL:
11752 /* For security, always ack immediately */
11753 if (delayreject)
11755 if (register_verify(fr->callno, &addr, &ies)) {
11756 if (!iaxs[fr->callno]) {
11757 break;
11758 }
11759 /* Send delayed failure */
11761 break;
11762 }
11763 if (!iaxs[fr->callno]) {
11764 break;
11765 }
11768
11770 ast_sockaddr_setnull(&addr);
11771 }
11772 if (update_registry(&addr, fr->callno, ies.devicetype, fd, ies.refresh)) {
11773 ast_log(LOG_WARNING, "Registry error\n");
11774 }
11775 if (!iaxs[fr->callno]) {
11776 break;
11777 }
11778 if (ies.provverpres && ies.serviceident && !(ast_sockaddr_isnull(&addr))) {
11780 check_provisioning(&addr, fd, ies.serviceident, ies.provver);
11782 }
11783 break;
11784 }
11786 break;
11787 case IAX_COMMAND_REGACK:
11788 if (iax2_ack_registry(&ies, &addr, fr->callno)) {
11789 ast_log(LOG_WARNING, "Registration failure\n");
11790 }
11791 /* Send ack immediately, before we destroy */
11793 iax2_destroy(fr->callno);
11794 break;
11795 case IAX_COMMAND_REGREJ:
11796 if (iaxs[fr->callno]->reg) {
11797 if (authdebug) {
11798 ast_log(LOG_NOTICE, "Registration of '%s' rejected: '%s' from: '%s'\n",
11799 iaxs[fr->callno]->reg->username, ies.cause ? ies.cause : "<unknown>",
11800 ast_sockaddr_stringify(&addr));
11801 }
11802 iax2_publish_registry(iaxs[fr->callno]->reg->username, ast_sockaddr_stringify(&addr), "Rejected", S_OR(ies.cause, "<unknown>"));
11804 }
11805 /* Send ack immediately, before we destroy */
11807 iax2_destroy(fr->callno);
11808 break;
11810 /* Authentication request */
11811 if (registry_rerequest(&ies, fr->callno, &addr)) {
11812 memset(&ied0, 0, sizeof(ied0));
11813 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No authority found");
11815 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11816 }
11817 break;
11818 case IAX_COMMAND_TXREJ:
11819 while (iaxs[fr->callno]
11820 && iaxs[fr->callno]->bridgecallno
11823 }
11824 if (!iaxs[fr->callno]) {
11825 break;
11826 }
11827
11829 ast_verb(3, "Channel '%s' unable to transfer\n", iaxs[fr->callno]->owner ? ast_channel_name(iaxs[fr->callno]->owner) : "<Unknown>");
11830 memset(&iaxs[fr->callno]->transfer, 0, sizeof(iaxs[fr->callno]->transfer));
11831
11832 if (!iaxs[fr->callno]->bridgecallno) {
11833 break;
11834 }
11835
11836 if (iaxs[iaxs[fr->callno]->bridgecallno]
11840 }
11842 break;
11844 while (iaxs[fr->callno]
11845 && iaxs[fr->callno]->bridgecallno
11848 }
11849 if (!iaxs[fr->callno]) {
11850 break;
11851 }
11852
11853 if (iaxs[fr->callno]->transferring == TRANSFER_BEGIN) {
11855 } else if (iaxs[fr->callno]->transferring == TRANSFER_MBEGIN) {
11857 } else {
11858 if (iaxs[fr->callno]->bridgecallno) {
11860 }
11861 break;
11862 }
11863 ast_verb(3, "Channel '%s' ready to transfer\n", iaxs[fr->callno]->owner ? ast_channel_name(iaxs[fr->callno]->owner) : "<Unknown>");
11864
11865 if (!iaxs[fr->callno]->bridgecallno) {
11866 break;
11867 }
11868
11869 if (!iaxs[iaxs[fr->callno]->bridgecallno]
11873 break;
11874 }
11875
11876 /* Both sides are ready */
11877
11878 /* XXX what isn't checked here is that both sides match transfer types. */
11879
11880 if (iaxs[fr->callno]->transferring == TRANSFER_MREADY) {
11881 ast_verb(3, "Attempting media bridge of %s and %s\n", iaxs[fr->callno]->owner ? ast_channel_name(iaxs[fr->callno]->owner) : "<Unknown>",
11882 iaxs[iaxs[fr->callno]->bridgecallno]->owner ? ast_channel_name(iaxs[iaxs[fr->callno]->bridgecallno]->owner) : "<Unknown>");
11883
11886
11887 memset(&ied0, 0, sizeof(ied0));
11888 memset(&ied1, 0, sizeof(ied1));
11891 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXMEDIA, 0, ied0.buf, ied0.pos, -1);
11892 send_command(iaxs[iaxs[fr->callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXMEDIA, 0, ied1.buf, ied1.pos, -1);
11893 } else {
11894 ast_verb(3, "Releasing %s and %s\n", iaxs[fr->callno]->owner ? ast_channel_name(iaxs[fr->callno]->owner) : "<Unknown>",
11895 iaxs[iaxs[fr->callno]->bridgecallno]->owner ? ast_channel_name(iaxs[iaxs[fr->callno]->bridgecallno]->owner) : "<Unknown>");
11896
11901
11902 /* Stop doing lag & ping requests */
11903 stop_stuff(fr->callno);
11905
11906 memset(&ied0, 0, sizeof(ied0));
11907 memset(&ied1, 0, sizeof(ied1));
11910 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXREL, 0, ied0.buf, ied0.pos, -1);
11911 send_command(iaxs[iaxs[fr->callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXREL, 0, ied1.buf, ied1.pos, -1);
11912 }
11914 break;
11915 case IAX_COMMAND_TXREQ:
11916 try_transfer(iaxs[fr->callno], &ies);
11917 break;
11918 case IAX_COMMAND_TXCNT:
11919 if (iaxs[fr->callno]->transferring)
11921 break;
11922 case IAX_COMMAND_TXREL:
11923 /* Send ack immediately, rather than waiting until we've changed addresses */
11925 complete_transfer(fr->callno, &ies);
11926 stop_stuff(fr->callno); /* for attended transfer to work with libiax */
11927 break;
11929 if (iaxs[fr->callno]->transferring == TRANSFER_READY) {
11930 AST_LIST_TRAVERSE(&frame_queue[fr->callno], cur, list) {
11931 /* Cancel any outstanding frames and start anew */
11932 if (cur->transfer) {
11933 cur->retries = -1;
11934 }
11935 }
11936 /* Start sending our media to the transfer address, but otherwise leave the call as-is */
11938 }
11939 break;
11940 case IAX_COMMAND_RTKEY:
11941 if (!IAX_CALLENCRYPTED(iaxs[fr->callno])) {
11943 "we've been told to rotate our encryption key, "
11944 "but this isn't an encrypted call. bad things will happen.\n"
11945 );
11946 break;
11947 }
11948
11949 IAX_DEBUGDIGEST("Receiving", ies.challenge);
11950
11951 ast_aes_set_decrypt_key((unsigned char *) ies.challenge, &iaxs[fr->callno]->dcx);
11952 break;
11953 case IAX_COMMAND_DPREP:
11954 complete_dpreply(iaxs[fr->callno], &ies);
11955 break;
11957 ast_log(LOG_NOTICE, "Peer did not understand our iax command '%d'\n", ies.iax_unknown);
11958 break;
11960 /* Firmware download */
11963 break;
11964 }
11965 memset(&ied0, 0, sizeof(ied0));
11966 res = iax_firmware_append(&ied0, ies.devicetype, ies.fwdesc);
11967 if (res < 0)
11968 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11969 else if (res > 0)
11970 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_FWDATA, 0, ied0.buf, ied0.pos, -1);
11971 else
11972 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_FWDATA, 0, ied0.buf, ied0.pos, -1);
11973 break;
11975 {
11976 struct iax_frame *cur;
11977 /* find last sent frame */
11978 if ((cur = AST_LIST_LAST(&frame_queue[fr->callno])) && ies.calltoken && ies.calltokendata) {
11979 resend_with_token(fr->callno, cur, (char *) ies.calltokendata);
11980 }
11981 break;
11982 }
11983 default:
11984 ast_debug(1, "Unknown IAX command %d on %d/%d\n", f.subclass.integer, fr->callno, iaxs[fr->callno]->peercallno);
11985 memset(&ied0, 0, sizeof(ied0));
11987 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_UNSUPPORT, 0, ied0.buf, ied0.pos, -1);
11988 }
11989 /* Free remote variables (if any) */
11990 if (ies.vars) {
11992 ast_debug(1, "I can haz IAX vars, but they is no good :-(\n");
11993 ies.vars = NULL;
11994 }
11995
11996 /* Don't actually pass these frames along */
11997 if ((f.subclass.integer != IAX_COMMAND_ACK) &&
12002 if (iaxs[fr->callno] && iaxs[fr->callno]->aseqno != iaxs[fr->callno]->iseqno) {
12004 }
12005 }
12007 return 1;
12008 }
12009 /* Unless this is an ACK or INVAL frame, ack it */
12010 if (iaxs[fr->callno] && iaxs[fr->callno]->aseqno != iaxs[fr->callno]->iseqno)
12012 } else if (minivid) {
12014 if (iaxs[fr->callno]->videoformat > 0) {
12015 if (ntohs(vh->ts) & 0x8000LL) {
12016 f.subclass.frame_ending = 1;
12017 }
12019 if (!f.subclass.format) {
12022 return 1;
12023 }
12024 } else {
12025 ast_log(LOG_WARNING, "Received mini frame before first full video frame\n");
12026 iax2_vnak(fr->callno);
12029 return 1;
12030 }
12031 f.datalen = res - sizeof(*vh);
12032 if (f.datalen < 0) {
12033 ast_log(LOG_ERROR, "Dropping malformed frame (datalen %d?)\n", f.datalen);
12036 return 1;
12037 }
12038 if (f.datalen)
12039 f.data.ptr = thread->buf + sizeof(*vh);
12040 else
12041 f.data.ptr = NULL;
12042#ifdef IAXTESTS
12043 if (test_resync) {
12044 fr->ts = (iaxs[fr->callno]->last & 0xFFFF8000L) | ((ntohs(vh->ts) + test_resync) & 0x7fff);
12045 } else
12046#endif /* IAXTESTS */
12047 fr->ts = (iaxs[fr->callno]->last & 0xFFFF8000L) | (ntohs(vh->ts) & 0x7fff);
12048 } else {
12049 /* A mini frame */
12051 if (iaxs[fr->callno]->voiceformat > 0) {
12053 if (!f.subclass.format) {
12056 return 1;
12057 }
12058 } else {
12059 ast_debug(1, "Received mini frame before first full voice frame\n");
12060 iax2_vnak(fr->callno);
12063 return 1;
12064 }
12065 f.datalen = res - sizeof(struct ast_iax2_mini_hdr);
12066 if (f.datalen < 0) {
12067 ast_log(LOG_ERROR, "Dropping malformed frame (datalen %d?)\n", f.datalen);
12070 return 1;
12071 }
12072 if (f.datalen)
12073 f.data.ptr = thread->buf + sizeof(*mh);
12074 else
12075 f.data.ptr = NULL;
12076#ifdef IAXTESTS
12077 if (test_resync) {
12078 fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | ((ntohs(mh->ts) + test_resync) & 0xffff);
12079 } else
12080#endif /* IAXTESTS */
12081 fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | ntohs(mh->ts);
12082 /* FIXME? Surely right here would be the right place to undo timestamp wraparound? */
12083 }
12084
12085 /* Don't pass any packets until we're started */
12086 if (!iaxs[fr->callno]
12090 return 1;
12091 }
12092
12093 if (f.frametype == AST_FRAME_CONTROL) {
12095 /* Control frame not allowed to come from the wire. */
12096 ast_debug(2, "Callno %d: Blocked receiving control frame %d.\n",
12097 fr->callno, f.subclass.integer);
12100 return 1;
12101 }
12104 if (iaxs[fr->callno]
12106 /* We are not configured to allow receiving these updates. */
12107 ast_debug(2, "Callno %d: Config blocked receiving control frame %d.\n",
12108 fr->callno, f.subclass.integer);
12111 return 1;
12112 }
12113 }
12114
12116 if (iaxs[fr->callno] && iaxs[fr->callno]->owner) {
12119 } else if (f.subclass.integer == AST_CONTROL_CONGESTION) {
12121 }
12123 }
12124 }
12125
12128 && iaxs[fr->callno]) {
12130
12131 /*
12132 * Process a received connected line update.
12133 *
12134 * Initialize defaults.
12135 */
12137 connected.id.number.presentation = iaxs[fr->callno]->calling_pres;
12138 connected.id.name.presentation = iaxs[fr->callno]->calling_pres;
12139
12141 ast_string_field_set(iaxs[fr->callno], cid_num, connected.id.number.str);
12142 ast_string_field_set(iaxs[fr->callno], cid_name, connected.id.name.str);
12144
12146 if (iaxs[fr->callno] && iaxs[fr->callno]->owner) {
12148 S_COR(connected.id.number.valid, connected.id.number.str, ""),
12149 S_COR(connected.id.name.valid, connected.id.name.str, ""),
12150 NULL);
12151 ast_channel_caller(iaxs[fr->callno]->owner)->id.number.presentation = connected.id.number.presentation;
12152 ast_channel_caller(iaxs[fr->callno]->owner)->id.name.presentation = connected.id.name.presentation;
12154 }
12155 }
12157 }
12158
12159 /* Common things */
12160 f.src = "IAX2";
12161 f.mallocd = 0;
12162 f.offset = 0;
12163 f.len = 0;
12164 if (f.datalen && (f.frametype == AST_FRAME_VOICE)) {
12166 /* We need to byteswap incoming slinear samples from network byte order */
12169 } else
12170 f.samples = 0;
12171
12172 if (f.datalen < 0) {
12173 ast_log(LOG_ERROR, "Dropping malformed frame (datalen %d?)\n", f.datalen);
12176 return 1;
12177 }
12178
12179 iax_frame_wrap(fr, &f);
12180
12181 /* If this is our most recent packet, use it as our basis for timestamping */
12182 if (iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts) {
12183 /*iaxs[fr->callno]->last = fr->ts; (do it afterwards cos schedule/forward_delivery needs the last ts too)*/
12184 fr->outoforder = 0;
12185 } else {
12186 if (iaxdebug && iaxs[fr->callno]) {
12187 ast_debug(1, "Received out of order packet... (type=%u, subclass %d, ts = %u, last = %u)\n", f.frametype, f.subclass.integer, fr->ts, iaxs[fr->callno]->last);
12188 }
12189 fr->outoforder = 1;
12190 }
12192 if (iaxs[fr->callno]) {
12193 duped_fr = iaxfrdup2(fr);
12194 if (duped_fr) {
12195 schedule_delivery(duped_fr, updatehistory, 0, &fr->ts);
12196 }
12197 }
12198 if (iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts) {
12199 iaxs[fr->callno]->last = fr->ts;
12200#if 1
12201 if (iaxdebug)
12202 ast_debug(8, "For call=%d, set last=%u\n", fr->callno, fr->ts);
12203#endif
12204 }
12205
12206 /* Always run again */
12209 return 1;
12210}
12211
12212static int socket_process(struct iax2_thread *thread)
12213{
12214 int res = socket_process_helper(thread);
12217 }
12218 return res;
12219}
12220
12221/* Function to clean up process thread if it is cancelled */
12222static void iax2_process_thread_cleanup(void *data)
12223{
12224 struct iax2_thread *thread = data;
12225 ast_mutex_destroy(&thread->lock);
12226 ast_cond_destroy(&thread->cond);
12227 ast_mutex_destroy(&thread->init_lock);
12228 ast_cond_destroy(&thread->init_cond);
12230 /* Ignore check_return warning from Coverity for ast_atomic_dec_and_test below */
12232}
12233
12234static void *iax2_process_thread(void *data)
12235{
12236 struct iax2_thread *thread = data;
12237 struct timeval wait;
12238 struct timespec ts;
12239 int put_into_idle = 0;
12240 int first_time = 1;
12241 int old_state;
12242
12244
12245 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &old_state);
12246 pthread_cleanup_push(iax2_process_thread_cleanup, data);
12247
12248 for (;;) {
12249 /* Wait for something to signal us to be awake */
12250 ast_mutex_lock(&thread->lock);
12251
12252 if (thread->stop) {
12253 ast_mutex_unlock(&thread->lock);
12254 break;
12255 }
12256
12257 /* Flag that we're ready to accept signals */
12258 if (first_time) {
12259 signal_condition(&thread->init_lock, &thread->init_cond);
12260 first_time = 0;
12261 }
12262
12263 /* Put into idle list if applicable */
12264 if (put_into_idle) {
12266 }
12267
12268 if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
12269 struct iax2_thread *t = NULL;
12270 /* Wait to be signalled or time out */
12271 wait = ast_tvadd(ast_tvnow(), ast_samp2tv(30000, 1000));
12272 ts.tv_sec = wait.tv_sec;
12273 ts.tv_nsec = wait.tv_usec * 1000;
12274 if (ast_cond_timedwait(&thread->cond, &thread->lock, &ts) == ETIMEDOUT) {
12275 /* This thread was never put back into the available dynamic
12276 * thread list, so just go away. */
12277 if (!put_into_idle || thread->stop) {
12278 ast_mutex_unlock(&thread->lock);
12279 break;
12280 }
12282 /* Account for the case where this thread is acquired *right* after a timeout */
12286 if (t) {
12287 /* This dynamic thread timed out waiting for a task and was
12288 * not acquired immediately after the timeout,
12289 * so it's time to go away. */
12290 ast_mutex_unlock(&thread->lock);
12291 break;
12292 }
12293 /* Someone grabbed our thread *right* after we timed out.
12294 * Wait for them to set us up with something to do and signal
12295 * us to continue. */
12296 wait = ast_tvadd(ast_tvnow(), ast_samp2tv(30000, 1000));
12297 ts.tv_sec = wait.tv_sec;
12298 ts.tv_nsec = wait.tv_usec * 1000;
12299 if (ast_cond_timedwait(&thread->cond, &thread->lock, &ts) == ETIMEDOUT) {
12300 ast_mutex_unlock(&thread->lock);
12301 break;
12302 }
12303 }
12304 } else {
12305 ast_cond_wait(&thread->cond, &thread->lock);
12306 }
12307
12308 /* Go back into our respective list */
12309 put_into_idle = 1;
12310
12311 ast_mutex_unlock(&thread->lock);
12312
12313 if (thread->stop) {
12314 break;
12315 }
12316
12317 /* See what we need to do */
12318 switch (thread->iostate) {
12319 case IAX_IOSTATE_IDLE:
12320 continue;
12321 case IAX_IOSTATE_READY:
12322 thread->actions++;
12323 thread->iostate = IAX_IOSTATE_PROCESSING;
12326 break;
12328 thread->actions++;
12329 thread->iostate = IAX_IOSTATE_PROCESSING;
12330#ifdef SCHED_MULTITHREADED
12331 thread->schedfunc(thread->scheddata);
12332#endif
12333 break;
12334 default:
12335 break;
12336 }
12337
12338 /* The network thread added us to the active_thread list when we were given
12339 * frames to process, Now that we are done, we must remove ourselves from
12340 * the active list, and return to the idle list */
12344
12345 /* Make sure another frame didn't sneak in there after we thought we were done. */
12347
12348 time(&thread->checktime);
12349 thread->iostate = IAX_IOSTATE_IDLE;
12350#ifdef DEBUG_SCHED_MULTITHREAD
12351 thread->curfunc[0]='\0';
12352#endif
12353 }
12354
12355 /*!
12356 * \note For some reason, idle threads are exiting without being
12357 * removed from an idle list, which is causing memory
12358 * corruption. Forcibly remove it from the list, if it's there.
12359 */
12363
12367
12368 if (!thread->stop) {
12369 /* Nobody asked me to stop so nobody is waiting to join me. */
12370 pthread_detach(pthread_self());
12371 }
12372
12373 /* I am exiting here on my own volition, I need to clean up my own data structures
12374 * Assume that I am no longer in any of the lists (idle, active, or dynamic)
12375 */
12376 pthread_cleanup_pop(1);
12377 return NULL;
12378}
12379
12380static int iax2_do_register(struct iax2_registry *reg)
12381{
12382 struct iax_ie_data ied;
12383 if (iaxdebug)
12384 ast_debug(1, "Sending registration request for '%s'\n", reg->username);
12385
12386 if (reg->dnsmgr &&
12387 ((reg->regstate == REG_STATE_TIMEOUT) || ast_sockaddr_isnull(&reg->addr))) {
12388 /* Maybe the IP has changed, force DNS refresh */
12390 }
12391
12392 /*
12393 * if IP has Changed, free allocated call to create a new one with new IP
12394 * call has the pointer to IP and must be updated to the new one
12395 */
12396 if (reg->dnsmgr && ast_dnsmgr_changed(reg->dnsmgr) && (reg->callno > 0)) {
12397 int callno = reg->callno;
12398 ast_mutex_lock(&iaxsl[callno]);
12399 iax2_destroy(callno);
12400 ast_mutex_unlock(&iaxsl[callno]);
12401 reg->callno = 0;
12402 }
12403 if (ast_sockaddr_isnull(&reg->addr)) {
12404 if (iaxdebug)
12405 ast_debug(1, "Unable to send registration request for '%s' without IP address\n", reg->username);
12406 /* Setup the next registration attempt */
12408 (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
12409 return -1;
12410 }
12411 if (!ast_sockaddr_port(&reg->addr) && reg->port) {
12412 ast_sockaddr_set_port(&reg->addr, reg->port);
12413 }
12414
12415 if (!reg->callno) {
12416
12417 ast_debug(3, "Allocate call number\n");
12418
12419 reg->callno = find_callno_locked(0, 0, &reg->addr, NEW_FORCE, defaultsockfd, 0);
12420 if (reg->callno < 1) {
12421 ast_log(LOG_WARNING, "Unable to create call for registration\n");
12422 return -1;
12423 } else
12424 ast_debug(3, "Registration created on call %d\n", reg->callno);
12425 iaxs[reg->callno]->reg = reg;
12427 }
12428 /* Setup the next registration a little early */
12430 (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
12431 /* Send the request */
12432 memset(&ied, 0, sizeof(ied));
12435 add_empty_calltoken_ie(iaxs[reg->callno], &ied); /* this _MUST_ be the last ie added */
12438 return 0;
12439}
12440
12441static int iax2_provision(struct ast_sockaddr *end, int sockfd, const char *dest, const char *template, int force)
12442{
12443 /* Returns 1 if provisioned, -1 if not able to find destination, or 0 if no provisioning
12444 is found for template */
12445 struct iax_ie_data provdata;
12446 struct iax_ie_data ied;
12447 unsigned int sig;
12448 struct ast_sockaddr addr;
12449 int callno;
12450 struct create_addr_info cai;
12451
12452 memset(&cai, 0, sizeof(cai));
12453
12454 ast_debug(1, "Provisioning '%s' from template '%s'\n", dest, template);
12455
12456 if (iax_provision_build(&provdata, &sig, template, force)) {
12457 ast_debug(1, "No provisioning found for template '%s'\n", template);
12458 return 0;
12459 }
12460
12461 if (end) {
12462 ast_sockaddr_copy(&addr, end);
12463 cai.sockfd = sockfd;
12464 } else if (create_addr(dest, NULL, &addr, &cai))
12465 return -1;
12466
12467 /* Build the rest of the message */
12468 memset(&ied, 0, sizeof(ied));
12469 iax_ie_append_raw(&ied, IAX_IE_PROVISIONING, provdata.buf, provdata.pos);
12470
12471 callno = find_callno_locked(0, 0, &addr, NEW_FORCE, cai.sockfd, 0);
12472 if (!callno)
12473 return -1;
12474
12475 if (iaxs[callno]) {
12476 /* Schedule autodestruct in case they don't ever give us anything back */
12477 iaxs[callno]->autoid = iax2_sched_replace(iaxs[callno]->autoid,
12478 sched, 15000, auto_hangup, (void *)(long)callno);
12480 /* Got a call number now, so go ahead and send the provisioning information */
12481 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PROVISION, 0, ied.buf, ied.pos, -1);
12482 }
12483 ast_mutex_unlock(&iaxsl[callno]);
12484
12485 return 1;
12486}
12487
12488static char *papp = "IAX2Provision";
12489
12490/*! iax2provision
12491\ingroup applications
12492*/
12493static int iax2_prov_app(struct ast_channel *chan, const char *data)
12494{
12495 int res;
12496 char *sdata;
12497 char *opts;
12498 int force =0;
12499 unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(chan));
12500 if (ast_strlen_zero(data))
12501 data = "default";
12502 sdata = ast_strdupa(data);
12503 opts = strchr(sdata, '|');
12504 if (opts)
12505 *opts='\0';
12506
12507 if (ast_channel_tech(chan) != &iax2_tech) {
12508 ast_log(LOG_NOTICE, "Can't provision a non-IAX device!\n");
12509 return -1;
12510 }
12511 if (!callno || !iaxs[callno] || ast_sockaddr_isnull(&iaxs[callno]->addr)) {
12512 ast_log(LOG_NOTICE, "Can't provision something with no IP?\n");
12513 return -1;
12514 }
12515 res = iax2_provision(&iaxs[callno]->addr, iaxs[callno]->sockfd, NULL, sdata, force);
12516 ast_verb(3, "Provisioned IAXY at '%s' with '%s'= %d\n",
12517 ast_sockaddr_stringify(&iaxs[callno]->addr),
12518 sdata, res);
12519 return res;
12520}
12521
12522static char *handle_cli_iax2_provision(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
12523{
12524 int force = 0;
12525 int res;
12526
12527 switch (cmd) {
12528 case CLI_INIT:
12529 e->command = "iax2 provision";
12530 e->usage =
12531 "Usage: iax2 provision <host> <template> [forced]\n"
12532 " Provisions the given peer or IP address using a template\n"
12533 " matching either 'template' or '*' if the template is not\n"
12534 " found. If 'forced' is specified, even empty provisioning\n"
12535 " fields will be provisioned as empty fields.\n";
12536 return NULL;
12537 case CLI_GENERATE:
12538 if (a->pos == 3)
12539 return iax_prov_complete_template(a->line, a->word, a->pos, a->n);
12540 return NULL;
12541 }
12542
12543 if (a->argc < 4)
12544 return CLI_SHOWUSAGE;
12545 if (a->argc > 4) {
12546 if (!strcasecmp(a->argv[4], "forced"))
12547 force = 1;
12548 else
12549 return CLI_SHOWUSAGE;
12550 }
12551 res = iax2_provision(NULL, -1, a->argv[2], a->argv[3], force);
12552 if (res < 0)
12553 ast_cli(a->fd, "Unable to find peer/address '%s'\n", a->argv[2]);
12554 else if (res < 1)
12555 ast_cli(a->fd, "No template (including wildcard) matching '%s'\n", a->argv[3]);
12556 else
12557 ast_cli(a->fd, "Provisioning '%s' with template '%s'%s\n", a->argv[2], a->argv[3], force ? ", forced" : "");
12558 return CLI_SUCCESS;
12559}
12560
12561static void __iax2_poke_noanswer(const void *data)
12562{
12563 struct iax2_peer *peer = (struct iax2_peer *)data;
12564 int callno;
12565
12566 if (peer->lastms > -1) {
12567 RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
12568
12569 ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE! Time: %d\n", peer->name, peer->lastms);
12571 blob = ast_json_pack("{s: s, s: i}",
12572 "peer_status", "Unreachable",
12573 "time", peer->lastms);
12575 ast_devstate_changed(AST_DEVICE_UNAVAILABLE, AST_DEVSTATE_CACHABLE, "IAX2/%s", peer->name); /* Activate notification */
12576 }
12577 if ((callno = peer->callno) > 0) {
12581 }
12582 peer->callno = 0;
12583 peer->lastms = -1;
12584 /* Try again quickly */
12586 if (peer->pokeexpire == -1)
12587 peer_unref(peer);
12588}
12589
12590static int iax2_poke_noanswer(const void *data)
12591{
12592 struct iax2_peer *peer = (struct iax2_peer *)data;
12593 peer->pokeexpire = -1;
12594#ifdef SCHED_MULTITHREADED
12596#endif
12598 peer_unref(peer);
12599 return 0;
12600}
12601
12602static int iax2_poke_peer_cb(void *obj, void *arg, int flags)
12603{
12604 struct iax2_peer *peer = obj;
12605
12606 iax2_poke_peer(peer, 0);
12607
12608 return 0;
12609}
12610
12611static int iax2_poke_peer(struct iax2_peer *peer, int heldcall)
12612{
12613 int callno;
12614 int poke_timeout;
12615
12616 if (!peer->maxms || (ast_sockaddr_isnull(&peer->addr) && !peer->dnsmgr)) {
12617 /* IF we have no IP without dnsmgr, or this isn't to be monitored, return
12618 immediately after clearing things out */
12619 peer->lastms = 0;
12620 peer->historicms = 0;
12621 peer->pokeexpire = -1;
12622 peer->callno = 0;
12623 return 0;
12624 }
12625
12626 /* The peer could change the callno inside iax2_destroy, since we do deadlock avoidance */
12627 if ((callno = peer->callno) > 0) {
12628 ast_log(LOG_NOTICE, "Still have a callno...\n");
12632 }
12633 if (heldcall)
12634 ast_mutex_unlock(&iaxsl[heldcall]);
12635 callno = peer->callno = find_callno(0, 0, &peer->addr, NEW_FORCE, peer->sockfd, 0);
12636 if (heldcall)
12637 ast_mutex_lock(&iaxsl[heldcall]);
12638 if (callno < 1) {
12639 ast_log(LOG_WARNING, "Unable to allocate call for poking peer '%s'\n", peer->name);
12640 return -1;
12641 }
12642
12643 if (peer->pokeexpire > -1) {
12644 if (!AST_SCHED_DEL(sched, peer->pokeexpire)) {
12645 peer->pokeexpire = -1;
12646 peer_unref(peer);
12647 }
12648 }
12649
12650 if (peer->lastms < 0){
12651 /* If the host is already unreachable then use time less than the unreachable
12652 * interval. 5/6 is arbitrary multiplier to get value less than
12653 * peer->pokefreqnotok. Value less than peer->pokefreqnotok is used to expire
12654 * current POKE before starting new POKE (which is scheduled after
12655 * peer->pokefreqnotok). */
12656 poke_timeout = peer->pokefreqnotok * 5 / 6;
12657 } else {
12658 /* If the host is reachable, use timeout large enough to allow for multiple
12659 * POKE retries. Limit this value to less than peer->pokefreqok. 5/6 is arbitrary
12660 * multiplier to get value less than peer->pokefreqok. Value less than
12661 * peer->pokefreqok is used to expire current POKE before starting new POKE
12662 * (which is scheduled after peer->pokefreqok). */
12663 poke_timeout = MIN(MAX_RETRY_TIME * 2 + peer->maxms, peer->pokefreqok * 5 / 6);
12664 }
12665
12666 /* Queue up a new task to handle no reply */
12667 peer->pokeexpire = iax2_sched_add(sched, poke_timeout, iax2_poke_noanswer, peer_ref(peer));
12668
12669 if (peer->pokeexpire == -1)
12670 peer_unref(peer);
12671
12672 /* And send the poke */
12674 if (iaxs[callno]) {
12675 struct iax_ie_data ied = {
12676 .buf = { 0 },
12677 .pos = 0,
12678 };
12679
12680 /* Speed up retransmission times for this qualify call */
12681 iaxs[callno]->pingtime = peer->maxms / 8;
12682 iaxs[callno]->peerpoke = peer;
12683
12684 add_empty_calltoken_ie(iaxs[callno], &ied); /* this _MUST_ be the last ie added */
12685 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_POKE, 0, ied.buf, ied.pos, -1);
12686 }
12687 ast_mutex_unlock(&iaxsl[callno]);
12688
12689 return 0;
12690}
12691
12692static void free_context(struct iax2_context *con)
12693{
12694 struct iax2_context *conl;
12695 while(con) {
12696 conl = con;
12697 con = con->next;
12698 ast_free(conl);
12699 }
12700}
12701
12702static struct ast_channel *iax2_request(const char *type, struct ast_format_cap *cap, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor, const char *data, int *cause)
12703{
12704 int callno;
12705 int res;
12706 struct ast_sockaddr addr;
12707 struct ast_channel *c;
12708 struct parsed_dial_string pds;
12709 struct create_addr_info cai;
12710 char *tmpstr;
12711 ast_callid callid;
12712
12713 memset(&pds, 0, sizeof(pds));
12714 tmpstr = ast_strdupa(data);
12715 parse_dial_string(tmpstr, &pds);
12716
12718
12719 if (ast_strlen_zero(pds.peer)) {
12720 ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", data);
12721 return NULL;
12722 }
12723 memset(&cai, 0, sizeof(cai));
12725
12727
12728 /* Populate our address from the given */
12729 if (create_addr(pds.peer, NULL, &addr, &cai)) {
12730 *cause = AST_CAUSE_UNREGISTERED;
12731 return NULL;
12732 }
12733
12734 if (pds.port) {
12735 int bindport;
12736 ast_parse_arg(pds.port, PARSE_UINT32 | PARSE_IN_RANGE, &bindport, 0, 65535);
12737 ast_sockaddr_set_port(&addr, bindport);
12738 }
12739
12740 callno = find_callno_locked(0, 0, &addr, NEW_FORCE, cai.sockfd, 0);
12741 if (callno < 1) {
12742 ast_log(LOG_WARNING, "Unable to create call\n");
12743 *cause = AST_CAUSE_CONGESTION;
12744 return NULL;
12745 }
12746
12747 /* If this is a trunk, update it now */
12749 if (ast_test_flag64(&cai, IAX_TRUNK)) {
12750 int new_callno;
12751 if ((new_callno = make_trunk(callno, 1)) != -1)
12752 callno = new_callno;
12753 }
12754 iaxs[callno]->maxtime = cai.maxtime;
12755 if (callid) {
12756 iax_pvt_callid_set(callno, callid);
12757 }
12758
12759 if (cai.found) {
12760 ast_string_field_set(iaxs[callno], host, pds.peer);
12761 }
12762
12763 c = ast_iax2_new(callno, AST_STATE_DOWN, cai.capability, &cai.prefs, assignedids,
12764 requestor, cai.found);
12765
12766 ast_mutex_unlock(&iaxsl[callno]);
12767
12768 if (c) {
12769 struct ast_format_cap *joint;
12770 struct ast_format *format;
12771 if (callid) {
12773 ast_channel_callid_set(c, callid);
12775 }
12776
12778 if (!joint) {
12779 ast_hangup(c);
12780 return NULL;
12781 }
12782
12784
12785 /* If there is no joint format find one through translation */
12786 if (!ast_format_cap_count(joint)) {
12787 struct ast_format *best_fmt_cap = NULL;
12788 struct ast_format *best_fmt_native = NULL;
12789
12790 res = ast_translator_best_choice(cap, ast_channel_nativeformats(c), &best_fmt_cap, &best_fmt_native);
12791 if (res < 0) {
12792 struct ast_str *native_cap_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
12794
12795 ast_log(LOG_WARNING, "Unable to create translator path for %s to %s on %s\n",
12797 ast_format_cap_get_names(cap, &cap_buf),
12799 ast_hangup(c);
12800 ao2_ref(joint, -1);
12801 return NULL;
12802 }
12803 ast_format_cap_append(joint, best_fmt_native, 0);
12804 ao2_ref(best_fmt_cap, -1);
12805 ao2_ref(best_fmt_native, -1);
12806 }
12811
12812 ao2_ref(joint, -1);
12813 ao2_ref(format, -1);
12814 }
12815
12816 return c;
12817}
12818
12819static void *network_thread(void *ignore)
12820{
12821 int res;
12822
12823 if (timer) {
12825 }
12826
12827 for (;;) {
12828 pthread_testcancel();
12829 /* Wake up once a second just in case SIGURG was sent while
12830 * we weren't in poll(), to make sure we don't hang when trying
12831 * to unload. */
12832 res = ast_io_wait(io, 1000);
12833 /* Timeout(=0), and EINTR is not a thread exit condition. We do
12834 * not want to exit the thread loop on these conditions. */
12835 if (res < 0 && errno != -EINTR) {
12836 ast_log(LOG_ERROR, "IAX2 network thread unexpected exit: %s\n", strerror(errno));
12837 break;
12838 }
12839 }
12840
12841 return NULL;
12842}
12843
12844static int start_network_thread(void)
12845{
12846 struct iax2_thread *thread;
12847 int threadcount = 0;
12848 int x;
12849 for (x = 0; x < iaxthreadcount; x++) {
12850 thread = ast_calloc(1, sizeof(*thread));
12851 if (thread) {
12853 thread->threadnum = ++threadcount;
12854 ast_mutex_init(&thread->lock);
12855 ast_cond_init(&thread->cond, NULL);
12856 ast_mutex_init(&thread->init_lock);
12857 ast_cond_init(&thread->init_cond, NULL);
12858
12859 ast_mutex_lock(&thread->init_lock);
12860
12862 ast_log(LOG_WARNING, "Failed to create new thread!\n");
12863 ast_mutex_destroy(&thread->lock);
12864 ast_cond_destroy(&thread->cond);
12865 ast_mutex_unlock(&thread->init_lock);
12866 ast_mutex_destroy(&thread->init_lock);
12867 ast_cond_destroy(&thread->init_cond);
12869 thread = NULL;
12870 continue;
12871 }
12872 /* Wait for the thread to be ready */
12873 ast_cond_wait(&thread->init_cond, &thread->init_lock);
12874
12875 /* Done with init_lock */
12876 ast_mutex_unlock(&thread->init_lock);
12877
12881 }
12882 }
12884 ast_log(LOG_ERROR, "Failed to create new thread!\n");
12885 return -1;
12886 }
12887 ast_verb(2, "%d helper threads started\n", threadcount);
12888 return 0;
12889}
12890
12891static struct iax2_context *build_context(const char *context)
12892{
12893 struct iax2_context *con;
12894
12895 if ((con = ast_calloc(1, sizeof(*con))))
12896 ast_copy_string(con->context, context, sizeof(con->context));
12897
12898 return con;
12899}
12900
12901static int get_auth_methods(const char *value)
12902{
12903 int methods = 0;
12904 if (strstr(value, "rsa"))
12906 if (strstr(value, "md5"))
12908 if (strstr(value, "plaintext"))
12910 return methods;
12911}
12912
12913
12914/*! \brief Check if address can be used as packet source.
12915 \retval 0 address available
12916 \retval 1 address unavailable
12917 \retval -1 error
12918*/
12919static int check_srcaddr(struct ast_sockaddr *addr)
12920{
12921 int sd;
12922
12923 sd = socket(addr->ss.ss_family, SOCK_DGRAM, 0);
12924 if (sd < 0) {
12925 ast_log(LOG_ERROR, "Socket: %s\n", strerror(errno));
12926 return -1;
12927 }
12928
12929 if (ast_bind(sd, addr) < 0) {
12930 ast_debug(1, "Can't bind: %s\n", strerror(errno));
12931 close(sd);
12932 return 1;
12933 }
12934
12935 close(sd);
12936 return 0;
12937}
12938
12939/*! \brief Parse the "sourceaddress" value,
12940 lookup in netsock list and set peer's sockfd. Defaults to defaultsockfd if
12941 not found. */
12942static int peer_set_srcaddr(struct iax2_peer *peer, const char *srcaddr)
12943{
12944 struct ast_sockaddr addr;
12945 int nonlocal = 1;
12946 int port = IAX_DEFAULT_PORTNO;
12947 int sockfd = defaultsockfd;
12948 char *tmp;
12949 char *host;
12950 char *portstr;
12951
12952 tmp = ast_strdupa(srcaddr);
12953 ast_sockaddr_split_hostport(tmp, &host, &portstr, 0);
12954
12955 if (portstr) {
12956 port = atoi(portstr);
12957 if (port < 1)
12958 port = IAX_DEFAULT_PORTNO;
12959 }
12960
12961 addr.ss.ss_family = AST_AF_UNSPEC;
12962 if (!ast_get_ip(&addr, host)) {
12963 struct ast_netsock *sock;
12964
12965 if (check_srcaddr(&addr) == 0) {
12966 /* ip address valid. */
12967 ast_sockaddr_set_port(&addr, port);
12968
12969 if (!(sock = ast_netsock_find(netsock, &addr)))
12970 sock = ast_netsock_find(outsock, &addr);
12971 if (sock) {
12972 sockfd = ast_netsock_sockfd(sock);
12973 nonlocal = 0;
12974 } else {
12975 /* INADDR_ANY matches anyway! */
12976 ast_sockaddr_parse(&addr, "0.0.0.0", 0);
12977 ast_sockaddr_set_port(&addr, port);
12978 if (ast_netsock_find(netsock, &addr)) {
12979 sock = ast_netsock_bind(outsock, io, srcaddr, port, qos.tos, qos.cos, socket_read, NULL);
12980 if (sock) {
12981 sockfd = ast_netsock_sockfd(sock);
12982 ast_netsock_unref(sock);
12983 nonlocal = 0;
12984 } else {
12985 nonlocal = 2;
12986 }
12987 }
12988 }
12989 }
12990 }
12991
12992 peer->sockfd = sockfd;
12993
12994 if (nonlocal == 1) {
12996 "Non-local or unbound address specified (%s) in sourceaddress for '%s', reverting to default\n",
12997 srcaddr,
12998 peer->name);
12999 return -1;
13000 } else if (nonlocal == 2) {
13002 "Unable to bind to sourceaddress '%s' for '%s', reverting to default\n",
13003 srcaddr,
13004 peer->name);
13005 return -1;
13006 } else {
13007 ast_debug(1, "Using sourceaddress %s for '%s'\n", srcaddr, peer->name);
13008 return 0;
13009 }
13010}
13011
13012static void peer_destructor(void *obj)
13013{
13014 struct iax2_peer *peer = obj;
13015 int callno = peer->callno;
13016
13017 ast_free_acl_list(peer->acl);
13018
13019 if (callno > 0) {
13023 }
13024
13025 register_peer_exten(peer, 0);
13026
13027 if (peer->dnsmgr)
13029
13030 if (peer->mwi_event_sub) {
13032 }
13033
13035
13037}
13038
13039/*! \brief Create peer structure based on configuration */
13040static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly)
13041{
13042 struct iax2_peer *peer = NULL;
13043 struct ast_acl_list *oldacl = NULL;
13044 int maskfound = 0;
13045 int found = 0;
13046 int firstpass = 1;
13047 int subscribe_acl_change = 0;
13048
13049 if (!temponly) {
13050 peer = ao2_find(peers, name, OBJ_KEY);
13051 if (peer && !ast_test_flag64(peer, IAX_DELME))
13052 firstpass = 0;
13053 }
13054
13055 if (peer) {
13056 found++;
13057 if (firstpass) {
13058 oldacl = peer->acl;
13059 peer->acl = NULL;
13060 }
13061 unlink_peer(peer);
13062 } else if ((peer = ao2_alloc(sizeof(*peer), peer_destructor))) {
13063 peer->expire = -1;
13064 peer->pokeexpire = -1;
13065 peer->sockfd = defaultsockfd;
13066 if (ast_string_field_init(peer, 32))
13067 peer = peer_unref(peer);
13068 if (!(peer->endpoint = ast_endpoint_create("IAX2", name))) {
13069 peer = peer_unref(peer);
13070 }
13071 }
13072
13073 if (peer) {
13074 if (firstpass) {
13078 peer->adsi = adsi;
13079 ast_string_field_set(peer, secret, "");
13080 if (!found) {
13082 ast_sockaddr_parse(&peer->addr, "0.0.0.0", 0);
13084 peer->expiry = min_reg_expire;
13085 }
13086 peer->prefs = prefs_global;
13088 peer->smoothing = 0;
13091 peer->maxcallno = 0;
13092 peercnt_modify((unsigned char) 0, 0, &peer->addr);
13094 ast_string_field_set(peer,context,"");
13095 ast_string_field_set(peer,peercontext,"");
13097 ast_string_field_set(peer, cid_name, "");
13098 ast_string_field_set(peer, cid_num, "");
13101 }
13102
13103 if (!v) {
13104 v = alt;
13105 alt = NULL;
13106 }
13107 while(v) {
13108 if (!strcasecmp(v->name, "secret")) {
13109 ast_string_field_set(peer, secret, v->value);
13110 } else if (!strcasecmp(v->name, "mailbox")) {
13111 ast_string_field_set(peer, mailbox, v->value);
13112 } else if (!strcasecmp(v->name, "mohinterpret")) {
13114 } else if (!strcasecmp(v->name, "mohsuggest")) {
13116 } else if (!strcasecmp(v->name, "dbsecret")) {
13117 ast_string_field_set(peer, dbsecret, v->value);
13118 } else if (!strcasecmp(v->name, "description")) {
13119 ast_string_field_set(peer, description, v->value);
13120 } else if (!strcasecmp(v->name, "trunk")) {
13122 if (ast_test_flag64(peer, IAX_TRUNK) && !timer) {
13123 ast_log(LOG_WARNING, "Unable to support trunking on peer '%s' without a timing interface\n", peer->name);
13125 }
13126 } else if (!strcasecmp(v->name, "auth")) {
13128 if (peer->authmethods & IAX_AUTH_PLAINTEXT) {
13129 ast_log(LOG_WARNING, "Auth method for peer '%s' is set to deprecated 'plaintext' at line %d of iax.conf\n", peer->name, v->lineno);
13130 }
13131 } else if (!strcasecmp(v->name, "encryption")) {
13133 if (!peer->encmethods) {
13135 }
13136 } else if (!strcasecmp(v->name, "forceencryption")) {
13137 if (ast_false(v->value)) {
13139 } else {
13141 if (peer->encmethods) {
13143 }
13144 }
13145 } else if (!strcasecmp(v->name, "transfer")) {
13146 if (!strcasecmp(v->value, "mediaonly")) {
13148 } else if (ast_true(v->value)) {
13150 } else
13152 } else if (!strcasecmp(v->name, "jitterbuffer")) {
13154 } else if (!strcasecmp(v->name, "host")) {
13155 if (!strcasecmp(v->value, "dynamic")) {
13156 /* They'll register with us */
13158 if (!found) {
13159 int peer_port = ast_sockaddr_port(&peer->addr);
13160 if (peer_port) {
13161 ast_sockaddr_set_port(&peer->defaddr, peer_port);
13162 }
13163 ast_sockaddr_setnull(&peer->addr);
13164 }
13165 } else {
13166 /* Non-dynamic. Make sure we become that way if we're not */
13167 AST_SCHED_DEL(sched, peer->expire);
13169 if (peer->dnsmgr) {
13170 // Make sure we refresh dnsmgr if we're using it
13172 } else {
13173 // Or just invalidate the address
13174 peer->addr.ss.ss_family = AST_AF_UNSPEC;
13175 }
13176 if (ast_dnsmgr_lookup(v->value, &peer->addr, &peer->dnsmgr, srvlookup ? "_iax._udp" : NULL)) {
13177 return peer_unref(peer);
13178 }
13179 if (!ast_sockaddr_port(&peer->addr)) {
13181 }
13182 }
13183 } else if (!strcasecmp(v->name, "defaultip")) {
13184 struct ast_sockaddr peer_defaddr_tmp;
13185 peer_defaddr_tmp.ss.ss_family = AF_UNSPEC;
13186 if (ast_get_ip(&peer_defaddr_tmp, v->value)) {
13187 return peer_unref(peer);
13188 }
13189 ast_sockaddr_set_port(&peer_defaddr_tmp, ast_sockaddr_port(&peer->defaddr));
13190 ast_sockaddr_copy(&peer->defaddr, &peer_defaddr_tmp);
13191 } else if (!strcasecmp(v->name, "sourceaddress")) {
13192 peer_set_srcaddr(peer, v->value);
13193 } else if (!strcasecmp(v->name, "permit") ||
13194 !strcasecmp(v->name, "deny") ||
13195 !strcasecmp(v->name, "acl")) {
13196 ast_append_acl(v->name, v->value, &peer->acl, NULL, &subscribe_acl_change);
13197 } else if (!strcasecmp(v->name, "mask")) {
13198 maskfound++;
13199 ast_sockaddr_parse(&peer->mask, v->value, 0);
13200 } else if (!strcasecmp(v->name, "context")) {
13201 ast_string_field_set(peer, context, v->value);
13202 } else if (!strcasecmp(v->name, "regexten")) {
13203 ast_string_field_set(peer, regexten, v->value);
13204 } else if (!strcasecmp(v->name, "peercontext")) {
13205 ast_string_field_set(peer, peercontext, v->value);
13206 } else if (!strcasecmp(v->name, "port")) {
13207 int bindport;
13208 if (ast_parse_arg(v->value, PARSE_UINT32 | PARSE_IN_RANGE, &bindport, 0, 65535)) {
13209 bindport = IAX_DEFAULT_PORTNO;
13210 }
13211 if (ast_test_flag64(peer, IAX_DYNAMIC)) {
13212 ast_sockaddr_set_port(&peer->defaddr, bindport);
13213 } else {
13214 ast_sockaddr_set_port(&peer->addr, bindport);
13215 }
13216 } else if (!strcasecmp(v->name, "username")) {
13217 ast_string_field_set(peer, username, v->value);
13218 } else if (!strcasecmp(v->name, "allow")) {
13219 iax2_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 1);
13220 } else if (!strcasecmp(v->name, "disallow")) {
13221 iax2_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 0);
13222 } else if (!strcasecmp(v->name, "callerid")) {
13223 if (!ast_strlen_zero(v->value)) {
13224 char name2[80];
13225 char num2[80];
13226 ast_callerid_split(v->value, name2, sizeof(name2), num2, sizeof(num2));
13227 ast_string_field_set(peer, cid_name, name2);
13228 ast_string_field_set(peer, cid_num, num2);
13229 } else {
13230 ast_string_field_set(peer, cid_name, "");
13231 ast_string_field_set(peer, cid_num, "");
13232 }
13234 } else if (!strcasecmp(v->name, "fullname")) {
13235 ast_string_field_set(peer, cid_name, S_OR(v->value, ""));
13237 } else if (!strcasecmp(v->name, "cid_number")) {
13238 ast_string_field_set(peer, cid_num, S_OR(v->value, ""));
13240 } else if (!strcasecmp(v->name, "sendani")) {
13242 } else if (!strcasecmp(v->name, "inkeys")) {
13243 ast_string_field_set(peer, inkeys, v->value);
13244 } else if (!strcasecmp(v->name, "outkey")) {
13245 ast_string_field_set(peer, outkey, v->value);
13246 } else if (!strcasecmp(v->name, "qualify")) {
13247 if (!strcasecmp(v->value, "no")) {
13248 peer->maxms = 0;
13249 } else if (!strcasecmp(v->value, "yes")) {
13250 peer->maxms = DEFAULT_MAXMS;
13251 } else if (sscanf(v->value, "%30d", &peer->maxms) != 1) {
13252 ast_log(LOG_WARNING, "Qualification of peer '%s' should be 'yes', 'no', or a number of milliseconds at line %d of iax.conf\n", peer->name, v->lineno);
13253 peer->maxms = 0;
13254 }
13255 } else if (!strcasecmp(v->name, "qualifysmoothing")) {
13256 peer->smoothing = ast_true(v->value);
13257 } else if (!strcasecmp(v->name, "qualifyfreqok")) {
13258 if (sscanf(v->value, "%30d", &peer->pokefreqok) != 1) {
13259 ast_log(LOG_WARNING, "Qualification testing frequency of peer '%s' when OK should a number of milliseconds at line %d of iax.conf\n", peer->name, v->lineno);
13260 }
13261 } else if (!strcasecmp(v->name, "qualifyfreqnotok")) {
13262 if (sscanf(v->value, "%30d", &peer->pokefreqnotok) != 1) {
13263 ast_log(LOG_WARNING, "Qualification testing frequency of peer '%s' when NOT OK should be a number of milliseconds at line %d of iax.conf\n", peer->name, v->lineno);
13264 }
13265 } else if (!strcasecmp(v->name, "timezone")) {
13267 } else if (!strcasecmp(v->name, "adsi")) {
13268 peer->adsi = ast_true(v->value);
13269 } else if (!strcasecmp(v->name, "connectedline")) {
13270 if (ast_true(v->value)) {
13272 } else if (!strcasecmp(v->value, "send")) {
13275 } else if (!strcasecmp(v->value, "receive")) {
13278 } else {
13280 }
13281 } else if (!strcasecmp(v->name, "maxcallnumbers")) {
13282 if (sscanf(v->value, "%10hu", &peer->maxcallno) != 1) {
13283 ast_log(LOG_WARNING, "maxcallnumbers must be set to a valid number. %s is not valid at line %d.\n", v->value, v->lineno);
13284 } else {
13285 peercnt_modify((unsigned char) 1, peer->maxcallno, &peer->addr);
13286 }
13287 } else if (!strcasecmp(v->name, "requirecalltoken")) {
13288 /* default is required unless in optional ip list */
13289 if (ast_false(v->value)) {
13291 } else if (!strcasecmp(v->value, "auto")) {
13293 } else if (ast_true(v->value)) {
13295 } else {
13296 ast_log(LOG_WARNING, "requirecalltoken must be set to a valid value. at line %d\n", v->lineno);
13297 }
13298 } /* else if (strcasecmp(v->name,"type")) */
13299 /* ast_log(LOG_WARNING, "Ignoring %s\n", v->name); */
13300 v = v->next;
13301 if (!v) {
13302 v = alt;
13303 alt = NULL;
13304 }
13305 }
13306 if (!peer->authmethods)
13307 peer->authmethods = IAX_AUTH_MD5;
13309 }
13310
13311 if (!maskfound && !ast_sockaddr_isnull(&peer->addr)) {
13312 if (ast_sockaddr_is_ipv4_mapped(&peer->addr)) {
13313 ast_sockaddr_parse(&peer->mask, "::ffff:ffff:ffff", 0);
13314 } else if (ast_sockaddr_is_ipv6(&peer->addr)) {
13315 ast_sockaddr_parse(&peer->mask, "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", 0);
13316 } else {
13317 ast_sockaddr_parse(&peer->mask, "255.255.255.255", 0);
13318 }
13319 }
13320
13321 if (oldacl) {
13322 ast_free_acl_list(oldacl);
13323 }
13324
13325 if (!ast_strlen_zero(peer->mailbox) && !peer->mwi_event_sub) {
13326 /* The MWI subscriptions exist just so the core knows we care about those
13327 * mailboxes. However, we just grab the events out of the cache when it
13328 * is time to send MWI, since it is only sent with a REGACK. */
13330 }
13331
13332 if (subscribe_acl_change) {
13334 }
13335
13336 return peer;
13337}
13338
13339static void user_destructor(void *obj)
13340{
13341 struct iax2_user *user = obj;
13342
13343 ast_free_acl_list(user->acl);
13344 free_context(user->contexts);
13345 if(user->vars) {
13347 user->vars = NULL;
13348 }
13350}
13351
13352/*! \brief Create in-memory user structure from configuration */
13353static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly)
13354{
13355 struct iax2_user *user = NULL;
13356 struct iax2_context *con, *conl = NULL;
13357 struct ast_acl_list *oldacl = NULL;
13358 struct iax2_context *oldcon = NULL;
13359 int format;
13360 int firstpass=1;
13361 int oldcurauthreq = 0;
13362 int subscribe_acl_change = 0;
13363 char *varname = NULL, *varval = NULL;
13364 struct ast_variable *tmpvar = NULL;
13365
13366 if (!temponly) {
13369 firstpass = 0;
13370 }
13371
13372 if (user) {
13373 if (firstpass) {
13374 oldcurauthreq = user->curauthreq;
13375 oldacl = user->acl;
13376 oldcon = user->contexts;
13377 user->acl = NULL;
13378 user->contexts = NULL;
13379 }
13380 /* Already in the list, remove it and it will be added back (or FREE'd) */
13382 } else {
13383 user = ao2_alloc(sizeof(*user), user_destructor);
13384 }
13385
13386 if (user) {
13387 if (firstpass) {
13389 memset(user, 0, sizeof(struct iax2_user));
13390 if (ast_string_field_init(user, 32)) {
13391 user = user_unref(user);
13392 goto cleanup;
13393 }
13394 user->maxauthreq = maxauthreq;
13395 user->curauthreq = oldcurauthreq;
13396 user->prefs = prefs_global;
13397 user->capability = iax2_capability;
13398 user->encmethods = iax2_encryption;
13399 user->authmethods = iax2_authmethods;
13400 user->adsi = adsi;
13401 user->calltoken_required = CALLTOKEN_DEFAULT;
13406 ast_string_field_set(user, cid_name, "");
13407 ast_string_field_set(user, cid_num, "");
13411 }
13412 if (!v) {
13413 v = alt;
13414 alt = NULL;
13415 }
13416 while(v) {
13417 if (!strcasecmp(v->name, "context")) {
13418 con = build_context(v->value);
13419 if (con) {
13420 if (conl)
13421 conl->next = con;
13422 else
13423 user->contexts = con;
13424 conl = con;
13425 }
13426 } else if (!strcasecmp(v->name, "permit") ||
13427 !strcasecmp(v->name, "deny") ||
13428 !strcasecmp(v->name, "acl")) {
13429 ast_append_acl(v->name, v->value, &user->acl, NULL, &subscribe_acl_change);
13430 } else if (!strcasecmp(v->name, "setvar")) {
13431 varname = ast_strdupa(v->value);
13432 if ((varval = strchr(varname, '='))) {
13433 *varval = '\0';
13434 varval++;
13435 if ((tmpvar = ast_variable_new(varname, varval, ""))) {
13436 if (ast_variable_list_replace(&user->vars, tmpvar)) {
13437 tmpvar->next = user->vars;
13438 user->vars = tmpvar;
13439 }
13440 }
13441 }
13442 } else if (!strcasecmp(v->name, "allow")) {
13443 iax2_parse_allow_disallow(&user->prefs, &user->capability, v->value, 1);
13444 } else if (!strcasecmp(v->name, "disallow")) {
13445 iax2_parse_allow_disallow(&user->prefs, &user->capability,v->value, 0);
13446 } else if (!strcasecmp(v->name, "trunk")) {
13448 if (ast_test_flag64(user, IAX_TRUNK) && !timer) {
13449 ast_log(LOG_WARNING, "Unable to support trunking on user '%s' without a timing interface\n", user->name);
13451 }
13452 } else if (!strcasecmp(v->name, "auth")) {
13453 user->authmethods = get_auth_methods(v->value);
13454 if (user->authmethods & IAX_AUTH_PLAINTEXT) {
13455 ast_log(LOG_WARNING, "Auth method for user '%s' is set to deprecated 'plaintext' at line %d of iax.conf\n", user->name, v->lineno);
13456 }
13457 } else if (!strcasecmp(v->name, "encryption")) {
13458 user->encmethods |= get_encrypt_methods(v->value);
13459 if (!user->encmethods) {
13461 }
13462 } else if (!strcasecmp(v->name, "forceencryption")) {
13463 if (ast_false(v->value)) {
13465 } else {
13466 user->encmethods |= get_encrypt_methods(v->value);
13467 if (user->encmethods) {
13469 }
13470 }
13471 } else if (!strcasecmp(v->name, "transfer")) {
13472 if (!strcasecmp(v->value, "mediaonly")) {
13474 } else if (ast_true(v->value)) {
13476 } else
13478 } else if (!strcasecmp(v->name, "codecpriority")) {
13479 if(!strcasecmp(v->value, "caller"))
13481 else if(!strcasecmp(v->value, "disabled"))
13483 else if(!strcasecmp(v->value, "reqonly")) {
13486 }
13487 } else if (!strcasecmp(v->name, "immediate")) {
13489 } else if (!strcasecmp(v->name, "jitterbuffer")) {
13491 } else if (!strcasecmp(v->name, "dbsecret")) {
13492 ast_string_field_set(user, dbsecret, v->value);
13493 } else if (!strcasecmp(v->name, "secret")) {
13494 if (!ast_strlen_zero(user->secret)) {
13495 char *old = ast_strdupa(user->secret);
13496
13497 ast_string_field_build(user, secret, "%s;%s", old, v->value);
13498 } else
13499 ast_string_field_set(user, secret, v->value);
13500 } else if (!strcasecmp(v->name, "callerid")) {
13501 if (!ast_strlen_zero(v->value) && strcasecmp(v->value, "asreceived")) {
13502 char name2[80];
13503 char num2[80];
13504 ast_callerid_split(v->value, name2, sizeof(name2), num2, sizeof(num2));
13505 ast_string_field_set(user, cid_name, name2);
13506 ast_string_field_set(user, cid_num, num2);
13508 } else {
13510 ast_string_field_set(user, cid_name, "");
13511 ast_string_field_set(user, cid_num, "");
13512 }
13513 } else if (!strcasecmp(v->name, "fullname")) {
13514 if (!ast_strlen_zero(v->value)) {
13515 ast_string_field_set(user, cid_name, v->value);
13517 } else {
13518 ast_string_field_set(user, cid_name, "");
13519 if (ast_strlen_zero(user->cid_num))
13521 }
13522 } else if (!strcasecmp(v->name, "cid_number")) {
13523 if (!ast_strlen_zero(v->value)) {
13524 ast_string_field_set(user, cid_num, v->value);
13526 } else {
13527 ast_string_field_set(user, cid_num, "");
13528 if (ast_strlen_zero(user->cid_name))
13530 }
13531 } else if (!strcasecmp(v->name, "accountcode")) {
13533 } else if (!strcasecmp(v->name, "mohinterpret")) {
13535 } else if (!strcasecmp(v->name, "mohsuggest")) {
13537 } else if (!strcasecmp(v->name, "parkinglot")) {
13538 ast_string_field_set(user, parkinglot, v->value);
13539 } else if (!strcasecmp(v->name, "language")) {
13541 } else if (!strcasecmp(v->name, "amaflags")) {
13542 format = ast_channel_string2amaflag(v->value);
13543 if (format < 0) {
13544 ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
13545 } else {
13546 user->amaflags = format;
13547 }
13548 } else if (!strcasecmp(v->name, "inkeys")) {
13549 ast_string_field_set(user, inkeys, v->value);
13550 } else if (!strcasecmp(v->name, "maxauthreq")) {
13551 user->maxauthreq = atoi(v->value);
13552 if (user->maxauthreq < 0)
13553 user->maxauthreq = 0;
13554 } else if (!strcasecmp(v->name, "adsi")) {
13555 user->adsi = ast_true(v->value);
13556 } else if (!strcasecmp(v->name, "connectedline")) {
13557 if (ast_true(v->value)) {
13559 } else if (!strcasecmp(v->value, "send")) {
13562 } else if (!strcasecmp(v->value, "receive")) {
13565 } else {
13567 }
13568 } else if (!strcasecmp(v->name, "requirecalltoken")) {
13569 /* default is required unless in optional ip list */
13570 if (ast_false(v->value)) {
13571 user->calltoken_required = CALLTOKEN_NO;
13572 } else if (!strcasecmp(v->value, "auto")) {
13573 user->calltoken_required = CALLTOKEN_AUTO;
13574 } else if (ast_true(v->value)) {
13575 user->calltoken_required = CALLTOKEN_YES;
13576 } else {
13577 ast_log(LOG_WARNING, "requirecalltoken must be set to a valid value. at line %d\n", v->lineno);
13578 }
13579 } /* else if (strcasecmp(v->name,"type")) */
13580 /* ast_log(LOG_WARNING, "Ignoring %s\n", v->name); */
13581 v = v->next;
13582 if (!v) {
13583 v = alt;
13584 alt = NULL;
13585 }
13586 }
13587 if (!user->authmethods) {
13588 if (!ast_strlen_zero(user->secret)) {
13589 user->authmethods = IAX_AUTH_MD5;
13590 if (!ast_strlen_zero(user->inkeys))
13591 user->authmethods |= IAX_AUTH_RSA;
13592 } else if (!ast_strlen_zero(user->inkeys)) {
13593 user->authmethods = IAX_AUTH_RSA;
13594 } else {
13595 user->authmethods = IAX_AUTH_MD5;
13596 }
13597 }
13599 }
13600cleanup:
13601 if (oldacl) {
13602 ast_free_acl_list(oldacl);
13603 }
13604 if (oldcon) {
13605 free_context(oldcon);
13606 }
13607
13608 if (subscribe_acl_change) {
13610 }
13611
13612 return user;
13613}
13614
13615static int peer_delme_cb(void *obj, void *arg, int flags)
13616{
13617 struct iax2_peer *peer = obj;
13618
13620
13621 return 0;
13622}
13623
13624static int user_delme_cb(void *obj, void *arg, int flags)
13625{
13626 struct iax2_user *user = obj;
13627
13629
13630 return 0;
13631}
13632
13633static void delete_users(void)
13634{
13635 struct iax2_registry *reg;
13636
13638
13640 while ((reg = AST_LIST_REMOVE_HEAD(&registrations, entry))) {
13641 if (sched) {
13642 AST_SCHED_DEL(sched, reg->expire);
13643 }
13644 if (reg->callno) {
13645 int callno = reg->callno;
13647 if (iaxs[callno]) {
13648 iaxs[callno]->reg = NULL;
13650 }
13652 }
13653 if (reg->dnsmgr)
13655 ast_free(reg);
13656 }
13658
13660}
13661
13662static void prune_users(void)
13663{
13664 struct iax2_user *user;
13665 struct ao2_iterator i;
13666
13667 i = ao2_iterator_init(users, 0);
13668 while ((user = ao2_iterator_next(&i))) {
13671 }
13673 }
13675}
13676
13677/* Prune peers who still are supposed to be deleted */
13678static void prune_peers(void)
13679{
13680 struct iax2_peer *peer;
13681 struct ao2_iterator i;
13682
13683 i = ao2_iterator_init(peers, 0);
13684 while ((peer = ao2_iterator_next(&i))) {
13686 unlink_peer(peer);
13687 }
13688 peer_unref(peer);
13689 }
13691}
13692
13693static void set_config_destroy(void)
13694{
13695 strcpy(accountcode, "");
13696 strcpy(language, "");
13697 strcpy(mohinterpret, "");
13698 strcpy(mohsuggest, "");
13700 amaflags = 0;
13701 delayreject = 0;
13704 delete_users();
13707}
13708
13709/*! \brief Load configuration */
13710static int set_config(const char *config_file, int reload, int forced)
13711{
13712 struct ast_config *cfg;
13713 iax2_format capability;
13714 struct ast_variable *v;
13715 char *cat;
13716 const char *utype;
13717 const char *tosval;
13718 int format;
13719 int portno = IAX_DEFAULT_PORTNO;
13720 int x;
13721 int mtuv;
13722 int subscribe_network_change = 1;
13723 struct iax2_user *user;
13724 struct iax2_peer *peer;
13725 struct ast_netsock *ns;
13726 struct ast_flags config_flags = { (reload && !forced) ? CONFIG_FLAG_FILEUNCHANGED : 0 };
13727 struct ast_sockaddr bindaddr;
13728 struct iax2_codec_pref prefs_new;
13729
13730 cfg = ast_config_load(config_file, config_flags);
13731
13732 if (!cfg) {
13733 ast_log(LOG_ERROR, "Unable to load config %s\n", config_file);
13734 return -1;
13735 } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
13737 if ((cfg = ast_config_load(config_file, config_flags)) == CONFIG_STATUS_FILEINVALID) {
13738 ast_log(LOG_ERROR, "Config file %s is in an invalid format. Aborting.\n", config_file);
13739 return 0;
13740 }
13741 if (!cfg) {
13742 /* should have been able to load the config here */
13743 ast_log(LOG_ERROR, "Unable to load config %s again\n", config_file);
13744 return -1;
13745 }
13746 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
13747 ast_log(LOG_ERROR, "Config file %s is in an invalid format. Aborting.\n", config_file);
13748 return 0;
13749 } else { /* iax.conf changed */
13751 }
13752
13753 if (reload) {
13755 }
13756
13757 ast_sockaddr_parse(&bindaddr, "0.0.0.0:0", 0);
13758
13759 /* Setup new codec prefs */
13761
13762 /* Reset Global Flags */
13763 memset(&globalflags, 0, sizeof(globalflags));
13766
13767#ifdef SO_NO_CHECK
13768 nochecksums = 0;
13769#endif
13770 /* Reset default parking lot */
13771 default_parkinglot[0] = '\0';
13772
13778
13779 maxauthreq = 3;
13780
13781 srvlookup = 0;
13782 iax2_authmethods = 0;
13783
13784 v = ast_variable_browse(cfg, "general");
13785
13786 /* Seed initial tos value */
13787 tosval = ast_variable_retrieve(cfg, "general", "tos");
13788 if (tosval) {
13789 if (ast_str2tos(tosval, &qos.tos))
13790 ast_log(LOG_WARNING, "Invalid tos value, refer to QoS documentation\n");
13791 }
13792 /* Seed initial cos value */
13793 tosval = ast_variable_retrieve(cfg, "general", "cos");
13794 if (tosval) {
13795 if (ast_str2cos(tosval, &qos.cos))
13796 ast_log(LOG_WARNING, "Invalid cos value, refer to QoS documentation\n");
13797 }
13798 while(v) {
13799 if (!strcasecmp(v->name, "bindport")) {
13800 if (reload) {
13801 ast_log(LOG_NOTICE, "Ignoring bindport on reload\n");
13802 }
13803 else if (ast_parse_arg(v->value, PARSE_UINT32 | PARSE_IN_RANGE, &portno, 1024, 65535)) {
13804 portno = IAX_DEFAULT_PORTNO;
13805 }
13806 } else if (!strcasecmp(v->name, "pingtime")){
13807 ping_time = atoi(v->value);
13808 }
13809 else if (!strcasecmp(v->name, "iaxthreadcount")) {
13810 if (reload) {
13811 if (atoi(v->value) != iaxthreadcount)
13812 ast_log(LOG_NOTICE, "Ignoring any changes to iaxthreadcount during reload\n");
13813 } else {
13814 iaxthreadcount = atoi(v->value);
13815 if (iaxthreadcount < 1) {
13816 ast_log(LOG_NOTICE, "iaxthreadcount must be at least 1.\n");
13817 iaxthreadcount = 1;
13818 } else if (iaxthreadcount > 256) {
13819 ast_log(LOG_NOTICE, "limiting iaxthreadcount to 256\n");
13820 iaxthreadcount = 256;
13821 }
13822 }
13823 } else if (!strcasecmp(v->name, "iaxmaxthreadcount")) {
13824 if (reload) {
13826 iaxmaxthreadcount = atoi(v->value);
13828 } else {
13829 iaxmaxthreadcount = atoi(v->value);
13830 if (iaxmaxthreadcount < 0) {
13831 ast_log(LOG_NOTICE, "iaxmaxthreadcount must be at least 0.\n");
13833 } else if (iaxmaxthreadcount > 256) {
13834 ast_log(LOG_NOTICE, "Limiting iaxmaxthreadcount to 256\n");
13835 iaxmaxthreadcount = 256;
13836 }
13837 }
13838 } else if (!strcasecmp(v->name, "nochecksums")) {
13839#ifdef SO_NO_CHECK
13840 if (ast_true(v->value))
13841 nochecksums = 1;
13842 else
13843 nochecksums = 0;
13844#else
13845 if (ast_true(v->value))
13846 ast_log(LOG_WARNING, "Disabling RTP checksums is not supported on this operating system!\n");
13847#endif
13848 }
13849 else if (!strcasecmp(v->name, "maxjitterbuffer"))
13850 maxjitterbuffer = atoi(v->value);
13851 else if (!strcasecmp(v->name, "resyncthreshold"))
13852 resyncthreshold = atoi(v->value);
13853 else if (!strcasecmp(v->name, "maxjitterinterps"))
13854 maxjitterinterps = atoi(v->value);
13855 else if (!strcasecmp(v->name, "jittertargetextra"))
13856 jittertargetextra = atoi(v->value);
13857 else if (!strcasecmp(v->name, "lagrqtime"))
13858 lagrq_time = atoi(v->value);
13859 else if (!strcasecmp(v->name, "maxregexpire"))
13860 max_reg_expire = atoi(v->value);
13861 else if (!strcasecmp(v->name, "minregexpire"))
13862 min_reg_expire = atoi(v->value);
13863 else if (!strcasecmp(v->name, "bindaddr")) {
13864 if (reload) {
13865 ast_log(LOG_NOTICE, "Ignoring bindaddr on reload\n");
13866 } else {
13867
13868 if (!ast_parse_arg(v->value, PARSE_ADDR, NULL)) {
13869
13871
13872 if (!ast_sockaddr_port(&bindaddr)) {
13874 }
13875
13876 if (!(ns = ast_netsock_bindaddr(netsock, io, &bindaddr, qos.tos, qos.cos, socket_read, NULL))) {
13877 ast_log(LOG_WARNING, "Unable to apply binding to '%s' at line %d\n", v->value, v->lineno);
13878 } else {
13879 ast_verb(2, "Binding IAX2 to address %s\n", ast_sockaddr_stringify(&bindaddr));
13880
13881 if (defaultsockfd < 0) {
13883 }
13885 }
13886
13887 } else {
13888 ast_log(LOG_WARNING, "Invalid address '%s' specified, at line %d\n", v->value, v->lineno);
13889 }
13890 }
13891 } else if (!strcasecmp(v->name, "auth")) {
13894 ast_log(LOG_WARNING, "Default auth method is set to deprecated 'plaintext' at line %d of iax.conf\n", v->lineno);
13895 }
13896 } else if (!strcasecmp(v->name, "authdebug")) {
13897 authdebug = ast_true(v->value);
13898 } else if (!strcasecmp(v->name, "encryption")) {
13900 if (!iax2_encryption) {
13902 }
13903 } else if (!strcasecmp(v->name, "forceencryption")) {
13904 if (ast_false(v->value)) {
13906 } else {
13908 if (iax2_encryption) {
13910 }
13911 }
13912 } else if (!strcasecmp(v->name, "transfer")) {
13913 if (!strcasecmp(v->value, "mediaonly")) {
13915 } else if (ast_true(v->value)) {
13917 } else
13919 } else if (!strcasecmp(v->name, "codecpriority")) {
13920 if(!strcasecmp(v->value, "caller"))
13922 else if(!strcasecmp(v->value, "disabled"))
13924 else if(!strcasecmp(v->value, "reqonly")) {
13927 }
13928 } else if (!strcasecmp(v->name, "jitterbuffer"))
13930 else if (!strcasecmp(v->name, "delayreject"))
13932 else if (!strcasecmp(v->name, "allowfwdownload"))
13934 else if (!strcasecmp(v->name, "rtcachefriends"))
13936 else if (!strcasecmp(v->name, "rtignoreregexpire"))
13938 else if (!strcasecmp(v->name, "rtupdate"))
13940 else if (!strcasecmp(v->name, "rtsavesysname"))
13942 else if (!strcasecmp(v->name, "trunktimestamps"))
13944 else if (!strcasecmp(v->name, "rtautoclear")) {
13945 int i = atoi(v->value);
13946 if(i > 0)
13948 else
13949 i = 0;
13951 } else if (!strcasecmp(v->name, "trunkfreq")) {
13952 trunkfreq = atoi(v->value);
13953 if (trunkfreq < 10) {
13954 ast_log(LOG_NOTICE, "trunkfreq must be between 10ms and 1000ms, using 10ms instead.\n");
13955 trunkfreq = 10;
13956 } else if (trunkfreq > 1000) {
13957 ast_log(LOG_NOTICE, "trunkfreq must be between 10ms and 1000ms, using 1000ms instead.\n");
13958 trunkfreq = 1000;
13959 }
13960 if (timer) {
13962 }
13963 } else if (!strcasecmp(v->name, "trunkmtu")) {
13964 mtuv = atoi(v->value);
13965 if (mtuv == 0 )
13967 else if (mtuv >= 172 && mtuv < 4000)
13968 global_max_trunk_mtu = mtuv;
13969 else
13970 ast_log(LOG_NOTICE, "trunkmtu value out of bounds (%d) at line %d\n",
13971 mtuv, v->lineno);
13972 } else if (!strcasecmp(v->name, "trunkmaxsize")) {
13973 trunkmaxsize = atoi(v->value);
13974 if (trunkmaxsize == 0)
13976 } else if (!strcasecmp(v->name, "autokill")) {
13977 if (sscanf(v->value, "%30d", &x) == 1) {
13978 if (x >= 0)
13979 autokill = x;
13980 else
13981 ast_log(LOG_NOTICE, "Nice try, but autokill has to be >0 or 'yes' or 'no' at line %d\n", v->lineno);
13982 } else if (ast_true(v->value)) {
13984 } else {
13985 autokill = 0;
13986 }
13987 } else if (!strcasecmp(v->name, "bandwidth")) {
13988 if (!strcasecmp(v->value, "low")) {
13989 capability = iax2_codec_pref_from_bitfield(&prefs_new,
13991 } else if (!strcasecmp(v->value, "medium")) {
13992 capability = iax2_codec_pref_from_bitfield(&prefs_new,
13994 } else if (!strcasecmp(v->value, "high")) {
13995 capability = iax2_codec_pref_from_bitfield(&prefs_new,
13997 } else {
13998 ast_log(LOG_WARNING, "bandwidth must be either low, medium, or high\n");
13999 }
14000 } else if (!strcasecmp(v->name, "allow")) {
14001 iax2_parse_allow_disallow(&prefs_new, &capability, v->value, 1);
14002 } else if (!strcasecmp(v->name, "disallow")) {
14003 iax2_parse_allow_disallow(&prefs_new, &capability, v->value, 0);
14004 } else if (!strcasecmp(v->name, "register")) {
14005 iax2_register(v->value, v->lineno);
14006 } else if (!strcasecmp(v->name, "iaxcompat")) {
14007 iaxcompat = ast_true(v->value);
14008 } else if (!strcasecmp(v->name, "regcontext")) {
14010 /* Create context if it doesn't exist already */
14012 } else if (!strcasecmp(v->name, "tos")) {
14013 if (ast_str2tos(v->value, &qos.tos))
14014 ast_log(LOG_WARNING, "Invalid tos value at line %d, refer to QoS documentation\n", v->lineno);
14015 } else if (!strcasecmp(v->name, "cos")) {
14016 if (ast_str2cos(v->value, &qos.cos))
14017 ast_log(LOG_WARNING, "Invalid cos value at line %d, refer to QoS documentation\n", v->lineno);
14018 } else if (!strcasecmp(v->name, "parkinglot")) {
14020 } else if (!strcasecmp(v->name, "accountcode")) {
14022 } else if (!strcasecmp(v->name, "mohinterpret")) {
14024 } else if (!strcasecmp(v->name, "mohsuggest")) {
14026 } else if (!strcasecmp(v->name, "amaflags")) {
14027 format = ast_channel_string2amaflag(v->value);
14028 if (format < 0) {
14029 ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
14030 } else {
14031 amaflags = format;
14032 }
14033 } else if (!strcasecmp(v->name, "language")) {
14034 ast_copy_string(language, v->value, sizeof(language));
14035 } else if (!strcasecmp(v->name, "maxauthreq")) {
14036 maxauthreq = atoi(v->value);
14037 if (maxauthreq < 0)
14038 maxauthreq = 0;
14039 } else if (!strcasecmp(v->name, "adsi")) {
14040 adsi = ast_true(v->value);
14041 } else if (!strcasecmp(v->name, "srvlookup")) {
14042 srvlookup = ast_true(v->value);
14043 } else if (!strcasecmp(v->name, "connectedline")) {
14044 if (ast_true(v->value)) {
14046 } else if (!strcasecmp(v->value, "send")) {
14049 } else if (!strcasecmp(v->value, "receive")) {
14052 } else {
14054 }
14055 } else if (!strcasecmp(v->name, "maxcallnumbers")) {
14056 if (sscanf(v->value, "%10hu", &global_maxcallno) != 1) {
14057 ast_log(LOG_WARNING, "maxcallnumbers must be set to a valid number. %s is not valid at line %d\n", v->value, v->lineno);
14058 }
14059 } else if (!strcasecmp(v->name, "maxcallnumbers_nonvalidated")) {
14060 if (sscanf(v->value, "%10hu", &global_maxcallno_nonval) != 1) {
14061 ast_log(LOG_WARNING, "maxcallnumbers_nonvalidated must be set to a valid number. %s is not valid at line %d.\n", v->value, v->lineno);
14062 }
14063 } else if (!strcasecmp(v->name, "calltokenoptional")) {
14064 if (add_calltoken_ignore(v->value)) {
14065 ast_log(LOG_WARNING, "Invalid calltokenoptional address range - '%s' line %d\n", v->value, v->lineno);
14066 return -1;
14067 }
14068 } else if (!strcasecmp(v->name, "calltokenexpiration")) {
14069 int temp = -1;
14070 sscanf(v->value, "%u", &temp);
14071 if( temp <= 0 ){
14072 ast_log(LOG_WARNING, "Invalid calltokenexpiration value %s. Should be integer greater than 0.\n", v->value);
14073 } else {
14074 max_calltoken_delay = temp;
14075 }
14076 } else if (!strcasecmp(v->name, "subscribe_network_change_event")) {
14077 if (ast_true(v->value)) {
14078 subscribe_network_change = 1;
14079 } else if (ast_false(v->value)) {
14080 subscribe_network_change = 0;
14081 } else {
14082 ast_log(LOG_WARNING, "subscribe_network_change_event value %s is not valid at line %d.\n", v->value, v->lineno);
14083 }
14084 } else if (!strcasecmp(v->name, "shrinkcallerid")) {
14085 if (ast_true(v->value)) {
14087 } else if (ast_false(v->value)) {
14089 } else {
14090 ast_log(LOG_WARNING, "shrinkcallerid value %s is not valid at line %d.\n", v->value, v->lineno);
14091 }
14092 }/*else if (strcasecmp(v->name,"type")) */
14093 /* ast_log(LOG_WARNING, "Ignoring %s\n", v->name); */
14094 v = v->next;
14095 }
14096
14097 if (subscribe_network_change) {
14099 } else {
14101 }
14102
14103 if (defaultsockfd < 0) {
14104
14106
14107 if (!(ns = ast_netsock_bindaddr(netsock, io, &bindaddr, qos.tos, qos.cos, socket_read, NULL))) {
14108 ast_log(LOG_ERROR, "Unable to create network socket: %s\n", strerror(errno));
14109 } else {
14110 ast_verb(2, "Binding IAX2 to default address %s\n", ast_sockaddr_stringify(&bindaddr));
14113 }
14114 }
14115 if (reload) {
14118 if (!outsock) {
14119 ast_log(LOG_ERROR, "Could not allocate outsock list.\n");
14120 return -1;
14121 }
14123 }
14124
14126 ast_log(LOG_WARNING, "Minimum registration interval of %d is more than maximum of %d, resetting minimum to %d\n",
14129 }
14130 prefs_global = prefs_new;
14131 iax2_capability = capability;
14132
14133 cat = ast_category_browse(cfg, NULL);
14134 while(cat) {
14135 if (strcasecmp(cat, "general")) {
14136 utype = ast_variable_retrieve(cfg, cat, "type");
14137 if (!strcasecmp(cat, "callnumberlimits")) {
14139 } else if (utype) {
14140 if (!strcasecmp(utype, "user") || !strcasecmp(utype, "friend")) {
14141 user = build_user(cat, ast_variable_browse(cfg, cat), NULL, 0);
14142 if (user) {
14144 user = user_unref(user);
14145 }
14146 }
14147 if (!strcasecmp(utype, "peer") || !strcasecmp(utype, "friend")) {
14148 peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0);
14149 if (peer) {
14150 if (ast_test_flag64(peer, IAX_DYNAMIC))
14151 reg_source_db(peer);
14152 ao2_link(peers, peer);
14153 peer = peer_unref(peer);
14154 }
14155 } else if (strcasecmp(utype, "user")) {
14156 ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, config_file);
14157 }
14158 } else
14159 ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
14160 }
14161 cat = ast_category_browse(cfg, cat);
14162 }
14163 ast_config_destroy(cfg);
14164 return 1;
14165}
14166
14167static void poke_all_peers(void)
14168{
14169 struct ao2_iterator i;
14170 struct iax2_peer *peer;
14171
14172 i = ao2_iterator_init(peers, 0);
14173 while ((peer = ao2_iterator_next(&i))) {
14174 iax2_poke_peer(peer, 0);
14175 peer_unref(peer);
14176 }
14178}
14179static int reload_config(int forced_reload)
14180{
14181 static const char config[] = "iax.conf";
14182 struct iax2_registry *reg;
14183
14184 if (set_config(config, 1, forced_reload) > 0) {
14185 prune_peers();
14186 prune_users();
14192 memset(&debugaddr, '\0', sizeof(debugaddr));
14193
14196 iax2_do_register(reg);
14198
14199 /* Qualify hosts, too */
14201 }
14202
14205 ast_unload_realtime("iaxpeers");
14206
14207 return 0;
14208}
14209
14210static char *handle_cli_iax2_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14211{
14212 switch (cmd) {
14213 case CLI_INIT:
14214 e->command = "iax2 reload";
14215 e->usage =
14216 "Usage: iax2 reload\n"
14217 " Reloads IAX configuration from iax.conf\n";
14218 return NULL;
14219 case CLI_GENERATE:
14220 return NULL;
14221 }
14222
14223 reload_config(0);
14224
14225 return CLI_SUCCESS;
14226}
14227
14228static int reload(void)
14229{
14230 return reload_config(0);
14231}
14232
14233static int cache_get_callno_locked(const char *data)
14234{
14235 struct ast_sockaddr addr;
14236 int x;
14237 int callno;
14238 struct iax_ie_data ied;
14239 struct create_addr_info cai;
14240 struct parsed_dial_string pds;
14241 char *tmpstr;
14242
14243 for (x = 0; x < ARRAY_LEN(iaxs); x++) {
14244 /* Look for an *exact match* call. Once a call is negotiated, it can only
14245 look up entries for a single context */
14246 if (!ast_mutex_trylock(&iaxsl[x])) {
14247 if (iaxs[x] && !strcasecmp(data, iaxs[x]->dproot))
14248 return x;
14250 }
14251 }
14252
14253 /* No match found, we need to create a new one */
14254
14255 memset(&cai, 0, sizeof(cai));
14256 memset(&ied, 0, sizeof(ied));
14257 memset(&pds, 0, sizeof(pds));
14258
14259 tmpstr = ast_strdupa(data);
14260 parse_dial_string(tmpstr, &pds);
14261
14262 if (ast_strlen_zero(pds.peer)) {
14263 ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", data);
14264 return -1;
14265 }
14266
14267 /* Populate our address from the given */
14268 if (create_addr(pds.peer, NULL, &addr, &cai))
14269 return -1;
14270
14271 ast_debug(1, "peer: %s, username: %s, password: %s, context: %s\n",
14272 pds.peer, pds.username, pds.password, pds.context);
14273
14274 callno = find_callno_locked(0, 0, &addr, NEW_FORCE, cai.sockfd, 0);
14275 if (callno < 1) {
14276 ast_log(LOG_WARNING, "Unable to create call\n");
14277 return -1;
14278 }
14279
14280 ast_string_field_set(iaxs[callno], dproot, data);
14282
14285 /* the string format is slightly different from a standard dial string,
14286 because the context appears in the 'exten' position
14287 */
14288 if (pds.exten)
14290 if (pds.username)
14294 /* Keep password handy */
14295 if (pds.password)
14296 ast_string_field_set(iaxs[callno], secret, pds.password);
14297 if (pds.key)
14298 ast_string_field_set(iaxs[callno], outkey, pds.key);
14299 /* Start the call going */
14300 add_empty_calltoken_ie(iaxs[callno], &ied); /* this _MUST_ be the last ie added */
14301 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
14302
14303 return callno;
14304}
14305
14306static struct iax2_dpcache *find_cache(struct ast_channel *chan, const char *data, const char *context, const char *exten, int priority)
14307{
14308 struct iax2_dpcache *dp = NULL;
14309 struct timeval now = ast_tvnow();
14310 int x, com[2], timeout, doabort, callno;
14311
14312 AST_LIST_TRAVERSE_SAFE_BEGIN(&dpcache, dp, cache_list) {
14313 if (ast_tvcmp(now, dp->expiry) > 0) {
14314 AST_LIST_REMOVE_CURRENT(cache_list);
14315 if ((dp->flags & CACHE_FLAG_PENDING) || dp->callno)
14316 ast_log(LOG_WARNING, "DP still has peer field or pending or callno (flags = %d, peer = blah, callno = %d)\n", dp->flags, dp->callno);
14317 else
14318 ast_free(dp);
14319 continue;
14320 }
14321 if (!strcmp(dp->peercontext, data) && !strcmp(dp->exten, exten))
14322 break;
14323 }
14325
14326 if (!dp) {
14327 /* No matching entry. Create a new one. */
14328 /* First, can we make a callno? */
14329 if ((callno = cache_get_callno_locked(data)) < 0) {
14330 ast_log(LOG_WARNING, "Unable to generate call for '%s'\n", data);
14331 return NULL;
14332 }
14333 if (!(dp = ast_calloc(1, sizeof(*dp)))) {
14334 ast_mutex_unlock(&iaxsl[callno]);
14335 return NULL;
14336 }
14337 ast_copy_string(dp->peercontext, data, sizeof(dp->peercontext));
14338 ast_copy_string(dp->exten, exten, sizeof(dp->exten));
14339 dp->expiry = ast_tvnow();
14340 dp->orig = dp->expiry;
14341 /* Expires in 30 mins by default */
14342 dp->expiry.tv_sec += iaxdefaultdpcache;
14344 for (x = 0; x < ARRAY_LEN(dp->waiters); x++)
14345 dp->waiters[x] = -1;
14346 /* Insert into the lists */
14347 AST_LIST_INSERT_TAIL(&dpcache, dp, cache_list);
14348 AST_LIST_INSERT_TAIL(&iaxs[callno]->dpentries, dp, peer_list);
14349 /* Send the request if we're already up */
14350 if (ast_test_flag(&iaxs[callno]->state, IAX_STATE_STARTED))
14351 iax2_dprequest(dp, callno);
14352 ast_mutex_unlock(&iaxsl[callno]);
14353 }
14354
14355 /* By here we must have a dp */
14356 if (dp->flags & CACHE_FLAG_PENDING) {
14357 int res;
14358 struct pollfd pfd;
14359 /* Okay, here it starts to get nasty. We need a pipe now to wait
14360 for a reply to come back so long as it's pending */
14361 for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
14362 /* Find an empty slot */
14363 if (dp->waiters[x] < 0)
14364 break;
14365 }
14366 if (x >= ARRAY_LEN(dp->waiters)) {
14367 ast_log(LOG_WARNING, "No more waiter positions available\n");
14368 return NULL;
14369 }
14370 if (pipe(com)) {
14371 ast_log(LOG_WARNING, "Unable to create pipe for comm\n");
14372 return NULL;
14373 }
14374 dp->waiters[x] = com[1];
14375 /* Okay, now we wait */
14376 timeout = iaxdefaulttimeout * 1000;
14377 /* Temporarily unlock */
14379 doabort = 0;
14380
14381 /* chan is in autoservice here, so do NOT service it here! */
14382 pfd.fd = com[0];
14383 pfd.events = POLLIN;
14384 pfd.revents = 0;
14385 /* Wait for pipe activity... if the channel hangs up, we'll catch it on the way out. */
14386 res = ast_poll(&pfd, 1, timeout);
14387 if (res < 0) {
14388 ast_log(LOG_WARNING, "poll returned < 0: %s\n", strerror(errno));
14389 return NULL;
14390 } else if (!pfd.revents) {
14391 ast_log(LOG_WARNING, "Timeout waiting for %s exten %s\n", data, exten);
14392 }
14393
14394 if (chan && ast_check_hangup(chan)) {
14395 doabort = 1;
14396 }
14397
14399 dp->waiters[x] = -1;
14400 close(com[1]);
14401 close(com[0]);
14402 if (doabort) {
14403 /* Don't interpret anything, just abort. */
14404 return NULL;
14405 }
14406 if (!(dp->flags & CACHE_FLAG_TIMEOUT)) {
14407 /* Now to do non-independent analysis the results of our wait */
14408 if (dp->flags & CACHE_FLAG_PENDING) {
14409 /* Still pending... It's a timeout. Wake everybody up. Consider it no longer
14410 pending. Don't let it take as long to timeout. */
14411 dp->flags &= ~CACHE_FLAG_PENDING;
14413 /* Expire after only 60 seconds now. This is designed to help reduce backlog in heavily loaded
14414 systems without leaving it unavailable once the server comes back online */
14415 dp->expiry.tv_sec = dp->orig.tv_sec + 60;
14416 for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
14417 if (dp->waiters[x] > -1) {
14418 if (write(dp->waiters[x], "asdf", 4) < 0) {
14419 ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
14420 }
14421 }
14422 }
14423 }
14424 }
14425 /* Our caller will obtain the rest */
14426 }
14427 return dp;
14428}
14429
14430/*! \brief Part of the IAX2 switch interface */
14431static int iax2_exists(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
14432{
14433 int res = 0;
14434 struct iax2_dpcache *dp = NULL;
14435#if 0
14436 ast_log(LOG_NOTICE, "iax2_exists: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
14437#endif
14438 if ((priority != 1) && (priority != 2))
14439 return 0;
14440
14442 if ((dp = find_cache(chan, data, context, exten, priority))) {
14443 if (dp->flags & CACHE_FLAG_EXISTS)
14444 res = 1;
14445 } else {
14446 ast_log(LOG_WARNING, "Unable to make DP cache\n");
14447 }
14449
14450 return res;
14451}
14452
14453/*! \brief part of the IAX2 dial plan switch interface */
14454static int iax2_canmatch(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
14455{
14456 int res = 0;
14457 struct iax2_dpcache *dp = NULL;
14458#if 0
14459 ast_log(LOG_NOTICE, "iax2_canmatch: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
14460#endif
14461 if ((priority != 1) && (priority != 2))
14462 return 0;
14463
14465 if ((dp = find_cache(chan, data, context, exten, priority))) {
14466 if (dp->flags & CACHE_FLAG_CANEXIST)
14467 res = 1;
14468 } else {
14469 ast_log(LOG_WARNING, "Unable to make DP cache\n");
14470 }
14472
14473 return res;
14474}
14475
14476/*! \brief Part of the IAX2 Switch interface */
14477static int iax2_matchmore(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
14478{
14479 int res = 0;
14480 struct iax2_dpcache *dp = NULL;
14481#if 0
14482 ast_log(LOG_NOTICE, "iax2_matchmore: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
14483#endif
14484 if ((priority != 1) && (priority != 2))
14485 return 0;
14486
14488 if ((dp = find_cache(chan, data, context, exten, priority))) {
14489 if (dp->flags & CACHE_FLAG_MATCHMORE)
14490 res = 1;
14491 } else {
14492 ast_log(LOG_WARNING, "Unable to make DP cache\n");
14493 }
14495
14496 return res;
14497}
14498
14499/*! \brief Execute IAX2 dialplan switch */
14500static int iax2_exec(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
14501{
14502 char odata[256];
14503 char req[sizeof(odata) + AST_MAX_CONTEXT + AST_MAX_EXTENSION + sizeof("IAX2//@")];
14504 char *ncontext;
14505 struct iax2_dpcache *dp = NULL;
14506 struct ast_app *dial = NULL;
14507#if 0
14508 ast_log(LOG_NOTICE, "iax2_exec: con: %s, exten: %s, pri: %d, cid: %s, data: %s, newstack: %d\n", context, exten, priority, callerid ? callerid : "<unknown>", data, newstack);
14509#endif
14510 if (priority == 2) {
14511 /* Indicate status, can be overridden in dialplan */
14512 const char *dialstatus = pbx_builtin_getvar_helper(chan, "DIALSTATUS");
14513 if (dialstatus) {
14514 dial = pbx_findapp(dialstatus);
14515 if (dial)
14516 pbx_exec(chan, dial, "");
14517 }
14518 return -1;
14519 } else if (priority != 1)
14520 return -1;
14521
14523 if ((dp = find_cache(chan, data, context, exten, priority))) {
14524 if (dp->flags & CACHE_FLAG_EXISTS) {
14525 ast_copy_string(odata, data, sizeof(odata));
14526 ncontext = strchr(odata, '/');
14527 if (ncontext) {
14528 *ncontext = '\0';
14529 ncontext++;
14530 snprintf(req, sizeof(req), "IAX2/%s/%s@%s", odata, exten, ncontext);
14531 } else {
14532 snprintf(req, sizeof(req), "IAX2/%s/%s", odata, exten);
14533 }
14534 ast_verb(3, "Executing Dial('%s')\n", req);
14535 } else {
14537 ast_log(LOG_WARNING, "Can't execute nonexistent extension '%s[@%s]' in data '%s'\n", exten, context, data);
14538 return -1;
14539 }
14540 }
14542
14543 if ((dial = pbx_findapp("Dial")))
14544 return pbx_exec(chan, dial, req);
14545 else
14546 ast_log(LOG_WARNING, "No dial application registered\n");
14547
14548 return -1;
14549}
14550
14551static int function_iaxpeer(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
14552{
14553 struct iax2_peer *peer;
14554 char *peername, *colname;
14555
14556 peername = ast_strdupa(data);
14557
14558 /* if our channel, return the IP address of the endpoint of current channel */
14559 if (!strcmp(peername,"CURRENTCHANNEL")) {
14560 unsigned short callno;
14561 if (!chan || ast_channel_tech(chan) != &iax2_tech) {
14562 return -1;
14563 }
14566 return 0;
14567 }
14568
14569 if ((colname = strchr(peername, ',')))
14570 *colname++ = '\0';
14571 else
14572 colname = "ip";
14573
14574 if (!(peer = find_peer(peername, 1)))
14575 return -1;
14576
14577 if (!strcasecmp(colname, "ip")) {
14579 } else if (!strcasecmp(colname, "status")) {
14580 peer_status(peer, buf, len);
14581 } else if (!strcasecmp(colname, "mailbox")) {
14582 ast_copy_string(buf, peer->mailbox, len);
14583 } else if (!strcasecmp(colname, "context")) {
14584 ast_copy_string(buf, peer->context, len);
14585 } else if (!strcasecmp(colname, "expire")) {
14586 snprintf(buf, len, "%d", peer->expire);
14587 } else if (!strcasecmp(colname, "dynamic")) {
14588 ast_copy_string(buf, (ast_test_flag64(peer, IAX_DYNAMIC) ? "yes" : "no"), len);
14589 } else if (!strcasecmp(colname, "callerid_name")) {
14591 } else if (!strcasecmp(colname, "callerid_num")) {
14592 ast_copy_string(buf, peer->cid_num, len);
14593 } else if (!strcasecmp(colname, "codecs")) {
14594 struct ast_str *codec_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
14595
14596 iax2_getformatname_multiple(peer->capability, &codec_buf);
14597 ast_copy_string(buf, ast_str_buffer(codec_buf), len);
14598 } else if (!strncasecmp(colname, "codec[", 6)) {
14599 char *codecnum, *ptr;
14600 struct ast_format *tmpfmt;
14601
14602 /* skip over "codec" to the '[' */
14603 codecnum = colname + 5;
14604 *codecnum = '\0';
14605 codecnum++;
14606 if ((ptr = strchr(codecnum, ']'))) {
14607 *ptr = '\0';
14608 }
14609 if((iax2_codec_pref_index(&peer->prefs, atoi(codecnum), &tmpfmt))) {
14611 } else {
14612 buf[0] = '\0';
14613 }
14614 } else {
14615 buf[0] = '\0';
14616 }
14617
14618 peer_unref(peer);
14619
14620 return 0;
14621}
14622
14623static struct ast_custom_function iaxpeer_function = {
14624 .name = "IAXPEER",
14625 .read = function_iaxpeer,
14626};
14627
14628static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *args, char *buf, size_t buflen)
14629{
14630 struct chan_iax2_pvt *pvt;
14631 unsigned int callno;
14632 int res = 0;
14633
14634 if (!chan || ast_channel_tech(chan) != &iax2_tech) {
14635 ast_log(LOG_ERROR, "This function requires a valid IAX2 channel\n");
14636 return -1;
14637 }
14638
14641 if (!(pvt = iaxs[callno])) {
14643 return -1;
14644 }
14645
14646 if (!strcasecmp(args, "osptoken")) {
14647 ast_copy_string(buf, pvt->osptoken, buflen);
14648 } else if (!strcasecmp(args, "peerip")) {
14650 } else if (!strcasecmp(args, "peername")) {
14651 ast_copy_string(buf, pvt->username, buflen);
14652 } else if (!strcasecmp(args, "auth_method")) {
14654 } else if (!strcasecmp(args, "secure_signaling") || !strcasecmp(args, "secure_media")) {
14655 snprintf(buf, buflen, "%s", IAX_CALLENCRYPTED(pvt) ? "1" : "");
14656 } else {
14657 res = -1;
14658 }
14659
14661
14662 return res;
14663}
14664
14665/*! \brief Part of the device state notification system ---*/
14666static int iax2_devicestate(const char *data)
14667{
14668 struct parsed_dial_string pds;
14669 char *tmp = ast_strdupa(data);
14670 struct iax2_peer *p;
14671 int res = AST_DEVICE_INVALID;
14672
14673 memset(&pds, 0, sizeof(pds));
14674 parse_dial_string(tmp, &pds);
14675
14676 if (ast_strlen_zero(pds.peer)) {
14677 ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", data);
14678 return res;
14679 }
14680
14681 ast_debug(3, "Checking device state for device %s\n", pds.peer);
14682
14683 /* SLD: FIXME: second call to find_peer during registration */
14684 if (!(p = find_peer(pds.peer, 1)))
14685 return res;
14686
14688
14689 ast_debug(3, "Found peer. What's device state of %s? addr=%s, defaddr=%s maxms=%d, lastms=%d\n",
14691
14692 if (((!ast_sockaddr_isnull(&p->addr)) || (!ast_sockaddr_isnull(&p->defaddr))) &&
14693 (!p->maxms || ((p->lastms > -1) && (p->historicms <= p->maxms)))) {
14694 /* Peer is registered, or have default IP address
14695 and a valid registration */
14696 if (p->historicms == 0 || p->historicms <= p->maxms)
14697 /* let the core figure out whether it is in use or not */
14698 res = AST_DEVICE_UNKNOWN;
14699 }
14700
14701 peer_unref(p);
14702
14703 return res;
14704}
14705
14706static struct ast_switch iax2_switch =
14707{
14708 .name = "IAX2",
14709 .description = "IAX Remote Dialplan Switch",
14710 .exists = iax2_exists,
14711 .canmatch = iax2_canmatch,
14712 .exec = iax2_exec,
14713 .matchmore = iax2_matchmore,
14714};
14715
14716static struct ast_cli_entry cli_iax2[] = {
14717 AST_CLI_DEFINE(handle_cli_iax2_provision, "Provision an IAX device"),
14718 AST_CLI_DEFINE(handle_cli_iax2_prune_realtime, "Prune a cached realtime lookup"),
14719 AST_CLI_DEFINE(handle_cli_iax2_reload, "Reload IAX configuration"),
14720 AST_CLI_DEFINE(handle_cli_iax2_set_mtu, "Set the IAX systemwide trunking MTU"),
14721 AST_CLI_DEFINE(handle_cli_iax2_set_debug, "Enable/Disable IAX debugging"),
14722 AST_CLI_DEFINE(handle_cli_iax2_set_debug_trunk, "Enable/Disable IAX trunk debugging"),
14723 AST_CLI_DEFINE(handle_cli_iax2_set_debug_jb, "Enable/Disable IAX jitterbuffer debugging"),
14724 AST_CLI_DEFINE(handle_cli_iax2_show_cache, "Display IAX cached dialplan"),
14725 AST_CLI_DEFINE(handle_cli_iax2_show_channels, "List active IAX channels"),
14726 AST_CLI_DEFINE(handle_cli_iax2_show_firmware, "List available IAX firmware"),
14727 AST_CLI_DEFINE(handle_cli_iax2_show_netstats, "List active IAX channel netstats"),
14728 AST_CLI_DEFINE(handle_cli_iax2_show_peer, "Show details on specific IAX peer"),
14729 AST_CLI_DEFINE(handle_cli_iax2_show_peers, "List defined IAX peers"),
14730 AST_CLI_DEFINE(handle_cli_iax2_show_registry, "Display IAX registration status"),
14731 AST_CLI_DEFINE(handle_cli_iax2_show_stats, "Display IAX statistics"),
14732 AST_CLI_DEFINE(handle_cli_iax2_show_threads, "Display IAX helper thread info"),
14733 AST_CLI_DEFINE(handle_cli_iax2_show_users, "List defined IAX users"),
14734 AST_CLI_DEFINE(handle_cli_iax2_test_losspct, "Set IAX2 incoming frame loss percentage"),
14735 AST_CLI_DEFINE(handle_cli_iax2_unregister, "Unregister (force expiration) an IAX2 peer from the registry"),
14736 AST_CLI_DEFINE(handle_cli_iax2_show_callno_limits, "Show current entries in IP call number limit table"),
14737#ifdef IAXTESTS
14738 AST_CLI_DEFINE(handle_cli_iax2_test_jitter, "Simulates jitter for testing"),
14739 AST_CLI_DEFINE(handle_cli_iax2_test_late, "Test the receipt of a late frame"),
14740 AST_CLI_DEFINE(handle_cli_iax2_test_resync, "Test a resync in received timestamps"),
14741#endif /* IAXTESTS */
14742};
14743
14744static void cleanup_thread_list(void *head)
14745{
14746 AST_LIST_HEAD(iax2_thread_list, iax2_thread);
14747 struct iax2_thread_list *list_head = head;
14748 struct iax2_thread *thread;
14749
14750 AST_LIST_LOCK(list_head);
14751 while ((thread = AST_LIST_REMOVE_HEAD(list_head, list))) {
14752 pthread_t thread_id = thread->threadid;
14753
14754 thread->stop = 1;
14755 signal_condition(&thread->lock, &thread->cond);
14756
14757 AST_LIST_UNLOCK(list_head);
14758 pthread_join(thread_id, NULL);
14759 AST_LIST_LOCK(list_head);
14760 }
14761 AST_LIST_UNLOCK(list_head);
14762}
14763
14764static int __unload_module(void)
14765{
14766 int x;
14767
14770
14771 ast_manager_unregister("IAXpeers");
14772 ast_manager_unregister("IAXpeerlist");
14773 ast_manager_unregister("IAXnetstats");
14774 ast_manager_unregister("IAXregistry");
14779
14781 pthread_cancel(netthreadid);
14782 pthread_kill(netthreadid, SIGURG);
14783 pthread_join(netthreadid, NULL);
14784 }
14785
14786 for (x = 0; x < ARRAY_LEN(iaxs); x++) {
14787 if (iaxs[x]) {
14788 iax2_destroy(x);
14789 }
14790 }
14791
14792 /* Call for all threads to halt */
14796
14799 for (x = 0; x < ARRAY_LEN(iaxs); x++) {
14800 if (iaxs[x]) {
14801 iax2_destroy(x);
14802 }
14803 }
14804 ast_manager_unregister( "IAXpeers" );
14805 ast_manager_unregister( "IAXpeerlist" );
14806 ast_manager_unregister( "IAXnetstats" );
14807 ast_manager_unregister( "IAXregistry" );
14812 delete_users();
14815
14816 for (x = 0; x < ARRAY_LEN(iaxsl); x++) {
14818 }
14819
14820 ao2_ref(peers, -1);
14821 ao2_ref(users, -1);
14826 if (timer) {
14828 timer = NULL;
14829 }
14831
14834 sched = NULL;
14835 ao2_ref(peercnts, -1);
14836
14838 ast_unload_realtime("iaxpeers");
14839
14842 return 0;
14843}
14844
14845static int unload_module(void)
14846{
14849 return __unload_module();
14850}
14851
14852static int peer_set_sock_cb(void *obj, void *arg, int flags)
14853{
14854 struct iax2_peer *peer = obj;
14855
14856 if (peer->sockfd < 0)
14857 peer->sockfd = defaultsockfd;
14858
14859 return 0;
14860}
14861
14862static int pvt_hash_cb(const void *obj, const int flags)
14863{
14864 const struct chan_iax2_pvt *pvt = obj;
14865
14866 return pvt->peercallno;
14867}
14868
14869static int pvt_cmp_cb(void *obj, void *arg, int flags)
14870{
14871 struct chan_iax2_pvt *pvt = obj, *pvt2 = arg;
14872
14873 /* The frames_received field is used to hold whether we're matching
14874 * against a full frame or not ... */
14875
14876 return match(&pvt2->addr, pvt2->peercallno, pvt2->callno, pvt,
14877 pvt2->frames_received) ? CMP_MATCH | CMP_STOP : 0;
14878}
14879
14880static int transfercallno_pvt_hash_cb(const void *obj, const int flags)
14881{
14882 const struct chan_iax2_pvt *pvt = obj;
14883
14884 return pvt->transfercallno;
14885}
14886
14887static int transfercallno_pvt_cmp_cb(void *obj, void *arg, int flags)
14888{
14889 struct chan_iax2_pvt *pvt = obj, *pvt2 = arg;
14890
14891 /* The frames_received field is used to hold whether we're matching
14892 * against a full frame or not ... */
14893
14894 return match(&pvt2->transfer, pvt2->transfercallno, pvt2->callno, pvt,
14895 pvt2->frames_received) ? CMP_MATCH | CMP_STOP : 0;
14896}
14897
14898static int load_objects(void)
14899{
14902
14905 if (!peers) {
14906 goto container_fail;
14907 }
14908
14911 if (!users) {
14912 goto container_fail;
14913 }
14914
14917 if (!iax_peercallno_pvts) {
14918 goto container_fail;
14919 }
14920
14924 goto container_fail;
14925 }
14926
14929 if (!peercnts) {
14930 goto container_fail;
14931 }
14932
14935 if (!callno_limits) {
14936 goto container_fail;
14937 }
14938
14941 if (!calltoken_ignores) {
14942 goto container_fail;
14943 }
14944
14945 if (create_callno_pools()) {
14946 goto container_fail;
14947 }
14948
14950 if (!transmit_processor) {
14951 goto container_fail;
14952 }
14953
14954 return 0;
14955
14956container_fail:
14957 if (peers) {
14958 ao2_ref(peers, -1);
14959 }
14960 if (users) {
14961 ao2_ref(users, -1);
14962 }
14963 if (iax_peercallno_pvts) {
14965 }
14968 }
14969 if (peercnts) {
14970 ao2_ref(peercnts, -1);
14971 }
14972 if (callno_limits) {
14974 }
14975 if (calltoken_ignores) {
14977 }
14978 return -1;
14979}
14980
14981/*!
14982 * \brief Load the module
14983 *
14984 * Module loading including tests for configuration or dependencies.
14985 * This function can return AST_MODULE_LOAD_FAILURE, AST_MODULE_LOAD_DECLINE,
14986 * or AST_MODULE_LOAD_SUCCESS. If a dependency or environment variable fails
14987 * tests return AST_MODULE_LOAD_FAILURE. If the module can not load the
14988 * configuration file or other non-critical problem return
14989 * AST_MODULE_LOAD_DECLINE. On success return AST_MODULE_LOAD_SUCCESS.
14990 */
14991static int load_module(void)
14992{
14993 static const char config[] = "iax.conf";
14994 int x = 0;
14995 struct iax2_registry *reg = NULL;
14996
14999 }
15001
15002 if (load_objects()) {
15006 }
15007
15008 memset(iaxs, 0, sizeof(iaxs));
15009
15010 for (x = 0; x < ARRAY_LEN(iaxsl); x++) {
15011 ast_mutex_init(&iaxsl[x]);
15012 }
15013
15014 if (!(sched = ast_sched_context_create())) {
15015 ast_log(LOG_ERROR, "Failed to create scheduler thread\n");
15019 }
15020
15025 sched = NULL;
15027 }
15028
15029 if (!(io = io_context_create())) {
15030 ast_log(LOG_ERROR, "Failed to create I/O context\n");
15034 sched = NULL;
15036 }
15037
15038 if (!(netsock = ast_netsock_list_alloc())) {
15039 ast_log(LOG_ERROR, "Failed to create netsock list\n");
15044 sched = NULL;
15046 }
15048
15050 if (!outsock) {
15051 ast_log(LOG_ERROR, "Could not allocate outsock list.\n");
15056 sched = NULL;
15058 }
15060
15062
15066
15067 if ((timer = ast_timer_open())) {
15069 }
15070
15071 if (set_config(config, 0, 0) == -1) {
15072 if (timer) {
15074 timer = NULL;
15075 }
15078 }
15079
15081
15083
15086
15091
15093 ast_log(LOG_ERROR, "Unable to register channel class %s\n", "IAX2");
15096 }
15097
15099 ast_log(LOG_ERROR, "Unable to register IAX switch\n");
15100 }
15101
15102 if (start_network_thread()) {
15103 ast_log(LOG_ERROR, "Unable to start network thread\n");
15106 } else {
15107 ast_verb(2, "IAX Ready and Listening\n");
15108 }
15109
15112 iax2_do_register(reg);
15114
15117
15118
15121
15122 ast_realtime_require_field("iaxpeers", "name", RQ_CHAR, 10, "ipaddr", RQ_CHAR, 15, "port", RQ_UINTEGER2, 5, "regseconds", RQ_UINTEGER2, 6, SENTINEL);
15123
15125
15127}
15128
15129AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Inter Asterisk eXchange (Ver 2)",
15130 .support_level = AST_MODULE_SUPPORT_CORE,
15131 .load = load_module,
15132 .unload = unload_module,
15133 .reload = reload,
15134 .load_pri = AST_MODPRI_CHANNEL_DRIVER,
15135 .requires = "dnsmgr",
15136 .optional_modules = "res_crypto",
15137);
enum ast_acl_sense ast_apply_acl(struct ast_acl_list *acl_list, const struct ast_sockaddr *addr, const char *purpose)
Apply a set of rules to a given IP address.
Definition acl.c:799
void ast_free_ha(struct ast_ha *ha)
Free a list of HAs.
Definition acl.c:222
int ast_str2tos(const char *value, unsigned int *tos)
Convert a string to the appropriate TOS value.
Definition acl.c:983
struct stasis_message_type * ast_named_acl_change_type(void)
a stasis_message_type for changes against a named ACL or the set of all named ACLs
void ast_copy_ha(const struct ast_ha *from, struct ast_ha *to)
Copy the contents of one HA to another.
Definition acl.c:255
void ast_append_acl(const char *sense, const char *stuff, struct ast_acl_list **path, int *error, int *named_acl_flag)
Add a rule to an ACL struct.
Definition acl.c:429
@ AST_SENSE_ALLOW
Definition acl.h:38
@ AST_SENSE_DENY
Definition acl.h:37
int ast_get_ip(struct ast_sockaddr *addr, const char *hostname)
Get the IP address given a hostname.
Definition acl.c:1016
int ast_acl_list_is_empty(struct ast_acl_list *acl_list)
Determines if an ACL is empty or if it contains entries.
Definition acl.c:540
int ast_str2cos(const char *value, unsigned int *cos)
Convert a string to the appropriate COS value.
Definition acl.c:969
struct ast_acl_list * ast_free_acl_list(struct ast_acl_list *acl)
Free a list of ACLs.
Definition acl.c:233
struct ast_ha * ast_append_ha(const char *sense, const char *stuff, struct ast_ha *path, int *error)
Add a new rule to a list of HAs.
Definition acl.c:712
int ast_get_ip_or_srv(struct ast_sockaddr *addr, const char *hostname, const char *service)
Get the IP address given a hostname and optional service.
Definition acl.c:933
void ast_cli_unregister_multiple(void)
Definition ael_main.c:408
static const struct adsi_event events[]
char digit
jack_status_t status
Definition app_jack.c:149
pthread_t thread
Definition app_sla.c:335
ast_cond_t cond
Definition app_sla.c:336
ast_mutex_t lock
Definition app_sla.c:337
static char zonetag[80]
static int copy(char *infile, char *outfile)
Utility function to copy a file.
#define var
Definition ast_expr2f.c:605
int ast_db_put(const char *family, const char *key, const char *value)
Store value addressed by family/key.
Definition db.c:335
int ast_db_get(const char *family, const char *key, char *value, int valuelen)
Get key value specified by family/key.
Definition db.c:421
int ast_db_del(const char *family, const char *key)
Delete entry in astdb.
Definition db.c:472
char * strsep(char **str, const char *delims)
#define ast_alloca(size)
call __builtin_alloca to ensure we get gcc builtin semantics
Definition astmm.h:288
#define ast_free(a)
Definition astmm.h:180
#define ast_realloc(p, len)
A wrapper for realloc()
Definition astmm.h:226
#define ast_strdup(str)
A wrapper for strdup()
Definition astmm.h:241
#define ast_strdupa(s)
duplicate a string in memory from the stack
Definition astmm.h:298
void ast_free_ptr(void *ptr)
free() wrapper
Definition astmm.c:1739
#define ast_calloc(num, len)
A wrapper for calloc()
Definition astmm.h:202
#define ast_malloc(len)
A wrapper for malloc()
Definition astmm.h:191
#define ast_log
Definition astobj2.c:42
#define ao2_iterator_next(iter)
Definition astobj2.h:1911
#define ao2_link(container, obj)
Add an object to a container.
Definition astobj2.h:1532
@ CMP_MATCH
Definition astobj2.h:1027
@ CMP_STOP
Definition astobj2.h:1028
#define OBJ_KEY
Definition astobj2.h:1151
#define OBJ_POINTER
Definition astobj2.h:1150
@ AO2_ALLOC_OPT_LOCK_MUTEX
Definition astobj2.h:363
#define ao2_callback(c, flags, cb_fn, arg)
ao2_callback() is a generic function that applies cb_fn() to all objects in a container,...
Definition astobj2.h:1693
#define ao2_cleanup(obj)
Definition astobj2.h:1934
#define ao2_unlink(container, obj)
Remove an object from a container.
Definition astobj2.h:1578
#define ao2_find(container, arg, flags)
Definition astobj2.h:1736
struct ao2_iterator ao2_iterator_init(struct ao2_container *c, int flags) attribute_warn_unused_result
Create an iterator for a container.
#define ao2_unlock(a)
Definition astobj2.h:729
#define ao2_lock(a)
Definition astobj2.h:717
#define ao2_ref(o, delta)
Reference/unreference an object and return the old refcount.
Definition astobj2.h:459
void ao2_iterator_destroy(struct ao2_iterator *iter)
Destroy a container iterator.
@ OBJ_NODATA
Definition astobj2.h:1044
@ OBJ_MULTIPLE
Definition astobj2.h:1049
@ OBJ_UNLINK
Definition astobj2.h:1039
#define ao2_alloc(data_size, destructor_fn)
Definition astobj2.h:409
#define ao2_container_alloc_hash(ao2_options, container_options, n_buckets, hash_fn, sort_fn, cmp_fn)
Allocate and initialize a hash container with the desired number of buckets.
Definition astobj2.h:1303
enum ast_transfer_result ast_bridge_transfer_blind(int is_external, struct ast_channel *transferer, const char *exten, const char *context, transfer_channel_cb new_channel_cb, void *user_data)
Blind transfer target to the extension and context provided.
Definition bridge.c:4634
@ AST_BRIDGE_TRANSFER_SUCCESS
Definition bridge.h:1161
#define AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN
Definition callerid.h:440
char * ast_callerid_merge(char *buf, int bufsiz, const char *name, const char *num, const char *unknown)
Definition callerid.c:1273
#define AST_PRES_NUMBER_NOT_AVAILABLE
Definition callerid.h:461
void ast_shrink_phone_number(char *n)
Shrink a phone number in place to just digits (more accurately it just removes ()'s,...
Definition callerid.c:1101
int ast_callerid_split(const char *src, char *name, int namelen, char *num, int numlen)
Definition callerid.c:1292
#define AST_CAUSE_CONGESTION
Definition causes.h:153
#define AST_CAUSE_BEARERCAPABILITY_NOTAVAIL
Definition causes.h:130
#define AST_CAUSE_DESTINATION_OUT_OF_ORDER
Definition causes.h:115
#define AST_CAUSE_NO_USER_RESPONSE
Definition causes.h:108
#define AST_CAUSE_FACILITY_NOT_SUBSCRIBED
Definition causes.h:126
#define AST_CAUSE_CALL_REJECTED
Definition causes.h:111
#define AST_CAUSE_FACILITY_REJECTED
Definition causes.h:117
#define AST_CAUSE_NO_ROUTE_DESTINATION
Definition causes.h:100
#define AST_CAUSE_UNREGISTERED
Definition causes.h:154
#define AST_CAUSE_BUSY
Definition causes.h:149
static int priority
static const char config_file[]
Definition cdr_odbc.c:54
static int connected
Definition cdr_pgsql.c:73
static char * tz
Definition cdr_pgsql.c:71
#define MAX_USER_BUCKETS
Definition chan_iax2.c:1040
static int timing_read(int *id, int fd, short events, void *cbdata)
Definition chan_iax2.c:9655
#define IAX_TRUNKTIMESTAMPS
Definition chan_iax2.c:556
static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen)
Definition chan_iax2.c:5864
static void set_peercnt_limit(struct peercnt *peercnt)
Definition chan_iax2.c:2639
static int check_access(int callno, struct ast_sockaddr *addr, struct iax_ies *ies)
Definition chan_iax2.c:7940
static int iaxthreadcount
Definition chan_iax2.c:757
static int send_ping(const void *data)
Definition chan_iax2.c:1826
static int iax2_trunk_expired(struct iax2_trunk_peer *tpeer, struct timeval *now)
Definition chan_iax2.c:9647
iax2_thread_iostate
Definition chan_iax2.c:1128
@ IAX_IOSTATE_PROCESSING
Definition chan_iax2.c:1131
@ IAX_IOSTATE_SCHEDREADY
Definition chan_iax2.c:1132
@ IAX_IOSTATE_IDLE
Definition chan_iax2.c:1129
@ IAX_IOSTATE_READY
Definition chan_iax2.c:1130
static int manager_iax2_show_peers(struct mansession *s, const struct message *m)
callback to display iax peers in manager
Definition chan_iax2.c:7398
static struct ao2_container * peercnts
Definition chan_iax2.c:1044
static struct iax2_context * build_context(const char *context)
static void save_rr(struct iax_frame *fr, struct iax_ies *ies)
Definition chan_iax2.c:9823
#define IAX_ALREADYGONE
Definition chan_iax2.c:544
#define IAX_PROVISION
Definition chan_iax2.c:545
static int update_registry(struct ast_sockaddr *addr, int callno, char *devtype, int fd, unsigned short refresh)
Definition chan_iax2.c:9197
static int iax2_write(struct ast_channel *c, struct ast_frame *f)
Definition chan_iax2.c:7836
#define AUTH_METHOD_NAMES_BUFSIZE
Definition chan_iax2.c:444
static struct iax2_peer * realtime_peer(const char *peername, struct ast_sockaddr *addr)
Definition chan_iax2.c:4470
static int socket_process_meta(int packet_len, struct ast_iax2_meta_hdr *meta, struct ast_sockaddr *addr, int sockfd, struct iax_frame *fr)
static struct iax2_user * user_unref(struct iax2_user *user)
Definition chan_iax2.c:2125
static int apply_context(struct iax2_context *con, const char *context)
Definition chan_iax2.c:7929
static struct ast_channel_tech iax2_tech
Definition chan_iax2.c:1379
static void __auto_hangup(const void *nothing)
Definition chan_iax2.c:9526
static int iax2_poke_peer_cb(void *obj, void *arg, int flags)
static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
Definition chan_iax2.c:2174
static char * complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags)
Definition chan_iax2.c:3977
static int autokill
Definition chan_iax2.c:383
static int randomcalltokendata
Definition chan_iax2.c:1022
static int iaxdynamicthreadcount
Definition chan_iax2.c:759
static void iax2_lock_owner(int callno)
Definition chan_iax2.c:1419
static int delayreject
Definition chan_iax2.c:515
static int iax2_queue_hold(int callno, const char *musicclass)
Queue a hold frame on the ast_channel owner.
Definition chan_iax2.c:3362
#define MAX_TIMESTAMP_SKEW
Definition chan_iax2.c:749
static void acl_change_stasis_subscribe(void)
Definition chan_iax2.c:1555
static void store_by_transfercallno(struct chan_iax2_pvt *pvt)
Definition chan_iax2.c:2485
static struct ast_channel * ast_iax2_new(int callno, int state, iax2_format capability, struct iax2_codec_pref *prefs, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor, unsigned int cachable)
Create new call, interface with the PBX core.
Definition chan_iax2.c:5959
static void jb_error_output(const char *fmt,...)
Definition chan_iax2.c:1294
static int peer_hash_cb(const void *obj, const int flags)
Definition chan_iax2.c:2048
static void iax2_publish_registry(const char *username, const char *domain, const char *status, const char *cause)
Definition chan_iax2.c:8905
static int replace_callno(const void *obj)
Definition chan_iax2.c:3068
#define CALLNO_ENTRY_IS_VALIDATED(a)
Definition chan_iax2.c:992
static int auto_congest(const void *data)
Definition chan_iax2.c:4848
static unsigned int calc_txpeerstamp(struct iax2_trunk_peer *tpeer, int sampms, struct timeval *now)
Definition chan_iax2.c:6158
static void __iax2_poke_noanswer(const void *data)
static int iax2_predestroy(int callno)
Definition chan_iax2.c:3522
static int update_packet(struct iax_frame *f)
Definition chan_iax2.c:3607
static int iaxcompat
Definition chan_iax2.c:384
static int iax2_trunk_queue(struct chan_iax2_pvt *pvt, struct iax_frame *fr)
Definition chan_iax2.c:6413
static char * handle_cli_iax2_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition chan_iax2.c:3726
static int peercnt_hash_cb(const void *obj, const int flags)
Definition chan_iax2.c:2545
static int check_provisioning(struct ast_sockaddr *addr, int sockfd, char *si, unsigned int ver)
Definition chan_iax2.c:9794
static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
Definition chan_iax2.c:5497
static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int)
Definition chan_iax2.c:7924
static void unwrap_timestamp(struct iax_frame *fr)
Definition chan_iax2.c:4159
static int wait_for_peercallno(struct chan_iax2_pvt *pvt)
Definition chan_iax2.c:5478
static int iax2_hangup(struct ast_channel *c)
Definition chan_iax2.c:5430
static int queue_signalling(struct chan_iax2_pvt *pvt, struct ast_frame *f)
All frames other than that of type AST_FRAME_IAX must be held until we have received a destination ca...
Definition chan_iax2.c:2257
static int __schedule_action(void(*func)(const void *data), const void *data, const char *funcname)
Definition chan_iax2.c:1738
static int addr_range_match_address_cb(void *obj, void *arg, int flags)
Definition chan_iax2.c:2561
static int maxjitterbuffer
Definition chan_iax2.c:372
static int auth_fail(int callno, int failcode)
Definition chan_iax2.c:9511
static char * handle_cli_iax2_test_losspct(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition chan_iax2.c:3787
#define PEERS_FORMAT2
Definition chan_iax2.c:6995
#define PTR_TO_CALLNO(a)
Definition chan_iax2.c:329
static int iax2_queue_hangup(int callno)
Queue a hangup frame on the ast_channel owner.
Definition chan_iax2.c:3408
static int peercnt_remove_cb(const void *obj)
Definition chan_iax2.c:2794
static unsigned int fix_peerts(struct timeval *rxtrunktime, int callno, unsigned int ts)
Definition chan_iax2.c:6187
static unsigned char compress_subclass(iax2_format subclass)
Definition chan_iax2.c:1899
static int handle_error(void)
Definition chan_iax2.c:3441
#define IAX_TRUNK
Definition chan_iax2.c:538
static const char * auth_method_labels[]
Name of effective auth method.
Definition chan_iax2.c:436
static int peer_cmp_cb(void *obj, void *arg, int flags)
Definition chan_iax2.c:2059
static void resend_with_token(int callno, struct iax_frame *f, const char *newtoken)
Definition chan_iax2.c:4921
static int get_auth_methods(const char *value)
static int handle_call_token(struct ast_iax2_full_hdr *fh, struct iax_ies *ies, struct ast_sockaddr *addr, int fd)
Definition chan_iax2.c:5043
static struct chan_iax2_pvt * new_iax(struct ast_sockaddr *addr, const char *host)
Definition chan_iax2.c:2329
static char default_parkinglot[AST_MAX_CONTEXT]
Definition chan_iax2.c:359
static struct iax2_trunk_peer * find_tpeer(struct ast_sockaddr *addr, int fd)
Definition chan_iax2.c:6377
static void iax_error_output(const char *data)
Definition chan_iax2.c:1289
static void vnak_retransmit(int callno, int last)
Definition chan_iax2.c:9573
static int user_delme_cb(void *obj, void *arg, int flags)
static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int)
Definition chan_iax2.c:7919
static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen)
static struct ast_custom_function iaxvar_function
#define IAX_SHRINKCALLERID
Definition chan_iax2.c:565
static void defer_full_frame(struct iax2_thread *from_here, struct iax2_thread *to_here)
Queue the last read full frame for processing by a certain thread.
Definition chan_iax2.c:9937
static int iax2_exec(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
Execute IAX2 dialplan switch.
static int __unload_module(void)
static char * handle_cli_iax2_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition chan_iax2.c:7737
static struct stasis_subscription * acl_change_sub
Definition chan_iax2.c:365
static int iax2_poke_peer(struct iax2_peer *peer, int heldcall)
static iax2_format iax2_capability
Definition chan_iax2.c:496
#define DEFAULT_MAX_THREAD_COUNT
Definition chan_iax2.c:333
static ast_mutex_t iaxsl[ARRAY_LEN(iaxs)]
chan_iax2_pvt structure locks
Definition chan_iax2.c:1249
static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration)
Definition chan_iax2.c:4432
static uint16_t DEFAULT_MAXCALLNO_LIMIT_NONVAL
Definition chan_iax2.c:1054
static struct ast_sched_context * sched
Definition chan_iax2.c:494
static void * dp_lookup_thread(void *data)
Definition chan_iax2.c:9765
static uint16_t DEFAULT_MAXCALLNO_LIMIT
Definition chan_iax2.c:1052
static void peercnt_modify(unsigned char reg, uint16_t limit, struct ast_sockaddr *sockaddr)
Definition chan_iax2.c:2689
static int transmit_trunk(struct iax_frame *f, struct ast_sockaddr *addr, int sockfd)
Definition chan_iax2.c:3475
static int registry_rerequest(struct iax_ies *ies, int callno, struct ast_sockaddr *addr)
Definition chan_iax2.c:9423
static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int)
Definition chan_iax2.c:7884
static void encmethods_to_str(int e, struct ast_str **buf)
Definition chan_iax2.c:1836
static void construct_rr(struct chan_iax2_pvt *pvt, struct iax_ie_data *iep)
Definition chan_iax2.c:9807
static struct ast_custom_function iaxpeer_function
static int load_objects(void)
static int complete_transfer(int callno, struct iax_ies *ies)
Definition chan_iax2.c:8844
static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
Definition chan_iax2.c:4454
static struct ast_format * codec_choose_from_prefs(struct iax2_codec_pref *pref, struct ast_format_cap *cap)
Definition chan_iax2.c:1933
static int prune_addr_range_cb(void *obj, void *arg, int flags)
Definition chan_iax2.c:2678
static void iax_debug_output(const char *data)
Definition chan_iax2.c:1283
#define IAX_CALLENCRYPTED(pvt)
Definition chan_iax2.c:477
static char * handle_cli_iax2_provision(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
static uint16_t global_maxcallno_nonval
Definition chan_iax2.c:1059
static int maxjitterinterps
Definition chan_iax2.c:374
static int schedule_delivery(struct iax_frame *fr, int updatehistory, int fromtrunk, unsigned int *tsout)
Definition chan_iax2.c:4329
#define IAX_ENCRYPTED
Definition chan_iax2.c:547
static void jb_debug_output(const char *fmt,...)
Definition chan_iax2.c:1318
#define IAX_CODEC_NOCAP
Definition chan_iax2.c:551
static int ping_time
Definition chan_iax2.c:370
static void iax_pvt_callid_new(int callno)
Definition chan_iax2.c:1223
static char * regstate2str(int regstate)
Definition chan_iax2.c:7459
static int last_authmethod
Definition chan_iax2.c:385
#define IAX_NOTRANSFER
Definition chan_iax2.c:539
static int __iax2_show_peers(int fd, int *total, struct mansession *s, const int argc, const char *const argv[])
Definition chan_iax2.c:7099
#define IAX_IMMEDIATE
Definition chan_iax2.c:561
static int iax2_call(struct ast_channel *c, const char *dest, int timeout)
Definition chan_iax2.c:5205
static char * handle_cli_iax2_set_mtu(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Set trunk MTU from CLI.
Definition chan_iax2.c:4046
static int trunk_untimed
Definition chan_iax2.c:355
static void pvt_destructor(void *obj)
Definition chan_iax2.c:2282
static int addr_range_hash_cb(const void *obj, const int flags)
Definition chan_iax2.c:2531
static int pvt_hash_cb(const void *obj, const int flags)
static int iax2_queue_unhold(int callno)
Queue an unhold frame on the ast_channel owner.
Definition chan_iax2.c:3385
#define MAX_TRUNK_MTU
Maximum transmission unit for the UDP packet in the trunk not to be fragmented. This is based on 1516...
Definition chan_iax2.c:352
static int iax2_getpeername(struct ast_sockaddr addr, char *host, int len)
Definition chan_iax2.c:2131
static struct iax2_peer * build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly)
Create peer structure based on configuration.
static int find_callno_locked(unsigned short callno, unsigned short dcallno, struct ast_sockaddr *addr, int new, int sockfd, int full_frame)
Definition chan_iax2.c:3324
static void * iax2_process_thread(void *data)
static struct @119 frame_queue[IAX_MAX_CALLS]
a list of frames that may need to be retransmitted
static int iax2_digit_begin(struct ast_channel *c, char digit)
Definition chan_iax2.c:4427
static struct iax2_user * build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly)
Create in-memory user structure from configuration.
static char regcontext[AST_MAX_CONTEXT]
Definition chan_iax2.c:362
static int socket_process_helper(struct iax2_thread *thread)
#define IAX_CAPABILITY_FULLBANDWIDTH
Definition chan_iax2.c:410
static struct ao2_container * peers
Definition chan_iax2.c:1038
static int set_config(const char *config_file, int reload, int forced)
Load configuration.
static int try_transfer(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
Definition chan_iax2.c:8763
static void _iax2_show_peers_one(int fd, struct mansession *s, struct show_peers_context *cont, struct iax2_peer *peer)
Definition chan_iax2.c:6998
static void __auto_congest(const void *nothing)
Definition chan_iax2.c:4835
#define IAX_HASCALLERID
Definition chan_iax2.c:535
static void free_signaling_queue_entry(struct signaling_queue_entry *s)
Definition chan_iax2.c:2234
static int __send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno, int now, int transfer, int final)
Definition chan_iax2.c:7865
#define MARK_IAX_SUBCLASS_TX
Definition chan_iax2.c:755
static int iax2_key_rotate(const void *vpvt)
Definition chan_iax2.c:5592
#define schedule_action(func, data)
Definition chan_iax2.c:1763
static int invalid_key(ast_aes_decrypt_key *ecx)
Definition chan_iax2.c:6496
static int user_cmp_cb(void *obj, void *arg, int flags)
Definition chan_iax2.c:2082
static void __expire_registry(const void *data)
Definition chan_iax2.c:9093
static void reg_source_db(struct iax2_peer *p)
Definition chan_iax2.c:9143
static int scheduled_destroy(const void *vid)
Definition chan_iax2.c:2222
static void prune_peers(void)
static time_t max_calltoken_delay
Definition chan_iax2.c:1024
static struct ao2_container * callno_limits
Definition chan_iax2.c:1047
static int calltoken_required(struct ast_sockaddr *addr, const char *name, int subclass)
Definition chan_iax2.c:2580
static struct ast_frame * iax2_read(struct ast_channel *c)
Definition chan_iax2.c:5586
static struct ast_netsock_list * netsock
Definition chan_iax2.c:403
static int min_reg_expire
Definition chan_iax2.c:396
static int add_calltoken_ignore(const char *addr)
Definition chan_iax2.c:2881
static int authenticate_reply(struct chan_iax2_pvt *p, struct ast_sockaddr *addr, struct iax_ies *ies, const char *override, const char *okey)
Definition chan_iax2.c:8596
#define ACN_FORMAT2
static char * handle_cli_iax2_show_firmware(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition chan_iax2.c:7371
static int iax2_transfer(struct ast_channel *c, const char *dest)
Definition chan_iax2.c:5917
static int iax2_transmit(struct iax_frame *fr)
Definition chan_iax2.c:4420
#define IAX_SENDANI
Definition chan_iax2.c:542
struct iax_frame * last
Definition chan_iax2.c:1018
static void __auth_reject(const void *nothing)
Definition chan_iax2.c:9477
static int adsi
Definition chan_iax2.c:514
static void build_ecx_key(const unsigned char *digest, struct chan_iax2_pvt *pvt)
Definition chan_iax2.c:6518
iax2_thread_type
Definition chan_iax2.c:1135
@ IAX_THREAD_TYPE_DYNAMIC
Definition chan_iax2.c:1137
@ IAX_THREAD_TYPE_POOL
Definition chan_iax2.c:1136
#define CALLNO_ENTRY_GET_CALLNO(a)
Definition chan_iax2.c:993
static int iax2_getpeertrunk(struct ast_sockaddr addr)
Definition chan_iax2.c:5937
static int attempt_transmit(const void *data)
Definition chan_iax2.c:3717
static int encrypt_frame(ast_aes_encrypt_key *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen)
Definition chan_iax2.c:6629
static struct ast_netsock_list * outsock
Definition chan_iax2.c:404
static void prune_users(void)
#define DEFAULT_CONTEXT
Definition chan_iax2.c:357
static void user_destructor(void *obj)
static struct ao2_container * iax_transfercallno_pvts
Another container of iax2_pvt structures.
Definition chan_iax2.c:1256
static struct iax2_user * find_user(const char *name)
Definition chan_iax2.c:2120
static int resyncthreshold
Definition chan_iax2.c:373
#define IAX_RECVCONNECTEDLINE
Definition chan_iax2.c:563
static void register_peer_exten(struct iax2_peer *peer, int onoff)
Definition chan_iax2.c:9055
static int transfercallno_pvt_cmp_cb(void *obj, void *arg, int flags)
#define MAX_RETRY_TIME
Definition chan_iax2.c:742
static int iaxdynamicthreadnum
Definition chan_iax2.c:760
static ast_mutex_t callno_pool_lock
Definition chan_iax2.c:1001
#define TRUNK_CALL_START
Definition chan_iax2.c:1260
static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int)
Definition chan_iax2.c:7909
#define MAX_TRUNKDATA
Definition chan_iax2.c:377
static int trunk_maxmtu
Definition chan_iax2.c:355
#define DEFAULT_FREQ_OK
Definition chan_iax2.c:432
static void free_context(struct iax2_context *con)
static char * handle_cli_iax2_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition chan_iax2.c:7564
#define CALLNO_ENTRY_SET_VALIDATED(a)
Definition chan_iax2.c:991
static uint16_t total_nonval_callno_used
Definition chan_iax2.c:1061
static int complete_dpreply(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
Definition chan_iax2.c:8797
#define IAX_DEBUGDIGEST(msg, key)
Definition chan_iax2.c:480
static const char tdesc[]
Definition chan_iax2.c:347
static void parse_dial_string(char *data, struct parsed_dial_string *pds)
Parses an IAX dial string into its component parts.
Definition chan_iax2.c:5145
static int global_rtautoclear
Definition chan_iax2.c:566
static void iax2_destroy(int callno)
Definition chan_iax2.c:3545
static int manager_iax2_show_netstats(struct mansession *s, const struct message *m)
Definition chan_iax2.c:7351
static void spawn_dp_lookup(int callno, const char *context, const char *callednum, const char *callerid)
Definition chan_iax2.c:9776
#define CALLNO_TO_PTR(a)
Definition chan_iax2.c:330
static struct iax_frame * iaxfrdup2(struct iax_frame *fr)
Definition chan_iax2.c:2372
static int transmit_frame(void *data)
Definition chan_iax2.c:4393
static int acf_iaxvar_write(struct ast_channel *chan, const char *cmd, char *data, const char *value)
static int iax2_answer(struct ast_channel *c)
Definition chan_iax2.c:5857
static int iax2_authmethods
Definition chan_iax2.c:517
static const char * iax2_getformatname_multiple(iax2_format format, struct ast_str **codec_buf)
Definition chan_iax2.c:2001
static void set_hangup_source_and_cause(int callno, unsigned char causecode)
#define IAX_RTUPDATE
Definition chan_iax2.c:553
#define IAX_QUELCH
Definition chan_iax2.c:546
static int iax2_canmatch(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
part of the IAX2 dial plan switch interface
static void __send_ping(const void *data)
Definition chan_iax2.c:1802
static struct iax2_peer * find_peer(const char *name, int realtime)
Definition chan_iax2.c:2095
static char * handle_cli_iax2_show_netstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition chan_iax2.c:7714
#define MIN_RETRY_TIME
Definition chan_iax2.c:741
static int iaxactivethreadcount
Definition chan_iax2.c:761
static int check_srcaddr(struct ast_sockaddr *addr)
Check if address can be used as packet source.
#define IAX_MAXAUTHREQ
Definition chan_iax2.c:558
static void insert_idle_thread(struct iax2_thread *thread)
Definition chan_iax2.c:1656
static void acl_change_stasis_unsubscribe(void)
Definition chan_iax2.c:1565
static int match(struct ast_sockaddr *addr, unsigned short callno, unsigned short dcallno, const struct chan_iax2_pvt *cur, int check_dcallno)
Definition chan_iax2.c:2401
static int pvt_cmp_cb(void *obj, void *arg, int flags)
static int authenticate(const char *challenge, const char *secret, const char *keyn, int authmethods, struct iax_ie_data *ied, struct ast_sockaddr *addr, struct chan_iax2_pvt *pvt)
Definition chan_iax2.c:8518
static void network_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message)
Definition chan_iax2.c:1583
static int iaxdefaulttimeout
Definition chan_iax2.c:389
static struct ao2_container * users
Definition chan_iax2.c:1041
static int auth_reject(const void *data)
Definition chan_iax2.c:9497
static int create_callno_pools(void)
Definition chan_iax2.c:3107
static void send_signaling(struct chan_iax2_pvt *pvt)
This function must be called once we are sure the other side has given us a call number....
Definition chan_iax2.c:2244
#define CALLTOKEN_IE_FORMAT
static char * handle_cli_iax2_show_cache(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition chan_iax2.c:4087
#define IAX_FORCE_ENCRYPT
Definition chan_iax2.c:564
static char * handle_cli_iax2_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
static void network_change_stasis_subscribe(void)
Definition chan_iax2.c:1540
static struct ast_switch iax2_switch
iax_transfer_state
Definition chan_iax2.c:708
@ TRANSFER_MEDIA
Definition chan_iax2.c:718
@ TRANSFER_NONE
Definition chan_iax2.c:709
@ TRANSFER_MPASSTHROUGH
Definition chan_iax2.c:717
@ TRANSFER_MEDIAPASS
Definition chan_iax2.c:719
@ TRANSFER_PASSTHROUGH
Definition chan_iax2.c:713
@ TRANSFER_MRELEASED
Definition chan_iax2.c:716
@ TRANSFER_BEGIN
Definition chan_iax2.c:710
@ TRANSFER_MREADY
Definition chan_iax2.c:715
@ TRANSFER_READY
Definition chan_iax2.c:711
@ TRANSFER_MBEGIN
Definition chan_iax2.c:714
@ TRANSFER_RELEASED
Definition chan_iax2.c:712
static void poke_all_peers(void)
#define IAX_SENDCONNECTEDLINE
Definition chan_iax2.c:562
static int(* iax2_regfunk)(const char *username, int onoff)
Definition chan_iax2.c:407
static int network_change_sched_cb(const void *data)
Definition chan_iax2.c:1570
static int find_callno(unsigned short callno, unsigned short dcallno, struct ast_sockaddr *addr, int new, int sockfd, int full_frame)
Definition chan_iax2.c:3320
static int __do_deliver(void *data)
Definition chan_iax2.c:3426
#define IAX_RTCACHEFRIENDS
Definition chan_iax2.c:552
#define IAX_RTIGNOREREGEXPIRE
Definition chan_iax2.c:555
static char * papp
static int socket_process(struct iax2_thread *thread)
static int manager_iax2_show_registry(struct mansession *s, const struct message *m)
Definition chan_iax2.c:7522
static void dp_lookup(int callno, const char *context, const char *callednum, const char *callerid, int skiplock)
Definition chan_iax2.c:9733
static int iax2_poke_noanswer(const void *data)
static int get_unused_callno(enum callno_type type, int validated, callno_entry *entry)
Definition chan_iax2.c:2991
static char * handle_cli_iax2_show_callno_limits(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition chan_iax2.c:2922
static char * handle_cli_iax2_show_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition chan_iax2.c:4000
static int authdebug
Definition chan_iax2.c:382
static struct ast_taskprocessor * transmit_processor
Definition chan_iax2.c:1020
static int iaxdefaultdpcache
Definition chan_iax2.c:387
static int trunk_nmaxmtu
Definition chan_iax2.c:355
static int function_iaxpeer(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
#define DEFAULT_MAXMS
Definition chan_iax2.c:431
static int send_lagrq(const void *data)
Definition chan_iax2.c:1890
static int peer_set_srcaddr(struct iax2_peer *peer, const char *srcaddr)
Parse the "sourceaddress" value, lookup in netsock list and set peer's sockfd. Defaults to defaultsoc...
static int peercnt_add(struct ast_sockaddr *addr)
Definition chan_iax2.c:2717
static int iax2_do_register(struct iax2_registry *reg)
static int iax2_register(const char *value, int lineno)
Definition chan_iax2.c:9019
static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
Definition chan_iax2.c:4444
static struct ast_timer * timer
Definition chan_iax2.c:401
static void __send_lagrq(const void *data)
Definition chan_iax2.c:1866
static void unlink_peer(struct iax2_peer *peer)
Definition chan_iax2.c:9074
static int authenticate_request(int call_num)
Definition chan_iax2.c:8210
static struct iax2_peer * peer_unref(struct iax2_peer *peer)
Definition chan_iax2.c:2114
static int iax2_append_register(const char *hostname, const char *username, const char *secret, const char *porta)
Definition chan_iax2.c:8977
static int maxauthreq
Definition chan_iax2.c:368
static int firmware_show_callback(struct ast_iax2_firmware_header *header, void *user_data)
Definition chan_iax2.c:7358
static int get_from_jb(const void *p)
Definition chan_iax2.c:4314
static void save_osptoken(struct iax_frame *fr, struct iax_ies *ies)
Definition chan_iax2.c:9834
static int max_reg_expire
Definition chan_iax2.c:397
iax_reg_state
Definition chan_iax2.c:698
@ REG_STATE_REGSENT
Definition chan_iax2.c:700
@ REG_STATE_TIMEOUT
Definition chan_iax2.c:704
@ REG_STATE_AUTHSENT
Definition chan_iax2.c:701
@ REG_STATE_NOAUTH
Definition chan_iax2.c:705
@ REG_STATE_REGISTERED
Definition chan_iax2.c:702
@ REG_STATE_REJECTED
Definition chan_iax2.c:703
@ REG_STATE_UNREGISTERED
Definition chan_iax2.c:699
static int iax2_queryoption(struct ast_channel *c, int option, void *data, int *datalen)
Definition chan_iax2.c:5569
static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts, struct ast_frame *f)
Definition chan_iax2.c:6202
#define ACN_FORMAT1
#define DEFAULT_RETRY_TIME
Definition chan_iax2.c:334
static int peer_status(struct iax2_peer *peer, char *status, int statuslen)
peer_status: Report Peer status in character string
Definition chan_iax2.c:3878
static void set_config_destroy(void)
static int attribute_pure iax2_allow_new(int frametype, int subclass, int inbound)
Definition chan_iax2.c:3171
#define IAX_RTSAVE_SYSNAME
Definition chan_iax2.c:543
static iax2_format iax2_codec_choose(struct iax2_codec_pref *pref, iax2_format formats)
Definition chan_iax2.c:1967
static int iax2_delete_from_sched(const void *data)
Definition chan_iax2.c:2163
static int lagrq_time
Definition chan_iax2.c:371
static char * handle_cli_iax2_set_debug_jb(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition chan_iax2.c:7810
#define DEFAULT_FREQ_NOTOK
Definition chan_iax2.c:433
static void update_jbsched(struct chan_iax2_pvt *pvt)
Definition chan_iax2.c:4194
static void store_by_peercallno(struct chan_iax2_pvt *pvt)
Definition chan_iax2.c:2504
static int set_peercnt_limit_all_cb(void *obj, void *arg, int flags)
Definition chan_iax2.c:2664
static int trunkmaxsize
Definition chan_iax2.c:380
@ NEW_PREVENT
Definition chan_iax2.c:2391
@ NEW_ALLOW
Definition chan_iax2.c:2393
@ NEW_FORCE
Definition chan_iax2.c:2395
@ NEW_ALLOW_CALLTOKEN_VALIDATED
Definition chan_iax2.c:2398
static void handle_deferred_full_frames(struct iax2_thread *thread)
Handle any deferred full frames for this thread.
Definition chan_iax2.c:9907
static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt)
Definition chan_iax2.c:7630
static int transfercallno_pvt_hash_cb(const void *obj, const int flags)
static int test_losspct
Definition chan_iax2.c:502
static int decrypt_frame(int callno, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen)
Definition chan_iax2.c:6668
static int srvlookup
Definition chan_iax2.c:399
static void iax_pvt_callid_set(int callno, ast_callid callid)
Definition chan_iax2.c:1218
static void __get_from_jb(const void *p)
Definition chan_iax2.c:4211
static int iax2_encryption
Definition chan_iax2.c:516
static int peercnt_remove_by_addr(struct ast_sockaddr *addr)
Definition chan_iax2.c:2808
static int decode_frame(ast_aes_decrypt_key *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen)
Definition chan_iax2.c:6576
static struct call_number_pool callno_pool
Definition chan_iax2.c:1004
static pthread_t netthreadid
Definition chan_iax2.c:521
#define CALLNO_ENTRY_TO_PTR(a)
Definition chan_iax2.c:989
static int trunkfreq
Definition chan_iax2.c:379
static void build_rand_pad(unsigned char *buf, ssize_t len)
Definition chan_iax2.c:6486
static void signal_condition(ast_mutex_t *lock, ast_cond_t *cond)
Definition chan_iax2.c:1196
static char * handle_cli_iax2_set_debug_trunk(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition chan_iax2.c:7784
static char * handle_cli_iax2_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition chan_iax2.c:7481
static int iax2_sched_add(struct ast_sched_context *sched, int when, ast_sched_cb callback, const void *data)
Definition chan_iax2.c:1772
static int socket_read(int *id, int fd, short events, void *cbdata)
Definition chan_iax2.c:9968
static int peer_delme_cb(void *obj, void *arg, int flags)
static int create_addr(const char *peername, struct ast_channel *c, struct ast_sockaddr *addr, struct create_addr_info *cai)
Definition chan_iax2.c:4719
static char * auth_method_names(int authmethods, char *restrict buf)
Get names of all auth methods.
Definition chan_iax2.c:452
static int user_hash_cb(const void *obj, const int flags)
Definition chan_iax2.c:2071
static void peer_destructor(void *obj)
static void __iax2_do_register_s(const void *data)
Definition chan_iax2.c:8736
#define IAX_USEJITTERBUF
Definition chan_iax2.c:540
static int send_apathetic_reply(unsigned short callno, unsigned short dcallno, struct ast_sockaddr *addr, int command, int ts, unsigned char seqno, int sockfd, struct iax_ie_data *ied)
Definition chan_iax2.c:4883
static void jb_warning_output(const char *fmt,...)
Definition chan_iax2.c:1306
static int iax2_exists(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
Part of the IAX2 switch interface.
calltoken_peer_enum
Call token validation settings.
Definition chan_iax2.c:573
@ CALLTOKEN_DEFAULT
Default calltoken required unless the ip is in the ignorelist.
Definition chan_iax2.c:575
@ CALLTOKEN_AUTO
Require call token validation after a successful registration using call token validation occurs.
Definition chan_iax2.c:580
@ CALLTOKEN_NO
Do not require call token validation.
Definition chan_iax2.c:582
@ CALLTOKEN_YES
Require call token validation.
Definition chan_iax2.c:577
static int get_encrypt_methods(const char *s)
Definition chan_iax2.c:1852
static int jittertargetextra
Definition chan_iax2.c:375
static int iax2_matchmore(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
Part of the IAX2 Switch interface.
static struct ast_flags64 globalflags
Definition chan_iax2.c:519
static struct iax2_dpcache * find_cache(struct ast_channel *chan, const char *data, const char *context, const char *exten, int priority)
static iax2_format uncompress_subclass(unsigned char csub)
Definition chan_iax2.c:1919
static void * network_thread(void *ignore)
static char * handle_cli_iax2_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition chan_iax2.c:7326
static int iax2_is_control_frame_allowed(int subtype)
Definition chan_iax2.c:1443
static void network_change_stasis_unsubscribe(void)
Definition chan_iax2.c:1550
static void realtime_update_peer(const char *peername, struct ast_sockaddr *sockaddr, time_t regtime)
Definition chan_iax2.c:4677
static struct io_context * io
Definition chan_iax2.c:493
static int trunk_timed
Definition chan_iax2.c:355
static char * complete_iax2_unregister(const char *line, const char *word, int pos, int state)
Definition chan_iax2.c:7301
static struct stasis_subscription * network_change_sub
Definition chan_iax2.c:364
static int raw_hangup(struct ast_sockaddr *addr, unsigned short src, unsigned short dst, int sockfd)
Definition chan_iax2.c:8173
#define PTR_TO_CALLNO_ENTRY(a)
Definition chan_iax2.c:988
static struct ao2_container * calltoken_ignores
Definition chan_iax2.c:1050
static void * iax2_dup_variable_datastore(void *)
Definition chan_iax2.c:1614
static struct iax2_codec_pref prefs_global
Definition chan_iax2.c:345
iax2_state
Definition chan_iax2.c:523
@ IAX_STATE_TBD
Definition chan_iax2.c:526
@ IAX_STATE_AUTHENTICATED
Definition chan_iax2.c:525
@ IAX_STATE_STARTED
Definition chan_iax2.c:524
static struct iax2_user * realtime_user(const char *username, struct ast_sockaddr *addr)
Definition chan_iax2.c:4602
#define IAX2_TRUNK_PREFACE
Definition chan_iax2.c:675
static int iax2_ack_registry(struct iax_ies *ies, struct ast_sockaddr *addr, int callno)
Acknowledgment received for OUR registration.
Definition chan_iax2.c:8911
static void __iax2_poke_peer_s(const void *data)
Definition chan_iax2.c:9586
static int load_module(void)
Load the module.
static int iax2_vnak(int callno)
Definition chan_iax2.c:9568
#define IAX_CAPABILITY_MEDBANDWIDTH
Definition chan_iax2.c:412
static int iax2_parse_allow_disallow(struct iax2_codec_pref *pref, iax2_format *formats, const char *list, int allowing)
Definition chan_iax2.c:2015
#define DEFAULT_TRUNKDATA
Definition chan_iax2.c:747
static char * handle_cli_iax2_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Show one peer in detail.
Definition chan_iax2.c:3901
static void iax2_process_thread_cleanup(void *data)
#define IAX_TRANSFERMEDIA
Definition chan_iax2.c:557
static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen)
Definition chan_iax2.c:4449
#define IAX_KEYPOPULATED
Definition chan_iax2.c:548
static int addr_range_cmp_cb(void *obj, void *arg, int flags)
Definition chan_iax2.c:2537
#define IAX_RTAUTOCLEAR
Definition chan_iax2.c:554
static int registry_authrequest(int callno)
Definition chan_iax2.c:9375
static int iax2_provision(struct ast_sockaddr *end, int sockfd, const char *dest, const char *template, int force)
#define FORMAT
const char * iax2_getformatname(iax2_format format)
iax2 wrapper function for ast_getformatname
Definition chan_iax2.c:1989
#define DEFAULT_THREAD_COUNT
Definition chan_iax2.c:332
static int iaxdebug
Definition chan_iax2.c:498
static int acf_iaxvar_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
static void iax2_free_variable_datastore(void *)
Definition chan_iax2.c:1638
uint16_t callno_entry
Definition chan_iax2.c:777
static int iax2_poke_peer_s(const void *data)
Definition chan_iax2.c:9593
static int addr_range_delme_cb(void *obj, void *arg, int flags)
Definition chan_iax2.c:2524
static struct iax2_thread * find_idle_thread(void)
Definition chan_iax2.c:1671
static struct ast_channel * iax2_request(const char *type, struct ast_format_cap *cap, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor, const char *data, int *cause)
#define IAX_DYNAMIC
Definition chan_iax2.c:541
static void add_empty_calltoken_ie(struct chan_iax2_pvt *pvt, struct iax_ie_data *ied)
Definition chan_iax2.c:4911
static int max_retries
Definition chan_iax2.c:369
static void delete_users(void)
#define MIN_REUSE_TIME
Definition chan_iax2.c:340
#define FORMAT2
#define IAX_TEMPONLY
Definition chan_iax2.c:537
#define IAX_DELAYPBXSTART
Definition chan_iax2.c:559
static int cache_get_callno_locked(const char *data)
static void iax_outputframe(struct iax_frame *f, struct ast_iax2_full_hdr *fhi, int rx, struct ast_sockaddr *addr, int datalen)
Definition chan_iax2.c:1265
static int unload_module(void)
static void remove_by_transfercallno(struct chan_iax2_pvt *pvt)
Definition chan_iax2.c:2495
static struct chan_iax2_pvt * iaxs[IAX_MAX_CALLS]
an array of iax2 pvt structures
Definition chan_iax2.c:1211
static int reload(void)
static int peer_set_sock_cb(void *obj, void *arg, int flags)
static int amaflags
Definition chan_iax2.c:513
static void stop_stuff(int callno)
Definition chan_iax2.c:9472
static char * handle_cli_iax2_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition chan_iax2.c:6910
static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now)
Definition chan_iax2.c:9604
static void log_jitterstats(unsigned short callno)
Definition chan_iax2.c:9864
static struct iax2_peer * peer_ref(struct iax2_peer *peer)
Definition chan_iax2.c:2108
static ast_callid iax_pvt_callid_get(int callno)
Definition chan_iax2.c:1213
#define IAX_CAPABILITY_LOWBANDWIDTH
Definition chan_iax2.c:422
static void cleanup_thread_list(void *head)
static int iaxtrunkdebug
Definition chan_iax2.c:500
static int manager_iax2_show_peer_list(struct mansession *s, const struct message *m)
callback to display iax peers in manager format
Definition chan_iax2.c:7420
static int iax2_queue_frame(int callno, struct ast_frame *f)
Queue a frame to a call's owning asterisk channel.
Definition chan_iax2.c:3339
static int authenticate_verify(struct chan_iax2_pvt *p, struct iax_ies *ies)
Definition chan_iax2.c:8261
static int iax2_sendtext(struct ast_channel *c, const char *text)
Definition chan_iax2.c:4437
static struct ast_sockaddr debugaddr
Definition chan_iax2.c:1263
static int send_packet(struct iax_frame *f)
Definition chan_iax2.c:3488
static char language[MAX_LANGUAGE]
Definition chan_iax2.c:361
static char accountcode[AST_MAX_ACCOUNT_CODE]
Definition chan_iax2.c:510
static void merge_encryption(struct chan_iax2_pvt *p, unsigned int enc)
Definition chan_iax2.c:8189
static void memcpy_decrypt(unsigned char *dst, const unsigned char *src, int len, ast_aes_decrypt_key *dcx)
Definition chan_iax2.c:6528
static char * handle_cli_iax2_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition chan_iax2.c:7260
#define IAX_ALLOWFWDOWNLOAD
Definition chan_iax2.c:560
#define IAX_CODEC_USER_FIRST
Definition chan_iax2.c:549
static int iax2_lock_callno_unless_destroyed(int callno)
Acquire the iaxsl[callno] if call exists and not having ongoing hangup.
Definition chan_iax2.c:1784
static struct call_number_pool callno_pool_trunk
Definition chan_iax2.c:1007
static uint16_t global_maxcallno
Definition chan_iax2.c:1056
static void remove_by_peercallno(struct chan_iax2_pvt *pvt)
Definition chan_iax2.c:2514
#define CALLTOKEN_HASH_FORMAT
#define IAX_DELME
Definition chan_iax2.c:536
@ CACHE_FLAG_TIMEOUT
Definition chan_iax2.c:1097
@ CACHE_FLAG_EXISTS
Definition chan_iax2.c:1089
@ CACHE_FLAG_UNKNOWN
Definition chan_iax2.c:1101
@ CACHE_FLAG_MATCHMORE
Definition chan_iax2.c:1103
@ CACHE_FLAG_CANEXIST
Definition chan_iax2.c:1093
@ CACHE_FLAG_PENDING
Definition chan_iax2.c:1095
@ CACHE_FLAG_NONEXISTENT
Definition chan_iax2.c:1091
@ CACHE_FLAG_TRANSMITTED
Definition chan_iax2.c:1099
static int start_network_thread(void)
#define PEERS_FORMAT
Definition chan_iax2.c:6996
static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset)
Definition chan_iax2.c:6337
callno_type
Definition chan_iax2.c:983
@ CALLNO_TYPE_TRUNK
Definition chan_iax2.c:985
@ CALLNO_TYPE_NORMAL
Definition chan_iax2.c:984
static int iax2_sched_replace(int id, struct ast_sched_context *con, int when, ast_sched_cb callback, const void *data)
Definition chan_iax2.c:1766
static char mohsuggest[MAX_MUSICCLASS]
Definition chan_iax2.c:512
static int __find_callno(unsigned short callno, unsigned short dcallno, struct ast_sockaddr *addr, int new, int sockfd, int return_locked, int check_dcallno)
Definition chan_iax2.c:3194
static void build_encryption_keys(const unsigned char *digest, struct chan_iax2_pvt *pvt)
Definition chan_iax2.c:6512
static struct @118 qos
static void build_callno_limits(struct ast_variable *v)
Definition chan_iax2.c:2826
static void __attempt_transmit(const void *data)
Definition chan_iax2.c:3634
static struct ast_cli_entry cli_iax2[]
static unsigned int iax2_datetime(const char *tz)
Definition chan_iax2.c:4857
static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final)
Definition chan_iax2.c:6696
#define IAX_CODEC_NOPREFS
Definition chan_iax2.c:550
static int auto_hangup(const void *data)
Definition chan_iax2.c:9541
static char * handle_cli_iax2_show_threads(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition chan_iax2.c:7191
static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message)
Definition chan_iax2.c:1597
static char mohinterpret[MAX_MUSICCLASS]
Definition chan_iax2.c:511
static const struct ast_datastore_info iax2_variable_datastore_info
Definition chan_iax2.c:1608
static void sched_delay_remove(struct ast_sockaddr *addr, callno_entry entry)
Definition chan_iax2.c:3140
static int iax2_do_register_s(const void *data)
Definition chan_iax2.c:8754
static int iax2_devicestate(const char *data)
Part of the device state notification system —.
static void peercnt_remove(struct peercnt *peercnt)
Definition chan_iax2.c:2768
static int network_change_sched_id
Definition chan_iax2.c:366
static int expire_registry(const void *data)
Definition chan_iax2.c:9134
#define MAX_PEER_BUCKETS
Definition chan_iax2.c:1036
static void iax2_frame_free(struct iax_frame *fr)
Definition chan_iax2.c:2216
static void memcpy_encrypt(unsigned char *dst, const unsigned char *src, int len, ast_aes_encrypt_key *ecx)
Definition chan_iax2.c:6552
static void requirecalltoken_mark_auto(const char *name, int subclass)
Definition chan_iax2.c:5003
static int defaultsockfd
Definition chan_iax2.c:405
static int iaxmaxthreadcount
Definition chan_iax2.c:758
static int peercnt_cmp_cb(void *obj, void *arg, int flags)
Definition chan_iax2.c:2555
static struct ao2_container * iax_peercallno_pvts
Another container of iax2_pvt structures.
Definition chan_iax2.c:1240
static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int)
Definition chan_iax2.c:7895
static int make_trunk(unsigned short callno, int locked)
Definition chan_iax2.c:2419
static int register_verify(int callno, struct ast_sockaddr *addr, struct iax_ies *ies)
Verify inbound registration.
Definition chan_iax2.c:8356
static int global_max_trunk_mtu
Definition chan_iax2.c:354
static void iax2_dprequest(struct iax2_dpcache *dp, int callno)
Definition chan_iax2.c:9556
static const char type[]
struct ast_sockaddr bindaddr
static char version[AST_MAX_EXTENSION]
static const char config[]
static int transfer(void *data)
static int reload_config(void)
void ast_channel_exten_set(struct ast_channel *chan, const char *value)
const char * ast_channel_name(const struct ast_channel *chan)
#define ast_channel_alloc_with_endpoint(needqueue, state, cid_num, cid_name, acctcode, exten, context, assignedids, requestor, amaflag, endpoint,...)
Definition channel.h:1303
void * ast_channel_tech_pvt(const struct ast_channel *chan)
int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
Add a datastore to a channel.
Definition channel.c:2376
void ast_hangup(struct ast_channel *chan)
Hang up a channel.
Definition channel.c:2540
#define AST_BRIDGE_DTMF_CHANNEL_0
Report DTMF on channel 0.
Definition channel.h:2420
#define ast_channel_alloc(needqueue, state, cid_num, cid_name, acctcode, exten, context, assignedids, requestor, amaflag,...)
Create a channel structure.
Definition channel.h:1299
int ast_queue_hangup(struct ast_channel *chan)
Queue a hangup frame.
Definition channel.c:1182
int ast_party_id_presentation(const struct ast_party_id *id)
Determine the overall presentation value for the given party.
Definition channel.c:1808
#define DATASTORE_INHERIT_FOREVER
Definition channel.h:194
void ast_channel_nativeformats_set(struct ast_channel *chan, struct ast_format_cap *value)
void ast_party_connected_line_free(struct ast_party_connected_line *doomed)
Destroy the connected line information contents.
Definition channel.c:2059
struct ast_channel * ast_waitfor_n(struct ast_channel **chan, int n, int *ms)
Waits for input on a group of channels Wait for input on an array of channels for a given # of millis...
Definition channel.c:3161
#define ast_channel_lock(chan)
Definition channel.h:2983
struct ast_format_cap * ast_channel_nativeformats(const struct ast_channel *chan)
@ AST_FLAG_DISABLE_DEVSTATE_CACHE
Definition channel.h:1049
struct ast_party_redirecting * ast_channel_redirecting(struct ast_channel *chan)
void ast_channel_unregister(const struct ast_channel_tech *tech)
Unregister a channel technology.
Definition channel.c:571
struct ast_flags * ast_channel_flags(struct ast_channel *chan)
#define ast_channel_ref(c)
Increase channel reference count.
Definition channel.h:3008
struct ast_party_connected_line * ast_channel_connected(struct ast_channel *chan)
int ast_queue_frame(struct ast_channel *chan, struct ast_frame *f)
Queue one or more frames to a channel's frame queue.
Definition channel.c:1171
const char * ast_channel_context(const struct ast_channel *chan)
int ast_write(struct ast_channel *chan, struct ast_frame *frame)
Write a frame to a channel This function writes the given frame to the indicated channel.
Definition channel.c:5167
struct ast_frame * ast_read(struct ast_channel *chan)
Reads a frame.
Definition channel.c:4278
#define AST_BRIDGE_DTMF_CHANNEL_1
Report DTMF on channel 1.
Definition channel.h:2422
#define ast_channel_trylock(chan)
Definition channel.h:2985
int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control, const void *data, size_t datalen)
Queue a control frame with payload.
Definition channel.c:1296
ast_channel_adsicpe
Definition channel.h:888
@ AST_ADSI_UNAVAILABLE
Definition channel.h:891
void ast_set_callerid(struct ast_channel *chan, const char *cid_num, const char *cid_name, const char *cid_ani)
Set caller ID number, name and ANI and generate AMI event.
Definition channel.c:7370
int ast_set_read_format(struct ast_channel *chan, struct ast_format *format)
Sets read format on channel chan.
Definition channel.c:5785
void ast_channel_set_rawreadformat(struct ast_channel *chan, struct ast_format *format)
void ast_channel_tech_pvt_set(struct ast_channel *chan, void *value)
int ast_connected_line_parse_data(const unsigned char *data, size_t datalen, struct ast_party_connected_line *connected)
Parse connected line indication frame data.
Definition channel.c:8961
int ast_check_hangup(struct ast_channel *chan)
Check to see if a channel is needing hang up.
Definition channel.c:446
int ast_channel_hangupcause(const struct ast_channel *chan)
void ast_channel_set_rawwriteformat(struct ast_channel *chan, struct ast_format *format)
struct ast_party_dialed * ast_channel_dialed(struct ast_channel *chan)
#define AST_MAX_ACCOUNT_CODE
Definition channel.h:172
struct ast_channel * ast_channel_release(struct ast_channel *chan)
Unlink and release reference to a channel.
Definition channel.c:1571
void ast_set_hangupsource(struct ast_channel *chan, const char *source, int force)
Set the source of the hangup in this channel and it's bridge.
Definition channel.c:2498
void ast_channel_hangupcause_hash_set(struct ast_channel *chan, const struct ast_control_pvt_cause_code *cause_code, int datalen)
Sets the HANGUPCAUSE hash and optionally the SIP_CAUSE hash on the given channel.
Definition channel.c:4368
int ast_queue_unhold(struct ast_channel *chan)
Queue an unhold frame.
Definition channel.c:1274
ast_bridge_result
Definition channel.h:208
@ AST_BRIDGE_FAILED_NOWARN
Definition channel.h:211
@ AST_BRIDGE_RETRY
Definition channel.h:212
@ AST_BRIDGE_COMPLETE
Definition channel.h:209
@ AST_BRIDGE_FAILED
Definition channel.h:210
int ast_queue_hold(struct ast_channel *chan, const char *musicclass)
Queue a hold frame.
Definition channel.c:1249
void ast_channel_set_readformat(struct ast_channel *chan, struct ast_format *format)
#define AST_CHANNEL_NAME
Definition channel.h:173
int ast_channel_register(const struct ast_channel_tech *tech)
Register a channel technology (a new channel driver) Called by a channel module to register the kind ...
Definition channel.c:540
void ast_channel_softhangup_internal_flag_add(struct ast_channel *chan, int value)
#define ast_channel_unref(c)
Decrease channel reference count.
Definition channel.h:3019
struct ast_format * ast_channel_writeformat(struct ast_channel *chan)
int ast_set_write_format(struct ast_channel *chan, struct ast_format *format)
Sets write format on channel chan.
Definition channel.c:5826
#define AST_MAX_CONTEXT
Definition channel.h:135
void ast_party_connected_line_init(struct ast_party_connected_line *init)
Initialize the given connected line structure.
Definition channel.c:2009
void ast_channel_amaflags_set(struct ast_channel *chan, enum ama_flags value)
const char * ast_channel_language(const struct ast_channel *chan)
void ast_channel_context_set(struct ast_channel *chan, const char *value)
@ AST_SOFTHANGUP_DEV
Definition channel.h:1141
enum ama_flags ast_channel_string2amaflag(const char *flag)
Convert a string to a detail record AMA flag.
Definition channel.c:4382
@ AST_CHAN_TP_WANTSJITTER
Channels have this property if they can accept input with jitter; i.e. most VoIP channels.
Definition channel.h:980
struct ast_party_caller * ast_channel_caller(struct ast_channel *chan)
void ast_channel_callid_set(struct ast_channel *chan, ast_callid value)
void ast_channel_hangupcause_set(struct ast_channel *chan, int value)
void ast_channel_adsicpe_set(struct ast_channel *chan, enum ast_channel_adsicpe value)
void ast_channel_tech_set(struct ast_channel *chan, const struct ast_channel_tech *value)
#define ast_channel_unlock(chan)
Definition channel.h:2984
#define AST_MAX_EXTENSION
Definition channel.h:134
void ast_channel_set_writeformat(struct ast_channel *chan, struct ast_format *format)
#define MAX_MUSICCLASS
Definition channel.h:175
struct ast_datastore * ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, const char *uid)
Find a datastore on a channel.
Definition channel.c:2390
struct ast_format * ast_channel_readformat(struct ast_channel *chan)
uint64_t iax2_format_compatibility_best(uint64_t formats)
Pick the best format from the given bitfield formats.
uint64_t iax2_format_compatibility_cap2bitfield(const struct ast_format_cap *cap)
Convert a format capabilities structure to a bitfield.
int iax2_format_compatibility_bitfield2cap(uint64_t bitfield, struct ast_format_cap *cap)
Convert a bitfield to a format capabilities structure.
ast_channel_state
ast_channel states
@ AST_STATE_RING
@ AST_STATE_RINGING
@ AST_STATE_DOWN
@ AST_STATE_RESERVED
int ast_setstate(struct ast_channel *chan, enum ast_channel_state)
Change the state of a channel.
Definition channel.c:7422
static struct ast_channel * callback(struct ast_channelstorage_instance *driver, ao2_callback_data_fn *cb_fn, void *arg, void *data, int ao2_flags, int rdlock)
const char * ast_var_name(const struct ast_var_t *var)
Definition chanvars.c:60
#define ast_var_assign(name, value)
Definition chanvars.h:40
const char * ast_var_value(const struct ast_var_t *var)
Definition chanvars.c:80
void ast_var_delete(struct ast_var_t *var)
Definition extconf.c:2469
#define CLI_SHOWUSAGE
Definition cli.h:45
#define CLI_SUCCESS
Definition cli.h:44
#define AST_CLI_DEFINE(fn, txt,...)
Definition cli.h:197
#define RESULT_SHOWUSAGE
Definition cli.h:41
void ast_cli(int fd, const char *fmt,...)
Definition clicompat.c:6
#define RESULT_SUCCESS
Definition cli.h:40
char * ast_cli_complete(const char *word, const char *const choices[], int pos)
Definition main/cli.c:1931
@ CLI_HANDLER
Definition cli.h:154
@ CLI_INIT
Definition cli.h:152
@ CLI_GENERATE
Definition cli.h:153
#define CLI_FAILURE
Definition cli.h:46
#define RESULT_FAILURE
Definition cli.h:42
#define ast_cli_register_multiple(e, len)
Register multiple commands.
Definition cli.h:265
@ AST_MEDIA_TYPE_AUDIO
Definition codec.h:32
@ AST_MEDIA_TYPE_UNKNOWN
Definition codec.h:31
unsigned int ast_codec_samples_count(struct ast_frame *frame)
Get the number of samples contained within a frame.
Definition codec.c:379
int iax2_codec_pref_string(struct iax2_codec_pref *pref, char *buf, size_t size)
Dump audio codec preference list into a string.
Definition codec_pref.c:178
void iax2_codec_pref_prepend(struct iax2_codec_pref *pref, struct ast_format *format, unsigned int framing, int only_if_existing)
Prepend an audio codec to a preference list, removing it first if it was already there.
Definition codec_pref.c:432
uint64_t iax2_codec_pref_order_value_to_format_bitfield(int order_value)
Convert an iax2_codec_pref order value into a format bitfield.
Definition codec_pref.c:367
uint64_t iax2_codec_pref_from_bitfield(struct iax2_codec_pref *pref, uint64_t bitfield)
Create codec preference list from the given bitfield formats.
Definition codec_pref.c:481
struct ast_format * iax2_codec_pref_index(struct iax2_codec_pref *pref, int idx, struct ast_format **result)
Codec located at a particular place in the preference index.
Definition codec_pref.c:77
void iax2_codec_pref_convert(struct iax2_codec_pref *pref, char *buf, size_t size, int right)
Shift an audio codec preference list up or down 65 bytes so that it becomes an ASCII string.
Definition codec_pref.c:44
void iax2_codec_pref_remove_missing(struct iax2_codec_pref *pref, uint64_t bitfield)
Removes format from the pref list that aren't in the bitfield.
Definition codec_pref.c:288
void iax2_codec_pref_append(struct iax2_codec_pref *pref, struct ast_format *format, unsigned int framing)
Append a audio codec to a preference list, removing it first if it was already there.
Definition codec_pref.c:420
int iax2_codec_pref_to_cap(struct iax2_codec_pref *pref, struct ast_format_cap *cap)
Convert a preference structure to a capabilities structure.
Definition codec_pref.c:91
int iax2_codec_pref_best_bitfield2cap(uint64_t bitfield, struct iax2_codec_pref *prefs, struct ast_format_cap *cap)
Convert a bitfield to a format capabilities structure in the "best" order.
Definition codec_pref.c:112
short word
#define attribute_pure
Definition compiler.h:35
#define SENTINEL
Definition compiler.h:87
int AST_OPTIONAL_API_NAME() ast_check_signature(struct ast_key *key, const char *msg, const char *sig)
Check the authenticity of a message signature using a given public key.
Definition res_crypto.c:673
int AST_OPTIONAL_API_NAME() ast_aes_set_encrypt_key(const unsigned char *key, ast_aes_encrypt_key *ctx)
Set an encryption key.
Definition res_crypto.c:700
int AST_OPTIONAL_API_NAME() ast_sign(struct ast_key *key, char *msg, char *sig)
Sign a message signature using a given private key.
Definition res_crypto.c:584
int AST_OPTIONAL_API_NAME() ast_aes_decrypt(const unsigned char *in, unsigned char *out, const ast_aes_decrypt_key *key)
AES decrypt data.
Definition res_crypto.c:790
#define AST_KEY_PUBLIC
Definition crypto.h:46
#define AST_KEY_PRIVATE
Definition crypto.h:47
struct ast_key *AST_OPTIONAL_API_NAME() ast_key_get(const char *kname, int ktype)
Retrieve a key.
Definition res_crypto.c:149
int AST_OPTIONAL_API_NAME() ast_aes_set_decrypt_key(const unsigned char *key, ast_aes_decrypt_key *ctx)
Set a decryption key.
Definition res_crypto.c:709
int AST_OPTIONAL_API_NAME() ast_aes_encrypt(const unsigned char *in, unsigned char *out, const ast_aes_encrypt_key *key)
AES encrypt data.
Definition res_crypto.c:749
#define ast_datastore_alloc(info, uid)
Definition datastore.h:85
int ast_datastore_free(struct ast_datastore *datastore)
Free a data store object.
Definition datastore.c:68
@ AST_DEVSTATE_CACHABLE
Definition devicestate.h:70
int ast_devstate_changed(enum ast_device_state state, enum ast_devstate_cache cachable, const char *fmt,...)
Tells Asterisk the State for Device is changed.
@ AST_DEVICE_UNKNOWN
Definition devicestate.h:53
@ AST_DEVICE_INVALID
Definition devicestate.h:57
@ AST_DEVICE_NOT_INUSE
Definition devicestate.h:54
@ AST_DEVICE_UNAVAILABLE
Definition devicestate.h:58
void ast_dnsmgr_release(struct ast_dnsmgr_entry *entry)
Free a DNS manager entry.
Definition dnsmgr.c:136
int ast_dnsmgr_lookup(const char *name, struct ast_sockaddr *result, struct ast_dnsmgr_entry **dnsmgr, const char *service)
Allocate and initialize a DNS manager entry.
Definition dnsmgr.c:191
int ast_dnsmgr_changed(struct ast_dnsmgr_entry *entry)
Check is see if a dnsmgr entry has changed.
Definition dnsmgr.c:247
int ast_dnsmgr_refresh(struct ast_dnsmgr_entry *entry)
Force a refresh of a dnsmgr entry.
Definition dnsmgr.c:239
threshold
Definition dsp.h:73
char * end
Definition eagi_proxy.c:73
char buf[BUFSIZE]
Definition eagi_proxy.c:66
@ AST_ENDPOINT_OFFLINE
Definition endpoints.h:55
@ AST_ENDPOINT_ONLINE
Definition endpoints.h:57
void ast_endpoint_set_state(struct ast_endpoint *endpoint, enum ast_endpoint_state state)
Updates the state of the given endpoint.
void ast_endpoint_shutdown(struct ast_endpoint *endpoint)
Shutsdown an ast_endpoint.
struct ast_endpoint * ast_endpoint_create(const char *tech, const char *resource)
Create an endpoint struct.
#define abs(x)
Definition f2c.h:195
int iax_firmware_get_version(const char *dev, uint16_t *version)
Definition firmware.c:263
void iax_firmware_reload(void)
Definition firmware.c:206
void iax_firmware_unload(void)
Definition firmware.c:250
int iax_firmware_append(struct iax_ie_data *ied, const char *dev, unsigned int desc)
Definition firmware.c:283
void iax_firmware_traverse(const char *filter, int(*callback)(struct ast_iax2_firmware_header *header, void *data), void *data)
Definition firmware.c:321
enum ast_media_type ast_format_get_type(const struct ast_format *format)
Get the media type of a format.
Definition format.c:354
unsigned int ast_format_get_sample_rate(const struct ast_format *format)
Get the sample rate of a media format.
Definition format.c:379
enum ast_format_cmp_res ast_format_cmp(const struct ast_format *format1, const struct ast_format *format2)
Compare two formats.
Definition format.c:201
@ AST_FORMAT_CMP_EQUAL
Definition format.h:36
const char * ast_format_get_name(const struct ast_format *format)
Get the name associated with a format.
Definition format.c:334
unsigned int ast_format_get_default_ms(const struct ast_format *format)
Get the default framing size (in milliseconds) for a format.
Definition format.c:359
struct ast_format * ast_format_slin
Built-in cached signed linear 8kHz format.
struct ast_format * ast_format_none
Built-in "null" format.
#define AST_FORMAT_CAP_NAMES_LEN
Definition format_cap.h:324
int ast_format_cap_append_by_type(struct ast_format_cap *cap, enum ast_media_type type)
Add all codecs Asterisk knows about for a specific type to the capabilities structure.
Definition format_cap.c:216
struct ast_format * ast_format_cap_get_format(const struct ast_format_cap *cap, int position)
Get the format at a specific index.
Definition format_cap.c:400
unsigned int ast_format_cap_get_format_framing(const struct ast_format_cap *cap, const struct ast_format *format)
Get the framing for a format.
Definition format_cap.c:443
int ast_format_cap_update_by_allow_disallow(struct ast_format_cap *cap, const char *list, int allowing)
Parse an "allow" or "deny" list and modify a format capabilities structure accordingly.
Definition format_cap.c:320
int ast_format_cap_get_compatible(const struct ast_format_cap *cap1, const struct ast_format_cap *cap2, struct ast_format_cap *result)
Find the compatible formats between two capabilities structures.
Definition format_cap.c:628
@ AST_FORMAT_CAP_FLAG_DEFAULT
Definition format_cap.h:38
const char * ast_format_cap_get_names(const struct ast_format_cap *cap, struct ast_str **buf)
Get the names of codecs of a set of formats.
Definition format_cap.c:734
int ast_format_cap_identical(const struct ast_format_cap *cap1, const struct ast_format_cap *cap2)
Determine if two capabilities structures are identical.
Definition format_cap.c:687
#define ast_format_cap_append(cap, format, framing)
Add format capability to capabilities structure.
Definition format_cap.h:99
#define ast_format_cap_alloc(flags)
Allocate a new ast_format_cap structure.
Definition format_cap.h:49
size_t ast_format_cap_count(const struct ast_format_cap *cap)
Get the number of formats present within the capabilities structure.
Definition format_cap.c:395
struct ast_format * ast_format_cap_get_compatible_format(const struct ast_format_cap *cap, const struct ast_format *format)
Find if input ast_format is within the capabilities of the ast_format_cap object then return the comp...
Definition format_cap.c:546
static const char name[]
Definition format_mp3.c:68
static int exists(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
Definition func_logic.c:185
static int md5(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
Definition func_md5.c:55
static int len(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t buflen)
void astman_send_listack(struct mansession *s, const struct message *m, char *msg, char *listflag)
Send ack in manager transaction to begin a list.
Definition manager.c:2042
void astman_send_list_complete_start(struct mansession *s, const struct message *m, const char *event_name, int count)
Start the list complete event.
Definition manager.c:2078
const char * astman_get_header(const struct message *m, char *var)
Get header from manager transaction.
Definition manager.c:1661
void astman_send_list_complete_end(struct mansession *s)
End the list complete event.
Definition manager.c:2086
void astman_append(struct mansession *s, const char *fmt,...)
Definition manager.c:1921
int ast_manager_unregister(const char *action)
Unregister a registered manager command.
Definition manager.c:7716
void ast_endpoint_blob_publish(struct ast_endpoint *endpoint, struct stasis_message_type *type, struct ast_json *blob)
Creates and publishes a ast_endpoint_blob message.
void ast_channel_stage_snapshot_done(struct ast_channel *chan)
Clear flag to indicate channel snapshot is being staged, and publish snapshot.
struct stasis_message_type * ast_endpoint_state_type(void)
Message type for endpoint state changes.
void ast_channel_stage_snapshot(struct ast_channel *chan)
Set flag to indicate channel snapshot is being staged.
static int iax2_prov_app(struct ast_channel *chan, const char *data)
const char * ext
Definition http.c:151
#define IAX_IE_PASSWORD
Definition iax2.h:137
#define IAX_LINGER_TIMEOUT
Definition iax2.h:126
#define IAX_IE_RR_PKTS
Definition iax2.h:179
#define IAX_DPSTATUS_CANEXIST
Definition iax2.h:218
@ IAX_COMMAND_FWDOWNL
Definition iax2.h:111
@ IAX_COMMAND_TXREL
Definition iax2.h:91
@ IAX_COMMAND_TXMEDIA
Definition iax2.h:115
@ IAX_COMMAND_AUTHREP
Definition iax2.h:60
@ IAX_COMMAND_PROVISION
Definition iax2.h:109
@ IAX_COMMAND_DPREP
Definition iax2.h:79
@ IAX_COMMAND_REGAUTH
Definition iax2.h:67
@ IAX_COMMAND_INVAL
Definition iax2.h:61
@ IAX_COMMAND_REJECT
Definition iax2.h:57
@ IAX_COMMAND_FWDATA
Definition iax2.h:113
@ IAX_COMMAND_ACK
Definition iax2.h:55
@ IAX_COMMAND_PONG
Definition iax2.h:54
@ IAX_COMMAND_LAGRQ
Definition iax2.h:62
@ IAX_COMMAND_HANGUP
Definition iax2.h:56
@ IAX_COMMAND_TXREADY
Definition iax2.h:89
@ IAX_COMMAND_TXACC
Definition iax2.h:87
@ IAX_COMMAND_QUELCH
Definition iax2.h:95
@ IAX_COMMAND_PING
Definition iax2.h:53
@ IAX_COMMAND_TRANSFER
Definition iax2.h:107
@ IAX_COMMAND_LAGRP
Definition iax2.h:63
@ IAX_COMMAND_TXCNT
Definition iax2.h:85
@ IAX_COMMAND_REGACK
Definition iax2.h:69
@ IAX_COMMAND_AUTHREQ
Definition iax2.h:59
@ IAX_COMMAND_TXREJ
Definition iax2.h:93
@ IAX_COMMAND_REGREJ
Definition iax2.h:71
@ IAX_COMMAND_REGREL
Definition iax2.h:73
@ IAX_COMMAND_CALLTOKEN
Definition iax2.h:119
@ IAX_COMMAND_DIAL
Definition iax2.h:81
@ IAX_COMMAND_ACCEPT
Definition iax2.h:58
@ IAX_COMMAND_UNSUPPORT
Definition iax2.h:105
@ IAX_COMMAND_NEW
Definition iax2.h:52
@ IAX_COMMAND_POKE
Definition iax2.h:99
@ IAX_COMMAND_REGREQ
Definition iax2.h:65
@ IAX_COMMAND_VNAK
Definition iax2.h:75
@ IAX_COMMAND_UNQUELCH
Definition iax2.h:97
@ IAX_COMMAND_TXREQ
Definition iax2.h:83
@ IAX_COMMAND_RTKEY
Definition iax2.h:117
@ IAX_COMMAND_DPREQ
Definition iax2.h:77
#define IAX_IE_RR_JITTER
Definition iax2.h:177
#define IAX_MAX_OSPBLOCK_SIZE
Definition iax2.h:192
#define IAX_IE_DNID
Definition iax2.h:143
#define IAX_IE_CALLINGANI2
Definition iax2.h:190
#define IAX_FLAG_SC_LOG
Definition iax2.h:44
#define IAX_IE_DATETIME
Definition iax2.h:161
#define IAX_IE_CAUSE
Definition iax2.h:152
#define IAX_IE_DPSTATUS
Definition iax2.h:150
#define IAX_IE_CALLING_NUMBER
Definition iax2.h:132
#define IAX_IE_TRANSFERID
Definition iax2.h:157
#define IAX_IE_CALLTOKEN
Definition iax2.h:185
#define IAX_IE_CALLING_ANI
Definition iax2.h:133
#define IAX_DEFAULT_PORTNO
Definition iax2.h:128
#define IAX_IE_CALLINGTNS
Definition iax2.h:170
#define IAX_IE_RSA_RESULT
Definition iax2.h:147
#define IAX_IE_MSGCOUNT
Definition iax2.h:154
#define IAX_META_TRUNK_SUPERMINI
Definition iax2.h:207
#define IAX_IE_IAX_UNKNOWN
Definition iax2.h:153
int64_t iax2_format
Definition iax2.h:224
#define IAX_DPSTATUS_NONEXISTENT
Definition iax2.h:219
#define IAX_IE_FORMAT2
Definition iax2.h:188
#define IAX_DPSTATUS_IGNOREPAT
Definition iax2.h:220
#define IAX_IE_CAPABILITY2
Definition iax2.h:187
#define IAX_IE_CALLING_NAME
Definition iax2.h:134
#define IAX_DEFAULT_REG_EXPIRE
Definition iax2.h:123
#define IAX_IE_ADSICPE
Definition iax2.h:142
#define IAX_IE_VARIABLE
Definition iax2.h:183
#define IAX_AUTH_RSA
Definition iax2.h:199
#define IAX_IE_OSPTOKEN
Definition iax2.h:184
#define IAX_IE_LANGUAGE
Definition iax2.h:140
#define IAX_MAX_OSPTOKEN_SIZE
Definition iax2.h:194
#define IAX_IE_RDNIS
Definition iax2.h:158
#define IAX_FLAG_FULL
Definition iax2.h:40
#define IAX_IE_RR_DROPPED
Definition iax2.h:181
#define IAX_MAX_SHIFT
Definition iax2.h:46
#define IAX_IE_FORMAT
Definition iax2.h:139
#define IAX_IE_ENCRYPTION
Definition iax2.h:173
#define IAX_ENCRYPT_AES128
Definition iax2.h:201
#define IAX_AUTH_MD5
Definition iax2.h:198
#define IAX_MAX_OSPBUFF_SIZE
Definition iax2.h:195
#define IAX_IE_FIRMWAREVER
Definition iax2.h:164
#define IAX_FLAG_RETRANS
Definition iax2.h:42
#define IAX_IE_CODEC_PREFS
Definition iax2.h:175
#define IAX_IE_CALLED_NUMBER
Definition iax2.h:131
#define IAX_IE_CAPABILITY
Definition iax2.h:138
#define IAX_DPSTATUS_MATCHMORE
Definition iax2.h:221
#define IAX_IE_PROVISIONING
Definition iax2.h:159
#define IAX_IE_MD5_RESULT
Definition iax2.h:146
#define IAX_PROTO_VERSION
Definition iax2.h:27
#define IAX_IE_AUTOANSWER
Definition iax2.h:155
#define IAX_IE_VERSION
Definition iax2.h:141
#define IAX_ENCRYPT_KEYROTATE
Definition iax2.h:202
#define IAX_IE_RR_OOO
Definition iax2.h:182
#define IAX_IE_CALLNO
Definition iax2.h:151
#define IAX_IE_APPARENT_ADDR
Definition iax2.h:148
#define IAX_AUTH_PLAINTEXT
Definition iax2.h:197
#define IAX_IE_REFRESH
Definition iax2.h:149
#define IAX_MAX_OSPBLOCK_NUM
Definition iax2.h:193
#define IAX_META_TRUNK
Definition iax2.h:204
#define IAX_META_TRUNK_MINI
Definition iax2.h:208
#define IAX_IE_CALLINGPRES
Definition iax2.h:168
#define IAX_IE_CAUSECODE
Definition iax2.h:172
#define IAX_IE_AUTHMETHODS
Definition iax2.h:144
#define IAX_IE_RR_LOSS
Definition iax2.h:178
#define IAX_MAX_CALLS
Definition iax2.h:37
#define IAX_IE_CALLED_CONTEXT
Definition iax2.h:135
#define IAX_IE_CALLINGTON
Definition iax2.h:169
#define IAX_DPSTATUS_EXISTS
Definition iax2.h:217
#define IAX_IE_USERNAME
Definition iax2.h:136
#define IAX_IE_CHALLENGE
Definition iax2.h:145
#define IAX_IE_RR_DELAY
Definition iax2.h:180
int ast_app_inboxcount(const char *mailboxes, int *newmsgs, int *oldmsgs)
Determine number of new/old messages in a mailbox.
Definition main/app.c:604
#define ast_config_load(filename, flags)
Load a config file.
@ CONFIG_FLAG_FILEUNCHANGED
char * ast_category_browse(struct ast_config *config, const char *prev_name)
Browse categories.
Definition extconf.c:3324
int ast_realtime_require_field(const char *family,...) attribute_sentinel
Inform realtime what fields that may be stored.
#define ast_variable_new(name, value, filename)
int ast_unload_realtime(const char *family)
Release any resources cached for a realtime family.
#define CONFIG_STATUS_FILEUNCHANGED
#define CONFIG_STATUS_FILEINVALID
int ast_parse_arg(const char *arg, enum ast_parse_flags flags, void *p_result,...)
The argument parsing routine.
void ast_config_destroy(struct ast_config *cfg)
Destroys a config.
Definition extconf.c:1287
int ast_variable_list_replace(struct ast_variable **head, struct ast_variable *replacement)
Replace a variable in the given list with a new value.
const char * ast_variable_retrieve(struct ast_config *config, const char *category, const char *variable)
int ast_update_realtime(const char *family, const char *keyfield, const char *lookup,...) attribute_sentinel
Update realtime configuration.
struct ast_variable * ast_load_realtime(const char *family,...) attribute_sentinel
void ast_variables_destroy(struct ast_variable *var)
Free variable list.
Definition extconf.c:1260
struct ast_variable * ast_variable_browse(const struct ast_config *config, const char *category_name)
Definition extconf.c:1213
uint64_t ast_format_compatibility_format2bitfield(const struct ast_format *format)
Convert a format structure to its respective bitfield.
struct ast_format * ast_format_compatibility_bitfield2format(uint64_t bitfield)
Convert a bitfield to its respective format structure.
#define ast_frame_byteswap_be(fr)
#define AST_FRAME_DTMF
#define AST_OPTION_RELAXDTMF
#define AST_OPTION_TONE_VERIFY
#define AST_OPTION_RXGAIN
#define AST_OPTION_DIGIT_DETECT
@ AST_TRANSFER_SUCCESS
#define AST_OPTION_OPRMODE
#define ast_frfree(fr)
@ AST_FRFLAG_HAS_TIMING_INFO
#define AST_OPTION_TDD
#define AST_OPTION_SECURE_MEDIA
#define AST_OPTION_FLAG_REQUEST
#define AST_OPTION_FAX_DETECT
#define AST_OPTION_TXGAIN
#define AST_FRIENDLY_OFFSET
Offset into a frame's data buffer.
#define AST_OPTION_SECURE_SIGNALING
@ AST_FRAME_DTMF_END
@ AST_FRAME_DTMF_BEGIN
@ AST_FRAME_CONTROL
ast_control_frame_type
Internal control frame subtype field values.
@ AST_CONTROL_SRCUPDATE
@ AST_CONTROL_RECORD_CANCEL
@ AST_CONTROL_PROGRESS
@ AST_CONTROL_STREAM_TOPOLOGY_SOURCE_CHANGED
@ AST_CONTROL_OFFHOOK
@ AST_CONTROL_STREAM_RESTART
@ AST_CONTROL_STREAM_SUSPEND
@ AST_CONTROL_RADIO_UNKEY
@ AST_CONTROL_UNHOLD
@ AST_CONTROL_VIDUPDATE
@ AST_CONTROL_STREAM_TOPOLOGY_REQUEST_CHANGE
@ AST_CONTROL_STREAM_REVERSE
@ AST_CONTROL_PROCEEDING
@ AST_CONTROL_REDIRECTING
@ AST_CONTROL_TAKEOFFHOOK
@ AST_CONTROL_T38_PARAMETERS
@ AST_CONTROL_READ_ACTION
@ AST_CONTROL_RECORD_STOP
@ AST_CONTROL_CONGESTION
@ AST_CONTROL_PLAYBACK_BEGIN
@ AST_CONTROL_ANSWER
@ AST_CONTROL_RECORD_MUTE
@ AST_CONTROL_RINGING
@ AST_CONTROL_HANGUP
@ AST_CONTROL_STREAM_STOP
@ AST_CONTROL_RADIO_KEY
@ AST_CONTROL_OPTION
@ AST_CONTROL_STREAM_TOPOLOGY_CHANGED
@ AST_CONTROL_CONNECTED_LINE
@ AST_CONTROL_END_OF_Q
@ AST_CONTROL_TRANSFER
@ AST_CONTROL_STREAM_FORWARD
@ AST_CONTROL_FLASH
@ AST_CONTROL_RECORD_SUSPEND
@ AST_CONTROL_SRCCHANGE
@ AST_CONTROL_INCOMPLETE
@ _XXX_AST_CONTROL_T38
@ AST_CONTROL_MASQUERADE_NOTIFY
@ AST_CONTROL_PVT_CAUSE_CODE
@ AST_CONTROL_UPDATE_RTP_PEER
#define AST_OPTION_AUDIO_MODE
struct ast_frame ast_null_frame
Definition main/frame.c:79
void ast_callid_strnprint(char *buffer, size_t buffer_size, ast_callid callid)
copy a string representation of the callid into a target string
Definition logger.c:2258
#define ast_debug(level,...)
Log a DEBUG message.
ast_callid ast_read_threadstorage_callid(void)
extracts the callid from the thread
Definition logger.c:2268
int ast_callid_threadassoc_add(ast_callid callid)
Adds a known callid to thread storage of the calling thread.
Definition logger.c:2290
#define AST_CALLID_BUFFER_LENGTH
ast_callid ast_create_callid(void)
factory function to create a new uniquely identifying callid.
Definition logger.c:2263
unsigned int ast_callid
#define VERBOSE_PREFIX_4
int ast_callid_threadassoc_remove(void)
Removes callid from thread storage of the calling thread.
Definition logger.c:2309
#define LOG_ERROR
#define ast_verb(level,...)
#define LOG_NOTICE
#define LOG_WARNING
#define ast_verbose(...)
#define AST_IO_IN
Definition io.h:34
struct io_context * io_context_create(void)
Creates a context Create a context for I/O operations Basically mallocs an IO structure and sets up s...
Definition io.c:81
int * ast_io_add(struct io_context *ioc, int fd, ast_io_cb callback, short events, void *data)
Adds an IO context.
Definition io.c:162
#define AST_IO_PRI
Definition io.h:38
void io_context_destroy(struct io_context *ioc)
Destroys a context.
Definition io.c:107
int ast_io_wait(struct io_context *ioc, int howlong)
Waits for IO.
Definition io.c:278
void jb_destroy(jitterbuf *jb)
destroy jitterbuf
Definition jitterbuf.c:99
void jb_reset(jitterbuf *jb)
reset jitterbuf
Definition jitterbuf.c:72
enum jb_return_code jb_get(jitterbuf *jb, jb_frame *frame, long now, long interpl)
get a frame for time now (receiver's time) return value is one of JB_OK: You've got frame!...
Definition jitterbuf.c:785
jitterbuf * jb_new(void)
new jitterbuf
Definition jitterbuf.c:86
void jb_setoutput(jb_output_function_t err, jb_output_function_t warn, jb_output_function_t dbg)
Definition jitterbuf.c:55
enum jb_return_code jb_put(jitterbuf *jb, void *data, const enum jb_frame_type type, long ms, long ts, long now)
queue a frame
Definition jitterbuf.c:525
long jb_next(jitterbuf *jb)
when is the next frame due out, in receiver's time (0=EMPTY) This value may change as frames are adde...
Definition jitterbuf.c:767
@ JB_TYPE_CONTROL
Definition jitterbuf.h:61
@ JB_TYPE_SILENCE
Definition jitterbuf.h:64
@ JB_TYPE_VOICE
Definition jitterbuf.h:62
enum jb_return_code jb_setconf(jitterbuf *jb, jb_conf *conf)
set jitterbuf conf
Definition jitterbuf.c:825
enum jb_return_code jb_getall(jitterbuf *jb, jb_frame *frameout)
unconditionally get frames from jitterbuf until empty
Definition jitterbuf.c:801
@ JB_EMPTY
Definition jitterbuf.h:52
@ JB_SCHED
Definition jitterbuf.h:56
@ JB_DROP
Definition jitterbuf.h:55
@ JB_NOFRAME
Definition jitterbuf.h:53
@ JB_INTERP
Definition jitterbuf.h:54
@ JB_OK
Definition jitterbuf.h:51
enum jb_return_code jb_getinfo(jitterbuf *jb, jb_info *stats)
get jitterbuf info: only "statistics" may be valid
Definition jitterbuf.c:815
void ast_json_unref(struct ast_json *value)
Decrease refcount on value. If refcount reaches zero, value is freed.
Definition json.c:73
struct ast_json * ast_json_pack(char const *format,...)
Helper for creating complex JSON values.
Definition json.c:612
AST_JSON_INT_T ast_json_int_t
Primarily used to cast when packing to an "I" type.
Definition json.h:87
#define AST_LIST_HEAD_INIT_NOLOCK(head)
Initializes a list head structure.
#define AST_LIST_HEAD_STATIC(name, type)
Defines a structure to be used to hold a list of specified type, statically initialized.
#define AST_LIST_HEAD_NOLOCK(name, type)
Defines a structure to be used to hold a list of specified type (with no lock).
#define AST_LIST_LAST(head)
Returns the last entry contained in a list.
#define AST_LIST_TRAVERSE(head, var, field)
Loops over (traverses) the entries in a list.
#define AST_LIST_HEAD_DESTROY(head)
Destroys a list head structure.
#define AST_LIST_INSERT_TAIL(head, elm, field)
Appends a list entry to the tail of a list.
#define AST_LIST_ENTRY(type)
Declare a forward link structure inside a list entry.
#define AST_LIST_HEAD_INIT(head)
Initializes a list head structure.
#define AST_LIST_TRAVERSE_SAFE_END
Closes a safe loop traversal block.
#define AST_LIST_INSERT_BEFORE_CURRENT(elm, field)
Inserts a list entry before the current entry during a traversal.
#define AST_LIST_LOCK(head)
Locks a list.
Definition linkedlists.h:40
#define AST_LIST_INSERT_HEAD(head, elm, field)
Inserts a list entry at the head of a list.
#define AST_LIST_REMOVE(head, elm, field)
Removes a specific entry from a list.
#define AST_LIST_TRAVERSE_SAFE_BEGIN(head, var, field)
Loops safely over (traverses) the entries in a list.
#define AST_LIST_REMOVE_CURRENT(field)
Removes the current entry from a list during a traversal.
#define AST_LIST_REMOVE_HEAD(head, field)
Removes and returns the head entry from a list.
#define AST_LIST_UNLOCK(head)
Attempts to unlock a list.
#define AST_LIST_HEAD(name, type)
Defines a structure to be used to hold a list of specified type.
struct ast_tm * ast_localtime(const struct timeval *timep, struct ast_tm *p_tm, const char *zone)
Timezone-independent version of localtime_r(3).
Definition localtime.c:1739
#define ast_cond_destroy(cond)
Definition lock.h:209
#define ast_cond_wait(cond, mutex)
Definition lock.h:212
#define AST_PTHREADT_NULL
Definition lock.h:73
#define ast_cond_init(cond, attr)
Definition lock.h:208
#define ast_cond_timedwait(cond, mutex, time)
Definition lock.h:213
#define ast_mutex_init(pmutex)
Definition lock.h:193
#define DEADLOCK_AVOIDANCE(lock)
Definition lock.h:486
#define ast_mutex_unlock(a)
Definition lock.h:197
int ast_atomic_fetchadd_int(volatile int *p, int v)
Atomically add v to *p and return the previous value of *p.
Definition lock.h:764
#define ast_mutex_trylock(a)
Definition lock.h:198
pthread_cond_t ast_cond_t
Definition lock.h:185
#define ast_mutex_destroy(a)
Definition lock.h:195
#define ast_mutex_lock(a)
Definition lock.h:196
#define AST_MUTEX_DEFINE_STATIC(mutex)
Definition lock.h:527
int ast_atomic_dec_and_test(volatile int *p)
decrement *p by 1 and return true if the variable has reached 0.
Definition lock.h:774
#define ast_cond_signal(cond)
Definition lock.h:210
static char hostname[MAXHOSTNAMELEN]
Definition logger.c:116
int errno
#define EVENT_FLAG_REPORTING
Definition manager.h:84
#define EVENT_FLAG_SYSTEM
Definition manager.h:75
#define ast_manager_register_xml(action, authority, func)
Register a manager callback using XML documentation to describe the manager.
Definition manager.h:193
void MD5Update(struct MD5Context *context, unsigned char const *buf, unsigned len)
Definition md5.c:72
void MD5Init(struct MD5Context *context)
Definition md5.c:57
void MD5Final(unsigned char digest[MD5_DIGEST_LENGTH], struct MD5Context *context)
Definition md5.c:120
@ AST_MODFLAG_LOAD_ORDER
Definition module.h:331
#define ast_module_unref(mod)
Release a reference to the module.
Definition module.h:483
#define ast_module_ref(mod)
Hold a reference to the module.
Definition module.h:457
#define AST_MODULE_INFO(keystr, flags_to_set, desc, fields...)
Definition module.h:557
@ AST_MODPRI_CHANNEL_DRIVER
Definition module.h:341
@ AST_MODULE_SUPPORT_CORE
Definition module.h:121
#define ASTERISK_GPL_KEY
The text the key() function should return.
Definition module.h:46
int ast_unregister_application(const char *app)
Unregister an application.
Definition pbx_app.c:404
@ AST_MODULE_LOAD_SUCCESS
Definition module.h:70
@ AST_MODULE_LOAD_DECLINE
Module has failed to load, may be in an inconsistent state.
Definition module.h:78
#define ast_register_application_xml(app, execute)
Register an application using XML documentation.
Definition module.h:640
int ast_moh_start(struct ast_channel *chan, const char *mclass, const char *interpclass)
Turn on music on hold on a given channel.
Definition channel.c:7802
void ast_moh_stop(struct ast_channel *chan)
Turn off music on hold on a given channel.
Definition channel.c:7812
struct stasis_message_type * ast_mwi_state_type(void)
Get the Stasis Message Bus API message type for MWI messages.
void * ast_mwi_unsubscribe(struct ast_mwi_subscriber *sub)
Unsubscribe from the stasis topic and MWI.
Definition mwi.c:254
struct stasis_cache * ast_mwi_state_cache(void)
Backend cache for ast_mwi_topic_cached().
Definition mwi.c:94
struct ast_mwi_subscriber * ast_mwi_subscribe_pool(const char *mailbox, stasis_subscription_cb callback, void *data)
Add an MWI state subscriber, and stasis subscription to the mailbox.
Definition mwi.c:235
meta
below block is needed for mssql
Definition env.py:22
static char * ast_sockaddr_stringify(const struct ast_sockaddr *addr)
Wrapper around ast_sockaddr_stringify_fmt() with default format.
Definition netsock2.h:256
#define ast_sockaddr_port(addr)
Get the port number of a socket address.
Definition netsock2.h:517
static void ast_sockaddr_copy(struct ast_sockaddr *dst, const struct ast_sockaddr *src)
Copies the data from one ast_sockaddr to another.
Definition netsock2.h:167
int ast_sockaddr_is_ipv6(const struct ast_sockaddr *addr)
Determine if this is an IPv6 address.
Definition netsock2.c:524
int ast_bind(int sockfd, const struct ast_sockaddr *addr)
Wrapper around bind(2) that uses struct ast_sockaddr.
Definition netsock2.c:590
int ast_sockaddr_apply_netmask(const struct ast_sockaddr *addr, const struct ast_sockaddr *netmask, struct ast_sockaddr *result)
Apply a netmask to an address and store the result in a separate structure.
Definition netsock2.c:357
@ AST_AF_UNSPEC
Definition netsock2.h:54
int ast_sockaddr_cmp_addr(const struct ast_sockaddr *a, const struct ast_sockaddr *b)
Compares the addresses of two ast_sockaddr structures.
Definition netsock2.c:413
ssize_t ast_sendto(int sockfd, const void *buf, size_t len, int flags, const struct ast_sockaddr *dest_addr)
Wrapper around sendto(2) that uses ast_sockaddr.
Definition netsock2.c:614
int ast_sockaddr_split_hostport(char *str, char **host, char **port, int flags)
Splits a string into its host and port components.
Definition netsock2.c:164
int ast_sockaddr_resolve(struct ast_sockaddr **addrs, const char *str, int flags, int family)
Parses a string with an IPv4 or IPv6 address and place results into an array.
Definition netsock2.c:280
int ast_sockaddr_parse(struct ast_sockaddr *addr, const char *str, int flags)
Parse an IPv4 or IPv6 address string.
Definition netsock2.c:230
static int ast_sockaddr_isnull(const struct ast_sockaddr *addr)
Checks if the ast_sockaddr is null. "null" in this sense essentially means uninitialized,...
Definition netsock2.h:127
ssize_t ast_recvfrom(int sockfd, void *buf, size_t len, int flags, struct ast_sockaddr *src_addr)
Wrapper around recvfrom(2) that uses struct ast_sockaddr.
Definition netsock2.c:606
int ast_sockaddr_cmp(const struct ast_sockaddr *a, const struct ast_sockaddr *b)
Compares two ast_sockaddr structures.
Definition netsock2.c:388
static char * ast_sockaddr_stringify_port(const struct ast_sockaddr *addr)
Wrapper around ast_sockaddr_stringify_fmt() to return a port only.
Definition netsock2.h:358
#define ast_sockaddr_set_port(addr, port)
Sets the port number of a socket address.
Definition netsock2.h:532
static char * ast_sockaddr_stringify_addr(const struct ast_sockaddr *addr)
Wrapper around ast_sockaddr_stringify_fmt() to return an address only.
Definition netsock2.h:286
static void ast_sockaddr_setnull(struct ast_sockaddr *addr)
Sets address addr to null.
Definition netsock2.h:138
int ast_sockaddr_is_ipv4_mapped(const struct ast_sockaddr *addr)
Determine if this is an IPv4-mapped IPv6 address.
Definition netsock2.c:507
int ast_sockaddr_hash(const struct ast_sockaddr *addr)
Computes a hash value from the address. The port is ignored.
Definition netsock2.c:548
int ast_netsock_release(struct ast_netsock_list *list)
Definition netsock.c:85
struct ast_netsock_list * ast_netsock_list_alloc(void)
Definition netsock.c:72
struct ast_netsock * ast_netsock_bind(struct ast_netsock_list *list, struct io_context *ioc, const char *bindinfo, int defaultport, int tos, int cos, ast_io_cb callback, void *data)
Definition netsock.c:167
void ast_netsock_unref(struct ast_netsock *ns)
Definition netsock.c:198
int ast_netsock_sockfd(const struct ast_netsock *ns)
Definition netsock.c:183
struct ast_netsock * ast_netsock_find(struct ast_netsock_list *list, struct ast_sockaddr *addr)
Definition netsock.c:94
int ast_netsock_init(struct ast_netsock_list *list)
Definition netsock.c:77
struct ast_netsock * ast_netsock_bindaddr(struct ast_netsock_list *list, struct io_context *ioc, struct ast_sockaddr *bindaddr, int tos, int cos, ast_io_cb callback, void *data)
Definition netsock.c:109
const char * ast_inet_ntoa(struct in_addr ia)
thread-safe replacement for inet_ntoa().
Definition utils.c:962
int iax_parse_ies(struct iax_ies *ies, unsigned char *data, int datalen)
Definition parser.c:795
int iax_get_iframes(void)
Definition parser.c:1354
#define DIRECTION_OUTGRESS
Definition parser.h:89
int iax_ie_append_addr(struct iax_ie_data *ied, unsigned char ie, const struct ast_sockaddr *addr)
Definition parser.c:741
void iax_frame_subclass2str(enum iax_frame_subclass subclass, char *str, size_t len)
Definition parser.c:463
int iax_ie_append_byte(struct iax_ie_data *ied, unsigned char ie, unsigned char dat)
Definition parser.c:775
void iax_frame_free(struct iax_frame *fr)
Definition parser.c:1299
int iax_ie_append(struct iax_ie_data *ied, unsigned char ie)
Definition parser.c:780
int iax_ie_append_versioned_uint64(struct iax_ie_data *ied, unsigned char ie, unsigned char version, uint64_t value)
Definition parser.c:746
struct iax_frame * iax_frame_new(int direction, int datalen, unsigned int cacheable)
Definition parser.c:1230
int iax_ie_append_raw(struct iax_ie_data *ied, unsigned char ie, const void *data, int datalen)
Definition parser.c:726
int iax_ie_append_int(struct iax_ie_data *ied, unsigned char ie, unsigned int value)
Definition parser.c:756
void iax_set_output(void(*output)(const char *data))
int iax_get_oframes(void)
Definition parser.c:1355
#define DIRECTION_INGRESS
Definition parser.h:88
void iax_frame_wrap(struct iax_frame *fr, struct ast_frame *f)
Definition parser.c:1196
int iax_ie_append_short(struct iax_ie_data *ied, unsigned char ie, unsigned short value)
Definition parser.c:763
void iax_showframe(struct iax_frame *f, struct ast_iax2_full_hdr *fhi, int rx, struct ast_sockaddr *addr, int datalen)
Definition parser.c:595
int iax_ie_append_str(struct iax_ie_data *ied, unsigned char ie, const char *str)
Definition parser.c:770
int iax_get_frames(void)
Definition parser.c:1353
void iax_set_error(void(*output)(const char *data))
const char * ast_config_AST_SYSTEM_NAME
Definition options.c:171
static int totalcalls
Definition pbx.c:794
int ast_add_extension(const char *context, int replace, const char *extension, int priority, const char *label, const char *callerid, const char *application, void *data, void(*datad)(void *), const char *registrar)
Add and extension to an extension context.
Definition pbx.c:6968
int ast_context_destroy_by_name(const char *context, const char *registrar)
Destroy a context by name.
Definition pbx.c:8249
void ast_unregister_switch(struct ast_switch *sw)
Unregister an alternative switch.
Definition pbx_switch.c:76
int ast_register_switch(struct ast_switch *sw)
Register an alternative dialplan switch.
Definition pbx_switch.c:58
const char * pbx_builtin_getvar_helper(struct ast_channel *chan, const char *name)
Return a pointer to the value of the corresponding channel variable.
int ast_exists_extension(struct ast_channel *c, const char *context, const char *exten, int priority, const char *callerid)
Determine whether an extension exists.
Definition pbx.c:4211
struct ast_context * ast_context_find_or_create(struct ast_context **extcontexts, struct ast_hashtab *exttable, const char *name, const char *registrar)
Register a new context or find an existing one.
Definition pbx.c:6185
int pbx_exec(struct ast_channel *c, struct ast_app *app, const char *data)
Execute an application.
Definition pbx_app.c:483
int pbx_builtin_setvar_helper(struct ast_channel *chan, const char *name, const char *value)
Add a variable to the channel variable stack, removing the most recently set value for the same name.
int ast_context_remove_extension(const char *context, const char *extension, int priority, const char *registrar)
Simply remove extension from context.
Definition pbx.c:4984
#define ast_custom_function_register(acf)
Register a custom function.
Definition pbx.h:1563
int ast_canmatch_extension(struct ast_channel *c, const char *context, const char *exten, int priority, const char *callerid)
Looks for a valid matching extension.
Definition pbx.c:4226
int ast_custom_function_unregister(struct ast_custom_function *acf)
Unregister a custom function.
enum ast_pbx_result ast_pbx_start(struct ast_channel *c)
Create a new thread and start the PBX.
Definition pbx.c:4744
int ast_ignore_pattern(const char *context, const char *pattern)
Checks to see if a number should be ignored.
Definition pbx.c:6919
int ast_matchmore_extension(struct ast_channel *c, const char *context, const char *exten, int priority, const char *callerid)
Looks to see if adding anything to this extension might match something. (exists ^ canmatch)
Definition pbx.c:4231
struct ast_app * pbx_findapp(const char *app)
Look up an application.
Definition ael_main.c:165
static int netsocket
Definition pbx_dundi.c:195
static int matchmore(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
Definition pbx_lua.c:1386
#define ast_poll(a, b, c)
Definition poll-compat.h:88
int iax_provision_reload(int reload)
Definition provision.c:526
int iax_provision_build(struct iax_ie_data *provdata, unsigned int *signature, const char *template, int force)
Definition provision.c:209
int iax_provision_unload(void)
Definition provision.c:517
char * iax_prov_complete_template(const char *line, const char *word, int pos, int state)
Definition provision.c:179
int iax_provision_version(unsigned int *signature, const char *template, int force)
Definition provision.c:258
static int total
Definition res_adsi.c:970
static struct stasis_subscription * sub
Statsd channel stats. Exmaple of how to subscribe to Stasis events.
static struct @487 methods[]
static void challenge(const char *endpoint_id, struct ast_sip_auth *auth, pjsip_tx_data *tdata, const pjsip_rx_data *rdata, int is_stale, const pjsip_auth_algorithm *algorithm)
Send a WWW-Authenticate challenge.
static void cleanup(void)
Clean up any old apps that we don't need any more.
Definition res_stasis.c:327
static struct @523 args
unsigned int refresh
#define NULL
Definition resample.c:96
#define AST_SCHED_DEL(sched, id)
Remove a scheduler entry.
Definition sched.h:46
void ast_sched_clean_by_callback(struct ast_sched_context *con, ast_sched_cb match, ast_sched_cb cleanup_cb)
Clean all scheduled events with matching callback.
Definition sched.c:409
int ast_sched_replace(int old_id, struct ast_sched_context *con, int when, ast_sched_cb callback, const void *data) attribute_warn_unused_result
replace a scheduler entry
Definition sched.c:559
int ast_sched_add(struct ast_sched_context *con, int when, ast_sched_cb callback, const void *data) attribute_warn_unused_result
Adds a scheduled event.
Definition sched.c:567
void ast_sched_context_destroy(struct ast_sched_context *c)
destroys a schedule context
Definition sched.c:271
int ast_sched_start_thread(struct ast_sched_context *con)
Start a thread for processing scheduler entries.
Definition sched.c:197
int(* ast_sched_cb)(const void *data)
scheduler callback
Definition sched.h:178
struct ast_sched_context * ast_sched_context_create(void)
Create a scheduler context.
Definition sched.c:238
struct stasis_topic * ast_security_topic(void)
A stasis_topic which publishes messages for security related issues.
@ STASIS_SUBSCRIPTION_FILTER_SELECTIVE
Definition stasis.h:297
int stasis_subscription_accept_message_type(struct stasis_subscription *subscription, const struct stasis_message_type *type)
Indicate to a subscription that we are interested in a message type.
Definition stasis.c:1090
int stasis_subscription_set_filter(struct stasis_subscription *subscription, enum stasis_subscription_message_filter filter)
Set the message type filtering level on a subscription.
Definition stasis.c:1144
void stasis_subscription_cb_noop(void *data, struct stasis_subscription *sub, struct stasis_message *message)
Stasis subscription callback function that does nothing.
Definition stasis.c:876
void * stasis_message_data(const struct stasis_message *msg)
Get the data contained in a message.
struct stasis_subscription * stasis_unsubscribe_and_join(struct stasis_subscription *subscription)
Cancel a subscription, blocking until the last message is processed.
Definition stasis.c:1201
struct stasis_message * stasis_cache_get(struct stasis_cache *cache, struct stasis_message_type *type, const char *id)
Retrieve an item from the cache for the ast_eid_default entity.
#define stasis_subscribe(topic, callback, data)
Definition stasis.h:649
void ast_system_publish_registry(const char *channeltype, const char *username, const char *domain, const char *status, const char *cause)
Publish a channel driver outgoing registration message.
struct stasis_topic * ast_system_topic(void)
A Stasis Message Bus API topic which publishes messages regarding system changes.
struct stasis_message_type * ast_network_change_type(void)
A stasis_message_type for network changes.
#define AST_DECLARE_STRING_FIELDS(field_list)
Declare the fields needed in a structure.
#define AST_STRING_FIELD(name)
Declare a string field.
#define ast_string_field_set(x, field, data)
Set a field to a simple string value.
#define ast_string_field_init(x, size)
Initialize a field pool and fields.
#define ast_string_field_build(x, field, fmt, args...)
Set a field to a complex (built) value.
#define ast_string_field_free_memory(x)
free all memory - to be called before destroying the object
int ast_str_append(struct ast_str **buf, ssize_t max_len, const char *fmt,...)
Append to a thread local dynamic string.
Definition strings.h:1139
size_t attribute_pure ast_str_strlen(const struct ast_str *buf)
Returns the current length of the string stored within buf.
Definition strings.h:730
#define S_OR(a, b)
returns the equivalent of logic or for strings: first one if not empty, otherwise second one.
Definition strings.h:80
static force_inline int attribute_pure ast_str_hash(const char *str)
Compute a hash value on a string.
Definition strings.h:1259
int attribute_pure ast_true(const char *val)
Make sure something is true. Determine if a string containing a boolean value is "true"....
Definition utils.c:2233
#define S_COR(a, b, c)
returns the equivalent of logic or for strings, with an additional boolean check: second one if not e...
Definition strings.h:87
int ast_get_time_t(const char *src, time_t *dst, time_t _default, int *consumed)
Parse a time (integer) string.
Definition utils.c:2480
static force_inline int attribute_pure ast_strlen_zero(const char *s)
Definition strings.h:65
int attribute_pure ast_false(const char *val)
Make sure something is false. Determine if a string containing a boolean value is "false"....
Definition utils.c:2250
#define ast_str_alloca(init_len)
Definition strings.h:848
char * ast_strip_quoted(char *s, const char *beg_quotes, const char *end_quotes)
Strip leading/trailing whitespace and quotes from a string.
Definition utils.c:1852
int ast_str_set(struct ast_str **buf, ssize_t max_len, const char *fmt,...)
Set a dynamic string using variable arguments.
Definition strings.h:1113
char *attribute_pure ast_str_buffer(const struct ast_str *buf)
Returns the string buffer within the ast_str buf.
Definition strings.h:761
void ast_copy_string(char *dst, const char *src, size_t size)
Size-limited null-terminating string copy.
Definition strings.h:425
struct ast_ha ha
Definition chan_iax2.c:1080
unsigned char delme
Definition chan_iax2.c:1084
uint16_t limit
Definition chan_iax2.c:1082
unsigned char raw[AST_CRYPTO_AES_BLOCKSIZE/8]
Definition crypto.h:40
Generic container type.
When we need to walk through a container, we use an ao2_iterator to keep track of the current positio...
Definition astobj2.h:1821
Wrapper for an ast_acl linked list.
Definition acl.h:76
ast_app: A registered application
Definition pbx_app.c:45
Structure to pass both assignedid values to channel drivers.
Definition channel.h:606
Structure to describe a channel "technology", ie a channel driver See for examples:
Definition channel.h:648
struct ast_format_cap * capabilities
Definition channel.h:652
const char *const type
Definition channel.h:649
Main Channel structure associated with a channel.
const char * data
char context[AST_MAX_CONTEXT]
descriptor for a cli entry.
Definition cli.h:171
int args
This gets set in ast_cli_register()
Definition cli.h:185
char * command
Definition cli.h:186
const char * usage
Definition cli.h:177
Data structure associated with a custom dialplan function.
Definition pbx.h:118
const char * name
Definition pbx.h:119
Structure for a data store type.
Definition datastore.h:31
const char * type
Definition datastore.h:32
Structure for a data store object.
Definition datastore.h:64
void * data
Definition datastore.h:66
unsigned int inheritance
Definition datastore.h:69
Definition dnsmgr.c:66
Structure used to handle a large number of boolean flags == used only in app_dial?
Definition utils.h:225
Structure used to handle boolean flags.
Definition utils.h:220
Format capabilities structure, holds formats + preference order + etc.
Definition format_cap.c:54
Definition of a media format.
Definition format.c:43
struct ast_format * format
Data structure associated with a single frame of data.
union ast_frame::@236 data
struct ast_frame_subclass subclass
struct timeval delivery
enum ast_frame_type frametype
struct ast_frame * next
internal representation of ACL entries In principle user applications would have no need for this,...
Definition acl.h:51
struct ast_sockaddr addr
Definition acl.h:53
struct ast_sockaddr netmask
Definition acl.h:54
unsigned char encdata[0]
Definition iax2.h:245
unsigned short dcallno
Definition iax2.h:232
unsigned short scallno
Definition iax2.h:231
unsigned int ts
Definition iax2.h:233
unsigned char iseqno
Definition iax2.h:235
unsigned char csub
Definition iax2.h:237
unsigned char oseqno
Definition iax2.h:234
unsigned char type
Definition iax2.h:236
Definition iax2.h:282
unsigned short callno
Definition iax2.h:283
unsigned short len
Definition iax2.h:284
unsigned int ts
Definition iax2.h:278
unsigned char data[0]
Definition iax2.h:279
unsigned short len
Definition iax2.h:289
struct ast_iax2_mini_hdr mini
Definition iax2.h:290
unsigned short callno
Definition iax2.h:259
unsigned char encdata[0]
Definition iax2.h:260
unsigned short callno
Definition iax2.h:250
unsigned short ts
Definition iax2.h:251
unsigned short zeros
Definition iax2.h:271
unsigned short callno
Definition iax2.h:272
unsigned short ts
Definition iax2.h:273
Abstract JSON element (object, array, string, int, ...).
struct ast_module * self
Definition module.h:356
Structure for mutex and tracking information.
Definition lock.h:142
The structure that contains MWI state.
Definition mwi.h:455
int old_msgs
Definition mwi.h:460
int new_msgs
Definition mwi.h:459
int sockfd
Definition netsock.c:54
struct ast_party_id id
Caller party ID.
Definition channel.h:422
int ani2
Automatic Number Identification 2 (Info Digits)
Definition channel.h:435
struct ast_party_id ani
Automatic Number Identification (ANI)
Definition channel.h:429
Connected Line/Party information.
Definition channel.h:458
struct ast_party_id id
Connected party ID.
Definition channel.h:460
struct ast_party_dialed::@218 number
Dialed/Called number.
char * str
Subscriber phone number (Malloced)
Definition channel.h:388
int transit_network_select
Transit Network Select.
Definition channel.h:399
struct ast_party_name name
Subscriber name.
Definition channel.h:342
struct ast_party_number number
Subscriber phone number.
Definition channel.h:344
int presentation
Q.931 encoded presentation-indicator encoded field.
Definition channel.h:279
unsigned char valid
TRUE if the name information is valid/present.
Definition channel.h:281
char * str
Subscriber name (Malloced)
Definition channel.h:266
int presentation
Q.931 presentation-indicator and screening-indicator encoded fields.
Definition channel.h:297
unsigned char valid
TRUE if the number information is valid/present.
Definition channel.h:299
char * str
Subscriber phone number (Malloced)
Definition channel.h:293
int plan
Q.931 Type-Of-Number and Numbering-Plan encoded fields.
Definition channel.h:295
struct ast_party_id from
Who is redirecting the call (Sent to the party the call is redirected toward)
Definition channel.h:529
Socket address structure.
Definition netsock2.h:97
struct sockaddr_storage ss
Definition netsock2.h:98
Support for dynamic strings.
Definition strings.h:623
const char * name
Definition pbx.h:164
A ast_taskprocessor structure is a singleton by name.
struct ast_var_t::@221 entries
Structure for variables, used for configurations and for channel variables.
struct ast_variable * next
callno_entry numbers[IAX_MAX_CALLS/2+1]
Definition chan_iax2.c:998
unsigned char semirand[32]
Definition chan_iax2.c:918
const ast_string_field mohinterpret
Definition chan_iax2.c:899
int first_iax_message
Definition chan_iax2.c:803
struct ast_sockaddr addr
Definition chan_iax2.c:813
struct ast_variable * vars
Definition chan_iax2.c:957
const ast_string_field language
Definition chan_iax2.c:899
int frames_received
Definition chan_iax2.c:967
const ast_string_field cid_num
Definition chan_iax2.c:899
struct chan_iax2_pvt::signaling_queue signaling_queue
iax2_format svideoformat
Definition chan_iax2.c:791
unsigned int lastsent
Definition chan_iax2.c:797
const ast_string_field inkeys
Definition chan_iax2.c:899
const ast_string_field outkey
Definition chan_iax2.c:899
unsigned int nextpred
Definition chan_iax2.c:801
iax2_format capability
Definition chan_iax2.c:793
int destroy_initiated
Definition chan_iax2.c:969
unsigned int pingtime
Definition chan_iax2.c:809
const ast_string_field dproot
Definition chan_iax2.c:899
const ast_string_field mohsuggest
Definition chan_iax2.c:899
unsigned short bridgecallno
Definition chan_iax2.c:942
const ast_string_field accountcode
Definition chan_iax2.c:899
const ast_string_field username
Definition chan_iax2.c:899
iax2_format peercapability
Definition chan_iax2.c:832
struct ast_variable * iaxvars
Definition chan_iax2.c:959
struct ast_flags state
Definition chan_iax2.c:848
unsigned int notsilenttx
Definition chan_iax2.c:807
unsigned int lastvsent
Definition chan_iax2.c:799
ast_callid callid
Definition chan_iax2.c:783
unsigned char iseqno
Definition chan_iax2.c:856
char hold_signaling
Definition chan_iax2.c:973
struct timeval rxcore
Definition chan_iax2.c:836
struct ast_sockaddr transfer
Definition chan_iax2.c:932
iax2_format voiceformat
Definition chan_iax2.c:785
const ast_string_field context
Definition chan_iax2.c:899
unsigned short peercallno
Definition chan_iax2.c:823
struct iax2_codec_pref prefs
Definition chan_iax2.c:815
unsigned short callno
Definition chan_iax2.c:819
unsigned char calltoken_ie_len
Definition chan_iax2.c:971
const ast_string_field parkinglot
Definition chan_iax2.c:899
iax2_format videoformat
Definition chan_iax2.c:787
unsigned char rseqno
Definition chan_iax2.c:854
const ast_string_field host
Definition chan_iax2.c:899
callno_entry callno_entry
Definition chan_iax2.c:821
uint64_t flags
Definition chan_iax2.c:924
unsigned short transfercallno
Definition chan_iax2.c:934
struct ast_channel * owner
Definition chan_iax2.c:846
const ast_string_field rdnis
Definition chan_iax2.c:899
unsigned char oseqno
Definition chan_iax2.c:852
struct timeval offset
Definition chan_iax2.c:834
unsigned char aseqno
Definition chan_iax2.c:858
iax2_format svoiceformat
Definition chan_iax2.c:789
const ast_string_field challenge
Definition chan_iax2.c:899
const ast_string_field exten
Definition chan_iax2.c:899
ast_aes_decrypt_key dcx
Definition chan_iax2.c:913
struct iax_rr remote_rr
Definition chan_iax2.c:961
unsigned int last
Definition chan_iax2.c:795
ast_aes_encrypt_key tdcx
Definition chan_iax2.c:936
const ast_string_field ani
Definition chan_iax2.c:899
iax2_format peerformat
Definition chan_iax2.c:830
struct iax2_codec_pref rprefs
Definition chan_iax2.c:817
jitterbuf * jb
Definition chan_iax2.c:838
struct iax2_registry * reg
Definition chan_iax2.c:920
ast_aes_decrypt_key mydcx
Definition chan_iax2.c:911
const ast_string_field cid_name
Definition chan_iax2.c:899
enum iax_transfer_state transferring
Definition chan_iax2.c:928
int last_iax_message
Definition chan_iax2.c:805
int eff_auth_method
Definition chan_iax2.c:905
const ast_string_field secret
Definition chan_iax2.c:899
ast_aes_encrypt_key ecx
Definition chan_iax2.c:909
const ast_string_field dnid
Definition chan_iax2.c:899
const ast_string_field osptoken
Definition chan_iax2.c:899
struct iax2_peer * peerpoke
Definition chan_iax2.c:922
const ast_string_field peer
Definition chan_iax2.c:899
iax2_format chosenformat
Definition chan_iax2.c:828
struct chan_iax2_pvt::@124 dpentries
iax2_format capability
Definition chan_iax2.c:4698
char username[80]
Definition chan_iax2.c:4707
struct iax2_codec_pref prefs
Definition chan_iax2.c:4700
char timezone[80]
Definition chan_iax2.c:4710
char cid_name[80]
Definition chan_iax2.c:4712
char context[AST_MAX_CONTEXT]
Definition chan_iax2.c:4713
char peercontext[AST_MAX_CONTEXT]
Definition chan_iax2.c:4714
char mohsuggest[MAX_MUSICCLASS]
Definition chan_iax2.c:4716
char mohinterpret[MAX_MUSICCLASS]
Definition chan_iax2.c:4715
char context[AST_MAX_EXTENSION]
Definition chan_iax2.c:9728
char callednum[AST_MAX_EXTENSION]
Definition chan_iax2.c:9729
char * callerid
Definition chan_iax2.c:9730
Definition file.c:70
char order[IAX2_CODEC_PREF_SIZE]
Definition codec_pref.h:36
char context[AST_MAX_CONTEXT]
Definition chan_iax2.c:530
struct iax2_context * next
Definition chan_iax2.c:531
int waiters[256]
Definition chan_iax2.c:1113
struct iax2_dpcache::@127 peer_list
struct timeval expiry
Definition chan_iax2.c:1110
char exten[AST_MAX_EXTENSION]
Definition chan_iax2.c:1108
unsigned short callno
Definition chan_iax2.c:1112
struct timeval orig
Definition chan_iax2.c:1109
struct iax2_dpcache::@126 cache_list
char peercontext[AST_MAX_CONTEXT]
Definition chan_iax2.c:1107
const ast_string_field peercontext
Definition chan_iax2.c:636
const ast_string_field mohinterpret
Definition chan_iax2.c:636
int pokefreqok
Definition chan_iax2.c:661
struct ast_sockaddr addr
Definition chan_iax2.c:639
struct ast_dnsmgr_entry * dnsmgr
Definition chan_iax2.c:638
const ast_string_field cid_num
Definition chan_iax2.c:636
const ast_string_field inkeys
Definition chan_iax2.c:636
const ast_string_field outkey
Definition chan_iax2.c:636
struct ast_mwi_subscriber * mwi_event_sub
Definition chan_iax2.c:667
enum calltoken_peer_enum calltoken_required
Definition chan_iax2.c:670
iax2_format capability
Definition chan_iax2.c:653
int pokefreqnotok
Definition chan_iax2.c:662
int historicms
Definition chan_iax2.c:663
int authmethods
Definition chan_iax2.c:648
const ast_string_field regexten
Definition chan_iax2.c:636
const ast_string_field mohsuggest
Definition chan_iax2.c:636
const ast_string_field username
Definition chan_iax2.c:636
const ast_string_field zonetag
Definition chan_iax2.c:636
struct ast_sockaddr defaddr
Definition chan_iax2.c:647
uint16_t maxcallno
Definition chan_iax2.c:665
const ast_string_field description
Definition chan_iax2.c:636
const ast_string_field context
Definition chan_iax2.c:636
struct iax2_codec_pref prefs
Definition chan_iax2.c:637
const ast_string_field parkinglot
Definition chan_iax2.c:636
uint64_t flags
Definition chan_iax2.c:644
const ast_string_field dbsecret
Definition chan_iax2.c:636
struct ast_sockaddr mask
Definition chan_iax2.c:642
int encmethods
Definition chan_iax2.c:649
struct ast_endpoint * endpoint
Definition chan_iax2.c:672
int pokeexpire
Definition chan_iax2.c:657
int formats
Definition chan_iax2.c:640
struct ast_acl_list * acl
Definition chan_iax2.c:669
const ast_string_field name
Definition chan_iax2.c:636
const ast_string_field cid_name
Definition chan_iax2.c:636
int smoothing
Definition chan_iax2.c:664
const ast_string_field secret
Definition chan_iax2.c:636
const ast_string_field mailbox
Definition chan_iax2.c:636
unsigned char buf[1]
Definition chan_iax2.c:1143
struct iax2_pkt_buf::@128 entry
struct ast_sockaddr addr
Definition chan_iax2.c:723
struct ast_dnsmgr_entry * dnsmgr
Definition chan_iax2.c:732
char hostname[]
Definition chan_iax2.c:735
enum iax_reg_state regstate
Definition chan_iax2.c:728
struct iax2_registry::@123 entry
char username[80]
Definition chan_iax2.c:724
char secret[80]
Definition chan_iax2.c:725
struct ast_sockaddr us
Definition chan_iax2.c:731
struct ast_sockaddr addr
Definition chan_iax2.c:1177
unsigned char readbuf[4096]
Definition chan_iax2.c:1161
ast_cond_t cond
Definition chan_iax2.c:1168
ast_cond_t init_cond
Definition chan_iax2.c:1170
time_t checktime
Definition chan_iax2.c:1166
struct iax2_thread::@130 ffinfo
unsigned char stop
Definition chan_iax2.c:1185
unsigned char csub
Definition chan_iax2.c:1179
pthread_t threadid
Definition chan_iax2.c:1158
unsigned short callno
Definition chan_iax2.c:1176
struct ast_sockaddr ioaddr
Definition chan_iax2.c:1160
ast_mutex_t init_lock
Definition chan_iax2.c:1169
struct iax2_thread::@129 list
struct iax2_thread::@131 full_frames
unsigned char * buf
Definition chan_iax2.c:1162
enum iax2_thread_iostate iostate
Definition chan_iax2.c:1149
ast_mutex_t lock
Definition chan_iax2.c:1167
const void * scheddata
Definition chan_iax2.c:1152
size_t buf_size
Definition chan_iax2.c:1164
enum iax2_thread_type type
Definition chan_iax2.c:1148
void(* schedfunc)(const void *)
Definition chan_iax2.c:1151
char curfunc[80]
Definition chan_iax2.c:1155
ssize_t buf_len
Definition chan_iax2.c:1163
struct ast_sockaddr addr
Definition chan_iax2.c:680
struct timeval lasttxtime
Definition chan_iax2.c:683
unsigned int lastsent
Definition chan_iax2.c:685
struct timeval rxtrunktime
Definition chan_iax2.c:682
struct iax2_trunk_peer::@122 list
unsigned int trunkdataalloc
Definition chan_iax2.c:689
unsigned int trunkdatalen
Definition chan_iax2.c:688
unsigned char * trunkdata
Definition chan_iax2.c:687
struct timeval trunkact
Definition chan_iax2.c:684
ast_mutex_t lock
Definition chan_iax2.c:678
struct timeval txtrunktime
Definition chan_iax2.c:681
const ast_string_field mohinterpret
Definition chan_iax2.c:598
struct ast_variable * vars
Definition chan_iax2.c:611
const ast_string_field language
Definition chan_iax2.c:598
const ast_string_field cid_num
Definition chan_iax2.c:598
const ast_string_field inkeys
Definition chan_iax2.c:598
struct iax2_context * contexts
Definition chan_iax2.c:610
enum calltoken_peer_enum calltoken_required
Definition chan_iax2.c:612
iax2_format capability
Definition chan_iax2.c:605
int authmethods
Definition chan_iax2.c:600
const ast_string_field mohsuggest
Definition chan_iax2.c:598
const ast_string_field accountcode
Definition chan_iax2.c:598
struct iax2_codec_pref prefs
Definition chan_iax2.c:608
const ast_string_field parkinglot
Definition chan_iax2.c:598
uint64_t flags
Definition chan_iax2.c:604
const ast_string_field dbsecret
Definition chan_iax2.c:598
int encmethods
Definition chan_iax2.c:601
int maxauthreq
Definition chan_iax2.c:606
int curauthreq
Definition chan_iax2.c:607
struct ast_acl_list * acl
Definition chan_iax2.c:609
const ast_string_field name
Definition chan_iax2.c:598
const ast_string_field cid_name
Definition chan_iax2.c:598
int amaflags
Definition chan_iax2.c:602
const ast_string_field secret
Definition chan_iax2.c:598
unsigned char semirand[32]
Definition parser.h:138
unsigned short dcallno
Definition parser.h:102
struct iax_frame::@144 list
unsigned int final
Definition parser.h:120
unsigned int sentyet
Definition parser.h:116
int retrans
Definition parser.h:130
unsigned int ts
Definition parser.h:110
unsigned char afdata[0]
Definition parser.h:146
unsigned int outoforder
Definition parser.h:114
void * data
Definition parser.h:104
unsigned short callno
Definition parser.h:100
int retries
Definition parser.h:108
int encmethods
Definition parser.h:132
int iseqno
Definition parser.h:128
size_t afdatalen
Definition parser.h:144
unsigned int direction
Definition parser.h:122
ast_aes_decrypt_key mydcx
Definition parser.h:136
struct iax_frame * next
Definition parser.h:140
int datalen
Definition parser.h:106
int retrytime
Definition parser.h:112
unsigned int transfer
Definition parser.h:118
ast_aes_encrypt_key ecx
Definition parser.h:134
struct ast_frame af
Definition parser.h:142
unsigned int cacheable
Definition parser.h:124
int oseqno
Definition parser.h:126
unsigned char buf[1024]
Definition parser.h:150
struct ast_sockaddr apparent_addr
Definition parser.h:52
unsigned short adsicpe
Definition parser.h:44
unsigned int rr_jitter
Definition parser.h:75
unsigned int provver
Definition parser.h:72
unsigned char * calltokendata
Definition parser.h:85
unsigned int rr_pkts
Definition parser.h:77
struct ast_variable * vars
Definition parser.h:81
unsigned char calltoken
Definition parser.h:84
unsigned char iax_unknown
Definition parser.h:58
int calling_ani2
Definition parser.h:35
unsigned int rr_loss
Definition parser.h:76
unsigned int authmethods
Definition parser.h:47
char * challenge
Definition parser.h:49
char * dnid
Definition parser.h:45
char * calling_name
Definition parser.h:31
iax2_format capability
Definition parser.h:39
char * called_context
Definition parser.h:36
char * calling_number
Definition parser.h:29
unsigned int fwdesc
Definition parser.h:67
char * calling_ani
Definition parser.h:30
int calling_ton
Definition parser.h:32
char * password
Definition parser.h:38
unsigned int transferid
Definition parser.h:62
unsigned int rr_dropped
Definition parser.h:79
unsigned char causecode
Definition parser.h:57
unsigned int ospblocklength[IAX_MAX_OSPBLOCK_NUM]
Definition parser.h:83
int msgcount
Definition parser.h:59
int calling_tns
Definition parser.h:33
char * called_number
Definition parser.h:28
unsigned short callno
Definition parser.h:55
char * md5_result
Definition parser.h:50
int provverpres
Definition parser.h:74
char * language
Definition parser.h:42
char * codec_prefs
Definition parser.h:41
iax2_format format
Definition parser.h:40
unsigned int encmethods
Definition parser.h:48
unsigned short dpstatus
Definition parser.h:54
char * username
Definition parser.h:37
char * rsa_result
Definition parser.h:51
int calling_pres
Definition parser.h:34
int version
Definition parser.h:43
char * cause
Definition parser.h:56
int musiconhold
Definition parser.h:61
unsigned short refresh
Definition parser.h:53
char * serviceident
Definition parser.h:65
unsigned int rr_ooo
Definition parser.h:80
char * devicetype
Definition parser.h:64
char * rdnis
Definition parser.h:46
unsigned short rr_delay
Definition parser.h:78
char * osptokenblock[IAX_MAX_OSPBLOCK_NUM]
Definition parser.h:82
int ooo
Definition chan_iax2.c:770
int losscnt
Definition chan_iax2.c:766
int delay
Definition chan_iax2.c:768
int losspct
Definition chan_iax2.c:765
int dropped
Definition chan_iax2.c:769
int jitter
Definition chan_iax2.c:764
int packets
Definition chan_iax2.c:767
Global IO variables are now in a struct in order to be made threadsafe.
Definition io.c:71
long target_extra
Definition jitterbuf.h:72
long max_jitterbuf
Definition jitterbuf.h:69
long resync_threshold
Definition jitterbuf.h:70
long max_contig_interp
Definition jitterbuf.h:71
long ms
Definition jitterbuf.h:104
void * data
Definition jitterbuf.h:102
long min
Definition jitterbuf.h:87
long current
Definition jitterbuf.h:88
long frames_in
Definition jitterbuf.h:79
long losspct
Definition jitterbuf.h:90
long frames_lost
Definition jitterbuf.h:82
long frames_ooo
Definition jitterbuf.h:84
long frames_dropped
Definition jitterbuf.h:83
long jitter
Definition jitterbuf.h:86
In case you didn't read that giant block of text above the mansession_session struct,...
Definition manager.c:323
Number structure.
struct ast_sockaddr addr
Definition chan_iax2.c:1067
unsigned char reg
Definition chan_iax2.c:1074
uint16_t limit
Definition chan_iax2.c:1071
uint16_t cur
Definition chan_iax2.c:1069
Scheduler ID holder.
Definition sched.c:70
Definition sched.c:76
Definition chan_iax2.c:978
struct ast_frame f
Definition chan_iax2.c:979
struct signaling_queue_entry * next
Definition chan_iax2.c:980
structure to hold users read from phoneprov_users.conf
list of users found in the config file
int value
Definition syslog.c:37
struct ast_taskprocessor * ast_taskprocessor_get(const char *name, enum ast_tps_options create)
Get a reference to a taskprocessor with the specified name and create the taskprocessor if necessary.
void * ast_taskprocessor_unreference(struct ast_taskprocessor *tps)
Unreference the specified taskprocessor and its reference count will decrement.
@ TPS_REF_DEFAULT
return a reference to a taskprocessor, create one if it does not exist
#define ast_taskprocessor_push(tps, task_exe, datap)
int done
static struct test_val a
static struct test_val c
struct timeval ast_samp2tv(unsigned int _nsamp, unsigned int _rate)
Returns a timeval corresponding to the duration of n samples at rate r. Useful to convert samples to ...
Definition time.h:282
int ast_tvzero(const struct timeval t)
Returns true if the argument is 0,0.
Definition time.h:117
int ast_tvcmp(struct timeval _a, struct timeval _b)
Compress two struct timeval instances returning -1, 0, 1 if the first arg is smaller,...
Definition time.h:137
struct timeval ast_tvadd(struct timeval a, struct timeval b)
Returns the sum of two timevals a + b.
Definition extconf.c:2280
struct timeval ast_tvsub(struct timeval a, struct timeval b)
Returns the difference of two timevals a - b.
Definition extconf.c:2295
int64_t ast_tvdiff_ms(struct timeval end, struct timeval start)
Computes the difference (in milliseconds) between two struct timeval instances.
Definition time.h:107
struct timeval ast_tvnow(void)
Returns current timeval. Meant to replace calls to gettimeofday().
Definition time.h:159
struct timeval ast_tv(ast_time_t sec, ast_suseconds_t usec)
Returns a timeval from sec, usec.
Definition time.h:235
void ast_timer_close(struct ast_timer *handle)
Close an opened timing handle.
Definition timing.c:154
int ast_timer_ack(const struct ast_timer *handle, unsigned int quantity)
Acknowledge a timer event.
Definition timing.c:171
int ast_timer_set_rate(const struct ast_timer *handle, unsigned int rate)
Set the timing tick rate.
Definition timing.c:166
struct ast_timer * ast_timer_open(void)
Open a timer.
Definition timing.c:122
int ast_timer_fd(const struct ast_timer *handle)
Get a poll()-able file descriptor for a timer.
Definition timing.c:161
int ast_translator_best_choice(struct ast_format_cap *dst_cap, struct ast_format_cap *src_cap, struct ast_format **dst_fmt_out, struct ast_format **src_fmt_out)
Chooses the best translation path.
Definition translate.c:1676
int error(const char *format,...)
#define ast_test_flag(p, flag)
Definition utils.h:64
#define RAII_VAR(vartype, varname, initval, dtor)
Declare a variable that will call a destructor function when it goes out of scope.
Definition utils.h:981
#define ast_set2_flag64(p, value, flag)
Definition utils.h:171
#define ast_test_flag64(p, flag)
Definition utils.h:140
#define ast_assert(a)
Definition utils.h:779
#define ast_set_flags_to64(p, flag, value)
Definition utils.h:181
#define ast_clear_flag64(p, flag)
Definition utils.h:154
#define MIN(a, b)
Definition utils.h:252
#define ast_pthread_create_background(a, b, c, d)
Definition utils.h:632
#define ast_assert_return(a,...)
Definition utils.h:780
#define ast_clear_flag(p, flag)
Definition utils.h:78
long int ast_random(void)
Definition utils.c:2346
#define ast_pthread_create_detached(a, b, c, d)
Definition utils.h:628
#define ast_copy_flags64(dest, src, flagz)
Definition utils.h:161
#define ast_set_flag64(p, flag)
Definition utils.h:147
#define ast_set_flag(p, flag)
Definition utils.h:71
#define ARRAY_LEN(a)
Definition utils.h:706
void ast_sha1_hash(char *output, const char *input)
Produces SHA1 hash based on input string.
Definition utils.c:266

◆ IAX_CAPABILITY_FULLBANDWIDTH

#define IAX_CAPABILITY_FULLBANDWIDTH   0xFFFF

Definition at line 410 of file chan_iax2.c.

◆ IAX_CAPABILITY_LOWBANDWIDTH

#define IAX_CAPABILITY_LOWBANDWIDTH
Value:
~AST_FORMAT_G726 & \
~AST_FORMAT_G726_AAL2 & \
~AST_FORMAT_ADPCM)

Definition at line 422 of file chan_iax2.c.

◆ IAX_CAPABILITY_LOWFREE

#define IAX_CAPABILITY_LOWFREE
Value:
~AST_FORMAT_G723)

Definition at line 427 of file chan_iax2.c.

◆ IAX_CAPABILITY_MEDBANDWIDTH

#define IAX_CAPABILITY_MEDBANDWIDTH

Definition at line 412 of file chan_iax2.c.

◆ IAX_CODEC_NOCAP

#define IAX_CODEC_NOCAP   (uint64_t)(1LLU << 16)

only consider requested format and ignore capabilities

Definition at line 551 of file chan_iax2.c.

◆ IAX_CODEC_NOPREFS

#define IAX_CODEC_NOPREFS   (uint64_t)(1LLU << 15)

Force old behaviour by turning off prefs

Definition at line 550 of file chan_iax2.c.

◆ IAX_CODEC_USER_FIRST

#define IAX_CODEC_USER_FIRST   (uint64_t)(1LLU << 14)

are we willing to let the other guy choose the codec?

Definition at line 549 of file chan_iax2.c.

◆ IAX_DEBUGDIGEST

#define IAX_DEBUGDIGEST (   msg,
  key 
)

Definition at line 480 of file chan_iax2.c.

480 { \
481 int idx; \
482 char digest[33] = ""; \
483 \
484 if (!iaxdebug) \
485 break; \
486 \
487 for (idx = 0; idx < 16; idx++) \
488 sprintf(digest + (idx << 1), "%02hhx", (unsigned char) key[idx]); \
489 \
490 ast_log(LOG_NOTICE, msg " IAX_COMMAND_RTKEY to rotate key to '%s'\n", digest); \
491 } while(0)

◆ IAX_DELAYPBXSTART

#define IAX_DELAYPBXSTART   (uint64_t)(1LLU << 25)

Don't start a PBX on the channel until the peer sends us a response, so that we've achieved a three-way handshake with them before sending voice or anything else

Definition at line 559 of file chan_iax2.c.

◆ IAX_DELME

#define IAX_DELME   (uint64_t)(1LLU << 1)

Needs to be deleted

Definition at line 536 of file chan_iax2.c.

◆ IAX_DYNAMIC

#define IAX_DYNAMIC   (uint64_t)(1LLU << 6)

dynamic peer

Definition at line 541 of file chan_iax2.c.

◆ IAX_ENCRYPTED

#define IAX_ENCRYPTED   (uint64_t)(1LLU << 12)

Whether we should assume encrypted tx/rx

Definition at line 547 of file chan_iax2.c.

◆ IAX_FORCE_ENCRYPT

#define IAX_FORCE_ENCRYPT   (uint64_t)(1LLU << 30)

Forces call encryption, if encryption not possible hangup

Definition at line 564 of file chan_iax2.c.

◆ IAX_HASCALLERID

#define IAX_HASCALLERID   (uint64_t)(1LLU << 0)

CallerID has been specified

Definition at line 535 of file chan_iax2.c.

◆ IAX_IMMEDIATE

#define IAX_IMMEDIATE   (uint64_t)(1LLU << 27)

Allow immediate off-hook to extension s

Definition at line 561 of file chan_iax2.c.

◆ IAX_KEYPOPULATED

#define IAX_KEYPOPULATED   (uint64_t)(1LLU << 13)

Whether we have a key populated

Definition at line 548 of file chan_iax2.c.

◆ IAX_MAXAUTHREQ

#define IAX_MAXAUTHREQ   (uint64_t)(1LLU << 24)

Maximum outstanding AUTHREQ restriction is in place

Definition at line 558 of file chan_iax2.c.

◆ IAX_NOTRANSFER

#define IAX_NOTRANSFER   (uint64_t)(1LLU << 4)

Don't native bridge

Definition at line 539 of file chan_iax2.c.

◆ IAX_PROVISION

#define IAX_PROVISION   (uint64_t)(1LLU << 10)

This is a provisioning request

Definition at line 545 of file chan_iax2.c.

◆ IAX_QUELCH

#define IAX_QUELCH   (uint64_t)(1LLU << 11)

Whether or not we quelch audio

Definition at line 546 of file chan_iax2.c.

◆ IAX_RECVCONNECTEDLINE

#define IAX_RECVCONNECTEDLINE   (uint64_t)(1LLU << 29)

Allow receiving of connected line updates

Definition at line 563 of file chan_iax2.c.

◆ IAX_RTAUTOCLEAR

#define IAX_RTAUTOCLEAR   (uint64_t)(1LLU << 19)

erase me on expire

Definition at line 554 of file chan_iax2.c.

◆ IAX_RTCACHEFRIENDS

#define IAX_RTCACHEFRIENDS   (uint64_t)(1LLU << 17)

let realtime stay till your reload

Definition at line 552 of file chan_iax2.c.

◆ IAX_RTIGNOREREGEXPIRE

#define IAX_RTIGNOREREGEXPIRE   (uint64_t)(1LLU << 21)

When using realtime, ignore registration expiration

Definition at line 555 of file chan_iax2.c.

◆ IAX_RTSAVE_SYSNAME

#define IAX_RTSAVE_SYSNAME   (uint64_t)(1LLU << 8)

Save Systname on Realtime Updates

Definition at line 543 of file chan_iax2.c.

◆ IAX_RTUPDATE

#define IAX_RTUPDATE   (uint64_t)(1LLU << 18)

Send a realtime update

Definition at line 553 of file chan_iax2.c.

◆ IAX_SENDANI

#define IAX_SENDANI   (uint64_t)(1LLU << 7)

Send ANI along with CallerID

Definition at line 542 of file chan_iax2.c.

◆ IAX_SENDCONNECTEDLINE

#define IAX_SENDCONNECTEDLINE   (uint64_t)(1LLU << 28)

Allow sending of connected line updates

Definition at line 562 of file chan_iax2.c.

◆ IAX_SHRINKCALLERID

#define IAX_SHRINKCALLERID   (uint64_t)(1LLU << 31)

Turn on and off caller id shrinking

Definition at line 565 of file chan_iax2.c.

◆ IAX_TEMPONLY

#define IAX_TEMPONLY   (uint64_t)(1LLU << 2)

Temporary (realtime)

Definition at line 537 of file chan_iax2.c.

◆ IAX_TRANSFERMEDIA

#define IAX_TRANSFERMEDIA   (uint64_t)(1LLU << 23)

When doing IAX2 transfers, transfer media only

Definition at line 557 of file chan_iax2.c.

◆ IAX_TRUNK

#define IAX_TRUNK   (uint64_t)(1LLU << 3)

Treat as a trunk

Definition at line 538 of file chan_iax2.c.

◆ IAX_TRUNKTIMESTAMPS

#define IAX_TRUNKTIMESTAMPS   (uint64_t)(1LLU << 22)

Send trunk timestamps

Definition at line 556 of file chan_iax2.c.

◆ IAX_USEJITTERBUF

#define IAX_USEJITTERBUF   (uint64_t)(1LLU << 5)

Use jitter buffer

Definition at line 540 of file chan_iax2.c.

◆ MARK_IAX_SUBCLASS_TX

#define MARK_IAX_SUBCLASS_TX   0x8000

Definition at line 755 of file chan_iax2.c.

◆ MAX_JITTER_BUFFER

#define MAX_JITTER_BUFFER   50

Definition at line 744 of file chan_iax2.c.

◆ MAX_PEER_BUCKETS

#define MAX_PEER_BUCKETS   563

This module will get much higher performance when doing a lot of user and peer lookups if the number of buckets is increased from 1. However, to maintain old behavior for Asterisk 1.4, these are set to 1 by default. When using multiple buckets, search order through these containers is considered random, so you will not be able to depend on the order the entries are specified in iax.conf for matching order.

Definition at line 1036 of file chan_iax2.c.

◆ MAX_RETRY_TIME

#define MAX_RETRY_TIME   10000

Definition at line 742 of file chan_iax2.c.

◆ MAX_TIMESTAMP_SKEW

#define MAX_TIMESTAMP_SKEW   160

maximum difference between actual and predicted ts for sending

Definition at line 749 of file chan_iax2.c.

◆ MAX_TRUNK_MTU

#define MAX_TRUNK_MTU   1240

Maximum transmission unit for the UDP packet in the trunk not to be fragmented. This is based on 1516 - ethernet - ip - udp - iax minus one g711 frame = 1240.

Definition at line 352 of file chan_iax2.c.

◆ MAX_TRUNKDATA

#define MAX_TRUNKDATA   640 * 200

40ms, uncompressed linear * 200 channels

Definition at line 377 of file chan_iax2.c.

◆ MAX_USER_BUCKETS

#define MAX_USER_BUCKETS   MAX_PEER_BUCKETS

Definition at line 1040 of file chan_iax2.c.

◆ MEMORY_SIZE

#define MEMORY_SIZE   100

Definition at line 335 of file chan_iax2.c.

◆ MIN_JITTER_BUFFER

#define MIN_JITTER_BUFFER   10

Definition at line 745 of file chan_iax2.c.

◆ MIN_RETRY_TIME

#define MIN_RETRY_TIME   100

Definition at line 741 of file chan_iax2.c.

◆ MIN_REUSE_TIME

#define MIN_REUSE_TIME   60 /* Don't reuse a call number within 60 seconds */

Definition at line 340 of file chan_iax2.c.

◆ PEERS_FORMAT

#define PEERS_FORMAT   "%-15.15s %-40.40s %s %-40.40s %-6s%s %s %-11s %-32.32s\n"

Definition at line 6996 of file chan_iax2.c.

◆ PEERS_FORMAT2

#define PEERS_FORMAT2   "%-15.15s %-40.40s %s %-40.40s %-9s %s %-11s %-32.32s\n"

Definition at line 6995 of file chan_iax2.c.

◆ PTR_TO_CALLNO

#define PTR_TO_CALLNO (   a)    ((unsigned short)(unsigned long)(a))

Definition at line 329 of file chan_iax2.c.

◆ PTR_TO_CALLNO_ENTRY

#define PTR_TO_CALLNO_ENTRY (   a)    ((uint16_t)(unsigned long)(a))

Definition at line 988 of file chan_iax2.c.

◆ SCHED_MULTITHREADED

#define SCHED_MULTITHREADED
Todo:
XXX The IAX2 channel driver needs its native bridge code converted to the new bridge technology scheme.
Note
The chan_dahdi native bridge code can be used as an example. It also appears that chan_iax2 also has a native transfer check like chan_dahdi to eliminate tromboned calls.
The existing native bridge code is marked with the IAX2_NATIVE_BRIDGING conditional.

Definition at line 318 of file chan_iax2.c.

◆ schedule_action

#define schedule_action (   func,
  data 
)    __schedule_action(func, data, __PRETTY_FUNCTION__)

Definition at line 1763 of file chan_iax2.c.

◆ TRUNK_CALL_START

#define TRUNK_CALL_START   (IAX_MAX_CALLS / 2)

Definition at line 1260 of file chan_iax2.c.

◆ TS_GAP_FOR_JB_RESYNC

#define TS_GAP_FOR_JB_RESYNC   5000

Definition at line 752 of file chan_iax2.c.

Typedef Documentation

◆ callno_entry

typedef uint16_t callno_entry

Definition at line 777 of file chan_iax2.c.

Enumeration Type Documentation

◆ anonymous enum

anonymous enum
Enumerator
CACHE_FLAG_EXISTS 

Extension exists

CACHE_FLAG_NONEXISTENT 

Extension is nonexistent

CACHE_FLAG_CANEXIST 

Extension can exist

CACHE_FLAG_PENDING 

Waiting to hear back response

CACHE_FLAG_TIMEOUT 

Timed out

CACHE_FLAG_TRANSMITTED 

Request transmitted

CACHE_FLAG_UNKNOWN 

Timeout

CACHE_FLAG_MATCHMORE 

Matchmore

Definition at line 1087 of file chan_iax2.c.

1087 {
1088 /*! Extension exists */
1089 CACHE_FLAG_EXISTS = (1 << 0),
1090 /*! Extension is nonexistent */
1091 CACHE_FLAG_NONEXISTENT = (1 << 1),
1092 /*! Extension can exist */
1093 CACHE_FLAG_CANEXIST = (1 << 2),
1094 /*! Waiting to hear back response */
1095 CACHE_FLAG_PENDING = (1 << 3),
1096 /*! Timed out */
1097 CACHE_FLAG_TIMEOUT = (1 << 4),
1098 /*! Request transmitted */
1099 CACHE_FLAG_TRANSMITTED = (1 << 5),
1100 /*! Timeout */
1101 CACHE_FLAG_UNKNOWN = (1 << 6),
1102 /*! Matchmore */
1103 CACHE_FLAG_MATCHMORE = (1 << 7),
1104};

◆ anonymous enum

anonymous enum
Enumerator
NEW_PREVENT 
NEW_ALLOW 
NEW_FORCE 
NEW_ALLOW_CALLTOKEN_VALIDATED 

Definition at line 2389 of file chan_iax2.c.

2389 {
2390 /* do not allow a new call number, only search ones in use for match */
2391 NEW_PREVENT = 0,
2392 /* search for match first, then allow a new one to be allocated */
2393 NEW_ALLOW = 1,
2394 /* do not search for match, force a new call number */
2395 NEW_FORCE = 2,
2396 /* do not search for match, force a new call number. Signifies call number
2397 * has been calltoken validated */
2399};

◆ callno_type

Enumerator
CALLNO_TYPE_NORMAL 
CALLNO_TYPE_TRUNK 

Definition at line 983 of file chan_iax2.c.

983 {
986};

◆ calltoken_peer_enum

Call token validation settings.

Enumerator
CALLTOKEN_DEFAULT 

Default calltoken required unless the ip is in the ignorelist.

CALLTOKEN_YES 

Require call token validation.

CALLTOKEN_AUTO 

Require call token validation after a successful registration using call token validation occurs.

CALLTOKEN_NO 

Do not require call token validation.

Definition at line 573 of file chan_iax2.c.

573 {
574 /*! \brief Default calltoken required unless the ip is in the ignorelist */
576 /*! \brief Require call token validation. */
577 CALLTOKEN_YES = 1,
578 /*! \brief Require call token validation after a successful registration
579 * using call token validation occurs. */
580 CALLTOKEN_AUTO = 2,
581 /*! \brief Do not require call token validation. */
582 CALLTOKEN_NO = 3,
583};

◆ iax2_state

enum iax2_state
Enumerator
IAX_STATE_STARTED 
IAX_STATE_AUTHENTICATED 
IAX_STATE_TBD 

Definition at line 523 of file chan_iax2.c.

523 {
524 IAX_STATE_STARTED = (1 << 0),
525 IAX_STATE_AUTHENTICATED = (1 << 1),
526 IAX_STATE_TBD = (1 << 2),
527};

◆ iax2_thread_iostate

Enumerator
IAX_IOSTATE_IDLE 
IAX_IOSTATE_READY 
IAX_IOSTATE_PROCESSING 
IAX_IOSTATE_SCHEDREADY 

Definition at line 1128 of file chan_iax2.c.

◆ iax2_thread_type

Enumerator
IAX_THREAD_TYPE_POOL 
IAX_THREAD_TYPE_DYNAMIC 

Definition at line 1135 of file chan_iax2.c.

1135 {
1138};

◆ iax_reg_state

Enumerator
REG_STATE_UNREGISTERED 
REG_STATE_REGSENT 
REG_STATE_AUTHSENT 
REG_STATE_REGISTERED 
REG_STATE_REJECTED 
REG_STATE_TIMEOUT 
REG_STATE_NOAUTH 

Definition at line 698 of file chan_iax2.c.

◆ iax_transfer_state

Enumerator
TRANSFER_NONE 
TRANSFER_BEGIN 
TRANSFER_READY 
TRANSFER_RELEASED 
TRANSFER_PASSTHROUGH 
TRANSFER_MBEGIN 
TRANSFER_MREADY 
TRANSFER_MRELEASED 
TRANSFER_MPASSTHROUGH 
TRANSFER_MEDIA 
TRANSFER_MEDIAPASS 

Definition at line 708 of file chan_iax2.c.

Function Documentation

◆ __attempt_transmit()

static void __attempt_transmit ( const void *  data)
static

Definition at line 3634 of file chan_iax2.c.

3635{
3636 /* Attempt to transmit the frame to the remote peer...
3637 Called without iaxsl held. */
3638 struct iax_frame *f = (struct iax_frame *)data;
3639 int freeme = 0;
3640 int callno = f->callno;
3641
3642 /* Make sure this call is still active */
3643 if (callno)
3645 if (callno && iaxs[callno]) {
3646 if (f->retries < 0) {
3647 /* Already ACK'd */
3648 freeme = 1;
3649 } else if (f->retries >= max_retries) {
3650 /* Too many attempts. Record an error. */
3651 if (f->transfer) {
3652 /* Transfer timeout */
3654 } else if (f->final) {
3656 } else {
3657 if (iaxs[callno]->owner) {
3658 ast_log(LOG_WARNING, "Max retries exceeded to host %s on %s (type = %u, subclass = %d, ts=%u, seqno=%d)\n",
3661 f->af.frametype,
3662 f->af.subclass.integer,
3663 f->ts,
3664 f->oseqno);
3665 }
3666 iaxs[callno]->error = ETIMEDOUT;
3667 if (iaxs[callno]->owner) {
3669 /* Hangup the fd */
3670 iax2_queue_frame(callno, &fr); /* XXX */
3671 /* Remember, owner could disappear */
3672 if (iaxs[callno] && iaxs[callno]->owner)
3674 } else {
3675 if (iaxs[callno]->reg) {
3676 memset(&iaxs[callno]->reg->us, 0, sizeof(iaxs[callno]->reg->us));
3677 iaxs[callno]->reg->regstate = REG_STATE_TIMEOUT;
3679 }
3680 iax2_destroy(callno);
3681 }
3682 }
3683 freeme = 1;
3684 } else {
3685 /* Update it if it needs it */
3686 update_packet(f);
3687 /* Attempt transmission */
3688 send_packet(f);
3689 f->retries++;
3690 /* Try again later after 10 times as long */
3691 f->retrytime *= 10;
3692 if (f->retrytime > MAX_RETRY_TIME)
3694 /* Transfer messages max out at one second */
3695 if (f->transfer && (f->retrytime > 1000))
3696 f->retrytime = 1000;
3698 }
3699 } else {
3700 /* Make sure it gets freed */
3701 f->retries = -1;
3702 freeme = 1;
3703 }
3704
3705 if (freeme) {
3706 /* Don't attempt delivery, just remove it from the queue */
3707 AST_LIST_REMOVE(&frame_queue[callno], f, list);
3708 ast_mutex_unlock(&iaxsl[callno]);
3709 f->retrans = -1; /* this is safe because this is the scheduled function */
3710 /* Free the IAX frame */
3711 iax2_frame_free(f);
3712 } else if (callno) {
3713 ast_mutex_unlock(&iaxsl[callno]);
3714 }
3715}

References chan_iax2_pvt::addr, iax_frame::af, AST_CAUSE_DESTINATION_OUT_OF_ORDER, ast_channel_hangupcause_set(), ast_channel_name(), AST_CONTROL_HANGUP, AST_FRAME_CONTROL, AST_FRAME_IAX, AST_LIST_REMOVE, ast_log, ast_mutex_lock, ast_mutex_unlock, ast_sockaddr_stringify_addr(), attempt_transmit(), iax_frame::callno, iax_frame::data, ast_frame::data, chan_iax2_pvt::error, iax_frame::final, frame_queue, ast_frame::frametype, iax2_destroy(), iax2_frame_free(), iax2_queue_frame(), iax2_sched_add(), IAX_COMMAND_TXREJ, IAX_DEFAULT_REG_EXPIRE, iaxs, iaxsl, ast_frame_subclass::integer, LOG_WARNING, max_retries, MAX_RETRY_TIME, NULL, iax_frame::oseqno, chan_iax2_pvt::owner, iax2_registry::refresh, chan_iax2_pvt::reg, REG_STATE_TIMEOUT, iax2_registry::regstate, iax_frame::retrans, iax_frame::retries, iax_frame::retrytime, send_command(), send_packet(), ast_frame::subclass, iax_frame::transfer, iax_frame::ts, ast_frame::uint32, update_packet(), and iax2_registry::us.

Referenced by attempt_transmit().

◆ __auth_reject()

static void __auth_reject ( const void *  nothing)
static

Definition at line 9477 of file chan_iax2.c.

9478{
9479 /* Called from IAX thread only, without iaxs lock */
9480 int callno = (int)(long)(nothing);
9481 struct iax_ie_data ied;
9482 ast_mutex_lock(&iaxsl[callno]);
9483 if (iaxs[callno]) {
9484 memset(&ied, 0, sizeof(ied));
9485 if (iaxs[callno]->authfail == IAX_COMMAND_REGREJ) {
9486 iax_ie_append_str(&ied, IAX_IE_CAUSE, "Registration Refused");
9488 } else if (iaxs[callno]->authfail == IAX_COMMAND_REJECT) {
9489 iax_ie_append_str(&ied, IAX_IE_CAUSE, "No authority found");
9491 }
9492 send_command_final(iaxs[callno], AST_FRAME_IAX, iaxs[callno]->authfail, 0, ied.buf, ied.pos, -1);
9493 }
9494 ast_mutex_unlock(&iaxsl[callno]);
9495}

References AST_CAUSE_FACILITY_NOT_SUBSCRIBED, AST_CAUSE_FACILITY_REJECTED, AST_FRAME_IAX, ast_mutex_lock, ast_mutex_unlock, iax_ie_data::buf, IAX_COMMAND_REGREJ, IAX_COMMAND_REJECT, iax_ie_append_byte(), iax_ie_append_str(), IAX_IE_CAUSE, IAX_IE_CAUSECODE, iaxs, iaxsl, iax_ie_data::pos, and send_command_final().

Referenced by auth_reject().

◆ __auto_congest()

static void __auto_congest ( const void *  nothing)
static

Definition at line 4835 of file chan_iax2.c.

4836{
4837 int callno = PTR_TO_CALLNO(nothing);
4839 ast_mutex_lock(&iaxsl[callno]);
4840 if (iaxs[callno]) {
4841 iaxs[callno]->initid = -1;
4842 iax2_queue_frame(callno, &f);
4843 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
4844 }
4845 ast_mutex_unlock(&iaxsl[callno]);
4846}

References AST_CONTROL_CONGESTION, AST_FRAME_CONTROL, ast_log, ast_mutex_lock, ast_mutex_unlock, iax2_queue_frame(), iaxs, iaxsl, chan_iax2_pvt::initid, LOG_NOTICE, and PTR_TO_CALLNO.

Referenced by auto_congest().

◆ __auto_hangup()

static void __auto_hangup ( const void *  nothing)
static

Definition at line 9526 of file chan_iax2.c.

9527{
9528 /* Called from IAX thread only, without iaxs lock */
9529 int callno = (int)(long)(nothing);
9530 struct iax_ie_data ied;
9531 ast_mutex_lock(&iaxsl[callno]);
9532 if (iaxs[callno]) {
9533 memset(&ied, 0, sizeof(ied));
9534 iax_ie_append_str(&ied, IAX_IE_CAUSE, "Timeout");
9536 send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1);
9537 }
9538 ast_mutex_unlock(&iaxsl[callno]);
9539}

References AST_CAUSE_NO_USER_RESPONSE, AST_FRAME_IAX, ast_mutex_lock, ast_mutex_unlock, iax_ie_data::buf, IAX_COMMAND_HANGUP, iax_ie_append_byte(), iax_ie_append_str(), IAX_IE_CAUSE, IAX_IE_CAUSECODE, iaxs, iaxsl, iax_ie_data::pos, and send_command_final().

Referenced by auto_hangup().

◆ __do_deliver()

static int __do_deliver ( void *  data)
static
Note
This function assumes that iaxsl[callno] is locked when called.
IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno] was valid before calling it, it may no longer be valid after calling it. This function calls iax2_queue_frame(), which may unlock and lock the mutex associated with this callno, meaning that another thread may grab it and destroy the call.

Definition at line 3426 of file chan_iax2.c.

3427{
3428 /* Just deliver the packet by using queueing. This is called by
3429 the IAX thread with the iaxsl lock held. */
3430 struct iax_frame *fr = data;
3431 fr->retrans = -1;
3434 iax2_queue_frame(fr->callno, &fr->af);
3435 /* Free our iax frame */
3436 iax2_frame_free(fr);
3437 /* And don't run again */
3438 return 0;
3439}

References iax_frame::af, ast_clear_flag, AST_FRFLAG_HAS_TIMING_INFO, ast_test_flag64, iax_frame::callno, iax_frame::data, iax2_frame_free(), iax2_queue_frame(), IAX_ALREADYGONE, iaxs, and iax_frame::retrans.

Referenced by __get_from_jb(), and schedule_delivery().

◆ __expire_registry()

static void __expire_registry ( const void *  data)
static

Definition at line 9093 of file chan_iax2.c.

9094{
9095 struct iax2_peer *peer = (struct iax2_peer *) data;
9096 RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
9097
9098 if (!peer)
9099 return;
9100 if (peer->expire == -1) {
9101 /* Removed already (possibly through CLI), ignore */
9102 return;
9103 }
9104
9105 peer->expire = -1;
9106
9107 ast_debug(1, "Expiring registration for peer '%s'\n", peer->name);
9109 realtime_update_peer(peer->name, &peer->addr, 0);
9111 blob = ast_json_pack("{s: s, s: s}",
9112 "peer_status", "Unregistered",
9113 "cause", "Expired");
9115 /* modify entry in peercnts table as _not_ registered */
9116 peercnt_modify((unsigned char) 0, 0, &peer->addr);
9117 /* Reset the address */
9118 ast_sockaddr_setnull(&peer->addr);
9119 /* Reset expiry value */
9120 peer->expiry = min_reg_expire;
9121 if (!ast_test_flag64(peer, IAX_TEMPONLY))
9122 ast_db_del("IAX/Registry", peer->name);
9123 register_peer_exten(peer, 0);
9124 ast_devstate_changed(AST_DEVICE_UNAVAILABLE, AST_DEVSTATE_CACHABLE, "IAX2/%s", peer->name); /* Activate notification */
9125 if (iax2_regfunk)
9126 iax2_regfunk(peer->name, 0);
9127
9129 unlink_peer(peer);
9130
9131 peer_unref(peer);
9132}

References iax2_peer::addr, ast_db_del(), ast_debug, AST_DEVICE_UNAVAILABLE, AST_DEVSTATE_CACHABLE, ast_devstate_changed(), ast_endpoint_blob_publish(), AST_ENDPOINT_OFFLINE, ast_endpoint_set_state(), ast_endpoint_state_type(), ast_json_pack(), ast_json_unref(), ast_sockaddr_setnull(), ast_test_flag64, iax2_peer::endpoint, iax2_peer::expire, iax2_peer::expiry, globalflags, iax2_regfunk, IAX_RTAUTOCLEAR, IAX_RTCACHEFRIENDS, IAX_RTUPDATE, IAX_TEMPONLY, min_reg_expire, iax2_peer::name, NULL, peer_unref(), peercnt_modify(), RAII_VAR, realtime_update_peer(), register_peer_exten(), and unlink_peer().

Referenced by expire_registry().

◆ __find_callno()

static int __find_callno ( unsigned short  callno,
unsigned short  dcallno,
struct ast_sockaddr addr,
int  new,
int  sockfd,
int  return_locked,
int  check_dcallno 
)
static
Note
Calling this function while holding another pvt lock can cause a deadlock.

Definition at line 3194 of file chan_iax2.c.

3195{
3196 int res = 0;
3197 int x;
3198 /* this call is calltoken validated as long as it is either NEW_FORCE
3199 * or NEW_ALLOW_CALLTOKEN_VALIDATED */
3200 int validated = (new > NEW_ALLOW) ? 1 : 0;
3201 char host[80];
3202
3203 if (new <= NEW_ALLOW) {
3204 if (callno) {
3205 struct chan_iax2_pvt *pvt;
3206 struct chan_iax2_pvt tmp_pvt = {
3207 .callno = dcallno,
3208 .peercallno = callno,
3209 .transfercallno = callno,
3210 /* hack!! */
3211 .frames_received = check_dcallno,
3212 };
3213
3214 ast_sockaddr_copy(&tmp_pvt.addr, addr);
3215 /* this works for finding normal call numbers not involving transferring */
3216 if ((pvt = ao2_find(iax_peercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
3217 if (return_locked) {
3218 ast_mutex_lock(&iaxsl[pvt->callno]);
3219 }
3220 res = pvt->callno;
3221 ao2_ref(pvt, -1);
3222 pvt = NULL;
3223 return res;
3224 }
3225 /* this searches for transfer call numbers that might not get caught otherwise */
3226 memset(&tmp_pvt.addr, 0, sizeof(tmp_pvt.addr));
3227 ast_sockaddr_copy(&tmp_pvt.transfer, addr);
3228 if ((pvt = ao2_find(iax_transfercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
3229 if (return_locked) {
3230 ast_mutex_lock(&iaxsl[pvt->callno]);
3231 }
3232 res = pvt->callno;
3233 ao2_ref(pvt, -1);
3234 pvt = NULL;
3235 return res;
3236 }
3237 }
3238 /* This will occur on the first response to a message that we initiated,
3239 * such as a PING. */
3240 if (dcallno) {
3241 ast_mutex_lock(&iaxsl[dcallno]);
3242 }
3243 if (callno && dcallno && iaxs[dcallno] && !iaxs[dcallno]->peercallno && match(addr, callno, dcallno, iaxs[dcallno], check_dcallno)) {
3244 iaxs[dcallno]->peercallno = callno;
3245 res = dcallno;
3246 store_by_peercallno(iaxs[dcallno]);
3247 if (!res || !return_locked) {
3248 ast_mutex_unlock(&iaxsl[dcallno]);
3249 }
3250 return res;
3251 }
3252 if (dcallno) {
3253 ast_mutex_unlock(&iaxsl[dcallno]);
3254 }
3255 }
3256 if (!res && (new >= NEW_ALLOW)) {
3257 callno_entry entry;
3258
3259 /* It may seem odd that we look through the peer list for a name for
3260 * this *incoming* call. Well, it is weird. However, users don't
3261 * have an IP address/port number that we can match against. So,
3262 * this is just checking for a peer that has that IP/port and
3263 * assuming that we have a user of the same name. This isn't always
3264 * correct, but it will be changed if needed after authentication. */
3265 if (!iax2_getpeername(*addr, host, sizeof(host)))
3266 snprintf(host, sizeof(host), "%s", ast_sockaddr_stringify(addr));
3267
3268 if (peercnt_add(addr)) {
3269 /* This address has hit its callnumber limit. When the limit
3270 * is reached, the connection is not added to the peercnts table.*/
3271 return 0;
3272 }
3273
3274 if (get_unused_callno(CALLNO_TYPE_NORMAL, validated, &entry)) {
3275 /* since we ran out of space, remove the peercnt
3276 * entry we added earlier */
3278 ast_log(LOG_WARNING, "No more space\n");
3279 return 0;
3280 }
3281 x = CALLNO_ENTRY_GET_CALLNO(entry);
3282 ast_mutex_lock(&iaxsl[x]);
3283
3284 iaxs[x] = new_iax(addr, host);
3285 if (iaxs[x]) {
3286 if (iaxdebug)
3287 ast_debug(1, "Creating new call structure %d\n", x);
3288 iaxs[x]->callno_entry = entry;
3289 iaxs[x]->sockfd = sockfd;
3291 iaxs[x]->peercallno = callno;
3292 iaxs[x]->callno = x;
3295 iaxs[x]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
3296 iaxs[x]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
3297 iaxs[x]->amaflags = amaflags;
3303
3304 if (iaxs[x]->peercallno) {
3306 }
3307 } else {
3308 ast_log(LOG_WARNING, "Out of resources\n");
3311 return 0;
3312 }
3313 if (!return_locked)
3315 res = x;
3316 }
3317 return res;
3318}

References accountcode, chan_iax2_pvt::addr, amaflags, chan_iax2_pvt::amaflags, ao2_find, ao2_ref, ast_copy_flags64, ast_debug, ast_log, ast_mutex_lock, ast_mutex_unlock, ast_sockaddr_copy(), ast_sockaddr_stringify(), ast_string_field_set, chan_iax2_pvt::callno, chan_iax2_pvt::callno_entry, CALLNO_ENTRY_GET_CALLNO, CALLNO_ENTRY_TO_PTR, CALLNO_TYPE_NORMAL, default_parkinglot, DEFAULT_RETRY_TIME, chan_iax2_pvt::expiry, get_unused_callno(), globalflags, chan_iax2_pvt::host, iax2_getpeername(), iax2_sched_add(), IAX_FORCE_ENCRYPT, IAX_NOTRANSFER, iax_peercallno_pvts, IAX_RECVCONNECTEDLINE, IAX_SENDCONNECTEDLINE, iax_transfercallno_pvts, IAX_TRANSFERMEDIA, IAX_USEJITTERBUF, iaxdebug, iaxs, iaxsl, chan_iax2_pvt::lagid, lagrq_time, LOG_WARNING, match(), min_reg_expire, mohinterpret, mohsuggest, NEW_ALLOW, new_iax(), NULL, OBJ_POINTER, chan_iax2_pvt::parkinglot, chan_iax2_pvt::peercallno, peercnt_add(), peercnt_remove_by_addr(), ping_time, chan_iax2_pvt::pingid, chan_iax2_pvt::pingtime, replace_callno(), send_lagrq(), send_ping(), chan_iax2_pvt::sockfd, store_by_peercallno(), and chan_iax2_pvt::transfer.

Referenced by find_callno(), and find_callno_locked().

◆ __get_from_jb()

static void __get_from_jb ( const void *  p)
static

Definition at line 4211 of file chan_iax2.c.

4212{
4213 int callno = PTR_TO_CALLNO(p);
4214 struct chan_iax2_pvt *pvt = NULL;
4215 struct iax_frame *fr;
4216 jb_frame frame;
4217 int ret;
4218 long ms;
4219 long next;
4220 struct timeval now = ast_tvnow();
4221 struct ast_format *voicefmt;
4222
4223 /* Make sure we have a valid private structure before going on */
4224 ast_mutex_lock(&iaxsl[callno]);
4225 pvt = iaxs[callno];
4226 if (!pvt) {
4227 /* No go! */
4228 ast_mutex_unlock(&iaxsl[callno]);
4229 return;
4230 }
4231
4232 pvt->jbid = -1;
4233
4234 /* round up a millisecond since ast_sched_runq does; */
4235 /* prevents us from spinning while waiting for our now */
4236 /* to catch up with runq's now */
4237 now.tv_usec += 1000;
4238
4239 ms = ast_tvdiff_ms(now, pvt->rxcore);
4240 if (ms >= (next = jb_next(pvt->jb))) {
4242 if (!voicefmt) {
4243 /* pvt->voiceformat won't be set if we haven't received any voice frames yet.
4244 * In this case, fall back to using the format negotiated during call setup,
4245 * so we don't stall the jitterbuffer completely. */
4247 if (!voicefmt) {
4248 /* As a last resort, we can use pvt->chosenformat.
4249 * This is set when we receive a call (either authenticated or unauthenticated),
4250 * so even if we haven't received any voice frames yet, we can still use the
4251 * right format.
4252 *
4253 * If we have to do this, in most cases, we aren't even processing voice frames
4254 * anyways, it's likely a non-voice frame. In that case, the format doesn't
4255 * really matter so much, because we could just pass 20 to jb_get instead
4256 * of calling ast_format_get_default_ms. However, until jb_get returns,
4257 * we don't actually know what kind of frame it is for sure, so use
4258 * the right format just to be safe. */
4260 }
4261 }
4262 if (!voicefmt) {
4263 /* This should never happen, since we should always be able to have an acceptable format to use. */
4264 ast_log(LOG_ERROR, "No voice, peer, or chosen format available on %s, backlogging frame\n", ast_channel_name(pvt->owner));
4265 goto cleanup; /* Don't crash if there's no voice format */
4266 }
4267 ret = jb_get(pvt->jb, &frame, ms, ast_format_get_default_ms(voicefmt));
4268 switch(ret) {
4269 case JB_OK:
4270 fr = frame.data;
4271 __do_deliver(fr);
4272 /* __do_deliver() can cause the call to disappear */
4273 pvt = iaxs[callno];
4274 break;
4275 case JB_INTERP:
4276 {
4277 struct ast_frame af = { 0, };
4278
4279 /* create an interpolation frame */
4281 af.subclass.format = voicefmt;
4282 af.samples = frame.ms * (ast_format_get_sample_rate(voicefmt) / 1000);
4283 af.src = "IAX2 JB interpolation";
4284 af.delivery = ast_tvadd(pvt->rxcore, ast_samp2tv(next, 1000));
4286
4287 /* queue the frame: For consistency, we would call __do_deliver here, but __do_deliver wants an iax_frame,
4288 * which we'd need to malloc, and then it would free it. That seems like a drag */
4289 if (!ast_test_flag64(iaxs[callno], IAX_ALREADYGONE)) {
4290 iax2_queue_frame(callno, &af);
4291 /* iax2_queue_frame() could cause the call to disappear */
4292 pvt = iaxs[callno];
4293 }
4294 }
4295 break;
4296 case JB_DROP:
4297 iax2_frame_free(frame.data);
4298 break;
4299 case JB_NOFRAME:
4300 case JB_EMPTY:
4301 /* do nothing */
4302 break;
4303 default:
4304 /* shouldn't happen */
4305 break;
4306 }
4307 }
4308cleanup:
4309 if (pvt)
4310 update_jbsched(pvt);
4311 ast_mutex_unlock(&iaxsl[callno]);
4312}

References __do_deliver(), ast_channel_name(), ast_format_compatibility_bitfield2format(), ast_format_get_default_ms(), ast_format_get_sample_rate(), AST_FRAME_VOICE, AST_FRIENDLY_OFFSET, ast_log, ast_mutex_lock, ast_mutex_unlock, ast_samp2tv(), ast_test_flag64, ast_tvadd(), ast_tvdiff_ms(), ast_tvnow(), chan_iax2_pvt::chosenformat, cleanup(), jb_frame::data, ast_frame::delivery, ast_frame_subclass::format, ast_frame::frametype, iax2_frame_free(), iax2_queue_frame(), IAX_ALREADYGONE, iaxs, iaxsl, chan_iax2_pvt::jb, JB_DROP, JB_EMPTY, jb_get(), JB_INTERP, jb_next(), JB_NOFRAME, JB_OK, chan_iax2_pvt::jbid, LOG_ERROR, jb_frame::ms, iax_frame::next, ast_frame::next, NULL, ast_frame::offset, chan_iax2_pvt::owner, chan_iax2_pvt::peerformat, PTR_TO_CALLNO, chan_iax2_pvt::rxcore, ast_frame::samples, ast_frame::src, ast_frame::subclass, update_jbsched(), and chan_iax2_pvt::voiceformat.

Referenced by get_from_jb().

◆ __iax2_do_register_s()

static void __iax2_do_register_s ( const void *  data)
static

Definition at line 8736 of file chan_iax2.c.

8737{
8738 struct iax2_registry *reg = (struct iax2_registry *)data;
8739
8740 if (ast_sockaddr_isnull(&reg->addr)) {
8741 reg->addr.ss.ss_family = AST_AF_UNSPEC;
8742 ast_dnsmgr_lookup(reg->hostname, &reg->addr, &reg->dnsmgr, srvlookup ? "_iax._udp" : NULL);
8743 if (!ast_sockaddr_port(&reg->addr)) {
8744 ast_sockaddr_set_port(&reg->addr, reg->port);
8745 } else {
8746 reg->port = ast_sockaddr_port(&reg->addr);
8747 }
8748 }
8749
8750 reg->expire = -1;
8751 iax2_do_register(reg);
8752}

References iax2_registry::addr, AST_AF_UNSPEC, ast_dnsmgr_lookup(), ast_sockaddr_isnull(), ast_sockaddr_port, ast_sockaddr_set_port, iax2_registry::dnsmgr, iax2_registry::expire, iax2_registry::hostname, iax2_do_register(), NULL, iax2_registry::port, srvlookup, and ast_sockaddr::ss.

Referenced by iax2_do_register_s().

◆ __iax2_poke_noanswer()

static void __iax2_poke_noanswer ( const void *  data)
static

Definition at line 12562 of file chan_iax2.c.

12563{
12564 struct iax2_peer *peer = (struct iax2_peer *)data;
12565 int callno;
12566
12567 if (peer->lastms > -1) {
12568 RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
12569
12570 ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE! Time: %d\n", peer->name, peer->lastms);
12572 blob = ast_json_pack("{s: s, s: i}",
12573 "peer_status", "Unreachable",
12574 "time", peer->lastms);
12576 ast_devstate_changed(AST_DEVICE_UNAVAILABLE, AST_DEVSTATE_CACHABLE, "IAX2/%s", peer->name); /* Activate notification */
12577 }
12578 if ((callno = peer->callno) > 0) {
12582 }
12583 peer->callno = 0;
12584 peer->lastms = -1;
12585 /* Try again quickly */
12587 if (peer->pokeexpire == -1)
12588 peer_unref(peer);
12589}

References AST_DEVICE_UNAVAILABLE, AST_DEVSTATE_CACHABLE, ast_devstate_changed(), ast_endpoint_blob_publish(), AST_ENDPOINT_OFFLINE, ast_endpoint_set_state(), ast_endpoint_state_type(), ast_json_pack(), ast_json_unref(), ast_log, ast_mutex_lock, ast_mutex_unlock, iax2_peer::callno, iax2_peer::endpoint, iax2_destroy(), iax2_poke_peer_s(), iax2_sched_add(), iaxsl, iax2_peer::lastms, LOG_NOTICE, iax2_peer::name, NULL, peer_ref(), peer_unref(), iax2_peer::pokeexpire, iax2_peer::pokefreqnotok, and RAII_VAR.

Referenced by iax2_poke_noanswer().

◆ __iax2_poke_peer_s()

static void __iax2_poke_peer_s ( const void *  data)
static

Definition at line 9586 of file chan_iax2.c.

9587{
9588 struct iax2_peer *peer = (struct iax2_peer *)data;
9589 iax2_poke_peer(peer, 0);
9590 peer_unref(peer);
9591}

References iax2_poke_peer(), and peer_unref().

Referenced by iax2_poke_peer_s().

◆ __iax2_show_peers()

static int __iax2_show_peers ( int  fd,
int *  total,
struct mansession s,
const int  argc,
const char *const  argv[] 
)
static

Definition at line 7099 of file chan_iax2.c.

7100{
7101 struct show_peers_context cont = {
7102 .havepattern = 0,
7103 .idtext = "",
7104 .registeredonly = 0,
7105
7106 .peerlist = 0,
7107
7108 .total_peers = 0,
7109 .online_peers = 0,
7110 .offline_peers = 0,
7111 .unmonitored_peers = 0,
7112 };
7113
7114 struct ao2_iterator i;
7115
7116 struct iax2_peer *peer = NULL;
7117
7118 switch (argc) {
7119 case 6:
7120 if (!strcasecmp(argv[3], "registered"))
7121 cont.registeredonly = 1;
7122 else
7123 return RESULT_SHOWUSAGE;
7124 if (!strcasecmp(argv[4], "like")) {
7125 if (regcomp(&cont.regexbuf, argv[5], REG_EXTENDED | REG_NOSUB))
7126 return RESULT_SHOWUSAGE;
7127 cont.havepattern = 1;
7128 } else
7129 return RESULT_SHOWUSAGE;
7130 break;
7131 case 5:
7132 if (!strcasecmp(argv[3], "like")) {
7133 if (regcomp(&cont.regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
7134 return RESULT_SHOWUSAGE;
7135 cont.havepattern = 1;
7136 } else
7137 return RESULT_SHOWUSAGE;
7138 break;
7139 case 4:
7140 if (!strcasecmp(argv[3], "registered")) {
7141 cont.registeredonly = 1;
7142 } else {
7143 return RESULT_SHOWUSAGE;
7144 }
7145 break;
7146 case 3:
7147 break;
7148 default:
7149 return RESULT_SHOWUSAGE;
7150 }
7151
7152
7153 if (!s) {
7154 ast_cli(fd, PEERS_FORMAT2, "Name/Username", "Host", " ", "Mask", "Port", " ", "Status", "Description");
7155 }
7156
7157 i = ao2_iterator_init(peers, 0);
7158 for (; (peer = ao2_iterator_next(&i)); peer_unref(peer)) {
7159
7160 if (cont.registeredonly && ast_sockaddr_isnull(&peer->addr)) {
7161 continue;
7162 }
7163 if (cont.havepattern && regexec(&cont.regexbuf, peer->name, 0, NULL, 0)) {
7164 continue;
7165 }
7166
7167 _iax2_show_peers_one(fd, s, &cont, peer);
7168
7169 }
7171
7172 if (!s) {
7173 ast_cli(fd,"%d iax2 peers [%d online, %d offline, %d unmonitored]\n",
7175 }
7176
7177 if (cont.havepattern) {
7178 regfree(&cont.regexbuf);
7179 }
7180
7181 if (total) {
7182 *total = cont.total_peers;
7183 }
7184
7185 return RESULT_SUCCESS;
7186
7187}

References _iax2_show_peers_one(), iax2_peer::addr, ao2_iterator_destroy(), ao2_iterator_init(), ao2_iterator_next, ast_cli(), ast_sockaddr_isnull(), show_peers_context::havepattern, iax2_peer::name, NULL, show_peers_context::offline_peers, show_peers_context::online_peers, peer_unref(), PEERS_FORMAT2, show_peers_context::regexbuf, show_peers_context::registeredonly, RESULT_SHOWUSAGE, RESULT_SUCCESS, total, show_peers_context::total_peers, and show_peers_context::unmonitored_peers.

Referenced by handle_cli_iax2_show_peers(), and manager_iax2_show_peers().

◆ __reg_module()

static void __reg_module ( void  )
static

Definition at line 15138 of file chan_iax2.c.

◆ __schedule_action()

static int __schedule_action ( void(*)(const void *data)  func,
const void *  data,
const char *  funcname 
)
static

Definition at line 1738 of file chan_iax2.c.

1739{
1740 struct iax2_thread *thread;
1741 static time_t lasterror;
1742 time_t t;
1743
1745 if (thread != NULL) {
1746 thread->schedfunc = func;
1747 thread->scheddata = data;
1748 thread->iostate = IAX_IOSTATE_SCHEDREADY;
1749#ifdef DEBUG_SCHED_MULTITHREAD
1750 ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc));
1751#endif
1752 signal_condition(&thread->lock, &thread->cond);
1753 return 0;
1754 }
1755 time(&t);
1756 if (t != lasterror) {
1757 lasterror = t;
1758 ast_debug(1, "Out of idle IAX2 threads for scheduling! (%s)\n", funcname);
1759 }
1760
1761 return -1;
1762}

References ast_copy_string(), ast_debug, find_idle_thread(), IAX_IOSTATE_SCHEDREADY, NULL, signal_condition(), and thread.

◆ __send_command()

static int __send_command ( struct chan_iax2_pvt i,
char  type,
int  command,
unsigned int  ts,
const unsigned char *  data,
int  datalen,
int  seqno,
int  now,
int  transfer,
int  final 
)
static

Definition at line 7865 of file chan_iax2.c.

7867{
7868 struct ast_frame f = { 0, };
7869 int res = 0;
7870
7871 f.frametype = type;
7872 f.subclass.integer = command;
7873 f.datalen = datalen;
7874 f.src = __FUNCTION__;
7875 f.data.ptr = (void *) data;
7876
7877 if ((res = queue_signalling(i, &f)) <= 0) {
7878 return res;
7879 }
7880
7881 return iax2_send(i, &f, ts, seqno, now, transfer, final);
7882}

References ast_frame::data, ast_frame::datalen, ast_frame::frametype, iax2_send(), ast_frame_subclass::integer, ast_frame::ptr, queue_signalling(), ast_frame::seqno, ast_frame::src, ast_frame::subclass, transfer(), ast_frame::ts, and type.

Referenced by send_command(), send_command_final(), send_command_immediate(), and send_command_transfer().

◆ __send_lagrq()

static void __send_lagrq ( const void *  data)
static

Definition at line 1866 of file chan_iax2.c.

1867{
1868 int callno = PTR_TO_CALLNO(data);
1869
1870 if (iax2_lock_callno_unless_destroyed(callno) == 0) {
1871 ast_debug(3, "Hangup initiated on call %d, aborting __send_lagrq\n", callno);
1872 return;
1873 }
1874
1875 /* Mark lagid as invalid scheduler id. */
1876 iaxs[callno]->lagid = -1;
1877
1878 /* callno is now locked. */
1879 if (iaxs[callno]->peercallno) {
1880 /* Send LAGRQ packet. */
1882
1883 /* Schedule sending next lagrq. */
1884 iaxs[callno]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, data);
1885 }
1886
1887 ast_mutex_unlock(&iaxsl[callno]);
1888}

References ast_debug, AST_FRAME_IAX, ast_mutex_unlock, iax2_thread::callno, iax2_lock_callno_unless_destroyed(), iax2_sched_add(), IAX_COMMAND_LAGRQ, iaxs, iaxsl, chan_iax2_pvt::lagid, lagrq_time, NULL, PTR_TO_CALLNO, send_command(), and send_lagrq().

Referenced by send_lagrq().

◆ __send_ping()

static void __send_ping ( const void *  data)
static

Definition at line 1802 of file chan_iax2.c.

1803{
1804 int callno = PTR_TO_CALLNO(data);
1805
1806 if (iax2_lock_callno_unless_destroyed(callno) == 0) {
1807 ast_debug(3, "Hangup initiated on call %d, aborting __send_ping\n", callno);
1808 return;
1809 }
1810
1811 /* Mark pingid as invalid scheduler id. */
1812 iaxs[callno]->pingid = -1;
1813
1814 /* callno is now locked. */
1815 if (iaxs[callno]->peercallno) {
1816 /* Send PING packet. */
1817 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
1818
1819 /* Schedule sending next ping. */
1820 iaxs[callno]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, data);
1821 }
1822
1823 ast_mutex_unlock(&iaxsl[callno]);
1824}

References ast_debug, AST_FRAME_IAX, ast_mutex_unlock, iax2_thread::callno, iax2_lock_callno_unless_destroyed(), iax2_sched_add(), IAX_COMMAND_PING, iaxs, iaxsl, NULL, ping_time, chan_iax2_pvt::pingid, PTR_TO_CALLNO, send_command(), and send_ping().

Referenced by send_ping().

◆ __unload_module()

static int __unload_module ( void  )
static

Definition at line 14765 of file chan_iax2.c.

14766{
14767 int x;
14768
14771
14772 ast_manager_unregister("IAXpeers");
14773 ast_manager_unregister("IAXpeerlist");
14774 ast_manager_unregister("IAXnetstats");
14775 ast_manager_unregister("IAXregistry");
14780
14782 pthread_cancel(netthreadid);
14783 pthread_kill(netthreadid, SIGURG);
14784 pthread_join(netthreadid, NULL);
14785 }
14786
14787 for (x = 0; x < ARRAY_LEN(iaxs); x++) {
14788 if (iaxs[x]) {
14789 iax2_destroy(x);
14790 }
14791 }
14792
14793 /* Call for all threads to halt */
14797
14800 for (x = 0; x < ARRAY_LEN(iaxs); x++) {
14801 if (iaxs[x]) {
14802 iax2_destroy(x);
14803 }
14804 }
14805 ast_manager_unregister( "IAXpeers" );
14806 ast_manager_unregister( "IAXpeerlist" );
14807 ast_manager_unregister( "IAXnetstats" );
14808 ast_manager_unregister( "IAXregistry" );
14813 delete_users();
14816
14817 for (x = 0; x < ARRAY_LEN(iaxsl); x++) {
14819 }
14820
14821 ao2_ref(peers, -1);
14822 ao2_ref(users, -1);
14827 if (timer) {
14829 timer = NULL;
14830 }
14832
14835 sched = NULL;
14836 ao2_ref(peercnts, -1);
14837
14839 ast_unload_realtime("iaxpeers");
14840
14843 return 0;
14844}

References acl_change_stasis_unsubscribe(), ao2_ref, ARRAY_LEN, ast_channel_unregister(), ast_cli_unregister_multiple(), ast_context_destroy_by_name(), ast_manager_unregister(), ast_mutex_destroy, ast_netsock_release(), AST_PTHREADT_NULL, ast_sched_clean_by_callback(), ast_sched_context_destroy(), ast_taskprocessor_unreference(), ast_timer_close(), ast_unload_realtime(), ast_unregister_application(), ast_unregister_switch(), callno_limits, calltoken_ignores, ast_channel_tech::capabilities, cleanup_thread_list(), cli_iax2, delete_users(), iax2_destroy(), iax2_switch, iax2_tech, iax_firmware_unload(), iax_peercallno_pvts, iax_provision_unload(), iax_transfercallno_pvts, iaxs, iaxsl, netsock, netthreadid, network_change_stasis_unsubscribe(), NULL, outsock, papp, peercnt_remove_cb(), peercnts, regcontext, timer, and transmit_processor.

Referenced by load_module(), and unload_module().

◆ __unreg_module()

static void __unreg_module ( void  )
static

Definition at line 15138 of file chan_iax2.c.

◆ _iax2_show_peers_one()

static void _iax2_show_peers_one ( int  fd,
struct mansession s,
struct show_peers_context cont,
struct iax2_peer peer 
)
static

Definition at line 6998 of file chan_iax2.c.

6999{
7000 char name[256] = "";
7001 char status[64];
7002 int retstatus;
7003 struct ast_str *encmethods = ast_str_alloca(256);
7004
7005 char *tmp_host, *tmp_mask, *tmp_port;
7006
7007 tmp_host = ast_strdupa(ast_sockaddr_stringify_addr(&peer->addr));
7008 tmp_mask = ast_strdupa(ast_sockaddr_stringify_addr(&peer->mask));
7009 tmp_port = ast_strdupa(ast_sockaddr_stringify_port(&peer->addr));
7010
7011 if (!ast_strlen_zero(peer->username)) {
7012 snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
7013 } else {
7014 ast_copy_string(name, peer->name, sizeof(name));
7015 }
7016
7017 encmethods_to_str(peer->encmethods, &encmethods);
7018 retstatus = peer_status(peer, status, sizeof(status));
7019 if (retstatus > 0) {
7020 cont->online_peers++;
7021 } else if (!retstatus) {
7022 cont->offline_peers++;
7023 } else {
7024 cont->unmonitored_peers++;
7025 }
7026
7027 if (s) {
7028 if (cont->peerlist) { /* IAXpeerlist */
7029 astman_append(s,
7030 "Event: PeerEntry\r\n%s"
7031 "Channeltype: IAX\r\n",
7032 cont->idtext);
7033 if (!ast_strlen_zero(peer->username)) {
7034 astman_append(s,
7035 "ObjectName: %s\r\n"
7036 "ObjectUsername: %s\r\n",
7037 peer->name,
7038 peer->username);
7039 } else {
7040 astman_append(s,
7041 "ObjectName: %s\r\n",
7042 name);
7043 }
7044 } else { /* IAXpeers */
7045 astman_append(s,
7046 "Event: PeerEntry\r\n%s"
7047 "Channeltype: IAX2\r\n"
7048 "ObjectName: %s\r\n",
7049 cont->idtext,
7050 name);
7051 }
7052 astman_append(s,
7053 "ChanObjectType: peer\r\n"
7054 "IPaddress: %s\r\n",
7055 tmp_host);
7056 if (cont->peerlist) { /* IAXpeerlist */
7057 astman_append(s,
7058 "Mask: %s\r\n"
7059 "Port: %s\r\n",
7060 tmp_mask,
7061 tmp_port);
7062 } else { /* IAXpeers */
7063 astman_append(s,
7064 "IPport: %s\r\n",
7065 tmp_port);
7066 }
7067 astman_append(s,
7068 "Dynamic: %s\r\n"
7069 "Trunk: %s\r\n"
7070 "Encryption: %s\r\n"
7071 "Status: %s\r\n",
7072 ast_test_flag64(peer, IAX_DYNAMIC) ? "yes" : "no",
7073 ast_test_flag64(peer, IAX_TRUNK) ? "yes" : "no",
7074 peer->encmethods ? ast_str_buffer(encmethods) : "no",
7075 status);
7076 if (cont->peerlist) { /* IAXpeerlist */
7077 astman_append(s, "\r\n");
7078 } else { /* IAXpeers */
7079 astman_append(s,
7080 "Description: %s\r\n\r\n",
7081 peer->description);
7082 }
7083 } else {
7085 name,
7086 tmp_host,
7087 ast_test_flag64(peer, IAX_DYNAMIC) ? "(D)" : "(S)",
7088 tmp_mask,
7089 tmp_port,
7090 ast_test_flag64(peer, IAX_TRUNK) ? "(T)" : " ",
7091 peer->encmethods ? "(E)" : " ",
7092 status,
7093 peer->description);
7094 }
7095
7096 cont->total_peers++;
7097}

References iax2_peer::addr, ast_cli(), ast_copy_string(), ast_sockaddr_stringify_addr(), ast_sockaddr_stringify_port(), ast_str_alloca, ast_str_buffer(), ast_strdupa, ast_strlen_zero(), ast_test_flag64, astman_append(), iax2_peer::description, iax2_peer::encmethods, encmethods_to_str(), IAX_DYNAMIC, IAX_TRUNK, show_peers_context::idtext, iax2_peer::mask, name, iax2_peer::name, show_peers_context::offline_peers, show_peers_context::online_peers, peer_status(), show_peers_context::peerlist, PEERS_FORMAT, status, show_peers_context::total_peers, show_peers_context::unmonitored_peers, and iax2_peer::username.

Referenced by __iax2_show_peers(), and manager_iax2_show_peer_list().

◆ acf_channel_read()

static int acf_channel_read ( struct ast_channel chan,
const char *  funcname,
char *  preparse,
char *  buf,
size_t  buflen 
)
static

Definition at line 14629 of file chan_iax2.c.

14630{
14631 struct chan_iax2_pvt *pvt;
14632 unsigned int callno;
14633 int res = 0;
14634
14635 if (!chan || ast_channel_tech(chan) != &iax2_tech) {
14636 ast_log(LOG_ERROR, "This function requires a valid IAX2 channel\n");
14637 return -1;
14638 }
14639
14642 if (!(pvt = iaxs[callno])) {
14644 return -1;
14645 }
14646
14647 if (!strcasecmp(args, "osptoken")) {
14648 ast_copy_string(buf, pvt->osptoken, buflen);
14649 } else if (!strcasecmp(args, "peerip")) {
14651 } else if (!strcasecmp(args, "peername")) {
14652 ast_copy_string(buf, pvt->username, buflen);
14653 } else if (!strcasecmp(args, "auth_method")) {
14655 } else if (!strcasecmp(args, "secure_signaling") || !strcasecmp(args, "secure_media")) {
14656 snprintf(buf, buflen, "%s", IAX_CALLENCRYPTED(pvt) ? "1" : "");
14657 } else {
14658 res = -1;
14659 }
14660
14662
14663 return res;
14664}

References chan_iax2_pvt::addr, args, ast_channel_tech_pvt(), ast_copy_string(), ast_log, ast_mutex_lock, ast_mutex_unlock, ast_sockaddr_isnull(), ast_sockaddr_stringify_addr(), auth_method_labels, buf, chan_iax2_pvt::callno, chan_iax2_pvt::eff_auth_method, iax2_tech, IAX_CALLENCRYPTED, iaxs, iaxsl, LOG_ERROR, chan_iax2_pvt::osptoken, PTR_TO_CALLNO, and chan_iax2_pvt::username.

◆ acf_iaxvar_read()

static int acf_iaxvar_read ( struct ast_channel chan,
const char *  cmd,
char *  data,
char *  buf,
size_t  len 
)
static

Definition at line 10172 of file chan_iax2.c.

10173{
10174 struct ast_datastore *variablestore;
10175 AST_LIST_HEAD(, ast_var_t) *varlist;
10176 struct ast_var_t *var;
10177
10178 if (!chan) {
10179 ast_log(LOG_WARNING, "No channel was provided to %s function.\n", cmd);
10180 return -1;
10181 }
10182
10184 if (!variablestore) {
10185 *buf = '\0';
10186 return 0;
10187 }
10188 varlist = variablestore->data;
10189
10190 AST_LIST_LOCK(varlist);
10191 AST_LIST_TRAVERSE(varlist, var, entries) {
10192 if (strcmp(var->name, data) == 0) {
10193 ast_copy_string(buf, var->value, len);
10194 break;
10195 }
10196 }
10197 AST_LIST_UNLOCK(varlist);
10198 return 0;
10199}

References ast_channel_datastore_find(), ast_copy_string(), AST_LIST_HEAD, AST_LIST_LOCK, AST_LIST_TRAVERSE, AST_LIST_UNLOCK, ast_log, buf, ast_datastore::data, ast_var_t::entries, iax2_variable_datastore_info, len(), LOG_WARNING, NULL, and var.

◆ acf_iaxvar_write()

static int acf_iaxvar_write ( struct ast_channel chan,
const char *  cmd,
char *  data,
const char *  value 
)
static

Definition at line 10201 of file chan_iax2.c.

10202{
10203 struct ast_datastore *variablestore;
10204 AST_LIST_HEAD(, ast_var_t) *varlist;
10205 struct ast_var_t *var;
10206
10207 if (!chan) {
10208 ast_log(LOG_WARNING, "No channel was provided to %s function.\n", cmd);
10209 return -1;
10210 }
10211
10213 if (!variablestore) {
10215 if (!variablestore) {
10216 ast_log(LOG_ERROR, "Memory allocation error\n");
10217 return -1;
10218 }
10219 varlist = ast_calloc(1, sizeof(*varlist));
10220 if (!varlist) {
10221 ast_datastore_free(variablestore);
10222 ast_log(LOG_ERROR, "Unable to assign new variable '%s'\n", data);
10223 return -1;
10224 }
10225
10226 AST_LIST_HEAD_INIT(varlist);
10227 variablestore->data = varlist;
10228 variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
10229 ast_channel_datastore_add(chan, variablestore);
10230 } else
10231 varlist = variablestore->data;
10232
10233 AST_LIST_LOCK(varlist);
10235 if (strcmp(var->name, data) == 0) {
10238 break;
10239 }
10240 }
10242 var = ast_var_assign(data, value);
10243 if (var)
10244 AST_LIST_INSERT_TAIL(varlist, var, entries);
10245 else
10246 ast_log(LOG_ERROR, "Unable to assign new variable '%s'\n", data);
10247 AST_LIST_UNLOCK(varlist);
10248 return 0;
10249}

References ast_calloc, ast_channel_datastore_add(), ast_channel_datastore_find(), ast_datastore_alloc, ast_datastore_free(), AST_LIST_HEAD, AST_LIST_HEAD_INIT, AST_LIST_INSERT_TAIL, AST_LIST_LOCK, AST_LIST_REMOVE_CURRENT, AST_LIST_TRAVERSE_SAFE_BEGIN, AST_LIST_TRAVERSE_SAFE_END, AST_LIST_UNLOCK, ast_log, ast_var_assign, ast_var_delete(), ast_datastore::data, DATASTORE_INHERIT_FOREVER, ast_var_t::entries, iax2_variable_datastore_info, ast_datastore::inheritance, LOG_ERROR, LOG_WARNING, NULL, value, and var.

◆ acl_change_stasis_cb()

static void acl_change_stasis_cb ( void *  data,
struct stasis_subscription sub,
struct stasis_message message 
)
static

Definition at line 1597 of file chan_iax2.c.

1599{
1601 return;
1602 }
1603
1604 ast_log(LOG_NOTICE, "Reloading chan_iax2 in response to ACL change event.\n");
1605 reload_config(1);
1606}

References ast_log, ast_named_acl_change_type(), LOG_NOTICE, and reload_config().

Referenced by acl_change_stasis_subscribe(), and rtp_reload().

◆ acl_change_stasis_subscribe()

static void acl_change_stasis_subscribe ( void  )
static

◆ acl_change_stasis_unsubscribe()

static void acl_change_stasis_unsubscribe ( void  )
static

Definition at line 1565 of file chan_iax2.c.

References acl_change_sub, and stasis_unsubscribe_and_join().

Referenced by __unload_module().

◆ add_calltoken_ignore()

static int add_calltoken_ignore ( const char *  addr)
static

Definition at line 2881 of file chan_iax2.c.

2882{
2883 struct addr_range tmp;
2884 struct addr_range *addr_range = NULL;
2885 struct ast_ha *ha = NULL;
2886 int error = 0;
2887
2888 if (ast_strlen_zero(addr)) {
2889 ast_log(LOG_WARNING, "invalid calltokenoptional (null)\n");
2890 return -1;
2891 }
2892
2893 ha = ast_append_ha("permit", addr, NULL, &error);
2894
2895 /* check for valid config information */
2896 if (error) {
2897 ast_log(LOG_WARNING, "Error %d creating calltokenoptional entry %s\n", error, addr);
2898 return -1;
2899 }
2900
2901 ast_copy_ha(ha, &tmp.ha);
2902 /* find or create the addr_range */
2905 addr_range->delme = 0;
2907 } else if ((addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
2908 /* copy over config data into addr_range object */
2909 ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible */
2911 } else {
2912 ast_free_ha(ha);
2913 return -1;
2914 }
2915
2916 ast_free_ha(ha);
2917 ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
2918
2919 return 0;
2920}

References ast_ha::addr, ao2_alloc, ao2_find, ao2_link, ao2_lock, ao2_ref, ao2_unlock, ast_append_ha(), ast_copy_ha(), ast_free_ha(), ast_log, ast_strlen_zero(), calltoken_ignores, addr_range::delme, error(), addr_range::ha, LOG_WARNING, NULL, and OBJ_POINTER.

Referenced by set_config().

◆ add_empty_calltoken_ie()

static void add_empty_calltoken_ie ( struct chan_iax2_pvt pvt,
struct iax_ie_data ied 
)
static

Definition at line 4911 of file chan_iax2.c.

4912{
4913 /* first make sure their are two empty bytes left in ied->buf */
4914 if (pvt && ied && (2 < ((int) sizeof(ied->buf) - ied->pos))) {
4915 ied->buf[ied->pos++] = IAX_IE_CALLTOKEN; /* type */
4916 ied->buf[ied->pos++] = 0; /* data size, ZERO in this case */
4917 pvt->calltoken_ie_len = 2;
4918 }
4919}

References iax_ie_data::buf, chan_iax2_pvt::calltoken_ie_len, IAX_IE_CALLTOKEN, and iax_ie_data::pos.

Referenced by cache_get_callno_locked(), iax2_call(), iax2_do_register(), iax2_poke_peer(), and registry_rerequest().

◆ addr_range_cmp_cb()

static int addr_range_cmp_cb ( void *  obj,
void *  arg,
int  flags 
)
static

Definition at line 2537 of file chan_iax2.c.

2538{
2539 struct addr_range *lim1 = obj, *lim2 = arg;
2540 return (!(ast_sockaddr_cmp_addr(&lim1->ha.addr, &lim2->ha.addr)) &&
2541 !(ast_sockaddr_cmp_addr(&lim1->ha.netmask, &lim2->ha.netmask))) ?
2542 CMP_MATCH | CMP_STOP : 0;
2543}

References ast_ha::addr, ast_sockaddr_cmp_addr(), CMP_MATCH, CMP_STOP, addr_range::ha, and ast_ha::netmask.

Referenced by load_objects().

◆ addr_range_delme_cb()

static int addr_range_delme_cb ( void *  obj,
void *  arg,
int  flags 
)
static

Definition at line 2524 of file chan_iax2.c.

2525{
2526 struct addr_range *lim = obj;
2527 lim->delme = 1;
2528 return 0;
2529}

References addr_range::delme.

Referenced by set_config_destroy().

◆ addr_range_hash_cb()

static int addr_range_hash_cb ( const void *  obj,
const int  flags 
)
static

Definition at line 2531 of file chan_iax2.c.

2532{
2533 const struct addr_range *lim = obj;
2534 return abs(ast_sockaddr_hash(&lim->ha.addr));
2535}

References abs, ast_ha::addr, ast_sockaddr_hash(), and addr_range::ha.

Referenced by load_objects().

◆ addr_range_match_address_cb()

static int addr_range_match_address_cb ( void *  obj,
void *  arg,
int  flags 
)
static

Definition at line 2561 of file chan_iax2.c.

2562{
2563 struct addr_range *addr_range = obj;
2564 struct ast_sockaddr *addr = arg;
2565 struct ast_sockaddr tmp_addr;
2566
2567 ast_sockaddr_apply_netmask(addr, &addr_range->ha.netmask, &tmp_addr);
2568
2569 if (!ast_sockaddr_cmp_addr(&tmp_addr, &addr_range->ha.addr)) {
2570 return CMP_MATCH | CMP_STOP;
2571 }
2572 return 0;
2573}

References ast_ha::addr, ast_sockaddr_apply_netmask(), ast_sockaddr_cmp_addr(), CMP_MATCH, CMP_STOP, addr_range::ha, and ast_ha::netmask.

Referenced by calltoken_required(), and set_peercnt_limit().

◆ apply_context()

static int apply_context ( struct iax2_context con,
const char *  context 
)
static

Definition at line 7929 of file chan_iax2.c.

7930{
7931 while(con) {
7932 if (!strcmp(con->context, context) || !strcmp(con->context, "*"))
7933 return -1;
7934 con = con->next;
7935 }
7936 return 0;
7937}

References iax2_context::context, and iax2_context::next.

Referenced by check_access().

◆ ast_cli_netstats()

static int ast_cli_netstats ( struct mansession s,
int  fd,
int  limit_fmt 
)
static

Definition at line 7630 of file chan_iax2.c.

7631{
7632 int x;
7633 int numchans = 0;
7634 char first_message[10] = { 0, };
7635 char last_message[10] = { 0, };
7636#define ACN_FORMAT1 "%-24.25s %4u %4d %4d %5d %3d %5d %4d %6d %4d %4d %5d %3d %5d %4d %6d %s%s %4s%s\n"
7637#define ACN_FORMAT2 "%s %u %d %d %d %d %d %d %d %d %d %d %d %d %d %d %s%s %s%s\n"
7638 for (x = 0; x < ARRAY_LEN(iaxs); x++) {
7639 ast_mutex_lock(&iaxsl[x]);
7640 if (iaxs[x]) {
7641 int localjitter, localdelay, locallost, locallosspct, localdropped, localooo;
7642 jb_info jbinfo;
7643 iax_frame_subclass2str(iaxs[x]->first_iax_message & ~MARK_IAX_SUBCLASS_TX, first_message, sizeof(first_message));
7644 iax_frame_subclass2str(iaxs[x]->last_iax_message & ~MARK_IAX_SUBCLASS_TX, last_message, sizeof(last_message));
7645
7647 jb_getinfo(iaxs[x]->jb, &jbinfo);
7648 localjitter = jbinfo.jitter;
7649 localdelay = jbinfo.current - jbinfo.min;
7650 locallost = jbinfo.frames_lost;
7651 locallosspct = jbinfo.losspct/1000;
7652 localdropped = jbinfo.frames_dropped;
7653 localooo = jbinfo.frames_ooo;
7654 } else {
7655 localjitter = -1;
7656 localdelay = 0;
7657 locallost = -1;
7658 locallosspct = -1;
7659 localdropped = 0;
7660 localooo = -1;
7661 }
7662 if (s)
7663 astman_append(s, limit_fmt ? ACN_FORMAT1 : ACN_FORMAT2,
7664 iaxs[x]->owner ? ast_channel_name(iaxs[x]->owner) : "(None)",
7665 iaxs[x]->pingtime,
7666 localjitter,
7667 localdelay,
7668 locallost,
7669 locallosspct,
7670 localdropped,
7671 localooo,
7672 iaxs[x]->frames_received/1000,
7673 iaxs[x]->remote_rr.jitter,
7674 iaxs[x]->remote_rr.delay,
7675 iaxs[x]->remote_rr.losscnt,
7676 iaxs[x]->remote_rr.losspct,
7677 iaxs[x]->remote_rr.dropped,
7678 iaxs[x]->remote_rr.ooo,
7679 iaxs[x]->remote_rr.packets/1000,
7680 (iaxs[x]->first_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
7681 first_message,
7682 (iaxs[x]->last_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
7683 last_message);
7684 else
7685 ast_cli(fd, limit_fmt ? ACN_FORMAT1 : ACN_FORMAT2,
7686 iaxs[x]->owner ? ast_channel_name(iaxs[x]->owner) : "(None)",
7687 iaxs[x]->pingtime,
7688 localjitter,
7689 localdelay,
7690 locallost,
7691 locallosspct,
7692 localdropped,
7693 localooo,
7694 iaxs[x]->frames_received/1000,
7695 iaxs[x]->remote_rr.jitter,
7696 iaxs[x]->remote_rr.delay,
7697 iaxs[x]->remote_rr.losscnt,
7698 iaxs[x]->remote_rr.losspct,
7699 iaxs[x]->remote_rr.dropped,
7700 iaxs[x]->remote_rr.ooo,
7701 iaxs[x]->remote_rr.packets/1000,
7702 (iaxs[x]->first_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
7703 first_message,
7704 (iaxs[x]->last_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
7705 last_message);
7706 numchans++;
7707 }
7709 }
7710
7711 return numchans;
7712}

References ACN_FORMAT1, ACN_FORMAT2, ARRAY_LEN, ast_channel_name(), ast_cli(), ast_mutex_lock, ast_mutex_unlock, ast_test_flag64, astman_append(), jb_info::current, iax_rr::delay, iax_rr::dropped, chan_iax2_pvt::first_iax_message, jb_info::frames_dropped, jb_info::frames_lost, jb_info::frames_ooo, chan_iax2_pvt::frames_received, iax_frame_subclass2str(), IAX_USEJITTERBUF, iaxs, iaxsl, jb_getinfo(), iax_rr::jitter, jb_info::jitter, chan_iax2_pvt::last_iax_message, iax_rr::losscnt, iax_rr::losspct, jb_info::losspct, MARK_IAX_SUBCLASS_TX, jb_info::min, iax_rr::ooo, chan_iax2_pvt::owner, iax_rr::packets, chan_iax2_pvt::pingtime, and chan_iax2_pvt::remote_rr.

Referenced by handle_cli_iax2_show_netstats(), and manager_iax2_show_netstats().

◆ ast_iax2_new()

static struct ast_channel * ast_iax2_new ( int  callno,
int  state,
iax2_format  capability,
struct iax2_codec_pref prefs,
const struct ast_assigned_ids assignedids,
const struct ast_channel requestor,
unsigned int  cachable 
)
static

Create new call, interface with the PBX core.

Definition at line 5959 of file chan_iax2.c.

5962{
5963 struct ast_channel *tmp = NULL;
5964 struct chan_iax2_pvt *i;
5965 struct iax2_peer *peer;
5966 struct ast_variable *v = NULL;
5967 struct ast_format_cap *native;
5968 struct ast_format *tmpfmt;
5969 ast_callid callid;
5970 char *peer_name = NULL;
5971
5972 if (!(i = iaxs[callno])) {
5973 ast_log(LOG_WARNING, "No IAX2 pvt found for callno '%d' !\n", callno);
5974 return NULL;
5975 }
5976
5977 if (!capability) {
5978 ast_log(LOG_WARNING, "No formats specified for call to: IAX2/%s-%d\n",
5979 i->host, i->callno);
5980 return NULL;
5981 }
5983 if (!native) {
5984 return NULL;
5985 }
5986 if (iax2_codec_pref_best_bitfield2cap(capability, prefs, native)
5987 || !ast_format_cap_count(native)) {
5988 ast_log(LOG_WARNING, "No requested formats available for call to: IAX2/%s-%d\n",
5989 i->host, i->callno);
5990 ao2_ref(native, -1);
5991 return NULL;
5992 }
5993
5994 if (!ast_strlen_zero(i->peer)) {
5995 peer_name = ast_strdupa(i->peer);
5996 } else if (!ast_strlen_zero(i->host)) {
5997 peer_name = ast_strdupa(i->host);
5998 }
5999
6000 /* Don't hold call lock while making a channel or looking up a peer */
6001 ast_mutex_unlock(&iaxsl[callno]);
6002
6003 if (!ast_strlen_zero(peer_name)) {
6004 peer = find_peer(peer_name, 1);
6005 if (peer && peer->endpoint) {
6007 i->accountcode, i->exten, i->context, assignedids, requestor,
6008 i->amaflags, peer->endpoint, "IAX2/%s-%d", i->host, i->callno);
6009 }
6010 ao2_cleanup(peer);
6011 }
6012
6013 if (!tmp) {
6014 tmp = ast_channel_alloc(1, state, i->cid_num, i->cid_name, i->accountcode,
6015 i->exten, i->context, assignedids, requestor, i->amaflags, "IAX2/%s-%d",
6016 i->host, i->callno);
6017 }
6018
6019 ast_mutex_lock(&iaxsl[callno]);
6020 if (i != iaxs[callno]) {
6021 if (tmp) {
6022 /* unlock and relock iaxsl[callno] to preserve locking order */
6023 ast_mutex_unlock(&iaxsl[callno]);
6024 ast_channel_unlock(tmp);
6025 tmp = ast_channel_release(tmp);
6026 ast_mutex_lock(&iaxsl[callno]);
6027 }
6028 ao2_ref(native, -1);
6029 return NULL;
6030 }
6031 if (!tmp) {
6032 ao2_ref(native, -1);
6033 return NULL;
6034 }
6035
6037
6038 if ((callid = iaxs[callno]->callid)) {
6039 ast_channel_callid_set(tmp, callid);
6040 }
6041
6043
6044 /* We can support any format by default, until we get restricted */
6045 ast_channel_nativeformats_set(tmp, native);
6046 tmpfmt = ast_format_cap_get_format(native, 0);
6047
6048 ast_channel_set_readformat(tmp, tmpfmt);
6049 ast_channel_set_rawreadformat(tmp, tmpfmt);
6050 ast_channel_set_writeformat(tmp, tmpfmt);
6051 ast_channel_set_rawwriteformat(tmp, tmpfmt);
6052
6053 ao2_ref(tmpfmt, -1);
6054 ao2_ref(native, -1);
6055
6057
6058 if (!ast_strlen_zero(i->parkinglot))
6059 ast_channel_parkinglot_set(tmp, i->parkinglot);
6060 /* Don't use ast_set_callerid() here because it will
6061 * generate a NewCallerID event before the NewChannel event */
6062 if (!ast_strlen_zero(i->ani)) {
6065 } else if (!ast_strlen_zero(i->cid_num)) {
6068 }
6070 if (!ast_strlen_zero(i->rdnis)) {
6073 }
6079 if (!ast_strlen_zero(i->language))
6080 ast_channel_language_set(tmp, i->language);
6082 ast_channel_accountcode_set(tmp, i->accountcode);
6083 if (i->amaflags)
6087 if (i->adsi)
6089 else
6091 i->owner = tmp;
6092 i->capability = capability;
6093
6094 if (!cachable) {
6096 }
6097
6098 /* Set inherited variables */
6099 if (i->vars) {
6100 for (v = i->vars ; v ; v = v->next)
6102 }
6103 if (i->iaxvars) {
6104 struct ast_datastore *variablestore;
6105 struct ast_variable *var, *prev = NULL;
6106 AST_LIST_HEAD(, ast_var_t) *varlist;
6107 ast_debug(1, "Loading up the channel with IAXVARs\n");
6108 varlist = ast_calloc(1, sizeof(*varlist));
6110 if (variablestore && varlist) {
6111 variablestore->data = varlist;
6112 variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
6113 AST_LIST_HEAD_INIT(varlist);
6114 for (var = i->iaxvars; var; var = var->next) {
6115 struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
6116 if (prev)
6117 ast_free(prev);
6118 prev = var;
6119 if (!newvar) {
6120 /* Don't abort list traversal, as this would leave i->iaxvars in an inconsistent state. */
6121 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
6122 } else {
6123 AST_LIST_INSERT_TAIL(varlist, newvar, entries);
6124 }
6125 }
6126 if (prev)
6127 ast_free(prev);
6128 i->iaxvars = NULL;
6129 ast_channel_datastore_add(i->owner, variablestore);
6130 } else {
6131 if (variablestore) {
6132 ast_datastore_free(variablestore);
6133 }
6134 if (varlist) {
6135 ast_free(varlist);
6136 }
6137 }
6138 }
6139
6141 ast_channel_unlock(tmp);
6142
6143 if (state != AST_STATE_DOWN) {
6144 if (ast_pbx_start(tmp)) {
6145 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", ast_channel_name(tmp));
6146 /* unlock and relock iaxsl[callno] to preserve locking order */
6147 ast_mutex_unlock(&iaxsl[callno]);
6148 ast_hangup(tmp);
6149 ast_mutex_lock(&iaxsl[callno]);
6150 return NULL;
6151 }
6152 }
6153
6155 return tmp;
6156}

References chan_iax2_pvt::accountcode, chan_iax2_pvt::adsi, chan_iax2_pvt::amaflags, chan_iax2_pvt::ani, ast_party_caller::ani, ast_party_caller::ani2, ao2_cleanup, ao2_ref, AST_ADSI_UNAVAILABLE, ast_calloc, ast_channel_adsicpe_set(), ast_channel_alloc, ast_channel_alloc_with_endpoint, ast_channel_amaflags_set(), ast_channel_caller(), ast_channel_callid_set(), ast_channel_context_set(), ast_channel_datastore_add(), ast_channel_dialed(), ast_channel_exten_set(), ast_channel_flags(), ast_channel_name(), ast_channel_nativeformats_set(), ast_channel_redirecting(), ast_channel_release(), ast_channel_set_rawreadformat(), ast_channel_set_rawwriteformat(), ast_channel_set_readformat(), ast_channel_set_writeformat(), ast_channel_stage_snapshot(), ast_channel_stage_snapshot_done(), ast_channel_tech_pvt_set(), ast_channel_tech_set(), ast_channel_unlock, ast_datastore_alloc, ast_datastore_free(), ast_debug, AST_FLAG_DISABLE_DEVSTATE_CACHE, ast_format_cap_alloc, ast_format_cap_count(), AST_FORMAT_CAP_FLAG_DEFAULT, ast_format_cap_get_format(), ast_free, ast_hangup(), AST_LIST_HEAD, AST_LIST_HEAD_INIT, AST_LIST_INSERT_TAIL, ast_log, ast_module_ref, ast_mutex_lock, ast_mutex_unlock, ast_pbx_start(), ast_set_flag, AST_STATE_DOWN, ast_strdup, ast_strdupa, ast_strlen_zero(), ast_var_assign, chan_iax2_pvt::calling_ani2, chan_iax2_pvt::calling_pres, chan_iax2_pvt::calling_tns, chan_iax2_pvt::calling_ton, chan_iax2_pvt::callno, CALLNO_TO_PTR, chan_iax2_pvt::capability, chan_iax2_pvt::cid_name, chan_iax2_pvt::cid_num, chan_iax2_pvt::context, ast_datastore::data, DATASTORE_INHERIT_FOREVER, chan_iax2_pvt::dnid, iax2_peer::endpoint, ast_var_t::entries, chan_iax2_pvt::exten, find_peer(), ast_party_redirecting::from, chan_iax2_pvt::host, iax2_codec_pref_best_bitfield2cap(), iax2_tech, iax2_variable_datastore_info, iaxs, iaxsl, chan_iax2_pvt::iaxvars, ast_party_caller::id, ast_datastore::inheritance, chan_iax2_pvt::language, LOG_ERROR, LOG_WARNING, ast_party_id::name, ast_variable::name, ast_variable::next, NULL, ast_party_id::number, ast_party_dialed::number, chan_iax2_pvt::owner, chan_iax2_pvt::parkinglot, pbx_builtin_setvar_helper(), chan_iax2_pvt::peer, chan_iax2_pvt::peeradsicpe, ast_party_number::plan, ast_party_name::presentation, ast_party_number::presentation, chan_iax2_pvt::rdnis, ast_module_info::self, ast_party_number::str, ast_party_dialed::str, ast_party_dialed::transit_network_select, ast_party_number::valid, ast_variable::value, var, and chan_iax2_pvt::vars.

Referenced by iax2_request(), and socket_process_helper().

◆ AST_MODULE_SELF_SYM()

struct ast_module * AST_MODULE_SELF_SYM ( void  )

Definition at line 15138 of file chan_iax2.c.

◆ attempt_transmit()

static int attempt_transmit ( const void *  data)
static

Definition at line 3717 of file chan_iax2.c.

3718{
3719#ifdef SCHED_MULTITHREADED
3721#endif
3722 __attempt_transmit(data);
3723 return 0;
3724}

References __attempt_transmit(), ast_frame::data, and schedule_action.

Referenced by __attempt_transmit(), and transmit_frame().

◆ auth_fail()

static int auth_fail ( int  callno,
int  failcode 
)
static

Definition at line 9511 of file chan_iax2.c.

9512{
9513 /* Schedule sending the authentication failure in one second, to prevent
9514 guessing */
9515 if (iaxs[callno]) {
9516 iaxs[callno]->authfail = failcode;
9517 if (delayreject) {
9518 iaxs[callno]->authid = iax2_sched_replace(iaxs[callno]->authid,
9519 sched, 1000, auth_reject, (void *)(long)callno);
9520 } else
9521 auth_reject((void *)(long)callno);
9522 }
9523 return 0;
9524}

References auth_reject(), chan_iax2_pvt::authfail, chan_iax2_pvt::authid, delayreject, iax2_sched_replace(), and iaxs.

Referenced by socket_process_helper().

◆ auth_method_names()

static char * auth_method_names ( int  authmethods,
char *restrict  buf 
)
static

Get names of all auth methods.

Parameters
Bitfield of auth methods
[out]bufBuffer into which to write the names. Must be of size AUTH_METHOD_NAMES_BUFSIZE.
Returns
Auth methods name

Definition at line 452 of file chan_iax2.c.

453{
454 char *pos = buf;
455
456 *pos = '\0';
457
458 if (authmethods & IAX_AUTH_RSA) {
459 pos += sprintf(pos, "|RSA");
460 }
461 if (authmethods & IAX_AUTH_MD5) {
462 pos += sprintf(pos, "|MD5");
463 }
464 if (authmethods & IAX_AUTH_PLAINTEXT) {
465 pos += sprintf(pos, "|plaintext");
466 }
467
468 if (pos == buf) { /* No auth methods */
469 strcpy(buf, "none");
470 return buf;
471 }
472
473 return buf + 1; /* Skip leading | */
474}

References buf, IAX_AUTH_MD5, IAX_AUTH_PLAINTEXT, and IAX_AUTH_RSA.

Referenced by socket_process_helper().

◆ auth_reject()

static int auth_reject ( const void *  data)
static

Definition at line 9497 of file chan_iax2.c.

9498{
9499 int callno = (int)(long)(data);
9500 ast_mutex_lock(&iaxsl[callno]);
9501 if (iaxs[callno])
9502 iaxs[callno]->authid = -1;
9503 ast_mutex_unlock(&iaxsl[callno]);
9504#ifdef SCHED_MULTITHREADED
9505 if (schedule_action(__auth_reject, data))
9506#endif
9507 __auth_reject(data);
9508 return 0;
9509}

References __auth_reject(), ast_mutex_lock, ast_mutex_unlock, chan_iax2_pvt::authid, iaxs, iaxsl, and schedule_action.

Referenced by auth_fail().

◆ authenticate()

static int authenticate ( const char *  challenge,
const char *  secret,
const char *  keyn,
int  authmethods,
struct iax_ie_data ied,
struct ast_sockaddr addr,
struct chan_iax2_pvt pvt 
)
static

Definition at line 8518 of file chan_iax2.c.

8519{
8520 int res = -1;
8521 int x;
8522 if (!ast_strlen_zero(keyn)) {
8523 if (!(authmethods & IAX_AUTH_RSA)) {
8524 if (ast_strlen_zero(secret)) {
8525 ast_log(LOG_WARNING, "Asked to authenticate to %s with an RSA key, but they don't allow RSA authentication\n", ast_sockaddr_stringify_addr(addr));
8526 }
8527 } else if (ast_strlen_zero(challenge)) {
8528 ast_log(LOG_WARNING, "No challenge provided for RSA authentication to %s\n", ast_sockaddr_stringify_addr(addr));
8529 } else {
8530 char sig[256];
8531 struct ast_key *key;
8532 key = ast_key_get(keyn, AST_KEY_PRIVATE);
8533 if (!key) {
8534 ast_log(LOG_WARNING, "Unable to find private key '%s'\n", keyn);
8535 } else {
8536 if (ast_sign(key, (char*)challenge, sig)) {
8537 ast_log(LOG_WARNING, "Unable to sign challenge with key\n");
8538 res = -1;
8539 } else {
8541 if (pvt) {
8543 }
8544 res = 0;
8545 }
8546 }
8547
8548 if (pvt && !ast_strlen_zero(secret)) {
8549 struct MD5Context md5;
8550 unsigned char digest[16];
8551
8552 MD5Init(&md5);
8553 MD5Update(&md5, (unsigned char *) challenge, strlen(challenge));
8554 MD5Update(&md5, (unsigned char *) secret, strlen(secret));
8555 MD5Final(digest, &md5);
8556
8557 build_encryption_keys(digest, pvt);
8558 }
8559 }
8560 }
8561 /* Fall back */
8562 if (res && !ast_strlen_zero(secret)) {
8563 if ((authmethods & IAX_AUTH_MD5) && !ast_strlen_zero(challenge)) {
8564 struct MD5Context md5;
8565 unsigned char digest[16];
8566 char digres[128];
8567 MD5Init(&md5);
8568 MD5Update(&md5, (unsigned char *)challenge, strlen(challenge));
8569 MD5Update(&md5, (unsigned char *)secret, strlen(secret));
8570 MD5Final(digest, &md5);
8571 /* If they support md5, authenticate with it. */
8572 for (x=0;x<16;x++)
8573 sprintf(digres + (x << 1), "%02hhx", digest[x]); /* safe */
8574 if (pvt) {
8575 build_encryption_keys(digest, pvt);
8577 }
8579 res = 0;
8580 } else if (authmethods & IAX_AUTH_PLAINTEXT) {
8581 iax_ie_append_str(ied, IAX_IE_PASSWORD, secret);
8582 if (pvt) {
8584 }
8585 res = 0;
8586 } else
8587 ast_log(LOG_WARNING, "No way to send secret to peer '%s' (their methods: %d)\n", ast_sockaddr_stringify_addr(addr), authmethods);
8588 }
8589 return res;
8590}

References ast_key_get(), AST_KEY_PRIVATE, ast_log, ast_sign(), ast_sockaddr_stringify_addr(), ast_strlen_zero(), build_encryption_keys(), challenge(), chan_iax2_pvt::eff_auth_method, IAX_AUTH_MD5, IAX_AUTH_PLAINTEXT, IAX_AUTH_RSA, iax_ie_append_str(), IAX_IE_MD5_RESULT, IAX_IE_PASSWORD, IAX_IE_RSA_RESULT, LOG_WARNING, md5(), MD5Final(), MD5Init(), and MD5Update().

Referenced by authenticate_reply(), and registry_rerequest().

◆ authenticate_reply()

static int authenticate_reply ( struct chan_iax2_pvt p,
struct ast_sockaddr addr,
struct iax_ies ies,
const char *  override,
const char *  okey 
)
static
Note
This function calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno, so do not call this function with a pvt lock held.

Definition at line 8596 of file chan_iax2.c.

8597{
8598 struct iax2_peer *peer = NULL;
8599 /* Start pessimistic */
8600 int res = -1;
8601 int authmethods = 0;
8602 struct iax_ie_data ied;
8603 uint16_t callno = p->callno;
8604
8605 memset(&ied, 0, sizeof(ied));
8606
8607 if (ies->username)
8608 ast_string_field_set(p, username, ies->username);
8609 if (ies->challenge)
8611 if (ies->authmethods)
8612 authmethods = ies->authmethods;
8613 if (authmethods & IAX_AUTH_MD5)
8615 else
8616 p->encmethods = 0;
8617
8618 /* Check for override RSA authentication first */
8619 if (!ast_strlen_zero(override) || !ast_strlen_zero(okey)) {
8620 /* Normal password authentication */
8621 res = authenticate(p->challenge, override, okey, authmethods, &ied, addr, p);
8622 } else {
8623 struct ao2_iterator i = ao2_iterator_init(peers, 0);
8624 while ((peer = ao2_iterator_next(&i))) {
8625 struct ast_sockaddr peer_addr;
8626 struct ast_sockaddr tmp_sockaddr1;
8627 struct ast_sockaddr tmp_sockaddr2;
8628
8629 ast_sockaddr_copy(&peer_addr, &peer->addr);
8630
8631 ast_sockaddr_apply_netmask(addr, &peer->mask, &tmp_sockaddr1);
8632 ast_sockaddr_apply_netmask(&peer_addr, &peer->mask, &tmp_sockaddr2);
8633
8634 if ((ast_strlen_zero(p->peer) || !strcmp(p->peer, peer->name))
8635 /* No peer specified at our end, or this is the peer */
8636 && (ast_strlen_zero(peer->username) || (!strcmp(peer->username, p->username)))
8637 /* No username specified in peer rule, or this is the right username */
8638 && (ast_sockaddr_isnull(&peer_addr) || !(ast_sockaddr_cmp_addr(&tmp_sockaddr1, &tmp_sockaddr2)))
8639 /* No specified host, or this is our host */
8640 ) {
8641 res = authenticate(p->challenge, peer->secret, peer->outkey, authmethods, &ied, addr, p);
8642 if (!res) {
8643 peer_unref(peer);
8644 break;
8645 }
8646 }
8647 peer_unref(peer);
8648 }
8650 if (!peer) {
8651 /* We checked our list and didn't find one. It's unlikely, but possible,
8652 that we're trying to authenticate *to* a realtime peer */
8653 const char *peer_name = ast_strdupa(p->peer);
8654 ast_mutex_unlock(&iaxsl[callno]);
8655 if ((peer = realtime_peer(peer_name, NULL))) {
8656 ast_mutex_lock(&iaxsl[callno]);
8657 if (!(p = iaxs[callno])) {
8658 peer_unref(peer);
8659 return -1;
8660 }
8661 res = authenticate(p->challenge, peer->secret,peer->outkey, authmethods, &ied, addr, p);
8662 peer_unref(peer);
8663 }
8664 if (!peer) {
8665 ast_mutex_lock(&iaxsl[callno]);
8666 if (!(p = iaxs[callno]))
8667 return -1;
8668 }
8669 }
8670 }
8671
8672 if (!(ies->authmethods & (IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT)) && (ies->authmethods & IAX_AUTH_RSA) && ast_strlen_zero(okey)) {
8673 /* If the only thing available is RSA, and we don't have an outkey, we can't do it... */
8674 ast_log(LOG_WARNING, "Call terminated. RSA authentication requires an outkey\n");
8675 return -1;
8676 }
8677
8678 if (ies->encmethods) {
8679 if (ast_strlen_zero(p->secret) &&
8681 ast_log(LOG_WARNING, "Call terminated. Encryption requested by peer but no secret available locally\n");
8682 return -1;
8683 }
8684 /* Don't even THINK about trying to encrypt or decrypt anything if we don't have valid keys, for some reason... */
8685 /* If either of these happens, it's our fault, not the user's. But we should abort rather than crash. */
8689 } else if (ast_test_flag64(iaxs[callno], IAX_FORCE_ENCRYPT)) {
8690 ast_log(LOG_NOTICE, "Call initiated without encryption while forceencryption=yes option is set\n");
8691 return -1; /* if force encryption is yes, and no encryption methods, then return -1 to hangup */
8692 }
8693 if (!res) {
8694 struct ast_datastore *variablestore;
8695 struct ast_variable *var, *prev = NULL;
8696 AST_LIST_HEAD(, ast_var_t) *varlist;
8697 varlist = ast_calloc(1, sizeof(*varlist));
8699 if (variablestore && varlist && p->owner) {
8700 variablestore->data = varlist;
8701 variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
8702 AST_LIST_HEAD_INIT(varlist);
8703 for (var = ies->vars; var; var = var->next) {
8704 struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
8705 if (prev)
8706 ast_free(prev);
8707 prev = var;
8708 if (!newvar) {
8709 /* Don't abort list traversal, as this would leave ies->vars in an inconsistent state. */
8710 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
8711 } else {
8712 AST_LIST_INSERT_TAIL(varlist, newvar, entries);
8713 }
8714 }
8715 if (prev)
8716 ast_free(prev);
8717 ies->vars = NULL;
8718 ast_channel_datastore_add(p->owner, variablestore);
8719 } else {
8720 if (p->owner)
8721 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
8722 if (variablestore)
8723 ast_datastore_free(variablestore);
8724 if (varlist)
8725 ast_free(varlist);
8726 }
8727 }
8728
8729 if (!res)
8730 res = send_command(p, AST_FRAME_IAX, IAX_COMMAND_AUTHREP, 0, ied.buf, ied.pos, -1);
8731 return res;
8732}

References iax2_peer::addr, ao2_iterator_destroy(), ao2_iterator_init(), ao2_iterator_next, ast_assert_return, ast_calloc, ast_channel_datastore_add(), ast_datastore_alloc, ast_datastore_free(), AST_FRAME_IAX, ast_free, AST_LIST_HEAD, AST_LIST_HEAD_INIT, AST_LIST_INSERT_TAIL, ast_log, ast_mutex_lock, ast_mutex_unlock, ast_set_flag64, ast_sockaddr_apply_netmask(), ast_sockaddr_cmp_addr(), ast_sockaddr_copy(), ast_sockaddr_isnull(), ast_strdupa, ast_string_field_set, ast_strlen_zero(), ast_test_flag64, ast_var_assign, authenticate(), iax2_peer::authmethods, iax_ies::authmethods, iax_ie_data::buf, chan_iax2_pvt::callno, chan_iax2_pvt::challenge, iax_ies::challenge, challenge(), ast_datastore::data, DATASTORE_INHERIT_FOREVER, chan_iax2_pvt::dcx, chan_iax2_pvt::ecx, chan_iax2_pvt::encmethods, iax_ies::encmethods, ast_var_t::entries, iax2_variable_datastore_info, IAX_AUTH_MD5, IAX_AUTH_PLAINTEXT, IAX_AUTH_RSA, IAX_COMMAND_AUTHREP, IAX_ENCRYPTED, IAX_FORCE_ENCRYPT, IAX_KEYPOPULATED, iaxs, iaxsl, ast_datastore::inheritance, invalid_key(), LOG_ERROR, LOG_NOTICE, LOG_WARNING, iax2_peer::mask, merge_encryption(), iax2_peer::name, NULL, iax2_peer::outkey, chan_iax2_pvt::owner, chan_iax2_pvt::peer, peer_unref(), iax_ie_data::pos, realtime_peer(), iax2_peer::secret, chan_iax2_pvt::secret, send_command(), iax2_peer::username, chan_iax2_pvt::username, iax_ies::username, var, and iax_ies::vars.

Referenced by socket_process_helper().

◆ authenticate_request()

static int authenticate_request ( int  call_num)
static
Precondition
iaxsl[call_num] is locked
Note
Since this function calls send_command_final(), the pvt struct for the given call number may disappear while executing this function.

Definition at line 8210 of file chan_iax2.c.

8211{
8212 struct iax_ie_data ied;
8213 int res = -1, authreq_restrict = 0;
8214 char challenge[10];
8215 struct chan_iax2_pvt *p = iaxs[call_num];
8216
8217 memset(&ied, 0, sizeof(ied));
8218
8219 /* If an AUTHREQ restriction is in place, make sure we can send an AUTHREQ back */
8221 struct iax2_user *user;
8222
8224 if (user) {
8225 if (user->curauthreq == user->maxauthreq)
8226 authreq_restrict = 1;
8227 else
8228 user->curauthreq++;
8229 user = user_unref(user);
8230 }
8231 }
8232
8233 /* If the AUTHREQ limit test failed, send back an error */
8234 if (authreq_restrict) {
8235 iax_ie_append_str(&ied, IAX_IE_CAUSE, "Unauthenticated call limit reached");
8237 send_command_final(p, AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied.buf, ied.pos, -1);
8238 return 0;
8239 }
8240
8242 if (p->authmethods & (IAX_AUTH_MD5 | IAX_AUTH_RSA)) {
8243 snprintf(challenge, sizeof(challenge), "%d", (int)ast_random());
8245 /* snprintf(p->challenge, sizeof(p->challenge), "%d", (int)ast_random()); */
8247 }
8248 if (p->encmethods)
8250
8252
8253 res = send_command(p, AST_FRAME_IAX, IAX_COMMAND_AUTHREQ, 0, ied.buf, ied.pos, -1);
8254
8255 if (p->encmethods)
8257
8258 return res;
8259}

References ao2_find, AST_CAUSE_CALL_REJECTED, AST_FRAME_IAX, ast_random(), ast_set_flag64, ast_string_field_set, ast_test_flag64, chan_iax2_pvt::authmethods, iax_ie_data::buf, chan_iax2_pvt::challenge, challenge(), chan_iax2_pvt::encmethods, IAX_AUTH_MD5, IAX_AUTH_RSA, IAX_COMMAND_AUTHREQ, IAX_COMMAND_REJECT, IAX_ENCRYPTED, iax_ie_append_byte(), iax_ie_append_short(), iax_ie_append_str(), IAX_IE_AUTHMETHODS, IAX_IE_CAUSE, IAX_IE_CAUSECODE, IAX_IE_CHALLENGE, IAX_IE_ENCRYPTION, IAX_IE_USERNAME, IAX_MAXAUTHREQ, iaxs, OBJ_KEY, iax_ie_data::pos, send_command(), send_command_final(), user_unref(), and chan_iax2_pvt::username.

Referenced by socket_process_helper().

◆ authenticate_verify()

static int authenticate_verify ( struct chan_iax2_pvt p,
struct iax_ies ies 
)
static

Definition at line 8261 of file chan_iax2.c.

8262{
8263 char requeststr[256];
8264 char md5secret[256] = "";
8265 char secret[256] = "";
8266 char rsasecret[256] = "";
8267 int res = -1;
8268 int x;
8269 struct iax2_user *user;
8270
8271 if (p->authrej) {
8272 return res;
8273 }
8274
8276 if (user) {
8278 ast_atomic_fetchadd_int(&user->curauthreq, -1);
8280 }
8281 ast_string_field_set(p, host, user->name);
8282 user = user_unref(user);
8283 }
8285 ast_log(LOG_WARNING, "Call Terminated, incoming call is unencrypted while force encrypt is enabled.\n");
8286 return res;
8287 }
8289 return res;
8290 if (ies->password)
8291 ast_copy_string(secret, ies->password, sizeof(secret));
8292 if (ies->md5_result)
8293 ast_copy_string(md5secret, ies->md5_result, sizeof(md5secret));
8294 if (ies->rsa_result)
8295 ast_copy_string(rsasecret, ies->rsa_result, sizeof(rsasecret));
8296 if ((p->authmethods & IAX_AUTH_RSA) && !ast_strlen_zero(rsasecret) && !ast_strlen_zero(p->inkeys)) {
8297 struct ast_key *key;
8298 char *keyn;
8299 char *tmpkey;
8300 char *stringp=NULL;
8301 if (!(tmpkey = ast_strdup(p->inkeys))) {
8302 ast_log(LOG_ERROR, "Unable to create a temporary string for parsing stored 'inkeys'\n");
8303 return res;
8304 }
8305 stringp = tmpkey;
8306 keyn = strsep(&stringp, ":");
8307 while(keyn) {
8308 key = ast_key_get(keyn, AST_KEY_PUBLIC);
8309 if (key && !ast_check_signature(key, p->challenge, rsasecret)) {
8310 res = 0;
8312 break;
8313 } else if (!key) {
8314 ast_log(LOG_WARNING, "Requested inkey '%s' for RSA authentication does not exist\n", keyn);
8315 }
8316 keyn = strsep(&stringp, ":");
8317 }
8318 ast_free(tmpkey);
8319 if (res && authdebug) {
8320 ast_log(LOG_WARNING, "No RSA public keys on file matched incoming call\n");
8321 }
8322 } else if (p->authmethods & IAX_AUTH_MD5) {
8323 struct MD5Context md5;
8324 unsigned char digest[16];
8325 char *tmppw, *stringp;
8326 tmppw = ast_strdupa(p->secret);
8327 stringp = tmppw;
8328 while((tmppw = strsep(&stringp, ";"))) {
8329 MD5Init(&md5);
8330 MD5Update(&md5, (unsigned char *)p->challenge, strlen(p->challenge));
8331 MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
8332 MD5Final(digest, &md5);
8333 /* If they support md5, authenticate with it. */
8334 for (x=0;x<16;x++)
8335 sprintf(requeststr + (x << 1), "%02hhx", digest[x]); /* safe */
8336 if (!strcasecmp(requeststr, md5secret)) {
8337 res = 0;
8339 break;
8340 } else if (authdebug) {
8341 ast_log(LOG_WARNING, "MD5 secret mismatch\n");
8342 }
8343 }
8344 } else if (p->authmethods & IAX_AUTH_PLAINTEXT) {
8345 if (!strcmp(secret, p->secret)) {
8346 res = 0;
8348 } else if (authdebug) {
8349 ast_log(LOG_WARNING, "Plaintext secret mismatch\n");
8350 }
8351 }
8352 return res;
8353}

References ao2_find, ast_atomic_fetchadd_int(), ast_check_signature(), ast_clear_flag64, ast_copy_string(), ast_free, ast_key_get(), AST_KEY_PUBLIC, ast_log, ast_strdup, ast_strdupa, ast_string_field_set, ast_strlen_zero(), ast_test_flag, ast_test_flag64, authdebug, chan_iax2_pvt::authmethods, chan_iax2_pvt::authrej, chan_iax2_pvt::challenge, chan_iax2_pvt::eff_auth_method, chan_iax2_pvt::encmethods, IAX_AUTH_MD5, IAX_AUTH_PLAINTEXT, IAX_AUTH_RSA, IAX_FORCE_ENCRYPT, IAX_MAXAUTHREQ, IAX_STATE_AUTHENTICATED, chan_iax2_pvt::inkeys, LOG_ERROR, LOG_WARNING, md5(), iax_ies::md5_result, MD5Final(), MD5Init(), MD5Update(), NULL, OBJ_KEY, iax_ies::password, iax_ies::rsa_result, iax2_user::secret, chan_iax2_pvt::secret, chan_iax2_pvt::state, strsep(), user_unref(), and chan_iax2_pvt::username.

Referenced by socket_process_helper().

◆ auto_congest()

static int auto_congest ( const void *  data)
static

Definition at line 4848 of file chan_iax2.c.

4849{
4850#ifdef SCHED_MULTITHREADED
4852#endif
4853 __auto_congest(data);
4854 return 0;
4855}

References __auto_congest(), ast_frame::data, and schedule_action.

Referenced by iax2_call().

◆ auto_hangup()

static int auto_hangup ( const void *  data)
static

Definition at line 9541 of file chan_iax2.c.

9542{
9543 int callno = (int)(long)(data);
9544 ast_mutex_lock(&iaxsl[callno]);
9545 if (iaxs[callno]) {
9546 iaxs[callno]->autoid = -1;
9547 }
9548 ast_mutex_unlock(&iaxsl[callno]);
9549#ifdef SCHED_MULTITHREADED
9550 if (schedule_action(__auto_hangup, data))
9551#endif
9552 __auto_hangup(data);
9553 return 0;
9554}

References __auto_hangup(), ast_mutex_lock, ast_mutex_unlock, chan_iax2_pvt::autoid, iaxs, iaxsl, and schedule_action.

Referenced by iax2_dprequest(), and iax2_provision().

◆ build_callno_limits()

static void build_callno_limits ( struct ast_variable v)
static

Definition at line 2826 of file chan_iax2.c.

2827{
2828 struct addr_range *addr_range = NULL;
2829 struct addr_range tmp;
2830 struct ast_ha *ha;
2831 int limit;
2832 int error;
2833 int found;
2834
2835 for (; v; v = v->next) {
2836 limit = -1;
2837 error = 0;
2838 found = 0;
2839 ha = ast_append_ha("permit", v->name, NULL, &error);
2840
2841 /* check for valid config information */
2842 if (error) {
2843 ast_log(LOG_ERROR, "Call number limit for %s could not be added, Invalid address range\n.", v->name);
2844 continue;
2845 } else if ((sscanf(v->value, "%d", &limit) != 1) || (limit < 0)) {
2846 ast_log(LOG_ERROR, "Call number limit for %s could not be added. Invalid limit %s\n.", v->name, v->value);
2847 ast_free_ha(ha);
2848 continue;
2849 }
2850
2851 ast_copy_ha(ha, &tmp.ha);
2852 /* find or create the addr_range */
2853 if ((addr_range = ao2_find(callno_limits, &tmp, OBJ_POINTER))) {
2855 found = 1;
2856 } else if (!(addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
2857 ast_free_ha(ha);
2858 return; /* out of memory */
2859 }
2860
2861 /* copy over config data into addr_range object */
2862 ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible for each limit */
2863 ast_free_ha(ha); /* cleanup the tmp ha */
2864 addr_range->limit = limit;
2865 addr_range->delme = 0;
2866
2867 /* cleanup */
2868 if (found) {
2870 } else {
2872 }
2873 ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
2874 }
2875}

References ao2_alloc, ao2_find, ao2_link, ao2_lock, ao2_ref, ao2_unlock, ast_append_ha(), ast_copy_ha(), ast_free_ha(), ast_log, callno_limits, addr_range::delme, error(), addr_range::ha, addr_range::limit, LOG_ERROR, ast_variable::name, ast_variable::next, NULL, OBJ_POINTER, and ast_variable::value.

Referenced by set_config().

◆ build_context()

static struct iax2_context * build_context ( const char *  context)
static

Definition at line 12892 of file chan_iax2.c.

12893{
12894 struct iax2_context *con;
12895
12896 if ((con = ast_calloc(1, sizeof(*con))))
12897 ast_copy_string(con->context, context, sizeof(con->context));
12898
12899 return con;
12900}

References ast_calloc, ast_copy_string(), and iax2_context::context.

Referenced by build_user().

◆ build_ecx_key()

static void build_ecx_key ( const unsigned char *  digest,
struct chan_iax2_pvt pvt 
)
static

Definition at line 6518 of file chan_iax2.c.

6519{
6520 /* it is required to hold the corresponding decrypt key to our encrypt key
6521 * in the pvt struct because queued frames occasionally need to be decrypted and
6522 * re-encrypted when updated for a retransmission */
6523 build_rand_pad(pvt->semirand, sizeof(pvt->semirand));
6524 ast_aes_set_encrypt_key(digest, &pvt->ecx);
6525 ast_aes_set_decrypt_key(digest, &pvt->mydcx);
6526}

References ast_aes_set_decrypt_key(), ast_aes_set_encrypt_key(), build_rand_pad(), chan_iax2_pvt::ecx, chan_iax2_pvt::mydcx, and chan_iax2_pvt::semirand.

Referenced by build_encryption_keys(), and iax2_key_rotate().

◆ build_encryption_keys()

static void build_encryption_keys ( const unsigned char *  digest,
struct chan_iax2_pvt pvt 
)
static

Definition at line 6512 of file chan_iax2.c.

6513{
6514 build_ecx_key(digest, pvt);
6515 ast_aes_set_decrypt_key(digest, &pvt->dcx);
6516}

References ast_aes_set_decrypt_key(), build_ecx_key(), and chan_iax2_pvt::dcx.

Referenced by authenticate(), and decrypt_frame().

◆ build_peer()

static struct iax2_peer * build_peer ( const char *  name,
struct ast_variable v,
struct ast_variable alt,
int  temponly 
)
static

Create peer structure based on configuration.

Definition at line 13041 of file chan_iax2.c.

13042{
13043 struct iax2_peer *peer = NULL;
13044 struct ast_acl_list *oldacl = NULL;
13045 int maskfound = 0;
13046 int found = 0;
13047 int firstpass = 1;
13048 int subscribe_acl_change = 0;
13049
13050 if (!temponly) {
13051 peer = ao2_find(peers, name, OBJ_KEY);
13052 if (peer && !ast_test_flag64(peer, IAX_DELME))
13053 firstpass = 0;
13054 }
13055
13056 if (peer) {
13057 found++;
13058 if (firstpass) {
13059 oldacl = peer->acl;
13060 peer->acl = NULL;
13061 }
13062 unlink_peer(peer);
13063 } else if ((peer = ao2_alloc(sizeof(*peer), peer_destructor))) {
13064 peer->expire = -1;
13065 peer->pokeexpire = -1;
13066 peer->sockfd = defaultsockfd;
13067 if (ast_string_field_init(peer, 32))
13068 peer = peer_unref(peer);
13069 if (!(peer->endpoint = ast_endpoint_create("IAX2", name))) {
13070 peer = peer_unref(peer);
13071 }
13072 }
13073
13074 if (peer) {
13075 if (firstpass) {
13079 peer->adsi = adsi;
13080 ast_string_field_set(peer, secret, "");
13081 if (!found) {
13083 ast_sockaddr_parse(&peer->addr, "0.0.0.0", 0);
13085 peer->expiry = min_reg_expire;
13086 }
13087 peer->prefs = prefs_global;
13089 peer->smoothing = 0;
13092 peer->maxcallno = 0;
13093 peercnt_modify((unsigned char) 0, 0, &peer->addr);
13095 ast_string_field_set(peer,context,"");
13096 ast_string_field_set(peer,peercontext,"");
13098 ast_string_field_set(peer, cid_name, "");
13099 ast_string_field_set(peer, cid_num, "");
13102 }
13103
13104 if (!v) {
13105 v = alt;
13106 alt = NULL;
13107 }
13108 while(v) {
13109 if (!strcasecmp(v->name, "secret")) {
13110 ast_string_field_set(peer, secret, v->value);
13111 } else if (!strcasecmp(v->name, "mailbox")) {
13112 ast_string_field_set(peer, mailbox, v->value);
13113 } else if (!strcasecmp(v->name, "mohinterpret")) {
13115 } else if (!strcasecmp(v->name, "mohsuggest")) {
13117 } else if (!strcasecmp(v->name, "dbsecret")) {
13118 ast_string_field_set(peer, dbsecret, v->value);
13119 } else if (!strcasecmp(v->name, "description")) {
13120 ast_string_field_set(peer, description, v->value);
13121 } else if (!strcasecmp(v->name, "trunk")) {
13123 if (ast_test_flag64(peer, IAX_TRUNK) && !timer) {
13124 ast_log(LOG_WARNING, "Unable to support trunking on peer '%s' without a timing interface\n", peer->name);
13126 }
13127 } else if (!strcasecmp(v->name, "auth")) {
13129 if (peer->authmethods & IAX_AUTH_PLAINTEXT) {
13130 ast_log(LOG_WARNING, "Auth method for peer '%s' is set to deprecated 'plaintext' at line %d of iax.conf\n", peer->name, v->lineno);
13131 }
13132 } else if (!strcasecmp(v->name, "encryption")) {
13134 if (!peer->encmethods) {
13136 }
13137 } else if (!strcasecmp(v->name, "forceencryption")) {
13138 if (ast_false(v->value)) {
13140 } else {
13142 if (peer->encmethods) {
13144 }
13145 }
13146 } else if (!strcasecmp(v->name, "transfer")) {
13147 if (!strcasecmp(v->value, "mediaonly")) {
13149 } else if (ast_true(v->value)) {
13151 } else
13153 } else if (!strcasecmp(v->name, "jitterbuffer")) {
13155 } else if (!strcasecmp(v->name, "host")) {
13156 if (!strcasecmp(v->value, "dynamic")) {
13157 /* They'll register with us */
13159 if (!found) {
13160 int peer_port = ast_sockaddr_port(&peer->addr);
13161 if (peer_port) {
13162 ast_sockaddr_set_port(&peer->defaddr, peer_port);
13163 }
13164 ast_sockaddr_setnull(&peer->addr);
13165 }
13166 } else {
13167 /* Non-dynamic. Make sure we become that way if we're not */
13168 AST_SCHED_DEL(sched, peer->expire);
13170 if (peer->dnsmgr) {
13171 // Make sure we refresh dnsmgr if we're using it
13173 } else {
13174 // Or just invalidate the address
13175 peer->addr.ss.ss_family = AST_AF_UNSPEC;
13176 }
13177 if (ast_dnsmgr_lookup(v->value, &peer->addr, &peer->dnsmgr, srvlookup ? "_iax._udp" : NULL)) {
13178