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 <asterisk/musiconhold.h>
36 #include <arpa/inet.h>
37 #include <sys/socket.h>
38 #include <netinet/in.h>
39 #include <netinet/in_systm.h>
40 #include <netinet/ip.h>
42 #include <sys/signal.h>
53 #include <sys/ioctl.h>
54 #include <linux/zaptel.h>
57 #include <mysql/mysql.h>
60 #include "iax2-parser.h"
63 #define IPTOS_MINCOST 0x02
67 * Uncomment to try experimental IAX bridge optimization,
68 * designed to reduce latency when IAX calls cannot
72 #define BRIDGE_OPTIMIZATION
75 #define DEFAULT_RETRY_TIME 1000
76 #define MEMORY_SIZE 100
77 #define DEFAULT_DROP 3
78 /* Flag to use with trunk calls, keeping these calls high up. It halves our effective use
79 but keeps the division between trunked and non-trunked better. */
80 #define TRUNK_CALL_START 0x4000
84 #define MIN_REUSE_TIME 60 /* Don't reuse a call number within 60 seconds */
86 /* Sample over last 100 units to determine historic jitter */
90 static ast_mutex_t mysqllock = AST_MUTEX_INITIALIZER;
92 static char mydbuser[80];
93 static char mydbpass[80];
94 static char mydbhost[80];
95 static char mydbname[80];
97 static char *desc = "Inter Asterisk eXchange (Ver 2)";
98 static char *tdesc = "Inter Asterisk eXchange Driver (Ver 2)";
99 static char *type = "IAX2";
101 static char context[80] = "default";
103 static int max_retries = 4;
104 static int ping_time = 20;
105 static int lagrq_time = 10;
106 static int maxtrunkcall = TRUNK_CALL_START;
107 static int maxnontrunkcall = 1;
108 static int maxjitterbuffer=3000;
109 static int trunkfreq = 20;
110 static int authdebug = 1;
111 static int iaxcompat = 0;
113 static int iaxdefaultdpcache=10 * 60; /* Cache dialplan entries for 10 minutes by default */
115 static int iaxdefaulttimeout = 5; /* Default to wait no more than 5 seconds for a reply to come back */
117 static int netsocket = -1;
121 static int expirey = IAX_DEFAULT_REG_EXPIRE;
123 static int timingfd = -1; /* Timing file descriptor */
126 static ast_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
128 int (*iax2_regfunk)(char *username, int onoff) = NULL;
131 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
133 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
134 ~AST_FORMAT_SLINEAR & \
138 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
142 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
146 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
147 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
148 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
150 static struct io_context *io;
151 static struct sched_context *sched;
153 static int iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
155 static int iax2_dropcount = DEFAULT_DROP;
157 static int use_jitterbuffer = 0;
159 static int iaxdebug = 0;
161 static int iaxtrunkdebug = 0;
163 static char accountcode[20];
164 static int amaflags = 0;
165 static int notransfer = 0;
167 static pthread_t netthreadid;
169 #define IAX_STATE_STARTED (1 << 0)
170 #define IAX_STATE_AUTHENTICATED (1 << 1)
171 #define IAX_STATE_TBD (1 << 2)
173 struct iax2_context {
174 char context[AST_MAX_EXTENSION];
175 struct iax2_context *next;
182 char accountcode[20];
183 char inkeys[80]; /* Key(s) this user can use to authenticate to us */
190 char callerid[AST_MAX_EXTENSION];
192 struct iax2_context *contexts;
193 struct iax2_user *next;
201 char outkey[80]; /* What key we use to talk to this peer */
202 char context[AST_MAX_EXTENSION]; /* Default context (for transfer really) */
203 char mailbox[AST_MAX_EXTENSION]; /* Mailbox */
204 struct sockaddr_in addr;
208 /* Dynamic Registration fields */
209 int dynamic; /* If this is a dynamic peer */
210 struct sockaddr_in defaddr; /* Default address if there is one */
211 int authmethods; /* Authentication methods (IAX_AUTH_*) */
212 char inkeys[80]; /* Key(s) this peer can use to authenticate to us */
215 /* Suggested caller id if registering */
216 char callerid[AST_MAX_EXTENSION];
217 /* Whether or not to send ANI */
219 int expire; /* Schedule entry for expirey */
220 int expirey; /* How soon to expire */
221 int capability; /* Capability */
222 int delme; /* I need to be deleted */
223 int temponly; /* I'm only a temp */
224 int trunk; /* Treat as an IAX trunking */
225 struct timeval txtrunktime; /* Transmit trunktime */
226 struct timeval rxtrunktime; /* Receive trunktime */
227 struct timeval lasttxtime; /* Last transmitted trunktime */
228 unsigned int lastsent; /* Last sent time */
231 int callno; /* Call number of POKE request */
232 int pokeexpire; /* When to expire poke */
233 int lastms; /* How long last response took (in ms), or -1 for no response */
234 int maxms; /* Max ms we will accept for the host to be up, 0 to not monitor */
237 struct iax2_peer *next;
241 #define REG_STATE_UNREGISTERED 0
242 #define REG_STATE_REGSENT 1
243 #define REG_STATE_AUTHSENT 2
244 #define REG_STATE_REGISTERED 3
245 #define REG_STATE_REJECTED 4
246 #define REG_STATE_TIMEOUT 5
247 #define REG_STATE_NOAUTH 6
249 #define TRANSFER_NONE 0
250 #define TRANSFER_BEGIN 1
251 #define TRANSFER_READY 2
252 #define TRANSFER_RELEASED 3
253 #define TRANSFER_PASSTHROUGH 4
255 struct iax2_registry {
256 struct sockaddr_in addr; /* Who we connect to for registration purposes */
258 char secret[80]; /* Password or key name in []'s */
260 int expire; /* Sched ID of expiration */
261 int refresh; /* How often to refresh */
263 int messages; /* Message count */
264 int callno; /* Associated call number if applicable */
265 struct sockaddr_in us; /* Who the server thinks we are */
266 struct iax2_registry *next;
269 static struct iax2_registry *registrations;
271 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
272 #define MIN_RETRY_TIME 100
273 #define MAX_RETRY_TIME 10000
274 #define MAX_JITTER_BUFFER 50
276 #define MAX_TRUNKDATA 640 /* 40ms, uncompressed linear */
278 /* If we have more than this much excess real jitter buffer, srhink it. */
279 static int max_jitter_buffer = MAX_JITTER_BUFFER;
281 struct chan_iax2_pvt {
282 /* Pipes for communication. pipe[1] belongs to the
283 network thread (write), and pipe[0] belongs to the individual
285 /* Whether or not we Quelch audio */
287 /* Last received voice format */
289 /* Last received voice format */
291 /* Last sent voice format */
293 /* Last sent video format */
295 /* What we are capable of sending */
297 /* Last received timestamp */
299 /* Last sent timestamp - never send the same timestamp twice in a single call */
300 unsigned int lastsent;
302 unsigned int pingtime;
303 /* Max time for initial response */
306 struct sockaddr_in addr;
307 /* Our call number */
308 unsigned short callno;
310 unsigned short peercallno;
311 /* Peer selected format */
313 /* Peer capability */
315 /* timeval that we base our transmission on */
316 struct timeval offset;
317 /* timeval that we base our delivery on */
318 struct timeval rxcore;
319 /* Historical delivery time */
320 int history[MEMORY_SIZE];
321 /* Current base jitterbuffer */
323 /* Current jitter measure */
325 /* Historic jitter value */
329 /* Error, as discovered by the manager */
331 /* Owner if we have one */
332 struct ast_channel *owner;
333 /* What's our state? */
335 /* Expirey (optional) */
337 /* Next outgoing sequence number */
338 unsigned char oseqno;
339 /* Next sequence number they have not yet acknowledged */
340 unsigned char rseqno;
341 /* Next incoming sequence number */
342 unsigned char iseqno;
343 /* Last incoming sequence number we have acknowledged */
344 unsigned char aseqno;
347 /* Default Context */
349 /* Caller ID if available */
351 /* Hidden Caller ID (i.e. ANI) if appropriate */
353 /* Whether or not ani should be transmitted in addition to Caller*ID */
355 /* Whether to request autoanswer */
359 /* Requested Extension */
360 char exten[AST_MAX_EXTENSION];
361 /* Expected Username */
363 /* Expected Secret */
365 /* permitted authentication methods */
369 /* Public keys permitted keys for incoming authentication */
371 /* Private key for outgoing authentication */
373 /* Preferred language */
375 /* Hostname/peername for naming purposes */
377 /* Associated registry */
378 struct iax2_registry *reg;
379 /* Associated peer for poking */
380 struct iax2_peer *peerpoke;
382 /* Transferring status */
384 /* Transfer identifier */
386 /* Already disconnected */
388 /* Who we are IAX transfering to */
389 struct sockaddr_in transfer;
390 /* What's the new call number for the transfer */
391 unsigned short transfercallno;
393 /* Status of knowledge of peer ADSI capability */
396 /* Who we are bridged to */
397 unsigned short bridgecallno;
398 unsigned int bridgesfmt;
399 struct ast_trans_pvt *bridgetrans;
401 int pingid; /* Transmit PING request */
402 int lagid; /* Retransmit lag request */
403 int autoid; /* Auto hangup for Dialplan requestor */
404 int initid; /* Initial peer auto-congest ID (based on qualified peers) */
405 char dproot[AST_MAX_EXTENSION];
406 char accountcode[20];
408 /* This is part of a trunk interface */
410 /* Trunk data and length */
411 unsigned char trunkdata[MAX_TRUNKDATA];
412 unsigned int trunkdatalen;
414 struct iax2_dpcache *dpentries;
415 int notransfer; /* do we want native bridging */
418 static struct ast_iax2_queue {
419 struct iax_frame *head;
420 struct iax_frame *tail;
425 static struct ast_user_list {
426 struct iax2_user *users;
430 static struct ast_peer_list {
431 struct iax2_peer *peers;
435 /* Extension exists */
436 #define CACHE_FLAG_EXISTS (1 << 0)
437 /* Extension is non-existant */
438 #define CACHE_FLAG_NONEXISTANT (1 << 1)
439 /* Extension can exist */
440 #define CACHE_FLAG_CANEXIST (1 << 2)
441 /* Waiting to hear back response */
442 #define CACHE_FLAG_PENDING (1 << 3)
444 #define CACHE_FLAG_TIMEOUT (1 << 4)
445 /* Request transmitted */
446 #define CACHE_FLAG_TRANSMITTED (1 << 5)
448 #define CACHE_FLAG_UNKNOWN (1 << 6)
450 #define CACHE_FLAG_MATCHMORE (1 << 7)
452 static struct iax2_dpcache {
453 char peercontext[AST_MAX_EXTENSION];
454 char exten[AST_MAX_EXTENSION];
456 struct timeval expirey;
458 unsigned short callno;
460 struct iax2_dpcache *next;
461 struct iax2_dpcache *peer; /* For linking in peers */
464 static ast_mutex_t dpcache_lock;
466 static void iax_debug_output(const char *data)
471 static void iax_error_output(const char *data)
473 ast_log(LOG_WARNING, data);
476 /* XXX We probably should use a mutex when working with this XXX */
477 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS];
478 static ast_mutex_t iaxsl[IAX_MAX_CALLS];
479 static struct timeval lastused[IAX_MAX_CALLS];
482 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, char *, int, int);
483 static int send_command_locked(struct chan_iax2_pvt *, char, int, unsigned int, char *, int, int);
484 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, char *, int, int);
485 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, char *, int, int);
486 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, char *, int);
488 static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts);
490 static int send_ping(void *data)
492 int callno = (long)data;
493 /* Ping only if it's real, not if it's bridged */
495 #ifdef BRIDGE_OPTIMIZATION
496 if (!iaxs[callno]->bridgecallno)
498 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
504 static int send_lagrq(void *data)
506 int callno = (long)data;
507 /* Ping only if it's real not if it's bridged */
509 #ifdef BRIDGE_OPTIMIZATION
510 if (!iaxs[callno]->bridgecallno)
512 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
518 static unsigned char compress_subclass(int subclass)
522 /* If it's 128 or smaller, just return it */
523 if (subclass < IAX_FLAG_SC_LOG)
525 /* Otherwise find its power */
526 for (x = 0; x < IAX_MAX_SHIFT; x++) {
527 if (subclass & (1 << x)) {
529 ast_log(LOG_WARNING, "Can't compress subclass %d\n", subclass);
535 return power | IAX_FLAG_SC_LOG;
538 static int uncompress_subclass(unsigned char csub)
540 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
541 if (csub & IAX_FLAG_SC_LOG) {
542 /* special case for 'compressed' -1 */
546 return 1 << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
552 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len, int lockpeer)
554 struct iax2_peer *peer;
557 ast_mutex_lock(&peerl.lock);
560 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
561 (peer->addr.sin_port == sin.sin_port)) {
562 strncpy(host, peer->name, len-1);
569 ast_mutex_unlock(&peerl.lock);
573 static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, int lockpeer)
575 struct chan_iax2_pvt *tmp;
576 tmp = malloc(sizeof(struct chan_iax2_pvt));
578 memset(tmp, 0, sizeof(struct chan_iax2_pvt));
581 tmp->transfercallno = 0;
582 tmp->bridgecallno = 0;
587 /* strncpy(tmp->context, context, sizeof(tmp->context)-1); */
588 strncpy(tmp->exten, "s", sizeof(tmp->exten)-1);
589 if (!iax2_getpeername(*sin, tmp->host, sizeof(tmp->host), lockpeer))
590 snprintf(tmp->host, sizeof(tmp->host), "%s:%d", inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
595 static int get_samples(struct ast_frame *f)
598 switch(f->subclass) {
599 case AST_FORMAT_SPEEX:
600 samples = 160; /* XXX Not necessarily true XXX */
602 case AST_FORMAT_G723_1:
603 samples = 240 /* XXX Not necessarily true XXX */;
605 case AST_FORMAT_ILBC:
606 samples = 240 * (f->datalen / 50);
609 samples = 160 * (f->datalen / 33);
611 case AST_FORMAT_G729A:
612 samples = 160 * (f->datalen / 20);
614 case AST_FORMAT_SLINEAR:
615 samples = f->datalen / 2;
617 case AST_FORMAT_LPC10:
619 samples += (((char *)(f->data))[7] & 0x1) * 8;
621 case AST_FORMAT_ULAW:
622 samples = f->datalen;
624 case AST_FORMAT_ALAW:
625 samples = f->datalen;
627 case AST_FORMAT_ADPCM:
628 samples = f->datalen *2;
631 ast_log(LOG_WARNING, "Don't know how to calculate samples on %d packets\n", f->subclass);
636 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
638 /* Malloc() a copy of a frame */
639 struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen);
641 memcpy(new, fr, sizeof(struct iax_frame));
642 iax_frame_wrap(new, &fr->af);
645 new->direction = DIRECTION_INGRESS;
651 #define NEW_PREVENT 0
655 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, struct chan_iax2_pvt *cur)
657 if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
658 (cur->addr.sin_port == sin->sin_port)) {
659 /* This is the main host */
660 if ((cur->peercallno == callno) ||
661 ((dcallno == cur->callno) && !cur->peercallno)) {
662 /* That's us. Be sure we keep track of the peer call number */
666 if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
667 (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
668 /* We're transferring */
669 if (dcallno == cur->callno)
675 static void update_max_trunk(void)
677 int max = TRUNK_CALL_START;
679 /* XXX Prolly don't need locks here XXX */
680 for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
686 ast_log(LOG_DEBUG, "New max trunk callno is %d\n", max);
689 static void update_max_nontrunk(void)
693 /* XXX Prolly don't need locks here XXX */
694 for (x=1;x<TRUNK_CALL_START - 1; x++) {
698 maxnontrunkcall = max;
700 ast_log(LOG_DEBUG, "New max nontrunk callno is %d\n", max);
703 static int make_trunk(unsigned short callno, int locked)
708 if (iaxs[callno]->oseqno) {
709 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
712 if (callno & TRUNK_CALL_START) {
713 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
716 gettimeofday(&now, NULL);
717 for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
718 ast_mutex_lock(&iaxsl[x]);
719 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) {
720 iaxs[x] = iaxs[callno];
723 /* Update the two timers that should have been started */
724 if (iaxs[x]->pingid > -1)
725 ast_sched_del(sched, iaxs[x]->pingid);
726 if (iaxs[x]->lagid > -1)
727 ast_sched_del(sched, iaxs[x]->lagid);
728 iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)x);
729 iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)x);
731 ast_mutex_unlock(&iaxsl[callno]);
734 ast_mutex_unlock(&iaxsl[x]);
737 ast_mutex_unlock(&iaxsl[x]);
739 if (x >= IAX_MAX_CALLS - 1) {
740 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
743 ast_log(LOG_DEBUG, "Made call %d into trunk call %d\n", callno, x);
744 /* We move this call from a non-trunked to a trunked call */
746 update_max_nontrunk();
750 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int lockpeer)
755 if (new <= NEW_ALLOW) {
756 /* Look for an existing connection first */
757 for (x=1;(res < 1) && (x<maxnontrunkcall);x++) {
758 ast_mutex_lock(&iaxsl[x]);
760 /* Look for an exact match */
761 if (match(sin, callno, dcallno, iaxs[x])) {
765 ast_mutex_unlock(&iaxsl[x]);
767 for (x=TRUNK_CALL_START;(res < 1) && (x<maxtrunkcall);x++) {
768 ast_mutex_lock(&iaxsl[x]);
770 /* Look for an exact match */
771 if (match(sin, callno, dcallno, iaxs[x])) {
775 ast_mutex_unlock(&iaxsl[x]);
778 if ((res < 1) && (new >= NEW_ALLOW)) {
779 gettimeofday(&now, NULL);
780 for (x=1;x<TRUNK_CALL_START;x++) {
781 /* Find first unused call number that hasn't been used in a while */
782 ast_mutex_lock(&iaxsl[x]);
783 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) break;
784 ast_mutex_unlock(&iaxsl[x]);
786 /* We've still got lock held if we found a spot */
787 if (x >= TRUNK_CALL_START) {
788 ast_log(LOG_WARNING, "No more space\n");
791 iaxs[x] = new_iax(sin, lockpeer);
792 ast_mutex_unlock(&iaxsl[x]);
793 update_max_nontrunk();
796 ast_log(LOG_DEBUG, "Creating new call structure %d\n", x);
797 iaxs[x]->addr.sin_port = sin->sin_port;
798 iaxs[x]->addr.sin_family = sin->sin_family;
799 iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
800 iaxs[x]->peercallno = callno;
802 iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
803 iaxs[x]->expirey = expirey;
804 iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)x);
805 iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)x);
806 iaxs[x]->amaflags = amaflags;
807 iaxs[x]->notransfer = notransfer;
808 strncpy(iaxs[x]->accountcode, accountcode, sizeof(iaxs[x]->accountcode)-1);
810 ast_log(LOG_WARNING, "Out of resources\n");
818 static void iax2_frame_free(struct iax_frame *fr)
820 if (fr->retrans > -1)
821 ast_sched_del(sched, fr->retrans);
825 static int iax2_queue_frame(int callno, struct ast_frame *f)
828 /* Assumes lock for callno is already held... */
831 if (!ast_mutex_trylock(&iaxsl[callno])) {
832 ast_log(LOG_WARNING, "Lock is not held on pass %d of iax2_queue_frame\n", pass);
835 if (iaxs[callno] && iaxs[callno]->owner) {
836 if (ast_mutex_trylock(&iaxs[callno]->owner->lock)) {
837 /* Avoid deadlock by pausing and trying again */
838 ast_mutex_unlock(&iaxsl[callno]);
840 ast_mutex_lock(&iaxsl[callno]);
842 ast_queue_frame(iaxs[callno]->owner, f, 0);
843 ast_mutex_unlock(&iaxs[callno]->owner->lock);
852 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
854 static int __do_deliver(void *data)
856 /* Just deliver the packet by using queueing. This is called by
857 the IAX thread with the iaxsl lock held. */
858 struct iax_frame *fr = data;
861 if (iaxs[fr->callno] && !iaxs[fr->callno]->alreadygone) {
862 if (fr->af.frametype == AST_FRAME_IAX) {
863 /* We have to treat some of these packets specially because
864 they're LAG measurement packets */
865 if (fr->af.subclass == IAX_COMMAND_LAGRQ) {
866 /* If we got a queued request, build a reply and send it */
867 fr->af.subclass = IAX_COMMAND_LAGRP;
868 iax2_send(iaxs[fr->callno], &fr->af, fr->ts, -1, 0, 0, 0);
869 } else if (fr->af.subclass == IAX_COMMAND_LAGRP) {
870 /* This is a reply we've been given, actually measure the difference */
871 ts = calc_timestamp(iaxs[fr->callno], 0);
872 iaxs[fr->callno]->lag = ts - fr->ts;
875 iax2_queue_frame(fr->callno, &fr->af);
878 /* Free our iax frame */
880 /* And don't run again */
884 static int do_deliver(void *data)
886 /* Locking version of __do_deliver */
887 struct iax_frame *fr = data;
888 int callno = fr->callno;
890 ast_mutex_lock(&iaxsl[callno]);
891 res = __do_deliver(data);
892 ast_mutex_unlock(&iaxsl[callno]);
896 static int handle_error(void)
898 /* XXX Ideally we should figure out why an error occured and then abort those
899 rather than continuing to try. Unfortunately, the published interface does
900 not seem to work XXX */
902 struct sockaddr_in *sin;
905 struct sock_extended_err e;
910 m.msg_controllen = sizeof(e);
912 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
914 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
916 if (m.msg_controllen) {
917 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
919 ast_log(LOG_WARNING, "Receive error from %s\n", inet_ntoa(sin->sin_addr));
921 ast_log(LOG_WARNING, "No address detected??\n");
923 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
930 static int send_packet(struct iax_frame *f)
933 /* Called with iaxsl held */
935 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));
936 /* Don't send if there was an error, but return error instead */
938 ast_log(LOG_WARNING, "Call number = %d\n", f->callno);
941 if (!iaxs[f->callno])
943 if (iaxs[f->callno]->error)
947 iax_showframe(f, NULL, 0, &iaxs[f->callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
948 res = sendto(netsocket, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[f->callno]->transfer,
949 sizeof(iaxs[f->callno]->transfer));
952 iax_showframe(f, NULL, 0, &iaxs[f->callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
953 res = sendto(netsocket, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[f->callno]->addr,
954 sizeof(iaxs[f->callno]->addr));
958 ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
966 static int iax2_predestroy(int callno)
968 struct ast_channel *c;
969 struct chan_iax2_pvt *pvt;
970 ast_mutex_lock(&iaxsl[callno]);
973 ast_mutex_unlock(&iaxsl[callno]);
976 if (!pvt->alreadygone) {
977 /* No more pings or lagrq's */
978 if (pvt->pingid > -1)
979 ast_sched_del(sched, pvt->pingid);
981 ast_sched_del(sched, pvt->lagid);
982 if (pvt->autoid > -1)
983 ast_sched_del(sched, pvt->autoid);
984 if (pvt->initid > -1)
985 ast_sched_del(sched, pvt->initid);
990 pvt->alreadygone = 1;
994 c->_softhangup |= AST_SOFTHANGUP_DEV;
996 ast_queue_hangup(c, 0);
998 ast_mutex_lock(&usecnt_lock);
1001 ast_log(LOG_WARNING, "Usecnt < 0???\n");
1002 ast_mutex_unlock(&usecnt_lock);
1004 ast_mutex_unlock(&iaxsl[callno]);
1005 ast_update_use_count();
1009 static int iax2_predestroy_nolock(int callno)
1012 ast_mutex_unlock(&iaxsl[callno]);
1013 res = iax2_predestroy(callno);
1014 ast_mutex_lock(&iaxsl[callno]);
1018 static void iax2_destroy(int callno)
1020 struct chan_iax2_pvt *pvt;
1021 struct iax_frame *cur;
1022 struct ast_channel *owner;
1025 ast_mutex_lock(&iaxsl[callno]);
1027 gettimeofday(&lastused[callno], NULL);
1034 if (ast_mutex_trylock(&owner->lock)) {
1035 ast_log(LOG_NOTICE, "Avoiding IAX destroy deadlock\n");
1036 ast_mutex_unlock(&iaxsl[callno]);
1042 iaxs[callno] = NULL;
1046 /* No more pings or lagrq's */
1047 if (pvt->pingid > -1)
1048 ast_sched_del(sched, pvt->pingid);
1049 if (pvt->lagid > -1)
1050 ast_sched_del(sched, pvt->lagid);
1051 if (pvt->autoid > -1)
1052 ast_sched_del(sched, pvt->autoid);
1053 if (pvt->initid > -1)
1054 ast_sched_del(sched, pvt->initid);
1059 if (pvt->bridgetrans)
1060 ast_translator_free_path(pvt->bridgetrans);
1061 pvt->bridgetrans = NULL;
1064 pvt->alreadygone = 1;
1067 /* If there's an owner, prod it to give up */
1068 owner->_softhangup |= AST_SOFTHANGUP_DEV;
1069 ast_queue_hangup(owner, 0);
1072 for (cur = iaxq.head; cur ; cur = cur->next) {
1073 /* Cancel any pending transmissions */
1074 if (cur->callno == pvt->callno)
1078 pvt->reg->callno = 0;
1084 ast_mutex_unlock(&owner->lock);
1086 ast_mutex_unlock(&iaxsl[callno]);
1087 if (callno & 0x4000)
1090 static void iax2_destroy_nolock(int callno)
1092 /* Actually it's easier to unlock, kill it, and relock */
1093 ast_mutex_unlock(&iaxsl[callno]);
1094 iax2_destroy(callno);
1095 ast_mutex_lock(&iaxsl[callno]);
1098 static int update_packet(struct iax_frame *f)
1100 /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
1101 struct ast_iax2_full_hdr *fh = f->data;
1102 /* Mark this as a retransmission */
1103 fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
1105 f->iseqno = iaxs[f->callno]->iseqno;
1106 fh->iseqno = f->iseqno;
1110 static int attempt_transmit(void *data)
1112 /* Attempt to transmit the frame to the remote peer...
1113 Called without iaxsl held. */
1114 struct iax_frame *f = data;
1116 int callno = f->callno;
1117 /* Make sure this call is still active */
1119 ast_mutex_lock(&iaxsl[callno]);
1120 if ((f->callno) && iaxs[f->callno]) {
1121 if ((f->retries < 0) /* Already ACK'd */ ||
1122 (f->retries >= max_retries) /* Too many attempts */) {
1123 /* Record an error if we've transmitted too many times */
1124 if (f->retries >= max_retries) {
1126 /* Transfer timeout */
1127 send_command(iaxs[f->callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
1128 } else if (f->final) {
1130 iax2_destroy_nolock(f->callno);
1132 if (iaxs[f->callno]->owner)
1133 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);
1134 iaxs[f->callno]->error = ETIMEDOUT;
1135 if (iaxs[f->callno]->owner) {
1136 struct ast_frame fr = { 0, };
1138 fr.frametype = AST_FRAME_CONTROL;
1139 fr.subclass = AST_CONTROL_HANGUP;
1140 iax2_queue_frame(f->callno, &fr);
1142 if (iaxs[f->callno]->reg) {
1143 memset(&iaxs[f->callno]->reg->us, 0, sizeof(iaxs[f->callno]->reg->us));
1144 iaxs[f->callno]->reg->regstate = REG_STATE_TIMEOUT;
1145 iaxs[f->callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
1147 iax2_destroy_nolock(f->callno);
1154 /* Update it if it needs it */
1156 /* Attempt transmission */
1159 /* Try again later after 10 times as long */
1161 if (f->retrytime > MAX_RETRY_TIME)
1162 f->retrytime = MAX_RETRY_TIME;
1163 /* Transfer messages max out at one second */
1164 if (f->transfer && (f->retrytime > 1000))
1165 f->retrytime = 1000;
1166 f->retrans = ast_sched_add(sched, f->retrytime, attempt_transmit, f);
1169 /* Make sure it gets freed */
1174 ast_mutex_unlock(&iaxsl[callno]);
1175 /* Do not try again */
1177 /* Don't attempt delivery, just remove it from the queue */
1178 ast_mutex_lock(&iaxq.lock);
1180 f->prev->next = f->next;
1182 iaxq.head = f->next;
1184 f->next->prev = f->prev;
1186 iaxq.tail = f->prev;
1188 ast_mutex_unlock(&iaxq.lock);
1190 /* Free the IAX frame */
1196 static int iax2_set_jitter(int fd, int argc, char *argv[])
1198 if ((argc != 4) && (argc != 5))
1199 return RESULT_SHOWUSAGE;
1201 max_jitter_buffer = atoi(argv[3]);
1202 if (max_jitter_buffer < 0)
1203 max_jitter_buffer = 0;
1206 if ((atoi(argv[3]) >= 0) && (atoi(argv[3]) < IAX_MAX_CALLS)) {
1207 if (iaxs[atoi(argv[3])]) {
1208 iaxs[atoi(argv[3])]->jitterbuffer = atoi(argv[4]);
1209 if (iaxs[atoi(argv[3])]->jitterbuffer < 0)
1210 iaxs[atoi(argv[3])]->jitterbuffer = 0;
1212 ast_cli(fd, "No such call '%d'\n", atoi(argv[3]));
1214 ast_cli(fd, "%d is not a valid call number\n", atoi(argv[3]));
1217 return RESULT_SUCCESS;
1220 static char jitter_usage[] =
1221 "Usage: iax set jitter [callid] <value>\n"
1222 " If used with a callid, it sets the jitter buffer to the given static\n"
1223 "value (until its next calculation). If used without a callid, the value is used\n"
1224 "to establish the maximum excess jitter buffer that is permitted before the jitter\n"
1225 "buffer size is reduced.";
1227 static int iax2_show_stats(int fd, int argc, char *argv[])
1229 struct iax_frame *cur;
1230 int cnt = 0, dead=0, final=0;
1232 return RESULT_SHOWUSAGE;
1233 for (cur = iaxq.head; cur ; cur = cur->next) {
1234 if (cur->retries < 0)
1240 ast_cli(fd, " IAX Statistics\n");
1241 ast_cli(fd, "---------------------\n");
1242 ast_cli(fd, "Outstanding frames: %d (%d ingress, %d outgress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
1243 ast_cli(fd, "Packets in transmit queue: %d dead, %d final, %d total\n", dead, final, cnt);
1244 return RESULT_SUCCESS;
1247 static int iax2_show_cache(int fd, int argc, char *argv[])
1249 struct iax2_dpcache *dp;
1250 char tmp[1024], *pc;
1254 gettimeofday(&tv, NULL);
1255 ast_mutex_lock(&dpcache_lock);
1257 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
1259 s = dp->expirey.tv_sec - tv.tv_sec;
1261 if (dp->flags & CACHE_FLAG_EXISTS)
1262 strcat(tmp, "EXISTS|");
1263 if (dp->flags & CACHE_FLAG_NONEXISTANT)
1264 strcat(tmp, "NONEXISTANT|");
1265 if (dp->flags & CACHE_FLAG_CANEXIST)
1266 strcat(tmp, "CANEXIST|");
1267 if (dp->flags & CACHE_FLAG_PENDING)
1268 strcat(tmp, "PENDING|");
1269 if (dp->flags & CACHE_FLAG_TIMEOUT)
1270 strcat(tmp, "TIMEOUT|");
1271 if (dp->flags & CACHE_FLAG_TRANSMITTED)
1272 strcat(tmp, "TRANSMITTED|");
1273 if (dp->flags & CACHE_FLAG_MATCHMORE)
1274 strcat(tmp, "MATCHMORE|");
1275 if (dp->flags & CACHE_FLAG_UNKNOWN)
1276 strcat(tmp, "UNKNOWN|");
1277 /* Trim trailing pipe */
1279 tmp[strlen(tmp) - 1] = '\0';
1281 strcpy(tmp, "(none)");
1283 pc = strchr(dp->peercontext, '@');
1285 pc = dp->peercontext;
1288 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
1289 if (dp->waiters[x] > -1)
1292 ast_cli(fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
1294 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
1297 ast_mutex_unlock(&dpcache_lock);
1298 return RESULT_SUCCESS;
1301 static char show_stats_usage[] =
1302 "Usage: iax show stats\n"
1303 " Display statistics on IAX channel driver.\n";
1306 static char show_cache_usage[] =
1307 "Usage: iax show cache\n"
1308 " Display currently cached IAX Dialplan results.\n";
1310 static struct ast_cli_entry cli_set_jitter =
1311 { { "iax2", "set", "jitter", NULL }, iax2_set_jitter, "Sets IAX jitter buffer", jitter_usage };
1313 static struct ast_cli_entry cli_show_stats =
1314 { { "iax2", "show", "stats", NULL }, iax2_show_stats, "Display IAX statistics", show_stats_usage };
1316 static struct ast_cli_entry cli_show_cache =
1317 { { "iax2", "show", "cache", NULL }, iax2_show_cache, "Display IAX cached dialplan", show_cache_usage };
1319 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p);
1321 #ifdef BRIDGE_OPTIMIZATION
1322 static unsigned int calc_fakestamp(struct chan_iax2_pvt *from, struct chan_iax2_pvt *to, unsigned int ts);
1324 static int forward_delivery(struct iax_frame *fr)
1326 struct chan_iax2_pvt *p1, *p2;
1327 p1 = iaxs[fr->callno];
1328 p2 = iaxs[p1->bridgecallno];
1333 /* Fix relative timestamp */
1334 fr->ts = calc_fakestamp(p1, p2, fr->ts);
1335 /* Now just send it send on the 2nd one
1336 with adjusted timestamp */
1337 return iax2_send(p2, &fr->af, fr->ts, -1, 0, 0, 0);
1341 static int schedule_delivery(struct iax_frame *fr, int reallydeliver, int updatehistory)
1344 int drops[MEMORY_SIZE];
1345 int min, max=0, maxone=0,y,z, match;
1346 /* ms is a measure of the "lateness" of the packet relative to the first
1347 packet we received, which always has a lateness of 1. Called by
1348 IAX thread, with iaxsl lock held. */
1349 ms = calc_rxstamp(iaxs[fr->callno]) - fr->ts;
1352 /* What likely happened here is that our counter has circled but we haven't
1353 gotten the update from the main packet. We'll just pretend that we did, and
1354 update the timestamp appropriately. */
1359 /* We got this packet out of order. Lets add 65536 to it to bring it into our new
1364 /* Rotate our history queue of "lateness". Don't worry about those initial
1365 zeros because the first entry will always be zero */
1366 if (updatehistory) {
1367 for (x=0;x<MEMORY_SIZE - 1;x++)
1368 iaxs[fr->callno]->history[x] = iaxs[fr->callno]->history[x+1];
1369 /* Add a history entry for this one */
1370 iaxs[fr->callno]->history[x] = ms;
1373 /* Initialize the minimum to reasonable values. It's too much
1374 work to do the same for the maximum, repeatedly */
1375 min=iaxs[fr->callno]->history[0];
1376 for (z=0;z < iax2_dropcount + 1;z++) {
1377 /* Start very optimistic ;-) */
1379 for (x=0;x<MEMORY_SIZE;x++) {
1380 if (max < iaxs[fr->callno]->history[x]) {
1381 /* We have a candidate new maximum value. Make
1382 sure it's not in our drop list */
1384 for (y=0;!match && (y<z);y++)
1385 match |= (drops[y] == x);
1387 /* It's not in our list, use it as the new maximum */
1388 max = iaxs[fr->callno]->history[x];
1394 /* On our first pass, find the minimum too */
1395 if (min > iaxs[fr->callno]->history[x])
1396 min = iaxs[fr->callno]->history[x];
1403 /* Just for reference, keep the "jitter" value, the difference between the
1404 earliest and the latest. */
1405 iaxs[fr->callno]->jitter = max - min;
1407 /* IIR filter for keeping track of historic jitter, but always increase
1408 historic jitter immediately for increase */
1410 if (iaxs[fr->callno]->jitter > iaxs[fr->callno]->historicjitter )
1411 iaxs[fr->callno]->historicjitter = iaxs[fr->callno]->jitter;
1413 iaxs[fr->callno]->historicjitter = GAMMA * (double)iaxs[fr->callno]->jitter + (1-GAMMA) *
1414 iaxs[fr->callno]->historicjitter;
1416 /* If our jitter buffer is too big (by a significant margin), then we slowly
1417 shrink it by about 1 ms each time to avoid letting the change be perceived */
1418 if (max < iaxs[fr->callno]->jitterbuffer - max_jitter_buffer)
1419 iaxs[fr->callno]->jitterbuffer -= 2;
1423 /* Constrain our maximum jitter buffer appropriately */
1424 if (max > min + maxjitterbuffer) {
1426 ast_log(LOG_DEBUG, "Constraining buffer from %d to %d + %d\n", max, min , maxjitterbuffer);
1427 max = min + maxjitterbuffer;
1431 /* If our jitter buffer is smaller than our maximum delay, grow the jitter
1432 buffer immediately to accomodate it (and a little more). */
1433 if (max > iaxs[fr->callno]->jitterbuffer)
1434 iaxs[fr->callno]->jitterbuffer = max
1435 /* + ((float)iaxs[fr->callno]->jitter) * 0.1 */;
1439 ast_log(LOG_DEBUG, "min = %d, max = %d, jb = %d, lateness = %d\n", min, max, iaxs[fr->callno]->jitterbuffer, ms);
1441 /* Subtract the lateness from our jitter buffer to know how long to wait
1442 before sending our packet. */
1443 ms = iaxs[fr->callno]->jitterbuffer - ms;
1445 if (!use_jitterbuffer)
1448 /* If the caller just wanted us to update, return now */
1454 ast_log(LOG_DEBUG, "Calculated ms is %d\n", ms);
1455 /* Don't deliver it more than 4 ms late */
1456 if ((ms > -4) || (fr->af.frametype != AST_FRAME_VOICE)) {
1460 ast_log(LOG_DEBUG, "Dropping voice packet since %d ms is, too old\n", ms);
1461 /* Free our iax frame */
1462 iax2_frame_free(fr);
1466 ast_log(LOG_DEBUG, "Scheduling delivery in %d ms\n", ms);
1467 fr->retrans = ast_sched_add(sched, ms, do_deliver, fr);
1472 static int iax2_transmit(struct iax_frame *fr)
1474 /* Lock the queue and place this packet at the end */
1477 /* By setting this to 0, the network thread will send it for us, and
1478 queue retransmission if necessary */
1480 ast_mutex_lock(&iaxq.lock);
1487 iaxq.tail->next = fr;
1488 fr->prev = iaxq.tail;
1492 ast_mutex_unlock(&iaxq.lock);
1493 /* Wake up the network thread */
1494 pthread_kill(netthreadid, SIGURG);
1500 static int iax2_digit(struct ast_channel *c, char digit)
1502 return send_command_locked(c->pvt->pvt, AST_FRAME_DTMF, digit, 0, NULL, 0, -1);
1505 static int iax2_sendtext(struct ast_channel *c, char *text)
1508 return send_command_locked(c->pvt->pvt, AST_FRAME_TEXT,
1509 0, 0, text, strlen(text) + 1, -1);
1512 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
1514 return send_command_locked(c->pvt->pvt, AST_FRAME_IMAGE, img->subclass, 0, img->data, img->datalen, -1);
1517 static int iax2_sendhtml(struct ast_channel *c, int subclass, char *data, int datalen)
1519 return send_command_locked(c->pvt->pvt, AST_FRAME_HTML, subclass, 0, data, datalen, -1);
1522 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
1524 struct chan_iax2_pvt *pvt = newchan->pvt->pvt;
1525 pvt->owner = newchan;
1529 #ifdef MYSQL_FRIENDS
1531 static void mysql_update_peer(char *peer, struct sockaddr_in *sin)
1533 if (mysql && (strlen(peer) < 128)) {
1537 name = alloca(strlen(peer) * 2 + 1);
1539 mysql_real_escape_string(mysql, name, peer, strlen(peer));
1540 snprintf(query, sizeof(query), "UPDATE iaxfriends SET ipaddr=\"%s\", port=\"%d\", regseconds=\"%ld\" WHERE name=\"%s\"",
1541 inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), nowtime, name);
1542 ast_mutex_lock(&mysqllock);
1543 if (mysql_real_query(mysql, query, strlen(query)))
1544 ast_log(LOG_WARNING, "Unable to update database\n");
1546 ast_mutex_unlock(&mysqllock);
1550 static struct iax2_peer *mysql_peer(char *peer)
1552 struct iax2_peer *p;
1555 p = malloc(sizeof(struct iax2_peer));
1556 memset(p, 0, sizeof(struct iax2_peer));
1557 if (mysql && (strlen(peer) < 128)) {
1562 time_t regseconds, nowtime;
1564 MYSQL_FIELD *fields;
1566 name = alloca(strlen(peer) * 2 + 1);
1567 mysql_real_escape_string(mysql, name, peer, strlen(peer));
1568 snprintf(query, sizeof(query), "SELECT * FROM iaxfriends WHERE name=\"%s\"", name);
1569 ast_mutex_lock(&mysqllock);
1570 mysql_query(mysql, query);
1571 if ((result = mysql_store_result(mysql))) {
1572 if ((rowval = mysql_fetch_row(result))) {
1573 numfields = mysql_num_fields(result);
1574 fields = mysql_fetch_fields(result);
1576 for (x=0;x<numfields;x++) {
1578 if (!strcasecmp(fields[x].name, "secret")) {
1579 strncpy(p->secret, rowval[x], sizeof(p->secret));
1580 } else if (!strcasecmp(fields[x].name, "context")) {
1581 strncpy(p->context, rowval[x], sizeof(p->context) - 1);
1582 } else if (!strcasecmp(fields[x].name, "ipaddr")) {
1583 inet_aton(rowval[x], &p->addr.sin_addr);
1584 } else if (!strcasecmp(fields[x].name, "port")) {
1585 if (sscanf(rowval[x], "%i", &port) != 1)
1587 p->addr.sin_port = htons(port);
1588 } else if (!strcasecmp(fields[x].name, "regseconds")) {
1589 if (sscanf(rowval[x], "%li", ®seconds) != 1)
1595 if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE)
1596 memset(&p->addr, 0, sizeof(p->addr));
1598 mysql_free_result(result);
1601 ast_mutex_unlock(&mysqllock);
1607 strncpy(p->name, peer, sizeof(p->name) - 1);
1611 p->capability = iax2_capability;
1612 p->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
1616 static struct iax2_user *mysql_user(char *user)
1618 struct iax2_user *p;
1619 struct iax2_context *con;
1622 p = malloc(sizeof(struct iax2_user));
1623 memset(p, 0, sizeof(struct iax2_user));
1624 con = malloc(sizeof(struct iax2_context));
1625 memset(con, 0, sizeof(struct iax2_context));
1626 strcpy(con->context, "default");
1628 if (mysql && (strlen(user) < 128)) {
1633 MYSQL_FIELD *fields;
1635 name = alloca(strlen(user) * 2 + 1);
1636 mysql_real_escape_string(mysql, name, user, strlen(user));
1637 snprintf(query, sizeof(query), "SELECT * FROM iaxfriends WHERE name=\"%s\"", name);
1638 ast_mutex_lock(&mysqllock);
1639 mysql_query(mysql, query);
1640 if ((result = mysql_store_result(mysql))) {
1641 if ((rowval = mysql_fetch_row(result))) {
1642 numfields = mysql_num_fields(result);
1643 fields = mysql_fetch_fields(result);
1645 for (x=0;x<numfields;x++) {
1647 if (!strcasecmp(fields[x].name, "secret")) {
1648 strncpy(p->secret, rowval[x], sizeof(p->secret));
1649 } else if (!strcasecmp(fields[x].name, "context")) {
1650 strncpy(p->contexts->context, rowval[x], sizeof(p->contexts->context) - 1);
1655 mysql_free_result(result);
1658 ast_mutex_unlock(&mysqllock);
1666 strncpy(p->name, user, sizeof(p->name) - 1);
1668 p->capability = iax2_capability;
1669 p->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
1673 #endif /* MYSQL_FRIENDS */
1675 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)
1678 struct iax2_peer *p;
1686 sin->sin_family = AF_INET;
1687 ast_mutex_lock(&peerl.lock);
1690 if (!strcasecmp(p->name, peer)) {
1695 ast_mutex_unlock(&peerl.lock);
1696 #ifdef MYSQL_FRIENDS
1698 p = mysql_peer(peer);
1702 if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
1703 (!p->maxms || ((p->lastms > 0) && (p->lastms <= p->maxms)))) {
1705 *sendani = p->sendani; /* Whether we transmit ANI */
1707 *maxtime = p->maxms; /* Max time they should take */
1709 strncpy(context, p->context, AST_MAX_EXTENSION - 1);
1713 *capability = p->capability;
1715 strncpy(secret, p->secret, seclen);
1716 if (p->addr.sin_addr.s_addr) {
1717 sin->sin_addr = p->addr.sin_addr;
1718 sin->sin_port = p->addr.sin_port;
1720 sin->sin_addr = p->defaddr.sin_addr;
1721 sin->sin_port = p->defaddr.sin_port;
1724 *notransfer=p->notransfer;
1732 hp = gethostbyname(peer);
1734 memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
1735 sin->sin_port = htons(IAX_DEFAULT_PORTNO);
1738 ast_log(LOG_WARNING, "No such host: %s\n", peer);
1748 static int auto_congest(void *nothing)
1750 int callno = (int)(long)(nothing);
1751 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_CONGESTION };
1752 ast_mutex_lock(&iaxsl[callno]);
1754 iaxs[callno]->initid = -1;
1755 iax2_queue_frame(callno, &f);
1756 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
1758 ast_mutex_unlock(&iaxsl[callno]);
1762 static unsigned int iax2_datetime(void)
1768 localtime_r(&t, &tm);
1769 tmp = (tm.tm_sec >> 1) & 0x1f; /* 5 bits of seconds */
1770 tmp |= (tm.tm_min & 0x3f) << 5; /* 6 bits of minutes */
1771 tmp |= (tm.tm_hour & 0x1f) << 11; /* 5 bits of hours */
1772 tmp |= (tm.tm_mday & 0x1f) << 16; /* 5 bits of day of month */
1773 tmp |= ((tm.tm_mon + 1) & 0xf) << 21; /* 4 bits of month */
1774 tmp |= ((tm.tm_year - 100) & 0x7f) << 25; /* 7 bits of year */
1778 static int iax2_call(struct ast_channel *c, char *dest, int timeout)
1780 struct sockaddr_in sin;
1785 char *secret = NULL;
1788 char *l=NULL, *n=NULL;
1789 struct iax_ie_data ied;
1790 char myrdest [5] = "s";
1791 char context[AST_MAX_EXTENSION] ="";
1792 char *portno = NULL;
1794 struct chan_iax2_pvt *p = c->pvt->pvt;
1796 char storedsecret[80];
1797 if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
1798 ast_log(LOG_WARNING, "Line is already in use (%s)?\n", c->name);
1801 strncpy(host, dest, sizeof(host)-1);
1803 strsep(&stringp, "/");
1804 /* If no destination extension specified, use 's' */
1805 rdest = strsep(&stringp, "/");
1809 /* Check for trailing options */
1810 opts = strsep(&stringp, "/");
1815 strsep(&stringp, "@");
1816 rcontext = strsep(&stringp, "@");
1818 strsep(&stringp, "@");
1819 username = strsep(&stringp, "@");
1821 /* Really the second argument is the host, not the username */
1829 username = strsep(&stringp, ":");
1830 secret = strsep(&stringp, ":");
1833 if (strsep(&stringp, ":")) {
1835 strsep(&stringp, ":");
1836 portno = strsep(&stringp, ":");
1838 if (create_addr(&sin, NULL, NULL, NULL, hname, context, NULL, NULL, storedsecret, sizeof(storedsecret) - 1)) {
1839 ast_log(LOG_WARNING, "No address associated with '%s'\n", hname);
1842 /* Keep track of the context for outgoing calls too */
1843 strncpy(c->context, context, sizeof(c->context) - 1);
1845 sin.sin_port = htons(atoi(portno));
1848 strncpy(cid, c->callerid, sizeof(cid) - 1);
1849 ast_callerid_parse(cid, &n, &l);
1851 ast_shrink_phone_number(l);
1853 /* Now build request */
1854 memset(&ied, 0, sizeof(ied));
1855 /* On new call, first IE MUST be IAX version of caller */
1856 iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
1857 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, rdest);
1858 if (strchr(opts, 'a')) {
1859 /* Request auto answer */
1860 iax_ie_append(&ied, IAX_IE_AUTOANSWER);
1863 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
1865 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n);
1866 if (p->sendani && c->ani) {
1868 strncpy(cid, c->ani, sizeof(cid) - 1);
1869 ast_callerid_parse(cid, &n, &l);
1871 ast_shrink_phone_number(l);
1872 iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, l);
1875 if (c->language && strlen(c->language))
1876 iax_ie_append_str(&ied, IAX_IE_LANGUAGE, c->language);
1877 if (c->dnid && strlen(c->dnid))
1878 iax_ie_append_str(&ied, IAX_IE_DNID, c->dnid);
1880 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, rcontext);
1882 iax_ie_append_str(&ied, IAX_IE_USERNAME, username);
1883 if (!secret && strlen(storedsecret))
1884 secret = storedsecret;
1886 if (secret[0] == '[') {
1887 /* This is an RSA key, not a normal secret */
1888 strncpy(p->outkey, secret + 1, sizeof(p->secret)-1);
1889 if (strlen(p->outkey)) {
1890 p->outkey[strlen(p->outkey) - 1] = '\0';
1893 strncpy(p->secret, secret, sizeof(p->secret)-1);
1895 iax_ie_append_int(&ied, IAX_IE_FORMAT, c->nativeformats);
1896 iax_ie_append_int(&ied, IAX_IE_CAPABILITY, p->capability);
1897 iax_ie_append_short(&ied, IAX_IE_ADSICPE, c->adsicpe);
1898 iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime());
1899 /* Transmit the string in a "NEW" request */
1901 /* XXX We have no equivalent XXX */
1902 if (option_verbose > 2)
1903 ast_verbose(VERBOSE_PREFIX_3 "Calling using options '%s'\n", requeststr);
1906 /* Initialize pingtime and auto-congest time */
1907 p->pingtime = p->maxtime / 2;
1908 p->initid = ast_sched_add(sched, p->maxtime * 2, auto_congest, (void *)(long)p->callno);
1910 send_command_locked(p, AST_FRAME_IAX,
1911 IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
1912 ast_setstate(c, AST_STATE_RINGING);
1916 static int iax2_hangup(struct ast_channel *c)
1918 struct chan_iax2_pvt *pvt = c->pvt->pvt;
1922 callno = pvt->callno;
1923 ast_mutex_lock(&iaxsl[callno]);
1924 ast_log(LOG_DEBUG, "We're hanging up %s now...\n", c->name);
1925 alreadygone = pvt->alreadygone;
1926 /* Send the hangup unless we have had a transmission error or are already gone */
1927 if (!pvt->error && !alreadygone)
1928 send_command_final(pvt, AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, NULL, 0, -1);
1929 /* Explicitly predestroy it */
1930 iax2_predestroy_nolock(callno);
1931 /* If we were already gone to begin with, destroy us now */
1933 ast_log(LOG_DEBUG, "Really destroying %s now...\n", c->name);
1934 iax2_destroy_nolock(callno);
1936 ast_mutex_unlock(&iaxsl[callno]);
1938 if (option_verbose > 2)
1939 ast_verbose(VERBOSE_PREFIX_3 "Hungup '%s'\n", c->name);
1943 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
1945 struct ast_option_header *h;
1947 h = malloc(datalen + sizeof(struct ast_option_header));
1949 h->flag = AST_OPTION_FLAG_REQUEST;
1950 h->option = htons(option);
1951 memcpy(h->data, data, datalen);
1952 res = send_command_locked((struct chan_iax2_pvt *)c->pvt->pvt, AST_FRAME_CONTROL,
1953 AST_CONTROL_OPTION, 0, (char *)h, datalen + sizeof(struct ast_option_header), -1);
1957 ast_log(LOG_WARNING, "Out of memory\n");
1960 static struct ast_frame *iax2_read(struct ast_channel *c)
1962 static struct ast_frame f = { AST_FRAME_NULL, };
1963 ast_log(LOG_NOTICE, "I should never be called!\n");
1967 static int iax2_start_transfer(struct ast_channel *c0, struct ast_channel *c1)
1970 struct iax_ie_data ied0;
1971 struct iax_ie_data ied1;
1972 struct chan_iax2_pvt *p0 = c0->pvt->pvt;
1973 struct chan_iax2_pvt *p1 = c1->pvt->pvt;
1974 unsigned int transferid = rand();
1975 memset(&ied0, 0, sizeof(ied0));
1976 iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &p1->addr);
1977 iax_ie_append_short(&ied0, IAX_IE_CALLNO, p1->peercallno);
1978 iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, transferid);
1980 memset(&ied1, 0, sizeof(ied1));
1981 iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &p0->addr);
1982 iax_ie_append_short(&ied1, IAX_IE_CALLNO, p0->peercallno);
1983 iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, transferid);
1985 res = send_command(p0, AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
1988 res = send_command(p1, AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
1991 p0->transferring = TRANSFER_BEGIN;
1992 p1->transferring = TRANSFER_BEGIN;
1996 static void lock_both(struct chan_iax2_pvt *p0, struct chan_iax2_pvt *p1)
1998 ast_mutex_lock(&iaxsl[p0->callno]);
1999 while (ast_mutex_trylock(&iaxsl[p1->callno])) {
2000 ast_mutex_unlock(&iaxsl[p0->callno]);
2002 ast_mutex_lock(&iaxsl[p0->callno]);
2006 static void unlock_both(struct chan_iax2_pvt *p0, struct chan_iax2_pvt *p1)
2008 ast_mutex_unlock(&iaxsl[p1->callno]);
2009 ast_mutex_unlock(&iaxsl[p0->callno]);
2012 static int iax2_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
2014 struct ast_channel *cs[3];
2015 struct ast_channel *who;
2018 int transferstarted=0;
2019 struct ast_frame *f;
2020 struct chan_iax2_pvt *p0 = c0->pvt->pvt;
2021 struct chan_iax2_pvt *p1 = c1->pvt->pvt;
2022 struct timeval waittimer = {0, 0}, tv;
2025 /* Put them in native bridge mode */
2026 p0->bridgecallno = p1->callno;
2027 p1->bridgecallno = p0->callno;
2028 unlock_both(p0, p1);
2030 /* If not, try to bridge until we can execute a transfer, if we can */
2033 for (/* ever */;;) {
2034 /* Check in case we got masqueraded into */
2035 if ((c0->type != type) || (c1->type != type)) {
2036 if (option_verbose > 2)
2037 ast_verbose(VERBOSE_PREFIX_3 "Can't masquerade, we're different...\n");
2038 /* Remove from native mode */
2039 if (c0->type == type) {
2040 ast_mutex_lock(&iaxsl[p0->callno]);
2041 p0->bridgecallno = 0;
2042 ast_mutex_unlock(&iaxsl[p0->callno]);
2044 if (c1->type == type) {
2045 ast_mutex_lock(&iaxsl[p1->callno]);
2046 p1->bridgecallno = 0;
2047 ast_mutex_unlock(&iaxsl[p1->callno]);
2051 if (c0->nativeformats != c1->nativeformats) {
2052 ast_verbose(VERBOSE_PREFIX_3 "Operating with different codecs, can't native bridge...\n");
2053 /* Remove from native mode */
2055 p0->bridgecallno = 0;
2056 p1->bridgecallno = 0;
2057 unlock_both(p0, p1);
2060 /* check if transfered and if we really want native bridging */
2061 if (!transferstarted && !p0->notransfer && !p1->notransfer) {
2062 /* Try the transfer */
2063 if (iax2_start_transfer(c0, c1))
2064 ast_log(LOG_WARNING, "Unable to start the transfer\n");
2065 transferstarted = 1;
2067 if ((p0->transferring == TRANSFER_RELEASED) && (p1->transferring == TRANSFER_RELEASED)) {
2068 /* Call has been transferred. We're no longer involved */
2069 gettimeofday(&tv, NULL);
2070 if (!waittimer.tv_sec && !waittimer.tv_usec) {
2071 waittimer.tv_sec = tv.tv_sec;
2072 waittimer.tv_usec = tv.tv_usec;
2073 } else if (tv.tv_sec - waittimer.tv_sec > IAX_LINGER_TIMEOUT) {
2074 c0->_softhangup |= AST_SOFTHANGUP_DEV;
2075 c1->_softhangup |= AST_SOFTHANGUP_DEV;
2083 who = ast_waitfor_n(cs, 2, &to);
2085 if (ast_check_hangup(c0) || ast_check_hangup(c1)) {
2098 if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
2104 if ((f->frametype == AST_FRAME_VOICE) ||
2105 (f->frametype == AST_FRAME_TEXT) ||
2106 (f->frametype == AST_FRAME_VIDEO) ||
2107 (f->frametype == AST_FRAME_IMAGE) ||
2108 (f->frametype == AST_FRAME_DTMF)) {
2109 if ((f->frametype == AST_FRAME_DTMF) &&
2110 (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
2112 if ((flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
2115 /* Take out of conference mode */
2117 /* Remove from native mode */
2123 if (flags & AST_BRIDGE_DTMF_CHANNEL_1) {
2127 /* Remove from native mode */
2134 ast_log(LOG_DEBUG, "Read from %s\n", who->name);
2136 ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
2148 /* Swap who gets priority */
2154 p0->bridgecallno = 0;
2155 p1->bridgecallno = 0;
2156 unlock_both(p0, p1);
2160 static int iax2_answer(struct ast_channel *c)
2162 struct chan_iax2_pvt *pvt = c->pvt->pvt;
2164 ast_log(LOG_DEBUG, "Answering\n");
2165 return send_command(pvt, AST_FRAME_CONTROL, AST_CONTROL_ANSWER, 0, NULL, 0, -1);
2168 static int iax2_indicate(struct ast_channel *c, int condition)
2170 struct chan_iax2_pvt *pvt = c->pvt->pvt;
2172 ast_log(LOG_DEBUG, "Indicating condition %d\n", condition);
2173 return send_command(pvt, AST_FRAME_CONTROL, condition, 0, NULL, 0, -1);
2176 static int iax2_transfer(struct ast_channel *c, char *dest)
2178 struct chan_iax2_pvt *pvt = c->pvt->pvt;
2179 struct iax_ie_data ied;
2180 char tmp[256] = "", *context;
2181 strncpy(tmp, dest, sizeof(tmp) - 1);
2182 context = strchr(tmp, '@');
2187 memset(&ied, 0, sizeof(ied));
2188 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, tmp);
2190 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, context);
2192 ast_log(LOG_DEBUG, "Transferring '%s' to '%s'\n", c->name, dest);
2193 return send_command(pvt, AST_FRAME_IAX, IAX_COMMAND_TRANSFER, 0, ied.buf, ied.pos, -1);
2197 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
2199 static int iax2_getpeertrunk(struct sockaddr_in sin)
2201 struct iax2_peer *peer;
2203 ast_mutex_lock(&peerl.lock);
2206 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
2207 (peer->addr.sin_port == sin.sin_port)) {
2213 ast_mutex_unlock(&peerl.lock);
2217 static struct ast_channel *ast_iax2_new(struct chan_iax2_pvt *i, int state, int capability)
2219 struct ast_channel *tmp;
2220 tmp = ast_channel_alloc(1);
2222 if (strlen(i->username))
2223 snprintf(tmp->name, sizeof(tmp->name), "IAX2[%s@%s]/%d", i->username, i->host, i->callno);
2225 snprintf(tmp->name, sizeof(tmp->name), "IAX2[%s]/%d", i->host, i->callno);
2227 /* We can support any format by default, until we get restricted */
2228 tmp->nativeformats = capability;
2229 tmp->readformat = 0;
2230 tmp->writeformat = 0;
2232 tmp->pvt->send_digit = iax2_digit;
2233 tmp->pvt->send_text = iax2_sendtext;
2234 tmp->pvt->send_image = iax2_sendimage;
2235 tmp->pvt->send_html = iax2_sendhtml;
2236 tmp->pvt->call = iax2_call;
2237 tmp->pvt->hangup = iax2_hangup;
2238 tmp->pvt->answer = iax2_answer;
2239 tmp->pvt->read = iax2_read;
2240 tmp->pvt->write = iax2_write;
2241 tmp->pvt->write_video = iax2_write;
2242 tmp->pvt->indicate = iax2_indicate;
2243 tmp->pvt->setoption = iax2_setoption;
2244 tmp->pvt->bridge = iax2_bridge;
2245 tmp->pvt->transfer = iax2_transfer;
2246 if (strlen(i->callerid))
2247 tmp->callerid = strdup(i->callerid);
2249 tmp->ani = strdup(i->ani);
2250 if (strlen(i->language))
2251 strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
2252 if (strlen(i->dnid))
2253 tmp->dnid = strdup(i->dnid);
2254 if (strlen(i->accountcode))
2255 strncpy(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode)-1);
2257 tmp->amaflags = i->amaflags;
2258 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
2259 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
2260 tmp->adsicpe = i->peeradsicpe;
2261 tmp->pvt->fixup = iax2_fixup;
2263 i->capability = capability;
2264 ast_setstate(tmp, state);
2265 ast_mutex_lock(&usecnt_lock);
2267 ast_mutex_unlock(&usecnt_lock);
2268 ast_update_use_count();
2269 if (state != AST_STATE_DOWN) {
2270 if (ast_pbx_start(tmp)) {
2271 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
2280 static unsigned int calc_txpeerstamp(struct iax2_peer *peer)
2283 unsigned int mssincetx;
2285 gettimeofday(&tv, NULL);
2286 mssincetx = (tv.tv_sec - peer->lasttxtime.tv_sec) * 1000 + (tv.tv_usec - peer->lasttxtime.tv_usec) / 1000;
2287 if (mssincetx > 5000) {
2288 /* If it's been at least 5 seconds since the last time we transmitted on this trunk, reset our timers */
2289 peer->txtrunktime.tv_sec = tv.tv_sec;
2290 peer->txtrunktime.tv_usec = tv.tv_usec;
2292 /* Update last transmit time now */
2293 peer->lasttxtime.tv_sec = tv.tv_sec;
2294 peer->lasttxtime.tv_usec = tv.tv_usec;
2296 /* Calculate ms offset */
2297 ms = (tv.tv_sec - peer->txtrunktime.tv_sec) * 1000 + (tv.tv_usec - peer->txtrunktime.tv_usec) / 1000;
2299 /* We never send the same timestamp twice, so fudge a little if we must */
2300 if (ms == peer->lastsent)
2301 ms = peer->lastsent + 1;
2302 peer->lastsent = ms;
2306 static unsigned int fix_peerts(struct iax2_peer *peer, int callno, unsigned int ts)
2308 long ms; /* NOT unsigned */
2309 if (!iaxs[callno]->rxcore.tv_sec && !iaxs[callno]->rxcore.tv_usec) {
2310 /* Initialize rxcore time if appropriate */
2311 gettimeofday(&iaxs[callno]->rxcore, NULL);
2313 /* Calculate difference between trunk and channel */
2314 ms = (peer->rxtrunktime.tv_sec - iaxs[callno]->rxcore.tv_sec) * 1000 +
2315 (peer->rxtrunktime.tv_usec - iaxs[callno]->rxcore.tv_usec) / 1000;
2316 /* Return as the sum of trunk time and the difference between trunk and real time */
2320 static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts)
2324 if (!p->offset.tv_sec && !p->offset.tv_usec)
2325 gettimeofday(&p->offset, NULL);
2326 /* If the timestamp is specified, just send it as is */
2329 gettimeofday(&tv, NULL);
2330 ms = (tv.tv_sec - p->offset.tv_sec) * 1000 + (tv.tv_usec - p->offset.tv_usec) / 1000;
2331 /* We never send the same timestamp twice, so fudge a little if we must */
2332 if (ms <= p->lastsent)
2333 ms = p->lastsent + 1;
2338 #ifdef BRIDGE_OPTIMIZATION
2339 static unsigned int calc_fakestamp(struct chan_iax2_pvt *p1, struct chan_iax2_pvt *p2, unsigned int fakets)
2342 /* Receive from p1, send to p2 */
2344 /* Setup rxcore if necessary on outgoing channel */
2345 if (!p1->rxcore.tv_sec && !p1->rxcore.tv_usec)
2346 gettimeofday(&p1->rxcore, NULL);
2348 /* Setup txcore if necessary on outgoing channel */
2349 if (!p2->offset.tv_sec && !p2->offset.tv_usec)
2350 gettimeofday(&p2->offset, NULL);
2352 /* Now, ts is the timestamp of the original packet in the orignal context.
2353 Adding rxcore to it gives us when we would want the packet to be delivered normally.
2354 Subtracting txcore of the outgoing channel gives us what we'd expect */
2356 ms = (p1->rxcore.tv_sec - p2->offset.tv_sec) * 1000 + (p1->rxcore.tv_usec - p2->offset.tv_usec) / 1000;
2358 if (fakets <= p2->lastsent)
2359 fakets = p2->lastsent + 1;
2360 p2->lastsent = fakets;
2365 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p)
2367 /* Returns where in "receive time" we are */
2370 /* Setup rxcore if necessary */
2371 if (!p->rxcore.tv_sec && !p->rxcore.tv_usec)
2372 gettimeofday(&p->rxcore, NULL);
2374 gettimeofday(&tv, NULL);
2375 ms = (tv.tv_sec - p->rxcore.tv_sec) * 1000 + (tv.tv_usec - p->rxcore.tv_usec) / 1000;
2379 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final)
2381 /* Queue a packet for delivery on a given private structure. Use "ts" for
2382 timestamp, or calculate if ts is 0. Send immediately without retransmission
2383 or delayed, with retransmission */
2384 struct ast_iax2_full_hdr *fh;
2385 struct ast_iax2_mini_hdr *mh;
2386 struct ast_iax2_video_hdr *vh;
2388 struct iax_frame fr2;
2389 unsigned char buffer[4096];
2391 struct iax_frame *fr;
2394 unsigned int lastsent;
2398 ast_log(LOG_WARNING, "No private structure for packet?\n");
2402 lastsent = pvt->lastsent;
2404 /* Calculate actual timestamp */
2405 fts = calc_timestamp(pvt, ts);
2407 if ((pvt->trunk || ((fts & 0xFFFF0000L) == (lastsent & 0xFFFF0000L)))
2408 /* High two bits are the same on timestamp, or sending on a trunk */ &&
2409 (f->frametype == AST_FRAME_VOICE)
2410 /* is a voice frame */ &&
2411 (f->subclass == pvt->svoiceformat)
2412 /* is the same type */ ) {
2413 /* Force immediate rather than delayed transmission */
2415 /* Mark that mini-style frame is appropriate */
2418 if (((fts & 0xFFFF8000L) == (lastsent & 0xFFFF8000L)) &&
2419 (f->frametype == AST_FRAME_VIDEO) &&
2420 ((f->subclass & ~0x1) == pvt->svideoformat)) {
2424 /* Allocate an iax_frame */
2428 fr = iax_frame_new(DIRECTION_OUTGRESS, f->datalen);
2430 ast_log(LOG_WARNING, "Out of memory\n");
2433 /* Copy our prospective frame into our immediate or retransmitted wrapper */
2434 iax_frame_wrap(fr, f);
2438 ast_log(LOG_WARNING, "timestamp is 0?\n");
2440 iax2_frame_free(fr);
2443 fr->callno = pvt->callno;
2444 fr->transfer = transfer;
2447 /* We need a full frame */
2451 fr->oseqno = pvt->oseqno++;
2452 fr->iseqno = pvt->iseqno;
2453 fh = (struct ast_iax2_full_hdr *)(fr->af.data - sizeof(struct ast_iax2_full_hdr));
2454 fh->scallno = htons(fr->callno | IAX_FLAG_FULL);
2455 fh->ts = htonl(fr->ts);
2456 fh->oseqno = fr->oseqno;
2460 fh->iseqno = fr->iseqno;
2461 /* Keep track of the last thing we've acknowledged */
2463 pvt->aseqno = fr->iseqno;
2464 fh->type = fr->af.frametype & 0xFF;
2465 if (fr->af.frametype == AST_FRAME_VIDEO)
2466 fh->csub = compress_subclass(fr->af.subclass & ~0x1) | ((fr->af.subclass & 0x1) << 6);
2468 fh->csub = compress_subclass(fr->af.subclass);
2470 fr->dcallno = pvt->transfercallno;
2472 fr->dcallno = pvt->peercallno;
2473 fh->dcallno = htons(fr->dcallno);
2474 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_full_hdr);
2477 /* Retry after 2x the ping time has passed */
2478 fr->retrytime = pvt->pingtime * 2;
2479 if (fr->retrytime < MIN_RETRY_TIME)
2480 fr->retrytime = MIN_RETRY_TIME;
2481 if (fr->retrytime > MAX_RETRY_TIME)
2482 fr->retrytime = MAX_RETRY_TIME;
2483 /* Acks' don't get retried */
2484 if ((f->frametype == AST_FRAME_IAX) && (f->subclass == IAX_COMMAND_ACK))
2486 if (f->frametype == AST_FRAME_VOICE) {
2487 pvt->svoiceformat = f->subclass;
2489 if (f->frametype == AST_FRAME_VIDEO) {
2490 pvt->svideoformat = f->subclass & ~0x1;
2493 res = send_packet(fr);
2495 res = iax2_transmit(fr);
2498 /* Queue for transmission in a meta frame */
2499 if ((sizeof(pvt->trunkdata) - pvt->trunkdatalen) >= fr->af.datalen) {
2500 memcpy(pvt->trunkdata + pvt->trunkdatalen, fr->af.data, fr->af.datalen);
2501 pvt->trunkdatalen += fr->af.datalen;
2503 pvt->trunkerror = 0;
2505 if (!pvt->trunkerror)
2506 ast_log(LOG_WARNING, "Out of trunk data space on call number %d, dropping\n", pvt->callno);
2507 pvt->trunkerror = 1;
2510 } else if (fr->af.frametype == AST_FRAME_VIDEO) {
2511 /* Video frame have no sequence number */
2514 vh = (struct ast_iax2_video_hdr *)(fr->af.data - sizeof(struct ast_iax2_video_hdr));
2516 vh->callno = htons(0x8000 | fr->callno);
2517 vh->ts = htons((fr->ts & 0x7FFF) | (fr->af.subclass & 0x1 ? 0x8000 : 0));
2518 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_video_hdr);
2521 res = send_packet(fr);
2523 /* Mini-frames have no sequence number */
2526 /* Mini frame will do */
2527 mh = (struct ast_iax2_mini_hdr *)(fr->af.data - sizeof(struct ast_iax2_mini_hdr));
2528 mh->callno = htons(fr->callno);
2529 mh->ts = htons(fr->ts & 0xFFFF);
2530 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_mini_hdr);
2533 res = send_packet(fr);
2541 static int iax2_show_users(int fd, int argc, char *argv[])
2543 #define FORMAT "%-15.15s %-15.15s %-15.15s %-15.15s %-5.5s\n"
2544 #define FORMAT2 "%-15.15s %-15.15s %-15.15d %-15.15s %-5.5s\n"
2545 struct iax2_user *user;
2547 return RESULT_SHOWUSAGE;
2548 ast_mutex_lock(&userl.lock);
2549 ast_cli(fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C");
2550 for(user=userl.users;user;user=user->next) {
2551 ast_cli(fd, FORMAT2, user->name, user->secret, user->authmethods,
2552 user->contexts ? user->contexts->context : context,
2553 user->ha ? "Yes" : "No");
2555 ast_mutex_unlock(&userl.lock);
2556 return RESULT_SUCCESS;
2561 static int iax2_show_peers(int fd, int argc, char *argv[])
2563 #define FORMAT2 "%-15.15s %-15.15s %s %-15.15s %-8s %-10s\n"
2564 #define FORMAT "%-15.15s %-15.15s %s %-15.15s %-5d%s %-10s\n"
2565 struct iax2_peer *peer;
2566 char name[256] = "";
2567 int registeredonly=0;
2568 if ((argc != 3) && (argc != 4))
2569 return RESULT_SHOWUSAGE;
2571 if (!strcasecmp(argv[3], "registered")) {
2574 return RESULT_SHOWUSAGE;
2576 ast_mutex_lock(&peerl.lock);
2577 ast_cli(fd, FORMAT2, "Name/Username", "Host", " ", "Mask", "Port", "Status");
2578 for (peer = peerl.peers;peer;peer = peer->next) {
2581 if (registeredonly && !peer->addr.sin_addr.s_addr)
2583 if (strlen(peer->username))
2584 snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
2586 strncpy(name, peer->name, sizeof(name) - 1);
2588 if (peer->lastms < 0)
2589 strcpy(status, "UNREACHABLE");
2590 else if (peer->lastms > peer->maxms)
2591 snprintf(status, sizeof(status), "LAGGED (%d ms)", peer->lastms);
2592 else if (peer->lastms)
2593 snprintf(status, sizeof(status), "OK (%d ms)", peer->lastms);
2595 strcpy(status, "UNKNOWN");
2597 strcpy(status, "Unmonitored");
2598 strncpy(nm, inet_ntoa(peer->mask), sizeof(nm)-1);
2599 ast_cli(fd, FORMAT, name,
2600 peer->addr.sin_addr.s_addr ? inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
2601 peer->dynamic ? "(D)" : "(S)",
2603 ntohs(peer->addr.sin_port), peer->trunk ? "(T)" : " ", status);
2605 ast_mutex_unlock(&peerl.lock);
2606 return RESULT_SUCCESS;
2611 /* JDG: callback to display iax peers in manager */
2612 static int manager_iax2_show_peers( struct mansession *s, struct message *m )
2614 char *a[] = { "iax2", "show", "users" };
2616 ret = iax2_show_peers( s->fd, 3, a );
2617 ast_cli( s->fd, "\r\n" );
2621 static char *regstate2str(int regstate)
2624 case REG_STATE_UNREGISTERED:
2625 return "Unregistered";
2626 case REG_STATE_REGSENT:
2627 return "Request Sent";
2628 case REG_STATE_AUTHSENT:
2629 return "Auth. Sent";
2630 case REG_STATE_REGISTERED:
2631 return "Registered";
2632 case REG_STATE_REJECTED:
2634 case REG_STATE_TIMEOUT:
2636 case REG_STATE_NOAUTH:
2637 return "No Authentication";
2643 static int iax2_show_registry(int fd, int argc, char *argv[])
2645 #define FORMAT2 "%-20.20s %-10.10s %-20.20s %8.8s %s\n"
2646 #define FORMAT "%-20.20s %-10.10s %-20.20s %8d %s\n"
2647 struct iax2_registry *reg;
2651 return RESULT_SHOWUSAGE;
2652 ast_mutex_lock(&peerl.lock);
2653 ast_cli(fd, FORMAT2, "Host", "Username", "Perceived", "Refresh", "State");
2654 for (reg = registrations;reg;reg = reg->next) {
2655 snprintf(host, sizeof(host), "%s:%d", inet_ntoa(reg->addr.sin_addr), ntohs(reg->addr.sin_port));
2656 if (reg->us.sin_addr.s_addr)
2657 snprintf(perceived, sizeof(perceived), "%s:%d", inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
2659 strcpy(perceived, "<Unregistered>");
2660 ast_cli(fd, FORMAT, host,
2661 reg->username, perceived, reg->refresh, regstate2str(reg->regstate));
2663 ast_mutex_unlock(&peerl.lock);
2664 return RESULT_SUCCESS;
2669 static int iax2_show_channels(int fd, int argc, char *argv[])
2671 #define FORMAT2 "%-15.15s %-10.10s %-11.11s %-11.11s %-7.7s %-6.6s %s\n"
2672 #define FORMAT "%-15.15s %-10.10s %5.5d/%5.5d %5.5d/%5.5d %-5.5dms %-4.4dms %-6.6s\n"
2676 return RESULT_SHOWUSAGE;
2677 ast_cli(fd, FORMAT2, "Peer", "Username", "ID (Lo/Rem)", "Seq (Tx/Rx)", "Lag", "Jitter", "Format");
2678 for (x=0;x<IAX_MAX_CALLS;x++) {
2679 ast_mutex_lock(&iaxsl[x]);
2681 ast_cli(fd, FORMAT, inet_ntoa(iaxs[x]->addr.sin_addr),
2682 strlen(iaxs[x]->username) ? iaxs[x]->username : "(None)",
2683 iaxs[x]->callno, iaxs[x]->peercallno,
2684 iaxs[x]->oseqno, iaxs[x]->iseqno,
2687 ast_getformatname(iaxs[x]->voiceformat) );
2690 ast_mutex_unlock(&iaxsl[x]);
2692 ast_cli(fd, "%d active IAX channel(s)\n", numchans);
2693 return RESULT_SUCCESS;
2698 static int iax2_do_trunk_debug(int fd, int argc, char *argv[])
2701 return RESULT_SHOWUSAGE;
2703 ast_cli(fd, "IAX2 Trunk Debug Requested\n");
2704 return RESULT_SUCCESS;
2707 static int iax2_do_debug(int fd, int argc, char *argv[])
2710 return RESULT_SHOWUSAGE;
2712 ast_cli(fd, "IAX2 Debugging Enabled\n");
2713 return RESULT_SUCCESS;
2716 static int iax2_no_debug(int fd, int argc, char *argv[])
2719 return RESULT_SHOWUSAGE;
2721 ast_cli(fd, "IAX2 Debugging Disabled\n");
2722 return RESULT_SUCCESS;
2727 static char show_users_usage[] =
2728 "Usage: iax2 show users\n"
2729 " Lists all users known to the IAX (Inter-Asterisk eXchange rev 2) subsystem.\n";
2731 static char show_channels_usage[] =
2732 "Usage: iax2 show channels\n"
2733 " Lists all currently active IAX channels.\n";
2735 static char show_peers_usage[] =
2736 "Usage: iax2 show peers\n"
2737 " Lists all known IAX peers.\n";
2739 static char show_reg_usage[] =
2740 "Usage: iax2 show registry\n"
2741 " Lists all registration requests and status.\n";
2743 static char debug_usage[] =
2744 "Usage: iax2 debug\n"
2745 " Enables dumping of IAX packets for debugging purposes\n";
2747 static char no_debug_usage[] =
2748 "Usage: iax2 no debug\n"
2749 " Disables dumping of IAX packets for debugging purposes\n";
2751 static char debug_trunk_usage[] =
2752 "Usage: iax2 trunk debug\n"
2753 " Requests current status of IAX trunking\n";
2755 static struct ast_cli_entry cli_show_users =
2756 { { "iax2", "show", "users", NULL }, iax2_show_users, "Show defined IAX users", show_users_usage };
2757 static struct ast_cli_entry cli_show_channels =
2758 { { "iax2", "show", "channels", NULL }, iax2_show_channels, "Show active IAX channels", show_channels_usage };
2759 static struct ast_cli_entry cli_show_peers =
2760 { { "iax2", "show", "peers", NULL }, iax2_show_peers, "Show defined IAX peers", show_peers_usage };
2761 static struct ast_cli_entry cli_show_registry =
2762 { { "iax2", "show", "registry", NULL }, iax2_show_registry, "Show IAX registration status", show_reg_usage };
2763 static struct ast_cli_entry cli_debug =
2764 { { "iax2", "debug", NULL }, iax2_do_debug, "Enable IAX debugging", debug_usage };
2765 static struct ast_cli_entry cli_trunk_debug =
2766 { { "iax2", "trunk", "debug", NULL }, iax2_do_trunk_debug, "Request IAX trunk debug", debug_trunk_usage };
2767 static struct ast_cli_entry cli_no_debug =
2768 { { "iax2", "no", "debug", NULL }, iax2_no_debug, "Disable IAX debugging", no_debug_usage };
2770 static int iax2_write(struct ast_channel *c, struct ast_frame *f)
2772 struct chan_iax2_pvt *i = c->pvt->pvt;
2775 /* If there's an outstanding error, return failure now */
2777 ast_log(LOG_DEBUG, "Write error: %s\n", strerror(errno));
2780 /* If it's already gone, just return */
2783 /* Don't waste bandwidth sending null frames */
2784 if (f->frametype == AST_FRAME_NULL)
2786 /* If we're quelching voice, don't bother sending it */
2787 if ((f->frametype == AST_FRAME_VOICE) && i->quelch)
2789 if (!(i->state & IAX_STATE_STARTED))
2791 /* Simple, just queue for transmission */
2792 return iax2_send(i, f, 0, -1, 0, 0, 0);
2795 static int __send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno,
2796 int now, int transfer, int final)
2800 f.subclass = command;
2801 f.datalen = datalen;
2805 f.src = __FUNCTION__;
2807 return iax2_send(i, &f, ts, seqno, now, transfer, final);
2810 static int send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2812 return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 0);
2815 static int send_command_locked(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2818 ast_mutex_lock(&iaxsl[i->callno]);
2819 res = send_command(i, type, command, ts, data, datalen, seqno);
2820 ast_mutex_unlock(&iaxsl[i->callno]);
2824 #ifdef BRIDGE_OPTIMIZATION
2825 static int forward_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2827 return __send_command(iaxs[i->bridgecallno], type, command, ts, data, datalen, seqno, 0, 0, 0);
2831 static int send_command_final(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2833 /* It is assumed that the callno has already been locked */
2834 iax2_predestroy_nolock(i->callno);
2835 return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 1);
2838 static int send_command_immediate(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2840 return __send_command(i, type, command, ts, data, datalen, seqno, 1, 0, 0);
2843 static int send_command_transfer(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen)
2845 return __send_command(i, type, command, ts, data, datalen, 0, 0, 1, 0);
2848 static int apply_context(struct iax2_context *con, char *context)
2851 if (!strcmp(con->context, context))
2859 static int check_access(int callno, struct sockaddr_in *sin, struct iax_ies *ies)
2861 /* Start pessimistic */
2864 struct iax2_user *user;
2865 int gotcapability=0;
2868 if (ies->called_number)
2869 strncpy(iaxs[callno]->exten, ies->called_number, sizeof(iaxs[callno]->exten) - 1);
2870 if (ies->calling_number) {
2871 if (ies->calling_name)
2872 snprintf(iaxs[callno]->callerid, sizeof(iaxs[callno]->callerid), "\"%s\" <%s>", ies->calling_name, ies->calling_number);
2874 strncpy(iaxs[callno]->callerid, ies->calling_number, sizeof(iaxs[callno]->callerid) - 1);
2875 } else if (ies->calling_name)
2876 strncpy(iaxs[callno]->callerid, ies->calling_name, sizeof(iaxs[callno]->callerid) - 1);
2877 if (ies->calling_ani)
2878 strncpy(iaxs[callno]->ani, ies->calling_ani, sizeof(iaxs[callno]->ani) - 1);
2880 strncpy(iaxs[callno]->dnid, ies->dnid, sizeof(iaxs[callno]->dnid)-1);
2881 if (ies->called_context)
2882 strncpy(iaxs[callno]->context, ies->called_context, sizeof(iaxs[callno]->context)-1);
2884 strncpy(iaxs[callno]->language, ies->language, sizeof(iaxs[callno]->language)-1);
2886 strncpy(iaxs[callno]->username, ies->username, sizeof(iaxs[callno]->username)-1);
2888 iaxs[callno]->peerformat = ies->format;
2890 iaxs[callno]->peeradsicpe = ies->adsicpe;
2891 if (ies->capability) {
2893 iaxs[callno]->peercapability = ies->capability;
2896 version = ies->version;
2898 iaxs[callno]->peercapability = iaxs[callno]->peerformat;
2899 if (version > IAX_PROTO_VERSION) {
2900 ast_log(LOG_WARNING, "Peer '%s' has too new a protocol version (%d) for me\n",
2901 inet_ntoa(sin->sin_addr), version);
2904 ast_mutex_lock(&userl.lock);
2905 /* Search the userlist for a compatible entry, and fill in the rest */
2908 if ((!strlen(iaxs[callno]->username) || /* No username specified */
2909 !strcmp(iaxs[callno]->username, user->name)) /* Or this username specified */
2910 && ast_apply_ha(user->ha, sin) /* Access is permitted from this IP */
2911 && (!strlen(iaxs[callno]->context) || /* No context specified */
2912 apply_context(user->contexts, iaxs[callno]->context))) { /* Context is permitted */
2917 ast_mutex_unlock(&userl.lock);
2918 #ifdef MYSQL_FRIENDS
2919 if (!user && mysql && strlen(iaxs[callno]->username) && (strlen(iaxs[callno]->username) < 128)) {
2920 user = mysql_user(iaxs[callno]->username);
2921 if (user && strlen(iaxs[callno]->context) && /* No context specified */
2922 !apply_context(user->contexts, iaxs[callno]->context)) { /* Context is permitted */
2924 free(user->contexts);
2931 /* We found our match (use the first) */
2933 /* Store the requested username if not specified */
2934 if (!strlen(iaxs[callno]->username))
2935 strncpy(iaxs[callno]->username, user->name, sizeof(iaxs[callno]->username)-1);
2936 /* Store whether this is a trunked call, too, of course, and move if appropriate */
2937 iaxs[callno]->trunk = user->trunk;
2938 iaxs[callno]->capability = user->capability;
2939 /* And use the default context */
2940 if (!strlen(iaxs[callno]->context)) {
2942 strncpy(iaxs[callno]->context, user->contexts->context, sizeof(iaxs[callno]->context)-1);
2944 strncpy(iaxs[callno]->context, context, sizeof(iaxs[callno]->context)-1);
2946 /* Copy the secret */
2947 strncpy(iaxs[callno]->secret, user->secret, sizeof(iaxs[callno]->secret)-1);
2948 /* And any input keys */
2949 strncpy(iaxs[callno]->inkeys, user->inkeys, sizeof(iaxs[callno]->inkeys));
2950 /* And the permitted authentication methods */
2951 iaxs[callno]->authmethods = user->authmethods;
2952 /* If they have callerid, override the given caller id. Always store the ANI */
2953 if (strlen(iaxs[callno]->callerid)) {
2954 if (user->hascallerid)
2955 strncpy(iaxs[callno]->callerid, user->callerid, sizeof(iaxs[callno]->callerid)-1);
2956 strncpy(iaxs[callno]->ani, user->callerid, sizeof(iaxs[callno]->ani)-1);
2958 if (strlen(user->accountcode))
2959 strncpy(iaxs[callno]->accountcode, user->accountcode, sizeof(iaxs[callno]->accountcode)-1);
2961 iaxs[callno]->amaflags = user->amaflags;
2962 iaxs[callno]->notransfer = user->notransfer;
2965 iaxs[callno]->trunk = iax2_getpeertrunk(*sin);
2969 static int raw_hangup(struct sockaddr_in *sin, unsigned short src, unsigned short dst)
2971 struct ast_iax2_full_hdr fh;
2972 fh.scallno = htons(src | IAX_FLAG_FULL);
2973 fh.dcallno = htons(dst);
2977 fh.type = AST_FRAME_IAX;
2978 fh.csub = compress_subclass(IAX_COMMAND_INVAL);
2982 ast_log(LOG_DEBUG, "Raw Hangup %s:%d, src=%d, dst=%d\n",
2983 inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), src, dst);
2984 return sendto(netsocket, &fh, sizeof(fh), 0, (struct sockaddr *)sin, sizeof(*sin));
2987 static int authenticate_request(struct chan_iax2_pvt *p)
2989 struct iax_ie_data ied;
2990 memset(&ied, 0, sizeof(ied));
2991 iax_ie_append_short(&ied, IAX_IE_AUTHMETHODS, p->authmethods);
2992 if (p->authmethods & (IAX_AUTH_MD5 | IAX_AUTH_RSA)) {
2993 snprintf(p->challenge, sizeof(p->challenge), "%d", rand());
2994 iax_ie_append_str(&ied, IAX_IE_CHALLENGE, p->challenge);
2996 iax_ie_append_str(&ied,IAX_IE_USERNAME, p->username);
2997 return send_command(p, AST_FRAME_IAX, IAX_COMMAND_AUTHREQ, 0, ied.buf, ied.pos, -1);
3000 static int authenticate_verify(struct chan_iax2_pvt *p, struct iax_ies *ies)
3002 char requeststr[256] = "";
3003 char md5secret[256] = "";
3004 char secret[256] = "";
3005 char rsasecret[256] = "";
3009 if (!(p->state & IAX_STATE_AUTHENTICATED))
3012 strncpy(secret, ies->password, sizeof(secret) - 1);
3013 if (ies->md5_result)
3014 strncpy(md5secret, ies->md5_result, sizeof(md5secret)-1);
3015 if (ies->rsa_result)
3016 strncpy(rsasecret, ies->rsa_result, sizeof(rsasecret)-1);
3017 if ((p->authmethods & IAX_AUTH_RSA) && strlen(rsasecret) && strlen(p->inkeys)) {
3018 struct ast_key *key;
3022 strncpy(tmpkey, p->inkeys, sizeof(tmpkey));
3024 keyn = strsep(&stringp, ":");
3026 key = ast_key_get(keyn, AST_KEY_PUBLIC);
3027 if (key && !ast_check_signature(key, p->challenge, rsasecret)) {
3031 ast_log(LOG_WARNING, "requested inkey '%s' for RSA authentication does not exist\n", keyn);
3032 keyn = strsep(&stringp, ":");
3034 } else if (p->authmethods & IAX_AUTH_MD5) {
3035 struct MD5Context md5;
3036 unsigned char digest[16];
3038 MD5Update(&md5, p->challenge, strlen(p->challenge));
3039 MD5Update(&md5, p->secret, strlen(p->secret));
3040 MD5Final(digest, &md5);
3041 /* If they support md5, authenticate with it. */
3043 sprintf(requeststr + (x << 1), "%2.2x", digest[x]);
3044 if (!strcasecmp(requeststr, md5secret))
3046 } else if (p->authmethods & IAX_AUTH_PLAINTEXT) {
3047 if (!strcmp(secret, p->secret))
3053 static int register_verify(int callno, struct sockaddr_in *sin, struct iax_ies *ies)
3055 char requeststr[256] = "";
3056 char peer[256] = "";
3057 char md5secret[256] = "";
3058 char rsasecret[256] = "";
3059 char secret[256] = "";
3060 struct iax2_peer *p;
3061 struct ast_key *key;
3066 iaxs[callno]->state &= ~IAX_STATE_AUTHENTICATED;
3067 strcpy(iaxs[callno]->peer, "");
3069 strncpy(peer, ies->username, sizeof(peer) - 1);
3071 strncpy(secret, ies->password, sizeof(secret) - 1);
3072 if (ies->md5_result)
3073 strncpy(md5secret, ies->md5_result, sizeof(md5secret)-1);
3074 if (ies->rsa_result)
3075 strncpy(rsasecret, ies->rsa_result, sizeof(rsasecret)-1);
3077 expire = ies->refresh;
3079 if (!strlen(peer)) {
3080 ast_log(LOG_NOTICE, "Empty registration from %s\n", inet_ntoa(sin->sin_addr));
3084 ast_mutex_lock(&peerl.lock);
3085 for (p = peerl.peers; p ; p = p->next)
3086 if (!strcasecmp(p->name, peer))
3088 ast_mutex_unlock(&peerl.lock);
3089 #ifdef MYSQL_FRIENDS
3091 p = mysql_peer(peer);
3096 ast_log(LOG_NOTICE, "No registration for peer '%s' (from %s)\n", peer, inet_ntoa(sin->sin_addr));
3102 ast_log(LOG_NOTICE, "Peer '%s' is not dynamic (from %s)\n", peer, inet_ntoa(sin->sin_addr));
3108 if (!ast_apply_ha(p->ha, sin)) {
3110 ast_log(LOG_NOTICE, "Host %s denied access to register peer '%s'\n", inet_ntoa(sin->sin_addr), p->name);
3115 strncpy(iaxs[callno]->secret, p->secret, sizeof(iaxs[callno]->secret)-1);
3116 strncpy(iaxs[callno]->inkeys, p->inkeys, sizeof(iaxs[callno]->inkeys)-1);
3117 /* Check secret against what we have on file */
3118 if (strlen(rsasecret) && (p->authmethods & IAX_AUTH_RSA) && strlen(iaxs[callno]->challenge)) {
3119 if (strlen(p->inkeys)) {
3122 strncpy(tmpkeys, p->inkeys, sizeof(tmpkeys));
3124 keyn = strsep(&stringp, ":");
3126 key = ast_key_get(keyn, AST_KEY_PUBLIC);
3127 if (key && !ast_check_signature(key, iaxs[callno]->challenge, rsasecret)) {
3128 iaxs[callno]->state |= IAX_STATE_AUTHENTICATED;
3131 ast_log(LOG_WARNING, "requested inkey '%s' does not exist\n", keyn);
3132 keyn = strsep(&stringp, ":");
3136 ast_log(LOG_NOTICE, "Host %s failed RSA authentication with inkeys '%s'\n", peer, p->inkeys);
3143 ast_log(LOG_NOTICE, "Host '%s' trying to do RSA authentication, but we have no inkeys\n", peer);
3148 } else if (strlen(secret) && (p->authmethods & IAX_AUTH_PLAINTEXT)) {
3149 /* They've provided a plain text password and we support that */
3150 if (strcmp(secret, p->secret)) {
3152 ast_log(LOG_NOTICE, "Host %s did not provide proper plaintext password for '%s'\n", inet_ntoa(sin->sin_addr), p->name);
3157 iaxs[callno]->state |= IAX_STATE_AUTHENTICATED;
3158 } else if (strlen(md5secret) && (p->authmethods & IAX_AUTH_MD5) && strlen(iaxs[callno]->challenge)) {
3159 struct MD5Context md5;
3160 unsigned char digest[16];
3162 MD5Update(&md5, iaxs[callno]->challenge, strlen(iaxs[callno]->challenge));
3163 MD5Update(&md5, p->secret, strlen(p->secret));
3164 MD5Final(digest, &md5);
3166 sprintf(requeststr + (x << 1), "%2.2x", digest[x]);
3167 if (strcasecmp(requeststr, md5secret)) {
3169 ast_log(LOG_NOTICE, "Host %s failed MD5 authentication for '%s' (%s != %s)\n", inet_ntoa(sin->sin_addr), p->name, requeststr, md5secret);
3174 iaxs[callno]->state |= IAX_STATE_AUTHENTICATED;
3175 } else if (strlen(md5secret) || strlen(secret)) {
3177 ast_log(LOG_NOTICE, "Inappropriate authentication received\n");
3182 strncpy(iaxs[callno]->peer, peer, sizeof(iaxs[callno]->peer)-1);
3183 /* Choose lowest expirey number */
3184 if (expire && (expire < iaxs[callno]->expirey))
3185 iaxs[callno]->expirey = expire;
3192 static int authenticate(char *challenge, char *secret, char *keyn, int authmethods, struct iax_ie_data *ied, struct sockaddr_in *sin)
3196 if (keyn && strlen(keyn)) {
3197 if (!(authmethods & IAX_AUTH_RSA)) {
3198 if (!secret || !strlen(secret))
3199 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));
3200 } else if (!strlen(challenge)) {
3201 ast_log(LOG_NOTICE, "No challenge provided for RSA authentication to %s\n", inet_ntoa(sin->sin_addr));
3204 struct ast_key *key;
3205 key = ast_key_get(keyn, AST_KEY_PRIVATE);
3207 ast_log(LOG_NOTICE, "Unable to find private key '%s'\n", keyn);
3209 if (ast_sign(key, challenge, sig)) {
3210 ast_log(LOG_NOTICE, "Unable to sign challenge withy key\n");
3213 iax_ie_append_str(ied, IAX_IE_RSA_RESULT, sig);
3220 if (res && secret && strlen(secret)) {
3221 if ((authmethods & IAX_AUTH_MD5) && strlen(challenge)) {
3222 struct MD5Context md5;
3223 unsigned char digest[16];
3224 char digres[128] = "";
3226 MD5Update(&md5, challenge, strlen(challenge));
3227 MD5Update(&md5, secret, strlen(secret));
3228 MD5Final(digest, &md5);
3229 /* If they support md5, authenticate with it. */
3231 sprintf(digres + (x << 1), "%2.2x", digest[x]);
3232 iax_ie_append_str(ied, IAX_IE_MD5_RESULT, digres);
3234 } else if (authmethods & IAX_AUTH_PLAINTEXT) {
3235 iax_ie_append_str(ied, IAX_IE_PASSWORD, secret);
3238 ast_log(LOG_NOTICE, "No way to send secret to peer '%s' (their methods: %d)\n", inet_ntoa(sin->sin_addr), authmethods);
3243 static int authenticate_reply(struct chan_iax2_pvt *p, struct sockaddr_in *sin, struct iax_ies *ies, char *override, char *okey)
3245 struct iax2_peer *peer;
3246 /* Start pessimistic */
3248 int authmethods = 0;
3249 struct iax_ie_data ied;
3251 memset(&ied, 0, sizeof(ied));
3254 strncpy(p->username, ies->username, sizeof(p->username) - 1);
3256 strncpy(p->challenge, ies->challenge, sizeof(p->challenge)-1);
3257 if (ies->authmethods)
3258 authmethods = ies->authmethods;
3260 /* Check for override RSA authentication first */
3261 if ((override && strlen(override)) || (okey && strlen(okey))) {
3262 /* Normal password authentication */
3263 res = authenticate(p->challenge, override, okey, authmethods, &ied, sin);
3265 ast_mutex_lock(&peerl.lock);
3268 if ((!strlen(p->peer) || !strcmp(p->peer, peer->name))
3269 /* No peer specified at our end, or this is the peer */
3270 && (!strlen(peer->username) || (!strcmp(peer->username, p->username)))
3271 /* No username specified in peer rule, or this is the right username */
3272 && (!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)))
3273 /* No specified host, or this is our host */
3275 res = authenticate(p->challenge, peer->secret, peer->outkey, authmethods, &ied, sin);
3281 ast_mutex_unlock(&peerl.lock);
3284 res = send_command(p, AST_FRAME_IAX, IAX_COMMAND_AUTHREP, 0, ied.buf, ied.pos, -1);
3288 static int iax2_do_register(struct iax2_registry *reg);
3290 static int iax2_do_register_s(void *data)
3292 struct iax2_registry *reg = data;
3294 iax2_do_register(reg);
3298 static int try_transfer(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
3301 char newip[256] = "";
3302 struct iax_ie_data ied;
3303 struct sockaddr_in new;
3306 memset(&ied, 0, sizeof(ied));
3307 if (ies->apparent_addr)
3308 memcpy(&new, ies->apparent_addr, sizeof(new));
3310 newcall = ies->callno;
3311 if (!newcall || !new.sin_addr.s_addr || !new.sin_port) {
3312 ast_log(LOG_WARNING, "Invalid transfer request\n");
3315 pvt->transfercallno = newcall;
3316 memcpy(&pvt->transfer, &new, sizeof(pvt->transfer));
3317 inet_aton(newip, &pvt->transfer.sin_addr);
3318 pvt->transfer.sin_family = AF_INET;
3319 pvt->transferring = TRANSFER_BEGIN;
3320 pvt->transferid = ies->transferid;
3321 if (ies->transferid)
3322 iax_ie_append_int(&ied, IAX_IE_TRANSFERID, ies->transferid);
3323 send_command_transfer(pvt, AST_FRAME_IAX, IAX_COMMAND_TXCNT, 0, ied.buf, ied.pos);
3327 static int complete_dpreply(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
3329 char exten[256] = "";
3330 int status = CACHE_FLAG_UNKNOWN;
3331 int expirey = iaxdefaultdpcache;
3334 struct iax2_dpcache *dp, *prev;
3336 if (ies->called_number)
3337 strncpy(exten, ies->called_number, sizeof(exten)-1);
3339 if (ies->dpstatus & IAX_DPSTATUS_EXISTS)
3340 status = CACHE_FLAG_EXISTS;
3341 else if (ies->dpstatus & IAX_DPSTATUS_CANEXIST)
3342 status = CACHE_FLAG_CANEXIST;
3343 else if (ies->dpstatus & IAX_DPSTATUS_NONEXISTANT)
3344 status = CACHE_FLAG_NONEXISTANT;
3346 if (ies->dpstatus & IAX_DPSTATUS_IGNOREPAT) {
3347 /* Don't really do anything with this */
3350 expirey = ies->refresh;
3351 if (ies->dpstatus & IAX_DPSTATUS_MATCHMORE)
3352 matchmore = CACHE_FLAG_MATCHMORE;
3353 ast_mutex_lock(&dpcache_lock);
3355 dp = pvt->dpentries;
3357 if (!strcmp(dp->exten, exten)) {
3360 prev->peer = dp->peer;
3362 pvt->dpentries = dp->peer;
3365 dp->expirey.tv_sec = dp->orig.tv_sec + expirey;
3366 if (dp->flags & CACHE_FLAG_PENDING) {
3367 dp->flags &= ~CACHE_FLAG_PENDING;
3368 dp->flags |= status;
3369 dp->flags |= matchmore;
3371 /* Wake up waiters */
3372 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
3373 if (dp->waiters[x] > -1)
3374 write(dp->waiters[x], "asdf", 4);
3379 ast_mutex_unlock(&dpcache_lock);
3383 static int complete_transfer(int callno, struct iax_ies *ies)
3386 struct chan_iax2_pvt *pvt = iaxs[callno];
3387 struct iax_frame *cur;
3390 peercallno = ies->callno;
3392 if (peercallno < 1) {
3393 ast_log(LOG_WARNING, "Invalid transfer request\n");
3396 memcpy(&pvt->addr, &pvt->transfer, sizeof(pvt->addr));
3397 memset(&pvt->transfer, 0, sizeof(pvt->transfer));
3398 /* Reset sequence numbers */
3402 pvt->peercallno = peercallno;
3403 pvt->transferring = TRANSFER_NONE;
3404 pvt->svoiceformat = -1;
3405 pvt->voiceformat = 0;
3406 pvt->svideoformat = -1;
3407 pvt->videoformat = 0;
3408 pvt->transfercallno = -1;
3409 memset(&pvt->rxcore, 0, sizeof(pvt->rxcore));
3410 memset(&pvt->offset, 0, sizeof(pvt->offset));
3411 memset(&pvt->history, 0, sizeof(pvt->history));
3412 pvt->jitterbuffer = 0;
3414 pvt->historicjitter = 0;
3418 pvt->pingtime = DEFAULT_RETRY_TIME;
3419 ast_mutex_lock(&iaxq.lock);
3420 for (cur = iaxq.head; cur ; cur = cur->next) {
3421 /* We must cancel any packets that would have been transmitted
3422 because now we're talking to someone new. It's okay, they
3423 were transmitted to someone that didn't care anyway. */
3424 if (callno == cur->callno)
3427 ast_mutex_unlock(&iaxq.lock);
3431 static int iax2_ack_registry(struct iax_ies *ies, struct sockaddr_in *sin, int callno)
3433 struct iax2_registry *reg;
3434 /* Start pessimistic */
3435 char peer[256] = "";
3436 char msgstatus[40] = "";
3438 char ourip[256] = "<Unspecified>";
3439 struct sockaddr_in oldus;
3440 struct sockaddr_in us;
3443 memset(&us, 0, sizeof(us));
3444 if (ies->apparent_addr)
3445 memcpy(&us, ies->apparent_addr, sizeof(us));
3447 strncpy(peer, ies->username, sizeof(peer) - 1);
3449 refresh = ies->refresh;
3450 if (ies->calling_number) {
3451 /* We don't do anything with it really, but maybe we should */
3453 reg = iaxs[callno]->reg;
3455 ast_log(LOG_WARNING, "Registry acknowledge on unknown registery '%s'\n", peer);
3458 memcpy(&oldus, ®->us, sizeof(oldus));
3459 oldmsgs = reg->messages;
3460 if (inaddrcmp(®->addr, sin)) {
3461 ast_log(LOG_WARNING, "Received unsolicited registry ack from '%s'\n", inet_ntoa(sin->sin_addr));
3464 memcpy(®->us, &us, sizeof(reg->us));
3465 reg->messages = ies->msgcount;
3466 if (refresh && (reg->refresh < refresh)) {
3467 /* Refresh faster if necessary */
3468 reg->refresh = refresh;
3469 if (reg->expire > -1)
3470 ast_sched_del(sched, reg->expire);
3471 reg->expire = ast_sched_add(sched, (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
3473 if ((inaddrcmp(&oldus, ®->us) || (reg->messages != oldmsgs)) && (option_verbose > 2)) {
3474 if (reg->messages > 65534)
3475 snprintf(msgstatus, sizeof(msgstatus), " with message(s) waiting\n");
3476 else if (reg->messages > 1)
3477 snprintf(msgstatus, sizeof(msgstatus), " with %d messages waiting\n", reg->messages);
3478 else if (reg->messages > 0)
3479 snprintf(msgstatus, sizeof(msgstatus), " with 1 message waiting\n");
3480 else if (reg->messages > -1)
3481 snprintf(msgstatus, sizeof(msgstatus), " with no messages waiting\n");
3482 snprintf(ourip, sizeof(ourip), "%s:%d", inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
3483 ast_verbose(VERBOSE_PREFIX_3 "Registered to '%s', who sees us as %s%s\n", inet_ntoa(sin->sin_addr), ourip, msgstatus);
3485 reg->regstate = REG_STATE_REGISTERED;