2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2006, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
21 * \brief Implementation of Inter-Asterisk eXchange Version 2
23 * \author Mark Spencer <markster@digium.com>
26 * \arg \ref Config_iax
28 * \ingroup channel_drivers
33 #include <sys/types.h>
36 #include <sys/socket.h>
37 #include <netinet/in.h>
38 #include <arpa/inet.h>
39 #include <netinet/in_systm.h>
40 #include <netinet/ip.h>
42 #include <sys/signal.h>
53 #include <sys/ioctl.h>
55 #include <linux/zaptel.h>
58 #endif /* __linux__ */
63 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
65 #include "asterisk/lock.h"
66 #include "asterisk/frame.h"
67 #include "asterisk/channel.h"
68 #include "asterisk/logger.h"
69 #include "asterisk/module.h"
70 #include "asterisk/pbx.h"
71 #include "asterisk/sched.h"
72 #include "asterisk/io.h"
73 #include "asterisk/config.h"
74 #include "asterisk/options.h"
75 #include "asterisk/cli.h"
76 #include "asterisk/translate.h"
77 #include "asterisk/md5.h"
78 #include "asterisk/cdr.h"
79 #include "asterisk/crypto.h"
80 #include "asterisk/acl.h"
81 #include "asterisk/manager.h"
82 #include "asterisk/callerid.h"
83 #include "asterisk/app.h"
84 #include "asterisk/astdb.h"
85 #include "asterisk/musiconhold.h"
86 #include "asterisk/features.h"
87 #include "asterisk/utils.h"
88 #include "asterisk/causes.h"
89 #include "asterisk/localtime.h"
90 #include "asterisk/aes.h"
91 #include "asterisk/dnsmgr.h"
92 #include "asterisk/devicestate.h"
93 #include "asterisk/netsock.h"
94 #include "asterisk/stringfields.h"
97 #include "iax2-parser.h"
98 #include "iax2-provision.h"
100 /* Define NEWJB to use the new channel independent jitterbuffer,
101 * otherwise, use the old jitterbuffer */
104 /* Define SCHED_MULTITHREADED to run the scheduler in a special
105 multithreaded mode. */
106 #define SCHED_MULTITHREADED
108 /* Define DEBUG_SCHED_MULTITHREADED to keep track of where each
109 thread is actually doing. */
110 #define DEBUG_SCHED_MULTITHREAD
113 #include "../jitterbuf.h"
116 #ifndef IPTOS_MINCOST
117 #define IPTOS_MINCOST 0x02
121 static int nochecksums = 0;
125 * Uncomment to try experimental IAX bridge optimization,
126 * designed to reduce latency when IAX calls cannot
127 * be trasnferred -- obsolete
130 /* #define BRIDGE_OPTIMIZATION */
133 #define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
134 #define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
136 #define DEFAULT_THREAD_COUNT 10
137 #define DEFAULT_RETRY_TIME 1000
138 #define MEMORY_SIZE 100
139 #define DEFAULT_DROP 3
140 /* Flag to use with trunk calls, keeping these calls high up. It halves our effective use
141 but keeps the division between trunked and non-trunked better. */
142 #define TRUNK_CALL_START 0x4000
144 #define DEBUG_SUPPORT
146 #define MIN_REUSE_TIME 60 /* Don't reuse a call number within 60 seconds */
148 /* Sample over last 100 units to determine historic jitter */
151 static struct ast_codec_pref prefs;
153 static const char desc[] = "Inter Asterisk eXchange (Ver 2)";
154 static const char tdesc[] = "Inter Asterisk eXchange Driver (Ver 2)";
156 static char context[80] = "default";
158 static char language[MAX_LANGUAGE] = "";
159 static char regcontext[AST_MAX_CONTEXT] = "";
161 static int max_retries = 4;
162 static int ping_time = 20;
163 static int lagrq_time = 10;
164 static int maxtrunkcall = TRUNK_CALL_START;
165 static int maxnontrunkcall = 1;
166 static int maxjitterbuffer=1000;
168 static int resyncthreshold=1000;
169 static int maxjitterinterps=10;
171 static int jittershrinkrate=2;
172 static int trunkfreq = 20;
173 static int authdebug = 1;
174 static int autokill = 0;
175 static int iaxcompat = 0;
177 static int iaxdefaultdpcache=10 * 60; /* Cache dialplan entries for 10 minutes by default */
179 static int iaxdefaulttimeout = 5; /* Default to wait no more than 5 seconds for a reply to come back */
183 static int min_reg_expire;
184 static int max_reg_expire;
186 static int timingfd = -1; /* Timing file descriptor */
188 static struct ast_netsock_list *netsock;
189 static int defaultsockfd = -1;
192 AST_MUTEX_DEFINE_STATIC(usecnt_lock);
194 int (*iax2_regfunk)(char *username, int onoff) = NULL;
197 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
199 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
200 ~AST_FORMAT_SLINEAR & \
204 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
208 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
212 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
213 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
214 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
216 static struct io_context *io;
217 static struct sched_context *sched;
219 static int iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
221 static int iax2_dropcount = DEFAULT_DROP;
223 static int iaxdebug = 0;
225 static int iaxtrunkdebug = 0;
227 static int test_losspct = 0;
229 static int test_late = 0;
230 static int test_resync = 0;
231 static int test_jit = 0;
232 static int test_jitpct = 0;
233 #endif /* IAXTESTS */
235 static char accountcode[AST_MAX_ACCOUNT_CODE];
236 static int amaflags = 0;
237 static int delayreject = 0;
238 static int iax2_encryption = 0;
240 static struct ast_flags globalflags = { 0 };
242 static pthread_t netthreadid = AST_PTHREADT_NULL;
243 static pthread_t schedthreadid = AST_PTHREADT_NULL;
244 AST_MUTEX_DEFINE_STATIC(sched_lock);
245 static int sched_halt = 0;
246 static ast_cond_t sched_cond;
249 IAX_STATE_STARTED = (1 << 0),
250 IAX_STATE_AUTHENTICATED = (1 << 1),
251 IAX_STATE_TBD = (1 << 2),
252 IAX_STATE_UNCHANGED = (1 << 3),
255 struct iax2_context {
256 char context[AST_MAX_CONTEXT];
257 struct iax2_context *next;
261 IAX_HASCALLERID = (1 << 0), /*!< CallerID has been specified */
262 IAX_DELME = (1 << 1), /*!< Needs to be deleted */
263 IAX_TEMPONLY = (1 << 2), /*!< Temporary (realtime) */
264 IAX_TRUNK = (1 << 3), /*!< Treat as a trunk */
265 IAX_NOTRANSFER = (1 << 4), /*!< Don't native bridge */
266 IAX_USEJITTERBUF = (1 << 5), /*!< Use jitter buffer */
267 IAX_DYNAMIC = (1 << 6), /*!< dynamic peer */
268 IAX_SENDANI = (1 << 7), /*!< Send ANI along with CallerID */
269 /* (1 << 8) is currently unused due to the deprecation of an old option. Go ahead, take it! */
270 IAX_ALREADYGONE = (1 << 9), /*!< Already disconnected */
271 IAX_PROVISION = (1 << 10), /*!< This is a provisioning request */
272 IAX_QUELCH = (1 << 11), /*!< Whether or not we quelch audio */
273 IAX_ENCRYPTED = (1 << 12), /*!< Whether we should assume encrypted tx/rx */
274 IAX_KEYPOPULATED = (1 << 13), /*!< Whether we have a key populated */
275 IAX_CODEC_USER_FIRST = (1 << 14), /*!< are we willing to let the other guy choose the codec? */
276 IAX_CODEC_NOPREFS = (1 << 15), /*!< Force old behaviour by turning off prefs */
277 IAX_CODEC_NOCAP = (1 << 16), /*!< only consider requested format and ignore capabilities*/
278 IAX_RTCACHEFRIENDS = (1 << 17), /*!< let realtime stay till your reload */
279 IAX_RTUPDATE = (1 << 18), /*!< Send a realtime update */
280 IAX_RTAUTOCLEAR = (1 << 19), /*!< erase me on expire */
281 IAX_FORCEJITTERBUF = (1 << 20), /*!< Force jitterbuffer, even when bridged to a channel that can take jitter */
282 IAX_RTIGNOREREGEXPIRE = (1 << 21), /*!< When using realtime, ignore registration expiration */
283 IAX_TRUNKTIMESTAMPS = (1 << 22) /*!< Send trunk timestamps */
286 static int global_rtautoclear = 120;
288 static int reload_config(void);
289 static int iax2_reload(int fd, int argc, char *argv[]);
298 char accountcode[AST_MAX_ACCOUNT_CODE];
299 char inkeys[80]; /*!< Key(s) this user can use to authenticate to us */
300 char language[MAX_LANGUAGE];
304 char cid_num[AST_MAX_EXTENSION];
305 char cid_name[AST_MAX_EXTENSION];
306 struct ast_codec_pref prefs;
308 struct iax2_context *contexts;
309 struct iax2_user *next;
310 struct ast_variable *vars;
318 char outkey[80]; /*!< What key we use to talk to this peer */
319 char context[AST_MAX_CONTEXT]; /*!< For transfers only */
320 char regexten[AST_MAX_EXTENSION]; /*!< Extension to register (if regcontext is used) */
321 char peercontext[AST_MAX_EXTENSION]; /*!< Context to pass to peer */
322 char mailbox[AST_MAX_EXTENSION]; /*!< Mailbox */
323 struct ast_codec_pref prefs;
324 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
325 struct sockaddr_in addr;
327 int sockfd; /*!< Socket to use for transmission */
331 /* Dynamic Registration fields */
332 struct sockaddr_in defaddr; /*!< Default address if there is one */
333 int authmethods; /*!< Authentication methods (IAX_AUTH_*) */
334 int encmethods; /*!< Encryption methods (IAX_ENCRYPT_*) */
335 char inkeys[80]; /*!< Key(s) this peer can use to authenticate to us */
337 /* Suggested caller id if registering */
338 char cid_num[AST_MAX_EXTENSION]; /*!< Default context (for transfer really) */
339 char cid_name[AST_MAX_EXTENSION]; /*!< Default context (for transfer really) */
341 int expire; /*!< Schedule entry for expiry */
342 int expiry; /*!< How soon to expire */
343 int capability; /*!< Capability */
344 char zonetag[80]; /*!< Time Zone */
347 int callno; /*!< Call number of POKE request */
348 int pokeexpire; /*!< When to expire poke */
349 int lastms; /*!< How long last response took (in ms), or -1 for no response */
350 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
352 int pokefreqok; /*!< How often to check if the host is up */
353 int pokefreqnotok; /*!< How often to check when the host has been determined to be down */
354 int historicms; /*!< How long recent average responses took */
355 int smoothing; /*!< Sample over how many units to determine historic ms */
358 struct iax2_peer *next;
361 #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
363 static struct iax2_trunk_peer {
366 struct sockaddr_in addr;
367 struct timeval txtrunktime; /*!< Transmit trunktime */
368 struct timeval rxtrunktime; /*!< Receive trunktime */
369 struct timeval lasttxtime; /*!< Last transmitted trunktime */
370 struct timeval trunkact; /*!< Last trunk activity */
371 unsigned int lastsent; /*!< Last sent time */
372 /* Trunk data and length */
373 unsigned char *trunkdata;
374 unsigned int trunkdatalen;
375 unsigned int trunkdataalloc;
376 struct iax2_trunk_peer *next;
381 AST_MUTEX_DEFINE_STATIC(tpeerlock);
383 struct iax_firmware {
384 struct iax_firmware *next;
388 struct ast_iax2_firmware_header *fwh;
393 REG_STATE_UNREGISTERED = 0,
396 REG_STATE_REGISTERED,
402 enum iax_transfer_state {
410 struct iax2_registry {
411 struct sockaddr_in addr; /*!< Who we connect to for registration purposes */
413 char secret[80]; /*!< Password or key name in []'s */
415 int expire; /*!< Sched ID of expiration */
416 int refresh; /*!< How often to refresh */
417 enum iax_reg_state regstate;
418 int messages; /*!< Message count */
419 int callno; /*!< Associated call number if applicable */
420 struct sockaddr_in us; /*!< Who the server thinks we are */
421 struct iax2_registry *next;
424 static struct iax2_registry *registrations;
426 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
427 #define MIN_RETRY_TIME 100
428 #define MAX_RETRY_TIME 10000
430 #define MAX_JITTER_BUFFER 50
431 #define MIN_JITTER_BUFFER 10
433 #define DEFAULT_TRUNKDATA 640 * 10 /*!< 40ms, uncompressed linear * 10 channels */
434 #define MAX_TRUNKDATA 640 * 200 /*!< 40ms, uncompressed linear * 200 channels */
436 #define MAX_TIMESTAMP_SKEW 160 /*!< maximum difference between actual and predicted ts for sending */
438 /* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
439 #define TS_GAP_FOR_JB_RESYNC 5000
441 /* If we have more than this much excess real jitter buffer, shrink it. */
442 static int max_jitter_buffer = MAX_JITTER_BUFFER;
443 /* If we have less than this much excess real jitter buffer, enlarge it. */
444 static int min_jitter_buffer = MIN_JITTER_BUFFER;
446 static int iaxthreadcount = DEFAULT_THREAD_COUNT;
458 struct chan_iax2_pvt {
459 /*! Socket to send/receive on for this call */
461 /*! Last received voice format */
463 /*! Last received video format */
465 /*! Last sent voice format */
467 /*! Last sent video format */
469 /*! What we are capable of sending */
471 /*! Last received timestamp */
473 /*! Last sent timestamp - never send the same timestamp twice in a single call */
474 unsigned int lastsent;
475 /*! Next outgoing timestamp if everything is good */
476 unsigned int nextpred;
477 /*! True if the last voice we transmitted was not silence/CNG */
480 unsigned int pingtime;
481 /*! Max time for initial response */
484 struct sockaddr_in addr;
485 struct ast_codec_pref prefs;
486 /*! Our call number */
487 unsigned short callno;
489 unsigned short peercallno;
490 /*! Peer selected format */
492 /*! Peer capability */
494 /*! timeval that we base our transmission on */
495 struct timeval offset;
496 /*! timeval that we base our delivery on */
497 struct timeval rxcore;
499 /*! The jitterbuffer */
501 /*! active jb read scheduler id */
504 /*! Historical delivery time */
505 int history[MEMORY_SIZE];
506 /*! Current base jitterbuffer */
508 /*! Current jitter measure */
510 /*! Historic jitter value */
515 /*! Error, as discovered by the manager */
517 /*! Owner if we have one */
518 struct ast_channel *owner;
519 /*! What's our state? */
520 struct ast_flags state;
521 /*! Expiry (optional) */
523 /*! Next outgoing sequence number */
524 unsigned char oseqno;
525 /*! Next sequence number they have not yet acknowledged */
526 unsigned char rseqno;
527 /*! Next incoming sequence number */
528 unsigned char iseqno;
529 /*! Last incoming sequence number we have acknowledged */
530 unsigned char aseqno;
533 /*! Default Context */
535 /*! Caller ID if available */
538 /*! Hidden Caller ID (i.e. ANI) if appropriate */
544 /*! Requested Extension */
545 char exten[AST_MAX_EXTENSION];
546 /*! Expected Username */
548 /*! Expected Secret */
550 /*! permitted authentication methods */
552 /*! permitted encryption methods */
556 /*! Public keys permitted keys for incoming authentication */
558 /*! Private key for outgoing authentication */
560 /*! Encryption AES-128 Key */
562 /*! Decryption AES-128 Key */
564 /*! 32 bytes of semi-random data */
565 unsigned char semirand[32];
566 /*! Preferred language */
567 char language[MAX_LANGUAGE];
568 /*! Hostname/peername for naming purposes */
570 /*! Associated registry */
571 struct iax2_registry *reg;
572 /*! Associated peer for poking */
573 struct iax2_peer *peerpoke;
577 /*! Transferring status */
578 enum iax_transfer_state transferring;
579 /*! Transfer identifier */
581 /*! Who we are IAX transfering to */
582 struct sockaddr_in transfer;
583 /*! What's the new call number for the transfer */
584 unsigned short transfercallno;
585 /*! Transfer decrypt AES-128 Key */
586 aes_encrypt_ctx tdcx;
588 /*! Status of knowledge of peer ADSI capability */
591 /*! Who we are bridged to */
592 unsigned short bridgecallno;
593 unsigned int bridgesfmt;
594 struct ast_trans_pvt *bridgetrans;
596 int pingid; /*!< Transmit PING request */
597 int lagid; /*!< Retransmit lag request */
598 int autoid; /*!< Auto hangup for Dialplan requestor */
599 int authid; /*!< Authentication rejection ID */
600 int authfail; /*!< Reason to report failure */
601 int initid; /*!< Initial peer auto-congest ID (based on qualified peers) */
605 char dproot[AST_MAX_EXTENSION];
606 char accountcode[AST_MAX_ACCOUNT_CODE];
608 struct iax2_dpcache *dpentries;
609 struct ast_variable *vars;
610 /*! last received remote rr */
611 struct iax_rr remote_rr;
612 /*! Current base time: (just for stats) */
614 /*! Dropped frame count: (just for stats) */
616 /*! received frame count: (just for stats) */
620 static struct ast_iax2_queue {
621 struct iax_frame *head;
622 struct iax_frame *tail;
627 static struct ast_user_list {
628 struct iax2_user *users;
632 static struct ast_peer_list {
633 struct iax2_peer *peers;
637 static struct ast_firmware_list {
638 struct iax_firmware *wares;
642 /*! Extension exists */
643 #define CACHE_FLAG_EXISTS (1 << 0)
644 /*! Extension is nonexistent */
645 #define CACHE_FLAG_NONEXISTENT (1 << 1)
646 /*! Extension can exist */
647 #define CACHE_FLAG_CANEXIST (1 << 2)
648 /*! Waiting to hear back response */
649 #define CACHE_FLAG_PENDING (1 << 3)
651 #define CACHE_FLAG_TIMEOUT (1 << 4)
652 /*! Request transmitted */
653 #define CACHE_FLAG_TRANSMITTED (1 << 5)
655 #define CACHE_FLAG_UNKNOWN (1 << 6)
657 #define CACHE_FLAG_MATCHMORE (1 << 7)
659 static struct iax2_dpcache {
660 char peercontext[AST_MAX_CONTEXT];
661 char exten[AST_MAX_EXTENSION];
663 struct timeval expiry;
665 unsigned short callno;
667 struct iax2_dpcache *next;
668 struct iax2_dpcache *peer; /*!< For linking in peers */
671 AST_MUTEX_DEFINE_STATIC(dpcache_lock);
673 static void reg_source_db(struct iax2_peer *p);
674 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
676 static void destroy_peer(struct iax2_peer *peer);
677 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt);
679 #define IAX_IOSTATE_IDLE 0
680 #define IAX_IOSTATE_READY 1
681 #define IAX_IOSTATE_PROCESSING 2
682 #define IAX_IOSTATE_SCHEDREADY 3
685 ASTOBJ_COMPONENTS(struct iax2_thread);
687 #ifdef SCHED_MULTITHREADED
688 void (*schedfunc)(void *);
691 #ifdef DEBUG_SCHED_MULTITHREAD
698 struct sockaddr_in iosin;
699 unsigned char buf[4096];
707 struct iax2_thread_list {
708 ASTOBJ_CONTAINER_COMPONENTS(struct iax2_thread);
711 static struct iax2_thread_list idlelist, activelist;
713 static void signal_condition(ast_mutex_t *lock, ast_cond_t *cond)
715 ast_mutex_lock(lock);
716 ast_cond_signal(cond);
717 ast_mutex_unlock(lock);
720 static void iax_debug_output(const char *data)
723 ast_verbose("%s", data);
726 static void iax_error_output(const char *data)
728 ast_log(LOG_WARNING, "%s", data);
732 static void jb_error_output(const char *fmt, ...)
738 vsnprintf(buf, 1024, fmt, args);
741 ast_log(LOG_ERROR, buf);
744 static void jb_warning_output(const char *fmt, ...)
750 vsnprintf(buf, 1024, fmt, args);
753 ast_log(LOG_WARNING, buf);
756 static void jb_debug_output(const char *fmt, ...)
762 vsnprintf(buf, 1024, fmt, args);
770 /* XXX We probably should use a mutex when working with this XXX */
771 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS];
772 static ast_mutex_t iaxsl[IAX_MAX_CALLS];
773 static struct timeval lastused[IAX_MAX_CALLS];
776 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
777 static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int);
778 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
779 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
780 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
781 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, int temponly);
782 static struct iax2_user *build_user(const char *name, struct ast_variable *v, int temponly);
783 static void destroy_user(struct iax2_user *user);
784 static int expire_registry(void *data);
785 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
786 static int iax2_do_register(struct iax2_registry *reg);
787 static void prune_peers(void);
788 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
789 static int iax2_provision(struct sockaddr_in *end, int sockfd, char *dest, const char *template, int force);
791 static struct ast_channel *iax2_request(const char *type, int format, void *data, int *cause);
792 static int iax2_devicestate(void *data);
793 static int iax2_digit(struct ast_channel *c, char digit);
794 static int iax2_sendtext(struct ast_channel *c, const char *text);
795 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
796 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
797 static int iax2_call(struct ast_channel *c, char *dest, int timeout);
798 static int iax2_hangup(struct ast_channel *c);
799 static int iax2_answer(struct ast_channel *c);
800 static struct ast_frame *iax2_read(struct ast_channel *c);
801 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
802 static int iax2_indicate(struct ast_channel *c, int condition);
803 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
804 static 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);
805 static int iax2_transfer(struct ast_channel *c, const char *dest);
806 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
808 static const struct ast_channel_tech iax2_tech = {
810 .description = tdesc,
811 .capabilities = IAX_CAPABILITY_FULLBANDWIDTH,
812 .properties = AST_CHAN_TP_WANTSJITTER,
813 .requester = iax2_request,
814 .devicestate = iax2_devicestate,
815 .send_digit = iax2_digit,
816 .send_text = iax2_sendtext,
817 .send_image = iax2_sendimage,
818 .send_html = iax2_sendhtml,
820 .hangup = iax2_hangup,
821 .answer = iax2_answer,
824 .write_video = iax2_write,
825 .indicate = iax2_indicate,
826 .setoption = iax2_setoption,
827 .bridge = iax2_bridge,
828 .transfer = iax2_transfer,
832 static struct iax2_thread *find_idle_thread(void)
834 struct iax2_thread *thread;
835 thread = ASTOBJ_CONTAINER_UNLINK_START(&idlelist);
839 #ifdef SCHED_MULTITHREADED
840 static int __schedule_action(void (*func)(void *data), void *data, const char *funcname)
842 struct iax2_thread *thread;
843 static time_t lasterror;
845 thread = find_idle_thread();
847 thread->schedfunc = func;
848 thread->scheddata = data;
849 thread->iostate = IAX_IOSTATE_SCHEDREADY;
850 #ifdef DEBUG_SCHED_MULTITHREAD
851 ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc));
853 signal_condition(&thread->lock, &thread->cond);
858 ast_log(LOG_NOTICE, "Out of idle IAX2 threads for scheduling!\n");
862 #define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
865 static void __send_ping(void *data)
867 int callno = (long)data;
868 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
871 static int send_ping(void *data)
873 int callno = (long)data;
875 #ifdef BRIDGE_OPTIMIZATION
876 if (!iaxs[callno]->bridgecallno)
879 #ifdef SCHED_MULTITHREADED
880 if (schedule_action(__send_ping, data))
890 static int get_encrypt_methods(const char *s)
893 if (!strcasecmp(s, "aes128"))
894 e = IAX_ENCRYPT_AES128;
895 else if (ast_true(s))
896 e = IAX_ENCRYPT_AES128;
902 static void __send_lagrq(void *data)
904 int callno = (long)data;
905 /* Ping only if it's real not if it's bridged */
906 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
909 static int send_lagrq(void *data)
911 int callno = (long)data;
913 #ifdef BRIDGE_OPTIMIZATION
914 if (!iaxs[callno]->bridgecallno)
917 #ifdef SCHED_MULTITHREADED
918 if (schedule_action(__send_lagrq, data))
928 static unsigned char compress_subclass(int subclass)
932 /* If it's 128 or smaller, just return it */
933 if (subclass < IAX_FLAG_SC_LOG)
935 /* Otherwise find its power */
936 for (x = 0; x < IAX_MAX_SHIFT; x++) {
937 if (subclass & (1 << x)) {
939 ast_log(LOG_WARNING, "Can't compress subclass %d\n", subclass);
945 return power | IAX_FLAG_SC_LOG;
948 static int uncompress_subclass(unsigned char csub)
950 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
951 if (csub & IAX_FLAG_SC_LOG) {
952 /* special case for 'compressed' -1 */
956 return 1 << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
962 static struct iax2_peer *find_peer(const char *name, int realtime)
964 struct iax2_peer *peer;
965 ast_mutex_lock(&peerl.lock);
966 for(peer = peerl.peers; peer; peer = peer->next) {
967 if (!strcasecmp(peer->name, name)) {
971 ast_mutex_unlock(&peerl.lock);
972 if(!peer && realtime)
973 peer = realtime_peer(name, NULL);
977 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len, int lockpeer)
979 struct iax2_peer *peer;
983 ast_mutex_lock(&peerl.lock);
986 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
987 (peer->addr.sin_port == sin.sin_port)) {
988 ast_copy_string(host, peer->name, len);
995 ast_mutex_unlock(&peerl.lock);
997 peer = realtime_peer(NULL, &sin);
999 ast_copy_string(host, peer->name, len);
1000 if (ast_test_flag(peer, IAX_TEMPONLY))
1009 static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, int lockpeer, const char *host)
1011 struct chan_iax2_pvt *tmp;
1013 if (!(tmp = ast_calloc(1, sizeof(*tmp))))
1018 tmp->peercallno = 0;
1019 tmp->transfercallno = 0;
1020 tmp->bridgecallno = 0;
1026 /* ast_copy_string(tmp->context, context, sizeof(tmp->context)); */
1027 ast_copy_string(tmp->exten, "s", sizeof(tmp->exten));
1028 ast_copy_string(tmp->host, host, sizeof(tmp->host));
1035 jbconf.max_jitterbuf = maxjitterbuffer;
1036 jbconf.resync_threshold = resyncthreshold;
1037 jbconf.max_contig_interp = maxjitterinterps;
1038 jb_setconf(tmp->jb,&jbconf);
1044 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
1046 /* Malloc() a copy of a frame */
1047 struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen);
1049 memcpy(new, fr, sizeof(struct iax_frame));
1050 iax_frame_wrap(new, &fr->af);
1053 new->direction = DIRECTION_INGRESS;
1059 #define NEW_PREVENT 0
1063 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, struct chan_iax2_pvt *cur)
1065 if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
1066 (cur->addr.sin_port == sin->sin_port)) {
1067 /* This is the main host */
1068 if ((cur->peercallno == callno) ||
1069 ((dcallno == cur->callno) && !cur->peercallno)) {
1070 /* That's us. Be sure we keep track of the peer call number */
1074 if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
1075 (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
1076 /* We're transferring */
1077 if (dcallno == cur->callno)
1083 static void update_max_trunk(void)
1085 int max = TRUNK_CALL_START;
1087 /* XXX Prolly don't need locks here XXX */
1088 for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
1093 if (option_debug && iaxdebug)
1094 ast_log(LOG_DEBUG, "New max trunk callno is %d\n", max);
1097 static void update_max_nontrunk(void)
1101 /* XXX Prolly don't need locks here XXX */
1102 for (x=1;x<TRUNK_CALL_START - 1; x++) {
1106 maxnontrunkcall = max;
1107 if (option_debug && iaxdebug)
1108 ast_log(LOG_DEBUG, "New max nontrunk callno is %d\n", max);
1111 static int make_trunk(unsigned short callno, int locked)
1116 if (iaxs[callno]->oseqno) {
1117 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
1120 if (callno & TRUNK_CALL_START) {
1121 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
1124 gettimeofday(&now, NULL);
1125 for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
1126 ast_mutex_lock(&iaxsl[x]);
1127 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) {
1128 iaxs[x] = iaxs[callno];
1129 iaxs[x]->callno = x;
1130 iaxs[callno] = NULL;
1131 /* Update the two timers that should have been started */
1132 if (iaxs[x]->pingid > -1)
1133 ast_sched_del(sched, iaxs[x]->pingid);
1134 if (iaxs[x]->lagid > -1)
1135 ast_sched_del(sched, iaxs[x]->lagid);
1136 iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
1137 iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
1139 ast_mutex_unlock(&iaxsl[callno]);
1142 ast_mutex_unlock(&iaxsl[x]);
1145 ast_mutex_unlock(&iaxsl[x]);
1147 if (x >= IAX_MAX_CALLS - 1) {
1148 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
1151 ast_log(LOG_DEBUG, "Made call %d into trunk call %d\n", callno, x);
1152 /* We move this call from a non-trunked to a trunked call */
1154 update_max_nontrunk();
1158 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int lockpeer, int sockfd)
1163 char iabuf[INET_ADDRSTRLEN];
1165 if (new <= NEW_ALLOW) {
1166 /* Look for an existing connection first */
1167 for (x=1;(res < 1) && (x<maxnontrunkcall);x++) {
1168 ast_mutex_lock(&iaxsl[x]);
1170 /* Look for an exact match */
1171 if (match(sin, callno, dcallno, iaxs[x])) {
1175 ast_mutex_unlock(&iaxsl[x]);
1177 for (x=TRUNK_CALL_START;(res < 1) && (x<maxtrunkcall);x++) {
1178 ast_mutex_lock(&iaxsl[x]);
1180 /* Look for an exact match */
1181 if (match(sin, callno, dcallno, iaxs[x])) {
1185 ast_mutex_unlock(&iaxsl[x]);
1188 if ((res < 1) && (new >= NEW_ALLOW)) {
1189 if (!iax2_getpeername(*sin, host, sizeof(host), lockpeer))
1190 snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr), ntohs(sin->sin_port));
1191 gettimeofday(&now, NULL);
1192 for (x=1;x<TRUNK_CALL_START;x++) {
1193 /* Find first unused call number that hasn't been used in a while */
1194 ast_mutex_lock(&iaxsl[x]);
1195 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) break;
1196 ast_mutex_unlock(&iaxsl[x]);
1198 /* We've still got lock held if we found a spot */
1199 if (x >= TRUNK_CALL_START) {
1200 ast_log(LOG_WARNING, "No more space\n");
1203 iaxs[x] = new_iax(sin, lockpeer, host);
1204 update_max_nontrunk();
1206 if (option_debug && iaxdebug)
1207 ast_log(LOG_DEBUG, "Creating new call structure %d\n", x);
1208 iaxs[x]->sockfd = sockfd;
1209 iaxs[x]->addr.sin_port = sin->sin_port;
1210 iaxs[x]->addr.sin_family = sin->sin_family;
1211 iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
1212 iaxs[x]->peercallno = callno;
1213 iaxs[x]->callno = x;
1214 iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
1215 iaxs[x]->expiry = min_reg_expire;
1216 iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
1217 iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
1218 iaxs[x]->amaflags = amaflags;
1219 ast_copy_flags(iaxs[x], (&globalflags), IAX_NOTRANSFER | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
1220 ast_copy_string(iaxs[x]->accountcode, accountcode, sizeof(iaxs[x]->accountcode));
1222 ast_log(LOG_WARNING, "Out of resources\n");
1223 ast_mutex_unlock(&iaxsl[x]);
1226 ast_mutex_unlock(&iaxsl[x]);
1232 static void iax2_frame_free(struct iax_frame *fr)
1234 if (fr->retrans > -1)
1235 ast_sched_del(sched, fr->retrans);
1239 static int iax2_queue_frame(int callno, struct ast_frame *f)
1241 /* Assumes lock for callno is already held... */
1243 if (iaxs[callno] && iaxs[callno]->owner) {
1244 if (ast_mutex_trylock(&iaxs[callno]->owner->lock)) {
1245 /* Avoid deadlock by pausing and trying again */
1246 ast_mutex_unlock(&iaxsl[callno]);
1248 ast_mutex_lock(&iaxsl[callno]);
1250 ast_queue_frame(iaxs[callno]->owner, f);
1251 ast_mutex_unlock(&iaxs[callno]->owner->lock);
1260 static void destroy_firmware(struct iax_firmware *cur)
1262 /* Close firmware */
1264 munmap(cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh)));
1270 static int try_firmware(char *s)
1273 struct iax_firmware *cur;
1278 struct ast_iax2_firmware_header *fwh, fwh2;
1279 struct MD5Context md5;
1280 unsigned char sum[16];
1281 unsigned char buf[1024];
1285 s2 = alloca(strlen(s) + 100);
1287 ast_log(LOG_WARNING, "Alloca failed!\n");
1290 last = strrchr(s, '/');
1295 snprintf(s2, strlen(s) + 100, "/var/tmp/%s-%ld", last, (unsigned long)rand());
1296 res = stat(s, &stbuf);
1298 ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno));
1301 /* Make sure it's not a directory */
1302 if (S_ISDIR(stbuf.st_mode))
1304 ifd = open(s, O_RDONLY);
1306 ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
1309 fd = open(s2, O_RDWR | O_CREAT | O_EXCL);
1311 ast_log(LOG_WARNING, "Cannot open '%s' for writing: %s\n", s2, strerror(errno));
1315 /* Unlink our newly created file */
1318 /* Now copy the firmware into it */
1319 len = stbuf.st_size;
1322 if (chunk > sizeof(buf))
1323 chunk = sizeof(buf);
1324 res = read(ifd, buf, chunk);
1326 ast_log(LOG_WARNING, "Only read %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1331 res = write(fd, buf, chunk);
1333 ast_log(LOG_WARNING, "Only write %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1341 /* Return to the beginning */
1342 lseek(fd, 0, SEEK_SET);
1343 if ((res = read(fd, &fwh2, sizeof(fwh2))) != sizeof(fwh2)) {
1344 ast_log(LOG_WARNING, "Unable to read firmware header in '%s'\n", s);
1348 if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) {
1349 ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s);
1353 if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) {
1354 ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s);
1358 if (fwh2.devname[sizeof(fwh2.devname) - 1] || ast_strlen_zero((char *)fwh2.devname)) {
1359 ast_log(LOG_WARNING, "No or invalid device type specified for '%s'\n", s);
1363 fwh = mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
1365 ast_log(LOG_WARNING, "mmap failed: %s\n", strerror(errno));
1370 MD5Update(&md5, fwh->data, ntohl(fwh->datalen));
1371 MD5Final(sum, &md5);
1372 if (memcmp(sum, fwh->chksum, sizeof(sum))) {
1373 ast_log(LOG_WARNING, "Firmware file '%s' fails checksum\n", s);
1374 munmap(fwh, stbuf.st_size);
1380 if (!strcmp((char *)cur->fwh->devname, (char *)fwh->devname)) {
1381 /* Found a candidate */
1382 if (cur->dead || (ntohs(cur->fwh->version) < ntohs(fwh->version)))
1383 /* The version we have on loaded is older, load this one instead */
1385 /* This version is no newer than what we have. Don't worry about it.
1386 We'll consider it a proper load anyhow though */
1387 munmap(fwh, stbuf.st_size);
1394 /* Allocate a new one and link it */
1395 if ((cur = ast_calloc(1, sizeof(*cur)))) {
1397 cur->next = waresl.wares;
1403 munmap(cur->fwh, cur->mmaplen);
1409 cur->mmaplen = stbuf.st_size;
1415 static int iax_check_version(char *dev)
1418 struct iax_firmware *cur;
1419 if (!ast_strlen_zero(dev)) {
1420 ast_mutex_lock(&waresl.lock);
1423 if (!strcmp(dev, (char *)cur->fwh->devname)) {
1424 res = ntohs(cur->fwh->version);
1429 ast_mutex_unlock(&waresl.lock);
1434 static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
1437 unsigned int bs = desc & 0xff;
1438 unsigned int start = (desc >> 8) & 0xffffff;
1440 struct iax_firmware *cur;
1441 if (!ast_strlen_zero((char *)dev) && bs) {
1443 ast_mutex_lock(&waresl.lock);
1446 if (!strcmp((char *)dev, (char *)cur->fwh->devname)) {
1447 iax_ie_append_int(ied, IAX_IE_FWBLOCKDESC, desc);
1448 if (start < ntohl(cur->fwh->datalen)) {
1449 bytes = ntohl(cur->fwh->datalen) - start;
1452 iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes);
1455 iax_ie_append(ied, IAX_IE_FWBLOCKDATA);
1465 ast_mutex_unlock(&waresl.lock);
1471 static void reload_firmware(void)
1473 struct iax_firmware *cur, *curl, *curp;
1478 /* Mark all as dead */
1479 ast_mutex_lock(&waresl.lock);
1485 /* Now that we've freed them, load the new ones */
1486 snprintf(dir, sizeof(dir), "%s/firmware/iax", (char *)ast_config_AST_VAR_DIR);
1489 while((de = readdir(fwd))) {
1490 if (de->d_name[0] != '.') {
1491 snprintf(fn, sizeof(fn), "%s/%s", dir, de->d_name);
1492 if (!try_firmware(fn)) {
1493 if (option_verbose > 1)
1494 ast_verbose(VERBOSE_PREFIX_2 "Loaded firmware '%s'\n", de->d_name);
1500 ast_log(LOG_WARNING, "Error opening firmware directory '%s': %s\n", dir, strerror(errno));
1502 /* Clean up leftovers */
1514 destroy_firmware(curl);
1519 ast_mutex_unlock(&waresl.lock);
1522 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
1524 static int __do_deliver(void *data)
1526 /* Just deliver the packet by using queueing. This is called by
1527 the IAX thread with the iaxsl lock held. */
1528 struct iax_frame *fr = data;
1530 if (iaxs[fr->callno] && !ast_test_flag(iaxs[fr->callno], IAX_ALREADYGONE))
1531 iax2_queue_frame(fr->callno, &fr->af);
1532 /* Free our iax frame */
1533 iax2_frame_free(fr);
1534 /* And don't run again */
1539 static int __real_do_deliver(void *data)
1541 /* Locking version of __do_deliver */
1542 struct iax_frame *fr = data;
1543 int callno = fr->callno;
1545 ast_mutex_lock(&iaxsl[callno]);
1546 res = __do_deliver(data);
1547 ast_mutex_unlock(&iaxsl[callno]);
1550 static int do_deliver(void *data)
1552 #ifdef SCHED_MULTITHREADED
1553 if (schedule_action(__do_deliver, data))
1555 __real_do_deliver(data);
1560 static int handle_error(void)
1562 /* XXX Ideally we should figure out why an error occured and then abort those
1563 rather than continuing to try. Unfortunately, the published interface does
1564 not seem to work XXX */
1566 struct sockaddr_in *sin;
1569 struct sock_extended_err e;
1574 m.msg_controllen = sizeof(e);
1576 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
1578 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
1580 if (m.msg_controllen) {
1581 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
1583 ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr));
1585 ast_log(LOG_WARNING, "No address detected??\n");
1587 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
1594 static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin, int sockfd)
1597 res = sendto(sockfd, f->data, f->datalen, 0,(struct sockaddr *)sin,
1601 ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
1608 static int send_packet(struct iax_frame *f)
1611 char iabuf[INET_ADDRSTRLEN];
1612 int callno = f->callno;
1614 /* Called with iaxsl held */
1617 if (option_debug > 2 && iaxdebug)
1618 ast_log(LOG_DEBUG, "Sending %d on %d/%d to %s:%d\n", f->ts, callno, iaxs[callno]->peercallno, ast_inet_ntoa(iabuf, sizeof(iabuf), iaxs[callno]->addr.sin_addr), ntohs(iaxs[callno]->addr.sin_port));
1619 /* Don't send if there was an error, but return error instead */
1621 ast_log(LOG_WARNING, "Call number = %d\n", callno);
1624 if (iaxs[callno]->error)
1628 iax_showframe(f, NULL, 0, &iaxs[callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
1629 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->transfer,
1630 sizeof(iaxs[callno]->transfer));
1633 iax_showframe(f, NULL, 0, &iaxs[callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
1634 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->addr,
1635 sizeof(iaxs[callno]->addr));
1638 if (option_debug && iaxdebug)
1639 ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
1647 static int iax2_predestroy(int callno)
1649 struct ast_channel *c;
1650 struct chan_iax2_pvt *pvt;
1651 ast_mutex_lock(&iaxsl[callno]);
1654 ast_mutex_unlock(&iaxsl[callno]);
1657 if (!ast_test_flag(pvt, IAX_ALREADYGONE)) {
1658 /* No more pings or lagrq's */
1659 if (pvt->pingid > -1)
1660 ast_sched_del(sched, pvt->pingid);
1661 if (pvt->lagid > -1)
1662 ast_sched_del(sched, pvt->lagid);
1663 if (pvt->autoid > -1)
1664 ast_sched_del(sched, pvt->autoid);
1665 if (pvt->authid > -1)
1666 ast_sched_del(sched, pvt->authid);
1667 if (pvt->initid > -1)
1668 ast_sched_del(sched, pvt->initid);
1671 ast_sched_del(sched, pvt->jbid);
1679 ast_set_flag(pvt, IAX_ALREADYGONE);
1683 c->_softhangup |= AST_SOFTHANGUP_DEV;
1685 ast_queue_hangup(c);
1687 ast_mutex_lock(&usecnt_lock);
1690 ast_log(LOG_WARNING, "Usecnt < 0???\n");
1691 ast_mutex_unlock(&usecnt_lock);
1693 ast_mutex_unlock(&iaxsl[callno]);
1694 ast_update_use_count();
1698 static int iax2_predestroy_nolock(int callno)
1701 ast_mutex_unlock(&iaxsl[callno]);
1702 res = iax2_predestroy(callno);
1703 ast_mutex_lock(&iaxsl[callno]);
1707 static void iax2_destroy(int callno)
1709 struct chan_iax2_pvt *pvt;
1710 struct iax_frame *cur;
1711 struct ast_channel *owner;
1714 ast_mutex_lock(&iaxsl[callno]);
1716 gettimeofday(&lastused[callno], NULL);
1718 owner = pvt ? pvt->owner : NULL;
1721 if (ast_mutex_trylock(&owner->lock)) {
1722 ast_log(LOG_NOTICE, "Avoiding IAX destroy deadlock\n");
1723 ast_mutex_unlock(&iaxsl[callno]);
1729 iaxs[callno] = NULL;
1733 /* No more pings or lagrq's */
1734 if (pvt->pingid > -1)
1735 ast_sched_del(sched, pvt->pingid);
1736 if (pvt->lagid > -1)
1737 ast_sched_del(sched, pvt->lagid);
1738 if (pvt->autoid > -1)
1739 ast_sched_del(sched, pvt->autoid);
1740 if (pvt->authid > -1)
1741 ast_sched_del(sched, pvt->authid);
1742 if (pvt->initid > -1)
1743 ast_sched_del(sched, pvt->initid);
1746 ast_sched_del(sched, pvt->jbid);
1754 if (pvt->bridgetrans)
1755 ast_translator_free_path(pvt->bridgetrans);
1756 pvt->bridgetrans = NULL;
1759 ast_set_flag(pvt, IAX_ALREADYGONE);
1762 /* If there's an owner, prod it to give up */
1763 owner->_softhangup |= AST_SOFTHANGUP_DEV;
1764 ast_queue_hangup(owner);
1767 for (cur = iaxq.head; cur ; cur = cur->next) {
1768 /* Cancel any pending transmissions */
1769 if (cur->callno == pvt->callno)
1773 pvt->reg->callno = 0;
1776 ast_variables_destroy(pvt->vars);
1782 while(jb_getall(pvt->jb,&frame) == JB_OK)
1783 iax2_frame_free(frame.data);
1784 jb_destroy(pvt->jb);
1791 ast_mutex_unlock(&owner->lock);
1793 ast_mutex_unlock(&iaxsl[callno]);
1794 if (callno & 0x4000)
1797 static void iax2_destroy_nolock(int callno)
1799 /* Actually it's easier to unlock, kill it, and relock */
1800 ast_mutex_unlock(&iaxsl[callno]);
1801 iax2_destroy(callno);
1802 ast_mutex_lock(&iaxsl[callno]);
1805 static int update_packet(struct iax_frame *f)
1807 /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
1808 struct ast_iax2_full_hdr *fh = f->data;
1809 /* Mark this as a retransmission */
1810 fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
1812 f->iseqno = iaxs[f->callno]->iseqno;
1813 fh->iseqno = f->iseqno;
1817 static int attempt_transmit(void *data);
1818 static void __attempt_transmit(void *data)
1820 /* Attempt to transmit the frame to the remote peer...
1821 Called without iaxsl held. */
1822 struct iax_frame *f = data;
1824 int callno = f->callno;
1825 char iabuf[INET_ADDRSTRLEN];
1826 /* Make sure this call is still active */
1828 ast_mutex_lock(&iaxsl[callno]);
1829 if (callno && iaxs[callno]) {
1830 if ((f->retries < 0) /* Already ACK'd */ ||
1831 (f->retries >= max_retries) /* Too many attempts */) {
1832 /* Record an error if we've transmitted too many times */
1833 if (f->retries >= max_retries) {
1835 /* Transfer timeout */
1836 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
1837 } else if (f->final) {
1839 iax2_destroy_nolock(callno);
1841 if (iaxs[callno]->owner)
1842 ast_log(LOG_WARNING, "Max retries exceeded to host %s on %s (type = %d, subclass = %d, ts=%d, seqno=%d)\n", ast_inet_ntoa(iabuf, sizeof(iabuf), iaxs[f->callno]->addr.sin_addr),iaxs[f->callno]->owner->name , f->af.frametype, f->af.subclass, f->ts, f->oseqno);
1843 iaxs[callno]->error = ETIMEDOUT;
1844 if (iaxs[callno]->owner) {
1845 struct ast_frame fr = { 0, };
1847 fr.frametype = AST_FRAME_CONTROL;
1848 fr.subclass = AST_CONTROL_HANGUP;
1849 iax2_queue_frame(callno, &fr);
1850 /* Remember, owner could disappear */
1851 if (iaxs[callno]->owner)
1852 iaxs[callno]->owner->hangupcause = AST_CAUSE_DESTINATION_OUT_OF_ORDER;
1854 if (iaxs[callno]->reg) {
1855 memset(&iaxs[callno]->reg->us, 0, sizeof(iaxs[callno]->reg->us));
1856 iaxs[callno]->reg->regstate = REG_STATE_TIMEOUT;
1857 iaxs[callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
1859 iax2_destroy_nolock(callno);
1866 /* Update it if it needs it */
1868 /* Attempt transmission */
1871 /* Try again later after 10 times as long */
1873 if (f->retrytime > MAX_RETRY_TIME)
1874 f->retrytime = MAX_RETRY_TIME;
1875 /* Transfer messages max out at one second */
1876 if (f->transfer && (f->retrytime > 1000))
1877 f->retrytime = 1000;
1878 f->retrans = ast_sched_add(sched, f->retrytime, attempt_transmit, f);
1881 /* Make sure it gets freed */
1886 ast_mutex_unlock(&iaxsl[callno]);
1887 /* Do not try again */
1889 /* Don't attempt delivery, just remove it from the queue */
1890 ast_mutex_lock(&iaxq.lock);
1892 f->prev->next = f->next;
1894 iaxq.head = f->next;
1896 f->next->prev = f->prev;
1898 iaxq.tail = f->prev;
1900 ast_mutex_unlock(&iaxq.lock);
1902 /* Free the IAX frame */
1907 static int attempt_transmit(void *data)
1909 #ifdef SCHED_MULTITHREADED
1910 if (schedule_action(__attempt_transmit, data))
1912 __attempt_transmit(data);
1916 static int iax2_set_jitter(int fd, int argc, char *argv[])
1919 ast_cli(fd, "sorry, this command is deprecated\n");
1920 return RESULT_SUCCESS;
1922 if ((argc != 4) && (argc != 5))
1923 return RESULT_SHOWUSAGE;
1925 max_jitter_buffer = atoi(argv[3]);
1926 if (max_jitter_buffer < 0)
1927 max_jitter_buffer = 0;
1930 int callno = atoi(argv[3]);
1931 if ((callno >= 0) && (callno < IAX_MAX_CALLS)) {
1933 iaxs[callno]->jitterbuffer = atoi(argv[4]);
1934 if (iaxs[callno]->jitterbuffer < 0)
1935 iaxs[callno]->jitterbuffer = 0;
1937 ast_cli(fd, "No such call '%d'\n", callno);
1939 ast_cli(fd, "%d is not a valid call number\n", callno);
1942 return RESULT_SUCCESS;
1946 static char jitter_usage[] =
1947 "Usage: iax set jitter [callid] <value>\n"
1948 " If used with a callid, it sets the jitter buffer to the given static\n"
1949 "value (until its next calculation). If used without a callid, the value is used\n"
1950 "to establish the maximum excess jitter buffer that is permitted before the jitter\n"
1951 "buffer size is reduced.";
1953 static int iax2_prune_realtime(int fd, int argc, char *argv[])
1955 struct iax2_peer *peer;
1958 return RESULT_SHOWUSAGE;
1959 if (!strcmp(argv[3],"all")) {
1961 ast_cli(fd, "OK cache is flushed.\n");
1962 } else if ((peer = find_peer(argv[3], 0))) {
1963 if(ast_test_flag(peer, IAX_RTCACHEFRIENDS)) {
1964 ast_set_flag(peer, IAX_RTAUTOCLEAR);
1965 expire_registry(peer);
1966 ast_cli(fd, "OK peer %s was removed from the cache.\n", argv[3]);
1968 ast_cli(fd, "SORRY peer %s is not eligible for this operation.\n", argv[3]);
1971 ast_cli(fd, "SORRY peer %s was not found in the cache.\n", argv[3]);
1974 return RESULT_SUCCESS;
1977 static int iax2_test_losspct(int fd, int argc, char *argv[])
1980 return RESULT_SHOWUSAGE;
1982 test_losspct = atoi(argv[3]);
1984 return RESULT_SUCCESS;
1988 static int iax2_test_late(int fd, int argc, char *argv[])
1991 return RESULT_SHOWUSAGE;
1993 test_late = atoi(argv[3]);
1995 return RESULT_SUCCESS;
1998 static int iax2_test_resync(int fd, int argc, char *argv[])
2001 return RESULT_SHOWUSAGE;
2003 test_resync = atoi(argv[3]);
2005 return RESULT_SUCCESS;
2008 static int iax2_test_jitter(int fd, int argc, char *argv[])
2010 if (argc < 4 || argc > 5)
2011 return RESULT_SHOWUSAGE;
2013 test_jit = atoi(argv[3]);
2015 test_jitpct = atoi(argv[4]);
2017 return RESULT_SUCCESS;
2019 #endif /* IAXTESTS */
2021 /*! \brief peer_status: Report Peer status in character string */
2022 /* returns 1 if peer is online, -1 if unmonitored */
2023 static int peer_status(struct iax2_peer *peer, char *status, int statuslen)
2027 if (peer->lastms < 0) {
2028 ast_copy_string(status, "UNREACHABLE", statuslen);
2029 } else if (peer->lastms > peer->maxms) {
2030 snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
2032 } else if (peer->lastms) {
2033 snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
2036 ast_copy_string(status, "UNKNOWN", statuslen);
2039 ast_copy_string(status, "Unmonitored", statuslen);
2045 /*! \brief Show one peer in detail */
2046 static int iax2_show_peer(int fd, int argc, char *argv[])
2050 char iabuf[INET_ADDRSTRLEN];
2051 struct iax2_peer *peer;
2052 char codec_buf[512];
2053 int x = 0, codec = 0, load_realtime = 0;
2056 return RESULT_SHOWUSAGE;
2058 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? 1 : 0;
2060 peer = find_peer(argv[3], load_realtime);
2063 ast_cli(fd, " * Name : %s\n", peer->name);
2064 ast_cli(fd, " Secret : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
2065 ast_cli(fd, " Context : %s\n", peer->context);
2066 ast_cli(fd, " Mailbox : %s\n", peer->mailbox);
2067 ast_cli(fd, " Dynamic : %s\n", ast_test_flag(peer, IAX_DYNAMIC) ? "Yes":"No");
2068 ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
2069 ast_cli(fd, " Expire : %d\n", peer->expire);
2070 ast_cli(fd, " ACL : %s\n", (peer->ha?"Yes":"No"));
2071 ast_cli(fd, " Addr->IP : %s Port %d\n", peer->addr.sin_addr.s_addr ? ast_inet_ntoa(iabuf, sizeof(iabuf), peer->addr.sin_addr) : "(Unspecified)", ntohs(peer->addr.sin_port));
2072 ast_cli(fd, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
2073 ast_cli(fd, " Username : %s\n", peer->username);
2074 ast_cli(fd, " Codecs : ");
2075 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
2076 ast_cli(fd, "%s\n", codec_buf);
2078 ast_cli(fd, " Codec Order : (");
2079 for(x = 0; x < 32 ; x++) {
2080 codec = ast_codec_pref_index(&peer->prefs,x);
2083 ast_cli(fd, "%s", ast_getformatname(codec));
2084 if(x < 31 && ast_codec_pref_index(&peer->prefs,x+1))
2089 ast_cli(fd, "none");
2092 ast_cli(fd, " Status : ");
2093 peer_status(peer, status, sizeof(status));
2094 ast_cli(fd, "%s\n",status);
2095 ast_cli(fd, " Qualify : every %dms when OK, every %dms when UNREACHABLE (sample smoothing %s)\n", peer->pokefreqok, peer->pokefreqnotok, peer->smoothing ? "On" : "Off");
2097 if (ast_test_flag(peer, IAX_TEMPONLY))
2100 ast_cli(fd,"Peer %s not found.\n", argv[3]);
2104 return RESULT_SUCCESS;
2107 static char *complete_iax2_show_peer(const char *line, const char *word, int pos, int state)
2110 struct iax2_peer *p;
2112 int wordlen = strlen(word);
2114 /* 0 - iax2; 1 - show; 2 - peer; 3 - <peername> */
2116 ast_mutex_lock(&peerl.lock);
2117 for (p = peerl.peers ; p ; p = p->next) {
2118 if (!strncasecmp(p->name, word, wordlen) && ++which > state) {
2119 res = ast_strdup(p->name);
2123 ast_mutex_unlock(&peerl.lock);
2129 static int iax2_show_stats(int fd, int argc, char *argv[])
2131 struct iax_frame *cur;
2132 int cnt = 0, dead=0, final=0;
2134 return RESULT_SHOWUSAGE;
2135 for (cur = iaxq.head; cur ; cur = cur->next) {
2136 if (cur->retries < 0)
2142 ast_cli(fd, " IAX Statistics\n");
2143 ast_cli(fd, "---------------------\n");
2144 ast_cli(fd, "Outstanding frames: %d (%d ingress, %d egress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
2145 ast_cli(fd, "Packets in transmit queue: %d dead, %d final, %d total\n", dead, final, cnt);
2146 return RESULT_SUCCESS;
2149 static int iax2_show_cache(int fd, int argc, char *argv[])
2151 struct iax2_dpcache *dp;
2152 char tmp[1024], *pc;
2156 gettimeofday(&tv, NULL);
2157 ast_mutex_lock(&dpcache_lock);
2159 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
2161 s = dp->expiry.tv_sec - tv.tv_sec;
2163 if (dp->flags & CACHE_FLAG_EXISTS)
2164 strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
2165 if (dp->flags & CACHE_FLAG_NONEXISTENT)
2166 strncat(tmp, "NONEXISTENT|", sizeof(tmp) - strlen(tmp) - 1);
2167 if (dp->flags & CACHE_FLAG_CANEXIST)
2168 strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
2169 if (dp->flags & CACHE_FLAG_PENDING)
2170 strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
2171 if (dp->flags & CACHE_FLAG_TIMEOUT)
2172 strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
2173 if (dp->flags & CACHE_FLAG_TRANSMITTED)
2174 strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
2175 if (dp->flags & CACHE_FLAG_MATCHMORE)
2176 strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
2177 if (dp->flags & CACHE_FLAG_UNKNOWN)
2178 strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
2179 /* Trim trailing pipe */
2180 if (!ast_strlen_zero(tmp))
2181 tmp[strlen(tmp) - 1] = '\0';
2183 ast_copy_string(tmp, "(none)", sizeof(tmp));
2185 pc = strchr(dp->peercontext, '@');
2187 pc = dp->peercontext;
2190 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
2191 if (dp->waiters[x] > -1)
2194 ast_cli(fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
2196 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
2199 ast_mutex_unlock(&dpcache_lock);
2200 return RESULT_SUCCESS;
2203 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
2205 #ifdef BRIDGE_OPTIMIZATION
2206 static unsigned int calc_fakestamp(struct chan_iax2_pvt *from, struct chan_iax2_pvt *to, unsigned int ts);
2208 static int forward_delivery(struct iax_frame *fr)
2210 struct chan_iax2_pvt *p1, *p2;
2211 char iabuf[INET_ADDRSTRLEN];
2214 p1 = iaxs[fr->callno];
2215 p2 = iaxs[p1->bridgecallno];
2222 ast_log(LOG_DEBUG, "forward_delivery: Forwarding ts=%d on %d/%d to %d/%d on %s:%d\n",
2224 p1->callno, p1->peercallno,
2225 p2->callno, p2->peercallno,
2226 ast_inet_ntoa(iabuf, sizeof(iabuf), p2->addr.sin_addr),
2227 ntohs(p2->addr.sin_port));
2229 /* Undo wraparound - which can happen when full VOICE frame wasn't sent by our peer.
2230 This is necessary for when our peer is chan_iax2.c v1.1nn or earlier which didn't
2231 send full frame on timestamp wrap when doing optimized bridging
2232 (actually current code STILL doesn't)
2234 if (fr->ts + 50000 <= p1->last) {
2235 fr->ts = ( (p1->last & 0xFFFF0000) + 0x10000) | (fr->ts & 0xFFFF);
2237 ast_log(LOG_DEBUG, "forward_delivery: pushed forward timestamp to %u\n", fr->ts);
2240 /* Send with timestamp adjusted to the origin of the outbound leg */
2241 /* But don't destroy inbound timestamp still needed later to set "last" */
2243 fr->ts = calc_fakestamp(p1, p2, fr->ts);
2244 res = iax2_send(p2, &fr->af, fr->ts, -1, 0, 0, 0);
2250 static void unwrap_timestamp(struct iax_frame *fr)
2254 if ( (fr->ts & 0xFFFF0000) == (iaxs[fr->callno]->last & 0xFFFF0000) ) {
2255 x = fr->ts - iaxs[fr->callno]->last;
2257 /* Sudden big jump backwards in timestamp:
2258 What likely happened here is that miniframe timestamp has circled but we haven't
2259 gotten the update from the main packet. We'll just pretend that we did, and
2260 update the timestamp appropriately. */
2261 fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) + 0x10000) | (fr->ts & 0xFFFF);
2262 if (option_debug && iaxdebug)
2263 ast_log(LOG_DEBUG, "schedule_delivery: pushed forward timestamp\n");
2266 /* Sudden apparent big jump forwards in timestamp:
2267 What's likely happened is this is an old miniframe belonging to the previous
2268 top-16-bit timestamp that has turned up out of order.
2269 Adjust the timestamp appropriately. */
2270 fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) - 0x10000) | (fr->ts & 0xFFFF);
2271 if (option_debug && iaxdebug)
2272 ast_log(LOG_DEBUG, "schedule_delivery: pushed back timestamp\n");
2278 static int get_from_jb(void *p);
2280 static void update_jbsched(struct chan_iax2_pvt *pvt) {
2283 when = ast_tvdiff_ms(ast_tvnow(), pvt->rxcore);
2285 /* fprintf(stderr, "now = %d, next=%d\n", when, jb_next(pvt->jb)); */
2287 when = jb_next(pvt->jb) - when;
2288 /* fprintf(stderr, "when = %d\n", when); */
2290 if(pvt->jbid > -1) ast_sched_del(sched, pvt->jbid);
2293 /* XXX should really just empty until when > 0.. */
2297 pvt->jbid = ast_sched_add(sched, when, get_from_jb, (void *)pvt);
2299 /* Signal scheduler thread */
2300 signal_condition(&sched_lock, &sched_cond);
2303 static void __get_from_jb(void *p)
2305 /* make sure pvt is valid! */
2306 struct chan_iax2_pvt *pvt = p;
2307 struct iax_frame *fr;
2314 ast_mutex_lock(&iaxsl[pvt->callno]);
2315 /* fprintf(stderr, "get_from_jb called\n"); */
2318 gettimeofday(&tv,NULL);
2319 /* round up a millisecond since ast_sched_runq does; */
2320 /* prevents us from spinning while waiting for our now */
2321 /* to catch up with runq's now */
2324 now = ast_tvdiff_ms(tv, pvt->rxcore);
2326 if(now >= (next = jb_next(pvt->jb))) {
2327 ret = jb_get(pvt->jb,&frame,now,ast_codec_interp_len(pvt->voiceformat));
2330 /*if(frame.type == JB_TYPE_VOICE && next + 20 != jb_next(pvt->jb)) fprintf(stderr, "NEXT %ld is not %ld+20!\n", jb_next(pvt->jb), next); */
2336 struct ast_frame af;
2338 /*if(next + 20 != jb_next(pvt->jb)) fprintf(stderr, "NEXT %ld is not %ld+20!\n", jb_next(pvt->jb), next); */
2340 /* create an interpolation frame */
2341 /*fprintf(stderr, "Making Interpolation frame\n"); */
2342 af.frametype = AST_FRAME_VOICE;
2343 af.subclass = pvt->voiceformat;
2345 af.samples = frame.ms * 8;
2347 af.src = "IAX2 JB interpolation";
2349 af.delivery = ast_tvadd(pvt->rxcore, ast_samp2tv(next, 1000));
2350 af.offset=AST_FRIENDLY_OFFSET;
2352 /* queue the frame: For consistency, we would call __do_deliver here, but __do_deliver wants an iax_frame,
2353 * which we'd need to malloc, and then it would free it. That seems like a drag */
2354 if (iaxs[pvt->callno] && !ast_test_flag(iaxs[pvt->callno], IAX_ALREADYGONE))
2355 iax2_queue_frame(pvt->callno, &af);
2359 /*if(next != jb_next(pvt->jb)) fprintf(stderr, "NEXT %ld is not next %ld!\n", jb_next(pvt->jb), next); */
2360 iax2_frame_free(frame.data);
2367 /* shouldn't happen */
2371 update_jbsched(pvt);
2372 ast_mutex_unlock(&iaxsl[pvt->callno]);
2375 static int get_from_jb(void *data)
2377 #ifdef SCHED_MULTITHREADED
2378 if (schedule_action(__get_from_jb, data))
2380 __get_from_jb(data);
2385 /* while we transition from the old JB to the new one, we can either make two schedule_delivery functions, or
2386 * make preprocessor swiss-cheese out of this one. I'm not sure which is less revolting.. */
2387 static int schedule_delivery(struct iax_frame *fr, int updatehistory, int fromtrunk, unsigned int *tsout)
2397 unsigned int orig_ts;
2398 int drops[MEMORY_SIZE];
2399 int min, max=0, prevjitterbuffer, maxone=0,y,z, match;
2401 /* Remember current jitterbuffer so we can log any change */
2402 prevjitterbuffer = iaxs[fr->callno]->jitterbuffer;
2403 /* Similarly for the frame timestamp */
2408 if (option_debug && iaxdebug)
2409 ast_log(LOG_DEBUG, "schedule_delivery: ts=%d, last=%d, update=%d\n",
2410 fr->ts, iaxs[fr->callno]->last, updatehistory);
2413 /* Attempt to recover wrapped timestamps */
2414 unwrap_timestamp(fr);
2416 if (updatehistory) {
2419 /* Attempt to spot a change of timebase on timestamps coming from the other side
2420 We detect by noticing a jump in consecutive timestamps that can't reasonably be explained
2421 by network jitter or reordering. Sometimes, also, the peer stops sending us frames
2422 for a while - in this case this code might also resync us. But that's not a bad thing.
2423 Be careful of non-voice frames which are timestamped differently (especially ACKS!)
2424 [that's why we only do this when updatehistory is true]
2426 x = fr->ts - iaxs[fr->callno]->last;
2427 if (x > TS_GAP_FOR_JB_RESYNC || x < -TS_GAP_FOR_JB_RESYNC) {
2428 if (option_debug && iaxdebug)
2429 ast_log(LOG_DEBUG, "schedule_delivery: call=%d: TS jumped. resyncing rxcore (ts=%d, last=%d)\n",
2430 fr->callno, fr->ts, iaxs[fr->callno]->last);
2431 /* zap rxcore - calc_rxstamp will make a new one based on this frame */
2432 iaxs[fr->callno]->rxcore = ast_tv(0, 0);
2433 /* wipe "last" if stamps have jumped backwards */
2435 iaxs[fr->callno]->last = 0;
2436 /* should we also empty history? */
2438 /* ms is a measure of the "lateness" of the frame relative to the "reference"
2439 frame we received. (initially the very first, but also see code just above here).
2440 Understand that "ms" can easily be -ve if lag improves since the reference frame.
2441 Called by IAX thread, with iaxsl lock held. */
2442 ms = calc_rxstamp(iaxs[fr->callno], fr->ts) - fr->ts;
2444 /* Rotate our history queue of "lateness". Don't worry about those initial
2445 zeros because the first entry will always be zero */
2446 for (x=0;x<MEMORY_SIZE - 1;x++)
2447 iaxs[fr->callno]->history[x] = iaxs[fr->callno]->history[x+1];
2448 /* Add a history entry for this one */
2449 iaxs[fr->callno]->history[x] = ms;
2458 /* delivery time is sender's sent timestamp converted back into absolute time according to our clock */
2459 if ( !fromtrunk && !ast_tvzero(iaxs[fr->callno]->rxcore))
2460 fr->af.delivery = ast_tvadd(iaxs[fr->callno]->rxcore, ast_samp2tv(fr->ts, 1000));
2463 ast_log(LOG_DEBUG, "schedule_delivery: set delivery to 0 as we don't have an rxcore yet, or frame is from trunk.\n");
2465 fr->af.delivery = ast_tv(0,0);
2469 /* Initialize the minimum to reasonable values. It's too much
2470 work to do the same for the maximum, repeatedly */
2471 min=iaxs[fr->callno]->history[0];
2472 for (z=0;z < iax2_dropcount + 1;z++) {
2473 /* Start very optimistic ;-) */
2475 for (x=0;x<MEMORY_SIZE;x++) {
2476 if (max < iaxs[fr->callno]->history[x]) {
2477 /* We have a candidate new maximum value. Make
2478 sure it's not in our drop list */
2480 for (y=0;!match && (y<z);y++)
2481 match |= (drops[y] == x);
2483 /* It's not in our list, use it as the new maximum */
2484 max = iaxs[fr->callno]->history[x];
2490 /* On our first pass, find the minimum too */
2491 if (min > iaxs[fr->callno]->history[x])
2492 min = iaxs[fr->callno]->history[x];
2502 type = JB_TYPE_CONTROL;
2505 if(fr->af.frametype == AST_FRAME_VOICE) {
2506 type = JB_TYPE_VOICE;
2507 len = ast_codec_get_samples(&fr->af) / 8;
2508 } else if(fr->af.frametype == AST_FRAME_CNG) {
2509 type = JB_TYPE_SILENCE;
2512 if ( (!ast_test_flag(iaxs[fr->callno], IAX_USEJITTERBUF)) ) {
2519 /* if the user hasn't requested we force the use of the jitterbuffer, and we're bridged to
2520 * a channel that can accept jitter, then flush and suspend the jb, and send this frame straight through */
2521 if( (!ast_test_flag(iaxs[fr->callno], IAX_FORCEJITTERBUF)) &&
2522 iaxs[fr->callno]->owner && ast_bridged_channel(iaxs[fr->callno]->owner) &&
2523 (ast_bridged_channel(iaxs[fr->callno]->owner)->tech->properties & AST_CHAN_TP_WANTSJITTER)) {
2526 /* deliver any frames in the jb */
2527 while(jb_getall(iaxs[fr->callno]->jb,&frame) == JB_OK)
2528 __do_deliver(frame.data);
2530 jb_reset(iaxs[fr->callno]->jb);
2532 if (iaxs[fr->callno]->jbid > -1)
2533 ast_sched_del(sched, iaxs[fr->callno]->jbid);
2535 iaxs[fr->callno]->jbid = -1;
2537 /* deliver this frame now */
2546 /* insert into jitterbuffer */
2547 /* TODO: Perhaps we could act immediately if it's not droppable and late */
2548 ret = jb_put(iaxs[fr->callno]->jb, fr, type, len, fr->ts,
2549 calc_rxstamp(iaxs[fr->callno],fr->ts));
2550 if (ret == JB_DROP) {
2552 } else if (ret == JB_SCHED) {
2553 update_jbsched(iaxs[fr->callno]);
2556 /* Just for reference, keep the "jitter" value, the difference between the
2557 earliest and the latest. */
2559 iaxs[fr->callno]->jitter = max - min;
2561 /* IIR filter for keeping track of historic jitter, but always increase
2562 historic jitter immediately for increase */
2564 if (iaxs[fr->callno]->jitter > iaxs[fr->callno]->historicjitter )
2565 iaxs[fr->callno]->historicjitter = iaxs[fr->callno]->jitter;
2567 iaxs[fr->callno]->historicjitter = GAMMA * (double)iaxs[fr->callno]->jitter + (1-GAMMA) *
2568 iaxs[fr->callno]->historicjitter;
2570 /* If our jitter buffer is too big (by a significant margin), then we slowly
2571 shrink it to avoid letting the change be perceived */
2572 if (max < iaxs[fr->callno]->jitterbuffer - max_jitter_buffer)
2573 iaxs[fr->callno]->jitterbuffer -= jittershrinkrate;
2575 /* If our jitter buffer headroom is too small (by a significant margin), then we slowly enlarge it */
2576 /* min_jitter_buffer should be SMALLER than max_jitter_buffer - leaving a "no mans land"
2577 in between - otherwise the jitterbuffer size will hunt up and down causing unnecessary
2578 disruption. Set maxexcessbuffer to say 150msec, minexcessbuffer to say 50 */
2579 if (max > iaxs[fr->callno]->jitterbuffer - min_jitter_buffer)
2580 iaxs[fr->callno]->jitterbuffer += jittershrinkrate;
2582 /* If our jitter buffer is smaller than our maximum delay, grow the jitter
2583 buffer immediately to accomodate it (and a little more). */
2584 if (max > iaxs[fr->callno]->jitterbuffer)
2585 iaxs[fr->callno]->jitterbuffer = max
2586 /* + ((float)iaxs[fr->callno]->jitter) * 0.1 */;
2588 /* update "min", just for RRs and stats */
2589 iaxs[fr->callno]->min = min;
2591 /* Subtract the lateness from our jitter buffer to know how long to wait
2592 before sending our packet. */
2593 delay = iaxs[fr->callno]->jitterbuffer - ms;
2595 /* Whatever happens, no frame waits longer than maxjitterbuffer */
2596 if (delay > maxjitterbuffer)
2597 delay = maxjitterbuffer;
2599 /* If jitter buffer is disabled then just pretend the frame is "right on time" */
2600 /* If frame came from trunk, also don't do any delay */
2601 if ( (!ast_test_flag(iaxs[fr->callno], IAX_USEJITTERBUF)) || fromtrunk )
2604 if (option_debug && iaxdebug) {
2605 /* Log jitter stats for possible offline analysis */
2606 ast_log(LOG_DEBUG, "Jitter: call=%d ts=%d orig=%d last=%d %s: min=%d max=%d jb=%d %+d lateness=%d jbdelay=%d jitter=%d historic=%d\n",
2607 fr->callno, fr->ts, orig_ts, iaxs[fr->callno]->last,
2608 (fr->af.frametype == AST_FRAME_VOICE) ? "VOICE" : "CONTROL",
2609 min, max, iaxs[fr->callno]->jitterbuffer,
2610 iaxs[fr->callno]->jitterbuffer - prevjitterbuffer,
2612 iaxs[fr->callno]->jitter, iaxs[fr->callno]->historicjitter);
2616 /* Don't deliver it more than 4 ms late */
2617 if ((delay > -4) || (fr->af.frametype != AST_FRAME_VOICE)) {
2618 if (option_debug && iaxdebug)
2619 ast_log(LOG_DEBUG, "schedule_delivery: Delivering immediately (Calculated delay is %d)\n", delay);
2625 if (option_debug && iaxdebug)
2626 ast_log(LOG_DEBUG, "schedule_delivery: Dropping voice packet since %dms delay is too old\n", delay);
2627 iaxs[fr->callno]->frames_dropped++;
2631 if (option_debug && iaxdebug)
2632 ast_log(LOG_DEBUG, "schedule_delivery: Scheduling delivery in %d ms\n", delay);
2633 fr->retrans = ast_sched_add(sched, delay, do_deliver, fr);
2634 signal_condition(&sched_lock, &sched_cond);
2640 /* Free our iax frame */
2641 iax2_frame_free(fr);
2647 static int iax2_transmit(struct iax_frame *fr)
2649 /* Lock the queue and place this packet at the end */
2652 /* By setting this to 0, the network thread will send it for us, and
2653 queue retransmission if necessary */
2655 ast_mutex_lock(&iaxq.lock);
2662 iaxq.tail->next = fr;
2663 fr->prev = iaxq.tail;
2667 ast_mutex_unlock(&iaxq.lock);
2668 /* Wake up the network and scheduler thread */
2669 pthread_kill(netthreadid, SIGURG);
2670 signal_condition(&sched_lock, &sched_cond);
2676 static int iax2_digit(struct ast_channel *c, char digit)
2678 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF, digit, 0, NULL, 0, -1);
2681 static int iax2_sendtext(struct ast_channel *c, const char *text)
2684 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_TEXT,
2685 0, 0, (unsigned char *)text, strlen(text) + 1, -1);
2688 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
2690 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_IMAGE, img->subclass, 0, img->data, img->datalen, -1);
2693 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen)
2695 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_HTML, subclass, 0, (unsigned char *)data, datalen, -1);
2698 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
2700 unsigned short callno = PTR_TO_CALLNO(newchan->tech_pvt);
2701 ast_mutex_lock(&iaxsl[callno]);
2703 iaxs[callno]->owner = newchan;
2705 ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n");
2706 ast_mutex_unlock(&iaxsl[callno]);
2710 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin)
2712 struct ast_variable *var;
2713 struct ast_variable *tmp;
2714 struct iax2_peer *peer=NULL;
2715 time_t regseconds = 0, nowtime;
2719 var = ast_load_realtime("iaxpeers", "name", peername, NULL);
2721 char iabuf[INET_ADDRSTRLEN];
2723 ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr);
2724 sprintf(porta, "%d", ntohs(sin->sin_port));
2725 var = ast_load_realtime("iaxpeers", "ipaddr", iabuf, "port", porta, NULL);
2727 /* We'll need the peer name in order to build the structure! */
2730 if (!strcasecmp(tmp->name, "name"))
2731 peername = tmp->value;
2739 peer = build_peer(peername, var, ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS) ? 0 : 1);
2746 /* Make sure it's not a user only... */
2747 if (!strcasecmp(tmp->name, "type")) {
2748 if (strcasecmp(tmp->value, "friend") &&
2749 strcasecmp(tmp->value, "peer")) {
2750 /* Whoops, we weren't supposed to exist! */
2755 } else if (!strcasecmp(tmp->name, "regseconds")) {
2756 ast_get_time_t(tmp->value, ®seconds, 0, NULL);
2757 } else if (!strcasecmp(tmp->name, "ipaddr")) {
2758 inet_aton(tmp->value, &(peer->addr.sin_addr));
2759 } else if (!strcasecmp(tmp->name, "port")) {
2760 peer->addr.sin_port = htons(atoi(tmp->value));
2761 } else if (!strcasecmp(tmp->name, "host")) {
2762 if (!strcasecmp(tmp->value, "dynamic"))
2770 ast_variables_destroy(var);
2772 if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
2773 ast_copy_flags(peer, &globalflags, IAX_RTAUTOCLEAR|IAX_RTCACHEFRIENDS);
2774 if (ast_test_flag(peer, IAX_RTAUTOCLEAR)) {
2775 if (peer->expire > -1)
2776 ast_sched_del(sched, peer->expire);
2777 peer->expire = ast_sched_add(sched, (global_rtautoclear) * 1000, expire_registry, peer);
2779 ast_mutex_lock(&peerl.lock);
2780 peer->next = peerl.peers;
2782 ast_mutex_unlock(&peerl.lock);
2783 if (ast_test_flag(peer, IAX_DYNAMIC))
2784 reg_source_db(peer);
2786 ast_set_flag(peer, IAX_TEMPONLY);
2789 if (!ast_test_flag(&globalflags, IAX_RTIGNOREREGEXPIRE) && dynamic) {
2791 if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE) {
2792 memset(&peer->addr, 0, sizeof(peer->addr));
2794 ast_log(LOG_DEBUG, "realtime_peer: Bah, '%s' is expired (%d/%d/%d)!\n",
2795 peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
2799 ast_log(LOG_DEBUG, "realtime_peer: Registration for '%s' still active (%d/%d/%d)!\n",
2800 peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
2807 static struct iax2_user *realtime_user(const char *username)
2809 struct ast_variable *var;
2810 struct ast_variable *tmp;
2811 struct iax2_user *user=NULL;
2813 var = ast_load_realtime("iaxusers", "name", username, NULL);
2819 /* Make sure it's not a peer only... */
2820 if (!strcasecmp(tmp->name, "type")) {
2821 if (strcasecmp(tmp->value, "friend") &&
2822 strcasecmp(tmp->value, "user")) {
2829 user = build_user(username, var, !ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS));
2833 ast_variables_destroy(var);
2835 if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
2836 ast_set_flag(user, IAX_RTCACHEFRIENDS);
2837 ast_mutex_lock(&userl.lock);
2838 user->next = userl.users;
2840 ast_mutex_unlock(&userl.lock);
2842 ast_set_flag(user, IAX_TEMPONLY);
2848 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin)
2852 char regseconds[20];
2856 snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime);
2857 ast_inet_ntoa(ipaddr, sizeof(ipaddr), sin->sin_addr);
2858 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
2859 ast_update_realtime("iaxpeers", "name", peername, "ipaddr", ipaddr, "port", port, "regseconds", regseconds, NULL);
2862 struct create_addr_info {
2874 char context[AST_MAX_CONTEXT];
2875 char peercontext[AST_MAX_CONTEXT];
2878 static int create_addr(const char *peername, struct sockaddr_in *sin, struct create_addr_info *cai)
2880 struct ast_hostent ahp;
2882 struct iax2_peer *peer;
2884 ast_clear_flag(cai, IAX_SENDANI | IAX_TRUNK);
2885 cai->sockfd = defaultsockfd;
2887 sin->sin_family = AF_INET;
2889 if (!(peer = find_peer(peername, 1))) {
2892 hp = ast_gethostbyname(peername, &ahp);
2894 memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
2895 sin->sin_port = htons(IAX_DEFAULT_PORTNO);
2896 /* use global iax prefs for unknown peer/user */
2897 ast_codec_pref_convert(&prefs, cai->prefs, sizeof(cai->prefs), 1);
2900 ast_log(LOG_WARNING, "No such host: %s\n", peername);
2907 /* if the peer has no address (current or default), return failure */
2908 if (!(peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr)) {
2909 if (ast_test_flag(peer, IAX_TEMPONLY))
2914 /* if the peer is being monitored and is currently unreachable, return failure */
2915 if (peer->maxms && ((peer->lastms > peer->maxms) || (peer->lastms < 0))) {
2916 if (ast_test_flag(peer, IAX_TEMPONLY))
2921 ast_copy_flags(cai, peer, IAX_SENDANI | IAX_TRUNK | IAX_NOTRANSFER | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
2922 cai->maxtime = peer->maxms;
2923 cai->capability = peer->capability;
2924 cai->encmethods = peer->encmethods;
2925 cai->sockfd = peer->sockfd;
2926 ast_codec_pref_convert(&peer->prefs, cai->prefs, sizeof(cai->prefs), 1);
2927 ast_copy_string(cai->context, peer->context, sizeof(cai->context));
2928 ast_copy_string(cai->peercontext, peer->peercontext, sizeof(cai->peercontext));
2929 ast_copy_string(cai->username, peer->username, sizeof(cai->username));
2930 ast_copy_string(cai->timezone, peer->zonetag, sizeof(cai->timezone));
2931 ast_copy_string(cai->outkey, peer->outkey, sizeof(cai->outkey));
2932 if (ast_strlen_zero(peer->dbsecret)) {
2933 ast_copy_string(cai->secret, peer->secret, sizeof(cai->secret));
2938 family = ast_strdupa(peer->dbsecret);
2940 key = strchr(family, '/');
2944 if (!family || !key || ast_db_get(family, key, cai->secret, sizeof(cai->secret))) {
2945 ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", peer->dbsecret);
2946 if (ast_test_flag(peer, IAX_TEMPONLY))
2952 if (peer->addr.sin_addr.s_addr) {
2953 sin->sin_addr = peer->addr.sin_addr;
2954 sin->sin_port = peer->addr.sin_port;
2956 sin->sin_addr = peer->defaddr.sin_addr;
2957 sin->sin_port = peer->defaddr.sin_port;
2960 if (ast_test_flag(peer, IAX_TEMPONLY))
2966 static void __auto_congest(void *nothing)
2968 int callno = PTR_TO_CALLNO(nothing);
2969 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_CONGESTION };
2970 ast_mutex_lock(&iaxsl[callno]);
2972 iaxs[callno]->initid = -1;
2973 iax2_queue_frame(callno, &f);
2974 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
2976 ast_mutex_unlock(&iaxsl[callno]);
2979 static int auto_congest(void *data)
2981 #ifdef SCHED_MULTITHREADED
2982 if (schedule_action(__auto_congest, data))
2984 __auto_congest(data);
2988 static unsigned int iax2_datetime(char *tz)
2994 localtime_r(&t, &tm);
2995 if (!ast_strlen_zero(tz))
2996 ast_localtime(&t, &tm, tz);
2997 tmp = (tm.tm_sec >> 1) & 0x1f; /* 5 bits of seconds */
2998 tmp |= (tm.tm_min & 0x3f) << 5; /* 6 bits of minutes */
2999 tmp |= (tm.tm_hour & 0x1f) << 11; /* 5 bits of hours */
3000 tmp |= (tm.tm_mday & 0x1f) << 16; /* 5 bits of day of month */
3001 tmp |= ((tm.tm_mon + 1) & 0xf) << 21; /* 4 bits of month */
3002 tmp |= ((tm.tm_year - 100) & 0x7f) << 25; /* 7 bits of year */
3006 struct parsed_dial_string {
3018 * \brief Parses an IAX dial string into its component parts.
3019 * \param data the string to be parsed
3020 * \param pds pointer to a \c struct \c parsed_dial_string to be filled in
3023 * This function parses the string and fills the structure
3024 * with pointers to its component parts. The input string
3027 * \note This function supports both plaintext passwords and RSA
3028 * key names; if the password string is formatted as '[keyname]',
3029 * then the keyname will be placed into the key field, and the
3030 * password field will be set to NULL.
3032 * \note The dial string format is:
3033 * [username[:password]@]peer[:port][/exten[@@context]][/options]
3035 static void parse_dial_string(char *data, struct parsed_dial_string *pds)
3037 if (ast_strlen_zero(data))
3040 pds->peer = strsep(&data, "/");
3041 pds->exten = strsep(&data, "/");
3042 pds->options = data;
3046 pds->exten = strsep(&data, "@");
3047 pds->context = data;
3050 if (strchr(pds->peer, '@')) {
3052 pds->username = strsep(&data, "@");
3056 if (pds->username) {
3057 data = pds->username;
3058 pds->username = strsep(&data, ":");
3059 pds->password = data;
3063 pds->peer = strsep(&data, ":");
3066 /* check for a key name wrapped in [] in the secret position, if found,
3067 move it to the key field instead
3069 if (pds->password && (pds->password[0] == '[')) {
3070 pds->key = ast_strip_quoted(pds->password, "[", "]");
3071 pds->password = NULL;
3075 static int iax2_call(struct ast_channel *c, char *dest, int timeout)
3077 struct sockaddr_in sin;
3078 char *l=NULL, *n=NULL, *tmpstr;
3079 struct iax_ie_data ied;
3080 char *defaultrdest = "s";
3081 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
3082 struct parsed_dial_string pds;
3083 struct create_addr_info cai;
3085 if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
3086 ast_log(LOG_WARNING, "Channel is already in use (%s)?\n", c->name);
3090 memset(&cai, 0, sizeof(cai));
3091 cai.encmethods = iax2_encryption;
3093 memset(&pds, 0, sizeof(pds));
3094 tmpstr = ast_strdupa(dest);
3095 parse_dial_string(tmpstr, &pds);
3098 pds.exten = defaultrdest;
3100 if (create_addr(pds.peer, &sin, &cai)) {
3101 ast_log(LOG_WARNING, "No address associated with '%s'\n", pds.peer);
3105 if (!pds.username && !ast_strlen_zero(cai.username))
3106 pds.username = cai.username;
3107 if (!pds.password && !ast_strlen_zero(cai.secret))
3108 pds.password = cai.secret;
3109 if (!pds.key && !ast_strlen_zero(cai.outkey))
3110 pds.key = cai.outkey;
3111 if (!pds.context && !ast_strlen_zero(cai.peercontext))
3112 pds.context = cai.peercontext;
3114 /* Keep track of the context for outgoing calls too */
3115 ast_copy_string(c->context, cai.context, sizeof(c->context));
3118 sin.sin_port = htons(atoi(pds.port));
3121 n = c->cid.cid_name;
3123 /* Now build request */
3124 memset(&ied, 0, sizeof(ied));
3126 /* On new call, first IE MUST be IAX version of caller */
3127 iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
3128 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, pds.exten);
3129 if (pds.options && strchr(pds.options, 'a')) {
3130 /* Request auto answer */
3131 iax_ie_append(&ied, IAX_IE_AUTOANSWER);
3134 iax_ie_append_str(&ied, IAX_IE_CODEC_PREFS, cai.prefs);
3137 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
3138 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
3141 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
3143 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, AST_PRES_NUMBER_NOT_AVAILABLE);
3146 iax_ie_append_byte(&ied, IAX_IE_CALLINGTON, c->cid.cid_ton);
3147 iax_ie_append_short(&ied, IAX_IE_CALLINGTNS, c->cid.cid_tns);
3150 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n);
3151 if (ast_test_flag(iaxs[callno], IAX_SENDANI) && c->cid.cid_ani)
3152 iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, c->cid.cid_ani);
3154 if (!ast_strlen_zero(c->language))
3155 iax_ie_append_str(&ied, IAX_IE_LANGUAGE, c->language);
3156 if (!ast_strlen_zero(c->cid.cid_dnid))
3157 iax_ie_append_str(&ied, IAX_IE_DNID, c->cid.cid_dnid);
3158 if (!ast_strlen_zero(c->cid.cid_rdnis))
3159 iax_ie_append_str(&ied, IAX_IE_RDNIS, c->cid.cid_rdnis);