2 * Asterisk -- A telephony toolkit for Linux.
4 * Implementation of Inter-Asterisk eXchange Version 2
6 * Copyright (C) 2003 - 2005, Digium, Inc.
8 * Mark Spencer <markster@digium.com>
10 * This program is free software, distributed under the terms of
11 * the GNU General Public License
14 #include <asterisk/lock.h>
15 #include <asterisk/frame.h>
16 #include <asterisk/channel.h>
17 #include <asterisk/channel_pvt.h>
18 #include <asterisk/logger.h>
19 #include <asterisk/module.h>
20 #include <asterisk/pbx.h>
21 #include <asterisk/sched.h>
22 #include <asterisk/io.h>
23 #include <asterisk/config.h>
24 #include <asterisk/options.h>
25 #include <asterisk/cli.h>
26 #include <asterisk/translate.h>
27 #include <asterisk/md5.h>
28 #include <asterisk/cdr.h>
29 #include <asterisk/crypto.h>
30 #include <asterisk/acl.h>
31 #include <asterisk/manager.h>
32 #include <asterisk/callerid.h>
33 #include <asterisk/app.h>
34 #include <asterisk/astdb.h>
35 #include <asterisk/musiconhold.h>
36 #include <asterisk/features.h>
37 #include <asterisk/utils.h>
38 #include <asterisk/causes.h>
39 #include <asterisk/localtime.h>
40 #include <asterisk/aes.h>
42 #include <arpa/inet.h>
44 #include <sys/socket.h>
45 #include <netinet/in.h>
46 #include <netinet/in_systm.h>
47 #include <netinet/ip.h>
49 #include <sys/signal.h>
58 #include <sys/types.h>
62 #include <sys/ioctl.h>
64 #include <linux/zaptel.h>
67 #endif /* __linux__ */
70 #include "iax2-parser.h"
71 #include "iax2-provision.h"
72 #include "../astconf.h"
75 #define IPTOS_MINCOST 0x02
79 * Uncomment to try experimental IAX bridge optimization,
80 * designed to reduce latency when IAX calls cannot
84 #define BRIDGE_OPTIMIZATION
86 #define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
87 #define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
89 #define DEFAULT_RETRY_TIME 1000
90 #define MEMORY_SIZE 100
91 #define DEFAULT_DROP 3
92 /* Flag to use with trunk calls, keeping these calls high up. It halves our effective use
93 but keeps the division between trunked and non-trunked better. */
94 #define TRUNK_CALL_START 0x4000
98 #define MIN_REUSE_TIME 60 /* Don't reuse a call number within 60 seconds */
100 /* Sample over last 100 units to determine historic jitter */
103 static struct ast_codec_pref prefs;
105 static char *desc = "Inter Asterisk eXchange (Ver 2)";
106 static char *tdesc = "Inter Asterisk eXchange Driver (Ver 2)";
107 static char *channeltype = "IAX2";
109 static char context[80] = "default";
111 static char language[MAX_LANGUAGE] = "";
112 static char regcontext[AST_MAX_EXTENSION] = "";
114 static int max_retries = 4;
115 static int ping_time = 20;
116 static int lagrq_time = 10;
117 static int maxtrunkcall = TRUNK_CALL_START;
118 static int maxnontrunkcall = 1;
119 static int maxjitterbuffer=1000;
120 static int jittershrinkrate=2;
121 static int trunkfreq = 20;
122 static int authdebug = 1;
123 static int autokill = 0;
124 static int iaxcompat = 0;
126 static int iaxdefaultdpcache=10 * 60; /* Cache dialplan entries for 10 minutes by default */
128 static int iaxdefaulttimeout = 5; /* Default to wait no more than 5 seconds for a reply to come back */
132 static int expirey = IAX_DEFAULT_REG_EXPIRE;
134 static int timingfd = -1; /* Timing file descriptor */
136 static struct ast_netsock_list netsock;
137 static int defaultsockfd = -1;
140 AST_MUTEX_DEFINE_STATIC(usecnt_lock);
142 int (*iax2_regfunk)(char *username, int onoff) = NULL;
145 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
147 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
148 ~AST_FORMAT_SLINEAR & \
152 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
156 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
160 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
161 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
162 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
164 static struct io_context *io;
165 static struct sched_context *sched;
167 static int iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
169 static int iax2_dropcount = DEFAULT_DROP;
171 static int iaxdebug = 0;
173 static int iaxtrunkdebug = 0;
175 static char accountcode[20];
176 static int amaflags = 0;
177 static int delayreject = 0;
178 static int iax2_encryption = 0;
180 static struct ast_flags globalflags = {0};
182 static pthread_t netthreadid = AST_PTHREADT_NULL;
184 #define IAX_STATE_STARTED (1 << 0)
185 #define IAX_STATE_AUTHENTICATED (1 << 1)
186 #define IAX_STATE_TBD (1 << 2)
188 struct iax2_context {
189 char context[AST_MAX_EXTENSION];
190 struct iax2_context *next;
193 #define IAX_HASCALLERID (1 << 0) /* CallerID has been specified */
194 #define IAX_DELME (1 << 1) /* Needs to be deleted */
195 #define IAX_TEMPONLY (1 << 2) /* Temporary (realtime) */
196 #define IAX_TRUNK (1 << 3) /* Treat as a trunk */
197 #define IAX_NOTRANSFER (1 << 4) /* Don't native bridge */
198 #define IAX_USEJITTERBUF (1 << 5) /* Use jitter buffer */
199 #define IAX_DYNAMIC (1 << 6) /* dynamic peer */
200 #define IAX_SENDANI (1 << 7) /* Send ANI along with CallerID */
201 #define IAX_MESSAGEDETAIL (1 << 8) /* Show exact numbers */
202 #define IAX_ALREADYGONE (1 << 9) /* Already disconnected */
203 #define IAX_PROVISION (1 << 10) /* This is a provisioning request */
204 #define IAX_QUELCH (1 << 11) /* Whether or not we quelch audio */
205 #define IAX_ENCRYPTED (1 << 12) /* Whether we should assume encrypted tx/rx */
206 #define IAX_KEYPOPULATED (1 << 13) /* Whether we have a key populated */
207 #define IAX_CODEC_USER_FIRST (1 << 14) /* are we willing to let the other guy choose the codec? */
208 #define IAX_CODEC_NOPREFS (1 << 15) /* Force old behaviour by turning off prefs */
209 #define IAX_CODEC_NOCAP (1 << 16) /* only consider requested format and ignore capabilities*/
210 #define IAX_RTCACHEFRIENDS (1 << 17) /* let realtime stay till your reload */
211 #define IAX_RTNOUPDATE (1 << 18) /* Don't send a realtime update */
212 #define IAX_RTAUTOCLEAR (1 << 19) /* erase me on expire */
214 static int global_rtautoclear = 120;
216 static struct iax2_peer *realtime_peer(const char *peername);
217 static int reload_config(void);
225 char accountcode[20];
226 char inkeys[80]; /* Key(s) this user can use to authenticate to us */
227 char language[MAX_LANGUAGE];
231 char cid_num[AST_MAX_EXTENSION];
232 char cid_name[AST_MAX_EXTENSION];
233 struct ast_codec_pref prefs;
235 struct iax2_context *contexts;
236 struct iax2_user *next;
237 struct ast_variable *vars;
245 char outkey[80]; /* What key we use to talk to this peer */
246 char context[AST_MAX_EXTENSION]; /* For transfers only */
247 char regexten[AST_MAX_EXTENSION]; /* Extension to register (if regcontext is used) */
248 char peercontext[AST_MAX_EXTENSION]; /* Context to pass to peer */
249 char mailbox[AST_MAX_EXTENSION]; /* Mailbox */
250 struct ast_codec_pref prefs;
251 struct sockaddr_in addr;
253 int sockfd; /* Socket to use for transmission */
257 /* Dynamic Registration fields */
258 struct sockaddr_in defaddr; /* Default address if there is one */
259 int authmethods; /* Authentication methods (IAX_AUTH_*) */
260 int encmethods; /* Encryption methods (IAX_ENCRYPT_*) */
261 char inkeys[80]; /* Key(s) this peer can use to authenticate to us */
263 /* Suggested caller id if registering */
264 char cid_num[AST_MAX_EXTENSION]; /* Default context (for transfer really) */
265 char cid_name[AST_MAX_EXTENSION]; /* Default context (for transfer really) */
267 int expire; /* Schedule entry for expirey */
268 int expirey; /* How soon to expire */
269 int capability; /* Capability */
270 char zonetag[80]; /* Time Zone */
273 int callno; /* Call number of POKE request */
274 int pokeexpire; /* When to expire poke */
275 int lastms; /* How long last response took (in ms), or -1 for no response */
276 int maxms; /* Max ms we will accept for the host to be up, 0 to not monitor */
279 struct iax2_peer *next;
282 #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
284 static struct iax2_trunk_peer {
287 struct sockaddr_in addr;
288 struct timeval txtrunktime; /* Transmit trunktime */
289 struct timeval rxtrunktime; /* Receive trunktime */
290 struct timeval lasttxtime; /* Last transmitted trunktime */
291 struct timeval trunkact; /* Last trunk activity */
292 unsigned int lastsent; /* Last sent time */
293 /* Trunk data and length */
294 unsigned char *trunkdata;
295 unsigned int trunkdatalen;
296 unsigned int trunkdataalloc;
297 struct iax2_trunk_peer *next;
302 AST_MUTEX_DEFINE_STATIC(tpeerlock);
304 struct iax_firmware {
305 struct iax_firmware *next;
309 struct ast_iax2_firmware_header *fwh;
313 #define REG_STATE_UNREGISTERED 0
314 #define REG_STATE_REGSENT 1
315 #define REG_STATE_AUTHSENT 2
316 #define REG_STATE_REGISTERED 3
317 #define REG_STATE_REJECTED 4
318 #define REG_STATE_TIMEOUT 5
319 #define REG_STATE_NOAUTH 6
321 #define TRANSFER_NONE 0
322 #define TRANSFER_BEGIN 1
323 #define TRANSFER_READY 2
324 #define TRANSFER_RELEASED 3
325 #define TRANSFER_PASSTHROUGH 4
327 struct iax2_registry {
328 struct sockaddr_in addr; /* Who we connect to for registration purposes */
330 char secret[80]; /* Password or key name in []'s */
332 int expire; /* Sched ID of expiration */
333 int refresh; /* How often to refresh */
335 int messages; /* Message count */
336 int callno; /* Associated call number if applicable */
337 struct sockaddr_in us; /* Who the server thinks we are */
338 struct iax2_registry *next;
341 static struct iax2_registry *registrations;
343 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
344 #define MIN_RETRY_TIME 100
345 #define MAX_RETRY_TIME 10000
347 #define MAX_JITTER_BUFFER 50
348 #define MIN_JITTER_BUFFER 10
350 #define DEFAULT_TRUNKDATA 640 * 10 /* 40ms, uncompressed linear * 10 channels */
351 #define MAX_TRUNKDATA 640 * 200 /* 40ms, uncompressed linear * 200 channels */
353 #define MAX_TIMESTAMP_SKEW 640
355 /* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
356 #define TS_GAP_FOR_JB_RESYNC 5000
358 /* If we have more than this much excess real jitter buffer, shrink it. */
359 static int max_jitter_buffer = MAX_JITTER_BUFFER;
360 /* If we have less than this much excess real jitter buffer, enlarge it. */
361 static int min_jitter_buffer = MIN_JITTER_BUFFER;
373 struct chan_iax2_pvt {
374 /* Socket to send/receive on for this call */
376 /* Last received voice format */
378 /* Last received voice format */
380 /* Last sent voice format */
382 /* Last sent video format */
384 /* What we are capable of sending */
386 /* Last received timestamp */
388 /* Last sent timestamp - never send the same timestamp twice in a single call */
389 unsigned int lastsent;
390 /* Next outgoing timestamp if everything is good */
391 unsigned int nextpred;
392 /* True if the last voice we transmitted was not silence/CNG */
395 unsigned int pingtime;
396 /* Max time for initial response */
399 struct sockaddr_in addr;
400 struct ast_codec_pref prefs;
401 /* Our call number */
402 unsigned short callno;
404 unsigned short peercallno;
405 /* Peer selected format */
407 /* Peer capability */
409 /* timeval that we base our transmission on */
410 struct timeval offset;
411 /* timeval that we base our delivery on */
412 struct timeval rxcore;
413 /* Historical delivery time */
414 int history[MEMORY_SIZE];
415 /* Current base jitterbuffer */
417 /* Current jitter measure */
419 /* Historic jitter value */
423 /* Error, as discovered by the manager */
425 /* Owner if we have one */
426 struct ast_channel *owner;
427 /* What's our state? */
429 /* Expirey (optional) */
431 /* Next outgoing sequence number */
432 unsigned char oseqno;
433 /* Next sequence number they have not yet acknowledged */
434 unsigned char rseqno;
435 /* Next incoming sequence number */
436 unsigned char iseqno;
437 /* Last incoming sequence number we have acknowledged */
438 unsigned char aseqno;
441 /* Default Context */
443 /* Caller ID if available */
446 /* Hidden Caller ID (i.e. ANI) if appropriate */
450 /* Requested Extension */
451 char exten[AST_MAX_EXTENSION];
452 /* Expected Username */
454 /* Expected Secret */
456 /* permitted authentication methods */
458 /* permitted encryption methods */
462 /* Public keys permitted keys for incoming authentication */
464 /* Private key for outgoing authentication */
466 /* Encryption AES-128 Key */
468 /* Decryption AES-128 Key */
470 /* 32 bytes of semi-random data */
472 /* Preferred language */
473 char language[MAX_LANGUAGE];
474 /* Hostname/peername for naming purposes */
476 /* Associated registry */
477 struct iax2_registry *reg;
478 /* Associated peer for poking */
479 struct iax2_peer *peerpoke;
483 /* Transferring status */
485 /* Transfer identifier */
487 /* Who we are IAX transfering to */
488 struct sockaddr_in transfer;
489 /* What's the new call number for the transfer */
490 unsigned short transfercallno;
491 /* Transfer decrypt AES-128 Key */
492 aes_encrypt_ctx tdcx;
494 /* Status of knowledge of peer ADSI capability */
497 /* Who we are bridged to */
498 unsigned short bridgecallno;
499 unsigned int bridgesfmt;
500 struct ast_trans_pvt *bridgetrans;
502 int pingid; /* Transmit PING request */
503 int lagid; /* Retransmit lag request */
504 int autoid; /* Auto hangup for Dialplan requestor */
505 int authid; /* Authentication rejection ID */
506 int authfail; /* Reason to report failure */
507 int initid; /* Initial peer auto-congest ID (based on qualified peers) */
511 char dproot[AST_MAX_EXTENSION];
512 char accountcode[20];
514 struct iax2_dpcache *dpentries;
515 struct ast_variable *vars;
516 /* last received remote rr */
517 struct iax_rr remote_rr;
518 /* Current base time: (just for stats) */
520 /* Dropped frame count: (just for stats) */
522 /* received frame count: (just for stats) */
526 static struct ast_iax2_queue {
527 struct iax_frame *head;
528 struct iax_frame *tail;
533 static struct ast_user_list {
534 struct iax2_user *users;
538 static struct ast_peer_list {
539 struct iax2_peer *peers;
543 static struct ast_firmware_list {
544 struct iax_firmware *wares;
548 /* Extension exists */
549 #define CACHE_FLAG_EXISTS (1 << 0)
550 /* Extension is non-existant */
551 #define CACHE_FLAG_NONEXISTANT (1 << 1)
552 /* Extension can exist */
553 #define CACHE_FLAG_CANEXIST (1 << 2)
554 /* Waiting to hear back response */
555 #define CACHE_FLAG_PENDING (1 << 3)
557 #define CACHE_FLAG_TIMEOUT (1 << 4)
558 /* Request transmitted */
559 #define CACHE_FLAG_TRANSMITTED (1 << 5)
561 #define CACHE_FLAG_UNKNOWN (1 << 6)
563 #define CACHE_FLAG_MATCHMORE (1 << 7)
565 static struct iax2_dpcache {
566 char peercontext[AST_MAX_EXTENSION];
567 char exten[AST_MAX_EXTENSION];
569 struct timeval expirey;
571 unsigned short callno;
573 struct iax2_dpcache *next;
574 struct iax2_dpcache *peer; /* For linking in peers */
577 AST_MUTEX_DEFINE_STATIC(dpcache_lock);
579 static void destroy_peer(struct iax2_peer *peer);
581 static void iax_debug_output(const char *data)
584 ast_verbose("%s", data);
587 static void iax_error_output(const char *data)
589 ast_log(LOG_WARNING, "%s", data);
592 /* XXX We probably should use a mutex when working with this XXX */
593 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS];
594 static ast_mutex_t iaxsl[IAX_MAX_CALLS];
595 static struct timeval lastused[IAX_MAX_CALLS];
598 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, char *, int, int);
599 static int send_command_locked(unsigned short callno, char, int, unsigned int, char *, int, int);
600 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, char *, int, int);
601 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, char *, int, int);
602 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, char *, int);
603 static struct iax2_user *build_user(const char *name, struct ast_variable *v, int temponly);
604 static void destroy_user(struct iax2_user *user);
605 static int expire_registry(void *data);
606 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
607 static int iax2_do_register(struct iax2_registry *reg);
608 static void prune_peers(void);
609 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
610 static int iax2_provision(struct sockaddr_in *end, char *dest, const char *template, int force);
613 static int send_ping(void *data)
615 int callno = (long)data;
616 /* Ping only if it's real, not if it's bridged */
618 #ifdef BRIDGE_OPTIMIZATION
619 if (!iaxs[callno]->bridgecallno)
621 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
627 static int get_encrypt_methods(const char *s)
630 if (!strcasecmp(s, "aes128"))
631 e = IAX_ENCRYPT_AES128;
632 else if (ast_true(s))
633 e = IAX_ENCRYPT_AES128;
639 static int send_lagrq(void *data)
641 int callno = (long)data;
642 /* Ping only if it's real not if it's bridged */
644 #ifdef BRIDGE_OPTIMIZATION
645 if (!iaxs[callno]->bridgecallno)
647 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
653 static unsigned char compress_subclass(int subclass)
657 /* If it's 128 or smaller, just return it */
658 if (subclass < IAX_FLAG_SC_LOG)
660 /* Otherwise find its power */
661 for (x = 0; x < IAX_MAX_SHIFT; x++) {
662 if (subclass & (1 << x)) {
664 ast_log(LOG_WARNING, "Can't compress subclass %d\n", subclass);
670 return power | IAX_FLAG_SC_LOG;
673 static int uncompress_subclass(unsigned char csub)
675 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
676 if (csub & IAX_FLAG_SC_LOG) {
677 /* special case for 'compressed' -1 */
681 return 1 << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
687 static struct iax2_peer *find_peer(const char *name, int realtime)
689 struct iax2_peer *peer;
690 ast_mutex_lock(&peerl.lock);
691 for(peer = peerl.peers; peer; peer = peer->next) {
692 if (!strcasecmp(peer->name, name)) {
696 ast_mutex_unlock(&peerl.lock);
697 if(!peer && realtime)
698 peer = realtime_peer(name);
702 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len, int lockpeer)
704 struct iax2_peer *peer;
707 ast_mutex_lock(&peerl.lock);
710 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
711 (peer->addr.sin_port == sin.sin_port)) {
712 strncpy(host, peer->name, len-1);
719 ast_mutex_unlock(&peerl.lock);
723 static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, int lockpeer, const char *host)
725 struct chan_iax2_pvt *tmp;
726 tmp = malloc(sizeof(struct chan_iax2_pvt));
728 memset(tmp, 0, sizeof(struct chan_iax2_pvt));
732 tmp->transfercallno = 0;
733 tmp->bridgecallno = 0;
739 /* strncpy(tmp->context, context, sizeof(tmp->context)-1); */
740 strncpy(tmp->exten, "s", sizeof(tmp->exten)-1);
741 strncpy(tmp->host, host, sizeof(tmp->host)-1);
746 static int get_samples(struct ast_frame *f)
749 switch(f->subclass) {
750 case AST_FORMAT_SPEEX:
751 samples = 160; /* XXX Not necessarily true XXX */
753 case AST_FORMAT_G723_1:
754 samples = 240 /* XXX Not necessarily true XXX */;
756 case AST_FORMAT_ILBC:
757 samples = 240 * (f->datalen / 50);
760 samples = 160 * (f->datalen / 33);
762 case AST_FORMAT_G729A:
763 samples = 160 * (f->datalen / 20);
765 case AST_FORMAT_SLINEAR:
766 samples = f->datalen / 2;
768 case AST_FORMAT_LPC10:
770 samples += (((char *)(f->data))[7] & 0x1) * 8;
772 case AST_FORMAT_ULAW:
773 samples = f->datalen;
775 case AST_FORMAT_ALAW:
776 samples = f->datalen;
778 case AST_FORMAT_ADPCM:
779 case AST_FORMAT_G726:
780 samples = f->datalen *2;
783 ast_log(LOG_WARNING, "Don't know how to calculate samples on %d packets\n", f->subclass);
788 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
790 /* Malloc() a copy of a frame */
791 struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen);
793 memcpy(new, fr, sizeof(struct iax_frame));
794 iax_frame_wrap(new, &fr->af);
797 new->direction = DIRECTION_INGRESS;
803 #define NEW_PREVENT 0
807 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, struct chan_iax2_pvt *cur)
809 if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
810 (cur->addr.sin_port == sin->sin_port)) {
811 /* This is the main host */
812 if ((cur->peercallno == callno) ||
813 ((dcallno == cur->callno) && !cur->peercallno)) {
814 /* That's us. Be sure we keep track of the peer call number */
818 if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
819 (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
820 /* We're transferring */
821 if (dcallno == cur->callno)
827 static void update_max_trunk(void)
829 int max = TRUNK_CALL_START;
831 /* XXX Prolly don't need locks here XXX */
832 for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
838 ast_log(LOG_DEBUG, "New max trunk callno is %d\n", max);
841 static void update_max_nontrunk(void)
845 /* XXX Prolly don't need locks here XXX */
846 for (x=1;x<TRUNK_CALL_START - 1; x++) {
850 maxnontrunkcall = max;
852 ast_log(LOG_DEBUG, "New max nontrunk callno is %d\n", max);
855 static int make_trunk(unsigned short callno, int locked)
860 if (iaxs[callno]->oseqno) {
861 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
864 if (callno & TRUNK_CALL_START) {
865 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
868 gettimeofday(&now, NULL);
869 for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
870 ast_mutex_lock(&iaxsl[x]);
871 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) {
872 iaxs[x] = iaxs[callno];
875 /* Update the two timers that should have been started */
876 if (iaxs[x]->pingid > -1)
877 ast_sched_del(sched, iaxs[x]->pingid);
878 if (iaxs[x]->lagid > -1)
879 ast_sched_del(sched, iaxs[x]->lagid);
880 iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
881 iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
883 ast_mutex_unlock(&iaxsl[callno]);
886 ast_mutex_unlock(&iaxsl[x]);
889 ast_mutex_unlock(&iaxsl[x]);
891 if (x >= IAX_MAX_CALLS - 1) {
892 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
895 ast_log(LOG_DEBUG, "Made call %d into trunk call %d\n", callno, x);
896 /* We move this call from a non-trunked to a trunked call */
898 update_max_nontrunk();
902 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int lockpeer, int sockfd)
907 char iabuf[INET_ADDRSTRLEN];
909 if (new <= NEW_ALLOW) {
910 /* Look for an existing connection first */
911 for (x=1;(res < 1) && (x<maxnontrunkcall);x++) {
912 ast_mutex_lock(&iaxsl[x]);
914 /* Look for an exact match */
915 if (match(sin, callno, dcallno, iaxs[x])) {
919 ast_mutex_unlock(&iaxsl[x]);
921 for (x=TRUNK_CALL_START;(res < 1) && (x<maxtrunkcall);x++) {
922 ast_mutex_lock(&iaxsl[x]);
924 /* Look for an exact match */
925 if (match(sin, callno, dcallno, iaxs[x])) {
929 ast_mutex_unlock(&iaxsl[x]);
932 if ((res < 1) && (new >= NEW_ALLOW)) {
933 if (!iax2_getpeername(*sin, host, sizeof(host), lockpeer))
934 snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr), ntohs(sin->sin_port));
935 gettimeofday(&now, NULL);
936 for (x=1;x<TRUNK_CALL_START;x++) {
937 /* Find first unused call number that hasn't been used in a while */
938 ast_mutex_lock(&iaxsl[x]);
939 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) break;
940 ast_mutex_unlock(&iaxsl[x]);
942 /* We've still got lock held if we found a spot */
943 if (x >= TRUNK_CALL_START) {
944 ast_log(LOG_WARNING, "No more space\n");
947 iaxs[x] = new_iax(sin, lockpeer, host);
948 update_max_nontrunk();
951 ast_log(LOG_DEBUG, "Creating new call structure %d\n", x);
952 iaxs[x]->sockfd = sockfd;
953 iaxs[x]->addr.sin_port = sin->sin_port;
954 iaxs[x]->addr.sin_family = sin->sin_family;
955 iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
956 iaxs[x]->peercallno = callno;
958 iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
959 iaxs[x]->expirey = expirey;
960 iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
961 iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
962 iaxs[x]->amaflags = amaflags;
963 ast_copy_flags(iaxs[x], (&globalflags), IAX_NOTRANSFER | IAX_USEJITTERBUF);
964 strncpy(iaxs[x]->accountcode, accountcode, sizeof(iaxs[x]->accountcode)-1);
966 ast_log(LOG_WARNING, "Out of resources\n");
967 ast_mutex_unlock(&iaxsl[x]);
970 ast_mutex_unlock(&iaxsl[x]);
976 static void iax2_frame_free(struct iax_frame *fr)
978 if (fr->retrans > -1)
979 ast_sched_del(sched, fr->retrans);
983 static int iax2_queue_frame(int callno, struct ast_frame *f)
985 /* Assumes lock for callno is already held... */
987 if (iaxs[callno] && iaxs[callno]->owner) {
988 if (ast_mutex_trylock(&iaxs[callno]->owner->lock)) {
989 /* Avoid deadlock by pausing and trying again */
990 ast_mutex_unlock(&iaxsl[callno]);
992 ast_mutex_lock(&iaxsl[callno]);
994 ast_queue_frame(iaxs[callno]->owner, f);
995 ast_mutex_unlock(&iaxs[callno]->owner->lock);
1004 static void destroy_firmware(struct iax_firmware *cur)
1006 /* Close firmware */
1008 munmap(cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh)));
1014 static int try_firmware(char *s)
1017 struct iax_firmware *cur;
1022 struct ast_iax2_firmware_header *fwh, fwh2;
1023 struct MD5Context md5;
1024 unsigned char sum[16];
1025 unsigned char buf[1024];
1029 s2 = alloca(strlen(s) + 100);
1031 ast_log(LOG_WARNING, "Alloca failed!\n");
1034 last = strrchr(s, '/');
1039 snprintf(s2, strlen(s) + 100, "/var/tmp/%s-%ld", last, (unsigned long)rand());
1040 res = stat(s, &stbuf);
1042 ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno));
1045 /* Make sure it's not a directory */
1046 if (S_ISDIR(stbuf.st_mode))
1048 ifd = open(s, O_RDONLY);
1050 ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
1053 fd = open(s2, O_RDWR | O_CREAT | O_EXCL);
1055 ast_log(LOG_WARNING, "Cannot open '%s' for writing: %s\n", s2, strerror(errno));
1059 /* Unlink our newly created file */
1062 /* Now copy the firmware into it */
1063 len = stbuf.st_size;
1066 if (chunk > sizeof(buf))
1067 chunk = sizeof(buf);
1068 res = read(ifd, buf, chunk);
1070 ast_log(LOG_WARNING, "Only read %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1075 res = write(fd, buf, chunk);
1077 ast_log(LOG_WARNING, "Only write %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1085 /* Return to the beginning */
1086 lseek(fd, 0, SEEK_SET);
1087 if ((res = read(fd, &fwh2, sizeof(fwh2))) != sizeof(fwh2)) {
1088 ast_log(LOG_WARNING, "Unable to read firmware header in '%s'\n", s);
1092 if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) {
1093 ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s);
1097 if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) {
1098 ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s);
1102 if (fwh2.devname[sizeof(fwh2.devname) - 1] || ast_strlen_zero(fwh2.devname)) {
1103 ast_log(LOG_WARNING, "No or invalid device type specified for '%s'\n", s);
1107 fwh = mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
1109 ast_log(LOG_WARNING, "mmap failed: %s\n", strerror(errno));
1114 MD5Update(&md5, fwh->data, ntohl(fwh->datalen));
1115 MD5Final(sum, &md5);
1116 if (memcmp(sum, fwh->chksum, sizeof(sum))) {
1117 ast_log(LOG_WARNING, "Firmware file '%s' fails checksum\n", s);
1118 munmap(fwh, stbuf.st_size);
1124 if (!strcmp(cur->fwh->devname, fwh->devname)) {
1125 /* Found a candidate */
1126 if (cur->dead || (ntohs(cur->fwh->version) < ntohs(fwh->version)))
1127 /* The version we have on loaded is older, load this one instead */
1129 /* This version is no newer than what we have. Don't worry about it.
1130 We'll consider it a proper load anyhow though */
1131 munmap(fwh, stbuf.st_size);
1138 /* Allocate a new one and link it */
1139 cur = malloc(sizeof(struct iax_firmware));
1141 memset(cur, 0, sizeof(struct iax_firmware));
1143 cur->next = waresl.wares;
1149 munmap(cur->fwh, cur->mmaplen);
1155 cur->mmaplen = stbuf.st_size;
1161 static int iax_check_version(char *dev)
1164 struct iax_firmware *cur;
1165 if (dev && !ast_strlen_zero(dev)) {
1166 ast_mutex_lock(&waresl.lock);
1169 if (!strcmp(dev, cur->fwh->devname)) {
1170 res = ntohs(cur->fwh->version);
1175 ast_mutex_unlock(&waresl.lock);
1180 static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
1183 unsigned int bs = desc & 0xff;
1184 unsigned int start = (desc >> 8) & 0xffffff;
1186 struct iax_firmware *cur;
1187 if (dev && !ast_strlen_zero(dev) && bs) {
1189 ast_mutex_lock(&waresl.lock);
1192 if (!strcmp(dev, cur->fwh->devname)) {
1193 iax_ie_append_int(ied, IAX_IE_FWBLOCKDESC, desc);
1194 if (start < ntohl(cur->fwh->datalen)) {
1195 bytes = ntohl(cur->fwh->datalen) - start;
1198 iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes);
1201 iax_ie_append(ied, IAX_IE_FWBLOCKDATA);
1211 ast_mutex_unlock(&waresl.lock);
1217 static void reload_firmware(void)
1219 struct iax_firmware *cur, *curl, *curp;
1224 /* Mark all as dead */
1225 ast_mutex_lock(&waresl.lock);
1231 /* Now that we've freed them, load the new ones */
1232 snprintf(dir, sizeof(dir), "%s/firmware/iax", (char *)ast_config_AST_VAR_DIR);
1235 while((de = readdir(fwd))) {
1236 if (de->d_name[0] != '.') {
1237 snprintf(fn, sizeof(fn), "%s/%s", dir, de->d_name);
1238 if (!try_firmware(fn)) {
1239 if (option_verbose > 1)
1240 ast_verbose(VERBOSE_PREFIX_2 "Loaded firmware '%s'\n", de->d_name);
1246 ast_log(LOG_WARNING, "Error opening firmware directory '%s': %s\n", dir, strerror(errno));
1248 /* Clean up leftovers */
1260 destroy_firmware(curl);
1265 ast_mutex_unlock(&waresl.lock);
1268 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
1270 static int __do_deliver(void *data)
1272 /* Just deliver the packet by using queueing. This is called by
1273 the IAX thread with the iaxsl lock held. */
1274 struct iax_frame *fr = data;
1276 if (iaxs[fr->callno] && !ast_test_flag(iaxs[fr->callno], IAX_ALREADYGONE))
1277 iax2_queue_frame(fr->callno, &fr->af);
1278 /* Free our iax frame */
1279 iax2_frame_free(fr);
1280 /* And don't run again */
1284 static int do_deliver(void *data)
1286 /* Locking version of __do_deliver */
1287 struct iax_frame *fr = data;
1288 int callno = fr->callno;
1290 ast_mutex_lock(&iaxsl[callno]);
1291 res = __do_deliver(data);
1292 ast_mutex_unlock(&iaxsl[callno]);
1296 static int handle_error(void)
1298 /* XXX Ideally we should figure out why an error occured and then abort those
1299 rather than continuing to try. Unfortunately, the published interface does
1300 not seem to work XXX */
1302 struct sockaddr_in *sin;
1305 struct sock_extended_err e;
1310 m.msg_controllen = sizeof(e);
1312 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
1314 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
1316 if (m.msg_controllen) {
1317 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
1319 ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr));
1321 ast_log(LOG_WARNING, "No address detected??\n");
1323 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
1330 static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin, int sockfd)
1333 res = sendto(sockfd, f->data, f->datalen, 0,(struct sockaddr *)sin,
1337 ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
1344 static int send_packet(struct iax_frame *f)
1347 char iabuf[INET_ADDRSTRLEN];
1348 /* Called with iaxsl held */
1350 ast_log(LOG_DEBUG, "Sending %d on %d/%d to %s:%d\n", f->ts, f->callno, iaxs[f->callno]->peercallno, ast_inet_ntoa(iabuf, sizeof(iabuf), iaxs[f->callno]->addr.sin_addr), ntohs(iaxs[f->callno]->addr.sin_port));
1351 /* Don't send if there was an error, but return error instead */
1353 ast_log(LOG_WARNING, "Call number = %d\n", f->callno);
1356 if (!iaxs[f->callno])
1358 if (iaxs[f->callno]->error)
1362 iax_showframe(f, NULL, 0, &iaxs[f->callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
1363 res = sendto(iaxs[f->callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[f->callno]->transfer,
1364 sizeof(iaxs[f->callno]->transfer));
1367 iax_showframe(f, NULL, 0, &iaxs[f->callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
1368 res = sendto(iaxs[f->callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[f->callno]->addr,
1369 sizeof(iaxs[f->callno]->addr));
1373 ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
1381 static int iax2_predestroy(int callno)
1383 struct ast_channel *c;
1384 struct chan_iax2_pvt *pvt;
1385 ast_mutex_lock(&iaxsl[callno]);
1388 ast_mutex_unlock(&iaxsl[callno]);
1391 if (!ast_test_flag(pvt, IAX_ALREADYGONE)) {
1392 /* No more pings or lagrq's */
1393 if (pvt->pingid > -1)
1394 ast_sched_del(sched, pvt->pingid);
1395 if (pvt->lagid > -1)
1396 ast_sched_del(sched, pvt->lagid);
1397 if (pvt->autoid > -1)
1398 ast_sched_del(sched, pvt->autoid);
1399 if (pvt->authid > -1)
1400 ast_sched_del(sched, pvt->authid);
1401 if (pvt->initid > -1)
1402 ast_sched_del(sched, pvt->initid);
1408 ast_set_flag(pvt, IAX_ALREADYGONE);
1412 c->_softhangup |= AST_SOFTHANGUP_DEV;
1414 ast_queue_hangup(c);
1416 ast_mutex_lock(&usecnt_lock);
1419 ast_log(LOG_WARNING, "Usecnt < 0???\n");
1420 ast_mutex_unlock(&usecnt_lock);
1422 ast_mutex_unlock(&iaxsl[callno]);
1423 ast_update_use_count();
1427 static int iax2_predestroy_nolock(int callno)
1430 ast_mutex_unlock(&iaxsl[callno]);
1431 res = iax2_predestroy(callno);
1432 ast_mutex_lock(&iaxsl[callno]);
1436 static void iax2_destroy(int callno)
1438 struct chan_iax2_pvt *pvt;
1439 struct iax_frame *cur;
1440 struct ast_channel *owner;
1443 ast_mutex_lock(&iaxsl[callno]);
1445 gettimeofday(&lastused[callno], NULL);
1452 if (ast_mutex_trylock(&owner->lock)) {
1453 ast_log(LOG_NOTICE, "Avoiding IAX destroy deadlock\n");
1454 ast_mutex_unlock(&iaxsl[callno]);
1460 iaxs[callno] = NULL;
1464 /* No more pings or lagrq's */
1465 if (pvt->pingid > -1)
1466 ast_sched_del(sched, pvt->pingid);
1467 if (pvt->lagid > -1)
1468 ast_sched_del(sched, pvt->lagid);
1469 if (pvt->autoid > -1)
1470 ast_sched_del(sched, pvt->autoid);
1471 if (pvt->authid > -1)
1472 ast_sched_del(sched, pvt->authid);
1473 if (pvt->initid > -1)
1474 ast_sched_del(sched, pvt->initid);
1480 if (pvt->bridgetrans)
1481 ast_translator_free_path(pvt->bridgetrans);
1482 pvt->bridgetrans = NULL;
1485 ast_set_flag(pvt, IAX_ALREADYGONE);
1488 /* If there's an owner, prod it to give up */
1489 owner->_softhangup |= AST_SOFTHANGUP_DEV;
1490 ast_queue_hangup(owner);
1493 for (cur = iaxq.head; cur ; cur = cur->next) {
1494 /* Cancel any pending transmissions */
1495 if (cur->callno == pvt->callno)
1499 pvt->reg->callno = 0;
1503 ast_variables_destroy(pvt->vars);
1510 ast_mutex_unlock(&owner->lock);
1512 ast_mutex_unlock(&iaxsl[callno]);
1513 if (callno & 0x4000)
1516 static void iax2_destroy_nolock(int callno)
1518 /* Actually it's easier to unlock, kill it, and relock */
1519 ast_mutex_unlock(&iaxsl[callno]);
1520 iax2_destroy(callno);
1521 ast_mutex_lock(&iaxsl[callno]);
1524 static int update_packet(struct iax_frame *f)
1526 /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
1527 struct ast_iax2_full_hdr *fh = f->data;
1528 /* Mark this as a retransmission */
1529 fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
1531 f->iseqno = iaxs[f->callno]->iseqno;
1532 fh->iseqno = f->iseqno;
1536 static int attempt_transmit(void *data)
1538 /* Attempt to transmit the frame to the remote peer...
1539 Called without iaxsl held. */
1540 struct iax_frame *f = data;
1542 int callno = f->callno;
1543 char iabuf[INET_ADDRSTRLEN];
1544 /* Make sure this call is still active */
1546 ast_mutex_lock(&iaxsl[callno]);
1547 if ((f->callno) && iaxs[f->callno]) {
1548 if ((f->retries < 0) /* Already ACK'd */ ||
1549 (f->retries >= max_retries) /* Too many attempts */) {
1550 /* Record an error if we've transmitted too many times */
1551 if (f->retries >= max_retries) {
1553 /* Transfer timeout */
1554 send_command(iaxs[f->callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
1555 } else if (f->final) {
1557 iax2_destroy_nolock(f->callno);
1559 if (iaxs[f->callno]->owner)
1560 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);
1561 iaxs[f->callno]->error = ETIMEDOUT;
1562 if (iaxs[f->callno]->owner) {
1563 struct ast_frame fr = { 0, };
1565 fr.frametype = AST_FRAME_CONTROL;
1566 fr.subclass = AST_CONTROL_HANGUP;
1567 iax2_queue_frame(f->callno, &fr);
1568 /* Remember, owner could disappear */
1569 if (iaxs[f->callno]->owner)
1570 iaxs[f->callno]->owner->hangupcause = AST_CAUSE_DESTINATION_OUT_OF_ORDER;
1572 if (iaxs[f->callno]->reg) {
1573 memset(&iaxs[f->callno]->reg->us, 0, sizeof(iaxs[f->callno]->reg->us));
1574 iaxs[f->callno]->reg->regstate = REG_STATE_TIMEOUT;
1575 iaxs[f->callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
1577 iax2_destroy_nolock(f->callno);
1584 /* Update it if it needs it */
1586 /* Attempt transmission */
1589 /* Try again later after 10 times as long */
1591 if (f->retrytime > MAX_RETRY_TIME)
1592 f->retrytime = MAX_RETRY_TIME;
1593 /* Transfer messages max out at one second */
1594 if (f->transfer && (f->retrytime > 1000))
1595 f->retrytime = 1000;
1596 f->retrans = ast_sched_add(sched, f->retrytime, attempt_transmit, f);
1599 /* Make sure it gets freed */
1604 ast_mutex_unlock(&iaxsl[callno]);
1605 /* Do not try again */
1607 /* Don't attempt delivery, just remove it from the queue */
1608 ast_mutex_lock(&iaxq.lock);
1610 f->prev->next = f->next;
1612 iaxq.head = f->next;
1614 f->next->prev = f->prev;
1616 iaxq.tail = f->prev;
1618 ast_mutex_unlock(&iaxq.lock);
1620 /* Free the IAX frame */
1626 static int iax2_set_jitter(int fd, int argc, char *argv[])
1628 if ((argc != 4) && (argc != 5))
1629 return RESULT_SHOWUSAGE;
1631 max_jitter_buffer = atoi(argv[3]);
1632 if (max_jitter_buffer < 0)
1633 max_jitter_buffer = 0;
1636 if ((atoi(argv[3]) >= 0) && (atoi(argv[3]) < IAX_MAX_CALLS)) {
1637 if (iaxs[atoi(argv[3])]) {
1638 iaxs[atoi(argv[3])]->jitterbuffer = atoi(argv[4]);
1639 if (iaxs[atoi(argv[3])]->jitterbuffer < 0)
1640 iaxs[atoi(argv[3])]->jitterbuffer = 0;
1642 ast_cli(fd, "No such call '%d'\n", atoi(argv[3]));
1644 ast_cli(fd, "%d is not a valid call number\n", atoi(argv[3]));
1647 return RESULT_SUCCESS;
1650 static char jitter_usage[] =
1651 "Usage: iax set jitter [callid] <value>\n"
1652 " If used with a callid, it sets the jitter buffer to the given static\n"
1653 "value (until its next calculation). If used without a callid, the value is used\n"
1654 "to establish the maximum excess jitter buffer that is permitted before the jitter\n"
1655 "buffer size is reduced.";
1657 static int iax2_prune_realtime(int fd, int argc, char *argv[])
1659 struct iax2_peer *peer;
1662 return RESULT_SHOWUSAGE;
1663 if (!strcmp(argv[3],"all")) {
1665 ast_cli(fd, "OK cache is flushed.\n");
1666 } else if ((peer = find_peer(argv[3], 0))) {
1667 if(ast_test_flag(peer, IAX_RTCACHEFRIENDS)) {
1668 ast_set_flag(peer, IAX_RTAUTOCLEAR);
1669 expire_registry(peer);
1670 ast_cli(fd, "OK peer %s was removed from the cache.\n", argv[3]);
1672 ast_cli(fd, "SORRY peer %s is not eligible for this operation.\n", argv[3]);
1675 ast_cli(fd, "SORRY peer %s was not found in the cache.\n", argv[3]);
1678 return RESULT_SUCCESS;
1681 /*--- iax2_show_peer: Show one peer in detail ---*/
1682 static int iax2_show_peer(int fd, int argc, char *argv[])
1684 char status[30] = "";
1686 char iabuf[INET_ADDRSTRLEN];
1687 struct iax2_peer *peer;
1688 char codec_buf[512];
1689 int x = 0, codec = 0, load_realtime = 0;
1692 return RESULT_SHOWUSAGE;
1694 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? 1 : 0;
1696 peer = find_peer(argv[3], load_realtime);
1699 ast_cli(fd, " * Name : %s\n", peer->name);
1700 ast_cli(fd, " Secret : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
1701 ast_cli(fd, " Context : %s\n", peer->context);
1702 ast_cli(fd, " Mailbox : %s\n", peer->mailbox);
1703 ast_cli(fd, " Dynamic : %s\n", ast_test_flag(peer, IAX_DYNAMIC) ? "Yes":"No");
1704 ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
1705 ast_cli(fd, " Expire : %d\n", peer->expire);
1706 ast_cli(fd, " ACL : %s\n", (peer->ha?"Yes":"No"));
1707 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));
1708 ast_cli(fd, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
1709 ast_cli(fd, " Username : %s\n", peer->username);
1710 ast_cli(fd, " Codecs : ");
1711 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
1712 ast_cli(fd, "%s\n", codec_buf);
1714 ast_cli(fd, " Codec Order : (");
1715 for(x = 0; x < 32 ; x++) {
1716 codec = ast_codec_pref_index(&peer->prefs,x);
1719 ast_cli(fd, "%s", ast_getformatname(codec));
1720 if(x < 31 && ast_codec_pref_index(&peer->prefs,x+1))
1725 ast_cli(fd, "none");
1729 ast_cli(fd, " Status : ");
1730 if (peer->lastms < 0)
1731 strncpy(status, "UNREACHABLE", sizeof(status) - 1);
1732 else if (peer->lastms > peer->maxms)
1733 snprintf(status, sizeof(status), "LAGGED (%d ms)", peer->lastms);
1734 else if (peer->lastms)
1735 snprintf(status, sizeof(status), "OK (%d ms)", peer->lastms);
1737 strncpy(status, "UNKNOWN", sizeof(status) - 1);
1738 ast_cli(fd, "%s\n",status);
1740 if (ast_test_flag(peer, IAX_TEMPONLY))
1743 ast_cli(fd,"Peer %s not found.\n", argv[3]);
1747 return RESULT_SUCCESS;
1750 static char *complete_iax2_show_peer(char *line, char *word, int pos, int state)
1753 struct iax2_peer *p;
1755 /* 0 - iax2; 1 - show; 2 - peer; 3 - <peername> */
1757 ast_mutex_lock(&peerl.lock);
1758 for(p = peerl.peers ; p ; p = p->next) {
1759 if(!strncasecmp(p->name, word, strlen(word))) {
1760 if(++which > state) {
1761 return strdup(p->name);
1765 ast_mutex_unlock(&peerl.lock);
1771 static int iax2_show_stats(int fd, int argc, char *argv[])
1773 struct iax_frame *cur;
1774 int cnt = 0, dead=0, final=0;
1776 return RESULT_SHOWUSAGE;
1777 for (cur = iaxq.head; cur ; cur = cur->next) {
1778 if (cur->retries < 0)
1784 ast_cli(fd, " IAX Statistics\n");
1785 ast_cli(fd, "---------------------\n");
1786 ast_cli(fd, "Outstanding frames: %d (%d ingress, %d outgress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
1787 ast_cli(fd, "Packets in transmit queue: %d dead, %d final, %d total\n", dead, final, cnt);
1788 return RESULT_SUCCESS;
1791 static int iax2_show_cache(int fd, int argc, char *argv[])
1793 struct iax2_dpcache *dp;
1794 char tmp[1024] = "", *pc;
1798 gettimeofday(&tv, NULL);
1799 ast_mutex_lock(&dpcache_lock);
1801 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
1803 s = dp->expirey.tv_sec - tv.tv_sec;
1805 if (dp->flags & CACHE_FLAG_EXISTS)
1806 strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
1807 if (dp->flags & CACHE_FLAG_NONEXISTANT)
1808 strncat(tmp, "NONEXISTANT|", sizeof(tmp) - strlen(tmp) - 1);
1809 if (dp->flags & CACHE_FLAG_CANEXIST)
1810 strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
1811 if (dp->flags & CACHE_FLAG_PENDING)
1812 strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
1813 if (dp->flags & CACHE_FLAG_TIMEOUT)
1814 strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
1815 if (dp->flags & CACHE_FLAG_TRANSMITTED)
1816 strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
1817 if (dp->flags & CACHE_FLAG_MATCHMORE)
1818 strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
1819 if (dp->flags & CACHE_FLAG_UNKNOWN)
1820 strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
1821 /* Trim trailing pipe */
1822 if (!ast_strlen_zero(tmp))
1823 tmp[strlen(tmp) - 1] = '\0';
1825 strncpy(tmp, "(none)", sizeof(tmp) - 1);
1827 pc = strchr(dp->peercontext, '@');
1829 pc = dp->peercontext;
1832 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
1833 if (dp->waiters[x] > -1)
1836 ast_cli(fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
1838 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
1841 ast_mutex_unlock(&dpcache_lock);
1842 return RESULT_SUCCESS;
1845 static char show_stats_usage[] =
1846 "Usage: iax show stats\n"
1847 " Display statistics on IAX channel driver.\n";
1850 static char show_cache_usage[] =
1851 "Usage: iax show cache\n"
1852 " Display currently cached IAX Dialplan results.\n";
1854 static char show_peer_usage[] =
1855 "Usage: iax show peer <name>\n"
1856 " Display details on specific IAX peer\n";
1858 static char prune_realtime_usage[] =
1859 "Usage: iax2 prune realtime [<peername>|all]\n"
1860 " Prunes object(s) from the cache\n";
1862 static struct ast_cli_entry cli_set_jitter =
1863 { { "iax2", "set", "jitter", NULL }, iax2_set_jitter, "Sets IAX jitter buffer", jitter_usage };
1865 static struct ast_cli_entry cli_show_stats =
1866 { { "iax2", "show", "stats", NULL }, iax2_show_stats, "Display IAX statistics", show_stats_usage };
1868 static struct ast_cli_entry cli_show_cache =
1869 { { "iax2", "show", "cache", NULL }, iax2_show_cache, "Display IAX cached dialplan", show_cache_usage };
1871 static struct ast_cli_entry cli_show_peer =
1872 { { "iax2", "show", "peer", NULL }, iax2_show_peer, "Show details on specific IAX peer", show_peer_usage, complete_iax2_show_peer };
1874 static struct ast_cli_entry cli_prune_realtime =
1875 { { "iax2", "prune", "realtime", NULL }, iax2_prune_realtime, "Prune a cached realtime lookup", prune_realtime_usage, complete_iax2_show_peer };
1877 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
1879 #ifdef BRIDGE_OPTIMIZATION
1880 static unsigned int calc_fakestamp(struct chan_iax2_pvt *from, struct chan_iax2_pvt *to, unsigned int ts);
1882 static int forward_delivery(struct iax_frame *fr)
1884 struct chan_iax2_pvt *p1, *p2;
1885 char iabuf[INET_ADDRSTRLEN];
1888 p1 = iaxs[fr->callno];
1889 p2 = iaxs[p1->bridgecallno];
1896 ast_log(LOG_DEBUG, "forward_delivery: Forwarding ts=%d on %d/%d to %d/%d on %s:%d\n",
1898 p1->callno, p1->peercallno,
1899 p2->callno, p2->peercallno,
1900 ast_inet_ntoa(iabuf, sizeof(iabuf), p2->addr.sin_addr),
1901 ntohs(p2->addr.sin_port));
1903 /* Undo wraparound - which can happen when full VOICE frame wasn't sent by our peer.
1904 This is necessary for when our peer is chan_iax2.c v1.1nn or earlier which didn't
1905 send full frame on timestamp wrap when doing optimized bridging
1906 (actually current code STILL doesn't)
1908 if (fr->ts + 50000 <= p1->last) {
1909 fr->ts = ( (p1->last & 0xFFFF0000) + 0x10000) | (fr->ts & 0xFFFF);
1911 ast_log(LOG_DEBUG, "forward_delivery: pushed forward timestamp to %u\n", fr->ts);
1914 /* Send with timestamp adjusted to the origin of the outbound leg */
1915 /* But don't destroy inbound timestamp still needed later to set "last" */
1917 fr->ts = calc_fakestamp(p1, p2, fr->ts);
1918 res = iax2_send(p2, &fr->af, fr->ts, -1, 0, 0, 0);
1924 static void unwrap_timestamp(struct iax_frame *fr)
1928 if ( (fr->ts & 0xFFFF0000) == (iaxs[fr->callno]->last & 0xFFFF0000) ) {
1929 x = fr->ts - iaxs[fr->callno]->last;
1931 /* Sudden big jump backwards in timestamp:
1932 What likely happened here is that miniframe timestamp has circled but we haven't
1933 gotten the update from the main packet. We'll just pretend that we did, and
1934 update the timestamp appropriately. */
1935 fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) + 0x10000) | (fr->ts & 0xFFFF);
1937 ast_log(LOG_DEBUG, "schedule_delivery: pushed forward timestamp\n");
1940 /* Sudden apparent big jump forwards in timestamp:
1941 What's likely happened is this is an old miniframe belonging to the previous
1942 top-16-bit timestamp that has turned up out of order.
1943 Adjust the timestamp appropriately. */
1944 fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) - 0x10000) | (fr->ts & 0xFFFF);
1946 ast_log(LOG_DEBUG, "schedule_delivery: pushed back timestamp\n");
1951 static int schedule_delivery(struct iax_frame *fr, int reallydeliver, int updatehistory, int fromtrunk)
1955 unsigned int orig_ts;
1956 int drops[MEMORY_SIZE];
1957 int min, max=0, prevjitterbuffer, maxone=0,y,z, match;
1959 /* Remember current jitterbuffer so we can log any change */
1960 prevjitterbuffer = iaxs[fr->callno]->jitterbuffer;
1961 /* Similarly for the frame timestamp */
1966 ast_log(LOG_DEBUG, "schedule_delivery: ts=%d, last=%d, really=%d, update=%d\n",
1967 fr->ts, iaxs[fr->callno]->last, reallydeliver, updatehistory);
1970 /* Attempt to recover wrapped timestamps */
1971 unwrap_timestamp(fr);
1973 if (updatehistory) {
1975 /* Attempt to spot a change of timebase on timestamps coming from the other side
1976 We detect by noticing a jump in consecutive timestamps that can't reasonably be explained
1977 by network jitter or reordering. Sometimes, also, the peer stops sending us frames
1978 for a while - in this case this code might also resync us. But that's not a bad thing.
1979 Be careful of non-voice frames which are timestamped differently (especially ACKS!)
1980 [that's why we only do this when updatehistory is true]
1982 x = fr->ts - iaxs[fr->callno]->last;
1983 if (x > TS_GAP_FOR_JB_RESYNC || x < -TS_GAP_FOR_JB_RESYNC) {
1985 ast_log(LOG_DEBUG, "schedule_delivery: call=%d: TS jumped. resyncing rxcore (ts=%d, last=%d)\n",
1986 fr->callno, fr->ts, iaxs[fr->callno]->last);
1987 /* zap rxcore - calc_rxstamp will make a new one based on this frame */
1988 iaxs[fr->callno]->rxcore.tv_sec = 0;
1989 iaxs[fr->callno]->rxcore.tv_usec = 0;
1990 /* wipe "last" if stamps have jumped backwards */
1992 iaxs[fr->callno]->last = 0;
1993 /* should we also empty history? */
1996 /* ms is a measure of the "lateness" of the frame relative to the "reference"
1997 frame we received. (initially the very first, but also see code just above here).
1998 Understand that "ms" can easily be -ve if lag improves since the reference frame.
1999 Called by IAX thread, with iaxsl lock held. */
2000 ms = calc_rxstamp(iaxs[fr->callno], fr->ts) - fr->ts;
2002 /* Rotate our history queue of "lateness". Don't worry about those initial
2003 zeros because the first entry will always be zero */
2004 for (x=0;x<MEMORY_SIZE - 1;x++)
2005 iaxs[fr->callno]->history[x] = iaxs[fr->callno]->history[x+1];
2006 /* Add a history entry for this one */
2007 iaxs[fr->callno]->history[x] = ms;
2013 /* delivery time is sender's sent timestamp converted back into absolute time according to our clock */
2014 if ( (!fromtrunk) && (iaxs[fr->callno]->rxcore.tv_sec || iaxs[fr->callno]->rxcore.tv_usec) ) {
2015 fr->af.delivery.tv_sec = iaxs[fr->callno]->rxcore.tv_sec;
2016 fr->af.delivery.tv_usec = iaxs[fr->callno]->rxcore.tv_usec;
2017 fr->af.delivery.tv_sec += fr->ts / 1000;
2018 fr->af.delivery.tv_usec += (fr->ts % 1000) * 1000;
2019 if (fr->af.delivery.tv_usec >= 1000000) {
2020 fr->af.delivery.tv_usec -= 1000000;
2021 fr->af.delivery.tv_sec += 1;
2027 ast_log(LOG_DEBUG, "schedule_delivery: set delivery to 0 as we don't have an rxcore yet, or frame is from trunk.\n");
2029 fr->af.delivery.tv_sec = 0;
2030 fr->af.delivery.tv_usec = 0;
2033 /* Initialize the minimum to reasonable values. It's too much
2034 work to do the same for the maximum, repeatedly */
2035 min=iaxs[fr->callno]->history[0];
2036 for (z=0;z < iax2_dropcount + 1;z++) {
2037 /* Start very optimistic ;-) */
2039 for (x=0;x<MEMORY_SIZE;x++) {
2040 if (max < iaxs[fr->callno]->history[x]) {
2041 /* We have a candidate new maximum value. Make
2042 sure it's not in our drop list */
2044 for (y=0;!match && (y<z);y++)
2045 match |= (drops[y] == x);
2047 /* It's not in our list, use it as the new maximum */
2048 max = iaxs[fr->callno]->history[x];
2054 /* On our first pass, find the minimum too */
2055 if (min > iaxs[fr->callno]->history[x])
2056 min = iaxs[fr->callno]->history[x];
2063 /* Just for reference, keep the "jitter" value, the difference between the
2064 earliest and the latest. */
2066 iaxs[fr->callno]->jitter = max - min;
2068 /* IIR filter for keeping track of historic jitter, but always increase
2069 historic jitter immediately for increase */
2071 if (iaxs[fr->callno]->jitter > iaxs[fr->callno]->historicjitter )
2072 iaxs[fr->callno]->historicjitter = iaxs[fr->callno]->jitter;
2074 iaxs[fr->callno]->historicjitter = GAMMA * (double)iaxs[fr->callno]->jitter + (1-GAMMA) *
2075 iaxs[fr->callno]->historicjitter;
2077 /* If our jitter buffer is too big (by a significant margin), then we slowly
2078 shrink it to avoid letting the change be perceived */
2079 if (max < iaxs[fr->callno]->jitterbuffer - max_jitter_buffer)
2080 iaxs[fr->callno]->jitterbuffer -= jittershrinkrate;
2082 /* If our jitter buffer headroom is too small (by a significant margin), then we slowly enlarge it */
2083 /* min_jitter_buffer should be SMALLER than max_jitter_buffer - leaving a "no mans land"
2084 in between - otherwise the jitterbuffer size will hunt up and down causing unnecessary
2085 disruption. Set maxexcessbuffer to say 150msec, minexcessbuffer to say 50 */
2086 if (max > iaxs[fr->callno]->jitterbuffer - min_jitter_buffer)
2087 iaxs[fr->callno]->jitterbuffer += jittershrinkrate;
2089 /* If our jitter buffer is smaller than our maximum delay, grow the jitter
2090 buffer immediately to accomodate it (and a little more). */
2091 if (max > iaxs[fr->callno]->jitterbuffer)
2092 iaxs[fr->callno]->jitterbuffer = max
2093 /* + ((float)iaxs[fr->callno]->jitter) * 0.1 */;
2095 /* update "min", just for RRs and stats */
2096 iaxs[fr->callno]->min = min;
2098 /* If the caller just wanted us to update, return now */
2102 /* Subtract the lateness from our jitter buffer to know how long to wait
2103 before sending our packet. */
2104 delay = iaxs[fr->callno]->jitterbuffer - ms;
2106 /* Whatever happens, no frame waits longer than maxjitterbuffer */
2107 if (delay > maxjitterbuffer)
2108 delay = maxjitterbuffer;
2110 /* If jitter buffer is disabled then just pretend the frame is "right on time" */
2111 /* If frame came from trunk, also don't do any delay */
2112 if ( (!ast_test_flag(iaxs[fr->callno], IAX_USEJITTERBUF)) || fromtrunk )
2116 /* Log jitter stats for possible offline analysis */
2117 ast_log(LOG_DEBUG, "Jitter: call=%d ts=%d orig=%d last=%d %s: min=%d max=%d jb=%d %+d lateness=%d jbdelay=%d jitter=%d historic=%d\n",
2118 fr->callno, fr->ts, orig_ts, iaxs[fr->callno]->last,
2119 (fr->af.frametype == AST_FRAME_VOICE) ? "VOICE" : "CONTROL",
2120 min, max, iaxs[fr->callno]->jitterbuffer,
2121 iaxs[fr->callno]->jitterbuffer - prevjitterbuffer,
2123 iaxs[fr->callno]->jitter, iaxs[fr->callno]->historicjitter);
2127 /* Don't deliver it more than 4 ms late */
2128 if ((delay > -4) || (fr->af.frametype != AST_FRAME_VOICE)) {
2130 ast_log(LOG_DEBUG, "schedule_delivery: Delivering immediately (Calculated delay is %d)\n", delay);
2134 ast_log(LOG_DEBUG, "schedule_delivery: Dropping voice packet since %dms delay is too old\n", delay);
2135 iaxs[fr->callno]->frames_dropped++;
2136 /* Free our iax frame */
2137 iax2_frame_free(fr);
2141 ast_log(LOG_DEBUG, "schedule_delivery: Scheduling delivery in %d ms\n", delay);
2142 fr->retrans = ast_sched_add(sched, delay, do_deliver, fr);
2147 static int iax2_transmit(struct iax_frame *fr)
2149 /* Lock the queue and place this packet at the end */
2152 /* By setting this to 0, the network thread will send it for us, and
2153 queue retransmission if necessary */
2155 ast_mutex_lock(&iaxq.lock);
2162 iaxq.tail->next = fr;
2163 fr->prev = iaxq.tail;
2167 ast_mutex_unlock(&iaxq.lock);
2168 /* Wake up the network thread */
2169 pthread_kill(netthreadid, SIGURG);
2175 static int iax2_digit(struct ast_channel *c, char digit)
2177 return send_command_locked(PTR_TO_CALLNO(c->pvt->pvt), AST_FRAME_DTMF, digit, 0, NULL, 0, -1);
2180 static int iax2_sendtext(struct ast_channel *c, char *text)
2183 return send_command_locked(PTR_TO_CALLNO(c->pvt->pvt), AST_FRAME_TEXT,
2184 0, 0, text, strlen(text) + 1, -1);
2187 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
2189 return send_command_locked(PTR_TO_CALLNO(c->pvt->pvt), AST_FRAME_IMAGE, img->subclass, 0, img->data, img->datalen, -1);
2192 static int iax2_sendhtml(struct ast_channel *c, int subclass, char *data, int datalen)
2194 return send_command_locked(PTR_TO_CALLNO(c->pvt->pvt), AST_FRAME_HTML, subclass, 0, data, datalen, -1);
2197 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
2199 unsigned short callno = PTR_TO_CALLNO(newchan->pvt->pvt);
2200 ast_mutex_lock(&iaxsl[callno]);
2202 iaxs[callno]->owner = newchan;
2204 ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n");
2205 ast_mutex_unlock(&iaxsl[callno]);
2209 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, int temponly);
2210 static struct iax2_user *build_user(const char *name, struct ast_variable *v, int temponly);
2212 static void destroy_user(struct iax2_user *user);
2213 static int expire_registry(void *data);
2215 static struct iax2_peer *realtime_peer(const char *peername)
2217 struct ast_variable *var;
2218 struct ast_variable *tmp;
2219 struct iax2_peer *peer=NULL;
2220 time_t regseconds, nowtime;
2222 var = ast_load_realtime("iaxpeers", "name", peername, NULL);
2224 /* Make sure it's not a user only... */
2225 peer = build_peer(peername, var, ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS) ? 0 : 1);
2230 if (!strcasecmp(tmp->name, "type")) {
2231 if (strcasecmp(tmp->value, "friend") &&
2232 strcasecmp(tmp->value, "peer")) {
2233 /* Whoops, we weren't supposed to exist! */
2238 } else if (!strcasecmp(tmp->name, "regseconds")) {
2239 if (sscanf(tmp->value, "%li", ®seconds) != 1)
2241 } else if (!strcasecmp(tmp->name, "ipaddr")) {
2242 inet_aton(tmp->value, &(peer->addr.sin_addr));
2243 } else if (!strcasecmp(tmp->name, "port")) {
2244 peer->addr.sin_port = htons(atoi(tmp->value));
2245 } else if (!strcasecmp(tmp->name, "host")) {
2246 if (!strcasecmp(tmp->value, "dynamic"))
2252 /* Add some finishing touches, addresses, etc */
2253 if(ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
2254 ast_mutex_lock(&peerl.lock);
2255 peer->next = peerl.peers;
2257 ast_mutex_unlock(&peerl.lock);
2258 ast_copy_flags(peer, &globalflags, IAX_RTAUTOCLEAR|IAX_RTCACHEFRIENDS);
2259 if (ast_test_flag(peer, IAX_RTAUTOCLEAR))
2260 peer->expire = ast_sched_add(sched, (global_rtautoclear) * 1000, expire_registry, (void *)peer);
2262 ast_set_flag(peer, IAX_TEMPONLY);
2265 if (peer && dynamic) {
2267 if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE) {
2268 memset(&peer->addr, 0, sizeof(peer->addr));
2270 ast_log(LOG_DEBUG, "Bah, we're expired (%ld/%ld/%ld)!\n", nowtime - regseconds, regseconds, nowtime);
2274 ast_variables_destroy(var);
2279 static struct iax2_user *realtime_user(const char *username)
2281 struct ast_variable *var;
2282 struct ast_variable *tmp;
2283 struct iax2_user *user=NULL;
2284 var = ast_load_realtime("iaxusers", "name", username, NULL);
2286 /* Make sure it's not a user only... */
2287 user = build_user(username, var, !ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS));
2289 /* Add some finishing touches, addresses, etc */
2290 if(ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
2291 ast_mutex_lock(&userl.lock);
2292 user->next = userl.users;
2294 ast_mutex_unlock(&userl.lock);
2295 ast_set_flag(user, IAX_RTCACHEFRIENDS);
2297 ast_set_flag(user, IAX_TEMPONLY);
2301 if (!strcasecmp(tmp->name, "type")) {
2302 if (strcasecmp(tmp->value, "friend") &&
2303 strcasecmp(tmp->value, "user")) {
2304 /* Whoops, we weren't supposed to exist! */
2313 ast_variables_destroy(var);
2318 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin)
2322 char regseconds[20];
2326 snprintf(regseconds, sizeof(regseconds), "%ld", nowtime);
2327 ast_inet_ntoa(ipaddr, sizeof(ipaddr), sin->sin_addr);
2328 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
2329 ast_update_realtime("iaxpeers", "name", peername, "ipaddr", ipaddr, "port", port, "regseconds", regseconds, NULL);
2333 static int create_addr(struct sockaddr_in *sin, int *capability, int *sendani,
2334 int *maxtime, char *peer, char *context, int *trunk,
2335 int *notransfer, int *usejitterbuf, int *encmethods,
2336 char *username, int usernlen, char *secret, int seclen,
2337 int *ofound, char *peercontext, char *timezone, int tzlen, char *pref_str, size_t pref_size,
2340 struct ast_hostent ahp; struct hostent *hp;
2341 struct iax2_peer *p;
2350 *sockfd = defaultsockfd;
2351 sin->sin_family = AF_INET;
2352 p = find_peer(peer, 1);
2355 if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
2356 (!p->maxms || ((p->lastms > 0) && (p->lastms <= p->maxms)))) {
2359 ast_codec_pref_convert(&p->prefs, pref_str, pref_size, 1);
2362 *sendani = ast_test_flag(p, IAX_SENDANI); /* Whether we transmit ANI */
2364 *maxtime = p->maxms; /* Max time they should take */
2366 strncpy(context, p->context, AST_MAX_EXTENSION - 1);
2368 strncpy(peercontext, p->peercontext, AST_MAX_EXTENSION - 1);
2370 *trunk = ast_test_flag(p, IAX_TRUNK);
2372 *capability = p->capability;
2374 *encmethods = p->encmethods;
2376 strncpy(username, p->username, usernlen);
2377 if (p->addr.sin_addr.s_addr) {
2378 sin->sin_addr = p->addr.sin_addr;
2379 sin->sin_port = p->addr.sin_port;
2381 sin->sin_addr = p->defaddr.sin_addr;
2382 sin->sin_port = p->defaddr.sin_port;
2385 *sockfd = p->sockfd;
2387 *notransfer = ast_test_flag(p, IAX_NOTRANSFER);
2389 *usejitterbuf = ast_test_flag(p, IAX_USEJITTERBUF);
2391 if (!ast_strlen_zero(p->dbsecret)) {
2392 char *family, *key=NULL;
2393 family = ast_strdupa(p->dbsecret);
2395 key = strchr(family, '/');
2401 if (!family || !key || ast_db_get(family, key, secret, seclen)) {
2402 ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", p->dbsecret);
2403 if (ast_test_flag(p, IAX_TEMPONLY))
2408 strncpy(secret, p->secret, seclen); /* safe */
2411 snprintf(timezone, tzlen-1, "%s", p->zonetag);
2413 if (ast_test_flag(p, IAX_TEMPONLY))
2421 if(pref_str) { /* use global iax prefs for unknown peer/user */
2422 ast_codec_pref_convert(&prefs, pref_str, pref_size, 1);
2425 hp = ast_gethostbyname(peer, &ahp);
2427 memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
2428 sin->sin_port = htons(IAX_DEFAULT_PORTNO);
2431 ast_log(LOG_WARNING, "No such host: %s\n", peer);
2436 if (ast_test_flag(p, IAX_TEMPONLY))
2441 static int auto_congest(void *nothing)
2443 int callno = PTR_TO_CALLNO(nothing);
2444 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_CONGESTION };
2445 ast_mutex_lock(&iaxsl[callno]);
2447 iaxs[callno]->initid = -1;
2448 iax2_queue_frame(callno, &f);
2449 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
2451 ast_mutex_unlock(&iaxsl[callno]);
2455 static unsigned int iax2_datetime(char *tz)
2461 localtime_r(&t, &tm);
2462 if (!ast_strlen_zero(tz))
2463 ast_localtime(&t, &tm, tz);
2464 tmp = (tm.tm_sec >> 1) & 0x1f; /* 5 bits of seconds */
2465 tmp |= (tm.tm_min & 0x3f) << 5; /* 6 bits of minutes */
2466 tmp |= (tm.tm_hour & 0x1f) << 11; /* 5 bits of hours */
2467 tmp |= (tm.tm_mday & 0x1f) << 16; /* 5 bits of day of month */
2468 tmp |= ((tm.tm_mon + 1) & 0xf) << 21; /* 4 bits of month */
2469 tmp |= ((tm.tm_year - 100) & 0x7f) << 25; /* 7 bits of year */
2473 static int iax2_call(struct ast_channel *c, char *dest, int timeout)
2475 struct sockaddr_in sin;
2480 char *secret = NULL;
2482 char *l=NULL, *n=NULL;
2483 struct iax_ie_data ied;
2484 char myrdest [5] = "s";
2485 char context[AST_MAX_EXTENSION] ="";
2486 char peercontext[AST_MAX_EXTENSION] ="";
2487 char *portno = NULL;
2489 int encmethods=iax2_encryption;
2490 unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
2492 char storedusern[80], storedsecret[80];
2496 memset(out_prefs,0,32);
2498 if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
2499 ast_log(LOG_WARNING, "Line is already in use (%s)?\n", c->name);
2502 strncpy(host, dest, sizeof(host)-1);
2504 strsep(&stringp, "/");
2505 /* If no destination extension specified, use 's' */
2506 rdest = strsep(&stringp, "/");
2510 /* Check for trailing options */
2511 opts = strsep(&stringp, "/");
2516 strsep(&stringp, "@");
2517 rcontext = strsep(&stringp, "@");
2519 strsep(&stringp, "@");
2520 username = strsep(&stringp, "@");
2522 /* Really the second argument is the host, not the username */
2530 username = strsep(&stringp, ":");
2531 secret = strsep(&stringp, ":");
2534 if (strsep(&stringp, ":")) {
2536 strsep(&stringp, ":");
2537 portno = strsep(&stringp, ":");
2539 if (create_addr(&sin, NULL, NULL, NULL, hname, context, NULL, NULL, NULL, &encmethods, storedusern, sizeof(storedusern) - 1, storedsecret, sizeof(storedsecret) - 1, NULL, peercontext, tz, sizeof(tz), out_prefs, sizeof(out_prefs), NULL)) {
2540 ast_log(LOG_WARNING, "No address associated with '%s'\n", hname);
2543 /* Keep track of the context for outgoing calls too */
2544 strncpy(c->context, context, sizeof(c->context) - 1);
2546 sin.sin_port = htons(atoi(portno));
2549 n = c->cid.cid_name;
2550 /* Now build request */
2551 memset(&ied, 0, sizeof(ied));
2552 /* On new call, first IE MUST be IAX version of caller */
2553 iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
2554 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, rdest);
2555 if (strchr(opts, 'a')) {
2556 /* Request auto answer */
2557 iax_ie_append(&ied, IAX_IE_AUTOANSWER);
2559 iax_ie_append_str(&ied, IAX_IE_CODEC_PREFS, out_prefs);
2562 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
2563 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
2565 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, AST_PRES_NUMBER_NOT_AVAILABLE);
2566 iax_ie_append_byte(&ied, IAX_IE_CALLINGTON, c->cid.cid_ton);
2567 iax_ie_append_short(&ied, IAX_IE_CALLINGTNS, c->cid.cid_tns);
2569 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n);
2570 if (ast_test_flag(iaxs[callno], IAX_SENDANI) && c->cid.cid_ani) {
2571 iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, c->cid.cid_ani);
2573 if (c->language && !ast_strlen_zero(c->language))
2574 iax_ie_append_str(&ied, IAX_IE_LANGUAGE, c->language);
2575 if (c->cid.cid_dnid && !ast_strlen_zero(c->cid.cid_dnid))
2576 iax_ie_append_str(&ied, IAX_IE_DNID, c->cid.cid_dnid);
2578 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, rcontext);
2579 else if (strlen(peercontext))
2580 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, peercontext);
2581 if (!username && !ast_strlen_zero(storedusern))
2582 username = storedusern;
2584 iax_ie_append_str(&ied, IAX_IE_USERNAME, username);
2586 iax_ie_append_short(&ied, IAX_IE_ENCRYPTION, encmethods);
2587 if (!secret && !ast_strlen_zero(storedsecret))
2588 secret = storedsecret;
2589 ast_mutex_lock(&iaxsl[callno]);
2590 if (!ast_strlen_zero(c->context))
2591 strncpy(iaxs[callno]->context, c->context, sizeof(iaxs[callno]->context) - 1);
2593 strncpy(iaxs[callno]->username, username, sizeof(iaxs[callno]->username)-1);
2594 iaxs[callno]->encmethods = encmethods;
2596 if (secret[0] == '[') {
2597 /* This is an RSA key, not a normal secret */
2598 strncpy(iaxs[callno]->outkey, secret + 1, sizeof(iaxs[callno]->secret)-1);
2599 if (!ast_strlen_zero(iaxs[callno]->outkey)) {
2600 iaxs[callno]->outkey[strlen(iaxs[callno]->outkey) - 1] = '\0';
2603 strncpy(iaxs[callno]->secret, secret, sizeof(iaxs[callno]->secret)-1);
2605 iax_ie_append_int(&ied, IAX_IE_FORMAT, c->nativeformats);
2606 iax_ie_append_int(&ied, IAX_IE_CAPABILITY, iaxs[callno]->capability);
2607 iax_ie_append_short(&ied, IAX_IE_ADSICPE, c->adsicpe);
2608 iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime(tz));
2609 /* Transmit the string in a "NEW" request */
2611 /* XXX We have no equivalent XXX */
2612 if (option_verbose > 2)
2613 ast_verbose(VERBOSE_PREFIX_3 "Calling using options '%s'\n", requeststr);
2615 if (iaxs[callno]->maxtime) {
2616 /* Initialize pingtime and auto-congest time */
2617 iaxs[callno]->pingtime = iaxs[callno]->maxtime / 2;
2618 iaxs[callno]->initid = ast_sched_add(sched, iaxs[callno]->maxtime * 2, auto_congest, CALLNO_TO_PTR(callno));
2619 } else if (autokill) {
2620 iaxs[callno]->pingtime = autokill / 2;
2621 iaxs[callno]->initid = ast_sched_add(sched, autokill * 2, auto_congest, CALLNO_TO_PTR(callno));
2623 send_command(iaxs[callno], AST_FRAME_IAX,
2624 IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
2625 ast_mutex_unlock(&iaxsl[callno]);
2626 ast_setstate(c, AST_STATE_RINGING);
2630 static int iax2_hangup(struct ast_channel *c)
2632 unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
2634 struct iax_ie_data ied;
2635 memset(&ied, 0, sizeof(ied));
2636 ast_mutex_lock(&iaxsl[callno]);
2637 if (callno && iaxs[callno]) {
2638 ast_log(LOG_DEBUG, "We're hanging up %s now...\n", c->name);
2639 alreadygone = ast_test_flag(iaxs[callno], IAX_ALREADYGONE);
2640 /* Send the hangup unless we have had a transmission error or are already gone */
2641 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, (unsigned char)c->hangupcause);
2642 if (!iaxs[callno]->error && !alreadygone)
2643 send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1);
2644 /* Explicitly predestroy it */
2645 iax2_predestroy_nolock(callno);
2646 /* If we were already gone to begin with, destroy us now */
2648 ast_log(LOG_DEBUG, "Really destroying %s now...\n", c->name);
2649 iax2_destroy_nolock(callno);
2652 ast_mutex_unlock(&iaxsl[callno]);
2653 if (option_verbose > 2)
2654 ast_verbose(VERBOSE_PREFIX_3 "Hungup '%s'\n", c->name);
2658 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
2660 struct ast_option_header *h;
2662 h = malloc(datalen + sizeof(struct ast_option_header));
2664 h->flag = AST_OPTION_FLAG_REQUEST;
2665 h->option = htons(option);
2666 memcpy(h->data, data, datalen);
2667 res = send_command_locked(PTR_TO_CALLNO(c->pvt->pvt), AST_FRAME_CONTROL,
2668 AST_CONTROL_OPTION, 0, (char *)h, datalen + sizeof(struct ast_option_header), -1);
2672 ast_log(LOG_WARNING, "Out of memory\n");
2676 static struct ast_frame *iax2_read(struct ast_channel *c)
2678 static struct ast_frame f = { AST_FRAME_NULL, };
2679 ast_log(LOG_NOTICE, "I should never be called!\n");
2683 static int iax2_start_transfer(unsigned short callno0, unsigned short callno1)
2686 struct iax_ie_data ied0;
2687 struct iax_ie_data ied1;
2688 unsigned int transferid = rand();
2689 memset(&ied0, 0, sizeof(ied0));
2690 iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &iaxs[callno1]->addr);
2691 iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[callno1]->peercallno);
2692 iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, transferid);
2694 memset(&ied1, 0, sizeof(ied1));
2695 iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &iaxs[callno0]->addr);
2696 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[callno0]->peercallno);
2697 iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, transferid);
2699 res = send_command(iaxs[callno0], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
2702 res = send_command(iaxs[callno1], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
2705 iaxs[callno0]->transferring = TRANSFER_BEGIN;
2706 iaxs[callno1]->transferring = TRANSFER_BEGIN;
2710 static void lock_both(unsigned short callno0, unsigned short callno1)
2712 ast_mutex_lock(&iaxsl[callno0]);
2713 while (ast_mutex_trylock(&iaxsl[callno1])) {
2714 ast_mutex_unlock(&iaxsl[callno0]);
2716 ast_mutex_lock(&iaxsl[callno0]);
2720 static void unlock_both(unsigned short callno0, unsigned short callno1)
2722 ast_mutex_unlock(&iaxsl[callno1]);
2723 ast_mutex_unlock(&iaxsl[callno0]);
2726 static int iax2_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
2728 struct ast_channel *cs[3];
2729 struct ast_channel *who;
2732 int transferstarted=0;
2733 struct ast_frame *f;
2734 unsigned short callno0 = PTR_TO_CALLNO(c0->pvt->pvt);
2735 unsigned short callno1 = PTR_TO_CALLNO(c1->pvt->pvt);
2736 struct timeval waittimer = {0, 0}, tv;
2738 lock_both(callno0, callno1);
2739 /* Put them in native bridge mode */
2740 if (!flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1)) {
2741 iaxs[callno0]->bridgecallno = callno1;
2742 iaxs[callno1]->bridgecallno = callno0;
2744 unlock_both(callno0, callno1);
2746 /* If not, try to bridge until we can execute a transfer, if we can */
2749 for (/* ever */;;) {
2750 /* Check in case we got masqueraded into */
2751 if ((c0->type != channeltype) || (c1->type != channeltype)) {
2752 if (option_verbose > 2)
2753 ast_verbose(VERBOSE_PREFIX_3 "Can't masquerade, we're different...\n");
2754 /* Remove from native mode */
2755 if (c0->type == channeltype) {
2756 ast_mutex_lock(&iaxsl[callno0]);
2757 iaxs[callno0]->bridgecallno = 0;
2758 ast_mutex_unlock(&iaxsl[callno0]);
2760 if (c1->type == channeltype) {
2761 ast_mutex_lock(&iaxsl[callno1]);
2762 iaxs[callno1]->bridgecallno = 0;
2763 ast_mutex_unlock(&iaxsl[callno1]);
2767 if (c0->nativeformats != c1->nativeformats) {
2768 if (option_verbose > 2) {
2771 ast_getformatname_multiple(buf0, sizeof(buf0) -1, c0->nativeformats);
2772 ast_getformatname_multiple(buf1, sizeof(buf1) -1, c1->nativeformats);
2773 ast_verbose(VERBOSE_PREFIX_3 "Operating with different codecs %d[%s] %d[%s] , can't native bridge...\n", c0->nativeformats, buf0, c1->nativeformats, buf1);
2775 /* Remove from native mode */
2776 lock_both(callno0, callno1);
2777 iaxs[callno0]->bridgecallno = 0;
2778 iaxs[callno1]->bridgecallno = 0;
2779 unlock_both(callno0, callno1);
2782 /* check if transfered and if we really want native bridging */
2783 if (!transferstarted && !ast_test_flag(iaxs[callno0], IAX_NOTRANSFER) && !ast_test_flag(iaxs[callno1], IAX_NOTRANSFER) &&
2784 !(flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
2785 /* Try the transfer */
2786 if (iax2_start_transfer(callno0, callno1))
2787 ast_log(LOG_WARNING, "Unable to start the transfer\n");
2788 transferstarted = 1;
2790 if ((iaxs[callno0]->transferring == TRANSFER_RELEASED) && (iaxs[callno1]->transferring == TRANSFER_RELEASED)) {
2791 /* Call has been transferred. We're no longer involved */
2792 gettimeofday(&tv, NULL);
2793 if (!waittimer.tv_sec && !waittimer.tv_usec) {
2794 waittimer.tv_sec = tv.tv_sec;
2795 waittimer.tv_usec = tv.tv_usec;
2796 } else if (tv.tv_sec - waittimer.tv_sec > IAX_LINGER_TIMEOUT) {
2797 c0->_softhangup |= AST_SOFTHANGUP_DEV;
2798 c1->_softhangup |= AST_SOFTHANGUP_DEV;
2806 who = ast_waitfor_n(cs, 2, &to);
2808 if (ast_check_hangup(c0) || ast_check_hangup(c1)) {
2821 if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
2827 if ((f->frametype == AST_FRAME_VOICE) ||
2828 (f->frametype == AST_FRAME_TEXT) ||
2829 (f->frametype == AST_FRAME_VIDEO) ||
2830 (f->frametype == AST_FRAME_IMAGE) ||
2831 (f->frametype == AST_FRAME_DTMF)) {
2832 if ((f->frametype == AST_FRAME_DTMF) &&
2833 (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
2835 if ((flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
2838 /* Take out of conference mode */
2840 /* Remove from native mode */
2846 if (flags & AST_BRIDGE_DTMF_CHANNEL_1) {
2850 /* Remove from native mode */
2857 ast_log(LOG_DEBUG, "Read from %s\n", who->name);
2859 ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
2871 /* Swap who gets priority */
2876 lock_both(callno0, callno1);
2878 iaxs[callno0]->bridgecallno = 0;
2880 iaxs[callno1]->bridgecallno = 0;
2881 unlock_both(callno0, callno1);
2885 static int iax2_answer(struct ast_channel *c)
2887 unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
2889 ast_log(LOG_DEBUG, "Answering\n");
2890 return send_command_locked(callno, AST_FRAME_CONTROL, AST_CONTROL_ANSWER, 0, NULL, 0, -1);
2893 static int iax2_indicate(struct ast_channel *c, int condition)
2895 unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
2897 ast_log(LOG_DEBUG, "Indicating condition %d\n", condition);
2898 return send_command_locked(callno, AST_FRAME_CONTROL, condition, 0, NULL, 0, -1);
2901 static int iax2_transfer(struct ast_channel *c, char *dest)
2903 unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
2904 struct iax_ie_data ied;
2905 char tmp[256] = "", *context;
2906 strncpy(tmp, dest, sizeof(tmp) - 1);
2907 context = strchr(tmp, '@');
2912 memset(&ied, 0, sizeof(ied));
2913 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, tmp);
2915 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, context);
2917 ast_log(LOG_DEBUG, "Transferring '%s' to '%s'\n", c->name, dest);
2918 return send_command_locked(callno, AST_FRAME_IAX, IAX_COMMAND_TRANSFER, 0, ied.buf, ied.pos, -1);
2922 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
2924 static int iax2_getpeertrunk(struct sockaddr_in sin)
2926 struct iax2_peer *peer;
2928 ast_mutex_lock(&peerl.lock);
2931 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
2932 (peer->addr.sin_port == sin.sin_port)) {
2933 res = ast_test_flag(peer, IAX_TRUNK);
2938 ast_mutex_unlock(&peerl.lock);
2942 /*--- ast_iax2_new: Create new call, interface with the PBX core */
2943 static struct ast_channel *ast_iax2_new(int callno, int state, int capability)
2945 struct ast_channel *tmp;
2946 struct chan_iax2_pvt *i;
2947 struct ast_variable *v = NULL;
2949 /* Don't hold call lock */
2950 ast_mutex_unlock(&iaxsl[callno]);
2951 tmp = ast_channel_alloc(1);
2952 ast_mutex_lock(&iaxsl[callno]);
2955 if (!ast_strlen_zero(i->username))
2956 snprintf(tmp->name, sizeof(tmp->name), "IAX2/%s@%s-%d", i->username, i->host, i->callno);
2958 snprintf(tmp->name, sizeof(tmp->name), "IAX2/%s-%d", i->host, i->callno);
2959 tmp->type = channeltype;
2960 /* We can support any format by default, until we get restricted */
2961 tmp->nativeformats = capability;
2962 tmp->readformat = ast_best_codec(capability);
2963 tmp->writeformat = ast_best_codec(capability);
2964 tmp->pvt->pvt = CALLNO_TO_PTR(i->callno);
2965 tmp->pvt->send_digit = iax2_digit;
2966 tmp->pvt->send_text = iax2_sendtext;
2967 tmp->pvt->send_image = iax2_sendimage;
2968 tmp->pvt->send_html = iax2_sendhtml;
2969 tmp->pvt->call = iax2_call;
2970 tmp->pvt->hangup = iax2_hangup;
2971 tmp->pvt->answer = iax2_answer;
2972 tmp->pvt->read = iax2_read;
2973 tmp->pvt->write = iax2_write;
2974 tmp->pvt->write_video = iax2_write;
2975 tmp->pvt->indicate = iax2_indicate;
2976 tmp->pvt->setoption = iax2_setoption;
2977 tmp->pvt->bridge = iax2_bridge;
2978 tmp->pvt->transfer = iax2_transfer;
2979 if (!ast_strlen_zero(i->cid_num))
2980 tmp->cid.cid_num = strdup(i->cid_num);
2981 if (!ast_strlen_zero(i->cid_name))
2982 tmp->cid.cid_name = strdup(i->cid_name);
2983 if (!ast_strlen_zero(i->ani))
2984 tmp->cid.cid_ani = strdup(i->ani);
2985 if (!ast_strlen_zero(i->language))
2986 strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
2987 if (!ast_strlen_zero(i->dnid))
2988 tmp->cid.cid_dnid = strdup(i->dnid);
2989 tmp->cid.cid_pres = i->calling_pres;
2990 tmp->cid.cid_ton = i->calling_ton;
2991 tmp->cid.cid_tns = i->calling_tns;
2992 if (!ast_strlen_zero(i->accountcode))
2993 strncpy(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode)-1);
2995 tmp->amaflags = i->amaflags;
2996 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
2997 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
2998 tmp->adsicpe = i->peeradsicpe;
2999 tmp->pvt->fixup = iax2_fixup;
3001 i->capability = capability;
3002 ast_setstate(tmp, state);
3003 ast_mutex_lock(&usecnt_lock);
3005 ast_mutex_unlock(&usecnt_lock);
3006 ast_update_use_count();
3007 if (state != AST_STATE_DOWN) {
3008 if (ast_pbx_start(tmp)) {
3009 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
3014 for (v = i->vars ; v ; v = v->next)
3015 pbx_builtin_setvar_helper(tmp,v->name,v->value);