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 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
37 #include <sys/types.h>
40 #include <sys/socket.h>
41 #include <netinet/in.h>
42 #include <arpa/inet.h>
43 #include <netinet/in_systm.h>
44 #include <netinet/ip.h>
46 #include <sys/signal.h>
58 #include <sys/ioctl.h>
60 #include <linux/zaptel.h>
63 #endif /* __linux__ */
66 #include "asterisk/lock.h"
67 #include "asterisk/frame.h"
68 #include "asterisk/channel.h"
69 #include "asterisk/logger.h"
70 #include "asterisk/module.h"
71 #include "asterisk/pbx.h"
72 #include "asterisk/sched.h"
73 #include "asterisk/io.h"
74 #include "asterisk/config.h"
75 #include "asterisk/options.h"
76 #include "asterisk/cli.h"
77 #include "asterisk/translate.h"
78 #include "asterisk/md5.h"
79 #include "asterisk/cdr.h"
80 #include "asterisk/crypto.h"
81 #include "asterisk/acl.h"
82 #include "asterisk/manager.h"
83 #include "asterisk/callerid.h"
84 #include "asterisk/app.h"
85 #include "asterisk/astdb.h"
86 #include "asterisk/musiconhold.h"
87 #include "asterisk/features.h"
88 #include "asterisk/utils.h"
89 #include "asterisk/causes.h"
90 #include "asterisk/localtime.h"
91 #include "asterisk/aes.h"
92 #include "asterisk/dnsmgr.h"
93 #include "asterisk/devicestate.h"
94 #include "asterisk/netsock.h"
95 #include "asterisk/stringfields.h"
96 #include "asterisk/linkedlists.h"
99 #include "iax2-parser.h"
100 #include "iax2-provision.h"
101 #include "../jitterbuf.h"
103 /* Define SCHED_MULTITHREADED to run the scheduler in a special
104 multithreaded mode. */
105 #define SCHED_MULTITHREADED
107 /* Define DEBUG_SCHED_MULTITHREADED to keep track of where each
108 thread is actually doing. */
109 #define DEBUG_SCHED_MULTITHREAD
111 #ifndef IPTOS_MINCOST
112 #define IPTOS_MINCOST 0x02
116 static int nochecksums = 0;
120 * Uncomment to try experimental IAX bridge optimization,
121 * designed to reduce latency when IAX calls cannot
122 * be trasnferred -- obsolete
125 /* #define BRIDGE_OPTIMIZATION */
128 #define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
129 #define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
131 #define DEFAULT_THREAD_COUNT 10
132 #define DEFAULT_MAX_THREAD_COUNT 100
133 #define DEFAULT_RETRY_TIME 1000
134 #define MEMORY_SIZE 100
135 #define DEFAULT_DROP 3
136 /* Flag to use with trunk calls, keeping these calls high up. It halves our effective use
137 but keeps the division between trunked and non-trunked better. */
138 #define TRUNK_CALL_START 0x4000
140 #define DEBUG_SUPPORT
142 #define MIN_REUSE_TIME 60 /* Don't reuse a call number within 60 seconds */
144 /* Sample over last 100 units to determine historic jitter */
147 static struct ast_codec_pref prefs;
149 static const char tdesc[] = "Inter Asterisk eXchange Driver (Ver 2)";
151 static char context[80] = "default";
153 static char language[MAX_LANGUAGE] = "";
154 static char regcontext[AST_MAX_CONTEXT] = "";
156 static int max_retries = 4;
157 static int ping_time = 20;
158 static int lagrq_time = 10;
159 static int maxtrunkcall = TRUNK_CALL_START;
160 static int maxnontrunkcall = 1;
161 static int maxjitterbuffer=1000;
162 static int resyncthreshold=1000;
163 static int maxjitterinterps=10;
164 static int trunkfreq = 20;
165 static int authdebug = 1;
166 static int autokill = 0;
167 static int iaxcompat = 0;
169 static int iaxdefaultdpcache=10 * 60; /* Cache dialplan entries for 10 minutes by default */
171 static int iaxdefaulttimeout = 5; /* Default to wait no more than 5 seconds for a reply to come back */
175 static int min_reg_expire;
176 static int max_reg_expire;
178 static int timingfd = -1; /* Timing file descriptor */
180 static struct ast_netsock_list *netsock;
181 static int defaultsockfd = -1;
184 AST_MUTEX_DEFINE_STATIC(usecnt_lock);
186 int (*iax2_regfunk)(char *username, int onoff) = NULL;
189 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
191 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
192 ~AST_FORMAT_SLINEAR & \
196 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
200 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
204 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
205 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
206 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
208 static struct io_context *io;
209 static struct sched_context *sched;
211 static int iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
213 static int iaxdebug = 0;
215 static int iaxtrunkdebug = 0;
217 static int test_losspct = 0;
219 static int test_late = 0;
220 static int test_resync = 0;
221 static int test_jit = 0;
222 static int test_jitpct = 0;
223 #endif /* IAXTESTS */
225 static char accountcode[AST_MAX_ACCOUNT_CODE];
226 static int amaflags = 0;
227 static int delayreject = 0;
228 static int iax2_encryption = 0;
230 static struct ast_flags globalflags = { 0 };
232 static pthread_t netthreadid = AST_PTHREADT_NULL;
233 static pthread_t schedthreadid = AST_PTHREADT_NULL;
234 AST_MUTEX_DEFINE_STATIC(sched_lock);
235 static int sched_halt = 0;
236 static ast_cond_t sched_cond;
239 IAX_STATE_STARTED = (1 << 0),
240 IAX_STATE_AUTHENTICATED = (1 << 1),
241 IAX_STATE_TBD = (1 << 2),
242 IAX_STATE_UNCHANGED = (1 << 3),
245 struct iax2_context {
246 char context[AST_MAX_CONTEXT];
247 struct iax2_context *next;
251 IAX_HASCALLERID = (1 << 0), /*!< CallerID has been specified */
252 IAX_DELME = (1 << 1), /*!< Needs to be deleted */
253 IAX_TEMPONLY = (1 << 2), /*!< Temporary (realtime) */
254 IAX_TRUNK = (1 << 3), /*!< Treat as a trunk */
255 IAX_NOTRANSFER = (1 << 4), /*!< Don't native bridge */
256 IAX_USEJITTERBUF = (1 << 5), /*!< Use jitter buffer */
257 IAX_DYNAMIC = (1 << 6), /*!< dynamic peer */
258 IAX_SENDANI = (1 << 7), /*!< Send ANI along with CallerID */
259 /* (1 << 8) is currently unused due to the deprecation of an old option. Go ahead, take it! */
260 IAX_ALREADYGONE = (1 << 9), /*!< Already disconnected */
261 IAX_PROVISION = (1 << 10), /*!< This is a provisioning request */
262 IAX_QUELCH = (1 << 11), /*!< Whether or not we quelch audio */
263 IAX_ENCRYPTED = (1 << 12), /*!< Whether we should assume encrypted tx/rx */
264 IAX_KEYPOPULATED = (1 << 13), /*!< Whether we have a key populated */
265 IAX_CODEC_USER_FIRST = (1 << 14), /*!< are we willing to let the other guy choose the codec? */
266 IAX_CODEC_NOPREFS = (1 << 15), /*!< Force old behaviour by turning off prefs */
267 IAX_CODEC_NOCAP = (1 << 16), /*!< only consider requested format and ignore capabilities*/
268 IAX_RTCACHEFRIENDS = (1 << 17), /*!< let realtime stay till your reload */
269 IAX_RTUPDATE = (1 << 18), /*!< Send a realtime update */
270 IAX_RTAUTOCLEAR = (1 << 19), /*!< erase me on expire */
271 IAX_FORCEJITTERBUF = (1 << 20), /*!< Force jitterbuffer, even when bridged to a channel that can take jitter */
272 IAX_RTIGNOREREGEXPIRE = (1 << 21), /*!< When using realtime, ignore registration expiration */
273 IAX_TRUNKTIMESTAMPS = (1 << 22), /*!< Send trunk timestamps */
274 IAX_TRANSFERMEDIA = (1 << 23) /*!< When doing IAX2 transfers, transfer media only */
277 static int global_rtautoclear = 120;
279 static int reload_config(void);
280 static int iax2_reload(int fd, int argc, char *argv[]);
289 char accountcode[AST_MAX_ACCOUNT_CODE];
290 char inkeys[80]; /*!< Key(s) this user can use to authenticate to us */
291 char language[MAX_LANGUAGE];
295 char cid_num[AST_MAX_EXTENSION];
296 char cid_name[AST_MAX_EXTENSION];
297 struct ast_codec_pref prefs;
299 struct iax2_context *contexts;
300 struct ast_variable *vars;
301 AST_LIST_ENTRY(iax2_user) entry;
309 char outkey[80]; /*!< What key we use to talk to this peer */
310 char context[AST_MAX_CONTEXT]; /*!< For transfers only */
311 char regexten[AST_MAX_EXTENSION]; /*!< Extension to register (if regcontext is used) */
312 char peercontext[AST_MAX_EXTENSION]; /*!< Context to pass to peer */
313 char mailbox[AST_MAX_EXTENSION]; /*!< Mailbox */
314 struct ast_codec_pref prefs;
315 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
316 struct sockaddr_in addr;
318 int sockfd; /*!< Socket to use for transmission */
322 /* Dynamic Registration fields */
323 struct sockaddr_in defaddr; /*!< Default address if there is one */
324 int authmethods; /*!< Authentication methods (IAX_AUTH_*) */
325 int encmethods; /*!< Encryption methods (IAX_ENCRYPT_*) */
326 char inkeys[80]; /*!< Key(s) this peer can use to authenticate to us */
328 /* Suggested caller id if registering */
329 char cid_num[AST_MAX_EXTENSION]; /*!< Default context (for transfer really) */
330 char cid_name[AST_MAX_EXTENSION]; /*!< Default context (for transfer really) */
332 int expire; /*!< Schedule entry for expiry */
333 int expiry; /*!< How soon to expire */
334 int capability; /*!< Capability */
335 char zonetag[80]; /*!< Time Zone */
338 int callno; /*!< Call number of POKE request */
339 int pokeexpire; /*!< When to expire poke */
340 int lastms; /*!< How long last response took (in ms), or -1 for no response */
341 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
343 int pokefreqok; /*!< How often to check if the host is up */
344 int pokefreqnotok; /*!< How often to check when the host has been determined to be down */
345 int historicms; /*!< How long recent average responses took */
346 int smoothing; /*!< Sample over how many units to determine historic ms */
349 AST_LIST_ENTRY(iax2_peer) entry;
352 #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
354 static struct iax2_trunk_peer {
357 struct sockaddr_in addr;
358 struct timeval txtrunktime; /*!< Transmit trunktime */
359 struct timeval rxtrunktime; /*!< Receive trunktime */
360 struct timeval lasttxtime; /*!< Last transmitted trunktime */
361 struct timeval trunkact; /*!< Last trunk activity */
362 unsigned int lastsent; /*!< Last sent time */
363 /* Trunk data and length */
364 unsigned char *trunkdata;
365 unsigned int trunkdatalen;
366 unsigned int trunkdataalloc;
367 struct iax2_trunk_peer *next;
372 AST_MUTEX_DEFINE_STATIC(tpeerlock);
374 struct iax_firmware {
375 struct iax_firmware *next;
379 struct ast_iax2_firmware_header *fwh;
384 REG_STATE_UNREGISTERED = 0,
387 REG_STATE_REGISTERED,
393 enum iax_transfer_state {
398 TRANSFER_PASSTHROUGH,
402 TRANSFER_MPASSTHROUGH,
407 struct iax2_registry {
408 struct sockaddr_in addr; /*!< Who we connect to for registration purposes */
410 char secret[80]; /*!< Password or key name in []'s */
412 int expire; /*!< Sched ID of expiration */
413 int refresh; /*!< How often to refresh */
414 enum iax_reg_state regstate;
415 int messages; /*!< Message count, low 8 bits = new, high 8 bits = old */
416 int callno; /*!< Associated call number if applicable */
417 struct sockaddr_in us; /*!< Who the server thinks we are */
418 struct iax2_registry *next;
419 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
422 static struct iax2_registry *registrations;
424 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
425 #define MIN_RETRY_TIME 100
426 #define MAX_RETRY_TIME 10000
428 #define MAX_JITTER_BUFFER 50
429 #define MIN_JITTER_BUFFER 10
431 #define DEFAULT_TRUNKDATA 640 * 10 /*!< 40ms, uncompressed linear * 10 channels */
432 #define MAX_TRUNKDATA 640 * 200 /*!< 40ms, uncompressed linear * 200 channels */
434 #define MAX_TIMESTAMP_SKEW 160 /*!< maximum difference between actual and predicted ts for sending */
436 /* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
437 #define TS_GAP_FOR_JB_RESYNC 5000
439 static int iaxthreadcount = DEFAULT_THREAD_COUNT;
440 static int iaxmaxthreadcount = DEFAULT_MAX_THREAD_COUNT;
441 static int iaxdynamicthreadcount = 0;
453 struct chan_iax2_pvt {
454 /*! Socket to send/receive on for this call */
456 /*! Last received voice format */
458 /*! Last received video format */
460 /*! Last sent voice format */
462 /*! Last sent video format */
464 /*! What we are capable of sending */
466 /*! Last received timestamp */
468 /*! Last sent timestamp - never send the same timestamp twice in a single call */
469 unsigned int lastsent;
470 /*! Next outgoing timestamp if everything is good */
471 unsigned int nextpred;
472 /*! True if the last voice we transmitted was not silence/CNG */
475 unsigned int pingtime;
476 /*! Max time for initial response */
479 struct sockaddr_in addr;
480 /*! Actual used codec preferences */
481 struct ast_codec_pref prefs;
482 /*! Requested codec preferences */
483 struct ast_codec_pref rprefs;
484 /*! Our call number */
485 unsigned short callno;
487 unsigned short peercallno;
488 /*! Peer selected format */
490 /*! Peer capability */
492 /*! timeval that we base our transmission on */
493 struct timeval offset;
494 /*! timeval that we base our delivery on */
495 struct timeval rxcore;
496 /*! The jitterbuffer */
498 /*! active jb read scheduler id */
502 /*! Error, as discovered by the manager */
504 /*! Owner if we have one */
505 struct ast_channel *owner;
506 /*! What's our state? */
507 struct ast_flags state;
508 /*! Expiry (optional) */
510 /*! Next outgoing sequence number */
511 unsigned char oseqno;
512 /*! Next sequence number they have not yet acknowledged */
513 unsigned char rseqno;
514 /*! Next incoming sequence number */
515 unsigned char iseqno;
516 /*! Last incoming sequence number we have acknowledged */
517 unsigned char aseqno;
520 /*! Default Context */
522 /*! Caller ID if available */
525 /*! Hidden Caller ID (i.e. ANI) if appropriate */
531 /*! Requested Extension */
532 char exten[AST_MAX_EXTENSION];
533 /*! Expected Username */
535 /*! Expected Secret */
537 /*! permitted authentication methods */
539 /*! permitted encryption methods */
543 /*! Public keys permitted keys for incoming authentication */
545 /*! Private key for outgoing authentication */
547 /*! Encryption AES-128 Key */
549 /*! Decryption AES-128 Key */
551 /*! 32 bytes of semi-random data */
552 unsigned char semirand[32];
553 /*! Preferred language */
554 char language[MAX_LANGUAGE];
555 /*! Hostname/peername for naming purposes */
557 /*! Associated registry */
558 struct iax2_registry *reg;
559 /*! Associated peer for poking */
560 struct iax2_peer *peerpoke;
564 /*! Transferring status */
565 enum iax_transfer_state transferring;
566 /*! Transfer identifier */
568 /*! Who we are IAX transfering to */
569 struct sockaddr_in transfer;
570 /*! What's the new call number for the transfer */
571 unsigned short transfercallno;
572 /*! Transfer decrypt AES-128 Key */
573 aes_encrypt_ctx tdcx;
575 /*! Status of knowledge of peer ADSI capability */
578 /*! Who we are bridged to */
579 unsigned short bridgecallno;
580 unsigned int bridgesfmt;
581 struct ast_trans_pvt *bridgetrans;
583 int pingid; /*!< Transmit PING request */
584 int lagid; /*!< Retransmit lag request */
585 int autoid; /*!< Auto hangup for Dialplan requestor */
586 int authid; /*!< Authentication rejection ID */
587 int authfail; /*!< Reason to report failure */
588 int initid; /*!< Initial peer auto-congest ID (based on qualified peers) */
592 char dproot[AST_MAX_EXTENSION];
593 char accountcode[AST_MAX_ACCOUNT_CODE];
595 struct iax2_dpcache *dpentries;
596 struct ast_variable *vars;
597 /*! last received remote rr */
598 struct iax_rr remote_rr;
599 /*! Current base time: (just for stats) */
601 /*! Dropped frame count: (just for stats) */
603 /*! received frame count: (just for stats) */
607 static struct ast_iax2_queue {
608 struct iax_frame *head;
609 struct iax_frame *tail;
614 static AST_LIST_HEAD_STATIC(users, iax2_user);
616 static AST_LIST_HEAD_STATIC(peers, iax2_peer);
618 static struct ast_firmware_list {
619 struct iax_firmware *wares;
623 /*! Extension exists */
624 #define CACHE_FLAG_EXISTS (1 << 0)
625 /*! Extension is nonexistent */
626 #define CACHE_FLAG_NONEXISTENT (1 << 1)
627 /*! Extension can exist */
628 #define CACHE_FLAG_CANEXIST (1 << 2)
629 /*! Waiting to hear back response */
630 #define CACHE_FLAG_PENDING (1 << 3)
632 #define CACHE_FLAG_TIMEOUT (1 << 4)
633 /*! Request transmitted */
634 #define CACHE_FLAG_TRANSMITTED (1 << 5)
636 #define CACHE_FLAG_UNKNOWN (1 << 6)
638 #define CACHE_FLAG_MATCHMORE (1 << 7)
640 static struct iax2_dpcache {
641 char peercontext[AST_MAX_CONTEXT];
642 char exten[AST_MAX_EXTENSION];
644 struct timeval expiry;
646 unsigned short callno;
648 struct iax2_dpcache *next;
649 struct iax2_dpcache *peer; /*!< For linking in peers */
652 AST_MUTEX_DEFINE_STATIC(dpcache_lock);
654 static void reg_source_db(struct iax2_peer *p);
655 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
657 static void destroy_peer(struct iax2_peer *peer);
658 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt);
660 #define IAX_IOSTATE_IDLE 0
661 #define IAX_IOSTATE_READY 1
662 #define IAX_IOSTATE_PROCESSING 2
663 #define IAX_IOSTATE_SCHEDREADY 3
665 #define IAX_TYPE_POOL 1
666 #define IAX_TYPE_DYNAMIC 2
669 AST_LIST_ENTRY(iax2_thread) list;
672 #ifdef SCHED_MULTITHREADED
673 void (*schedfunc)(void *);
676 #ifdef DEBUG_SCHED_MULTITHREAD
683 struct sockaddr_in iosin;
684 unsigned char buf[4096];
693 static AST_LIST_HEAD_STATIC(idle_list, iax2_thread);
694 static AST_LIST_HEAD_STATIC(active_list, iax2_thread);
695 static AST_LIST_HEAD_STATIC(dynamic_list, iax2_thread);
697 static void *iax2_process_thread(void *data);
699 static void signal_condition(ast_mutex_t *lock, ast_cond_t *cond)
701 ast_mutex_lock(lock);
702 ast_cond_signal(cond);
703 ast_mutex_unlock(lock);
706 static void iax_debug_output(const char *data)
709 ast_verbose("%s", data);
712 static void iax_error_output(const char *data)
714 ast_log(LOG_WARNING, "%s", data);
717 static void jb_error_output(const char *fmt, ...)
723 vsnprintf(buf, 1024, fmt, args);
726 ast_log(LOG_ERROR, buf);
729 static void jb_warning_output(const char *fmt, ...)
735 vsnprintf(buf, 1024, fmt, args);
738 ast_log(LOG_WARNING, buf);
741 static void jb_debug_output(const char *fmt, ...)
747 vsnprintf(buf, 1024, fmt, args);
753 /* XXX We probably should use a mutex when working with this XXX */
754 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS];
755 static ast_mutex_t iaxsl[IAX_MAX_CALLS];
756 static struct timeval lastused[IAX_MAX_CALLS];
758 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);
759 static int expire_registry(void *data);
760 static int iax2_answer(struct ast_channel *c);
761 static int iax2_call(struct ast_channel *c, char *dest, int timeout);
762 static int iax2_devicestate(void *data);
763 static int iax2_digit(struct ast_channel *c, char digit);
764 static int iax2_do_register(struct iax2_registry *reg);
765 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
766 static int iax2_hangup(struct ast_channel *c);
767 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen);
768 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
769 static int iax2_provision(struct sockaddr_in *end, int sockfd, char *dest, const char *template, int force);
770 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
771 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
772 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
773 static int iax2_sendtext(struct ast_channel *c, const char *text);
774 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
775 static int iax2_transfer(struct ast_channel *c, const char *dest);
776 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
777 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
778 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
779 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
780 static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int);
781 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
782 static struct ast_channel *iax2_request(const char *type, int format, void *data, int *cause);
783 static struct ast_frame *iax2_read(struct ast_channel *c);
784 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, int temponly);
785 static struct iax2_user *build_user(const char *name, struct ast_variable *v, int temponly);
786 static void destroy_user(struct iax2_user *user);
787 static void prune_peers(void);
789 static const struct ast_channel_tech iax2_tech = {
791 .description = tdesc,
792 .capabilities = IAX_CAPABILITY_FULLBANDWIDTH,
793 .properties = AST_CHAN_TP_WANTSJITTER,
794 .requester = iax2_request,
795 .devicestate = iax2_devicestate,
796 .send_digit = iax2_digit,
797 .send_text = iax2_sendtext,
798 .send_image = iax2_sendimage,
799 .send_html = iax2_sendhtml,
801 .hangup = iax2_hangup,
802 .answer = iax2_answer,
805 .write_video = iax2_write,
806 .indicate = iax2_indicate,
807 .setoption = iax2_setoption,
808 .bridge = iax2_bridge,
809 .transfer = iax2_transfer,
813 static struct iax2_thread *find_idle_thread(void)
815 struct iax2_thread *thread = NULL;
817 /* Find free idle thread in the list, get a pointer to it, and remove it from the list */
818 AST_LIST_LOCK(&idle_list);
819 thread = AST_LIST_FIRST(&idle_list);
820 if (thread != NULL) {
821 AST_LIST_REMOVE(&idle_list, thread, list);
823 AST_LIST_UNLOCK(&idle_list);
825 /* If no idle thread is available from the regular list, try dynamic */
826 if (thread == NULL) {
827 AST_LIST_LOCK(&dynamic_list);
828 thread = AST_LIST_FIRST(&dynamic_list);
829 if (thread != NULL) {
830 AST_LIST_REMOVE(&dynamic_list, thread, list);
832 /* Make sure we absolutely have a thread... if not, try to make one if allowed */
833 if (thread == NULL && iaxmaxthreadcount > iaxdynamicthreadcount) {
834 /* We need to MAKE a thread! */
835 thread = ast_calloc(1, sizeof(*thread));
836 if (thread != NULL) {
837 thread->threadnum = iaxdynamicthreadcount;
838 thread->type = IAX_TYPE_DYNAMIC;
839 ast_mutex_init(&thread->lock);
840 ast_cond_init(&thread->cond, NULL);
841 if (ast_pthread_create(&thread->threadid, NULL, iax2_process_thread, thread)) {
845 /* All went well and the thread is up, so increment our count */
846 iaxdynamicthreadcount++;
850 AST_LIST_UNLOCK(&dynamic_list);
856 #ifdef SCHED_MULTITHREADED
857 static int __schedule_action(void (*func)(void *data), void *data, const char *funcname)
859 struct iax2_thread *thread = NULL;
860 static time_t lasterror;
863 thread = find_idle_thread();
865 if (thread != NULL) {
866 thread->schedfunc = func;
867 thread->scheddata = data;
868 thread->iostate = IAX_IOSTATE_SCHEDREADY;
869 #ifdef DEBUG_SCHED_MULTITHREAD
870 ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc));
872 signal_condition(&thread->lock, &thread->cond);
877 ast_log(LOG_NOTICE, "Out of idle IAX2 threads for scheduling!\n");
882 #define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
885 static void __send_ping(void *data)
887 int callno = (long)data;
888 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
891 static int send_ping(void *data)
893 int callno = (long)data;
895 #ifdef BRIDGE_OPTIMIZATION
896 if (!iaxs[callno]->bridgecallno)
899 #ifdef SCHED_MULTITHREADED
900 if (schedule_action(__send_ping, data))
910 static int get_encrypt_methods(const char *s)
913 if (!strcasecmp(s, "aes128"))
914 e = IAX_ENCRYPT_AES128;
915 else if (ast_true(s))
916 e = IAX_ENCRYPT_AES128;
922 static void __send_lagrq(void *data)
924 int callno = (long)data;
925 /* Ping only if it's real not if it's bridged */
926 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
929 static int send_lagrq(void *data)
931 int callno = (long)data;
933 #ifdef BRIDGE_OPTIMIZATION
934 if (!iaxs[callno]->bridgecallno)
937 #ifdef SCHED_MULTITHREADED
938 if (schedule_action(__send_lagrq, data))
948 static unsigned char compress_subclass(int subclass)
952 /* If it's 128 or smaller, just return it */
953 if (subclass < IAX_FLAG_SC_LOG)
955 /* Otherwise find its power */
956 for (x = 0; x < IAX_MAX_SHIFT; x++) {
957 if (subclass & (1 << x)) {
959 ast_log(LOG_WARNING, "Can't compress subclass %d\n", subclass);
965 return power | IAX_FLAG_SC_LOG;
968 static int uncompress_subclass(unsigned char csub)
970 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
971 if (csub & IAX_FLAG_SC_LOG) {
972 /* special case for 'compressed' -1 */
976 return 1 << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
982 static struct iax2_peer *find_peer(const char *name, int realtime)
984 struct iax2_peer *peer = NULL;
986 /* Grab peer from linked list */
987 AST_LIST_LOCK(&peers);
988 AST_LIST_TRAVERSE(&peers, peer, entry) {
989 if (!strcasecmp(peer->name, name)) {
993 AST_LIST_UNLOCK(&peers);
995 /* Now go for realtime if applicable */
996 if(!peer && realtime)
997 peer = realtime_peer(name, NULL);
1001 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len, int lockpeer)
1003 struct iax2_peer *peer = NULL;
1007 AST_LIST_LOCK(&peers);
1008 AST_LIST_TRAVERSE(&peers, peer, entry) {
1009 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
1010 (peer->addr.sin_port == sin.sin_port)) {
1011 ast_copy_string(host, peer->name, len);
1017 AST_LIST_UNLOCK(&peers);
1019 peer = realtime_peer(NULL, &sin);
1021 ast_copy_string(host, peer->name, len);
1022 if (ast_test_flag(peer, IAX_TEMPONLY))
1031 static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, int lockpeer, const char *host)
1033 struct chan_iax2_pvt *tmp;
1036 if (!(tmp = ast_calloc(1, sizeof(*tmp))))
1041 tmp->peercallno = 0;
1042 tmp->transfercallno = 0;
1043 tmp->bridgecallno = 0;
1049 /* ast_copy_string(tmp->context, context, sizeof(tmp->context)); */
1050 ast_copy_string(tmp->exten, "s", sizeof(tmp->exten));
1051 ast_copy_string(tmp->host, host, sizeof(tmp->host));
1055 jbconf.max_jitterbuf = maxjitterbuffer;
1056 jbconf.resync_threshold = resyncthreshold;
1057 jbconf.max_contig_interp = maxjitterinterps;
1058 jb_setconf(tmp->jb,&jbconf);
1063 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
1065 /* Malloc() a copy of a frame */
1066 struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen);
1068 memcpy(new, fr, sizeof(struct iax_frame));
1069 iax_frame_wrap(new, &fr->af);
1072 new->direction = DIRECTION_INGRESS;
1078 #define NEW_PREVENT 0
1082 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, struct chan_iax2_pvt *cur)
1084 if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
1085 (cur->addr.sin_port == sin->sin_port)) {
1086 /* This is the main host */
1087 if ((cur->peercallno == callno) ||
1088 ((dcallno == cur->callno) && !cur->peercallno)) {
1089 /* That's us. Be sure we keep track of the peer call number */
1093 if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
1094 (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
1095 /* We're transferring */
1096 if (dcallno == cur->callno)
1102 static void update_max_trunk(void)
1104 int max = TRUNK_CALL_START;
1106 /* XXX Prolly don't need locks here XXX */
1107 for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
1112 if (option_debug && iaxdebug)
1113 ast_log(LOG_DEBUG, "New max trunk callno is %d\n", max);
1116 static void update_max_nontrunk(void)
1120 /* XXX Prolly don't need locks here XXX */
1121 for (x=1;x<TRUNK_CALL_START - 1; x++) {
1125 maxnontrunkcall = max;
1126 if (option_debug && iaxdebug)
1127 ast_log(LOG_DEBUG, "New max nontrunk callno is %d\n", max);
1130 static int make_trunk(unsigned short callno, int locked)
1135 if (iaxs[callno]->oseqno) {
1136 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
1139 if (callno & TRUNK_CALL_START) {
1140 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
1143 gettimeofday(&now, NULL);
1144 for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
1145 ast_mutex_lock(&iaxsl[x]);
1146 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) {
1147 iaxs[x] = iaxs[callno];
1148 iaxs[x]->callno = x;
1149 iaxs[callno] = NULL;
1150 /* Update the two timers that should have been started */
1151 if (iaxs[x]->pingid > -1)
1152 ast_sched_del(sched, iaxs[x]->pingid);
1153 if (iaxs[x]->lagid > -1)
1154 ast_sched_del(sched, iaxs[x]->lagid);
1155 iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
1156 iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
1158 ast_mutex_unlock(&iaxsl[callno]);
1161 ast_mutex_unlock(&iaxsl[x]);
1164 ast_mutex_unlock(&iaxsl[x]);
1166 if (x >= IAX_MAX_CALLS - 1) {
1167 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
1170 ast_log(LOG_DEBUG, "Made call %d into trunk call %d\n", callno, x);
1171 /* We move this call from a non-trunked to a trunked call */
1173 update_max_nontrunk();
1177 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int lockpeer, int sockfd)
1182 char iabuf[INET_ADDRSTRLEN];
1184 if (new <= NEW_ALLOW) {
1185 /* Look for an existing connection first */
1186 for (x=1;(res < 1) && (x<maxnontrunkcall);x++) {
1187 ast_mutex_lock(&iaxsl[x]);
1189 /* Look for an exact match */
1190 if (match(sin, callno, dcallno, iaxs[x])) {
1194 ast_mutex_unlock(&iaxsl[x]);
1196 for (x=TRUNK_CALL_START;(res < 1) && (x<maxtrunkcall);x++) {
1197 ast_mutex_lock(&iaxsl[x]);
1199 /* Look for an exact match */
1200 if (match(sin, callno, dcallno, iaxs[x])) {
1204 ast_mutex_unlock(&iaxsl[x]);
1207 if ((res < 1) && (new >= NEW_ALLOW)) {
1208 if (!iax2_getpeername(*sin, host, sizeof(host), lockpeer))
1209 snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr), ntohs(sin->sin_port));
1210 gettimeofday(&now, NULL);
1211 for (x=1;x<TRUNK_CALL_START;x++) {
1212 /* Find first unused call number that hasn't been used in a while */
1213 ast_mutex_lock(&iaxsl[x]);
1214 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) break;
1215 ast_mutex_unlock(&iaxsl[x]);
1217 /* We've still got lock held if we found a spot */
1218 if (x >= TRUNK_CALL_START) {
1219 ast_log(LOG_WARNING, "No more space\n");
1222 iaxs[x] = new_iax(sin, lockpeer, host);
1223 update_max_nontrunk();
1225 if (option_debug && iaxdebug)
1226 ast_log(LOG_DEBUG, "Creating new call structure %d\n", x);
1227 iaxs[x]->sockfd = sockfd;
1228 iaxs[x]->addr.sin_port = sin->sin_port;
1229 iaxs[x]->addr.sin_family = sin->sin_family;
1230 iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
1231 iaxs[x]->peercallno = callno;
1232 iaxs[x]->callno = x;
1233 iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
1234 iaxs[x]->expiry = min_reg_expire;
1235 iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
1236 iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
1237 iaxs[x]->amaflags = amaflags;
1238 ast_copy_flags(iaxs[x], (&globalflags), IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
1239 ast_copy_string(iaxs[x]->accountcode, accountcode, sizeof(iaxs[x]->accountcode));
1241 ast_log(LOG_WARNING, "Out of resources\n");
1242 ast_mutex_unlock(&iaxsl[x]);
1245 ast_mutex_unlock(&iaxsl[x]);
1251 static void iax2_frame_free(struct iax_frame *fr)
1253 if (fr->retrans > -1)
1254 ast_sched_del(sched, fr->retrans);
1258 static int iax2_queue_frame(int callno, struct ast_frame *f)
1260 /* Assumes lock for callno is already held... */
1262 if (iaxs[callno] && iaxs[callno]->owner) {
1263 if (ast_mutex_trylock(&iaxs[callno]->owner->lock)) {
1264 /* Avoid deadlock by pausing and trying again */
1265 ast_mutex_unlock(&iaxsl[callno]);
1267 ast_mutex_lock(&iaxsl[callno]);
1269 ast_queue_frame(iaxs[callno]->owner, f);
1270 ast_mutex_unlock(&iaxs[callno]->owner->lock);
1279 static void destroy_firmware(struct iax_firmware *cur)
1281 /* Close firmware */
1283 munmap(cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh)));
1289 static int try_firmware(char *s)
1292 struct iax_firmware *cur;
1297 struct ast_iax2_firmware_header *fwh, fwh2;
1298 struct MD5Context md5;
1299 unsigned char sum[16];
1300 unsigned char buf[1024];
1304 s2 = alloca(strlen(s) + 100);
1306 ast_log(LOG_WARNING, "Alloca failed!\n");
1309 last = strrchr(s, '/');
1314 snprintf(s2, strlen(s) + 100, "/var/tmp/%s-%ld", last, (unsigned long)ast_random());
1315 res = stat(s, &stbuf);
1317 ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno));
1320 /* Make sure it's not a directory */
1321 if (S_ISDIR(stbuf.st_mode))
1323 ifd = open(s, O_RDONLY);
1325 ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
1328 fd = open(s2, O_RDWR | O_CREAT | O_EXCL);
1330 ast_log(LOG_WARNING, "Cannot open '%s' for writing: %s\n", s2, strerror(errno));
1334 /* Unlink our newly created file */
1337 /* Now copy the firmware into it */
1338 len = stbuf.st_size;
1341 if (chunk > sizeof(buf))
1342 chunk = sizeof(buf);
1343 res = read(ifd, buf, chunk);
1345 ast_log(LOG_WARNING, "Only read %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1350 res = write(fd, buf, chunk);
1352 ast_log(LOG_WARNING, "Only write %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1360 /* Return to the beginning */
1361 lseek(fd, 0, SEEK_SET);
1362 if ((res = read(fd, &fwh2, sizeof(fwh2))) != sizeof(fwh2)) {
1363 ast_log(LOG_WARNING, "Unable to read firmware header in '%s'\n", s);
1367 if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) {
1368 ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s);
1372 if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) {
1373 ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s);
1377 if (fwh2.devname[sizeof(fwh2.devname) - 1] || ast_strlen_zero((char *)fwh2.devname)) {
1378 ast_log(LOG_WARNING, "No or invalid device type specified for '%s'\n", s);
1382 fwh = mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
1384 ast_log(LOG_WARNING, "mmap failed: %s\n", strerror(errno));
1389 MD5Update(&md5, fwh->data, ntohl(fwh->datalen));
1390 MD5Final(sum, &md5);
1391 if (memcmp(sum, fwh->chksum, sizeof(sum))) {
1392 ast_log(LOG_WARNING, "Firmware file '%s' fails checksum\n", s);
1393 munmap(fwh, stbuf.st_size);
1399 if (!strcmp((char *)cur->fwh->devname, (char *)fwh->devname)) {
1400 /* Found a candidate */
1401 if (cur->dead || (ntohs(cur->fwh->version) < ntohs(fwh->version)))
1402 /* The version we have on loaded is older, load this one instead */
1404 /* This version is no newer than what we have. Don't worry about it.
1405 We'll consider it a proper load anyhow though */
1406 munmap(fwh, stbuf.st_size);
1413 /* Allocate a new one and link it */
1414 if ((cur = ast_calloc(1, sizeof(*cur)))) {
1416 cur->next = waresl.wares;
1422 munmap(cur->fwh, cur->mmaplen);
1428 cur->mmaplen = stbuf.st_size;
1434 static int iax_check_version(char *dev)
1437 struct iax_firmware *cur;
1438 if (!ast_strlen_zero(dev)) {
1439 ast_mutex_lock(&waresl.lock);
1442 if (!strcmp(dev, (char *)cur->fwh->devname)) {
1443 res = ntohs(cur->fwh->version);
1448 ast_mutex_unlock(&waresl.lock);
1453 static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
1456 unsigned int bs = desc & 0xff;
1457 unsigned int start = (desc >> 8) & 0xffffff;
1459 struct iax_firmware *cur;
1460 if (!ast_strlen_zero((char *)dev) && bs) {
1462 ast_mutex_lock(&waresl.lock);
1465 if (!strcmp((char *)dev, (char *)cur->fwh->devname)) {
1466 iax_ie_append_int(ied, IAX_IE_FWBLOCKDESC, desc);
1467 if (start < ntohl(cur->fwh->datalen)) {
1468 bytes = ntohl(cur->fwh->datalen) - start;
1471 iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes);
1474 iax_ie_append(ied, IAX_IE_FWBLOCKDATA);
1484 ast_mutex_unlock(&waresl.lock);
1490 static void reload_firmware(void)
1492 struct iax_firmware *cur, *curl, *curp;
1497 /* Mark all as dead */
1498 ast_mutex_lock(&waresl.lock);
1504 /* Now that we've freed them, load the new ones */
1505 snprintf(dir, sizeof(dir), "%s/firmware/iax", (char *)ast_config_AST_DATA_DIR);
1508 while((de = readdir(fwd))) {
1509 if (de->d_name[0] != '.') {
1510 snprintf(fn, sizeof(fn), "%s/%s", dir, de->d_name);
1511 if (!try_firmware(fn)) {
1512 if (option_verbose > 1)
1513 ast_verbose(VERBOSE_PREFIX_2 "Loaded firmware '%s'\n", de->d_name);
1519 ast_log(LOG_WARNING, "Error opening firmware directory '%s': %s\n", dir, strerror(errno));
1521 /* Clean up leftovers */
1533 destroy_firmware(curl);
1538 ast_mutex_unlock(&waresl.lock);
1541 static int __do_deliver(void *data)
1543 /* Just deliver the packet by using queueing. This is called by
1544 the IAX thread with the iaxsl lock held. */
1545 struct iax_frame *fr = data;
1547 fr->af.has_timing_info = 0;
1548 if (iaxs[fr->callno] && !ast_test_flag(iaxs[fr->callno], IAX_ALREADYGONE))
1549 iax2_queue_frame(fr->callno, &fr->af);
1550 /* Free our iax frame */
1551 iax2_frame_free(fr);
1552 /* And don't run again */
1556 static int handle_error(void)
1558 /* XXX Ideally we should figure out why an error occured and then abort those
1559 rather than continuing to try. Unfortunately, the published interface does
1560 not seem to work XXX */
1562 struct sockaddr_in *sin;
1565 struct sock_extended_err e;
1570 m.msg_controllen = sizeof(e);
1572 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
1574 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
1576 if (m.msg_controllen) {
1577 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
1579 ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr));
1581 ast_log(LOG_WARNING, "No address detected??\n");
1583 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
1590 static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin, int sockfd)
1593 res = sendto(sockfd, f->data, f->datalen, 0,(struct sockaddr *)sin,
1597 ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
1604 static int send_packet(struct iax_frame *f)
1607 char iabuf[INET_ADDRSTRLEN];
1608 int callno = f->callno;
1610 /* Don't send if there was an error, but return error instead */
1611 if (!callno || !iaxs[callno] || iaxs[callno]->error)
1614 /* Called with iaxsl held */
1615 if (option_debug > 2 && iaxdebug)
1616 ast_log(LOG_DEBUG, "Sending %d on %d/%d to %s:%d\n", f->ts, callno, iaxs[callno]->peercallno, ast_inet_ntoa(iabuf, sizeof(iabuf), iaxs[callno]->addr.sin_addr), ntohs(iaxs[callno]->addr.sin_port));
1619 iax_showframe(f, NULL, 0, &iaxs[callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
1620 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->transfer,
1621 sizeof(iaxs[callno]->transfer));
1624 iax_showframe(f, NULL, 0, &iaxs[callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
1625 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->addr,
1626 sizeof(iaxs[callno]->addr));
1629 if (option_debug && iaxdebug)
1630 ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
1637 static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
1639 /* No more pings or lagrq's */
1640 if (pvt->pingid > -1)
1641 ast_sched_del(sched, pvt->pingid);
1643 if (pvt->lagid > -1)
1644 ast_sched_del(sched, pvt->lagid);
1646 if (pvt->autoid > -1)
1647 ast_sched_del(sched, pvt->autoid);
1649 if (pvt->authid > -1)
1650 ast_sched_del(sched, pvt->authid);
1652 if (pvt->initid > -1)
1653 ast_sched_del(sched, pvt->initid);
1656 ast_sched_del(sched, pvt->jbid);
1660 static int iax2_predestroy(int callno)
1662 struct ast_channel *c;
1663 struct chan_iax2_pvt *pvt;
1664 ast_mutex_lock(&iaxsl[callno]);
1667 ast_mutex_unlock(&iaxsl[callno]);
1670 if (!ast_test_flag(pvt, IAX_ALREADYGONE)) {
1671 iax2_destroy_helper(pvt);
1672 ast_set_flag(pvt, IAX_ALREADYGONE);
1676 c->_softhangup |= AST_SOFTHANGUP_DEV;
1678 ast_queue_hangup(c);
1680 ast_mutex_lock(&usecnt_lock);
1683 ast_log(LOG_WARNING, "Usecnt < 0???\n");
1684 ast_mutex_unlock(&usecnt_lock);
1686 ast_mutex_unlock(&iaxsl[callno]);
1687 ast_update_use_count();
1691 static int iax2_predestroy_nolock(int callno)
1694 ast_mutex_unlock(&iaxsl[callno]);
1695 res = iax2_predestroy(callno);
1696 ast_mutex_lock(&iaxsl[callno]);
1700 static void iax2_destroy(int callno)
1702 struct chan_iax2_pvt *pvt;
1703 struct iax_frame *cur;
1704 struct ast_channel *owner;
1707 ast_mutex_lock(&iaxsl[callno]);
1709 gettimeofday(&lastused[callno], NULL);
1711 owner = pvt ? pvt->owner : NULL;
1714 if (ast_mutex_trylock(&owner->lock)) {
1715 ast_log(LOG_NOTICE, "Avoiding IAX destroy deadlock\n");
1716 ast_mutex_unlock(&iaxsl[callno]);
1722 iaxs[callno] = NULL;
1726 iax2_destroy_helper(pvt);
1727 if (pvt->bridgetrans)
1728 ast_translator_free_path(pvt->bridgetrans);
1729 pvt->bridgetrans = NULL;
1732 ast_set_flag(pvt, IAX_ALREADYGONE);
1735 /* If there's an owner, prod it to give up */
1736 owner->_softhangup |= AST_SOFTHANGUP_DEV;
1737 ast_queue_hangup(owner);
1740 for (cur = iaxq.head; cur ; cur = cur->next) {
1741 /* Cancel any pending transmissions */
1742 if (cur->callno == pvt->callno)
1746 pvt->reg->callno = 0;
1750 ast_variables_destroy(pvt->vars);
1754 while (jb_getall(pvt->jb, &frame) == JB_OK)
1755 iax2_frame_free(frame.data);
1756 jb_destroy(pvt->jb);
1761 ast_mutex_unlock(&owner->lock);
1763 ast_mutex_unlock(&iaxsl[callno]);
1764 if (callno & 0x4000)
1767 static void iax2_destroy_nolock(int callno)
1769 /* Actually it's easier to unlock, kill it, and relock */
1770 ast_mutex_unlock(&iaxsl[callno]);
1771 iax2_destroy(callno);
1772 ast_mutex_lock(&iaxsl[callno]);
1775 static int update_packet(struct iax_frame *f)
1777 /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
1778 struct ast_iax2_full_hdr *fh = f->data;
1779 /* Mark this as a retransmission */
1780 fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
1782 f->iseqno = iaxs[f->callno]->iseqno;
1783 fh->iseqno = f->iseqno;
1787 static int attempt_transmit(void *data);
1788 static void __attempt_transmit(void *data)
1790 /* Attempt to transmit the frame to the remote peer...
1791 Called without iaxsl held. */
1792 struct iax_frame *f = data;
1794 int callno = f->callno;
1795 char iabuf[INET_ADDRSTRLEN];
1796 /* Make sure this call is still active */
1798 ast_mutex_lock(&iaxsl[callno]);
1799 if (callno && iaxs[callno]) {
1800 if ((f->retries < 0) /* Already ACK'd */ ||
1801 (f->retries >= max_retries) /* Too many attempts */) {
1802 /* Record an error if we've transmitted too many times */
1803 if (f->retries >= max_retries) {
1805 /* Transfer timeout */
1806 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
1807 } else if (f->final) {
1809 iax2_destroy_nolock(callno);
1811 if (iaxs[callno]->owner)
1812 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);
1813 iaxs[callno]->error = ETIMEDOUT;
1814 if (iaxs[callno]->owner) {
1815 struct ast_frame fr = { 0, };
1817 fr.frametype = AST_FRAME_CONTROL;
1818 fr.subclass = AST_CONTROL_HANGUP;
1819 iax2_queue_frame(callno, &fr);
1820 /* Remember, owner could disappear */
1821 if (iaxs[callno]->owner)
1822 iaxs[callno]->owner->hangupcause = AST_CAUSE_DESTINATION_OUT_OF_ORDER;
1824 if (iaxs[callno]->reg) {
1825 memset(&iaxs[callno]->reg->us, 0, sizeof(iaxs[callno]->reg->us));
1826 iaxs[callno]->reg->regstate = REG_STATE_TIMEOUT;
1827 iaxs[callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
1829 iax2_destroy_nolock(callno);
1836 /* Update it if it needs it */
1838 /* Attempt transmission */
1841 /* Try again later after 10 times as long */
1843 if (f->retrytime > MAX_RETRY_TIME)
1844 f->retrytime = MAX_RETRY_TIME;
1845 /* Transfer messages max out at one second */
1846 if (f->transfer && (f->retrytime > 1000))
1847 f->retrytime = 1000;
1848 f->retrans = ast_sched_add(sched, f->retrytime, attempt_transmit, f);
1851 /* Make sure it gets freed */
1856 ast_mutex_unlock(&iaxsl[callno]);
1857 /* Do not try again */
1859 /* Don't attempt delivery, just remove it from the queue */
1860 ast_mutex_lock(&iaxq.lock);
1862 f->prev->next = f->next;
1864 iaxq.head = f->next;
1866 f->next->prev = f->prev;
1868 iaxq.tail = f->prev;
1870 ast_mutex_unlock(&iaxq.lock);
1872 /* Free the IAX frame */
1877 static int attempt_transmit(void *data)
1879 #ifdef SCHED_MULTITHREADED
1880 if (schedule_action(__attempt_transmit, data))
1882 __attempt_transmit(data);
1886 static int iax2_prune_realtime(int fd, int argc, char *argv[])
1888 struct iax2_peer *peer;
1891 return RESULT_SHOWUSAGE;
1892 if (!strcmp(argv[3],"all")) {
1894 ast_cli(fd, "OK cache is flushed.\n");
1895 } else if ((peer = find_peer(argv[3], 0))) {
1896 if(ast_test_flag(peer, IAX_RTCACHEFRIENDS)) {
1897 ast_set_flag(peer, IAX_RTAUTOCLEAR);
1898 expire_registry(peer->name);
1899 ast_cli(fd, "OK peer %s was removed from the cache.\n", argv[3]);
1901 ast_cli(fd, "SORRY peer %s is not eligible for this operation.\n", argv[3]);
1904 ast_cli(fd, "SORRY peer %s was not found in the cache.\n", argv[3]);
1907 return RESULT_SUCCESS;
1910 static int iax2_test_losspct(int fd, int argc, char *argv[])
1913 return RESULT_SHOWUSAGE;
1915 test_losspct = atoi(argv[3]);
1917 return RESULT_SUCCESS;
1921 static int iax2_test_late(int fd, int argc, char *argv[])
1924 return RESULT_SHOWUSAGE;
1926 test_late = atoi(argv[3]);
1928 return RESULT_SUCCESS;
1931 static int iax2_test_resync(int fd, int argc, char *argv[])
1934 return RESULT_SHOWUSAGE;
1936 test_resync = atoi(argv[3]);
1938 return RESULT_SUCCESS;
1941 static int iax2_test_jitter(int fd, int argc, char *argv[])
1943 if (argc < 4 || argc > 5)
1944 return RESULT_SHOWUSAGE;
1946 test_jit = atoi(argv[3]);
1948 test_jitpct = atoi(argv[4]);
1950 return RESULT_SUCCESS;
1952 #endif /* IAXTESTS */
1954 /*! \brief peer_status: Report Peer status in character string */
1955 /* returns 1 if peer is online, -1 if unmonitored */
1956 static int peer_status(struct iax2_peer *peer, char *status, int statuslen)
1960 if (peer->lastms < 0) {
1961 ast_copy_string(status, "UNREACHABLE", statuslen);
1962 } else if (peer->lastms > peer->maxms) {
1963 snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
1965 } else if (peer->lastms) {
1966 snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
1969 ast_copy_string(status, "UNKNOWN", statuslen);
1972 ast_copy_string(status, "Unmonitored", statuslen);
1978 /*! \brief Show one peer in detail */
1979 static int iax2_show_peer(int fd, int argc, char *argv[])
1983 char iabuf[INET_ADDRSTRLEN];
1984 struct iax2_peer *peer;
1985 char codec_buf[512];
1986 int x = 0, codec = 0, load_realtime = 0;
1989 return RESULT_SHOWUSAGE;
1991 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? 1 : 0;
1993 peer = find_peer(argv[3], load_realtime);
1996 ast_cli(fd, " * Name : %s\n", peer->name);
1997 ast_cli(fd, " Secret : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
1998 ast_cli(fd, " Context : %s\n", peer->context);
1999 ast_cli(fd, " Mailbox : %s\n", peer->mailbox);
2000 ast_cli(fd, " Dynamic : %s\n", ast_test_flag(peer, IAX_DYNAMIC) ? "Yes":"No");
2001 ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
2002 ast_cli(fd, " Expire : %d\n", peer->expire);
2003 ast_cli(fd, " ACL : %s\n", (peer->ha?"Yes":"No"));
2004 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));
2005 ast_cli(fd, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
2006 ast_cli(fd, " Username : %s\n", peer->username);
2007 ast_cli(fd, " Codecs : ");
2008 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
2009 ast_cli(fd, "%s\n", codec_buf);
2011 ast_cli(fd, " Codec Order : (");
2012 for(x = 0; x < 32 ; x++) {
2013 codec = ast_codec_pref_index(&peer->prefs,x);
2016 ast_cli(fd, "%s", ast_getformatname(codec));
2017 if(x < 31 && ast_codec_pref_index(&peer->prefs,x+1))
2022 ast_cli(fd, "none");
2025 ast_cli(fd, " Status : ");
2026 peer_status(peer, status, sizeof(status));
2027 ast_cli(fd, "%s\n",status);
2028 ast_cli(fd, " Qualify : every %dms when OK, every %dms when UNREACHABLE (sample smoothing %s)\n", peer->pokefreqok, peer->pokefreqnotok, peer->smoothing ? "On" : "Off");
2030 if (ast_test_flag(peer, IAX_TEMPONLY))
2033 ast_cli(fd,"Peer %s not found.\n", argv[3]);
2037 return RESULT_SUCCESS;
2040 static char *complete_iax2_show_peer(const char *line, const char *word, int pos, int state)
2043 struct iax2_peer *p = NULL;
2045 int wordlen = strlen(word);
2047 /* 0 - iax2; 1 - show; 2 - peer; 3 - <peername> */
2049 AST_LIST_LOCK(&peers);
2050 AST_LIST_TRAVERSE(&peers, p, entry) {
2051 if (!strncasecmp(p->name, word, wordlen) && ++which > state) {
2052 res = ast_strdup(p->name);
2056 AST_LIST_UNLOCK(&peers);
2062 static int iax2_show_stats(int fd, int argc, char *argv[])
2064 struct iax_frame *cur;
2065 int cnt = 0, dead=0, final=0;
2067 return RESULT_SHOWUSAGE;
2068 for (cur = iaxq.head; cur ; cur = cur->next) {
2069 if (cur->retries < 0)
2075 ast_cli(fd, " IAX Statistics\n");
2076 ast_cli(fd, "---------------------\n");
2077 ast_cli(fd, "Outstanding frames: %d (%d ingress, %d egress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
2078 ast_cli(fd, "Packets in transmit queue: %d dead, %d final, %d total\n", dead, final, cnt);
2079 return RESULT_SUCCESS;
2082 static int iax2_show_cache(int fd, int argc, char *argv[])
2084 struct iax2_dpcache *dp;
2085 char tmp[1024], *pc;
2089 gettimeofday(&tv, NULL);
2090 ast_mutex_lock(&dpcache_lock);
2092 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
2094 s = dp->expiry.tv_sec - tv.tv_sec;
2096 if (dp->flags & CACHE_FLAG_EXISTS)
2097 strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
2098 if (dp->flags & CACHE_FLAG_NONEXISTENT)
2099 strncat(tmp, "NONEXISTENT|", sizeof(tmp) - strlen(tmp) - 1);
2100 if (dp->flags & CACHE_FLAG_CANEXIST)
2101 strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
2102 if (dp->flags & CACHE_FLAG_PENDING)
2103 strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
2104 if (dp->flags & CACHE_FLAG_TIMEOUT)
2105 strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
2106 if (dp->flags & CACHE_FLAG_TRANSMITTED)
2107 strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
2108 if (dp->flags & CACHE_FLAG_MATCHMORE)
2109 strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
2110 if (dp->flags & CACHE_FLAG_UNKNOWN)
2111 strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
2112 /* Trim trailing pipe */
2113 if (!ast_strlen_zero(tmp))
2114 tmp[strlen(tmp) - 1] = '\0';
2116 ast_copy_string(tmp, "(none)", sizeof(tmp));
2118 pc = strchr(dp->peercontext, '@');
2120 pc = dp->peercontext;
2123 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
2124 if (dp->waiters[x] > -1)
2127 ast_cli(fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
2129 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
2132 ast_mutex_unlock(&dpcache_lock);
2133 return RESULT_SUCCESS;
2136 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
2138 #ifdef BRIDGE_OPTIMIZATION
2139 static unsigned int calc_fakestamp(struct chan_iax2_pvt *from, struct chan_iax2_pvt *to, unsigned int ts);
2141 static int forward_delivery(struct iax_frame *fr)
2143 struct chan_iax2_pvt *p1, *p2;
2144 char iabuf[INET_ADDRSTRLEN];
2147 p1 = iaxs[fr->callno];
2148 p2 = iaxs[p1->bridgecallno];
2155 ast_log(LOG_DEBUG, "forward_delivery: Forwarding ts=%d on %d/%d to %d/%d on %s:%d\n",
2157 p1->callno, p1->peercallno,
2158 p2->callno, p2->peercallno,
2159 ast_inet_ntoa(iabuf, sizeof(iabuf), p2->addr.sin_addr),
2160 ntohs(p2->addr.sin_port));
2162 /* Undo wraparound - which can happen when full VOICE frame wasn't sent by our peer.
2163 This is necessary for when our peer is chan_iax2.c v1.1nn or earlier which didn't
2164 send full frame on timestamp wrap when doing optimized bridging
2165 (actually current code STILL doesn't)
2167 if (fr->ts + 50000 <= p1->last) {
2168 fr->ts = ( (p1->last & 0xFFFF0000) + 0x10000) | (fr->ts & 0xFFFF);
2170 ast_log(LOG_DEBUG, "forward_delivery: pushed forward timestamp to %u\n", fr->ts);
2173 /* Send with timestamp adjusted to the origin of the outbound leg */
2174 /* But don't destroy inbound timestamp still needed later to set "last" */
2176 fr->ts = calc_fakestamp(p1, p2, fr->ts);
2177 res = iax2_send(p2, &fr->af, fr->ts, -1, 0, 0, 0);
2183 static void unwrap_timestamp(struct iax_frame *fr)
2187 if ( (fr->ts & 0xFFFF0000) == (iaxs[fr->callno]->last & 0xFFFF0000) ) {
2188 x = fr->ts - iaxs[fr->callno]->last;
2190 /* Sudden big jump backwards in timestamp:
2191 What likely happened here is that miniframe timestamp has circled but we haven't
2192 gotten the update from the main packet. We'll just pretend that we did, and
2193 update the timestamp appropriately. */
2194 fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) + 0x10000) | (fr->ts & 0xFFFF);
2195 if (option_debug && iaxdebug)
2196 ast_log(LOG_DEBUG, "schedule_delivery: pushed forward timestamp\n");
2199 /* Sudden apparent big jump forwards in timestamp:
2200 What's likely happened is this is an old miniframe belonging to the previous
2201 top-16-bit timestamp that has turned up out of order.
2202 Adjust the timestamp appropriately. */
2203 fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) - 0x10000) | (fr->ts & 0xFFFF);
2204 if (option_debug && iaxdebug)
2205 ast_log(LOG_DEBUG, "schedule_delivery: pushed back timestamp\n");
2210 static int get_from_jb(void *p);
2212 static void update_jbsched(struct chan_iax2_pvt *pvt)
2216 when = ast_tvdiff_ms(ast_tvnow(), pvt->rxcore);
2218 /* fprintf(stderr, "now = %d, next=%d\n", when, jb_next(pvt->jb)); */
2220 when = jb_next(pvt->jb) - when;
2221 /* fprintf(stderr, "when = %d\n", when); */
2223 if(pvt->jbid > -1) ast_sched_del(sched, pvt->jbid);
2226 /* XXX should really just empty until when > 0.. */
2230 pvt->jbid = ast_sched_add(sched, when, get_from_jb, CALLNO_TO_PTR(pvt->callno));
2232 /* Signal scheduler thread */
2233 signal_condition(&sched_lock, &sched_cond);
2236 static void __get_from_jb(void *p)
2238 int callno = PTR_TO_CALLNO(p);
2239 struct chan_iax2_pvt *pvt = iaxs[callno];
2240 struct iax_frame *fr;
2247 /* Make sure we have a valid private structure before going on */
2248 ast_mutex_lock(&iaxsl[callno]);
2252 ast_mutex_unlock(&iaxsl[callno]);
2256 /* fprintf(stderr, "get_from_jb called\n"); */
2259 gettimeofday(&tv,NULL);
2260 /* round up a millisecond since ast_sched_runq does; */
2261 /* prevents us from spinning while waiting for our now */
2262 /* to catch up with runq's now */
2265 now = ast_tvdiff_ms(tv, pvt->rxcore);
2267 if(now >= (next = jb_next(pvt->jb))) {
2268 ret = jb_get(pvt->jb,&frame,now,ast_codec_interp_len(pvt->voiceformat));
2271 /*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); */
2277 struct ast_frame af;
2279 /*if(next + 20 != jb_next(pvt->jb)) fprintf(stderr, "NEXT %ld is not %ld+20!\n", jb_next(pvt->jb), next); */
2281 /* create an interpolation frame */
2282 /*fprintf(stderr, "Making Interpolation frame\n"); */
2283 af.frametype = AST_FRAME_VOICE;
2284 af.subclass = pvt->voiceformat;
2286 af.samples = frame.ms * 8;
2288 af.src = "IAX2 JB interpolation";
2290 af.delivery = ast_tvadd(pvt->rxcore, ast_samp2tv(next, 1000));
2291 af.offset=AST_FRIENDLY_OFFSET;
2293 /* queue the frame: For consistency, we would call __do_deliver here, but __do_deliver wants an iax_frame,
2294 * which we'd need to malloc, and then it would free it. That seems like a drag */
2295 if (!ast_test_flag(iaxs[callno], IAX_ALREADYGONE))
2296 iax2_queue_frame(callno, &af);
2300 /*if(next != jb_next(pvt->jb)) fprintf(stderr, "NEXT %ld is not next %ld!\n", jb_next(pvt->jb), next); */
2301 iax2_frame_free(frame.data);
2308 /* shouldn't happen */
2312 update_jbsched(pvt);
2313 ast_mutex_unlock(&iaxsl[callno]);
2316 static int get_from_jb(void *data)
2318 #ifdef SCHED_MULTITHREADED
2319 if (schedule_action(__get_from_jb, data))
2321 __get_from_jb(data);
2325 static int schedule_delivery(struct iax_frame *fr, int updatehistory, int fromtrunk, unsigned int *tsout)
2331 /* Attempt to recover wrapped timestamps */
2332 unwrap_timestamp(fr);
2335 /* delivery time is sender's sent timestamp converted back into absolute time according to our clock */
2336 if ( !fromtrunk && !ast_tvzero(iaxs[fr->callno]->rxcore))
2337 fr->af.delivery = ast_tvadd(iaxs[fr->callno]->rxcore, ast_samp2tv(fr->ts, 1000));
2340 ast_log(LOG_DEBUG, "schedule_delivery: set delivery to 0 as we don't have an rxcore yet, or frame is from trunk.\n");
2342 fr->af.delivery = ast_tv(0,0);
2345 type = JB_TYPE_CONTROL;
2348 if(fr->af.frametype == AST_FRAME_VOICE) {
2349 type = JB_TYPE_VOICE;
2350 len = ast_codec_get_samples(&fr->af) / 8;
2351 } else if(fr->af.frametype == AST_FRAME_CNG) {
2352 type = JB_TYPE_SILENCE;
2355 if ( (!ast_test_flag(iaxs[fr->callno], IAX_USEJITTERBUF)) ) {
2362 /* if the user hasn't requested we force the use of the jitterbuffer, and we're bridged to
2363 * a channel that can accept jitter, then flush and suspend the jb, and send this frame straight through */
2364 if( (!ast_test_flag(iaxs[fr->callno], IAX_FORCEJITTERBUF)) &&
2365 iaxs[fr->callno]->owner && ast_bridged_channel(iaxs[fr->callno]->owner) &&
2366 (ast_bridged_channel(iaxs[fr->callno]->owner)->tech->properties & AST_CHAN_TP_WANTSJITTER)) {
2369 /* deliver any frames in the jb */
2370 while(jb_getall(iaxs[fr->callno]->jb,&frame) == JB_OK)
2371 __do_deliver(frame.data);
2373 jb_reset(iaxs[fr->callno]->jb);
2375 if (iaxs[fr->callno]->jbid > -1)
2376 ast_sched_del(sched, iaxs[fr->callno]->jbid);
2378 iaxs[fr->callno]->jbid = -1;
2380 /* deliver this frame now */
2387 /* insert into jitterbuffer */
2388 /* TODO: Perhaps we could act immediately if it's not droppable and late */
2389 ret = jb_put(iaxs[fr->callno]->jb, fr, type, len, fr->ts,
2390 calc_rxstamp(iaxs[fr->callno],fr->ts));
2391 if (ret == JB_DROP) {
2393 } else if (ret == JB_SCHED) {
2394 update_jbsched(iaxs[fr->callno]);
2399 /* Free our iax frame */
2400 iax2_frame_free(fr);
2406 static int iax2_transmit(struct iax_frame *fr)
2408 /* Lock the queue and place this packet at the end */
2411 /* By setting this to 0, the network thread will send it for us, and
2412 queue retransmission if necessary */
2414 ast_mutex_lock(&iaxq.lock);
2421 iaxq.tail->next = fr;
2422 fr->prev = iaxq.tail;
2426 ast_mutex_unlock(&iaxq.lock);
2427 /* Wake up the network and scheduler thread */
2428 pthread_kill(netthreadid, SIGURG);
2429 signal_condition(&sched_lock, &sched_cond);
2435 static int iax2_digit(struct ast_channel *c, char digit)
2437 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF, digit, 0, NULL, 0, -1);
2440 static int iax2_sendtext(struct ast_channel *c, const char *text)
2443 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_TEXT,
2444 0, 0, (unsigned char *)text, strlen(text) + 1, -1);
2447 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
2449 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_IMAGE, img->subclass, 0, img->data, img->datalen, -1);
2452 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen)
2454 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_HTML, subclass, 0, (unsigned char *)data, datalen, -1);
2457 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
2459 unsigned short callno = PTR_TO_CALLNO(newchan->tech_pvt);
2460 ast_mutex_lock(&iaxsl[callno]);
2462 iaxs[callno]->owner = newchan;
2464 ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n");
2465 ast_mutex_unlock(&iaxsl[callno]);
2469 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin)
2471 struct ast_variable *var;
2472 struct ast_variable *tmp;
2473 struct iax2_peer *peer=NULL;
2474 time_t regseconds = 0, nowtime;
2478 var = ast_load_realtime("iaxpeers", "name", peername, NULL);
2480 char iabuf[INET_ADDRSTRLEN];
2482 ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr);
2483 sprintf(porta, "%d", ntohs(sin->sin_port));
2484 var = ast_load_realtime("iaxpeers", "ipaddr", iabuf, "port", porta, NULL);
2486 /* We'll need the peer name in order to build the structure! */
2489 if (!strcasecmp(tmp->name, "name"))
2490 peername = tmp->value;
2498 peer = build_peer(peername, var, ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS) ? 0 : 1);
2505 /* Make sure it's not a user only... */
2506 if (!strcasecmp(tmp->name, "type")) {
2507 if (strcasecmp(tmp->value, "friend") &&
2508 strcasecmp(tmp->value, "peer")) {
2509 /* Whoops, we weren't supposed to exist! */
2514 } else if (!strcasecmp(tmp->name, "regseconds")) {
2515 ast_get_time_t(tmp->value, ®seconds, 0, NULL);
2516 } else if (!strcasecmp(tmp->name, "ipaddr")) {
2517 inet_aton(tmp->value, &(peer->addr.sin_addr));
2518 } else if (!strcasecmp(tmp->name, "port")) {
2519 peer->addr.sin_port = htons(atoi(tmp->value));
2520 } else if (!strcasecmp(tmp->name, "host")) {
2521 if (!strcasecmp(tmp->value, "dynamic"))
2529 ast_variables_destroy(var);
2531 if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
2532 ast_copy_flags(peer, &globalflags, IAX_RTAUTOCLEAR|IAX_RTCACHEFRIENDS);
2533 if (ast_test_flag(peer, IAX_RTAUTOCLEAR)) {
2534 if (peer->expire > -1)
2535 ast_sched_del(sched, peer->expire);
2536 peer->expire = ast_sched_add(sched, (global_rtautoclear) * 1000, expire_registry, (void*)peer->name);
2538 AST_LIST_LOCK(&peers);
2539 AST_LIST_INSERT_HEAD(&peers, peer, entry);
2540 AST_LIST_UNLOCK(&peers);
2541 if (ast_test_flag(peer, IAX_DYNAMIC))
2542 reg_source_db(peer);
2544 ast_set_flag(peer, IAX_TEMPONLY);
2547 if (!ast_test_flag(&globalflags, IAX_RTIGNOREREGEXPIRE) && dynamic) {
2549 if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE) {
2550 memset(&peer->addr, 0, sizeof(peer->addr));
2552 ast_log(LOG_DEBUG, "realtime_peer: Bah, '%s' is expired (%d/%d/%d)!\n",
2553 peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
2557 ast_log(LOG_DEBUG, "realtime_peer: Registration for '%s' still active (%d/%d/%d)!\n",
2558 peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
2565 static struct iax2_user *realtime_user(const char *username)
2567 struct ast_variable *var;
2568 struct ast_variable *tmp;
2569 struct iax2_user *user=NULL;
2571 var = ast_load_realtime("iaxusers", "name", username, NULL);
2577 /* Make sure it's not a peer only... */
2578 if (!strcasecmp(tmp->name, "type")) {
2579 if (strcasecmp(tmp->value, "friend") &&
2580 strcasecmp(tmp->value, "user")) {
2587 user = build_user(username, var, !ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS));
2591 ast_variables_destroy(var);
2593 if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
2594 ast_set_flag(user, IAX_RTCACHEFRIENDS);
2595 AST_LIST_LOCK(&users);
2596 AST_LIST_INSERT_HEAD(&users, user, entry);
2597 AST_LIST_UNLOCK(&users);
2599 ast_set_flag(user, IAX_TEMPONLY);
2605 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin)
2609 char regseconds[20];
2613 snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime);
2614 ast_inet_ntoa(ipaddr, sizeof(ipaddr), sin->sin_addr);
2615 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
2616 ast_update_realtime("iaxpeers", "name", peername, "ipaddr", ipaddr, "port", port, "regseconds", regseconds, NULL);
2619 struct create_addr_info {
2631 char context[AST_MAX_CONTEXT];
2632 char peercontext[AST_MAX_CONTEXT];
2635 static int create_addr(const char *peername, struct sockaddr_in *sin, struct create_addr_info *cai)
2637 struct ast_hostent ahp;
2639 struct iax2_peer *peer;
2641 ast_clear_flag(cai, IAX_SENDANI | IAX_TRUNK);
2642 cai->sockfd = defaultsockfd;
2644 sin->sin_family = AF_INET;
2646 if (!(peer = find_peer(peername, 1))) {
2649 hp = ast_gethostbyname(peername, &ahp);
2651 memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
2652 sin->sin_port = htons(IAX_DEFAULT_PORTNO);
2653 /* use global iax prefs for unknown peer/user */
2654 ast_codec_pref_convert(&prefs, cai->prefs, sizeof(cai->prefs), 1);
2657 ast_log(LOG_WARNING, "No such host: %s\n", peername);
2664 /* if the peer has no address (current or default), return failure */
2665 if (!(peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr)) {
2666 if (ast_test_flag(peer, IAX_TEMPONLY))
2671 /* if the peer is being monitored and is currently unreachable, return failure */
2672 if (peer->maxms && ((peer->lastms > peer->maxms) || (peer->lastms < 0))) {
2673 if (ast_test_flag(peer, IAX_TEMPONLY))
2678 ast_copy_flags(cai, peer, IAX_SENDANI | IAX_TRUNK | IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
2679 cai->maxtime = peer->maxms;
2680 cai->capability = peer->capability;
2681 cai->encmethods = peer->encmethods;
2682 cai->sockfd = peer->sockfd;
2683 ast_codec_pref_convert(&peer->prefs, cai->prefs, sizeof(cai->prefs), 1);
2684 ast_copy_string(cai->context, peer->context, sizeof(cai->context));
2685 ast_copy_string(cai->peercontext, peer->peercontext, sizeof(cai->peercontext));
2686 ast_copy_string(cai->username, peer->username, sizeof(cai->username));
2687 ast_copy_string(cai->timezone, peer->zonetag, sizeof(cai->timezone));
2688 ast_copy_string(cai->outkey, peer->outkey, sizeof(cai->outkey));
2689 if (ast_strlen_zero(peer->dbsecret)) {
2690 ast_copy_string(cai->secret, peer->secret, sizeof(cai->secret));
2695 family = ast_strdupa(peer->dbsecret);
2696 key = strchr(family, '/');
2699 if (!key || ast_db_get(family, key, cai->secret, sizeof(cai->secret))) {
2700 ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", peer->dbsecret);
2701 if (ast_test_flag(peer, IAX_TEMPONLY))
2707 if (peer->addr.sin_addr.s_addr) {
2708 sin->sin_addr = peer->addr.sin_addr;
2709 sin->sin_port = peer->addr.sin_port;
2711 sin->sin_addr = peer->defaddr.sin_addr;
2712 sin->sin_port = peer->defaddr.sin_port;
2715 if (ast_test_flag(peer, IAX_TEMPONLY))
2721 static void __auto_congest(void *nothing)
2723 int callno = PTR_TO_CALLNO(nothing);
2724 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_CONGESTION };
2725 ast_mutex_lock(&iaxsl[callno]);
2727 iaxs[callno]->initid = -1;
2728 iax2_queue_frame(callno, &f);
2729 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
2731 ast_mutex_unlock(&iaxsl[callno]);
2734 static int auto_congest(void *data)
2736 #ifdef SCHED_MULTITHREADED
2737 if (schedule_action(__auto_congest, data))
2739 __auto_congest(data);
2743 static unsigned int iax2_datetime(char *tz)
2749 localtime_r(&t, &tm);
2750 if (!ast_strlen_zero(tz))
2751 ast_localtime(&t, &tm, tz);
2752 tmp = (tm.tm_sec >> 1) & 0x1f; /* 5 bits of seconds */
2753 tmp |= (tm.tm_min & 0x3f) << 5; /* 6 bits of minutes */
2754 tmp |= (tm.tm_hour & 0x1f) << 11; /* 5 bits of hours */
2755 tmp |= (tm.tm_mday & 0x1f) << 16; /* 5 bits of day of month */
2756 tmp |= ((tm.tm_mon + 1) & 0xf) << 21; /* 4 bits of month */
2757 tmp |= ((tm.tm_year - 100) & 0x7f) << 25; /* 7 bits of year */
2761 struct parsed_dial_string {
2773 * \brief Parses an IAX dial string into its component parts.
2774 * \param data the string to be parsed
2775 * \param pds pointer to a \c struct \c parsed_dial_string to be filled in
2778 * This function parses the string and fills the structure
2779 * with pointers to its component parts. The input string
2782 * \note This function supports both plaintext passwords and RSA
2783 * key names; if the password string is formatted as '[keyname]',
2784 * then the keyname will be placed into the key field, and the
2785 * password field will be set to NULL.
2787 * \note The dial string format is:
2788 * [username[:password]@]peer[:port][/exten[@@context]][/options]
2790 static void parse_dial_string(char *data, struct parsed_dial_string *pds)
2792 if (ast_strlen_zero(data))
2795 pds->peer = strsep(&data, "/");
2796 pds->exten = strsep(&data, "/");
2797 pds->options = data;
2801 pds->exten = strsep(&data, "@");
2802 pds->context = data;
2805 if (strchr(pds->peer, '@')) {
2807 pds->username = strsep(&data, "@");
2811 if (pds->username) {
2812 data = pds->username;
2813 pds->username = strsep(&data, ":");
2814 pds->password = data;
2818 pds->peer = strsep(&data, ":");
2821 /* check for a key name wrapped in [] in the secret position, if found,
2822 move it to the key field instead
2824 if (pds->password && (pds->password[0] == '[')) {
2825 pds->key = ast_strip_quoted(pds->password, "[", "]");
2826 pds->password = NULL;
2830 static int iax2_call(struct ast_channel *c, char *dest, int timeout)
2832 struct sockaddr_in sin;
2833 char *l=NULL, *n=NULL, *tmpstr;
2834 struct iax_ie_data ied;
2835 char *defaultrdest = "s";
2836 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
2837 struct parsed_dial_string pds;
2838 struct create_addr_info cai;
2840 if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
2841 ast_log(LOG_WARNING, "Channel is already in use (%s)?\n", c->name);
2845 memset(&cai, 0, sizeof(cai));
2846 cai.encmethods = iax2_encryption;
2848 memset(&pds, 0, sizeof(pds));
2849 tmpstr = ast_strdupa(dest);
2850 parse_dial_string(tmpstr, &pds);
2853 pds.exten = defaultrdest;
2855 if (create_addr(pds.peer, &sin, &cai)) {
2856 ast_log(LOG_WARNING, "No address associated with '%s'\n", pds.peer);
2860 if (!pds.username && !ast_strlen_zero(cai.username))
2861 pds.username = cai.username;
2862 if (!pds.password && !ast_strlen_zero(cai.secret))
2863 pds.password = cai.secret;
2864 if (!pds.key && !ast_strlen_zero(cai.outkey))
2865 pds.key = cai.outkey;
2866 if (!pds.context && !ast_strlen_zero(cai.peercontext))
2867 pds.context = cai.peercontext;
2869 /* Keep track of the context for outgoing calls too */
2870 ast_copy_string(c->context, cai.context, sizeof(c->context));
2873 sin.sin_port = htons(atoi(pds.port));
2876 n = c->cid.cid_name;
2878 /* Now build request */
2879 memset(&ied, 0, sizeof(ied));
2881 /* On new call, first IE MUST be IAX version of caller */
2882 iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
2883 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, pds.exten);
2884 if (pds.options && strchr(pds.options, 'a')) {
2885 /* Request auto answer */
2886 iax_ie_append(&ied, IAX_IE_AUTOANSWER);
2889 iax_ie_append_str(&ied, IAX_IE_CODEC_PREFS, cai.prefs);
2892 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
2893 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
2896 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
2898 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, AST_PRES_NUMBER_NOT_AVAILABLE);
2901 iax_ie_append_byte(&ied, IAX_IE_CALLINGTON, c->cid.cid_ton);
2902 iax_ie_append_short(&ied, IAX_IE_CALLINGTNS, c->cid.cid_tns);
2905 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n);
2906 if (ast_test_flag(iaxs[callno], IAX_SENDANI) && c->cid.cid_ani)
2907 iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, c->cid.cid_ani);
2909 if (!ast_strlen_zero(c->language))
2910 iax_ie_append_str(&ied, IAX_IE_LANGUAGE, c->language);
2911 if (!ast_strlen_zero(c->cid.cid_dnid))
2912 iax_ie_append_str(&ied, IAX_IE_DNID, c->cid.cid_dnid);
2913 if (!ast_strlen_zero(c->cid.cid_rdnis))
2914 iax_ie_append_str(&ied, IAX_IE_RDNIS, c->cid.cid_rdnis);
2917 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, pds.context);
2920 iax_ie_append_str(&ied, IAX_IE_USERNAME, pds.username);
2923 iax_ie_append_short(&ied, IAX_IE_ENCRYPTION, cai.encmethods);
2925 ast_mutex_lock(&iaxsl[callno]);
2927 if (!ast_strlen_zero(c->context))
2928 ast_copy_string(iaxs[callno]->context, c->context, sizeof(iaxs[callno]->context));
2931 ast_copy_string(iaxs[callno]->username, pds.username, sizeof(iaxs[callno]->username));
2933 iaxs[callno]->encmethods = cai.encmethods;
2936 ast_copy_string(iaxs[callno]->outkey, pds.key, sizeof(iaxs[callno]->outkey));
2938 ast_copy_string(iaxs[callno]->secret, pds.password, sizeof(iaxs[callno]->secret));
2940 iax_ie_append_int(&ied, IAX_IE_FORMAT, c->nativeformats);
2941 iax_ie_append_int(&ied, IAX_IE_CAPABILITY, iaxs[callno]->capability);
2942 iax_ie_append_short(&ied, IAX_IE_ADSICPE, c->adsicpe);
2943 iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime(cai.timezone));
2945 if (iaxs[callno]->maxtime) {
2946 /* Initialize pingtime and auto-congest time */
2947 iaxs[callno]->pingtime = iaxs[callno]->maxtime / 2;
2948 iaxs[callno]->initid = ast_sched_add(sched, iaxs[callno]->maxtime * 2, auto_congest, CALLNO_TO_PTR(callno));
2949 } else if (autokill) {
2950 iaxs[callno]->pingtime = autokill / 2;
2951 iaxs[callno]->initid = ast_sched_add(sched, autokill * 2, auto_congest, CALLNO_TO_PTR(callno));
2954 /* Transmit the string in a "NEW" request */
2955 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
2957 ast_mutex_unlock(&iaxsl[callno]);
2958 ast_setstate(c, AST_STATE_RINGING);
2963 static int iax2_hangup(struct ast_channel *c)
2965 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
2967 struct iax_ie_data ied;
2968 memset(&ied, 0, sizeof(ied));
2969 ast_mutex_lock(&iaxsl[callno]);
2970 if (callno && iaxs[callno]) {
2971 ast_log(LOG_DEBUG, "We're hanging up %s now...\n", c->name);
2972 alreadygone = ast_test_flag(iaxs[callno], IAX_ALREADYGONE);
2973 /* Send the hangup unless we have had a transmission error or are already gone */
2974 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, (unsigned char)c->hangupcause);
2975 if (!iaxs[callno]->error && !alreadygone)
2976 send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1);
2977 /* Explicitly predestroy it */
2978 iax2_predestroy_nolock(callno);
2979 /* If we were already gone to begin with, destroy us now */
2981 ast_log(LOG_DEBUG, "Really destroying %s now...\n", c->name);
2982 iax2_destroy_nolock(callno);
2985 ast_mutex_unlock(&iaxsl[callno]);
2986 if (option_verbose > 2)
2987 ast_verbose(VERBOSE_PREFIX_3 "Hungup '%s'\n", c->name);
2991 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
2993 struct ast_option_header *h;
2997 case AST_OPTION_TXGAIN:
2998 case AST_OPTION_RXGAIN:
2999 /* these two cannot be sent, because they require a result */
3003 if (!(h = ast_malloc(datalen + sizeof(*h))))
3006 h->flag = AST_OPTION_FLAG_REQUEST;
3007 h->option = htons(option);
3008 memcpy(h->data, data, datalen);
3009 res = send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_CONTROL,
3010 AST_CONTROL_OPTION, 0, (unsigned char *) h,
3011 datalen + sizeof(*h), -1);
3017 static struct ast_frame *iax2_read(struct ast_channel *c)
3019 ast_log(LOG_NOTICE, "I should never be called!\n");
3020 return &ast_null_frame;
3023 static int iax2_start_transfer(unsigned short callno0, unsigned short callno1, int mediaonly)
3026 struct iax_ie_data ied0;
3027 struct iax_ie_data ied1;
3028 unsigned int transferid = (unsigned int)ast_random();
3029 memset(&ied0, 0, sizeof(ied0));
3030 iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &iaxs[callno1]->addr);
3031 iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[callno1]->peercallno);
3032 iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, transferid);
3034 memset(&ied1, 0, sizeof(ied1));
3035 iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &iaxs[callno0]->addr);
3036 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[callno0]->peercallno);
3037 iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, transferid);
3039 res = send_command(iaxs[callno0], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
3042 res = send_command(iaxs[callno1], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
3045 iaxs[callno0]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
3046 iaxs[callno1]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
3050 static void lock_both(unsigned short callno0, unsigned short callno1)
3052 ast_mutex_lock(&iaxsl[callno0]);
3053 while (ast_mutex_trylock(&iaxsl[callno1])) {
3054 ast_mutex_unlock(&iaxsl[callno0]);
3056 ast_mutex_lock(&iaxsl[callno0]);
3060 static void unlock_both(unsigned short callno0, unsigned short callno1)
3062 ast_mutex_unlock(&iaxsl[callno1]);
3063 ast_mutex_unlock(&iaxsl[callno0]);
3066 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)
3068 struct ast_channel *cs[3];
3069 struct ast_channel *who, *other;
3072 int transferstarted=0;
3073 struct ast_frame *f;
3074 unsigned short callno0 = PTR_TO_CALLNO(c0->tech_pvt);
3075 unsigned short callno1 = PTR_TO_CALLNO(c1->tech_pvt);
3076 struct timeval waittimer = {0, 0}, tv;
3078 lock_both(callno0, callno1);
3079 /* Put them in native bridge mode */
3080 if (!flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1)) {
3081 iaxs[callno0]->bridgecallno = callno1;
3082 iaxs[callno1]->bridgecallno = callno0;
3084 unlock_both(callno0, callno1);
3086 /* If not, try to bridge until we can execute a transfer, if we can */
3089 for (/* ever */;;) {
3090 /* Check in case we got masqueraded into */
3091 if ((c0->tech != &iax2_tech) || (c1->tech != &iax2_tech)) {
3092 if (option_verbose > 2)
3093 ast_verbose(VERBOSE_PREFIX_3 "Can't masquerade, we're different...\n");
3094 /* Remove from native mode */
3095 if (c0->tech == &iax2_tech) {
3096 ast_mutex_lock(&iaxsl[callno0]);
3097 iaxs[callno0]->bridgecallno = 0;
3098 ast_mutex_unlock(&iaxsl[callno0]);
3100 if (c1->tech == &iax2_tech) {
3101 ast_mutex_lock(&iaxsl[callno1]);
3102 iaxs[callno1]->bridgecallno = 0;
3103 ast_mutex_unlock(&iaxsl[callno1]);
3105 return AST_BRIDGE_FAILED_NOWARN;
3107 if (c0->nativeformats != c1->nativeformats) {
3108 if (option_verbose > 2) {
3111 ast_getformatname_multiple(buf0, sizeof(buf0) -1, c0->nativeformats);
3112 ast_getformatname_multiple(buf1, sizeof(buf1) -1, c1->nativeformats);
3113 ast_verbose(VERBOSE_PREFIX_3 "Operating with different codecs %d[%s] %d[%s] , can't native bridge...\n", c0->nativeformats, buf0, c1->nativeformats, buf1);
3115 /* Remove from native mode */
3116 lock_both(callno0, callno1);
3117 iaxs[callno0]->bridgecallno = 0;
3118 iaxs[callno1]->bridgecallno = 0;
3119 unlock_both(callno0, callno1);
3120 return AST_BRIDGE_FAILED_NOWARN;
3122 /* check if transfered and if we really want native bridging */
3123 if (!transferstarted && !ast_test_flag(iaxs[callno0], IAX_NOTRANSFER) && !ast_test_flag(iaxs[callno1], IAX_NOTRANSFER)) {
3124 /* Try the transfer */
3125 if (iax2_start_transfer(callno0, callno1, (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1)) ||
3126 ast_test_flag(iaxs[callno0], IAX_TRANSFERMEDIA) | ast_test_flag(iaxs[callno1], IAX_TRANSFERMEDIA)))
3127 ast_log(LOG_WARNING, "Unable to start the transfer\n");
3128 transferstarted = 1;
3130 if ((iaxs[callno0]->transferring == TRANSFER_RELEASED) && (iaxs[callno1]->transferring == TRANSFER_RELEASED)) {
3131 /* Call has been transferred. We're no longer involved */
3132 gettimeofday(&tv, NULL);
3133 if (ast_tvzero(waittimer)) {
3135 } else if (tv.tv_sec - waittimer.tv_sec > IAX_LINGER_TIMEOUT) {
3136 c0->_softhangup |= AST_SOFTHANGUP_DEV;
3137 c1->_softhangup |= AST_SOFTHANGUP_DEV;
3140 res = AST_BRIDGE_COMPLETE;
3145 who = ast_waitfor_n(cs, 2, &to);
3146 if (timeoutms > -1) {
3147 timeoutms -= (1000 - to);
3153 res = AST_BRIDGE_RETRY;
3156 if (ast_check_hangup(c0) || ast_check_hangup(c1)) {
3157 res = AST_BRIDGE_FAILED;
3166 res = AST_BRIDGE_COMPLETE;
3169 if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
3172 res = AST_BRIDGE_COMPLETE;
3175 other = (who == c0) ? c1 : c0; /* the 'other' channel */
3176 if ((f->frametype == AST_FRAME_VOICE) ||
3177 (f->frametype == AST_FRAME_TEXT) ||
3178 (f->frametype == AST_FRAME_VIDEO) ||
3179 (f->frametype == AST_FRAME_IMAGE) ||
3180 (f->frametype == AST_FRAME_DTMF)) {
3181 /* monitored dtmf take out of the bridge.
3182 * check if we monitor the specific source.
3184 int monitored_source = (who == c0) ? AST_BRIDGE_DTMF_CHANNEL_0 : AST_BRIDGE_DTMF_CHANNEL_1;
3185 if (f->frametype == AST_FRAME_DTMF && (flags & monitored_source)) {
3188 res = AST_BRIDGE_COMPLETE;
3189 /* Remove from native mode */
3192 /* everything else goes to the other side */
3193 ast_write(other, f);
3196 /* Swap who gets priority */
3201 lock_both(callno0, callno1);
3203 iaxs[callno0]->bridgecallno = 0;
3205 iaxs[callno1]->bridgecallno = 0;
3206 unlock_both(callno0, callno1);
3210 static int iax2_answer(struct ast_channel *c)
3212 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
3214 ast_log(LOG_DEBUG, "Answering IAX2 call\n");
3215 return send_command_locked(callno, AST_FRAME_CONTROL, AST_CONTROL_ANSWER, 0, NULL, 0, -1);
3218 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen)
3220 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
3221 if (option_debug && iaxdebug)
3222 ast_log(LOG_DEBUG, "Indicating condition %d\n", condition);
3223 return send_command_locked(callno, AST_FRAME_CONTROL, condition, 0, data, datalen, -1);
3226 static int iax2_transfer(struct ast_channel *c, const char *dest)
3228 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
3229 struct iax_ie_data ied;
3230 char tmp[256], *context;
3231 ast_copy_string(tmp, dest, sizeof(tmp));
3232 context = strchr(tmp, '@');
3237 memset(&ied, 0, sizeof(ied));
3238 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, tmp);
3240 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, context);
3242 ast_log(LOG_DEBUG, "Transferring '%s' to '%s'\n", c->name, dest);
3243 return send_command_locked(callno, AST_FRAME_IAX, IAX_COMMAND_TRANSFER, 0, ied.buf, ied.pos, -1);
3246 static int iax2_getpeertrunk(struct sockaddr_in sin)
3248 struct iax2_peer *peer = NULL;
3251 AST_LIST_LOCK(&peers);
3252 AST_LIST_TRAVERSE(&peers, peer, entry) {
3253 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
3254 (peer->addr.sin_port == sin.sin_port)) {
3255 res = ast_test_flag(peer, IAX_TRUNK);
3259 AST_LIST_UNLOCK(&peers);
3264 /*! \brief Create new call, interface with the PBX core */
3265 static struct ast_channel *ast_iax2_new(int callno, int state, int capability)
3267 struct ast_channel *tmp;
3268 struct chan_iax2_pvt *i;
3269 struct ast_variable *v = NULL;
3271 /* Don't hold call lock */
3272 ast_mutex_unlock(&iaxsl[callno]);
3273 tmp = ast_channel_alloc(1);
3274 ast_mutex_lock(&iaxsl[callno]);
3277 tmp->tech = &iax2_tech;
3278 ast_string_field_build(tmp, name, "IAX2/%s-%d", i->host, i->callno);
3279 /* We can support any format by default, until we get restricted */
3280 tmp->nativeformats = capability;
3281 tmp->readformat = ast_best_codec(capability);
3282 tmp->writeformat = ast_best_codec(capability);
3283 tmp->tech_pvt = CALLNO_TO_PTR(i->callno);
3285 if (!ast_strlen_zero(i->cid_num))
3286 tmp->cid.cid_num = ast_strdup(i->cid_num);
3287 if (!ast_strlen_zero(i->cid_name))
3288 tmp->cid.cid_name = ast_strdup(i->cid_name);
3289 if (!ast_strlen_zero(i->ani))
3290 tmp->cid.cid_ani = ast_strdup(i->ani);
3291 if (!ast_strlen_zero(i->language))
3292 ast_string_field_set(tmp, language, i->language);
3293 if (!ast_strlen_zero(i->dnid))
3294 tmp->cid.cid_dnid = ast_strdup(i->dnid);
3295 if (!ast_strlen_zero(i->rdnis))
3296 tmp->cid.cid_rdnis = ast_strdup(i->rdnis);
3297 tmp->cid.cid_pres = i->calling_pres;
3298 tmp->cid.cid_ton = i->calling_ton;
3299 tmp->cid.cid_tns = i->calling_tns;
3300 if (!ast_strlen_zero(i->accountcode))
3301 ast_string_field_set(tmp, accountcode, i->accountcode);
3303 tmp->amaflags = i->amaflags;
3304 ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
3305 ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
3306 tmp->adsicpe = i->peeradsicpe;
3308 i->capability = capability;
3309 ast_setstate(tmp, state);
3310 ast_mutex_lock(&usecnt_lock);
3312 ast_mutex_unlock(&usecnt_lock);
3313 ast_update_use_count();
3314 if (state != AST_STATE_DOWN) {
3315 if (ast_pbx_start(tmp)) {
3316 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
3321 for (v = i->vars ; v ; v = v->next)
3322 pbx_builtin_setvar_helper(tmp,v->name,v->value);
3328 static unsigned int calc_txpeerstamp(struct iax2_trunk_peer *tpeer, int sampms, struct timeval *tv)
3330 unsigned long int mssincetx; /* unsigned to handle overflows */
3333 tpeer->trunkact = *tv;
3334 mssincetx = ast_tvdiff_ms(*tv, tpeer->lasttxtime);
3335 if (mssincetx > 5000 || ast_tvzero(tpeer->txtrunktime)) {
3336 /* If it's been at least 5 seconds since the last time we transmitted on this trunk, reset our timers */
3337 tpeer->txtrunktime = *tv;
3338 tpeer->lastsent = 999999;
3340 /* Update last transmit time now */
3341 tpeer->lasttxtime = *tv;
3343 /* Calculate ms offset */
3344 ms = ast_tvdiff_ms(*tv, tpeer->txtrunktime);
3345 /* Predict from last value */
3346 pred = tpeer->lastsent + sampms;
3347 if (abs(ms - pred) < MAX_TIMESTAMP_SKEW)
3350 /* We never send the same timestamp twice, so fudge a little if we must */
3351 if (ms == tpeer->lastsent)
3352 ms = tpeer->lastsent + 1;
3353 tpeer->lastsent = ms;
3357 static unsigned int fix_peerts(struct timeval *tv, int callno, unsigned int ts)
3359 long ms; /* NOT unsigned */
3360 if (ast_tvzero(iaxs[callno]->rxcore)) {
3361 /* Initialize rxcore time if appropriate */
3362 gettimeofday(&iaxs[callno]->rxcore, NULL);
3363 /* Round to nearest 20ms so traces look pretty */
3364 iaxs[callno]->rxcore.tv_usec -= iaxs[callno]->rxcore.tv_usec % 20000;
3366 /* Calculate difference between trunk and channel */
3367 ms = ast_tvdiff_ms(*tv, iaxs[callno]->rxcore);
3368 /* Return as the sum of trunk time and the difference between trunk and real time */
3372 static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts, struct ast_frame *f)
3378 struct timeval *delivery = NULL;
3381 /* What sort of frame do we have?: voice is self-explanatory
3382 "genuine" means an IAX frame - things like LAGRQ/RP, PING/PONG, ACK
3383 non-genuine frames are CONTROL frames [ringing etc], DTMF
3384 The "genuine" distinction is needed because genuine frames must get a clock-based timestamp,
3385 the others need a timestamp slaved to the voice frames so that they go in sequence
3388 if (f->frametype == AST_FRAME_VOICE) {
3390 delivery = &f->delivery;
3391 } else if (f->frametype == AST_FRAME_IAX) {
3393 } else if (f->frametype == AST_FRAME_CNG) {
3397 if (ast_tvzero(p->offset)) {
3398 gettimeofday(&p->offset, NULL);
3399 /* Round to nearest 20ms for nice looking traces */
3400 p->offset.tv_usec -= p->offset.tv_usec % 20000;
3402 /* If the timestamp is specified, just send it as is */
3405 /* If we have a time that the frame arrived, always use it to make our timestamp */
3406 if (delivery && !ast_tvzero(*delivery)) {
3407 ms = ast_tvdiff_ms(*delivery, p->offset);
3408 if (option_debug > 2 && iaxdebug)
3409 ast_log(LOG_DEBUG, "calc_timestamp: call %d/%d: Timestamp slaved to delivery time\n", p->callno, iaxs[p->callno]->peercallno);
3411 ms = ast_tvdiff_ms(ast_tvnow(), p->offset);
3415 /* On a voice frame, use predicted values if appropriate */
3416 if (p->notsilenttx && abs(ms - p->nextpred) <= MAX_TIMESTAMP_SKEW) {
3417 /* Adjust our txcore, keeping voice and non-voice synchronized */
3419 When we send voice, we usually send "calculated" timestamps worked out
3420 on the basis of the number of samples sent. When we send other frames,
3421 we usually send timestamps worked out from the real clock.
3422 The problem is that they can tend to drift out of step because the
3423 source channel's clock and our clock may not be exactly at the same rate.
3424 We fix this by continuously "tweaking" p->offset. p->offset is "time zero"
3425 for this call. Moving it adjusts timestamps for non-voice frames.
3426 We make the adjustment in the style of a moving average. Each time we
3427 adjust p->offset by 10% of the difference between our clock-derived
3428 timestamp and the predicted timestamp. That's why you see "10000"
3429 below even though IAX2 timestamps are in milliseconds.
3430 The use of a moving average avoids offset moving too radically.
3431 Generally, "adjust" roams back and forth around 0, with offset hardly
3432 changing at all. But if a consistent different starts to develop it
3433 will be eliminated over the course of 10 frames (200-300msecs)
3435 adjust = (ms - p->nextpred);
3437 p->offset = ast_tvsub(p->offset, ast_samp2tv(abs(adjust), 10000));
3438 else if (adjust > 0)
3439 p->offset = ast_tvadd(p->offset, ast_samp2tv(adjust, 10000));
3442 p->nextpred = ms; /*f->samples / 8;*/
3443 if (p->nextpred <= p->lastsent)
3444 p->nextpred = p->lastsent + 3;
3448 /* in this case, just use the actual
3449 * time, since we're either way off
3450 * (shouldn't happen), or we're ending a
3451 * silent period -- and seed the next
3452 * predicted time. Also, round ms to the
3453 * next multiple of frame size (so our
3454 * silent periods are multiples of
3455 * frame size too) */
3457 if (iaxdebug && abs(ms - p->nextpred) > MAX_TIMESTAMP_SKEW )
3458 ast_log(LOG_DEBUG, "predicted timestamp skew (%u) > max (%u), using real ts instead.\n",
3459 abs(ms - p->nextpred), MAX_TIMESTAMP_SKEW);
3461 if (f->samples >= 8) /* check to make sure we dont core dump */
3463 int diff = ms % (f->samples / 8);
3465 ms += f->samples/8 - diff;
3472 /* On a dataframe, use last value + 3 (to accomodate jitter buffer shrinking) if appropriate unless
3473 it's a genuine frame */
3475 /* genuine (IAX LAGRQ etc) must keep their clock-based stamps */
3476 if (ms <= p->lastsent)
3477 ms = p->lastsent + 3;
3478 } else if (abs(ms - p->lastsent) <= MAX_TIMESTAMP_SKEW) {
3479 /* non-genuine frames (!?) (DTMF, CONTROL) should be pulled into the predicted stream stamps */
3480 ms = p->lastsent + 3;
3486 p->nextpred = p->nextpred + f->samples / 8;
3488 printf("TS: %s - %dms\n", voice ? "Audio" : "Control", ms);
3493 #ifdef BRIDGE_OPTIMIZATION
3494 static unsigned int calc_fakestamp(struct chan_iax2_pvt *p1, struct chan_iax2_pvt *p2, unsigned int fakets)
3497 /* Receive from p1, send to p2 */
3499 /* Setup rxcore if necessary on outgoing channel */
3500 if (ast_tvzero(p1->rxcore))
3501 p1->rxcore = ast_tvnow();
3503 /* Setup txcore if necessary on outgoing channel */
3504 if (ast_tvzero(p2->offset))
3505 p2->offset = ast_tvnow();
3507 /* Now, ts is the timestamp of the original packet in the orignal context.
3508 Adding rxcore to it gives us when we would want the packet to be delivered normally.
3509 Subtracting txcore of the outgoing channel gives us what we'd expect */
3511 ms = ast_tvdiff_ms(p1->rxcore, p2->offset);
3514 p2->lastsent = fakets;
3519 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset)
3521 /* Returns where in "receive time" we are. That is, how many ms
3522 since we received (or would have received) the frame with timestamp 0 */
3526 #endif /* IAXTESTS */
3527 /* Setup rxcore if necessary */
3528 if (ast_tvzero(p->rxcore)) {
3529 p->rxcore = ast_tvnow();
3530 if (option_debug && iaxdebug)
3531 ast_log(LOG_DEBUG, "calc_rxstamp: call=%d: rxcore set to %d.%6.6d - %dms\n",
3532 p->callno, (int)(p->rxcore.tv_sec), (int)(p->rxcore.tv_usec), offset);
3533 p->rxcore = ast_tvsub(p->rxcore, ast_samp2tv(offset, 1000));
3535 if (option_debug && iaxdebug)
3536 ast_log(LOG_DEBUG, "calc_rxstamp: call=%d: works out as %d.%6.6d\n",
3537 p->callno, (int)(p->rxcore.tv_sec),(int)( p->rxcore.tv_usec));
3541 ms = ast_tvdiff_ms(ast_tvnow(), p->rxcore);
3544 if (!test_jitpct || ((100.0 * ast_random() / (RAND_MAX + 1.0)) < test_jitpct)) {
3545 jit = (int)((float)test_jit * ast_random() / (RAND_MAX + 1.0));
3546 if ((int)(2.0 * ast_random() / (RAND_MAX + 1.0)))
3555 #endif /* IAXTESTS */
3559 static struct iax2_trunk_peer *find_tpeer(struct sockaddr_in *sin, int fd)
3561 struct iax2_trunk_peer *tpeer;
3562 char iabuf[INET_ADDRSTRLEN];
3563 /* Finds and locks trunk peer */
3564 ast_mutex_lock(&tpeerlock);
3567 /* We don't lock here because tpeer->addr *never* changes */
3568 if (!inaddrcmp(&tpeer->addr, sin)) {
3569 ast_mutex_lock(&tpeer->lock);
3572 tpeer = tpeer->next;
3575 if ((tpeer = ast_calloc(1, sizeof(*tpeer)))) {
3576 ast_mutex_init(&tpeer->lock);
3577 tpeer->lastsent = 9999;
3578 memcpy(&tpeer->addr, sin, sizeof(tpeer->addr));
3579 tpeer->trunkact = ast_tvnow();
3580 ast_mutex_lock(&tpeer->lock);
3581 tpeer->next = tpeers;
3585 setsockopt(tpeer->sockfd, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
3587 ast_log(LOG_DEBUG, "Created trunk peer for '%s:%d'\n", ast_inet_ntoa(iabuf, sizeof(iabuf), tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port));
3590 ast_mutex_unlock(&tpeerlock);
3594 static int iax2_trunk_queue(struct chan_iax2_pvt *pvt, struct iax_frame *fr)
3596 struct ast_frame *f;
3597 struct iax2_trunk_peer *tpeer;
3599 struct ast_iax2_meta_trunk_entry *met;
3600 struct ast_iax2_meta_trunk_mini *mtm;