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_user *build_user(const char *name, struct ast_variable *v, int temponly);
782 static void destroy_user(struct iax2_user *user);
783 static int expire_registry(void *data);
784 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
785 static int iax2_do_register(struct iax2_registry *reg);
786 static void prune_peers(void);
787 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
788 static int iax2_provision(struct sockaddr_in *end, int sockfd, char *dest, const char *template, int force);
790 static struct ast_channel *iax2_request(const char *type, int format, void *data, int *cause);
791 static int iax2_devicestate(void *data);
792 static int iax2_digit(struct ast_channel *c, char digit);
793 static int iax2_sendtext(struct ast_channel *c, const char *text);
794 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
795 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
796 static int iax2_call(struct ast_channel *c, char *dest, int timeout);
797 static int iax2_hangup(struct ast_channel *c);
798 static int iax2_answer(struct ast_channel *c);
799 static struct ast_frame *iax2_read(struct ast_channel *c);
800 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
801 static int iax2_indicate(struct ast_channel *c, int condition);
802 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
803 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);
804 static int iax2_transfer(struct ast_channel *c, const char *dest);
805 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
807 static const struct ast_channel_tech iax2_tech = {
809 .description = tdesc,
810 .capabilities = IAX_CAPABILITY_FULLBANDWIDTH,
811 .properties = AST_CHAN_TP_WANTSJITTER,
812 .requester = iax2_request,
813 .devicestate = iax2_devicestate,
814 .send_digit = iax2_digit,
815 .send_text = iax2_sendtext,
816 .send_image = iax2_sendimage,
817 .send_html = iax2_sendhtml,
819 .hangup = iax2_hangup,
820 .answer = iax2_answer,
823 .write_video = iax2_write,
824 .indicate = iax2_indicate,
825 .setoption = iax2_setoption,
826 .bridge = iax2_bridge,
827 .transfer = iax2_transfer,
831 static struct iax2_thread *find_idle_thread(void)
833 struct iax2_thread *thread;
834 thread = ASTOBJ_CONTAINER_UNLINK_START(&idlelist);
838 #ifdef SCHED_MULTITHREADED
839 static int __schedule_action(void (*func)(void *data), void *data, const char *funcname)
841 struct iax2_thread *thread;
842 static time_t lasterror;
844 thread = find_idle_thread();
846 thread->schedfunc = func;
847 thread->scheddata = data;
848 thread->iostate = IAX_IOSTATE_SCHEDREADY;
849 #ifdef DEBUG_SCHED_MULTITHREAD
850 ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc));
852 signal_condition(&thread->lock, &thread->cond);
857 ast_log(LOG_NOTICE, "Out of idle IAX2 threads for scheduling!\n");
861 #define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
864 static void __send_ping(void *data)
866 int callno = (long)data;
867 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
870 static int send_ping(void *data)
872 int callno = (long)data;
874 #ifdef BRIDGE_OPTIMIZATION
875 if (!iaxs[callno]->bridgecallno)
878 #ifdef SCHED_MULTITHREADED
879 if (schedule_action(__send_ping, data))
889 static int get_encrypt_methods(const char *s)
892 if (!strcasecmp(s, "aes128"))
893 e = IAX_ENCRYPT_AES128;
894 else if (ast_true(s))
895 e = IAX_ENCRYPT_AES128;
901 static void __send_lagrq(void *data)
903 int callno = (long)data;
904 /* Ping only if it's real not if it's bridged */
905 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
908 static int send_lagrq(void *data)
910 int callno = (long)data;
912 #ifdef BRIDGE_OPTIMIZATION
913 if (!iaxs[callno]->bridgecallno)
916 #ifdef SCHED_MULTITHREADED
917 if (schedule_action(__send_lagrq, data))
927 static unsigned char compress_subclass(int subclass)
931 /* If it's 128 or smaller, just return it */
932 if (subclass < IAX_FLAG_SC_LOG)
934 /* Otherwise find its power */
935 for (x = 0; x < IAX_MAX_SHIFT; x++) {
936 if (subclass & (1 << x)) {
938 ast_log(LOG_WARNING, "Can't compress subclass %d\n", subclass);
944 return power | IAX_FLAG_SC_LOG;
947 static int uncompress_subclass(unsigned char csub)
949 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
950 if (csub & IAX_FLAG_SC_LOG) {
951 /* special case for 'compressed' -1 */
955 return 1 << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
961 static struct iax2_peer *find_peer(const char *name, int realtime)
963 struct iax2_peer *peer;
964 ast_mutex_lock(&peerl.lock);
965 for(peer = peerl.peers; peer; peer = peer->next) {
966 if (!strcasecmp(peer->name, name)) {
970 ast_mutex_unlock(&peerl.lock);
971 if(!peer && realtime)
972 peer = realtime_peer(name, NULL);
976 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len, int lockpeer)
978 struct iax2_peer *peer;
982 ast_mutex_lock(&peerl.lock);
985 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
986 (peer->addr.sin_port == sin.sin_port)) {
987 ast_copy_string(host, peer->name, len);
994 ast_mutex_unlock(&peerl.lock);
996 peer = realtime_peer(NULL, &sin);
998 ast_copy_string(host, peer->name, len);
999 if (ast_test_flag(peer, IAX_TEMPONLY))
1008 static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, int lockpeer, const char *host)
1010 struct chan_iax2_pvt *tmp;
1012 if (!(tmp = ast_calloc(1, sizeof(*tmp))))
1017 tmp->peercallno = 0;
1018 tmp->transfercallno = 0;
1019 tmp->bridgecallno = 0;
1025 /* ast_copy_string(tmp->context, context, sizeof(tmp->context)); */
1026 ast_copy_string(tmp->exten, "s", sizeof(tmp->exten));
1027 ast_copy_string(tmp->host, host, sizeof(tmp->host));
1034 jbconf.max_jitterbuf = maxjitterbuffer;
1035 jbconf.resync_threshold = resyncthreshold;
1036 jbconf.max_contig_interp = maxjitterinterps;
1037 jb_setconf(tmp->jb,&jbconf);
1043 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
1045 /* Malloc() a copy of a frame */
1046 struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen);
1048 memcpy(new, fr, sizeof(struct iax_frame));
1049 iax_frame_wrap(new, &fr->af);
1052 new->direction = DIRECTION_INGRESS;
1058 #define NEW_PREVENT 0
1062 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, struct chan_iax2_pvt *cur)
1064 if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
1065 (cur->addr.sin_port == sin->sin_port)) {
1066 /* This is the main host */
1067 if ((cur->peercallno == callno) ||
1068 ((dcallno == cur->callno) && !cur->peercallno)) {
1069 /* That's us. Be sure we keep track of the peer call number */
1073 if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
1074 (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
1075 /* We're transferring */
1076 if (dcallno == cur->callno)
1082 static void update_max_trunk(void)
1084 int max = TRUNK_CALL_START;
1086 /* XXX Prolly don't need locks here XXX */
1087 for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
1092 if (option_debug && iaxdebug)
1093 ast_log(LOG_DEBUG, "New max trunk callno is %d\n", max);
1096 static void update_max_nontrunk(void)
1100 /* XXX Prolly don't need locks here XXX */
1101 for (x=1;x<TRUNK_CALL_START - 1; x++) {
1105 maxnontrunkcall = max;
1106 if (option_debug && iaxdebug)
1107 ast_log(LOG_DEBUG, "New max nontrunk callno is %d\n", max);
1110 static int make_trunk(unsigned short callno, int locked)
1115 if (iaxs[callno]->oseqno) {
1116 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
1119 if (callno & TRUNK_CALL_START) {
1120 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
1123 gettimeofday(&now, NULL);
1124 for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
1125 ast_mutex_lock(&iaxsl[x]);
1126 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) {
1127 iaxs[x] = iaxs[callno];
1128 iaxs[x]->callno = x;
1129 iaxs[callno] = NULL;
1130 /* Update the two timers that should have been started */
1131 if (iaxs[x]->pingid > -1)
1132 ast_sched_del(sched, iaxs[x]->pingid);
1133 if (iaxs[x]->lagid > -1)
1134 ast_sched_del(sched, iaxs[x]->lagid);
1135 iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
1136 iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
1138 ast_mutex_unlock(&iaxsl[callno]);
1141 ast_mutex_unlock(&iaxsl[x]);
1144 ast_mutex_unlock(&iaxsl[x]);
1146 if (x >= IAX_MAX_CALLS - 1) {
1147 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
1150 ast_log(LOG_DEBUG, "Made call %d into trunk call %d\n", callno, x);
1151 /* We move this call from a non-trunked to a trunked call */
1153 update_max_nontrunk();
1157 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int lockpeer, int sockfd)
1162 char iabuf[INET_ADDRSTRLEN];
1164 if (new <= NEW_ALLOW) {
1165 /* Look for an existing connection first */
1166 for (x=1;(res < 1) && (x<maxnontrunkcall);x++) {
1167 ast_mutex_lock(&iaxsl[x]);
1169 /* Look for an exact match */
1170 if (match(sin, callno, dcallno, iaxs[x])) {
1174 ast_mutex_unlock(&iaxsl[x]);
1176 for (x=TRUNK_CALL_START;(res < 1) && (x<maxtrunkcall);x++) {
1177 ast_mutex_lock(&iaxsl[x]);
1179 /* Look for an exact match */
1180 if (match(sin, callno, dcallno, iaxs[x])) {
1184 ast_mutex_unlock(&iaxsl[x]);
1187 if ((res < 1) && (new >= NEW_ALLOW)) {
1188 if (!iax2_getpeername(*sin, host, sizeof(host), lockpeer))
1189 snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr), ntohs(sin->sin_port));
1190 gettimeofday(&now, NULL);
1191 for (x=1;x<TRUNK_CALL_START;x++) {
1192 /* Find first unused call number that hasn't been used in a while */
1193 ast_mutex_lock(&iaxsl[x]);
1194 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) break;
1195 ast_mutex_unlock(&iaxsl[x]);
1197 /* We've still got lock held if we found a spot */
1198 if (x >= TRUNK_CALL_START) {
1199 ast_log(LOG_WARNING, "No more space\n");
1202 iaxs[x] = new_iax(sin, lockpeer, host);
1203 update_max_nontrunk();
1205 if (option_debug && iaxdebug)
1206 ast_log(LOG_DEBUG, "Creating new call structure %d\n", x);
1207 iaxs[x]->sockfd = sockfd;
1208 iaxs[x]->addr.sin_port = sin->sin_port;
1209 iaxs[x]->addr.sin_family = sin->sin_family;
1210 iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
1211 iaxs[x]->peercallno = callno;
1212 iaxs[x]->callno = x;
1213 iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
1214 iaxs[x]->expiry = min_reg_expire;
1215 iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
1216 iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
1217 iaxs[x]->amaflags = amaflags;
1218 ast_copy_flags(iaxs[x], (&globalflags), IAX_NOTRANSFER | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
1219 ast_copy_string(iaxs[x]->accountcode, accountcode, sizeof(iaxs[x]->accountcode));
1221 ast_log(LOG_WARNING, "Out of resources\n");
1222 ast_mutex_unlock(&iaxsl[x]);
1225 ast_mutex_unlock(&iaxsl[x]);
1231 static void iax2_frame_free(struct iax_frame *fr)
1233 if (fr->retrans > -1)
1234 ast_sched_del(sched, fr->retrans);
1238 static int iax2_queue_frame(int callno, struct ast_frame *f)
1240 /* Assumes lock for callno is already held... */
1242 if (iaxs[callno] && iaxs[callno]->owner) {
1243 if (ast_mutex_trylock(&iaxs[callno]->owner->lock)) {
1244 /* Avoid deadlock by pausing and trying again */
1245 ast_mutex_unlock(&iaxsl[callno]);
1247 ast_mutex_lock(&iaxsl[callno]);
1249 ast_queue_frame(iaxs[callno]->owner, f);
1250 ast_mutex_unlock(&iaxs[callno]->owner->lock);
1259 static void destroy_firmware(struct iax_firmware *cur)
1261 /* Close firmware */
1263 munmap(cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh)));
1269 static int try_firmware(char *s)
1272 struct iax_firmware *cur;
1277 struct ast_iax2_firmware_header *fwh, fwh2;
1278 struct MD5Context md5;
1279 unsigned char sum[16];
1280 unsigned char buf[1024];
1284 s2 = alloca(strlen(s) + 100);
1286 ast_log(LOG_WARNING, "Alloca failed!\n");
1289 last = strrchr(s, '/');
1294 snprintf(s2, strlen(s) + 100, "/var/tmp/%s-%ld", last, (unsigned long)rand());
1295 res = stat(s, &stbuf);
1297 ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno));
1300 /* Make sure it's not a directory */
1301 if (S_ISDIR(stbuf.st_mode))
1303 ifd = open(s, O_RDONLY);
1305 ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
1308 fd = open(s2, O_RDWR | O_CREAT | O_EXCL);
1310 ast_log(LOG_WARNING, "Cannot open '%s' for writing: %s\n", s2, strerror(errno));
1314 /* Unlink our newly created file */
1317 /* Now copy the firmware into it */
1318 len = stbuf.st_size;
1321 if (chunk > sizeof(buf))
1322 chunk = sizeof(buf);
1323 res = read(ifd, buf, chunk);
1325 ast_log(LOG_WARNING, "Only read %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1330 res = write(fd, buf, chunk);
1332 ast_log(LOG_WARNING, "Only write %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1340 /* Return to the beginning */
1341 lseek(fd, 0, SEEK_SET);
1342 if ((res = read(fd, &fwh2, sizeof(fwh2))) != sizeof(fwh2)) {
1343 ast_log(LOG_WARNING, "Unable to read firmware header in '%s'\n", s);
1347 if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) {
1348 ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s);
1352 if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) {
1353 ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s);
1357 if (fwh2.devname[sizeof(fwh2.devname) - 1] || ast_strlen_zero((char *)fwh2.devname)) {
1358 ast_log(LOG_WARNING, "No or invalid device type specified for '%s'\n", s);
1362 fwh = mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
1364 ast_log(LOG_WARNING, "mmap failed: %s\n", strerror(errno));
1369 MD5Update(&md5, fwh->data, ntohl(fwh->datalen));
1370 MD5Final(sum, &md5);
1371 if (memcmp(sum, fwh->chksum, sizeof(sum))) {
1372 ast_log(LOG_WARNING, "Firmware file '%s' fails checksum\n", s);
1373 munmap(fwh, stbuf.st_size);
1379 if (!strcmp((char *)cur->fwh->devname, (char *)fwh->devname)) {
1380 /* Found a candidate */
1381 if (cur->dead || (ntohs(cur->fwh->version) < ntohs(fwh->version)))
1382 /* The version we have on loaded is older, load this one instead */
1384 /* This version is no newer than what we have. Don't worry about it.
1385 We'll consider it a proper load anyhow though */
1386 munmap(fwh, stbuf.st_size);
1393 /* Allocate a new one and link it */
1394 if ((cur = ast_calloc(1, sizeof(*cur)))) {
1396 cur->next = waresl.wares;
1402 munmap(cur->fwh, cur->mmaplen);
1408 cur->mmaplen = stbuf.st_size;
1414 static int iax_check_version(char *dev)
1417 struct iax_firmware *cur;
1418 if (!ast_strlen_zero(dev)) {
1419 ast_mutex_lock(&waresl.lock);
1422 if (!strcmp(dev, (char *)cur->fwh->devname)) {
1423 res = ntohs(cur->fwh->version);
1428 ast_mutex_unlock(&waresl.lock);
1433 static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
1436 unsigned int bs = desc & 0xff;
1437 unsigned int start = (desc >> 8) & 0xffffff;
1439 struct iax_firmware *cur;
1440 if (!ast_strlen_zero((char *)dev) && bs) {
1442 ast_mutex_lock(&waresl.lock);
1445 if (!strcmp((char *)dev, (char *)cur->fwh->devname)) {
1446 iax_ie_append_int(ied, IAX_IE_FWBLOCKDESC, desc);
1447 if (start < ntohl(cur->fwh->datalen)) {
1448 bytes = ntohl(cur->fwh->datalen) - start;
1451 iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes);
1454 iax_ie_append(ied, IAX_IE_FWBLOCKDATA);
1464 ast_mutex_unlock(&waresl.lock);
1470 static void reload_firmware(void)
1472 struct iax_firmware *cur, *curl, *curp;
1477 /* Mark all as dead */
1478 ast_mutex_lock(&waresl.lock);
1484 /* Now that we've freed them, load the new ones */
1485 snprintf(dir, sizeof(dir), "%s/firmware/iax", (char *)ast_config_AST_VAR_DIR);
1488 while((de = readdir(fwd))) {
1489 if (de->d_name[0] != '.') {
1490 snprintf(fn, sizeof(fn), "%s/%s", dir, de->d_name);
1491 if (!try_firmware(fn)) {
1492 if (option_verbose > 1)
1493 ast_verbose(VERBOSE_PREFIX_2 "Loaded firmware '%s'\n", de->d_name);
1499 ast_log(LOG_WARNING, "Error opening firmware directory '%s': %s\n", dir, strerror(errno));
1501 /* Clean up leftovers */
1513 destroy_firmware(curl);
1518 ast_mutex_unlock(&waresl.lock);
1521 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
1523 static int __do_deliver(void *data)
1525 /* Just deliver the packet by using queueing. This is called by
1526 the IAX thread with the iaxsl lock held. */
1527 struct iax_frame *fr = data;
1529 if (iaxs[fr->callno] && !ast_test_flag(iaxs[fr->callno], IAX_ALREADYGONE))
1530 iax2_queue_frame(fr->callno, &fr->af);
1531 /* Free our iax frame */
1532 iax2_frame_free(fr);
1533 /* And don't run again */
1538 static int __real_do_deliver(void *data)
1540 /* Locking version of __do_deliver */
1541 struct iax_frame *fr = data;
1542 int callno = fr->callno;
1544 ast_mutex_lock(&iaxsl[callno]);
1545 res = __do_deliver(data);
1546 ast_mutex_unlock(&iaxsl[callno]);
1549 static int do_deliver(void *data)
1551 #ifdef SCHED_MULTITHREADED
1552 if (schedule_action(__do_deliver, data))
1554 __real_do_deliver(data);
1559 static int handle_error(void)
1561 /* XXX Ideally we should figure out why an error occured and then abort those
1562 rather than continuing to try. Unfortunately, the published interface does
1563 not seem to work XXX */
1565 struct sockaddr_in *sin;
1568 struct sock_extended_err e;
1573 m.msg_controllen = sizeof(e);
1575 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
1577 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
1579 if (m.msg_controllen) {
1580 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
1582 ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr));
1584 ast_log(LOG_WARNING, "No address detected??\n");
1586 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
1593 static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin, int sockfd)
1596 res = sendto(sockfd, f->data, f->datalen, 0,(struct sockaddr *)sin,
1600 ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
1607 static int send_packet(struct iax_frame *f)
1610 char iabuf[INET_ADDRSTRLEN];
1611 int callno = f->callno;
1613 /* Called with iaxsl held */
1616 if (option_debug > 2 && iaxdebug)
1617 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));
1618 /* Don't send if there was an error, but return error instead */
1620 ast_log(LOG_WARNING, "Call number = %d\n", callno);
1623 if (iaxs[callno]->error)
1627 iax_showframe(f, NULL, 0, &iaxs[callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
1628 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->transfer,
1629 sizeof(iaxs[callno]->transfer));
1632 iax_showframe(f, NULL, 0, &iaxs[callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
1633 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->addr,
1634 sizeof(iaxs[callno]->addr));
1637 if (option_debug && iaxdebug)
1638 ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
1646 static int iax2_predestroy(int callno)
1648 struct ast_channel *c;
1649 struct chan_iax2_pvt *pvt;
1650 ast_mutex_lock(&iaxsl[callno]);
1653 ast_mutex_unlock(&iaxsl[callno]);
1656 if (!ast_test_flag(pvt, IAX_ALREADYGONE)) {
1657 /* No more pings or lagrq's */
1658 if (pvt->pingid > -1)
1659 ast_sched_del(sched, pvt->pingid);
1660 if (pvt->lagid > -1)
1661 ast_sched_del(sched, pvt->lagid);
1662 if (pvt->autoid > -1)
1663 ast_sched_del(sched, pvt->autoid);
1664 if (pvt->authid > -1)
1665 ast_sched_del(sched, pvt->authid);
1666 if (pvt->initid > -1)
1667 ast_sched_del(sched, pvt->initid);
1670 ast_sched_del(sched, pvt->jbid);
1678 ast_set_flag(pvt, IAX_ALREADYGONE);
1682 c->_softhangup |= AST_SOFTHANGUP_DEV;
1684 ast_queue_hangup(c);
1686 ast_mutex_lock(&usecnt_lock);
1689 ast_log(LOG_WARNING, "Usecnt < 0???\n");
1690 ast_mutex_unlock(&usecnt_lock);
1692 ast_mutex_unlock(&iaxsl[callno]);
1693 ast_update_use_count();
1697 static int iax2_predestroy_nolock(int callno)
1700 ast_mutex_unlock(&iaxsl[callno]);
1701 res = iax2_predestroy(callno);
1702 ast_mutex_lock(&iaxsl[callno]);
1706 static void iax2_destroy(int callno)
1708 struct chan_iax2_pvt *pvt;
1709 struct iax_frame *cur;
1710 struct ast_channel *owner;
1713 ast_mutex_lock(&iaxsl[callno]);
1715 gettimeofday(&lastused[callno], NULL);
1717 owner = pvt ? pvt->owner : NULL;
1720 if (ast_mutex_trylock(&owner->lock)) {
1721 ast_log(LOG_NOTICE, "Avoiding IAX destroy deadlock\n");
1722 ast_mutex_unlock(&iaxsl[callno]);
1728 iaxs[callno] = NULL;
1732 /* No more pings or lagrq's */
1733 if (pvt->pingid > -1)
1734 ast_sched_del(sched, pvt->pingid);
1735 if (pvt->lagid > -1)
1736 ast_sched_del(sched, pvt->lagid);
1737 if (pvt->autoid > -1)
1738 ast_sched_del(sched, pvt->autoid);
1739 if (pvt->authid > -1)
1740 ast_sched_del(sched, pvt->authid);
1741 if (pvt->initid > -1)
1742 ast_sched_del(sched, pvt->initid);
1745 ast_sched_del(sched, pvt->jbid);
1753 if (pvt->bridgetrans)
1754 ast_translator_free_path(pvt->bridgetrans);
1755 pvt->bridgetrans = NULL;
1758 ast_set_flag(pvt, IAX_ALREADYGONE);
1761 /* If there's an owner, prod it to give up */
1762 owner->_softhangup |= AST_SOFTHANGUP_DEV;
1763 ast_queue_hangup(owner);
1766 for (cur = iaxq.head; cur ; cur = cur->next) {
1767 /* Cancel any pending transmissions */
1768 if (cur->callno == pvt->callno)
1772 pvt->reg->callno = 0;
1775 ast_variables_destroy(pvt->vars);
1781 while(jb_getall(pvt->jb,&frame) == JB_OK)
1782 iax2_frame_free(frame.data);
1783 jb_destroy(pvt->jb);
1790 ast_mutex_unlock(&owner->lock);
1792 ast_mutex_unlock(&iaxsl[callno]);
1793 if (callno & 0x4000)
1796 static void iax2_destroy_nolock(int callno)
1798 /* Actually it's easier to unlock, kill it, and relock */
1799 ast_mutex_unlock(&iaxsl[callno]);
1800 iax2_destroy(callno);
1801 ast_mutex_lock(&iaxsl[callno]);
1804 static int update_packet(struct iax_frame *f)
1806 /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
1807 struct ast_iax2_full_hdr *fh = f->data;
1808 /* Mark this as a retransmission */
1809 fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
1811 f->iseqno = iaxs[f->callno]->iseqno;
1812 fh->iseqno = f->iseqno;
1816 static int attempt_transmit(void *data);
1817 static void __attempt_transmit(void *data)
1819 /* Attempt to transmit the frame to the remote peer...
1820 Called without iaxsl held. */
1821 struct iax_frame *f = data;
1823 int callno = f->callno;
1824 char iabuf[INET_ADDRSTRLEN];
1825 /* Make sure this call is still active */
1827 ast_mutex_lock(&iaxsl[callno]);
1828 if (callno && iaxs[callno]) {
1829 if ((f->retries < 0) /* Already ACK'd */ ||
1830 (f->retries >= max_retries) /* Too many attempts */) {
1831 /* Record an error if we've transmitted too many times */
1832 if (f->retries >= max_retries) {
1834 /* Transfer timeout */
1835 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
1836 } else if (f->final) {
1838 iax2_destroy_nolock(callno);
1840 if (iaxs[callno]->owner)
1841 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);
1842 iaxs[callno]->error = ETIMEDOUT;
1843 if (iaxs[callno]->owner) {
1844 struct ast_frame fr = { 0, };
1846 fr.frametype = AST_FRAME_CONTROL;
1847 fr.subclass = AST_CONTROL_HANGUP;
1848 iax2_queue_frame(callno, &fr);
1849 /* Remember, owner could disappear */
1850 if (iaxs[callno]->owner)
1851 iaxs[callno]->owner->hangupcause = AST_CAUSE_DESTINATION_OUT_OF_ORDER;
1853 if (iaxs[callno]->reg) {
1854 memset(&iaxs[callno]->reg->us, 0, sizeof(iaxs[callno]->reg->us));
1855 iaxs[callno]->reg->regstate = REG_STATE_TIMEOUT;
1856 iaxs[callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
1858 iax2_destroy_nolock(callno);
1865 /* Update it if it needs it */
1867 /* Attempt transmission */
1870 /* Try again later after 10 times as long */
1872 if (f->retrytime > MAX_RETRY_TIME)
1873 f->retrytime = MAX_RETRY_TIME;
1874 /* Transfer messages max out at one second */
1875 if (f->transfer && (f->retrytime > 1000))
1876 f->retrytime = 1000;
1877 f->retrans = ast_sched_add(sched, f->retrytime, attempt_transmit, f);
1880 /* Make sure it gets freed */
1885 ast_mutex_unlock(&iaxsl[callno]);
1886 /* Do not try again */
1888 /* Don't attempt delivery, just remove it from the queue */
1889 ast_mutex_lock(&iaxq.lock);
1891 f->prev->next = f->next;
1893 iaxq.head = f->next;
1895 f->next->prev = f->prev;
1897 iaxq.tail = f->prev;
1899 ast_mutex_unlock(&iaxq.lock);
1901 /* Free the IAX frame */
1906 static int attempt_transmit(void *data)
1908 #ifdef SCHED_MULTITHREADED
1909 if (schedule_action(__attempt_transmit, data))
1911 __attempt_transmit(data);
1915 static int iax2_set_jitter(int fd, int argc, char *argv[])
1918 ast_cli(fd, "sorry, this command is deprecated\n");
1919 return RESULT_SUCCESS;
1921 if ((argc != 4) && (argc != 5))
1922 return RESULT_SHOWUSAGE;
1924 max_jitter_buffer = atoi(argv[3]);
1925 if (max_jitter_buffer < 0)
1926 max_jitter_buffer = 0;
1929 int callno = atoi(argv[3]);
1930 if ((callno >= 0) && (callno < IAX_MAX_CALLS)) {
1932 iaxs[callno]->jitterbuffer = atoi(argv[4]);
1933 if (iaxs[callno]->jitterbuffer < 0)
1934 iaxs[callno]->jitterbuffer = 0;
1936 ast_cli(fd, "No such call '%d'\n", callno);
1938 ast_cli(fd, "%d is not a valid call number\n", callno);
1941 return RESULT_SUCCESS;
1945 static char jitter_usage[] =
1946 "Usage: iax set jitter [callid] <value>\n"
1947 " If used with a callid, it sets the jitter buffer to the given static\n"
1948 "value (until its next calculation). If used without a callid, the value is used\n"
1949 "to establish the maximum excess jitter buffer that is permitted before the jitter\n"
1950 "buffer size is reduced.";
1952 static int iax2_prune_realtime(int fd, int argc, char *argv[])
1954 struct iax2_peer *peer;
1957 return RESULT_SHOWUSAGE;
1958 if (!strcmp(argv[3],"all")) {
1960 ast_cli(fd, "OK cache is flushed.\n");
1961 } else if ((peer = find_peer(argv[3], 0))) {
1962 if(ast_test_flag(peer, IAX_RTCACHEFRIENDS)) {
1963 ast_set_flag(peer, IAX_RTAUTOCLEAR);
1964 expire_registry(peer);
1965 ast_cli(fd, "OK peer %s was removed from the cache.\n", argv[3]);
1967 ast_cli(fd, "SORRY peer %s is not eligible for this operation.\n", argv[3]);
1970 ast_cli(fd, "SORRY peer %s was not found in the cache.\n", argv[3]);
1973 return RESULT_SUCCESS;
1976 static int iax2_test_losspct(int fd, int argc, char *argv[])
1979 return RESULT_SHOWUSAGE;
1981 test_losspct = atoi(argv[3]);
1983 return RESULT_SUCCESS;
1987 static int iax2_test_late(int fd, int argc, char *argv[])
1990 return RESULT_SHOWUSAGE;
1992 test_late = atoi(argv[3]);
1994 return RESULT_SUCCESS;
1997 static int iax2_test_resync(int fd, int argc, char *argv[])
2000 return RESULT_SHOWUSAGE;
2002 test_resync = atoi(argv[3]);
2004 return RESULT_SUCCESS;
2007 static int iax2_test_jitter(int fd, int argc, char *argv[])
2009 if (argc < 4 || argc > 5)
2010 return RESULT_SHOWUSAGE;
2012 test_jit = atoi(argv[3]);
2014 test_jitpct = atoi(argv[4]);
2016 return RESULT_SUCCESS;
2018 #endif /* IAXTESTS */
2020 /*! \brief peer_status: Report Peer status in character string */
2021 /* returns 1 if peer is online, -1 if unmonitored */
2022 static int peer_status(struct iax2_peer *peer, char *status, int statuslen)
2026 if (peer->lastms < 0) {
2027 ast_copy_string(status, "UNREACHABLE", statuslen);
2028 } else if (peer->lastms > peer->maxms) {
2029 snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
2031 } else if (peer->lastms) {
2032 snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
2035 ast_copy_string(status, "UNKNOWN", statuslen);
2038 ast_copy_string(status, "Unmonitored", statuslen);
2044 /*! \brief Show one peer in detail */
2045 static int iax2_show_peer(int fd, int argc, char *argv[])
2049 char iabuf[INET_ADDRSTRLEN];
2050 struct iax2_peer *peer;
2051 char codec_buf[512];
2052 int x = 0, codec = 0, load_realtime = 0;
2055 return RESULT_SHOWUSAGE;
2057 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? 1 : 0;
2059 peer = find_peer(argv[3], load_realtime);
2062 ast_cli(fd, " * Name : %s\n", peer->name);
2063 ast_cli(fd, " Secret : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
2064 ast_cli(fd, " Context : %s\n", peer->context);
2065 ast_cli(fd, " Mailbox : %s\n", peer->mailbox);
2066 ast_cli(fd, " Dynamic : %s\n", ast_test_flag(peer, IAX_DYNAMIC) ? "Yes":"No");
2067 ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
2068 ast_cli(fd, " Expire : %d\n", peer->expire);
2069 ast_cli(fd, " ACL : %s\n", (peer->ha?"Yes":"No"));
2070 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));
2071 ast_cli(fd, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
2072 ast_cli(fd, " Username : %s\n", peer->username);
2073 ast_cli(fd, " Codecs : ");
2074 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
2075 ast_cli(fd, "%s\n", codec_buf);
2077 ast_cli(fd, " Codec Order : (");
2078 for(x = 0; x < 32 ; x++) {
2079 codec = ast_codec_pref_index(&peer->prefs,x);
2082 ast_cli(fd, "%s", ast_getformatname(codec));
2083 if(x < 31 && ast_codec_pref_index(&peer->prefs,x+1))
2088 ast_cli(fd, "none");
2091 ast_cli(fd, " Status : ");
2092 peer_status(peer, status, sizeof(status));
2093 ast_cli(fd, "%s\n",status);
2094 ast_cli(fd, " Qualify : every %dms when OK, every %dms when UNREACHABLE (sample smoothing %s)\n", peer->pokefreqok, peer->pokefreqnotok, peer->smoothing ? "On" : "Off");
2096 if (ast_test_flag(peer, IAX_TEMPONLY))
2099 ast_cli(fd,"Peer %s not found.\n", argv[3]);
2103 return RESULT_SUCCESS;
2106 static char *complete_iax2_show_peer(const char *line, const char *word, int pos, int state)
2109 struct iax2_peer *p;
2111 int wordlen = strlen(word);
2113 /* 0 - iax2; 1 - show; 2 - peer; 3 - <peername> */
2115 ast_mutex_lock(&peerl.lock);
2116 for (p = peerl.peers ; p ; p = p->next) {
2117 if (!strncasecmp(p->name, word, wordlen) && ++which > state) {
2118 res = ast_strdup(p->name);
2122 ast_mutex_unlock(&peerl.lock);
2128 static int iax2_show_stats(int fd, int argc, char *argv[])
2130 struct iax_frame *cur;
2131 int cnt = 0, dead=0, final=0;
2133 return RESULT_SHOWUSAGE;
2134 for (cur = iaxq.head; cur ; cur = cur->next) {
2135 if (cur->retries < 0)
2141 ast_cli(fd, " IAX Statistics\n");
2142 ast_cli(fd, "---------------------\n");
2143 ast_cli(fd, "Outstanding frames: %d (%d ingress, %d egress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
2144 ast_cli(fd, "Packets in transmit queue: %d dead, %d final, %d total\n", dead, final, cnt);
2145 return RESULT_SUCCESS;
2148 static int iax2_show_cache(int fd, int argc, char *argv[])
2150 struct iax2_dpcache *dp;
2151 char tmp[1024], *pc;
2155 gettimeofday(&tv, NULL);
2156 ast_mutex_lock(&dpcache_lock);
2158 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
2160 s = dp->expiry.tv_sec - tv.tv_sec;
2162 if (dp->flags & CACHE_FLAG_EXISTS)
2163 strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
2164 if (dp->flags & CACHE_FLAG_NONEXISTENT)
2165 strncat(tmp, "NONEXISTENT|", sizeof(tmp) - strlen(tmp) - 1);
2166 if (dp->flags & CACHE_FLAG_CANEXIST)
2167 strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
2168 if (dp->flags & CACHE_FLAG_PENDING)
2169 strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
2170 if (dp->flags & CACHE_FLAG_TIMEOUT)
2171 strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
2172 if (dp->flags & CACHE_FLAG_TRANSMITTED)
2173 strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
2174 if (dp->flags & CACHE_FLAG_MATCHMORE)
2175 strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
2176 if (dp->flags & CACHE_FLAG_UNKNOWN)
2177 strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
2178 /* Trim trailing pipe */
2179 if (!ast_strlen_zero(tmp))
2180 tmp[strlen(tmp) - 1] = '\0';
2182 ast_copy_string(tmp, "(none)", sizeof(tmp));
2184 pc = strchr(dp->peercontext, '@');
2186 pc = dp->peercontext;
2189 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
2190 if (dp->waiters[x] > -1)
2193 ast_cli(fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
2195 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
2198 ast_mutex_unlock(&dpcache_lock);
2199 return RESULT_SUCCESS;
2202 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
2204 #ifdef BRIDGE_OPTIMIZATION
2205 static unsigned int calc_fakestamp(struct chan_iax2_pvt *from, struct chan_iax2_pvt *to, unsigned int ts);
2207 static int forward_delivery(struct iax_frame *fr)
2209 struct chan_iax2_pvt *p1, *p2;
2210 char iabuf[INET_ADDRSTRLEN];
2213 p1 = iaxs[fr->callno];
2214 p2 = iaxs[p1->bridgecallno];
2221 ast_log(LOG_DEBUG, "forward_delivery: Forwarding ts=%d on %d/%d to %d/%d on %s:%d\n",
2223 p1->callno, p1->peercallno,
2224 p2->callno, p2->peercallno,
2225 ast_inet_ntoa(iabuf, sizeof(iabuf), p2->addr.sin_addr),
2226 ntohs(p2->addr.sin_port));
2228 /* Undo wraparound - which can happen when full VOICE frame wasn't sent by our peer.
2229 This is necessary for when our peer is chan_iax2.c v1.1nn or earlier which didn't
2230 send full frame on timestamp wrap when doing optimized bridging
2231 (actually current code STILL doesn't)
2233 if (fr->ts + 50000 <= p1->last) {
2234 fr->ts = ( (p1->last & 0xFFFF0000) + 0x10000) | (fr->ts & 0xFFFF);
2236 ast_log(LOG_DEBUG, "forward_delivery: pushed forward timestamp to %u\n", fr->ts);
2239 /* Send with timestamp adjusted to the origin of the outbound leg */
2240 /* But don't destroy inbound timestamp still needed later to set "last" */
2242 fr->ts = calc_fakestamp(p1, p2, fr->ts);
2243 res = iax2_send(p2, &fr->af, fr->ts, -1, 0, 0, 0);
2249 static void unwrap_timestamp(struct iax_frame *fr)
2253 if ( (fr->ts & 0xFFFF0000) == (iaxs[fr->callno]->last & 0xFFFF0000) ) {
2254 x = fr->ts - iaxs[fr->callno]->last;
2256 /* Sudden big jump backwards in timestamp:
2257 What likely happened here is that miniframe timestamp has circled but we haven't
2258 gotten the update from the main packet. We'll just pretend that we did, and
2259 update the timestamp appropriately. */
2260 fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) + 0x10000) | (fr->ts & 0xFFFF);
2261 if (option_debug && iaxdebug)
2262 ast_log(LOG_DEBUG, "schedule_delivery: pushed forward timestamp\n");
2265 /* Sudden apparent big jump forwards in timestamp:
2266 What's likely happened is this is an old miniframe belonging to the previous
2267 top-16-bit timestamp that has turned up out of order.
2268 Adjust the timestamp appropriately. */
2269 fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) - 0x10000) | (fr->ts & 0xFFFF);
2270 if (option_debug && iaxdebug)
2271 ast_log(LOG_DEBUG, "schedule_delivery: pushed back timestamp\n");
2277 static int get_from_jb(void *p);
2279 static void update_jbsched(struct chan_iax2_pvt *pvt) {
2282 when = ast_tvdiff_ms(ast_tvnow(), pvt->rxcore);
2284 /* fprintf(stderr, "now = %d, next=%d\n", when, jb_next(pvt->jb)); */
2286 when = jb_next(pvt->jb) - when;
2287 /* fprintf(stderr, "when = %d\n", when); */
2289 if(pvt->jbid > -1) ast_sched_del(sched, pvt->jbid);
2292 /* XXX should really just empty until when > 0.. */
2296 pvt->jbid = ast_sched_add(sched, when, get_from_jb, (void *)pvt);
2298 /* Signal scheduler thread */
2299 signal_condition(&sched_lock, &sched_cond);
2302 static void __get_from_jb(void *p)
2304 /* make sure pvt is valid! */
2305 struct chan_iax2_pvt *pvt = p;
2306 struct iax_frame *fr;
2313 ast_mutex_lock(&iaxsl[pvt->callno]);
2314 /* fprintf(stderr, "get_from_jb called\n"); */
2317 gettimeofday(&tv,NULL);
2318 /* round up a millisecond since ast_sched_runq does; */
2319 /* prevents us from spinning while waiting for our now */
2320 /* to catch up with runq's now */
2323 now = ast_tvdiff_ms(tv, pvt->rxcore);
2325 if(now >= (next = jb_next(pvt->jb))) {
2326 ret = jb_get(pvt->jb,&frame,now,ast_codec_interp_len(pvt->voiceformat));
2329 /*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); */
2335 struct ast_frame af;
2337 /*if(next + 20 != jb_next(pvt->jb)) fprintf(stderr, "NEXT %ld is not %ld+20!\n", jb_next(pvt->jb), next); */
2339 /* create an interpolation frame */
2340 /*fprintf(stderr, "Making Interpolation frame\n"); */
2341 af.frametype = AST_FRAME_VOICE;
2342 af.subclass = pvt->voiceformat;
2344 af.samples = frame.ms * 8;
2346 af.src = "IAX2 JB interpolation";
2348 af.delivery = ast_tvadd(pvt->rxcore, ast_samp2tv(next, 1000));
2349 af.offset=AST_FRIENDLY_OFFSET;
2351 /* queue the frame: For consistency, we would call __do_deliver here, but __do_deliver wants an iax_frame,
2352 * which we'd need to malloc, and then it would free it. That seems like a drag */
2353 if (iaxs[pvt->callno] && !ast_test_flag(iaxs[pvt->callno], IAX_ALREADYGONE))
2354 iax2_queue_frame(pvt->callno, &af);
2358 /*if(next != jb_next(pvt->jb)) fprintf(stderr, "NEXT %ld is not next %ld!\n", jb_next(pvt->jb), next); */
2359 iax2_frame_free(frame.data);
2366 /* shouldn't happen */
2370 update_jbsched(pvt);
2371 ast_mutex_unlock(&iaxsl[pvt->callno]);
2374 static int get_from_jb(void *data)
2376 #ifdef SCHED_MULTITHREADED
2377 if (schedule_action(__get_from_jb, data))
2379 __get_from_jb(data);
2384 /* while we transition from the old JB to the new one, we can either make two schedule_delivery functions, or
2385 * make preprocessor swiss-cheese out of this one. I'm not sure which is less revolting.. */
2386 static int schedule_delivery(struct iax_frame *fr, int updatehistory, int fromtrunk, unsigned int *tsout)
2396 unsigned int orig_ts;
2397 int drops[MEMORY_SIZE];
2398 int min, max=0, prevjitterbuffer, maxone=0,y,z, match;
2400 /* Remember current jitterbuffer so we can log any change */
2401 prevjitterbuffer = iaxs[fr->callno]->jitterbuffer;
2402 /* Similarly for the frame timestamp */
2407 if (option_debug && iaxdebug)
2408 ast_log(LOG_DEBUG, "schedule_delivery: ts=%d, last=%d, update=%d\n",
2409 fr->ts, iaxs[fr->callno]->last, updatehistory);
2412 /* Attempt to recover wrapped timestamps */
2413 unwrap_timestamp(fr);
2415 if (updatehistory) {
2418 /* Attempt to spot a change of timebase on timestamps coming from the other side
2419 We detect by noticing a jump in consecutive timestamps that can't reasonably be explained
2420 by network jitter or reordering. Sometimes, also, the peer stops sending us frames
2421 for a while - in this case this code might also resync us. But that's not a bad thing.
2422 Be careful of non-voice frames which are timestamped differently (especially ACKS!)
2423 [that's why we only do this when updatehistory is true]
2425 x = fr->ts - iaxs[fr->callno]->last;
2426 if (x > TS_GAP_FOR_JB_RESYNC || x < -TS_GAP_FOR_JB_RESYNC) {
2427 if (option_debug && iaxdebug)
2428 ast_log(LOG_DEBUG, "schedule_delivery: call=%d: TS jumped. resyncing rxcore (ts=%d, last=%d)\n",
2429 fr->callno, fr->ts, iaxs[fr->callno]->last);
2430 /* zap rxcore - calc_rxstamp will make a new one based on this frame */
2431 iaxs[fr->callno]->rxcore = ast_tv(0, 0);
2432 /* wipe "last" if stamps have jumped backwards */
2434 iaxs[fr->callno]->last = 0;
2435 /* should we also empty history? */
2437 /* ms is a measure of the "lateness" of the frame relative to the "reference"
2438 frame we received. (initially the very first, but also see code just above here).
2439 Understand that "ms" can easily be -ve if lag improves since the reference frame.
2440 Called by IAX thread, with iaxsl lock held. */
2441 ms = calc_rxstamp(iaxs[fr->callno], fr->ts) - fr->ts;
2443 /* Rotate our history queue of "lateness". Don't worry about those initial
2444 zeros because the first entry will always be zero */
2445 for (x=0;x<MEMORY_SIZE - 1;x++)
2446 iaxs[fr->callno]->history[x] = iaxs[fr->callno]->history[x+1];
2447 /* Add a history entry for this one */
2448 iaxs[fr->callno]->history[x] = ms;
2457 /* delivery time is sender's sent timestamp converted back into absolute time according to our clock */
2458 if ( !fromtrunk && !ast_tvzero(iaxs[fr->callno]->rxcore))
2459 fr->af.delivery = ast_tvadd(iaxs[fr->callno]->rxcore, ast_samp2tv(fr->ts, 1000));
2462 ast_log(LOG_DEBUG, "schedule_delivery: set delivery to 0 as we don't have an rxcore yet, or frame is from trunk.\n");
2464 fr->af.delivery = ast_tv(0,0);
2468 /* Initialize the minimum to reasonable values. It's too much
2469 work to do the same for the maximum, repeatedly */
2470 min=iaxs[fr->callno]->history[0];
2471 for (z=0;z < iax2_dropcount + 1;z++) {
2472 /* Start very optimistic ;-) */
2474 for (x=0;x<MEMORY_SIZE;x++) {
2475 if (max < iaxs[fr->callno]->history[x]) {
2476 /* We have a candidate new maximum value. Make
2477 sure it's not in our drop list */
2479 for (y=0;!match && (y<z);y++)
2480 match |= (drops[y] == x);
2482 /* It's not in our list, use it as the new maximum */
2483 max = iaxs[fr->callno]->history[x];
2489 /* On our first pass, find the minimum too */
2490 if (min > iaxs[fr->callno]->history[x])
2491 min = iaxs[fr->callno]->history[x];
2501 type = JB_TYPE_CONTROL;
2504 if(fr->af.frametype == AST_FRAME_VOICE) {
2505 type = JB_TYPE_VOICE;
2506 len = ast_codec_get_samples(&fr->af) / 8;
2507 } else if(fr->af.frametype == AST_FRAME_CNG) {
2508 type = JB_TYPE_SILENCE;
2511 if ( (!ast_test_flag(iaxs[fr->callno], IAX_USEJITTERBUF)) ) {
2518 /* if the user hasn't requested we force the use of the jitterbuffer, and we're bridged to
2519 * a channel that can accept jitter, then flush and suspend the jb, and send this frame straight through */
2520 if( (!ast_test_flag(iaxs[fr->callno], IAX_FORCEJITTERBUF)) &&
2521 iaxs[fr->callno]->owner && ast_bridged_channel(iaxs[fr->callno]->owner) &&
2522 (ast_bridged_channel(iaxs[fr->callno]->owner)->tech->properties & AST_CHAN_TP_WANTSJITTER)) {
2525 /* deliver any frames in the jb */
2526 while(jb_getall(iaxs[fr->callno]->jb,&frame) == JB_OK)
2527 __do_deliver(frame.data);
2529 jb_reset(iaxs[fr->callno]->jb);
2531 if (iaxs[fr->callno]->jbid > -1)
2532 ast_sched_del(sched, iaxs[fr->callno]->jbid);
2534 iaxs[fr->callno]->jbid = -1;
2536 /* deliver this frame now */
2545 /* insert into jitterbuffer */
2546 /* TODO: Perhaps we could act immediately if it's not droppable and late */
2547 ret = jb_put(iaxs[fr->callno]->jb, fr, type, len, fr->ts,
2548 calc_rxstamp(iaxs[fr->callno],fr->ts));
2549 if (ret == JB_DROP) {
2551 } else if (ret == JB_SCHED) {
2552 update_jbsched(iaxs[fr->callno]);
2555 /* Just for reference, keep the "jitter" value, the difference between the
2556 earliest and the latest. */
2558 iaxs[fr->callno]->jitter = max - min;
2560 /* IIR filter for keeping track of historic jitter, but always increase
2561 historic jitter immediately for increase */
2563 if (iaxs[fr->callno]->jitter > iaxs[fr->callno]->historicjitter )
2564 iaxs[fr->callno]->historicjitter = iaxs[fr->callno]->jitter;
2566 iaxs[fr->callno]->historicjitter = GAMMA * (double)iaxs[fr->callno]->jitter + (1-GAMMA) *
2567 iaxs[fr->callno]->historicjitter;
2569 /* If our jitter buffer is too big (by a significant margin), then we slowly
2570 shrink it to avoid letting the change be perceived */
2571 if (max < iaxs[fr->callno]->jitterbuffer - max_jitter_buffer)
2572 iaxs[fr->callno]->jitterbuffer -= jittershrinkrate;
2574 /* If our jitter buffer headroom is too small (by a significant margin), then we slowly enlarge it */
2575 /* min_jitter_buffer should be SMALLER than max_jitter_buffer - leaving a "no mans land"
2576 in between - otherwise the jitterbuffer size will hunt up and down causing unnecessary
2577 disruption. Set maxexcessbuffer to say 150msec, minexcessbuffer to say 50 */
2578 if (max > iaxs[fr->callno]->jitterbuffer - min_jitter_buffer)
2579 iaxs[fr->callno]->jitterbuffer += jittershrinkrate;
2581 /* If our jitter buffer is smaller than our maximum delay, grow the jitter
2582 buffer immediately to accomodate it (and a little more). */
2583 if (max > iaxs[fr->callno]->jitterbuffer)
2584 iaxs[fr->callno]->jitterbuffer = max
2585 /* + ((float)iaxs[fr->callno]->jitter) * 0.1 */;
2587 /* update "min", just for RRs and stats */
2588 iaxs[fr->callno]->min = min;
2590 /* Subtract the lateness from our jitter buffer to know how long to wait
2591 before sending our packet. */
2592 delay = iaxs[fr->callno]->jitterbuffer - ms;
2594 /* Whatever happens, no frame waits longer than maxjitterbuffer */
2595 if (delay > maxjitterbuffer)
2596 delay = maxjitterbuffer;
2598 /* If jitter buffer is disabled then just pretend the frame is "right on time" */
2599 /* If frame came from trunk, also don't do any delay */
2600 if ( (!ast_test_flag(iaxs[fr->callno], IAX_USEJITTERBUF)) || fromtrunk )
2603 if (option_debug && iaxdebug) {
2604 /* Log jitter stats for possible offline analysis */
2605 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",
2606 fr->callno, fr->ts, orig_ts, iaxs[fr->callno]->last,
2607 (fr->af.frametype == AST_FRAME_VOICE) ? "VOICE" : "CONTROL",
2608 min, max, iaxs[fr->callno]->jitterbuffer,
2609 iaxs[fr->callno]->jitterbuffer - prevjitterbuffer,
2611 iaxs[fr->callno]->jitter, iaxs[fr->callno]->historicjitter);
2615 /* Don't deliver it more than 4 ms late */
2616 if ((delay > -4) || (fr->af.frametype != AST_FRAME_VOICE)) {
2617 if (option_debug && iaxdebug)
2618 ast_log(LOG_DEBUG, "schedule_delivery: Delivering immediately (Calculated delay is %d)\n", delay);
2624 if (option_debug && iaxdebug)
2625 ast_log(LOG_DEBUG, "schedule_delivery: Dropping voice packet since %dms delay is too old\n", delay);
2626 iaxs[fr->callno]->frames_dropped++;
2630 if (option_debug && iaxdebug)
2631 ast_log(LOG_DEBUG, "schedule_delivery: Scheduling delivery in %d ms\n", delay);
2632 fr->retrans = ast_sched_add(sched, delay, do_deliver, fr);
2633 signal_condition(&sched_lock, &sched_cond);
2639 /* Free our iax frame */
2640 iax2_frame_free(fr);
2646 static int iax2_transmit(struct iax_frame *fr)
2648 /* Lock the queue and place this packet at the end */
2651 /* By setting this to 0, the network thread will send it for us, and
2652 queue retransmission if necessary */
2654 ast_mutex_lock(&iaxq.lock);
2661 iaxq.tail->next = fr;
2662 fr->prev = iaxq.tail;
2666 ast_mutex_unlock(&iaxq.lock);
2667 /* Wake up the network and scheduler thread */
2668 pthread_kill(netthreadid, SIGURG);
2669 signal_condition(&sched_lock, &sched_cond);
2675 static int iax2_digit(struct ast_channel *c, char digit)
2677 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF, digit, 0, NULL, 0, -1);
2680 static int iax2_sendtext(struct ast_channel *c, const char *text)
2683 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_TEXT,
2684 0, 0, (unsigned char *)text, strlen(text) + 1, -1);
2687 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
2689 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_IMAGE, img->subclass, 0, img->data, img->datalen, -1);
2692 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen)
2694 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_HTML, subclass, 0, (unsigned char *)data, datalen, -1);
2697 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
2699 unsigned short callno = PTR_TO_CALLNO(newchan->tech_pvt);
2700 ast_mutex_lock(&iaxsl[callno]);
2702 iaxs[callno]->owner = newchan;
2704 ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n");
2705 ast_mutex_unlock(&iaxsl[callno]);
2709 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, int temponly);
2710 static struct iax2_user *build_user(const char *name, struct ast_variable *v, int temponly);
2712 static void destroy_user(struct iax2_user *user);
2713 static int expire_registry(void *data);
2715 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin)
2717 struct ast_variable *var;
2718 struct ast_variable *tmp;
2719 struct iax2_peer *peer=NULL;
2720 time_t regseconds = 0, nowtime;
2724 var = ast_load_realtime("iaxpeers", "name", peername, NULL);
2726 char iabuf[INET_ADDRSTRLEN];
2728 ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr);
2729 sprintf(porta, "%d", ntohs(sin->sin_port));
2730 var = ast_load_realtime("iaxpeers", "ipaddr", iabuf, "port", porta, NULL);
2732 /* We'll need the peer name in order to build the structure! */
2735 if (!strcasecmp(tmp->name, "name"))
2736 peername = tmp->value;
2744 peer = build_peer(peername, var, ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS) ? 0 : 1);
2751 /* Make sure it's not a user only... */
2752 if (!strcasecmp(tmp->name, "type")) {
2753 if (strcasecmp(tmp->value, "friend") &&
2754 strcasecmp(tmp->value, "peer")) {
2755 /* Whoops, we weren't supposed to exist! */
2760 } else if (!strcasecmp(tmp->name, "regseconds")) {
2761 ast_get_time_t(tmp->value, ®seconds, 0, NULL);
2762 } else if (!strcasecmp(tmp->name, "ipaddr")) {
2763 inet_aton(tmp->value, &(peer->addr.sin_addr));
2764 } else if (!strcasecmp(tmp->name, "port")) {
2765 peer->addr.sin_port = htons(atoi(tmp->value));
2766 } else if (!strcasecmp(tmp->name, "host")) {
2767 if (!strcasecmp(tmp->value, "dynamic"))
2775 ast_variables_destroy(var);
2777 if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
2778 ast_copy_flags(peer, &globalflags, IAX_RTAUTOCLEAR|IAX_RTCACHEFRIENDS);
2779 if (ast_test_flag(peer, IAX_RTAUTOCLEAR)) {
2780 if (peer->expire > -1)
2781 ast_sched_del(sched, peer->expire);
2782 peer->expire = ast_sched_add(sched, (global_rtautoclear) * 1000, expire_registry, peer);
2784 ast_mutex_lock(&peerl.lock);
2785 peer->next = peerl.peers;
2787 ast_mutex_unlock(&peerl.lock);
2788 if (ast_test_flag(peer, IAX_DYNAMIC))
2789 reg_source_db(peer);
2791 ast_set_flag(peer, IAX_TEMPONLY);
2794 if (!ast_test_flag(&globalflags, IAX_RTIGNOREREGEXPIRE) && dynamic) {
2796 if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE) {
2797 memset(&peer->addr, 0, sizeof(peer->addr));
2799 ast_log(LOG_DEBUG, "realtime_peer: Bah, '%s' is expired (%d/%d/%d)!\n",
2800 peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
2804 ast_log(LOG_DEBUG, "realtime_peer: Registration for '%s' still active (%d/%d/%d)!\n",
2805 peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
2812 static struct iax2_user *realtime_user(const char *username)
2814 struct ast_variable *var;
2815 struct ast_variable *tmp;
2816 struct iax2_user *user=NULL;
2818 var = ast_load_realtime("iaxusers", "name", username, NULL);
2824 /* Make sure it's not a peer only... */
2825 if (!strcasecmp(tmp->name, "type")) {
2826 if (strcasecmp(tmp->value, "friend") &&
2827 strcasecmp(tmp->value, "user")) {
2834 user = build_user(username, var, !ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS));
2838 ast_variables_destroy(var);
2840 if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
2841 ast_set_flag(user, IAX_RTCACHEFRIENDS);
2842 ast_mutex_lock(&userl.lock);
2843 user->next = userl.users;
2845 ast_mutex_unlock(&userl.lock);
2847 ast_set_flag(user, IAX_TEMPONLY);
2853 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin)
2857 char regseconds[20];
2861 snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime);
2862 ast_inet_ntoa(ipaddr, sizeof(ipaddr), sin->sin_addr);
2863 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
2864 ast_update_realtime("iaxpeers", "name", peername, "ipaddr", ipaddr, "port", port, "regseconds", regseconds, NULL);
2867 struct create_addr_info {
2879 char context[AST_MAX_CONTEXT];
2880 char peercontext[AST_MAX_CONTEXT];
2883 static int create_addr(const char *peername, struct sockaddr_in *sin, struct create_addr_info *cai)
2885 struct ast_hostent ahp;
2887 struct iax2_peer *peer;
2889 ast_clear_flag(cai, IAX_SENDANI | IAX_TRUNK);
2890 cai->sockfd = defaultsockfd;
2892 sin->sin_family = AF_INET;
2894 if (!(peer = find_peer(peername, 1))) {
2897 hp = ast_gethostbyname(peername, &ahp);
2899 memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
2900 sin->sin_port = htons(IAX_DEFAULT_PORTNO);
2901 /* use global iax prefs for unknown peer/user */
2902 ast_codec_pref_convert(&prefs, cai->prefs, sizeof(cai->prefs), 1);
2905 ast_log(LOG_WARNING, "No such host: %s\n", peername);
2912 /* if the peer has no address (current or default), return failure */
2913 if (!(peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr)) {
2914 if (ast_test_flag(peer, IAX_TEMPONLY))
2919 /* if the peer is being monitored and is currently unreachable, return failure */
2920 if (peer->maxms && ((peer->lastms > peer->maxms) || (peer->lastms < 0))) {
2921 if (ast_test_flag(peer, IAX_TEMPONLY))
2926 ast_copy_flags(cai, peer, IAX_SENDANI | IAX_TRUNK | IAX_NOTRANSFER | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
2927 cai->maxtime = peer->maxms;
2928 cai->capability = peer->capability;
2929 cai->encmethods = peer->encmethods;
2930 cai->sockfd = peer->sockfd;
2931 ast_codec_pref_convert(&peer->prefs, cai->prefs, sizeof(cai->prefs), 1);
2932 ast_copy_string(cai->context, peer->context, sizeof(cai->context));
2933 ast_copy_string(cai->peercontext, peer->peercontext, sizeof(cai->peercontext));
2934 ast_copy_string(cai->username, peer->username, sizeof(cai->username));
2935 ast_copy_string(cai->timezone, peer->zonetag, sizeof(cai->timezone));
2936 ast_copy_string(cai->outkey, peer->outkey, sizeof(cai->outkey));
2937 if (ast_strlen_zero(peer->dbsecret)) {
2938 ast_copy_string(cai->secret, peer->secret, sizeof(cai->secret));
2943 family = ast_strdupa(peer->dbsecret);
2945 key = strchr(family, '/');
2949 if (!family || !key || ast_db_get(family, key, cai->secret, sizeof(cai->secret))) {
2950 ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", peer->dbsecret);
2951 if (ast_test_flag(peer, IAX_TEMPONLY))
2957 if (peer->addr.sin_addr.s_addr) {
2958 sin->sin_addr = peer->addr.sin_addr;
2959 sin->sin_port = peer->addr.sin_port;
2961 sin->sin_addr = peer->defaddr.sin_addr;
2962 sin->sin_port = peer->defaddr.sin_port;
2965 if (ast_test_flag(peer, IAX_TEMPONLY))
2971 static void __auto_congest(void *nothing)
2973 int callno = PTR_TO_CALLNO(nothing);
2974 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_CONGESTION };
2975 ast_mutex_lock(&iaxsl[callno]);
2977 iaxs[callno]->initid = -1;
2978 iax2_queue_frame(callno, &f);
2979 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
2981 ast_mutex_unlock(&iaxsl[callno]);
2984 static int auto_congest(void *data)
2986 #ifdef SCHED_MULTITHREADED
2987 if (schedule_action(__auto_congest, data))
2989 __auto_congest(data);
2993 static unsigned int iax2_datetime(char *tz)
2999 localtime_r(&t, &tm);
3000 if (!ast_strlen_zero(tz))
3001 ast_localtime(&t, &tm, tz);
3002 tmp = (tm.tm_sec >> 1) & 0x1f; /* 5 bits of seconds */
3003 tmp |= (tm.tm_min & 0x3f) << 5; /* 6 bits of minutes */
3004 tmp |= (tm.tm_hour & 0x1f) << 11; /* 5 bits of hours */
3005 tmp |= (tm.tm_mday & 0x1f) << 16; /* 5 bits of day of month */
3006 tmp |= ((tm.tm_mon + 1) & 0xf) << 21; /* 4 bits of month */
3007 tmp |= ((tm.tm_year - 100) & 0x7f) << 25; /* 7 bits of year */
3011 struct parsed_dial_string {
3023 * \brief Parses an IAX dial string into its component parts.
3024 * \param data the string to be parsed
3025 * \param pds pointer to a \c struct \c parsed_dial_string to be filled in
3028 * This function parses the string and fills the structure
3029 * with pointers to its component parts. The input string
3032 * \note This function supports both plaintext passwords and RSA
3033 * key names; if the password string is formatted as '[keyname]',
3034 * then the keyname will be placed into the key field, and the
3035 * password field will be set to NULL.
3037 * \note The dial string format is:
3038 * [username[:password]@]peer[:port][/exten[@@context]][/options]
3040 static void parse_dial_string(char *data, struct parsed_dial_string *pds)
3042 if (ast_strlen_zero(data))
3045 pds->peer = strsep(&data, "/");
3046 pds->exten = strsep(&data, "/");
3047 pds->options = data;
3051 pds->exten = strsep(&data, "@");
3052 pds->context = data;
3055 if (strchr(pds->peer, '@')) {
3057 pds->username = strsep(&data, "@");
3061 if (pds->username) {
3062 data = pds->username;
3063 pds->username = strsep(&data, ":");
3064 pds->password = data;
3068 pds->peer = strsep(&data, ":");
3071 /* check for a key name wrapped in [] in the secret position, if found,
3072 move it to the key field instead
3074 if (pds->password && (pds->password[0] == '[')) {
3075 pds->key = ast_strip_quoted(pds->password, "[", "]");
3076 pds->password = NULL;
3080 static int iax2_call(struct ast_channel *c, char *dest, int timeout)
3082 struct sockaddr_in sin;
3083 char *l=NULL, *n=NULL, *tmpstr;
3084 struct iax_ie_data ied;
3085 char *defaultrdest = "s";
3086 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
3087 struct parsed_dial_string pds;
3088 struct create_addr_info cai;
3090 if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
3091 ast_log(LOG_WARNING, "Channel is already in use (%s)?\n", c->name);
3095 memset(&cai, 0, sizeof(cai));
3096 cai.encmethods = iax2_encryption;
3098 memset(&pds, 0, sizeof(pds));
3099 tmpstr = ast_strdupa(dest);
3100 parse_dial_string(tmpstr, &pds);
3103 pds.exten = defaultrdest;
3105 if (create_addr(pds.peer, &sin, &cai)) {
3106 ast_log(LOG_WARNING, "No address associated with '%s'\n", pds.peer);
3110 if (!pds.username && !ast_strlen_zero(cai.username))
3111 pds.username = cai.username;
3112 if (!pds.password && !ast_strlen_zero(cai.secret))
3113 pds.password = cai.secret;
3114 if (!pds.key && !ast_strlen_zero(cai.outkey))
3115 pds.key = cai.outkey;
3116 if (!pds.context && !ast_strlen_zero(cai.peercontext))
3117 pds.context = cai.peercontext;
3119 /* Keep track of the context for outgoing calls too */
3120 ast_copy_string(c->context, cai.context, sizeof(c->context));
3123 sin.sin_port = htons(atoi(pds.port));
3126 n = c->cid.cid_name;
3128 /* Now build request */
3129 memset(&ied, 0, sizeof(ied));
3131 /* On new call, first IE MUST be IAX version of caller */
3132 iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
3133 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, pds.exten);
3134 if (pds.options && strchr(pds.options, 'a')) {
3135 /* Request auto answer */
3136 iax_ie_append(&ied, IAX_IE_AUTOANSWER);
3139 iax_ie_append_str(&ied, IAX_IE_CODEC_PREFS, cai.prefs);
3142 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
3143 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
3146 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
3148 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, AST_PRES_NUMBER_NOT_AVAILABLE);
3151 iax_ie_append_byte(&ied, IAX_IE_CALLINGTON, c->cid.cid_ton);
3152 iax_ie_append_short(&ied, IAX_IE_CALLINGTNS, c->cid.cid_tns);
3155 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n);
3156 if (ast_test_flag(iaxs[callno], IAX_SENDANI) && c->cid.cid_ani)
3157 iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, c->cid.cid_ani);
3159 if (!ast_strlen_zero(c->language))
3160 iax_ie_append_str(&ied, IAX_IE_LANGUAGE, c->language);
3161 if (!ast_strlen_zero(c->cid.cid_dnid))
3162 iax_ie_append_str(&ied, IAX_IE_DNID, c->cid.cid_dnid);
3163 if (!ast_strlen_zero(c->cid.cid_rdnis))
3164 iax_ie_append_str(&ied, IAX_IE_RDNIS, c->cid.cid_rdnis);
3167 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, pds.context);
3170 iax_ie_append_str(&ied, IAX_IE_USERNAME, pds.username);
3173 iax_ie_append_short(&ied, IAX_IE_ENCRYPTION, cai.encmethods);
3175 ast_mutex_lock(&iaxsl[callno]);
3177 if (!ast_strlen_zero(c->context))
3178 ast_copy_string(iaxs[callno]->context, c->context, sizeof(iaxs[callno]->context));
3181 ast_copy_string(iaxs[callno]->username, pds.username, sizeof(iaxs[callno]->username));
3183 iaxs[callno]->encmethods = cai.encmethods;
3186 ast_copy_string(iaxs[callno]->outkey, pds.key, sizeof(iaxs[callno]->outkey));
3188 ast_copy_string(iaxs[callno]->secret, pds.password, sizeof(iaxs[callno]->secret));
3190 iax_ie_append_int(&ied, IAX_IE_FORMAT, c->nativeformats);
3191 iax_ie_append_int(&ied, IAX_IE_CAPABILITY, iaxs[callno]->capability);
3192 iax_ie_append_short(&ied, IAX_IE_ADSICPE, c->adsicpe);
3193 iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime(cai.timezone));
3195 if (iaxs[callno]->maxtime) {
3196 /* Initialize pingtime and auto-congest time */
3197 iaxs[callno]->pingtime = iaxs[callno]->maxtime / 2;
3198 iaxs[callno]->initid = ast_sched_add(sched, iaxs[callno]->maxtime * 2, auto_congest, CALLNO_TO_PTR(callno));
3199 } else if (autokill) {
3200 iaxs[callno]->pingtime = autokill / 2;
3201 iaxs[callno]->initid = ast_sched_add(sched, autokill * 2, auto_congest, CALLNO_TO_PTR(callno));
3204 /* Transmit the string in a "NEW" request */
3205 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
3207 ast_mutex_unlock(&iaxsl[callno]);
3208 ast_setstate(c, AST_STATE_RINGING);
3213 static int iax2_hangup(struct ast_channel *c)
3215 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
3217 struct iax_ie_data ied;
3218 memset(&ied, 0, sizeof(ied));
3219 ast_mutex_lock(&iaxsl[callno]);
3220 if (callno && iaxs[callno]) {
3221 ast_log(LOG_DEBUG, "We're hanging up %s now...\n", c->name);
3222 alreadygone = ast_test_flag(iaxs[callno], IAX_ALREADYGONE);
3223 /* Send the hangup unless we have had a transmission error or are already gone */
3224 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, (unsigned char)c->hangupcause);
3225 if (!iaxs[callno]->error && !alreadygone)
3226 send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1);
3227 /* Explicitly predestroy it */
3228 iax2_predestroy_nolock(callno);
3229 /* If we were already gone to begin with, destroy us now */
3231 ast_log(LOG_DEBUG, "Really destroying %s now...\n", c->name);
3232 iax2_destroy_nolock(callno);
3235 ast_mutex_unlock(&iaxsl[callno]);
3236 if (option_verbose > 2)
3237 ast_verbose(VERBOSE_PREFIX_3 "Hungup '%s'\n", c->name);
3241 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
3243 struct ast_option_header *h;
3247 case AST_OPTION_TXGAIN:
3248 case AST_OPTION_RXGAIN:
3249 /* these two cannot be sent, because they require a result */
3253 if (!(h = ast_malloc(datalen + sizeof(*h))))
3256 h->flag = AST_OPTION_FLAG_REQUEST;
3257 h->option = htons(option);
3258 memcpy(h->data, data, datalen);
3259 res = send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_CONTROL,
3260 AST_CONTROL_OPTION, 0, (unsigned char *) h,
3261 datalen + sizeof(*h), -1);
3267 static struct ast_frame *iax2_read(struct ast_channel *c)
3269 ast_log(LOG_NOTICE, "I should never be called!\n");
3270 return &ast_null_frame;
3273 static int iax2_start_transfer(unsigned short callno0, unsigned short callno1)
3276 struct iax_ie_data ied0;
3277 struct iax_ie_data ied1;
3278 unsigned int transferid = rand();
3279 memset(&ied0, 0, sizeof(ied0));
3280 iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &iaxs[callno1]->addr);
3281 iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[callno1]->peercallno);
3282 iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, transferid);
3284 memset(&ied1, 0, sizeof(ied1));
3285 iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &iaxs[callno0]->addr);
3286 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[callno0]->peercallno);
3287 iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, transferid);
3289 res = send_command(iaxs[callno0], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
3292 res = send_command(iaxs[callno1], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
3295 iaxs[callno0]->transferring = TRANSFER_BEGIN;
3296 iaxs[callno1]->transferring = TRANSFER_BEGIN;
3300 static void lock_both(unsigned short callno0, unsigned short callno1)
3302 ast_mutex_lock(&iaxsl[callno0]);
3303 while (ast_mutex_trylock(&iaxsl[callno1])) {
3304 ast_mutex_unlock(&iaxsl[callno0]);
3306 ast_mutex_lock(&iaxsl[callno0]);
3310 static void unlock_both(unsigned short callno0, unsigned short callno1)
3312 ast_mutex_unlock(&iaxsl[callno1]);
3313 ast_mutex_unlock(&iaxsl[callno0]);
3316 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)
3318 struct ast_channel *cs[3];
3319 struct ast_channel *who;
3322 int transferstarted=0;
3323 struct ast_frame *f;
3324 unsigned short callno0 = PTR_TO_CALLNO(c0->tech_pvt);
3325 unsigned short callno1 = PTR_TO_CALLNO(c1->tech_pvt);
3326 struct timeval waittimer = {0, 0}, tv;
3328 lock_both(callno0, callno1);
3329 /* Put them in native bridge mode */
3330 if (!flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1)) {
3331 iaxs[callno0]->bridgecallno = callno1;
3332 iaxs[callno1]->bridgecallno = callno0;
3334 unlock_both(callno0, callno1);
3336 /* If not, try to bridge until we can execute a transfer, if we can */
3339 for (/* ever */;;) {
3340 /* Check in case we got masqueraded into */
3341 if ((c0->tech != &iax2_tech) || (c1->tech != &iax2_tech)) {
3342 if (option_verbose > 2)
3343 ast_verbose(VERBOSE_PREFIX_3 "Can't masquerade, we're different...\n");
3344 /* Remove from native mode */
3345 if (c0->tech == &iax2_tech) {
3346 ast_mutex_lock(&iaxsl[callno0]);
3347 iaxs[callno0]->bridgecallno = 0;
3348 ast_mutex_unlock(&iaxsl[callno0]);
3350 if (c1->tech == &iax2_tech) {
3351 ast_mutex_lock(&iaxsl[callno1]);
3352 iaxs[callno1]->bridgecallno = 0;
3353 ast_mutex_unlock(&iaxsl[callno1]);
3355 return AST_BRIDGE_FAILED_NOWARN;
3357 if (c0->nativeformats != c1->nativeformats) {
3358 if (option_verbose > 2) {
3361 ast_getformatname_multiple(buf0, sizeof(buf0) -1, c0->nativeformats);
3362 ast_getformatname_multiple(buf1, sizeof(buf1) -1, c1->nativeformats);
3363 ast_verbose(VERBOSE_PREFIX_3 "Operating with different codecs %d[%s] %d[%s] , can't native bridge...\n", c0->nativeformats, buf0, c1->nativeformats, buf1);
3365 /* Remove from native mode */
3366 lock_both(callno0, callno1);
3367 iaxs[callno0]->bridgecallno = 0;
3368 iaxs[callno1]->bridgecallno = 0;
3369 unlock_both(callno0, callno1);
3370 return AST_BRIDGE_FAILED_NOWARN;
3372 /* check if transfered and if we really want native bridging */
3373 if (!transferstarted && !ast_test_flag(iaxs[callno0], IAX_NOTRANSFER) && !ast_test_flag(iaxs[callno1], IAX_NOTRANSFER) &&
3374 !(flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
3375 /* Try the transfer */
3376 if (iax2_start_transfer(callno0, callno1))
3377 ast_log(LOG_WARNING, "Unable to start the transfer\n");
3378 transferstarted = 1;
3380 if ((iaxs[callno0]->transferring == TRANSFER_RELEASED) && (iaxs[callno1]->transferring == TRANSFER_RELEASED)) {
3381 /* Call has been transferred. We're no longer involved */
3382 gettimeofday(&tv, NULL);
3383 if (ast_tvzero(waittimer)) {
3385 } else if (tv.tv_sec - waittimer.tv_sec > IAX_LINGER_TIMEOUT) {
3386 c0->_softhangup |= AST_SOFTHANGUP_DEV;
3387 c1->_softhangup |= AST_SOFTHANGUP_DEV;
3390 res = AST_BRIDGE_COMPLETE;
3395 who = ast_waitfor_n(cs, 2, &to);
3396 if (timeoutms > -1) {
3397 timeoutms -= (1000 - to);
3403 res = AST_BRIDGE_RETRY;
3406 if (ast_check_hangup(c0) || ast_check_hangup(c1)) {
3407 res = AST_BRIDGE_FAILED;
3416 res = AST_BRIDGE_COMPLETE;
3419 if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
3422 res = AST_BRIDGE_COMPLETE;
3425 if ((f->frametype == AST_FRAME_VOICE) ||
3426 (f->frametype == AST_FRAME_TEXT) ||
3427 (f->frametype == AST_FRAME_VIDEO) ||
3428 (f->frametype == AST_FRAME_IMAGE) ||
3429 (f->frametype == AST_FRAME_DTMF)) {
3430 if ((f->frametype == AST_FRAME_DTMF) &&
3431 (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
3433 if ((flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
3436 res = AST_BRIDGE_COMPLETE;
3437 /* Remove from native mode */
3443 if (flags & AST_BRIDGE_DTMF_CHANNEL_1) {
3446 res = AST_BRIDGE_COMPLETE;
3453 if (iaxdebug && option_debug)
3454 ast_log(LOG_DEBUG, "Read from %s\n", who->name);
3456 ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
3468 /* Swap who gets priority */
3473 lock_both(callno0, callno1);
3475 iaxs[callno0]->bridgecallno = 0;
3477 iaxs[callno1]->bridgecallno = 0;
3478 unlock_both(callno0, callno1);
3482 static int iax2_answer(struct ast_channel *c)
3484 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
3486 ast_log(LOG_DEBUG, "Answering IAX2 call\n");
3487 return send_command_locked(callno, AST_FRAME_CONTROL, AST_CONTROL_ANSWER, 0, NULL, 0, -1);
3490 static int iax2_indicate(struct ast_channel *c, int condition)
3492 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
3493 if (option_debug && iaxdebug)
3494 ast_log(LOG_DEBUG, "Indicating condition %d\n", condition);
3495 return send_command_locked(callno, AST_FRAME_CONTROL, condition, 0, NULL, 0, -1);
3498 static int iax2_transfer(struct ast_channel *c, const char *dest)
3500 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
3501 struct iax_ie_data ied;
3502 char tmp[256], *context;
3503 ast_copy_string(tmp, dest, sizeof(tmp));
3504 context = strchr(tmp, '@');
3509 memset(&ied, 0, sizeof(ied));
3510 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, tmp);
3512 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, context);
3514 ast_log(LOG_DEBUG, "Transferring '%s' to '%s'\n", c->name, dest);
3515 return send_command_locked(callno, AST_FRAME_IAX, IAX_COMMAND_TRANSFER, 0, ied.buf, ied.pos, -1);
3519 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
3521 static int iax2_getpeertrunk(struct sockaddr_in sin)
3523 struct iax2_peer *peer;
3525 ast_mutex_lock(&peerl.lock);
3528 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
3529 (peer->addr.sin_port == sin.sin_port)) {
3530 res = ast_test_flag(peer, IAX_TRUNK);
3535 ast_mutex_unlock(&peerl.lock);
3539 /*! \brief Create new call, interface with the PBX core */
3540 static struct ast_channel *ast_iax2_new(int callno, int state, int capability)
3542 struct ast_channel *tmp;
3543 struct chan_iax2_pvt *i;
3544 struct ast_variable *v = NULL;
3546 /* Don't hold call lock */
3547 ast_mutex_unlock(&iaxsl[callno]);
3548 tmp = ast_channel_alloc(1);
3549 ast_mutex_lock(&iaxsl[callno]);
3552 tmp->tech = &iax2_tech;
3553 ast_string_field_build(tmp, name, "IAX2/%s-%d", i->host, i->callno);
3554 /* We can support any format by default, until we get restricted */
3555 tmp->nativeformats = capability;
3556 tmp->readformat = ast_best_codec(capability);
3557 tmp->writeformat = ast_best_codec(capability);
3558 tmp->tech_pvt = CALLNO_TO_PTR(i->callno);
3560 if (!ast_strlen_zero(i->cid_num))
3561 tmp->cid.cid_num = ast_strdup(i->cid_num);
3562 if (!ast_strlen_zero(i->cid_name))
3563 tmp->cid.cid_name = ast_strdup(i->cid_name);
3564 if (!ast_strlen_zero(i->ani))
3565 tmp->cid.cid_ani = ast_strdup(i->ani);
3566 if (!ast_strlen_zero(i->language))
3567 ast_string_field_set(tmp, language, i->language);
3568 if (!ast_strlen_zero(i->dnid))
3569 tmp->cid.cid_dnid = ast_strdup(i->dnid);
3570 if (!ast_strlen_zero(i->rdnis))
3571 tmp->cid.cid_rdnis = ast_strdup(i->rdnis);
3572 tmp->cid.cid_pres = i->calling_pres;
3573 tmp->cid.cid_ton = i->calling_ton;
3574 tmp->cid.cid_tns = i->calling_tns;
3575 if (!ast_strlen_zero(i->accountcode))
3576 ast_string_field_set(tmp, accountcode, i->accountcode);
3578 tmp->amaflags = i->amaflags;
3579 ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
3580 ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
3581 tmp->adsicpe = i->peeradsicpe;
3583 i->capability = capability;
3584 ast_setstate(tmp, state);
3585 ast_mutex_lock(&usecnt_lock);
3587 ast_mutex_unlock(&usecnt_lock);
3588 ast_update_use_count();
3589 if (state != AST_STATE_DOWN) {
3590 if (ast_pbx_start(tmp)) {
3591 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
3596 for (v = i->vars ; v ; v = v->next)
3597 pbx_builtin_setvar_helper(tmp,v->name,v->value);
3603 static unsigned int calc_txpeerstamp(struct iax2_trunk_peer *tpeer, int sampms, struct timeval *tv)
3605 unsigned long int mssincetx; /* unsigned to handle overflows */
3608 tpeer->trunkact = *tv;
3609 mssincetx = ast_tvdiff_ms(*tv, tpeer->lasttxtime);
3610 if (mssincetx > 5000 || ast_tvzero(tpeer->txtrunktime)) {
3611 /* If it's been at least 5 seconds since the last time we transmitted on this trunk, reset our timers */