2 * Asterisk -- A telephony toolkit for Linux.
4 * Implementation of Inter-Asterisk eXchange Version 2
6 * Copyright (C) 2003, Digium
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 <arpa/inet.h>
36 #include <sys/socket.h>
37 #include <netinet/in.h>
38 #include <netinet/in_systm.h>
39 #include <netinet/ip.h>
41 #include <sys/signal.h>
50 #include <sys/ioctl.h>
51 #include <linux/zaptel.h>
55 #include "iax2-parser.h"
58 #define IPTOS_MINCOST 0x02
62 * Uncomment to try experimental IAX bridge optimization,
63 * designed to reduce latency when IAX calls cannot
67 #define BRIDGE_OPTIMIZATION
70 #define DEFAULT_RETRY_TIME 1000
71 #define MEMORY_SIZE 100
72 #define DEFAULT_DROP 3
73 /* Flag to use with trunk calls, keeping these calls high up. It halves our effective use
74 but keeps the division between trunked and non-trunked better. */
75 #define TRUNK_CALL_START 0x4000
79 #define MIN_REUSE_TIME 60 /* Don't reuse a call number within 60 seconds */
81 /* Sample over last 100 units to determine historic jitter */
84 static char *desc = "Inter Asterisk eXchange (Ver 2)";
85 static char *tdesc = "Inter Asterisk eXchange Driver (Ver 2)";
86 static char *type = "IAX2";
88 static char context[80] = "default";
90 static int max_retries = 4;
91 static int ping_time = 20;
92 static int lagrq_time = 10;
93 static int maxtrunkcall = TRUNK_CALL_START;
94 static int maxnontrunkcall = 1;
95 static int maxjitterbuffer=3000;
96 static int trunkfreq = 20;
98 static int iaxdefaultdpcache=10 * 60; /* Cache dialplan entries for 10 minutes by default */
100 static int iaxdefaulttimeout = 5; /* Default to wait no more than 5 seconds for a reply to come back */
102 static int netsocket = -1;
106 static int expirey = IAX_DEFAULT_REG_EXPIRE;
108 static int timingfd = -1; /* Timing file descriptor */
111 static ast_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
113 int (*iax2_regfunk)(char *username, int onoff) = NULL;
116 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
118 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
119 ~AST_FORMAT_SLINEAR & \
123 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
127 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
131 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
132 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
133 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
135 static struct io_context *io;
136 static struct sched_context *sched;
138 static int iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
140 static int iax2_dropcount = DEFAULT_DROP;
142 static int use_jitterbuffer = 0;
144 static int iaxdebug = 0;
146 static int iaxtrunkdebug = 0;
148 static char accountcode[20];
149 static int amaflags = 0;
150 static int notransfer = 0;
152 static pthread_t netthreadid;
154 #define IAX_STATE_STARTED (1 << 0)
155 #define IAX_STATE_AUTHENTICATED (1 << 1)
156 #define IAX_STATE_TBD (1 << 2)
158 struct iax2_context {
159 char context[AST_MAX_EXTENSION];
160 struct iax2_context *next;
167 char accountcode[20];
168 char inkeys[80]; /* Key(s) this user can use to authenticate to us */
173 char callerid[AST_MAX_EXTENSION];
175 struct iax2_context *contexts;
176 struct iax2_user *next;
184 char outkey[80]; /* What key we use to talk to this peer */
185 char context[AST_MAX_EXTENSION]; /* Default context (for transfer really) */
186 char mailbox[AST_MAX_EXTENSION]; /* Mailbox */
187 struct sockaddr_in addr;
191 /* Dynamic Registration fields */
192 int dynamic; /* If this is a dynamic peer */
193 struct sockaddr_in defaddr; /* Default address if there is one */
194 char challenge[80]; /* Challenge used to authenticate the secret */
195 int authmethods; /* Authentication methods (IAX_AUTH_*) */
196 char inkeys[80]; /* Key(s) this peer can use to authenticate to us */
199 /* Suggested caller id if registering */
200 char callerid[AST_MAX_EXTENSION];
201 /* Whether or not to send ANI */
203 int expire; /* Schedule entry for expirey */
204 int expirey; /* How soon to expire */
205 int capability; /* Capability */
206 int delme; /* I need to be deleted */
207 int trunk; /* Treat as an IAX trunking */
208 struct timeval txtrunktime; /* Transmit trunktime */
209 struct timeval rxtrunktime; /* Receive trunktime */
210 struct timeval lasttxtime; /* Last transmitted trunktime */
211 unsigned int lastsent; /* Last sent time */
214 int callno; /* Call number of POKE request */
215 int pokeexpire; /* When to expire poke */
216 int lastms; /* How long last response took (in ms), or -1 for no response */
217 int maxms; /* Max ms we will accept for the host to be up, 0 to not monitor */
220 struct iax2_peer *next;
224 #define REG_STATE_UNREGISTERED 0
225 #define REG_STATE_REGSENT 1
226 #define REG_STATE_AUTHSENT 2
227 #define REG_STATE_REGISTERED 3
228 #define REG_STATE_REJECTED 4
229 #define REG_STATE_TIMEOUT 5
230 #define REG_STATE_NOAUTH 6
232 #define TRANSFER_NONE 0
233 #define TRANSFER_BEGIN 1
234 #define TRANSFER_READY 2
235 #define TRANSFER_RELEASED 3
236 #define TRANSFER_PASSTHROUGH 4
238 struct iax2_registry {
239 struct sockaddr_in addr; /* Who we connect to for registration purposes */
241 char secret[80]; /* Password or key name in []'s */
243 int expire; /* Sched ID of expiration */
244 int refresh; /* How often to refresh */
246 int messages; /* Message count */
247 int callno; /* Associated call number if applicable */
248 struct sockaddr_in us; /* Who the server thinks we are */
249 struct iax2_registry *next;
252 static struct iax2_registry *registrations;
254 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
255 #define MIN_RETRY_TIME 100
256 #define MAX_RETRY_TIME 10000
257 #define MAX_JITTER_BUFFER 50
259 #define MAX_TRUNKDATA 640 /* 40ms, uncompressed linear */
261 /* If we have more than this much excess real jitter buffer, srhink it. */
262 static int max_jitter_buffer = MAX_JITTER_BUFFER;
264 struct chan_iax2_pvt {
265 /* Pipes for communication. pipe[1] belongs to the
266 network thread (write), and pipe[0] belongs to the individual
268 /* Whether or not we Quelch audio */
270 /* Last received voice format */
272 /* Last received voice format */
274 /* Last sent voice format */
276 /* Last sent video format */
278 /* What we are capable of sending */
280 /* Last received timestamp */
282 /* Last sent timestamp - never send the same timestamp twice in a single call */
283 unsigned int lastsent;
285 unsigned int pingtime;
286 /* Max time for initial response */
289 struct sockaddr_in addr;
290 /* Our call number */
291 unsigned short callno;
293 unsigned short peercallno;
294 /* Peer selected format */
296 /* Peer capability */
298 /* timeval that we base our transmission on */
299 struct timeval offset;
300 /* timeval that we base our delivery on */
301 struct timeval rxcore;
302 /* Historical delivery time */
303 int history[MEMORY_SIZE];
304 /* Current base jitterbuffer */
306 /* Current jitter measure */
308 /* Historic jitter value */
312 /* Error, as discovered by the manager */
314 /* Owner if we have one */
315 struct ast_channel *owner;
316 /* What's our state? */
318 /* Expirey (optional) */
320 /* Next outgoing sequence number */
321 unsigned char oseqno;
322 /* Next sequence number they have not yet acknowledged */
323 unsigned char rseqno;
324 /* Next incoming sequence number */
325 unsigned char iseqno;
326 /* Last incoming sequence number we have acknowledged */
327 unsigned char aseqno;
330 /* Default Context */
332 /* Caller ID if available */
334 /* Hidden Caller ID (i.e. ANI) if appropriate */
336 /* Whether or not ani should be transmitted in addition to Caller*ID */
338 /* Whether to request autoanswer */
342 /* Requested Extension */
343 char exten[AST_MAX_EXTENSION];
344 /* Expected Username */
346 /* Expected Secret */
348 /* permitted authentication methods */
352 /* Public keys permitted keys for incoming authentication */
354 /* Private key for outgoing authentication */
356 /* Preferred language */
358 /* Hostname/peername for naming purposes */
360 /* Associated registry */
361 struct iax2_registry *reg;
362 /* Associated peer for poking */
363 struct iax2_peer *peerpoke;
365 /* Transferring status */
367 /* Transfer identifier */
369 /* Already disconnected */
371 /* Who we are IAX transfering to */
372 struct sockaddr_in transfer;
373 /* What's the new call number for the transfer */
374 unsigned short transfercallno;
376 /* Status of knowledge of peer ADSI capability */
379 /* Who we are bridged to */
380 unsigned short bridgecallno;
381 int pingid; /* Transmit PING request */
382 int lagid; /* Retransmit lag request */
383 int autoid; /* Auto hangup for Dialplan requestor */
384 int initid; /* Initial peer auto-congest ID (based on qualified peers) */
385 char dproot[AST_MAX_EXTENSION];
386 char accountcode[20];
388 /* This is part of a trunk interface */
390 /* Trunk data and length */
391 unsigned char trunkdata[MAX_TRUNKDATA];
392 unsigned int trunkdatalen;
394 struct iax2_dpcache *dpentries;
395 int notransfer; /* do we want native bridging */
398 static struct ast_iax2_queue {
399 struct iax_frame *head;
400 struct iax_frame *tail;
405 static struct ast_user_list {
406 struct iax2_user *users;
410 static struct ast_peer_list {
411 struct iax2_peer *peers;
415 /* Extension exists */
416 #define CACHE_FLAG_EXISTS (1 << 0)
417 /* Extension is non-existant */
418 #define CACHE_FLAG_NONEXISTANT (1 << 1)
419 /* Extension can exist */
420 #define CACHE_FLAG_CANEXIST (1 << 2)
421 /* Waiting to hear back response */
422 #define CACHE_FLAG_PENDING (1 << 3)
424 #define CACHE_FLAG_TIMEOUT (1 << 4)
425 /* Request transmitted */
426 #define CACHE_FLAG_TRANSMITTED (1 << 5)
428 #define CACHE_FLAG_UNKNOWN (1 << 6)
430 #define CACHE_FLAG_MATCHMORE (1 << 7)
432 static struct iax2_dpcache {
433 char peercontext[AST_MAX_EXTENSION];
434 char exten[AST_MAX_EXTENSION];
436 struct timeval expirey;
438 unsigned short callno;
440 struct iax2_dpcache *next;
441 struct iax2_dpcache *peer; /* For linking in peers */
444 static ast_mutex_t dpcache_lock;
446 static void iax_debug_output(const char *data)
451 static void iax_error_output(const char *data)
453 ast_log(LOG_WARNING, data);
456 /* XXX We probably should use a mutex when working with this XXX */
457 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS];
458 static ast_mutex_t iaxsl[IAX_MAX_CALLS];
459 static struct timeval lastused[IAX_MAX_CALLS];
462 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, char *, int, int);
463 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, char *, int, int);
464 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, char *, int, int);
465 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, char *, int);
467 static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts);
469 static int send_ping(void *data)
471 int callno = (long)data;
472 /* Ping only if it's real, not if it's bridged */
474 #ifdef BRIDGE_OPTIMIZATION
475 if (!iaxs[callno]->bridgecallno)
477 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
483 static int send_lagrq(void *data)
485 int callno = (long)data;
486 /* Ping only if it's real not if it's bridged */
488 #ifdef BRIDGE_OPTIMIZATION
489 if (!iaxs[callno]->bridgecallno)
491 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
497 static unsigned char compress_subclass(int subclass)
501 /* If it's 128 or smaller, just return it */
502 if (subclass < IAX_FLAG_SC_LOG)
504 /* Otherwise find its power */
505 for (x = 0; x < IAX_MAX_SHIFT; x++) {
506 if (subclass & (1 << x)) {
508 ast_log(LOG_WARNING, "Can't compress subclass %d\n", subclass);
514 return power | IAX_FLAG_SC_LOG;
517 static int uncompress_subclass(unsigned char csub)
519 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
520 if (csub & IAX_FLAG_SC_LOG) {
521 /* special case for 'compressed' -1 */
525 return 1 << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
531 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len, int lockpeer)
533 struct iax2_peer *peer;
536 ast_mutex_lock(&peerl.lock);
539 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
540 (peer->addr.sin_port == sin.sin_port)) {
541 strncpy(host, peer->name, len-1);
548 ast_mutex_unlock(&peerl.lock);
552 static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, int lockpeer)
554 struct chan_iax2_pvt *tmp;
555 tmp = malloc(sizeof(struct chan_iax2_pvt));
557 memset(tmp, 0, sizeof(struct chan_iax2_pvt));
560 tmp->transfercallno = 0;
561 tmp->bridgecallno = 0;
566 /* strncpy(tmp->context, context, sizeof(tmp->context)-1); */
567 strncpy(tmp->exten, "s", sizeof(tmp->exten)-1);
568 if (!iax2_getpeername(*sin, tmp->host, sizeof(tmp->host), lockpeer))
569 snprintf(tmp->host, sizeof(tmp->host), "%s:%d", inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
574 static int get_samples(struct ast_frame *f)
577 switch(f->subclass) {
578 case AST_FORMAT_SPEEX:
579 samples = 160; /* XXX Not necessarily true XXX */
581 case AST_FORMAT_G723_1:
582 samples = 240 /* XXX Not necessarily true XXX */;
584 case AST_FORMAT_ILBC:
585 samples = 240 * (f->datalen / 50);
588 samples = 160 * (f->datalen / 33);
590 case AST_FORMAT_G729A:
591 samples = 160 * (f->datalen / 20);
593 case AST_FORMAT_SLINEAR:
594 samples = f->datalen / 2;
596 case AST_FORMAT_LPC10:
598 samples += (((char *)(f->data))[7] & 0x1) * 8;
600 case AST_FORMAT_ULAW:
601 samples = f->datalen;
603 case AST_FORMAT_ALAW:
604 samples = f->datalen;
606 case AST_FORMAT_ADPCM:
607 samples = f->datalen *2;
610 ast_log(LOG_WARNING, "Don't know how to calculate samples on %d packets\n", f->subclass);
615 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
617 /* Malloc() a copy of a frame */
618 struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen);
620 memcpy(new, fr, sizeof(struct iax_frame));
621 iax_frame_wrap(new, &fr->af);
624 new->direction = DIRECTION_INGRESS;
630 #define NEW_PREVENT 0
634 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, struct chan_iax2_pvt *cur)
636 if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
637 (cur->addr.sin_port == sin->sin_port)) {
638 /* This is the main host */
639 if ((cur->peercallno == callno) ||
640 ((dcallno == cur->callno) && !cur->peercallno)) {
641 /* That's us. Be sure we keep track of the peer call number */
645 if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
646 (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
647 /* We're transferring */
648 if (dcallno == cur->callno)
654 static void update_max_trunk(void)
656 int max = TRUNK_CALL_START;
658 /* XXX Prolly don't need locks here XXX */
659 for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
665 ast_log(LOG_DEBUG, "New max trunk callno is %d\n", max);
668 static void update_max_nontrunk(void)
672 /* XXX Prolly don't need locks here XXX */
673 for (x=1;x<TRUNK_CALL_START - 1; x++) {
677 maxnontrunkcall = max;
679 ast_log(LOG_DEBUG, "New max nontrunk callno is %d\n", max);
682 static int make_trunk(unsigned short callno, int locked)
687 if (iaxs[callno]->oseqno) {
688 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
691 if (callno & TRUNK_CALL_START) {
692 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
695 gettimeofday(&now, NULL);
696 for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
697 ast_mutex_lock(&iaxsl[x]);
698 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) {
699 iaxs[x] = iaxs[callno];
702 /* Update the two timers that should have been started */
703 if (iaxs[x]->pingid > -1)
704 ast_sched_del(sched, iaxs[x]->pingid);
705 if (iaxs[x]->lagid > -1)
706 ast_sched_del(sched, iaxs[x]->lagid);
707 iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)x);
708 iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)x);
710 ast_mutex_unlock(&iaxsl[callno]);
713 ast_mutex_unlock(&iaxsl[x]);
716 ast_mutex_unlock(&iaxsl[x]);
718 if (x >= IAX_MAX_CALLS - 1) {
719 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
722 ast_log(LOG_DEBUG, "Made call %d into trunk call %d\n", callno, x);
723 /* We move this call from a non-trunked to a trunked call */
725 update_max_nontrunk();
729 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int lockpeer)
734 if (new <= NEW_ALLOW) {
735 /* Look for an existing connection first */
736 for (x=1;(res < 1) && (x<maxnontrunkcall);x++) {
737 ast_mutex_lock(&iaxsl[x]);
739 /* Look for an exact match */
740 if (match(sin, callno, dcallno, iaxs[x])) {
744 ast_mutex_unlock(&iaxsl[x]);
746 for (x=TRUNK_CALL_START;(res < 1) && (x<maxtrunkcall);x++) {
747 ast_mutex_lock(&iaxsl[x]);
749 /* Look for an exact match */
750 if (match(sin, callno, dcallno, iaxs[x])) {
754 ast_mutex_unlock(&iaxsl[x]);
757 if ((res < 1) && (new >= NEW_ALLOW)) {
758 gettimeofday(&now, NULL);
759 for (x=1;x<TRUNK_CALL_START;x++) {
760 /* Find first unused call number that hasn't been used in a while */
761 ast_mutex_lock(&iaxsl[x]);
762 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) break;
763 ast_mutex_unlock(&iaxsl[x]);
765 /* We've still got lock held if we found a spot */
766 if (x >= TRUNK_CALL_START) {
767 ast_log(LOG_WARNING, "No more space\n");
770 iaxs[x] = new_iax(sin, lockpeer);
771 ast_mutex_unlock(&iaxsl[x]);
772 update_max_nontrunk();
775 ast_log(LOG_DEBUG, "Creating new call structure %d\n", x);
776 iaxs[x]->addr.sin_port = sin->sin_port;
777 iaxs[x]->addr.sin_family = sin->sin_family;
778 iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
779 iaxs[x]->peercallno = callno;
781 iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
782 iaxs[x]->expirey = expirey;
783 iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)x);
784 iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)x);
785 iaxs[x]->amaflags = amaflags;
786 iaxs[x]->notransfer = notransfer;
787 strncpy(iaxs[x]->accountcode, accountcode, sizeof(iaxs[x]->accountcode)-1);
789 ast_log(LOG_WARNING, "Out of resources\n");
797 static void iax2_frame_free(struct iax_frame *fr)
799 if (fr->retrans > -1)
800 ast_sched_del(sched, fr->retrans);
804 static int iax2_queue_frame(int callno, struct ast_frame *f)
807 /* Assumes lock for callno is already held... */
810 if (!ast_mutex_trylock(&iaxsl[callno])) {
811 ast_log(LOG_WARNING, "Lock is not held on pass %d of iax2_queue_frame\n", pass);
814 if (iaxs[callno] && iaxs[callno]->owner) {
815 if (ast_mutex_trylock(&iaxs[callno]->owner->lock)) {
816 /* Avoid deadlock by pausing and trying again */
817 ast_mutex_unlock(&iaxsl[callno]);
819 ast_mutex_lock(&iaxsl[callno]);
821 ast_queue_frame(iaxs[callno]->owner, f, 0);
822 ast_mutex_unlock(&iaxs[callno]->owner->lock);
831 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
833 static int __do_deliver(void *data)
835 /* Just deliver the packet by using queueing. This is called by
836 the IAX thread with the iaxsl lock held. */
837 struct iax_frame *fr = data;
840 if (iaxs[fr->callno] && !iaxs[fr->callno]->alreadygone) {
841 if (fr->af.frametype == AST_FRAME_IAX) {
842 /* We have to treat some of these packets specially because
843 they're LAG measurement packets */
844 if (fr->af.subclass == IAX_COMMAND_LAGRQ) {
845 /* If we got a queued request, build a reply and send it */
846 fr->af.subclass = IAX_COMMAND_LAGRP;
847 iax2_send(iaxs[fr->callno], &fr->af, fr->ts, -1, 0, 0, 0);
848 } else if (fr->af.subclass == IAX_COMMAND_LAGRP) {
849 /* This is a reply we've been given, actually measure the difference */
850 ts = calc_timestamp(iaxs[fr->callno], 0);
851 iaxs[fr->callno]->lag = ts - fr->ts;
854 iax2_queue_frame(fr->callno, &fr->af);
857 /* Free our iax frame */
859 /* And don't run again */
863 static int do_deliver(void *data)
865 /* Locking version of __do_deliver */
866 struct iax_frame *fr = data;
867 int callno = fr->callno;
869 ast_mutex_lock(&iaxsl[callno]);
870 res = __do_deliver(data);
871 ast_mutex_unlock(&iaxsl[callno]);
875 static int handle_error(void)
877 /* XXX Ideally we should figure out why an error occured and then abort those
878 rather than continuing to try. Unfortunately, the published interface does
879 not seem to work XXX */
881 struct sockaddr_in *sin;
884 struct sock_extended_err e;
889 m.msg_controllen = sizeof(e);
891 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
893 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
895 if (m.msg_controllen) {
896 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
898 ast_log(LOG_WARNING, "Receive error from %s\n", inet_ntoa(sin->sin_addr));
900 ast_log(LOG_WARNING, "No address detected??\n");
902 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
909 static int send_packet(struct iax_frame *f)
912 /* Called with iaxsl held */
914 ast_log(LOG_DEBUG, "Sending %d on %d/%d to %s:%d\n", f->ts, f->callno, iaxs[f->callno]->peercallno, inet_ntoa(iaxs[f->callno]->addr.sin_addr), ntohs(iaxs[f->callno]->addr.sin_port));
915 /* Don't send if there was an error, but return error instead */
917 ast_log(LOG_WARNING, "Call number = %d\n", f->callno);
920 if (!iaxs[f->callno])
922 if (iaxs[f->callno]->error)
926 iax_showframe(f, NULL, 0, &iaxs[f->callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
927 res = sendto(netsocket, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[f->callno]->transfer,
928 sizeof(iaxs[f->callno]->transfer));
931 iax_showframe(f, NULL, 0, &iaxs[f->callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
932 res = sendto(netsocket, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[f->callno]->addr,
933 sizeof(iaxs[f->callno]->addr));
937 ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
945 static int iax2_predestroy(int callno)
947 struct ast_channel *c;
948 struct chan_iax2_pvt *pvt;
949 ast_mutex_lock(&iaxsl[callno]);
952 ast_mutex_unlock(&iaxsl[callno]);
955 if (!pvt->alreadygone) {
956 /* No more pings or lagrq's */
957 if (pvt->pingid > -1)
958 ast_sched_del(sched, pvt->pingid);
960 ast_sched_del(sched, pvt->lagid);
961 if (pvt->autoid > -1)
962 ast_sched_del(sched, pvt->autoid);
963 if (pvt->initid > -1)
964 ast_sched_del(sched, pvt->initid);
969 pvt->alreadygone = 1;
973 c->_softhangup |= AST_SOFTHANGUP_DEV;
975 ast_queue_hangup(c, 0);
977 ast_mutex_lock(&usecnt_lock);
980 ast_log(LOG_WARNING, "Usecnt < 0???\n");
981 ast_mutex_unlock(&usecnt_lock);
982 ast_update_use_count();
984 ast_mutex_unlock(&iaxsl[callno]);
988 static int iax2_predestroy_nolock(int callno)
991 ast_mutex_unlock(&iaxsl[callno]);
992 res = iax2_predestroy(callno);
993 ast_mutex_lock(&iaxsl[callno]);
997 static void iax2_destroy(int callno)
999 struct chan_iax2_pvt *pvt;
1000 struct iax_frame *cur;
1001 struct ast_channel *owner;
1004 ast_mutex_lock(&iaxsl[callno]);
1006 gettimeofday(&lastused[callno], NULL);
1013 if (ast_mutex_trylock(&owner->lock)) {
1014 ast_log(LOG_NOTICE, "Avoiding IAX destroy deadlock\n");
1015 ast_mutex_unlock(&iaxsl[callno]);
1020 iaxs[callno] = NULL;
1023 /* No more pings or lagrq's */
1024 if (pvt->pingid > -1)
1025 ast_sched_del(sched, pvt->pingid);
1026 if (pvt->lagid > -1)
1027 ast_sched_del(sched, pvt->lagid);
1028 if (pvt->autoid > -1)
1029 ast_sched_del(sched, pvt->autoid);
1030 if (pvt->initid > -1)
1031 ast_sched_del(sched, pvt->initid);
1038 pvt->alreadygone = 1;
1041 /* If there's an owner, prod it to give up */
1042 owner->pvt->pvt = NULL;
1043 owner->_softhangup |= AST_SOFTHANGUP_DEV;
1044 ast_queue_hangup(owner, 0);
1047 for (cur = iaxq.head; cur ; cur = cur->next) {
1048 /* Cancel any pending transmissions */
1049 if (cur->callno == pvt->callno)
1053 pvt->reg->callno = 0;
1058 ast_mutex_unlock(&owner->lock);
1060 ast_mutex_unlock(&iaxsl[callno]);
1061 if (callno & 0x4000)
1064 static void iax2_destroy_nolock(int callno)
1066 /* Actually it's easier to unlock, kill it, and relock */
1067 ast_mutex_unlock(&iaxsl[callno]);
1068 iax2_destroy(callno);
1069 ast_mutex_lock(&iaxsl[callno]);
1072 static int update_packet(struct iax_frame *f)
1074 /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
1075 struct ast_iax2_full_hdr *fh = f->data;
1076 /* Mark this as a retransmission */
1077 fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
1079 f->iseqno = iaxs[f->callno]->iseqno;
1080 fh->iseqno = f->iseqno;
1084 static int attempt_transmit(void *data)
1086 /* Attempt to transmit the frame to the remote peer...
1087 Called without iaxsl held. */
1088 struct iax_frame *f = data;
1090 int callno = f->callno;
1091 /* Make sure this call is still active */
1093 ast_mutex_lock(&iaxsl[callno]);
1094 if ((f->callno) && iaxs[f->callno]) {
1095 if ((f->retries < 0) /* Already ACK'd */ ||
1096 (f->retries >= max_retries) /* Too many attempts */) {
1097 /* Record an error if we've transmitted too many times */
1098 if (f->retries >= max_retries) {
1100 /* Transfer timeout */
1101 send_command(iaxs[f->callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
1102 } else if (f->final) {
1104 iax2_destroy_nolock(f->callno);
1106 if (iaxs[f->callno]->owner)
1107 ast_log(LOG_WARNING, "Max retries exceeded to host %s on %s (type = %d, subclass = %d, ts=%d, seqno=%d)\n", inet_ntoa(iaxs[f->callno]->addr.sin_addr),iaxs[f->callno]->owner->name , f->af.frametype, f->af.subclass, f->ts, f->oseqno);
1108 iaxs[f->callno]->error = ETIMEDOUT;
1109 if (iaxs[f->callno]->owner) {
1110 struct ast_frame fr = { 0, };
1112 fr.frametype = AST_FRAME_CONTROL;
1113 fr.subclass = AST_CONTROL_HANGUP;
1114 iax2_queue_frame(f->callno, &fr);
1116 if (iaxs[f->callno]->reg) {
1117 memset(&iaxs[f->callno]->reg->us, 0, sizeof(iaxs[f->callno]->reg->us));
1118 iaxs[f->callno]->reg->regstate = REG_STATE_TIMEOUT;
1119 iaxs[f->callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
1121 iax2_destroy_nolock(f->callno);
1128 /* Update it if it needs it */
1130 /* Attempt transmission */
1133 /* Try again later after 10 times as long */
1135 if (f->retrytime > MAX_RETRY_TIME)
1136 f->retrytime = MAX_RETRY_TIME;
1137 /* Transfer messages max out at one second */
1138 if (f->transfer && (f->retrytime > 1000))
1139 f->retrytime = 1000;
1140 f->retrans = ast_sched_add(sched, f->retrytime, attempt_transmit, f);
1143 /* Make sure it gets freed */
1148 ast_mutex_unlock(&iaxsl[callno]);
1149 /* Do not try again */
1151 /* Don't attempt delivery, just remove it from the queue */
1152 ast_mutex_lock(&iaxq.lock);
1154 f->prev->next = f->next;
1156 iaxq.head = f->next;
1158 f->next->prev = f->prev;
1160 iaxq.tail = f->prev;
1162 ast_mutex_unlock(&iaxq.lock);
1164 /* Free the IAX frame */
1170 static int iax2_set_jitter(int fd, int argc, char *argv[])
1172 if ((argc != 4) && (argc != 5))
1173 return RESULT_SHOWUSAGE;
1175 max_jitter_buffer = atoi(argv[3]);
1176 if (max_jitter_buffer < 0)
1177 max_jitter_buffer = 0;
1180 if ((atoi(argv[3]) >= 0) && (atoi(argv[3]) < IAX_MAX_CALLS)) {
1181 if (iaxs[atoi(argv[3])]) {
1182 iaxs[atoi(argv[3])]->jitterbuffer = atoi(argv[4]);
1183 if (iaxs[atoi(argv[3])]->jitterbuffer < 0)
1184 iaxs[atoi(argv[3])]->jitterbuffer = 0;
1186 ast_cli(fd, "No such call '%d'\n", atoi(argv[3]));
1188 ast_cli(fd, "%d is not a valid call number\n", atoi(argv[3]));
1191 return RESULT_SUCCESS;
1194 static char jitter_usage[] =
1195 "Usage: iax set jitter [callid] <value>\n"
1196 " If used with a callid, it sets the jitter buffer to the given static\n"
1197 "value (until its next calculation). If used without a callid, the value is used\n"
1198 "to establish the maximum excess jitter buffer that is permitted before the jitter\n"
1199 "buffer size is reduced.";
1201 static int iax2_show_stats(int fd, int argc, char *argv[])
1203 struct iax_frame *cur;
1204 int cnt = 0, dead=0, final=0;
1206 return RESULT_SHOWUSAGE;
1207 for (cur = iaxq.head; cur ; cur = cur->next) {
1208 if (cur->retries < 0)
1214 ast_cli(fd, " IAX Statistics\n");
1215 ast_cli(fd, "---------------------\n");
1216 ast_cli(fd, "Outstanding frames: %d (%d ingress, %d outgress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
1217 ast_cli(fd, "Packets in transmit queue: %d dead, %d final, %d total\n", dead, final, cnt);
1218 return RESULT_SUCCESS;
1221 static int iax2_show_cache(int fd, int argc, char *argv[])
1223 struct iax2_dpcache *dp;
1224 char tmp[1024], *pc;
1228 gettimeofday(&tv, NULL);
1229 ast_mutex_lock(&dpcache_lock);
1231 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
1233 s = dp->expirey.tv_sec - tv.tv_sec;
1235 if (dp->flags & CACHE_FLAG_EXISTS)
1236 strcat(tmp, "EXISTS|");
1237 if (dp->flags & CACHE_FLAG_NONEXISTANT)
1238 strcat(tmp, "NONEXISTANT|");
1239 if (dp->flags & CACHE_FLAG_CANEXIST)
1240 strcat(tmp, "CANEXIST|");
1241 if (dp->flags & CACHE_FLAG_PENDING)
1242 strcat(tmp, "PENDING|");
1243 if (dp->flags & CACHE_FLAG_TIMEOUT)
1244 strcat(tmp, "TIMEOUT|");
1245 if (dp->flags & CACHE_FLAG_TRANSMITTED)
1246 strcat(tmp, "TRANSMITTED|");
1247 if (dp->flags & CACHE_FLAG_MATCHMORE)
1248 strcat(tmp, "MATCHMORE|");
1249 if (dp->flags & CACHE_FLAG_UNKNOWN)
1250 strcat(tmp, "UNKNOWN|");
1251 /* Trim trailing pipe */
1253 tmp[strlen(tmp) - 1] = '\0';
1255 strcpy(tmp, "(none)");
1257 pc = strchr(dp->peercontext, '@');
1259 pc = dp->peercontext;
1262 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
1263 if (dp->waiters[x] > -1)
1266 ast_cli(fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
1268 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
1271 ast_mutex_unlock(&dpcache_lock);
1272 return RESULT_SUCCESS;
1275 static char show_stats_usage[] =
1276 "Usage: iax show stats\n"
1277 " Display statistics on IAX channel driver.\n";
1280 static char show_cache_usage[] =
1281 "Usage: iax show cache\n"
1282 " Display currently cached IAX Dialplan results.\n";
1284 static struct ast_cli_entry cli_set_jitter =
1285 { { "iax2", "set", "jitter", NULL }, iax2_set_jitter, "Sets IAX jitter buffer", jitter_usage };
1287 static struct ast_cli_entry cli_show_stats =
1288 { { "iax2", "show", "stats", NULL }, iax2_show_stats, "Display IAX statistics", show_stats_usage };
1290 static struct ast_cli_entry cli_show_cache =
1291 { { "iax2", "show", "cache", NULL }, iax2_show_cache, "Display IAX cached dialplan", show_cache_usage };
1293 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p);
1295 #ifdef BRIDGE_OPTIMIZATION
1296 static unsigned int calc_fakestamp(struct chan_iax2_pvt *from, struct chan_iax2_pvt *to, unsigned int ts);
1298 static int forward_delivery(struct iax_frame *fr)
1300 struct chan_iax2_pvt *p1, *p2;
1301 p1 = iaxs[fr->callno];
1302 p2 = iaxs[p1->bridgecallno];
1307 /* Fix relative timestamp */
1308 fr->ts = calc_fakestamp(p1, p2, fr->ts);
1309 /* Now just send it send on the 2nd one
1310 with adjusted timestamp */
1311 return iax2_send(p2, &fr->af, fr->ts, -1, 0, 0, 0);
1315 static int schedule_delivery(struct iax_frame *fr, int reallydeliver, int updatehistory)
1318 int drops[MEMORY_SIZE];
1319 int min, max=0, maxone=0,y,z, match;
1320 /* ms is a measure of the "lateness" of the packet relative to the first
1321 packet we received, which always has a lateness of 1. Called by
1322 IAX thread, with iaxsl lock held. */
1323 ms = calc_rxstamp(iaxs[fr->callno]) - fr->ts;
1326 /* What likely happened here is that our counter has circled but we haven't
1327 gotten the update from the main packet. We'll just pretend that we did, and
1328 update the timestamp appropriately. */
1333 /* We got this packet out of order. Lets add 65536 to it to bring it into our new
1338 /* Rotate our history queue of "lateness". Don't worry about those initial
1339 zeros because the first entry will always be zero */
1340 if (updatehistory) {
1341 for (x=0;x<MEMORY_SIZE - 1;x++)
1342 iaxs[fr->callno]->history[x] = iaxs[fr->callno]->history[x+1];
1343 /* Add a history entry for this one */
1344 iaxs[fr->callno]->history[x] = ms;
1347 /* Initialize the minimum to reasonable values. It's too much
1348 work to do the same for the maximum, repeatedly */
1349 min=iaxs[fr->callno]->history[0];
1350 for (z=0;z < iax2_dropcount + 1;z++) {
1351 /* Start very optimistic ;-) */
1353 for (x=0;x<MEMORY_SIZE;x++) {
1354 if (max < iaxs[fr->callno]->history[x]) {
1355 /* We have a candidate new maximum value. Make
1356 sure it's not in our drop list */
1358 for (y=0;!match && (y<z);y++)
1359 match |= (drops[y] == x);
1361 /* It's not in our list, use it as the new maximum */
1362 max = iaxs[fr->callno]->history[x];
1368 /* On our first pass, find the minimum too */
1369 if (min > iaxs[fr->callno]->history[x])
1370 min = iaxs[fr->callno]->history[x];
1377 /* Just for reference, keep the "jitter" value, the difference between the
1378 earliest and the latest. */
1379 iaxs[fr->callno]->jitter = max - min;
1381 /* IIR filter for keeping track of historic jitter, but always increase
1382 historic jitter immediately for increase */
1384 if (iaxs[fr->callno]->jitter > iaxs[fr->callno]->historicjitter )
1385 iaxs[fr->callno]->historicjitter = iaxs[fr->callno]->jitter;
1387 iaxs[fr->callno]->historicjitter = GAMMA * (double)iaxs[fr->callno]->jitter + (1-GAMMA) *
1388 iaxs[fr->callno]->historicjitter;
1390 /* If our jitter buffer is too big (by a significant margin), then we slowly
1391 shrink it by about 1 ms each time to avoid letting the change be perceived */
1392 if (max < iaxs[fr->callno]->jitterbuffer - max_jitter_buffer)
1393 iaxs[fr->callno]->jitterbuffer -= 2;
1397 /* Constrain our maximum jitter buffer appropriately */
1398 if (max > min + maxjitterbuffer) {
1400 ast_log(LOG_DEBUG, "Constraining buffer from %d to %d + %d\n", max, min , maxjitterbuffer);
1401 max = min + maxjitterbuffer;
1405 /* If our jitter buffer is smaller than our maximum delay, grow the jitter
1406 buffer immediately to accomodate it (and a little more). */
1407 if (max > iaxs[fr->callno]->jitterbuffer)
1408 iaxs[fr->callno]->jitterbuffer = max
1409 /* + ((float)iaxs[fr->callno]->jitter) * 0.1 */;
1413 ast_log(LOG_DEBUG, "min = %d, max = %d, jb = %d, lateness = %d\n", min, max, iaxs[fr->callno]->jitterbuffer, ms);
1415 /* Subtract the lateness from our jitter buffer to know how long to wait
1416 before sending our packet. */
1417 ms = iaxs[fr->callno]->jitterbuffer - ms;
1419 if (!use_jitterbuffer)
1422 /* If the caller just wanted us to update, return now */
1428 ast_log(LOG_DEBUG, "Calculated ms is %d\n", ms);
1429 /* Don't deliver it more than 4 ms late */
1430 if ((ms > -4) || (fr->af.frametype != AST_FRAME_VOICE)) {
1434 ast_log(LOG_DEBUG, "Dropping voice packet since %d ms is, too old\n", ms);
1435 /* Free our iax frame */
1436 iax2_frame_free(fr);
1440 ast_log(LOG_DEBUG, "Scheduling delivery in %d ms\n", ms);
1441 fr->retrans = ast_sched_add(sched, ms, do_deliver, fr);
1446 static int iax2_transmit(struct iax_frame *fr)
1448 /* Lock the queue and place this packet at the end */
1451 /* By setting this to 0, the network thread will send it for us, and
1452 queue retransmission if necessary */
1454 ast_mutex_lock(&iaxq.lock);
1461 iaxq.tail->next = fr;
1462 fr->prev = iaxq.tail;
1466 ast_mutex_unlock(&iaxq.lock);
1467 /* Wake up the network thread */
1468 pthread_kill(netthreadid, SIGURG);
1474 static int iax2_digit(struct ast_channel *c, char digit)
1476 return send_command(c->pvt->pvt, AST_FRAME_DTMF, digit, 0, NULL, 0, -1);
1479 static int iax2_sendtext(struct ast_channel *c, char *text)
1482 return send_command(c->pvt->pvt, AST_FRAME_TEXT,
1483 0, 0, text, strlen(text) + 1, -1);
1486 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
1488 return send_command(c->pvt->pvt, AST_FRAME_IMAGE, img->subclass, 0, img->data, img->datalen, -1);
1491 static int iax2_sendhtml(struct ast_channel *c, int subclass, char *data, int datalen)
1493 return send_command(c->pvt->pvt, AST_FRAME_HTML, subclass, 0, data, datalen, -1);
1496 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
1498 struct chan_iax2_pvt *pvt = newchan->pvt->pvt;
1499 pvt->owner = newchan;
1503 static int create_addr(struct sockaddr_in *sin, int *capability, int *sendani, int *maxtime, char *peer, char *context, int *trunk, int *notransfer, char *secret, int seclen)
1506 struct iax2_peer *p;
1514 sin->sin_family = AF_INET;
1515 ast_mutex_lock(&peerl.lock);
1518 if (!strcasecmp(p->name, peer)) {
1520 if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
1521 (!p->maxms || ((p->lastms > 0) && (p->lastms <= p->maxms)))) {
1523 *sendani = p->sendani; /* Whether we transmit ANI */
1525 *maxtime = p->maxms; /* Max time they should take */
1527 strncpy(context, p->context, AST_MAX_EXTENSION - 1);
1531 *capability = p->capability;
1533 strncpy(secret, p->secret, seclen);
1534 if (p->addr.sin_addr.s_addr) {
1535 sin->sin_addr = p->addr.sin_addr;
1536 sin->sin_port = p->addr.sin_port;
1538 sin->sin_addr = p->defaddr.sin_addr;
1539 sin->sin_port = p->defaddr.sin_port;
1542 *notransfer=p->notransfer;
1548 ast_mutex_unlock(&peerl.lock);
1550 hp = gethostbyname(peer);
1552 memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
1553 sin->sin_port = htons(IAX_DEFAULT_PORTNO);
1556 ast_log(LOG_WARNING, "No such host: %s\n", peer);
1565 static int auto_congest(void *nothing)
1567 int callno = (int)(long)(nothing);
1568 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_CONGESTION };
1569 ast_mutex_lock(&iaxsl[callno]);
1571 iaxs[callno]->initid = -1;
1572 iax2_queue_frame(callno, &f);
1573 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
1575 ast_mutex_unlock(&iaxsl[callno]);
1579 static int iax2_call(struct ast_channel *c, char *dest, int timeout)
1581 struct sockaddr_in sin;
1586 char *secret = NULL;
1589 char *l=NULL, *n=NULL;
1590 struct iax_ie_data ied;
1591 char myrdest [5] = "s";
1592 char context[AST_MAX_EXTENSION] ="";
1593 char *portno = NULL;
1595 struct chan_iax2_pvt *p = c->pvt->pvt;
1597 char storedsecret[80];
1598 if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
1599 ast_log(LOG_WARNING, "Line is already in use (%s)?\n", c->name);
1602 strncpy(host, dest, sizeof(host)-1);
1604 strsep(&stringp, "/");
1605 /* If no destination extension specified, use 's' */
1606 rdest = strsep(&stringp, "/");
1610 /* Check for trailing options */
1611 opts = strsep(&stringp, "/");
1616 strsep(&stringp, "@");
1617 rcontext = strsep(&stringp, "@");
1619 strsep(&stringp, "@");
1620 username = strsep(&stringp, "@");
1622 /* Really the second argument is the host, not the username */
1630 username = strsep(&stringp, ":");
1631 secret = strsep(&stringp, ":");
1634 if (strsep(&stringp, ":")) {
1636 strsep(&stringp, ":");
1637 portno = strsep(&stringp, ":");
1639 if (create_addr(&sin, NULL, NULL, NULL, hname, context, NULL, NULL, storedsecret, sizeof(storedsecret) - 1)) {
1640 ast_log(LOG_WARNING, "No address associated with '%s'\n", hname);
1643 /* Keep track of the context for outgoing calls too */
1644 strncpy(c->context, context, sizeof(c->context) - 1);
1646 sin.sin_port = htons(atoi(portno));
1649 strncpy(cid, c->callerid, sizeof(cid) - 1);
1650 ast_callerid_parse(cid, &n, &l);
1652 ast_shrink_phone_number(l);
1654 /* Now build request */
1655 memset(&ied, 0, sizeof(ied));
1656 /* On new call, first IE MUST be IAX version of caller */
1657 iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
1658 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, rdest);
1659 if (strchr(opts, 'a')) {
1660 /* Request auto answer */
1661 iax_ie_append(&ied, IAX_IE_AUTOANSWER);
1664 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
1666 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n);
1667 if (p->sendani && c->ani) {
1669 strncpy(cid, c->ani, sizeof(cid) - 1);
1670 ast_callerid_parse(cid, &n, &l);
1672 ast_shrink_phone_number(l);
1673 iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, l);
1676 if (c->language && strlen(c->language))
1677 iax_ie_append_str(&ied, IAX_IE_LANGUAGE, c->language);
1678 if (c->dnid && strlen(c->dnid))
1679 iax_ie_append_str(&ied, IAX_IE_DNID, c->dnid);
1681 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, rcontext);
1683 iax_ie_append_str(&ied, IAX_IE_USERNAME, username);
1684 if (!secret && strlen(storedsecret))
1685 secret = storedsecret;
1687 if (secret[0] == '[') {
1688 /* This is an RSA key, not a normal secret */
1689 strncpy(p->outkey, secret + 1, sizeof(p->secret)-1);
1690 if (strlen(p->outkey)) {
1691 p->outkey[strlen(p->outkey) - 1] = '\0';
1694 strncpy(p->secret, secret, sizeof(p->secret)-1);
1696 iax_ie_append_int(&ied, IAX_IE_FORMAT, c->nativeformats);
1697 iax_ie_append_int(&ied, IAX_IE_CAPABILITY, p->capability);
1698 iax_ie_append_short(&ied, IAX_IE_ADSICPE, c->adsicpe);
1699 /* Transmit the string in a "NEW" request */
1701 /* XXX We have no equivalent XXX */
1702 if (option_verbose > 2)
1703 ast_verbose(VERBOSE_PREFIX_3 "Calling using options '%s'\n", requeststr);
1706 /* Initialize pingtime and auto-congest time */
1707 p->pingtime = p->maxtime / 2;
1708 p->initid = ast_sched_add(sched, p->maxtime * 2, auto_congest, (void *)(long)p->callno);
1710 send_command(p, AST_FRAME_IAX,
1711 IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
1712 ast_setstate(c, AST_STATE_RINGING);
1716 static int iax2_hangup(struct ast_channel *c)
1718 struct chan_iax2_pvt *pvt = c->pvt->pvt;
1722 callno = pvt->callno;
1723 ast_mutex_lock(&iaxsl[callno]);
1724 ast_log(LOG_DEBUG, "We're hanging up %s now...\n", c->name);
1725 alreadygone = pvt->alreadygone;
1726 /* Send the hangup unless we have had a transmission error or are already gone */
1727 if (!pvt->error && !alreadygone)
1728 send_command_final(pvt, AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, NULL, 0, -1);
1729 /* Explicitly predestroy it */
1730 iax2_predestroy_nolock(callno);
1731 /* If we were already gone to begin with, destroy us now */
1733 ast_log(LOG_DEBUG, "Really destroying %s now...\n", c->name);
1734 iax2_destroy_nolock(callno);
1736 ast_mutex_unlock(&iaxsl[callno]);
1738 if (option_verbose > 2)
1739 ast_verbose(VERBOSE_PREFIX_3 "Hungup '%s'\n", c->name);
1743 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
1745 struct ast_option_header *h;
1747 h = malloc(datalen + sizeof(struct ast_option_header));
1749 h->flag = AST_OPTION_FLAG_REQUEST;
1750 h->option = htons(option);
1751 memcpy(h->data, data, datalen);
1752 res = send_command((struct chan_iax2_pvt *)c->pvt->pvt, AST_FRAME_CONTROL,
1753 AST_CONTROL_OPTION, 0, (char *)h, datalen + sizeof(struct ast_option_header), -1);
1757 ast_log(LOG_WARNING, "Out of memory\n");
1760 static struct ast_frame *iax2_read(struct ast_channel *c)
1762 static struct ast_frame f = { AST_FRAME_NULL, };
1763 ast_log(LOG_NOTICE, "I should never be called!\n");
1767 static int iax2_start_transfer(struct ast_channel *c0, struct ast_channel *c1)
1770 struct iax_ie_data ied0;
1771 struct iax_ie_data ied1;
1772 struct chan_iax2_pvt *p0 = c0->pvt->pvt;
1773 struct chan_iax2_pvt *p1 = c1->pvt->pvt;
1774 unsigned int transferid = rand();
1775 memset(&ied0, 0, sizeof(ied0));
1776 iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &p1->addr);
1777 iax_ie_append_short(&ied0, IAX_IE_CALLNO, p1->peercallno);
1778 iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, transferid);
1780 memset(&ied1, 0, sizeof(ied1));
1781 iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &p0->addr);
1782 iax_ie_append_short(&ied1, IAX_IE_CALLNO, p0->peercallno);
1783 iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, transferid);
1785 res = send_command(p0, AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
1788 res = send_command(p1, AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
1791 p0->transferring = TRANSFER_BEGIN;
1792 p1->transferring = TRANSFER_BEGIN;
1796 static int iax2_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
1798 struct ast_channel *cs[3];
1799 struct ast_channel *who;
1802 int transferstarted=0;
1803 struct ast_frame *f;
1804 struct chan_iax2_pvt *p0 = c0->pvt->pvt;
1805 struct chan_iax2_pvt *p1 = c1->pvt->pvt;
1806 struct timeval waittimer = {0, 0}, tv;
1808 /* Put them in native bridge mode */
1809 p0->bridgecallno = p1->callno;
1810 p1->bridgecallno = p0->callno;
1812 /* If not, try to bridge until we can execute a transfer, if we can */
1815 for (/* ever */;;) {
1816 /* Check in case we got masqueraded into */
1817 if ((c0->type != type) || (c1->type != type)) {
1818 if (option_verbose > 2)
1819 ast_verbose(VERBOSE_PREFIX_3 "Can't masquerade, we're different...\n");
1820 /* Remove from native mode */
1821 p0->bridgecallno = 0;
1822 p1->bridgecallno = 0;
1825 if (c0->nativeformats != c1->nativeformats) {
1826 ast_verbose(VERBOSE_PREFIX_3 "Operating with different codecs, can't native bridge...\n");
1827 /* Remove from native mode */
1828 p0->bridgecallno = 0;
1829 p1->bridgecallno = 0;
1832 /* check if transfered and if we really want native bridging */
1833 if (!transferstarted && !p0->notransfer && !p1->notransfer) {
1834 /* Try the transfer */
1835 if (iax2_start_transfer(c0, c1))
1836 ast_log(LOG_WARNING, "Unable to start the transfer\n");
1837 transferstarted = 1;
1840 if ((p0->transferring == TRANSFER_RELEASED) && (p1->transferring == TRANSFER_RELEASED)) {
1841 /* Call has been transferred. We're no longer involved */
1842 gettimeofday(&tv, NULL);
1843 if (!waittimer.tv_sec && !waittimer.tv_usec) {
1844 waittimer.tv_sec = tv.tv_sec;
1845 waittimer.tv_usec = tv.tv_usec;
1846 } else if (tv.tv_sec - waittimer.tv_sec > IAX_LINGER_TIMEOUT) {
1847 c0->_softhangup |= AST_SOFTHANGUP_DEV;
1848 c1->_softhangup |= AST_SOFTHANGUP_DEV;
1856 who = ast_waitfor_n(cs, 2, &to);
1867 if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
1873 if ((f->frametype == AST_FRAME_VOICE) ||
1874 (f->frametype == AST_FRAME_TEXT) ||
1875 (f->frametype == AST_FRAME_VIDEO) ||
1876 (f->frametype == AST_FRAME_IMAGE) ||
1877 (f->frametype == AST_FRAME_DTMF)) {
1878 if ((f->frametype == AST_FRAME_DTMF) &&
1879 (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
1881 if ((flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
1884 /* Take out of conference mode */
1886 /* Remove from native mode */
1892 if (flags & AST_BRIDGE_DTMF_CHANNEL_1) {
1896 /* Remove from native mode */
1903 ast_log(LOG_DEBUG, "Read from %s\n", who->name);
1905 ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
1917 /* Swap who gets priority */
1922 p0->bridgecallno = 0;
1923 p1->bridgecallno = 0;
1927 static int iax2_answer(struct ast_channel *c)
1929 struct chan_iax2_pvt *pvt = c->pvt->pvt;
1931 ast_log(LOG_DEBUG, "Answering\n");
1932 return send_command(pvt, AST_FRAME_CONTROL, AST_CONTROL_ANSWER, 0, NULL, 0, -1);
1935 static int iax2_indicate(struct ast_channel *c, int condition)
1937 struct chan_iax2_pvt *pvt = c->pvt->pvt;
1939 ast_log(LOG_DEBUG, "Indicating condition %d\n", condition);
1940 return send_command(pvt, AST_FRAME_CONTROL, condition, 0, NULL, 0, -1);
1943 static int iax2_transfer(struct ast_channel *c, char *dest)
1945 struct chan_iax2_pvt *pvt = c->pvt->pvt;
1946 struct iax_ie_data ied;
1947 char tmp[256] = "", *context;
1948 strncpy(tmp, dest, sizeof(tmp) - 1);
1949 context = strchr(tmp, '@');
1954 memset(&ied, 0, sizeof(ied));
1955 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, tmp);
1957 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, context);
1959 ast_log(LOG_DEBUG, "Transferring '%s' to '%s'\n", c->name, dest);
1960 return send_command(pvt, AST_FRAME_IAX, IAX_COMMAND_TRANSFER, 0, ied.buf, ied.pos, -1);
1964 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
1966 static int iax2_getpeertrunk(struct sockaddr_in sin)
1968 struct iax2_peer *peer;
1970 ast_mutex_lock(&peerl.lock);
1973 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
1974 (peer->addr.sin_port == sin.sin_port)) {
1980 ast_mutex_unlock(&peerl.lock);
1984 static struct ast_channel *ast_iax2_new(struct chan_iax2_pvt *i, int state, int capability)
1986 struct ast_channel *tmp;
1987 tmp = ast_channel_alloc(1);
1989 if (strlen(i->username))
1990 snprintf(tmp->name, sizeof(tmp->name), "IAX2[%s@%s]/%d", i->username, i->host, i->callno);
1992 snprintf(tmp->name, sizeof(tmp->name), "IAX2[%s]/%d", i->host, i->callno);
1994 /* We can support any format by default, until we get restricted */
1995 tmp->nativeformats = capability;
1996 tmp->readformat = 0;
1997 tmp->writeformat = 0;
1999 tmp->pvt->send_digit = iax2_digit;
2000 tmp->pvt->send_text = iax2_sendtext;
2001 tmp->pvt->send_image = iax2_sendimage;
2002 tmp->pvt->send_html = iax2_sendhtml;
2003 tmp->pvt->call = iax2_call;
2004 tmp->pvt->hangup = iax2_hangup;
2005 tmp->pvt->answer = iax2_answer;
2006 tmp->pvt->read = iax2_read;
2007 tmp->pvt->write = iax2_write;
2008 tmp->pvt->write_video = iax2_write;
2009 tmp->pvt->indicate = iax2_indicate;
2010 tmp->pvt->setoption = iax2_setoption;
2011 tmp->pvt->bridge = iax2_bridge;
2012 tmp->pvt->transfer = iax2_transfer;
2013 if (strlen(i->callerid))
2014 tmp->callerid = strdup(i->callerid);
2016 tmp->ani = strdup(i->ani);
2017 if (strlen(i->language))
2018 strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
2019 if (strlen(i->dnid))
2020 tmp->dnid = strdup(i->dnid);
2021 if (strlen(i->accountcode))
2022 strncpy(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode)-1);
2024 tmp->amaflags = i->amaflags;
2025 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
2026 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
2027 tmp->adsicpe = i->peeradsicpe;
2028 tmp->pvt->fixup = iax2_fixup;
2030 i->capability = capability;
2031 ast_setstate(tmp, state);
2032 ast_mutex_lock(&usecnt_lock);
2034 ast_mutex_unlock(&usecnt_lock);
2035 ast_update_use_count();
2036 if (state != AST_STATE_DOWN) {
2037 if (ast_pbx_start(tmp)) {
2038 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
2047 static unsigned int calc_txpeerstamp(struct iax2_peer *peer)
2050 unsigned int mssincetx;
2052 gettimeofday(&tv, NULL);
2053 mssincetx = (tv.tv_sec - peer->lasttxtime.tv_sec) * 1000 + (tv.tv_usec - peer->lasttxtime.tv_usec) / 1000;
2054 if (mssincetx > 5000) {
2055 /* If it's been at least 5 seconds since the last time we transmitted on this trunk, reset our timers */
2056 peer->txtrunktime.tv_sec = tv.tv_sec;
2057 peer->txtrunktime.tv_usec = tv.tv_usec;
2059 /* Update last transmit time now */
2060 peer->lasttxtime.tv_sec = tv.tv_sec;
2061 peer->lasttxtime.tv_usec = tv.tv_usec;
2063 /* Calculate ms offset */
2064 ms = (tv.tv_sec - peer->txtrunktime.tv_sec) * 1000 + (tv.tv_usec - peer->txtrunktime.tv_usec) / 1000;
2066 /* We never send the same timestamp twice, so fudge a little if we must */
2067 if (ms == peer->lastsent)
2068 ms = peer->lastsent + 1;
2069 peer->lastsent = ms;
2073 static unsigned int fix_peerts(struct iax2_peer *peer, int callno, unsigned int ts)
2075 long ms; /* NOT unsigned */
2076 if (!iaxs[callno]->rxcore.tv_sec && !iaxs[callno]->rxcore.tv_usec) {
2077 /* Initialize rxcore time if appropriate */
2078 gettimeofday(&iaxs[callno]->rxcore, NULL);
2080 /* Calculate difference between trunk and channel */
2081 ms = (peer->rxtrunktime.tv_sec - iaxs[callno]->rxcore.tv_sec) * 1000 +
2082 (peer->rxtrunktime.tv_usec - iaxs[callno]->rxcore.tv_usec) / 1000;
2083 /* Return as the sum of trunk time and the difference between trunk and real time */
2087 static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts)
2091 if (!p->offset.tv_sec && !p->offset.tv_usec)
2092 gettimeofday(&p->offset, NULL);
2093 /* If the timestamp is specified, just send it as is */
2096 gettimeofday(&tv, NULL);
2097 ms = (tv.tv_sec - p->offset.tv_sec) * 1000 + (tv.tv_usec - p->offset.tv_usec) / 1000;
2098 /* We never send the same timestamp twice, so fudge a little if we must */
2099 if (ms <= p->lastsent)
2100 ms = p->lastsent + 1;
2105 #ifdef BRIDGE_OPTIMIZATION
2106 static unsigned int calc_fakestamp(struct chan_iax2_pvt *p1, struct chan_iax2_pvt *p2, unsigned int fakets)
2109 /* Receive from p1, send to p2 */
2111 /* Setup rxcore if necessary on outgoing channel */
2112 if (!p1->rxcore.tv_sec && !p1->rxcore.tv_usec)
2113 gettimeofday(&p1->rxcore, NULL);
2115 /* Setup txcore if necessary on outgoing channel */
2116 if (!p2->offset.tv_sec && !p2->offset.tv_usec)
2117 gettimeofday(&p2->offset, NULL);
2119 /* Now, ts is the timestamp of the original packet in the orignal context.
2120 Adding rxcore to it gives us when we would want the packet to be delivered normally.
2121 Subtracting txcore of the outgoing channel gives us what we'd expect */
2123 ms = (p1->rxcore.tv_sec - p2->offset.tv_sec) * 1000 + (p1->rxcore.tv_usec - p2->offset.tv_usec) / 1000;
2125 if (fakets <= p2->lastsent)
2126 fakets = p2->lastsent + 1;
2127 p2->lastsent = fakets;
2132 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p)
2134 /* Returns where in "receive time" we are */
2137 /* Setup rxcore if necessary */
2138 if (!p->rxcore.tv_sec && !p->rxcore.tv_usec)
2139 gettimeofday(&p->rxcore, NULL);
2141 gettimeofday(&tv, NULL);
2142 ms = (tv.tv_sec - p->rxcore.tv_sec) * 1000 + (tv.tv_usec - p->rxcore.tv_usec) / 1000;
2146 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final)
2148 /* Queue a packet for delivery on a given private structure. Use "ts" for
2149 timestamp, or calculate if ts is 0. Send immediately without retransmission
2150 or delayed, with retransmission */
2151 struct ast_iax2_full_hdr *fh;
2152 struct ast_iax2_mini_hdr *mh;
2153 struct ast_iax2_video_hdr *vh;
2155 struct iax_frame fr2;
2156 unsigned char buffer[4096];
2158 struct iax_frame *fr;
2161 unsigned int lastsent;
2165 ast_log(LOG_WARNING, "No private structure for packet?\n");
2169 lastsent = pvt->lastsent;
2171 /* Calculate actual timestamp */
2172 fts = calc_timestamp(pvt, ts);
2174 if ((pvt->trunk || ((fts & 0xFFFF0000L) == (lastsent & 0xFFFF0000L)))
2175 /* High two bits are the same on timestamp, or sending on a trunk */ &&
2176 (f->frametype == AST_FRAME_VOICE)
2177 /* is a voice frame */ &&
2178 (f->subclass == pvt->svoiceformat)
2179 /* is the same type */ ) {
2180 /* Force immediate rather than delayed transmission */
2182 /* Mark that mini-style frame is appropriate */
2185 if (((fts & 0xFFFF8000L) == (lastsent & 0xFFFF8000L)) &&
2186 (f->frametype == AST_FRAME_VIDEO) &&
2187 ((f->subclass & ~0x1) == pvt->svideoformat)) {
2191 /* Allocate an iax_frame */
2195 fr = iax_frame_new(DIRECTION_OUTGRESS, f->datalen);
2197 ast_log(LOG_WARNING, "Out of memory\n");
2200 /* Copy our prospective frame into our immediate or retransmitted wrapper */
2201 iax_frame_wrap(fr, f);
2205 ast_log(LOG_WARNING, "timestamp is 0?\n");
2207 iax2_frame_free(fr);
2210 fr->callno = pvt->callno;
2211 fr->transfer = transfer;
2214 /* We need a full frame */
2218 fr->oseqno = pvt->oseqno++;
2219 fr->iseqno = pvt->iseqno;
2220 fh = (struct ast_iax2_full_hdr *)(fr->af.data - sizeof(struct ast_iax2_full_hdr));
2221 fh->scallno = htons(fr->callno | IAX_FLAG_FULL);
2222 fh->ts = htonl(fr->ts);
2223 fh->oseqno = fr->oseqno;
2227 fh->iseqno = fr->iseqno;
2228 /* Keep track of the last thing we've acknowledged */
2229 pvt->aseqno = fr->iseqno;
2230 fh->type = fr->af.frametype & 0xFF;
2231 if (fr->af.frametype == AST_FRAME_VIDEO)
2232 fh->csub = compress_subclass(fr->af.subclass & ~0x1) | ((fr->af.subclass & 0x1) << 6);
2234 fh->csub = compress_subclass(fr->af.subclass);
2236 fr->dcallno = pvt->transfercallno;
2238 fr->dcallno = pvt->peercallno;
2239 fh->dcallno = htons(fr->dcallno);
2240 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_full_hdr);
2243 /* Retry after 2x the ping time has passed */
2244 fr->retrytime = pvt->pingtime * 2;
2245 if (fr->retrytime < MIN_RETRY_TIME)
2246 fr->retrytime = MIN_RETRY_TIME;
2247 if (fr->retrytime > MAX_RETRY_TIME)
2248 fr->retrytime = MAX_RETRY_TIME;
2249 /* Acks' don't get retried */
2250 if ((f->frametype == AST_FRAME_IAX) && (f->subclass == IAX_COMMAND_ACK))
2252 if (f->frametype == AST_FRAME_VOICE) {
2253 pvt->svoiceformat = f->subclass;
2255 if (f->frametype == AST_FRAME_VIDEO) {
2256 pvt->svideoformat = f->subclass & ~0x1;
2259 res = send_packet(fr);
2261 res = iax2_transmit(fr);
2264 /* Queue for transmission in a meta frame */
2265 if ((sizeof(pvt->trunkdata) - pvt->trunkdatalen) >= fr->af.datalen) {
2266 memcpy(pvt->trunkdata + pvt->trunkdatalen, fr->af.data, fr->af.datalen);
2267 pvt->trunkdatalen += fr->af.datalen;
2269 pvt->trunkerror = 0;
2271 if (!pvt->trunkerror)
2272 ast_log(LOG_WARNING, "Out of trunk data space on call number %d, dropping\n", pvt->callno);
2273 pvt->trunkerror = 1;
2276 } else if (fr->af.frametype == AST_FRAME_VIDEO) {
2277 /* Video frame have no sequence number */
2280 vh = (struct ast_iax2_video_hdr *)(fr->af.data - sizeof(struct ast_iax2_video_hdr));
2282 vh->callno = htons(0x8000 | fr->callno);
2283 vh->ts = htons((fr->ts & 0x7FFF) | (fr->af.subclass & 0x1 ? 0x8000 : 0));
2284 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_video_hdr);
2287 res = send_packet(fr);
2289 /* Mini-frames have no sequence number */
2292 /* Mini frame will do */
2293 mh = (struct ast_iax2_mini_hdr *)(fr->af.data - sizeof(struct ast_iax2_mini_hdr));
2294 mh->callno = htons(fr->callno);
2295 mh->ts = htons(fr->ts & 0xFFFF);
2296 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_mini_hdr);
2299 res = send_packet(fr);
2307 static int iax2_show_users(int fd, int argc, char *argv[])
2309 #define FORMAT "%-15.15s %-15.15s %-15.15s %-15.15s %-5.5s\n"
2310 #define FORMAT2 "%-15.15s %-15.15s %-15.15d %-15.15s %-5.5s\n"
2311 struct iax2_user *user;
2313 return RESULT_SHOWUSAGE;
2314 ast_mutex_lock(&userl.lock);
2315 ast_cli(fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C");
2316 for(user=userl.users;user;user=user->next) {
2317 ast_cli(fd, FORMAT2, user->name, user->secret, user->authmethods,
2318 user->contexts ? user->contexts->context : context,
2319 user->ha ? "Yes" : "No");
2321 ast_mutex_unlock(&userl.lock);
2322 return RESULT_SUCCESS;
2327 static int iax2_show_peers(int fd, int argc, char *argv[])
2329 #define FORMAT2 "%-15.15s %-15.15s %s %-15.15s %-8s %-10s\n"
2330 #define FORMAT "%-15.15s %-15.15s %s %-15.15s %-5d%s %-10s\n"
2331 struct iax2_peer *peer;
2332 char name[256] = "";
2333 int registeredonly=0;
2334 if ((argc != 3) && (argc != 4))
2335 return RESULT_SHOWUSAGE;
2337 if (!strcasecmp(argv[3], "registered")) {
2340 return RESULT_SHOWUSAGE;
2342 ast_mutex_lock(&peerl.lock);
2343 ast_cli(fd, FORMAT2, "Name/Username", "Host", " ", "Mask", "Port", "Status");
2344 for (peer = peerl.peers;peer;peer = peer->next) {
2347 if (registeredonly && !peer->addr.sin_addr.s_addr)
2349 if (strlen(peer->username))
2350 snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
2352 strncpy(name, peer->name, sizeof(name) - 1);
2354 if (peer->lastms < 0)
2355 strcpy(status, "UNREACHABLE");
2356 else if (peer->lastms > peer->maxms)
2357 snprintf(status, sizeof(status), "LAGGED (%d ms)", peer->lastms);
2358 else if (peer->lastms)
2359 snprintf(status, sizeof(status), "OK (%d ms)", peer->lastms);
2361 strcpy(status, "UNKNOWN");
2363 strcpy(status, "Unmonitored");
2364 strncpy(nm, inet_ntoa(peer->mask), sizeof(nm)-1);
2365 ast_cli(fd, FORMAT, name,
2366 peer->addr.sin_addr.s_addr ? inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
2367 peer->dynamic ? "(D)" : "(S)",
2369 ntohs(peer->addr.sin_port), peer->trunk ? "(T)" : " ", status);
2371 ast_mutex_unlock(&peerl.lock);
2372 return RESULT_SUCCESS;
2377 /* JDG: callback to display iax peers in manager */
2378 static int manager_iax2_show_peers( struct mansession *s, struct message *m )
2380 char *a[] = { "iax2", "show", "users" };
2382 ret = iax2_show_peers( s->fd, 3, a );
2383 ast_cli( s->fd, "\r\n" );
2387 static char *regstate2str(int regstate)
2390 case REG_STATE_UNREGISTERED:
2391 return "Unregistered";
2392 case REG_STATE_REGSENT:
2393 return "Request Sent";
2394 case REG_STATE_AUTHSENT:
2395 return "Auth. Sent";
2396 case REG_STATE_REGISTERED:
2397 return "Registered";
2398 case REG_STATE_REJECTED:
2400 case REG_STATE_TIMEOUT:
2402 case REG_STATE_NOAUTH:
2403 return "No Authentication";
2409 static int iax2_show_registry(int fd, int argc, char *argv[])
2411 #define FORMAT2 "%-20.20s %-10.10s %-20.20s %8.8s %s\n"
2412 #define FORMAT "%-20.20s %-10.10s %-20.20s %8d %s\n"
2413 struct iax2_registry *reg;
2417 return RESULT_SHOWUSAGE;
2418 ast_mutex_lock(&peerl.lock);
2419 ast_cli(fd, FORMAT2, "Host", "Username", "Perceived", "Refresh", "State");
2420 for (reg = registrations;reg;reg = reg->next) {
2421 snprintf(host, sizeof(host), "%s:%d", inet_ntoa(reg->addr.sin_addr), ntohs(reg->addr.sin_port));
2422 if (reg->us.sin_addr.s_addr)
2423 snprintf(perceived, sizeof(perceived), "%s:%d", inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
2425 strcpy(perceived, "<Unregistered>");
2426 ast_cli(fd, FORMAT, host,
2427 reg->username, perceived, reg->refresh, regstate2str(reg->regstate));
2429 ast_mutex_unlock(&peerl.lock);
2430 return RESULT_SUCCESS;
2435 static int iax2_show_channels(int fd, int argc, char *argv[])
2437 #define FORMAT2 "%-15.15s %-10.10s %-11.11s %-11.11s %-7.7s %-6.6s %s\n"
2438 #define FORMAT "%-15.15s %-10.10s %5.5d/%5.5d %5.5d/%5.5d %-5.5dms %-4.4dms %-6.6s\n"
2442 return RESULT_SHOWUSAGE;
2443 ast_cli(fd, FORMAT2, "Peer", "Username", "ID (Lo/Rem)", "Seq (Tx/Rx)", "Lag", "Jitter", "Format");
2444 for (x=0;x<IAX_MAX_CALLS;x++) {
2445 ast_mutex_lock(&iaxsl[x]);
2447 ast_cli(fd, FORMAT, inet_ntoa(iaxs[x]->addr.sin_addr),
2448 strlen(iaxs[x]->username) ? iaxs[x]->username : "(None)",
2449 iaxs[x]->callno, iaxs[x]->peercallno,
2450 iaxs[x]->oseqno, iaxs[x]->iseqno,
2453 ast_getformatname(iaxs[x]->voiceformat) );
2456 ast_mutex_unlock(&iaxsl[x]);
2458 ast_cli(fd, "%d active IAX channel(s)\n", numchans);
2459 return RESULT_SUCCESS;
2464 static int iax2_do_trunk_debug(int fd, int argc, char *argv[])
2467 return RESULT_SHOWUSAGE;
2469 ast_cli(fd, "IAX2 Trunk Debug Requested\n");
2470 return RESULT_SUCCESS;
2473 static int iax2_do_debug(int fd, int argc, char *argv[])
2476 return RESULT_SHOWUSAGE;
2478 ast_cli(fd, "IAX2 Debugging Enabled\n");
2479 return RESULT_SUCCESS;
2482 static int iax2_no_debug(int fd, int argc, char *argv[])
2485 return RESULT_SHOWUSAGE;
2487 ast_cli(fd, "IAX2 Debugging Disabled\n");
2488 return RESULT_SUCCESS;
2493 static char show_users_usage[] =
2494 "Usage: iax2 show users\n"
2495 " Lists all users known to the IAX (Inter-Asterisk eXchange rev 2) subsystem.\n";
2497 static char show_channels_usage[] =
2498 "Usage: iax2 show channels\n"
2499 " Lists all currently active IAX channels.\n";
2501 static char show_peers_usage[] =
2502 "Usage: iax2 show peers\n"
2503 " Lists all known IAX peers.\n";
2505 static char show_reg_usage[] =
2506 "Usage: iax2 show registry\n"
2507 " Lists all registration requests and status.\n";
2509 static char debug_usage[] =
2510 "Usage: iax2 debug\n"
2511 " Enables dumping of IAX packets for debugging purposes\n";
2513 static char no_debug_usage[] =
2514 "Usage: iax2 no debug\n"
2515 " Disables dumping of IAX packets for debugging purposes\n";
2517 static char debug_trunk_usage[] =
2518 "Usage: iax2 trunk debug\n"
2519 " Requests current status of IAX trunking\n";
2521 static struct ast_cli_entry cli_show_users =
2522 { { "iax2", "show", "users", NULL }, iax2_show_users, "Show defined IAX users", show_users_usage };
2523 static struct ast_cli_entry cli_show_channels =
2524 { { "iax2", "show", "channels", NULL }, iax2_show_channels, "Show active IAX channels", show_channels_usage };
2525 static struct ast_cli_entry cli_show_peers =
2526 { { "iax2", "show", "peers", NULL }, iax2_show_peers, "Show defined IAX peers", show_peers_usage };
2527 static struct ast_cli_entry cli_show_registry =
2528 { { "iax2", "show", "registry", NULL }, iax2_show_registry, "Show IAX registration status", show_reg_usage };
2529 static struct ast_cli_entry cli_debug =
2530 { { "iax2", "debug", NULL }, iax2_do_debug, "Enable IAX debugging", debug_usage };
2531 static struct ast_cli_entry cli_trunk_debug =
2532 { { "iax2", "trunk", "debug", NULL }, iax2_do_trunk_debug, "Request IAX trunk debug", debug_trunk_usage };
2533 static struct ast_cli_entry cli_no_debug =
2534 { { "iax2", "no", "debug", NULL }, iax2_no_debug, "Disable IAX debugging", no_debug_usage };
2536 static int iax2_write(struct ast_channel *c, struct ast_frame *f)
2538 struct chan_iax2_pvt *i = c->pvt->pvt;
2541 /* If there's an outstanding error, return failure now */
2543 ast_log(LOG_DEBUG, "Write error: %s\n", strerror(errno));
2546 /* If it's already gone, just return */
2549 /* Don't waste bandwidth sending null frames */
2550 if (f->frametype == AST_FRAME_NULL)
2552 /* If we're quelching voice, don't bother sending it */
2553 if ((f->frametype == AST_FRAME_VOICE) && i->quelch)
2555 if (!(i->state & IAX_STATE_STARTED))
2557 /* Simple, just queue for transmission */
2558 return iax2_send(i, f, 0, -1, 0, 0, 0);
2561 static int __send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno,
2562 int now, int transfer, int final)
2566 f.subclass = command;
2567 f.datalen = datalen;
2571 f.src = __FUNCTION__;
2573 return iax2_send(i, &f, ts, seqno, now, transfer, final);
2576 static int send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2578 return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 0);
2581 #ifdef BRIDGE_OPTIMIZATION
2582 static int forward_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2584 return __send_command(iaxs[i->bridgecallno], type, command, ts, data, datalen, seqno, 0, 0, 0);
2588 static int send_command_final(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2590 /* It is assumed that the callno has already been locked */
2591 iax2_predestroy_nolock(i->callno);
2592 return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 1);
2595 static int send_command_immediate(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2597 return __send_command(i, type, command, ts, data, datalen, seqno, 1, 0, 0);
2600 static int send_command_transfer(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen)
2602 return __send_command(i, type, command, ts, data, datalen, 0, 0, 1, 0);
2605 static int apply_context(struct iax2_context *con, char *context)
2608 if (!strcmp(con->context, context))
2616 static int check_access(int callno, struct sockaddr_in *sin, struct iax_ies *ies)
2618 /* Start pessimistic */
2621 struct iax2_user *user;
2622 int gotcapability=0;
2625 if (ies->called_number)
2626 strncpy(iaxs[callno]->exten, ies->called_number, sizeof(iaxs[callno]->exten) - 1);
2627 if (ies->calling_number) {
2628 if (ies->calling_name)
2629 snprintf(iaxs[callno]->callerid, sizeof(iaxs[callno]->callerid), "\"%s\" <%s>", ies->calling_name, ies->calling_number);
2631 strncpy(iaxs[callno]->callerid, ies->calling_number, sizeof(iaxs[callno]->callerid) - 1);
2632 } else if (ies->calling_name)
2633 strncpy(iaxs[callno]->callerid, ies->calling_name, sizeof(iaxs[callno]->callerid) - 1);
2634 if (ies->calling_ani)
2635 strncpy(iaxs[callno]->ani, ies->calling_ani, sizeof(iaxs[callno]->ani) - 1);
2637 strncpy(iaxs[callno]->dnid, ies->dnid, sizeof(iaxs[callno]->dnid)-1);
2638 if (ies->called_context)
2639 strncpy(iaxs[callno]->context, ies->called_context, sizeof(iaxs[callno]->context)-1);
2641 strncpy(iaxs[callno]->language, ies->language, sizeof(iaxs[callno]->language)-1);
2643 strncpy(iaxs[callno]->username, ies->username, sizeof(iaxs[callno]->username)-1);
2645 iaxs[callno]->peerformat = ies->format;
2647 iaxs[callno]->peeradsicpe = ies->adsicpe;
2648 if (ies->capability) {
2650 iaxs[callno]->peercapability = ies->capability;
2653 version = ies->version;
2655 iaxs[callno]->peercapability = iaxs[callno]->peerformat;
2656 if (version > IAX_PROTO_VERSION) {
2657 ast_log(LOG_WARNING, "Peer '%s' has too new a protocol version (%d) for me\n",
2658 inet_ntoa(sin->sin_addr), version);
2661 ast_mutex_lock(&userl.lock);
2662 /* Search the userlist for a compatible entry, and fill in the rest */
2665 if ((!strlen(iaxs[callno]->username) || /* No username specified */
2666 !strcmp(iaxs[callno]->username, user->name)) /* Or this username specified */
2667 && ast_apply_ha(user->ha, sin) /* Access is permitted from this IP */
2668 && (!strlen(iaxs[callno]->context) || /* No context specified */
2669 apply_context(user->contexts, iaxs[callno]->context))) { /* Context is permitted */
2670 /* We found our match (use the first) */
2672 /* Store the requested username if not specified */
2673 if (!strlen(iaxs[callno]->username))
2674 strncpy(iaxs[callno]->username, user->name, sizeof(iaxs[callno]->username)-1);
2675 /* Store whether this is a trunked call, too, of course, and move if appropriate */
2676 iaxs[callno]->trunk = user->trunk;
2677 iaxs[callno]->capability = user->capability;
2678 /* And use the default context */
2679 if (!strlen(iaxs[callno]->context)) {
2681 strncpy(iaxs[callno]->context, user->contexts->context, sizeof(iaxs[callno]->context)-1);
2683 strncpy(iaxs[callno]->context, context, sizeof(iaxs[callno]->context)-1);
2685 /* Copy the secret */
2686 strncpy(iaxs[callno]->secret, user->secret, sizeof(iaxs[callno]->secret)-1);
2687 /* And any input keys */
2688 strncpy(iaxs[callno]->inkeys, user->inkeys, sizeof(iaxs[callno]->inkeys));
2689 /* And the permitted authentication methods */
2690 iaxs[callno]->authmethods = user->authmethods;
2691 /* If they have callerid, override the given caller id. Always store the ANI */
2692 if (strlen(iaxs[callno]->callerid)) {
2693 if (user->hascallerid)
2694 strncpy(iaxs[callno]->callerid, user->callerid, sizeof(iaxs[callno]->callerid)-1);
2695 strncpy(iaxs[callno]->ani, user->callerid, sizeof(iaxs[callno]->ani)-1);
2697 if (strlen(user->accountcode))
2698 strncpy(iaxs[callno]->accountcode, user->accountcode, sizeof(iaxs[callno]->accountcode)-1);
2700 iaxs[callno]->amaflags = user->amaflags;
2701 iaxs[callno]->notransfer = user->notransfer;
2707 ast_mutex_unlock(&userl.lock);
2708 iaxs[callno]->trunk = iax2_getpeertrunk(*sin);
2712 static int raw_hangup(struct sockaddr_in *sin, unsigned short src, unsigned short dst)
2714 struct ast_iax2_full_hdr fh;
2715 fh.scallno = htons(src | IAX_FLAG_FULL);
2716 fh.dcallno = htons(dst);
2720 fh.type = AST_FRAME_IAX;
2721 fh.csub = compress_subclass(IAX_COMMAND_INVAL);
2725 ast_log(LOG_DEBUG, "Raw Hangup %s:%d, src=%d, dst=%d\n",
2726 inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), src, dst);
2727 return sendto(netsocket, &fh, sizeof(fh), 0, (struct sockaddr *)sin, sizeof(*sin));
2730 static int authenticate_request(struct chan_iax2_pvt *p)
2732 struct iax_ie_data ied;
2733 memset(&ied, 0, sizeof(ied));
2734 iax_ie_append_short(&ied, IAX_IE_AUTHMETHODS, p->authmethods);
2735 if (p->authmethods & (IAX_AUTH_MD5 | IAX_AUTH_RSA)) {
2736 snprintf(p->challenge, sizeof(p->challenge), "%d", rand());
2737 iax_ie_append_str(&ied, IAX_IE_CHALLENGE, p->challenge);
2739 iax_ie_append_str(&ied,IAX_IE_USERNAME, p->username);
2740 return send_command(p, AST_FRAME_IAX, IAX_COMMAND_AUTHREQ, 0, ied.buf, ied.pos, -1);
2743 static int authenticate_verify(struct chan_iax2_pvt *p, struct iax_ies *ies)
2745 char requeststr[256] = "";
2746 char md5secret[256] = "";
2747 char secret[256] = "";
2748 char rsasecret[256] = "";
2752 if (!(p->state & IAX_STATE_AUTHENTICATED))
2755 strncpy(secret, ies->password, sizeof(secret) - 1);
2756 if (ies->md5_result)
2757 strncpy(md5secret, ies->md5_result, sizeof(md5secret)-1);
2758 if (ies->rsa_result)
2759 strncpy(rsasecret, ies->rsa_result, sizeof(rsasecret)-1);
2760 if ((p->authmethods & IAX_AUTH_RSA) && strlen(rsasecret) && strlen(p->inkeys)) {
2761 struct ast_key *key;
2765 strncpy(tmpkey, p->inkeys, sizeof(tmpkey));
2767 keyn = strsep(&stringp, ":");
2769 key = ast_key_get(keyn, AST_KEY_PUBLIC);
2770 if (key && !ast_check_signature(key, p->challenge, rsasecret)) {
2774 ast_log(LOG_WARNING, "requested inkey '%s' for RSA authentication does not exist\n", keyn);
2775 keyn = strsep(&stringp, ":");
2777 } else if (p->authmethods & IAX_AUTH_MD5) {
2778 struct MD5Context md5;
2779 unsigned char digest[16];
2781 MD5Update(&md5, p->challenge, strlen(p->challenge));
2782 MD5Update(&md5, p->secret, strlen(p->secret));
2783 MD5Final(digest, &md5);
2784 /* If they support md5, authenticate with it. */
2786 sprintf(requeststr + (x << 1), "%2.2x", digest[x]);
2787 if (!strcasecmp(requeststr, md5secret))
2789 } else if (p->authmethods & IAX_AUTH_PLAINTEXT) {
2790 if (!strcmp(secret, p->secret))
2796 static int register_verify(int callno, struct sockaddr_in *sin, struct iax_ies *ies)
2798 char requeststr[256] = "";
2799 char peer[256] = "";
2800 char md5secret[256] = "";
2801 char rsasecret[256] = "";
2802 char secret[256] = "";
2803 struct iax2_peer *p;
2804 struct ast_key *key;
2809 iaxs[callno]->state &= ~IAX_STATE_AUTHENTICATED;
2810 strcpy(iaxs[callno]->peer, "");
2812 strncpy(peer, ies->username, sizeof(peer) - 1);
2814 strncpy(secret, ies->password, sizeof(secret) - 1);
2815 if (ies->md5_result)
2816 strncpy(md5secret, ies->md5_result, sizeof(md5secret)-1);
2817 if (ies->rsa_result)
2818 strncpy(rsasecret, ies->rsa_result, sizeof(rsasecret)-1);
2820 expire = ies->refresh;
2822 if (!strlen(peer)) {
2823 ast_log(LOG_NOTICE, "Empty registration from %s\n", inet_ntoa(sin->sin_addr));
2827 for (p = peerl.peers; p ; p = p->next)
2828 if (!strcasecmp(p->name, peer))
2832 ast_log(LOG_NOTICE, "No registration for peer '%s' (from %s)\n", peer, inet_ntoa(sin->sin_addr));
2837 ast_log(LOG_NOTICE, "Peer '%s' is not dynamic (from %s)\n", peer, inet_ntoa(sin->sin_addr));
2841 if (!ast_apply_ha(p->ha, sin)) {
2842 ast_log(LOG_NOTICE, "Host %s denied access to register peer '%s'\n", inet_ntoa(sin->sin_addr), p->name);
2845 strncpy(iaxs[callno]->secret, p->secret, sizeof(iaxs[callno]->secret)-1);
2846 strncpy(iaxs[callno]->inkeys, p->inkeys, sizeof(iaxs[callno]->inkeys)-1);
2847 /* Check secret against what we have on file */
2848 if (strlen(rsasecret) && (p->authmethods & IAX_AUTH_RSA) && strlen(p->challenge)) {
2849 if (strlen(p->inkeys)) {
2852 strncpy(tmpkeys, p->inkeys, sizeof(tmpkeys));
2854 keyn = strsep(&stringp, ":");
2856 key = ast_key_get(keyn, AST_KEY_PUBLIC);
2857 if (key && !ast_check_signature(key, p->challenge, rsasecret)) {
2858 iaxs[callno]->state |= IAX_STATE_AUTHENTICATED;
2861 ast_log(LOG_WARNING, "requested inkey '%s' does not exist\n", keyn);
2862 keyn = strsep(&stringp, ":");
2865 ast_log(LOG_NOTICE, "Host %s failed RSA authentication with inkeys '%s'\n", peer, p->inkeys);
2869 ast_log(LOG_NOTICE, "Host '%s' trying to do RSA authentication, but we have no inkeys\n", peer);
2872 } else if (strlen(secret) && (p->authmethods & IAX_AUTH_PLAINTEXT)) {
2873 /* They've provided a plain text password and we support that */
2874 if (strcmp(secret, p->secret)) {
2875 ast_log(LOG_NOTICE, "Host %s did not provide proper plaintext password for '%s'\n", inet_ntoa(sin->sin_addr), p->name);
2878 iaxs[callno]->state |= IAX_STATE_AUTHENTICATED;
2879 } else if (strlen(md5secret) && (p->authmethods & IAX_AUTH_MD5) && strlen(p->challenge)) {
2880 struct MD5Context md5;
2881 unsigned char digest[16];
2883 MD5Update(&md5, p->challenge, strlen(p->challenge));
2884 MD5Update(&md5, p->secret, strlen(p->secret));
2885 MD5Final(digest, &md5);
2887 sprintf(requeststr + (x << 1), "%2.2x", digest[x]);
2888 if (strcasecmp(requeststr, md5secret)) {
2889 ast_log(LOG_NOTICE, "Host %s failed MD5 authentication for '%s' (%s != %s)\n", inet_ntoa(sin->sin_addr), p->name, requeststr, md5secret);
2892 iaxs[callno]->state |= IAX_STATE_AUTHENTICATED;
2893 } else if (strlen(md5secret) || strlen(secret)) {
2894 ast_log(LOG_NOTICE, "Inappropriate authentication received\n");
2897 strncpy(iaxs[callno]->peer, peer, sizeof(iaxs[callno]->peer)-1);
2898 /* Choose lowest expirey number */
2899 if (expire && (expire < iaxs[callno]->expirey))
2900 iaxs[callno]->expirey = expire;
2905 static int authenticate(char *challenge, char *secret, char *keyn, int authmethods, struct iax_ie_data *ied, struct sockaddr_in *sin)
2909 if (keyn && strlen(keyn)) {
2910 if (!(authmethods & IAX_AUTH_RSA)) {
2911 if (!secret || !strlen(secret))
2912 ast_log(LOG_NOTICE, "Asked to authenticate to %s with an RSA key, but they don't allow RSA authentication\n", inet_ntoa(sin->sin_addr));
2913 } else if (!strlen(challenge)) {
2914 ast_log(LOG_NOTICE, "No challenge provided for RSA authentication to %s\n", inet_ntoa(sin->sin_addr));
2917 struct ast_key *key;
2918 key = ast_key_get(keyn, AST_KEY_PRIVATE);
2920 ast_log(LOG_NOTICE, "Unable to find private key '%s'\n", keyn);
2922 if (ast_sign(key, challenge, sig)) {
2923 ast_log(LOG_NOTICE, "Unable to sign challenge withy key\n");
2926 iax_ie_append_str(ied, IAX_IE_RSA_RESULT, sig);
2933 if (res && secret && strlen(secret)) {
2934 if ((authmethods & IAX_AUTH_MD5) && strlen(challenge)) {
2935 struct MD5Context md5;
2936 unsigned char digest[16];
2937 char digres[128] = "";
2939 MD5Update(&md5, challenge, strlen(challenge));
2940 MD5Update(&md5, secret, strlen(secret));
2941 MD5Final(digest, &md5);
2942 /* If they support md5, authenticate with it. */
2944 sprintf(digres + (x << 1), "%2.2x", digest[x]);
2945 iax_ie_append_str(ied, IAX_IE_MD5_RESULT, digres);
2947 } else if (authmethods & IAX_AUTH_PLAINTEXT) {
2948 iax_ie_append_str(ied, IAX_IE_PASSWORD, secret);
2951 ast_log(LOG_NOTICE, "No way to send secret to peer '%s' (their methods: %d)\n", inet_ntoa(sin->sin_addr), authmethods);
2956 static int authenticate_reply(struct chan_iax2_pvt *p, struct sockaddr_in *sin, struct iax_ies *ies, char *override, char *okey)
2958 struct iax2_peer *peer;
2959 /* Start pessimistic */
2961 int authmethods = 0;
2962 struct iax_ie_data ied;
2964 memset(&ied, 0, sizeof(ied));
2967 strncpy(p->username, ies->username, sizeof(p->username) - 1);
2969 strncpy(p->challenge, ies->challenge, sizeof(p->challenge)-1);
2970 if (ies->authmethods)
2971 authmethods = ies->authmethods;
2973 /* Check for override RSA authentication first */
2974 if ((override && strlen(override)) || (okey && strlen(okey))) {
2975 /* Normal password authentication */
2976 res = authenticate(p->challenge, override, okey, authmethods, &ied, sin);
2978 ast_mutex_lock(&peerl.lock);
2981 if ((!strlen(p->peer) || !strcmp(p->peer, peer->name))
2982 /* No peer specified at our end, or this is the peer */
2983 && (!strlen(peer->username) || (!strcmp(peer->username, p->username)))
2984 /* No username specified in peer rule, or this is the right username */
2985 && (!peer->addr.sin_addr.s_addr || ((sin->sin_addr.s_addr & peer->mask.s_addr) == (peer->addr.sin_addr.s_addr & peer->mask.s_addr)))
2986 /* No specified host, or this is our host */
2988 res = authenticate(p->challenge, peer->secret, peer->outkey, authmethods, &ied, sin);
2994 ast_mutex_unlock(&peerl.lock);
2997 res = send_command(p, AST_FRAME_IAX, IAX_COMMAND_AUTHREP, 0, ied.buf, ied.pos, -1);
3001 static int iax2_do_register(struct iax2_registry *reg);
3003 static int iax2_do_register_s(void *data)
3005 struct iax2_registry *reg = data;
3007 iax2_do_register(reg);
3011 static int try_transfer(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
3014 char newip[256] = "";
3015 struct iax_ie_data ied;
3016 struct sockaddr_in new;
3019 memset(&ied, 0, sizeof(ied));
3020 if (ies->apparent_addr)
3021 memcpy(&new, ies->apparent_addr, sizeof(new));
3023 newcall = ies->callno;
3024 if (!newcall || !new.sin_addr.s_addr || !new.sin_port) {
3025 ast_log(LOG_WARNING, "Invalid transfer request\n");
3028 pvt->transfercallno = newcall;
3029 memcpy(&pvt->transfer, &new, sizeof(pvt->transfer));
3030 inet_aton(newip, &pvt->transfer.sin_addr);
3031 pvt->transfer.sin_family = AF_INET;
3032 pvt->transferring = TRANSFER_BEGIN;
3033 pvt->transferid = ies->transferid;
3034 if (ies->transferid)
3035 iax_ie_append_int(&ied, IAX_IE_TRANSFERID, ies->transferid);
3036 send_command_transfer(pvt, AST_FRAME_IAX, IAX_COMMAND_TXCNT, 0, ied.buf, ied.pos);
3040 static int complete_dpreply(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
3042 char exten[256] = "";
3043 int status = CACHE_FLAG_UNKNOWN;
3044 int expirey = iaxdefaultdpcache;
3047 struct iax2_dpcache *dp, *prev;
3049 if (ies->called_number)
3050 strncpy(exten, ies->called_number, sizeof(exten)-1);
3052 if (ies->dpstatus & IAX_DPSTATUS_EXISTS)
3053 status = CACHE_FLAG_EXISTS;
3054 else if (ies->dpstatus & IAX_DPSTATUS_CANEXIST)
3055 status = CACHE_FLAG_CANEXIST;
3056 else if (ies->dpstatus & IAX_DPSTATUS_NONEXISTANT)
3057 status = CACHE_FLAG_NONEXISTANT;
3059 if (ies->dpstatus & IAX_DPSTATUS_IGNOREPAT) {
3060 /* Don't really do anything with this */
3063 expirey = ies->refresh;
3064 if (ies->dpstatus & IAX_DPSTATUS_MATCHMORE)
3065 matchmore = CACHE_FLAG_MATCHMORE;
3066 ast_mutex_lock(&dpcache_lock);
3068 dp = pvt->dpentries;
3070 if (!strcmp(dp->exten, exten)) {
3073 prev->peer = dp->peer;
3075 pvt->dpentries = dp->peer;
3078 dp->expirey.tv_sec = dp->orig.tv_sec + expirey;
3079 if (dp->flags & CACHE_FLAG_PENDING) {
3080 dp->flags &= ~CACHE_FLAG_PENDING;
3081 dp->flags |= status;
3082 dp->flags |= matchmore;
3084 /* Wake up waiters */
3085 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
3086 if (dp->waiters[x] > -1)
3087 write(dp->waiters[x], "asdf", 4);
3092 ast_mutex_unlock(&dpcache_lock);
3096 static int complete_transfer(int callno, struct iax_ies *ies)
3099 struct chan_iax2_pvt *pvt = iaxs[callno];
3100 struct iax_frame *cur;
3103 peercallno = ies->callno;
3105 if (peercallno < 1) {
3106 ast_log(LOG_WARNING, "Invalid transfer request\n");
3109 memcpy(&pvt->addr, &pvt->transfer, sizeof(pvt->addr));
3110 memset(&pvt->transfer, 0, sizeof(pvt->transfer));
3111 /* Reset sequence numbers */
3114 pvt->peercallno = peercallno;
3115 pvt->transferring = TRANSFER_NONE;
3116 pvt->svoiceformat = -1;
3117 pvt->voiceformat = 0;
3118 pvt->svideoformat = -1;
3119 pvt->videoformat = 0;
3120 pvt->transfercallno = -1;
3121 memset(&pvt->rxcore, 0, sizeof(pvt->rxcore));
3122 memset(&pvt->offset, 0, sizeof(pvt->offset));
3123 memset(&pvt->history, 0, sizeof(pvt->history));
3124 pvt->jitterbuffer = 0;
3126 pvt->historicjitter = 0;
3130 pvt->pingtime = DEFAULT_RETRY_TIME;
3131 ast_mutex_lock(&iaxq.lock);
3132 for (cur = iaxq.head; cur ; cur = cur->next) {
3133 /* We must cancel any packets that would have been transmitted
3134 because now we're talking to someone new. It's okay, they
3135 were transmitted to someone that didn't care anyway. */
3136 if (callno == cur->callno)
3139 ast_mutex_unlock(&iaxq.lock);
3143 static int iax2_ack_registry(struct iax_ies *ies, struct sockaddr_in *sin, int callno)
3145 struct iax2_registry *reg;
3146 /* Start pessimistic */
3147 char peer[256] = "";
3148 char msgstatus[40] = "";
3150 char ourip[256] = "<Unspecified>";
3151 struct sockaddr_in oldus;
3152 struct sockaddr_in us;
3155 memset(&us, 0, sizeof(us));
3156 if (ies->apparent_addr)
3157 memcpy(&us, ies->apparent_addr, sizeof(us));
3159 strncpy(peer, ies->username, sizeof(peer) - 1);
3161 refresh = ies->refresh;
3162 if (ies->calling_number) {
3163 /* We don't do anything with it really, but maybe we should */
3165 reg = iaxs[callno]->reg;
3167 ast_log(LOG_WARNING, "Registry acknowledge on unknown registery '%s'\n", peer);
3170 memcpy(&oldus, ®->us, sizeof(oldus));
3171 oldmsgs = reg->messages;
3172 if (inaddrcmp(®->addr, sin)) {
3173 ast_log(LOG_WARNING, "Received unsolicited registry ack from '%s'\n", inet_ntoa(sin->sin_addr));
3176 memcpy(®->us, &us, sizeof(reg->us));
3177 reg->messages = ies->msgcount;
3178 if (refresh && (reg->refresh < refresh)) {
3179 /* Refresh faster if necessary */
3180 reg->refresh = refresh;
3181 if (reg->expire > -1)
3182 ast_sched_del(sched, reg->expire);
3183 reg->expire = ast_sched_add(sched, (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
3185 if ((inaddrcmp(&oldus, ®->us) || (reg->messages != oldmsgs)) && (option_verbose > 2)) {
3186 if (reg->messages > 65534)
3187 snprintf(msgstatus, sizeof(msgstatus), " with message(s) waiting\n");
3188 else if (reg->messages > 1)
3189 snprintf(msgstatus, sizeof(msgstatus), " with %d messages waiting\n", reg->messages);
3190 else if (reg->messages > 0)
3191 snprintf(msgstatus, sizeof(msgstatus), " with 1 message waiting\n");
3192 else if (reg->messages > -1)
3193 snprintf(msgstatus, sizeof(msgstatus), " with no messages waiting\n");
3194 snprintf(ourip, sizeof(ourip), "%s:%d", inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
3195 ast_verbose(VERBOSE_PREFIX_3 "Registered to '%s', who sees us as %s%s\n", inet_ntoa(sin->sin_addr), ourip, msgstatus);
3197 reg->regstate = REG_STATE_REGISTERED;
3201 static int iax2_register(char *value, int lineno)
3203 struct iax2_registry *reg;
3205 char *username, *hostname, *secret;
3212 strncpy(copy, value, sizeof(copy)-1);
3214 username = strsep(&stringp, "@");
3215 hostname = strsep(&stringp, "@");
3217 ast_log(LOG_WARNING, "Format for registration is user[:secret]@host[:port] at line %d", lineno);
3221 username = strsep(&stringp, ":");
3222 secret = strsep(&stringp, ":");
3224 hostname = strsep(&stringp, ":");
3225 porta = strsep(&stringp, ":");
3227 if (porta && !atoi(porta)) {
3228 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
3231 hp = gethostbyname(hostname);
3233 ast_log(LOG_WARNING, "Host '%s' not found at line %d\n", hostname, lineno);
3236 reg = malloc(sizeof(struct iax2_registry));
3238 memset(reg, 0, sizeof(struct iax2_registry));
3239 strncpy(reg->username, username, sizeof(reg->username)-1);
3241 strncpy(reg->secret, secret, sizeof(reg->secret)-1);
3243 reg->refresh = IAX_DEFAULT_REG_EXPIRE;
3244 reg->addr.sin_family = AF_INET;
3245 memcpy(®->addr.sin_addr, hp->h_addr, sizeof(®->addr.sin_addr));
3246 reg->addr.sin_port = porta ? htons(atoi(porta)) : htons(IAX_DEFAULT_PORTNO);
3247 reg->next = registrations;
3249 registrations = reg;
3251 ast_log(LOG_ERROR, "Out of memory\n");
3257 static int expire_registry(void *data)
3259 struct iax2_peer *p = data;
3260 /* Reset the address */
3261 memset(&p->addr, 0, sizeof(p->addr));
3262 /* Reset expire notice */
3264 /* Reset expirey value */
3265 p->expirey = expirey;
3266 ast_db_del("IAX/Registry", p->name);
3268 iax2_regfunk(p->name, 0);
3273 static int iax2_poke_peer(struct iax2_peer *peer);
3275 static void reg_source_db(struct iax2_peer *p)
3280 if (!ast_db_get("IAX/Registry", p->name, data, sizeof(data))) {
3281 c = strchr(data, ':');
3285 if (inet_aton(data, &in)) {
3290 ast_verbose(VERBOSE_PREFIX_3 "Seeding '%s' at %s:%d for %d\n", p->name,
3291 inet_ntoa(in), atoi(c), atoi(d));
3293 p->expirey = atoi(d);
3294 memset(&p->addr, 0, sizeof(p->addr));
3295 p->addr.sin_family = AF_INET;
3296 p->addr.sin_addr = in;
3297 p->addr.sin_port = htons(atoi(c));
3299 ast_sched_del(sched, p->expire);
3300 p->expire = ast_sched_add(sched, p->expirey * 1000, expire_registry, (void *)p);
3302 iax2_regfunk(p->name, 1);
3310 static int update_registry(char *name, struct sockaddr_in *sin, int callno)
3312 /* Called from IAX thread only, with proper iaxsl lock */
3313 struct iax_ie_data ied;
3314 struct iax2_peer *p;
3317 memset(&ied, 0, sizeof(ied));
3318 for (p = peerl.peers;p;p = p->next) {
3319 if (!strcasecmp(name, p->name)) {
3320 if (inaddrcmp(&p->addr, sin)) {
3322 iax2_regfunk(p->name, 1);
3323 snprintf(data, sizeof(data), "%s:%d:%d", inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), p->expirey);
3324 ast_db_put("IAX/Registry", p->name, data);
3325 if (option_verbose > 2)
3326 ast_verbose(VERBOSE_PREFIX_3 "Registered '%s' (%s) at %s:%d\n", p->name,
3327 iaxs[callno]->state & IAX_STATE_AUTHENTICATED ? "AUTHENTICATED" : "UNAUTHENTICATED", inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
3330 /* Update the host */
3331 memcpy(&p->addr, sin, sizeof(p->addr));
3332 /* Setup the expirey */
3334 ast_sched_del(sched, p->expire);
3335 p->expire = ast_sched_add(sched, p->expirey * 1000, expire_registry, (void *)p);
3336 iax_ie_append_str(&ied, IAX_IE_USERNAME, p->name);
3337 iax_ie_append_short(&ied, IAX_IE_REFRESH, p->expirey);
3338 iax_ie_append_addr(&ied, IAX_IE_APPARENT_ADDR, &p->addr);
3339 if (strlen(p->mailbox)) {
3340 msgcount = ast_app_has_voicemail(p->mailbox);
3343 iax_ie_append_short(&ied, IAX_IE_MSGCOUNT, msgcount);
3346 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, p->callerid);
3347 return send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGACK, 0, ied.buf, ied.pos, -1);;
3350 ast_log(LOG_WARNING, "No such peer '%s'\n", name);
3354 static int registry_authrequest(char *name, int callno)
3356 struct iax_ie_data ied;
3357 struct iax2_peer *p;
3358 for (p = peerl.peers;p;p = p->next) {
3359 if (!strcasecmp(name, p->name)) {
3360 memset(&ied, 0, sizeof(ied));
3361 iax_ie_append_short(&ied, IAX_IE_AUTHMETHODS, p->authmethods);
3362 if (p->authmethods & (IAX_AUTH_RSA | IAX_AUTH_MD5)) {
3363 /* Build the challenge */
3364 snprintf(p->challenge, sizeof(p->challenge), "%d", rand());
3365 iax_ie_append_str(&ied, IAX_IE_CHALLENGE, p->challenge);
3367 iax_ie_append_str(&ied, IAX_IE_USERNAME, name);
3368 return send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGAUTH, 0, ied.buf, ied.pos, -1);;
3371 ast_log(LOG_WARNING, "No such peer '%s'\n", name);
3375 static int registry_rerequest(struct iax_ies *ies, int callno, struct sockaddr_in *sin)
3377 struct iax2_registry *reg;
3378 /* Start pessimistic */
3379 struct iax_ie_data ied;
3380 char peer[256] = "";
3381 char challenge[256] = "";
3383 int authmethods = 0;
3384 if (ies->authmethods)
3385 authmethods = ies->authmethods;
3387 strncpy(peer, ies->username, sizeof(peer) - 1);
3389 strncpy(challenge, ies->challenge, sizeof(challenge) - 1);
3390 memset(&ied, 0, sizeof(ied));
3391 reg = iaxs[callno]->reg;
3392 if (inaddrcmp(®->addr, sin)) {
3393 ast_log(LOG_WARNING, "Received unsolicited registry authenticate request from '%s'\n", inet_ntoa(sin->sin_addr));
3396 if (!strlen(reg->secret)) {
3397 ast_log(LOG_NOTICE, "No secret associated with peer '%s'\n", reg->username);
3398 reg->regstate = REG_STATE_NOAUTH;
3401 iax_ie_append_str(&ied, IAX_IE_USERNAME, reg->username);
3402 iax_ie_append_short(&ied, IAX_IE_REFRESH, reg->refresh);
3403 if (reg->secret[0] == '[') {
3405 strncpy(tmpkey, reg->secret + 1, sizeof(tmpkey) - 1);
3406 tmpkey[strlen(tmpkey) - 1] = '\0';
3407 res = authenticate(challenge, NULL, tmpkey, authmethods, &ied, sin);
3409 res = authenticate(challenge, reg->secret, NULL, authmethods, &ied, sin);
3411 reg->regstate = REG_STATE_AUTHSENT;
3412 return send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGREQ, 0, ied.buf, ied.pos, -1);
3415 ast_log(LOG_WARNING, "Registry acknowledge on unknown registery '%s'\n", peer);
3419 static int stop_stuff(int callno)
3421 if (iaxs[callno]->lagid > -1)
3422 ast_sched_del(sched, iaxs[callno]->lagid);
3423 iaxs[callno]->lagid = -1;
3424 if (iaxs[callno]->pingid > -1)
3425 ast_sched_del(sched, iaxs[callno]->pingid);
3426 iaxs[callno]->pingid = -1;
3427 if (iaxs[callno]->autoid > -1)
3428 ast_sched_del(sched, iaxs[callno]->autoid);
3429 iaxs[callno]->autoid = -1;
3430 if (iaxs[callno]->initid > -1)
3431 ast_sched_del(sched, iaxs[callno]->initid);
3432 iaxs[callno]->initid = -1;
3436 static int auto_hangup(void *nothing)
3438 /* Called from IAX thread only, without iaxs lock */
3439 int callno = (int)(long)(nothing);
3440 struct iax_ie_data ied;
3441 ast_mutex_lock(&iaxsl[callno]);
3443 iaxs[callno]->autoid = -1;
3444 memset(&ied, 0, sizeof(ied));
3445 iax_ie_append_str(&ied, IAX_IE_CAUSE, "Timeout");
3446 send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1);
3448 ast_mutex_unlock(&iaxsl[callno]);
3452 static void iax2_dprequest(struct iax2_dpcache *dp, int callno)
3454 struct iax_ie_data ied;
3455 /* Auto-hangup with 30 seconds of inactivity */
3456 if (iaxs[callno]->autoid > -1)
3457 ast_sched_del(sched, iaxs[callno]->autoid);
3458 iaxs[callno]->autoid = ast_sched_add(sched, 30000, auto_hangup, (void *)callno);
3459 memset(&ied, 0, sizeof(ied));
3460 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, dp->exten);
3461 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_DPREQ, 0, ied.buf, ied.pos, -1);
3462 dp->flags |= CACHE_FLAG_TRANSMITTED;
3465 static int iax2_vnak(int callno)
3467 return send_command_immediate(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_VNAK, 0, NULL, 0, iaxs[callno]->iseqno);
3470 static void vnak_retransmit(int callno, int last)
3472 struct iax_frame *f;
3473 ast_mutex_lock(&iaxq.lock);
3476 /* Send a copy immediately */
3477 if ((f->callno == callno) && iaxs[f->callno] &&
3478 (f->oseqno >= last)) {