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]);
1041 iaxs[callno] = NULL;
1044 /* No more pings or lagrq's */
1045 if (pvt->pingid > -1)
1046 ast_sched_del(sched, pvt->pingid);
1047 if (pvt->lagid > -1)
1048 ast_sched_del(sched, pvt->lagid);
1049 if (pvt->autoid > -1)
1050 ast_sched_del(sched, pvt->autoid);
1051 if (pvt->initid > -1)
1052 ast_sched_del(sched, pvt->initid);
1057 if (pvt->bridgetrans)
1058 ast_translator_free_path(pvt->bridgetrans);
1059 pvt->bridgetrans = NULL;
1062 pvt->alreadygone = 1;
1065 /* If there's an owner, prod it to give up */
1066 owner->pvt->pvt = NULL;
1067 owner->_softhangup |= AST_SOFTHANGUP_DEV;
1068 ast_queue_hangup(owner, 0);
1071 for (cur = iaxq.head; cur ; cur = cur->next) {
1072 /* Cancel any pending transmissions */
1073 if (cur->callno == pvt->callno)
1077 pvt->reg->callno = 0;
1082 ast_mutex_unlock(&owner->lock);
1084 ast_mutex_unlock(&iaxsl[callno]);
1085 if (callno & 0x4000)
1088 static void iax2_destroy_nolock(int callno)
1090 /* Actually it's easier to unlock, kill it, and relock */
1091 ast_mutex_unlock(&iaxsl[callno]);
1092 iax2_destroy(callno);
1093 ast_mutex_lock(&iaxsl[callno]);
1096 static int update_packet(struct iax_frame *f)
1098 /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
1099 struct ast_iax2_full_hdr *fh = f->data;
1100 /* Mark this as a retransmission */
1101 fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
1103 f->iseqno = iaxs[f->callno]->iseqno;
1104 fh->iseqno = f->iseqno;
1108 static int attempt_transmit(void *data)
1110 /* Attempt to transmit the frame to the remote peer...
1111 Called without iaxsl held. */
1112 struct iax_frame *f = data;
1114 int callno = f->callno;
1115 /* Make sure this call is still active */
1117 ast_mutex_lock(&iaxsl[callno]);
1118 if ((f->callno) && iaxs[f->callno]) {
1119 if ((f->retries < 0) /* Already ACK'd */ ||
1120 (f->retries >= max_retries) /* Too many attempts */) {
1121 /* Record an error if we've transmitted too many times */
1122 if (f->retries >= max_retries) {
1124 /* Transfer timeout */
1125 send_command(iaxs[f->callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
1126 } else if (f->final) {
1128 iax2_destroy_nolock(f->callno);
1130 if (iaxs[f->callno]->owner)
1131 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);
1132 iaxs[f->callno]->error = ETIMEDOUT;
1133 if (iaxs[f->callno]->owner) {
1134 struct ast_frame fr = { 0, };
1136 fr.frametype = AST_FRAME_CONTROL;
1137 fr.subclass = AST_CONTROL_HANGUP;
1138 iax2_queue_frame(f->callno, &fr);
1140 if (iaxs[f->callno]->reg) {
1141 memset(&iaxs[f->callno]->reg->us, 0, sizeof(iaxs[f->callno]->reg->us));
1142 iaxs[f->callno]->reg->regstate = REG_STATE_TIMEOUT;
1143 iaxs[f->callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
1145 iax2_destroy_nolock(f->callno);
1152 /* Update it if it needs it */
1154 /* Attempt transmission */
1157 /* Try again later after 10 times as long */
1159 if (f->retrytime > MAX_RETRY_TIME)
1160 f->retrytime = MAX_RETRY_TIME;
1161 /* Transfer messages max out at one second */
1162 if (f->transfer && (f->retrytime > 1000))
1163 f->retrytime = 1000;
1164 f->retrans = ast_sched_add(sched, f->retrytime, attempt_transmit, f);
1167 /* Make sure it gets freed */
1172 ast_mutex_unlock(&iaxsl[callno]);
1173 /* Do not try again */
1175 /* Don't attempt delivery, just remove it from the queue */
1176 ast_mutex_lock(&iaxq.lock);
1178 f->prev->next = f->next;
1180 iaxq.head = f->next;
1182 f->next->prev = f->prev;
1184 iaxq.tail = f->prev;
1186 ast_mutex_unlock(&iaxq.lock);
1188 /* Free the IAX frame */
1194 static int iax2_set_jitter(int fd, int argc, char *argv[])
1196 if ((argc != 4) && (argc != 5))
1197 return RESULT_SHOWUSAGE;
1199 max_jitter_buffer = atoi(argv[3]);
1200 if (max_jitter_buffer < 0)
1201 max_jitter_buffer = 0;
1204 if ((atoi(argv[3]) >= 0) && (atoi(argv[3]) < IAX_MAX_CALLS)) {
1205 if (iaxs[atoi(argv[3])]) {
1206 iaxs[atoi(argv[3])]->jitterbuffer = atoi(argv[4]);
1207 if (iaxs[atoi(argv[3])]->jitterbuffer < 0)
1208 iaxs[atoi(argv[3])]->jitterbuffer = 0;
1210 ast_cli(fd, "No such call '%d'\n", atoi(argv[3]));
1212 ast_cli(fd, "%d is not a valid call number\n", atoi(argv[3]));
1215 return RESULT_SUCCESS;
1218 static char jitter_usage[] =
1219 "Usage: iax set jitter [callid] <value>\n"
1220 " If used with a callid, it sets the jitter buffer to the given static\n"
1221 "value (until its next calculation). If used without a callid, the value is used\n"
1222 "to establish the maximum excess jitter buffer that is permitted before the jitter\n"
1223 "buffer size is reduced.";
1225 static int iax2_show_stats(int fd, int argc, char *argv[])
1227 struct iax_frame *cur;
1228 int cnt = 0, dead=0, final=0;
1230 return RESULT_SHOWUSAGE;
1231 for (cur = iaxq.head; cur ; cur = cur->next) {
1232 if (cur->retries < 0)
1238 ast_cli(fd, " IAX Statistics\n");
1239 ast_cli(fd, "---------------------\n");
1240 ast_cli(fd, "Outstanding frames: %d (%d ingress, %d outgress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
1241 ast_cli(fd, "Packets in transmit queue: %d dead, %d final, %d total\n", dead, final, cnt);
1242 return RESULT_SUCCESS;
1245 static int iax2_show_cache(int fd, int argc, char *argv[])
1247 struct iax2_dpcache *dp;
1248 char tmp[1024], *pc;
1252 gettimeofday(&tv, NULL);
1253 ast_mutex_lock(&dpcache_lock);
1255 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
1257 s = dp->expirey.tv_sec - tv.tv_sec;
1259 if (dp->flags & CACHE_FLAG_EXISTS)
1260 strcat(tmp, "EXISTS|");
1261 if (dp->flags & CACHE_FLAG_NONEXISTANT)
1262 strcat(tmp, "NONEXISTANT|");
1263 if (dp->flags & CACHE_FLAG_CANEXIST)
1264 strcat(tmp, "CANEXIST|");
1265 if (dp->flags & CACHE_FLAG_PENDING)
1266 strcat(tmp, "PENDING|");
1267 if (dp->flags & CACHE_FLAG_TIMEOUT)
1268 strcat(tmp, "TIMEOUT|");
1269 if (dp->flags & CACHE_FLAG_TRANSMITTED)
1270 strcat(tmp, "TRANSMITTED|");
1271 if (dp->flags & CACHE_FLAG_MATCHMORE)
1272 strcat(tmp, "MATCHMORE|");
1273 if (dp->flags & CACHE_FLAG_UNKNOWN)
1274 strcat(tmp, "UNKNOWN|");
1275 /* Trim trailing pipe */
1277 tmp[strlen(tmp) - 1] = '\0';
1279 strcpy(tmp, "(none)");
1281 pc = strchr(dp->peercontext, '@');
1283 pc = dp->peercontext;
1286 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
1287 if (dp->waiters[x] > -1)
1290 ast_cli(fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
1292 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
1295 ast_mutex_unlock(&dpcache_lock);
1296 return RESULT_SUCCESS;
1299 static char show_stats_usage[] =
1300 "Usage: iax show stats\n"
1301 " Display statistics on IAX channel driver.\n";
1304 static char show_cache_usage[] =
1305 "Usage: iax show cache\n"
1306 " Display currently cached IAX Dialplan results.\n";
1308 static struct ast_cli_entry cli_set_jitter =
1309 { { "iax2", "set", "jitter", NULL }, iax2_set_jitter, "Sets IAX jitter buffer", jitter_usage };
1311 static struct ast_cli_entry cli_show_stats =
1312 { { "iax2", "show", "stats", NULL }, iax2_show_stats, "Display IAX statistics", show_stats_usage };
1314 static struct ast_cli_entry cli_show_cache =
1315 { { "iax2", "show", "cache", NULL }, iax2_show_cache, "Display IAX cached dialplan", show_cache_usage };
1317 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p);
1319 #ifdef BRIDGE_OPTIMIZATION
1320 static unsigned int calc_fakestamp(struct chan_iax2_pvt *from, struct chan_iax2_pvt *to, unsigned int ts);
1322 static int forward_delivery(struct iax_frame *fr)
1324 struct chan_iax2_pvt *p1, *p2;
1325 p1 = iaxs[fr->callno];
1326 p2 = iaxs[p1->bridgecallno];
1331 /* Fix relative timestamp */
1332 fr->ts = calc_fakestamp(p1, p2, fr->ts);
1333 /* Now just send it send on the 2nd one
1334 with adjusted timestamp */
1335 return iax2_send(p2, &fr->af, fr->ts, -1, 0, 0, 0);
1339 static int schedule_delivery(struct iax_frame *fr, int reallydeliver, int updatehistory)
1342 int drops[MEMORY_SIZE];
1343 int min, max=0, maxone=0,y,z, match;
1344 /* ms is a measure of the "lateness" of the packet relative to the first
1345 packet we received, which always has a lateness of 1. Called by
1346 IAX thread, with iaxsl lock held. */
1347 ms = calc_rxstamp(iaxs[fr->callno]) - fr->ts;
1350 /* What likely happened here is that our counter has circled but we haven't
1351 gotten the update from the main packet. We'll just pretend that we did, and
1352 update the timestamp appropriately. */
1357 /* We got this packet out of order. Lets add 65536 to it to bring it into our new
1362 /* Rotate our history queue of "lateness". Don't worry about those initial
1363 zeros because the first entry will always be zero */
1364 if (updatehistory) {
1365 for (x=0;x<MEMORY_SIZE - 1;x++)
1366 iaxs[fr->callno]->history[x] = iaxs[fr->callno]->history[x+1];
1367 /* Add a history entry for this one */
1368 iaxs[fr->callno]->history[x] = ms;
1371 /* Initialize the minimum to reasonable values. It's too much
1372 work to do the same for the maximum, repeatedly */
1373 min=iaxs[fr->callno]->history[0];
1374 for (z=0;z < iax2_dropcount + 1;z++) {
1375 /* Start very optimistic ;-) */
1377 for (x=0;x<MEMORY_SIZE;x++) {
1378 if (max < iaxs[fr->callno]->history[x]) {
1379 /* We have a candidate new maximum value. Make
1380 sure it's not in our drop list */
1382 for (y=0;!match && (y<z);y++)
1383 match |= (drops[y] == x);
1385 /* It's not in our list, use it as the new maximum */
1386 max = iaxs[fr->callno]->history[x];
1392 /* On our first pass, find the minimum too */
1393 if (min > iaxs[fr->callno]->history[x])
1394 min = iaxs[fr->callno]->history[x];
1401 /* Just for reference, keep the "jitter" value, the difference between the
1402 earliest and the latest. */
1403 iaxs[fr->callno]->jitter = max - min;
1405 /* IIR filter for keeping track of historic jitter, but always increase
1406 historic jitter immediately for increase */
1408 if (iaxs[fr->callno]->jitter > iaxs[fr->callno]->historicjitter )
1409 iaxs[fr->callno]->historicjitter = iaxs[fr->callno]->jitter;
1411 iaxs[fr->callno]->historicjitter = GAMMA * (double)iaxs[fr->callno]->jitter + (1-GAMMA) *
1412 iaxs[fr->callno]->historicjitter;
1414 /* If our jitter buffer is too big (by a significant margin), then we slowly
1415 shrink it by about 1 ms each time to avoid letting the change be perceived */
1416 if (max < iaxs[fr->callno]->jitterbuffer - max_jitter_buffer)
1417 iaxs[fr->callno]->jitterbuffer -= 2;
1421 /* Constrain our maximum jitter buffer appropriately */
1422 if (max > min + maxjitterbuffer) {
1424 ast_log(LOG_DEBUG, "Constraining buffer from %d to %d + %d\n", max, min , maxjitterbuffer);
1425 max = min + maxjitterbuffer;
1429 /* If our jitter buffer is smaller than our maximum delay, grow the jitter
1430 buffer immediately to accomodate it (and a little more). */
1431 if (max > iaxs[fr->callno]->jitterbuffer)
1432 iaxs[fr->callno]->jitterbuffer = max
1433 /* + ((float)iaxs[fr->callno]->jitter) * 0.1 */;
1437 ast_log(LOG_DEBUG, "min = %d, max = %d, jb = %d, lateness = %d\n", min, max, iaxs[fr->callno]->jitterbuffer, ms);
1439 /* Subtract the lateness from our jitter buffer to know how long to wait
1440 before sending our packet. */
1441 ms = iaxs[fr->callno]->jitterbuffer - ms;
1443 if (!use_jitterbuffer)
1446 /* If the caller just wanted us to update, return now */
1452 ast_log(LOG_DEBUG, "Calculated ms is %d\n", ms);
1453 /* Don't deliver it more than 4 ms late */
1454 if ((ms > -4) || (fr->af.frametype != AST_FRAME_VOICE)) {
1458 ast_log(LOG_DEBUG, "Dropping voice packet since %d ms is, too old\n", ms);
1459 /* Free our iax frame */
1460 iax2_frame_free(fr);
1464 ast_log(LOG_DEBUG, "Scheduling delivery in %d ms\n", ms);
1465 fr->retrans = ast_sched_add(sched, ms, do_deliver, fr);
1470 static int iax2_transmit(struct iax_frame *fr)
1472 /* Lock the queue and place this packet at the end */
1475 /* By setting this to 0, the network thread will send it for us, and
1476 queue retransmission if necessary */
1478 ast_mutex_lock(&iaxq.lock);
1485 iaxq.tail->next = fr;
1486 fr->prev = iaxq.tail;
1490 ast_mutex_unlock(&iaxq.lock);
1491 /* Wake up the network thread */
1492 pthread_kill(netthreadid, SIGURG);
1498 static int iax2_digit(struct ast_channel *c, char digit)
1500 return send_command_locked(c->pvt->pvt, AST_FRAME_DTMF, digit, 0, NULL, 0, -1);
1503 static int iax2_sendtext(struct ast_channel *c, char *text)
1506 return send_command_locked(c->pvt->pvt, AST_FRAME_TEXT,
1507 0, 0, text, strlen(text) + 1, -1);
1510 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
1512 return send_command_locked(c->pvt->pvt, AST_FRAME_IMAGE, img->subclass, 0, img->data, img->datalen, -1);
1515 static int iax2_sendhtml(struct ast_channel *c, int subclass, char *data, int datalen)
1517 return send_command_locked(c->pvt->pvt, AST_FRAME_HTML, subclass, 0, data, datalen, -1);
1520 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
1522 struct chan_iax2_pvt *pvt = newchan->pvt->pvt;
1523 pvt->owner = newchan;
1527 #ifdef MYSQL_FRIENDS
1529 static void mysql_update_peer(char *peer, struct sockaddr_in *sin)
1531 if (mysql && (strlen(peer) < 128)) {
1535 name = alloca(strlen(peer) * 2 + 1);
1537 mysql_real_escape_string(mysql, name, peer, strlen(peer));
1538 snprintf(query, sizeof(query), "UPDATE iaxfriends SET ipaddr=\"%s\", port=\"%d\", regseconds=\"%ld\" WHERE name=\"%s\"",
1539 inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), nowtime, name);
1540 ast_mutex_lock(&mysqllock);
1541 if (mysql_real_query(mysql, query, strlen(query)))
1542 ast_log(LOG_WARNING, "Unable to update database\n");
1544 ast_mutex_unlock(&mysqllock);
1548 static struct iax2_peer *mysql_peer(char *peer)
1550 struct iax2_peer *p;
1553 p = malloc(sizeof(struct iax2_peer));
1554 memset(p, 0, sizeof(struct iax2_peer));
1555 if (mysql && (strlen(peer) < 128)) {
1560 time_t regseconds, nowtime;
1562 MYSQL_FIELD *fields;
1564 name = alloca(strlen(peer) * 2 + 1);
1565 mysql_real_escape_string(mysql, name, peer, strlen(peer));
1566 snprintf(query, sizeof(query), "SELECT * FROM iaxfriends WHERE name=\"%s\"", name);
1567 ast_mutex_lock(&mysqllock);
1568 mysql_query(mysql, query);
1569 if ((result = mysql_store_result(mysql))) {
1570 if ((rowval = mysql_fetch_row(result))) {
1571 numfields = mysql_num_fields(result);
1572 fields = mysql_fetch_fields(result);
1574 for (x=0;x<numfields;x++) {
1576 if (!strcasecmp(fields[x].name, "secret")) {
1577 strncpy(p->secret, rowval[x], sizeof(p->secret));
1578 } else if (!strcasecmp(fields[x].name, "context")) {
1579 strncpy(p->context, rowval[x], sizeof(p->context) - 1);
1580 } else if (!strcasecmp(fields[x].name, "ipaddr")) {
1581 inet_aton(rowval[x], &p->addr.sin_addr);
1582 } else if (!strcasecmp(fields[x].name, "port")) {
1583 if (sscanf(rowval[x], "%i", &port) != 1)
1585 p->addr.sin_port = htons(port);
1586 } else if (!strcasecmp(fields[x].name, "regseconds")) {
1587 if (sscanf(rowval[x], "%li", ®seconds) != 1)
1593 if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE)
1594 memset(&p->addr, 0, sizeof(p->addr));
1597 ast_mutex_unlock(&mysqllock);
1603 strncpy(p->name, peer, sizeof(p->name) - 1);
1607 p->capability = iax2_capability;
1608 p->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
1612 static struct iax2_user *mysql_user(char *user)
1614 struct iax2_user *p;
1615 struct iax2_context *con;
1618 p = malloc(sizeof(struct iax2_user));
1619 memset(p, 0, sizeof(struct iax2_user));
1620 con = malloc(sizeof(struct iax2_context));
1621 memset(con, 0, sizeof(struct iax2_context));
1622 strcpy(con->context, "default");
1624 if (mysql && (strlen(user) < 128)) {
1629 MYSQL_FIELD *fields;
1631 name = alloca(strlen(user) * 2 + 1);
1632 mysql_real_escape_string(mysql, name, user, strlen(user));
1633 snprintf(query, sizeof(query), "SELECT * FROM iaxfriends WHERE name=\"%s\"", name);
1634 ast_mutex_lock(&mysqllock);
1635 mysql_query(mysql, query);
1636 if ((result = mysql_store_result(mysql))) {
1637 if ((rowval = mysql_fetch_row(result))) {
1638 numfields = mysql_num_fields(result);
1639 fields = mysql_fetch_fields(result);
1641 for (x=0;x<numfields;x++) {
1643 if (!strcasecmp(fields[x].name, "secret")) {
1644 strncpy(p->secret, rowval[x], sizeof(p->secret));
1645 } else if (!strcasecmp(fields[x].name, "context")) {
1646 strncpy(p->contexts->context, rowval[x], sizeof(p->contexts->context) - 1);
1652 ast_mutex_unlock(&mysqllock);
1660 strncpy(p->name, user, sizeof(p->name) - 1);
1662 p->capability = iax2_capability;
1663 p->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
1667 #endif /* MYSQL_FRIENDS */
1669 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)
1672 struct iax2_peer *p;
1680 sin->sin_family = AF_INET;
1681 ast_mutex_lock(&peerl.lock);
1684 if (!strcasecmp(p->name, peer)) {
1689 ast_mutex_unlock(&peerl.lock);
1690 #ifdef MYSQL_FRIENDS
1692 p = mysql_peer(peer);
1696 if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
1697 (!p->maxms || ((p->lastms > 0) && (p->lastms <= p->maxms)))) {
1699 *sendani = p->sendani; /* Whether we transmit ANI */
1701 *maxtime = p->maxms; /* Max time they should take */
1703 strncpy(context, p->context, AST_MAX_EXTENSION - 1);
1707 *capability = p->capability;
1709 strncpy(secret, p->secret, seclen);
1710 if (p->addr.sin_addr.s_addr) {
1711 sin->sin_addr = p->addr.sin_addr;
1712 sin->sin_port = p->addr.sin_port;
1714 sin->sin_addr = p->defaddr.sin_addr;
1715 sin->sin_port = p->defaddr.sin_port;
1718 *notransfer=p->notransfer;
1726 hp = gethostbyname(peer);
1728 memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
1729 sin->sin_port = htons(IAX_DEFAULT_PORTNO);
1732 ast_log(LOG_WARNING, "No such host: %s\n", peer);
1742 static int auto_congest(void *nothing)
1744 int callno = (int)(long)(nothing);
1745 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_CONGESTION };
1746 ast_mutex_lock(&iaxsl[callno]);
1748 iaxs[callno]->initid = -1;
1749 iax2_queue_frame(callno, &f);
1750 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
1752 ast_mutex_unlock(&iaxsl[callno]);
1756 static unsigned int iax2_datetime(void)
1762 localtime_r(&t, &tm);
1763 tmp = (tm.tm_sec >> 1) & 0x1f; /* 5 bits of seconds */
1764 tmp |= (tm.tm_min & 0x3f) << 5; /* 6 bits of minutes */
1765 tmp |= (tm.tm_hour & 0x1f) << 11; /* 5 bits of hours */
1766 tmp |= (tm.tm_mday & 0x1f) << 16; /* 5 bits of day of month */
1767 tmp |= ((tm.tm_mon + 1) & 0xf) << 21; /* 4 bits of month */
1768 tmp |= ((tm.tm_year - 100) & 0x7f) << 25; /* 7 bits of year */
1772 static int iax2_call(struct ast_channel *c, char *dest, int timeout)
1774 struct sockaddr_in sin;
1779 char *secret = NULL;
1782 char *l=NULL, *n=NULL;
1783 struct iax_ie_data ied;
1784 char myrdest [5] = "s";
1785 char context[AST_MAX_EXTENSION] ="";
1786 char *portno = NULL;
1788 struct chan_iax2_pvt *p = c->pvt->pvt;
1790 char storedsecret[80];
1791 if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
1792 ast_log(LOG_WARNING, "Line is already in use (%s)?\n", c->name);
1795 strncpy(host, dest, sizeof(host)-1);
1797 strsep(&stringp, "/");
1798 /* If no destination extension specified, use 's' */
1799 rdest = strsep(&stringp, "/");
1803 /* Check for trailing options */
1804 opts = strsep(&stringp, "/");
1809 strsep(&stringp, "@");
1810 rcontext = strsep(&stringp, "@");
1812 strsep(&stringp, "@");
1813 username = strsep(&stringp, "@");
1815 /* Really the second argument is the host, not the username */
1823 username = strsep(&stringp, ":");
1824 secret = strsep(&stringp, ":");
1827 if (strsep(&stringp, ":")) {
1829 strsep(&stringp, ":");
1830 portno = strsep(&stringp, ":");
1832 if (create_addr(&sin, NULL, NULL, NULL, hname, context, NULL, NULL, storedsecret, sizeof(storedsecret) - 1)) {
1833 ast_log(LOG_WARNING, "No address associated with '%s'\n", hname);
1836 /* Keep track of the context for outgoing calls too */
1837 strncpy(c->context, context, sizeof(c->context) - 1);
1839 sin.sin_port = htons(atoi(portno));
1842 strncpy(cid, c->callerid, sizeof(cid) - 1);
1843 ast_callerid_parse(cid, &n, &l);
1845 ast_shrink_phone_number(l);
1847 /* Now build request */
1848 memset(&ied, 0, sizeof(ied));
1849 /* On new call, first IE MUST be IAX version of caller */
1850 iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
1851 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, rdest);
1852 if (strchr(opts, 'a')) {
1853 /* Request auto answer */
1854 iax_ie_append(&ied, IAX_IE_AUTOANSWER);
1857 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
1859 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n);
1860 if (p->sendani && c->ani) {
1862 strncpy(cid, c->ani, sizeof(cid) - 1);
1863 ast_callerid_parse(cid, &n, &l);
1865 ast_shrink_phone_number(l);
1866 iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, l);
1869 if (c->language && strlen(c->language))
1870 iax_ie_append_str(&ied, IAX_IE_LANGUAGE, c->language);
1871 if (c->dnid && strlen(c->dnid))
1872 iax_ie_append_str(&ied, IAX_IE_DNID, c->dnid);
1874 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, rcontext);
1876 iax_ie_append_str(&ied, IAX_IE_USERNAME, username);
1877 if (!secret && strlen(storedsecret))
1878 secret = storedsecret;
1880 if (secret[0] == '[') {
1881 /* This is an RSA key, not a normal secret */
1882 strncpy(p->outkey, secret + 1, sizeof(p->secret)-1);
1883 if (strlen(p->outkey)) {
1884 p->outkey[strlen(p->outkey) - 1] = '\0';
1887 strncpy(p->secret, secret, sizeof(p->secret)-1);
1889 iax_ie_append_int(&ied, IAX_IE_FORMAT, c->nativeformats);
1890 iax_ie_append_int(&ied, IAX_IE_CAPABILITY, p->capability);
1891 iax_ie_append_short(&ied, IAX_IE_ADSICPE, c->adsicpe);
1892 iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime());
1893 /* Transmit the string in a "NEW" request */
1895 /* XXX We have no equivalent XXX */
1896 if (option_verbose > 2)
1897 ast_verbose(VERBOSE_PREFIX_3 "Calling using options '%s'\n", requeststr);
1900 /* Initialize pingtime and auto-congest time */
1901 p->pingtime = p->maxtime / 2;
1902 p->initid = ast_sched_add(sched, p->maxtime * 2, auto_congest, (void *)(long)p->callno);
1904 send_command_locked(p, AST_FRAME_IAX,
1905 IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
1906 ast_setstate(c, AST_STATE_RINGING);
1910 static int iax2_hangup(struct ast_channel *c)
1912 struct chan_iax2_pvt *pvt = c->pvt->pvt;
1916 callno = pvt->callno;
1917 ast_mutex_lock(&iaxsl[callno]);
1918 ast_log(LOG_DEBUG, "We're hanging up %s now...\n", c->name);
1919 alreadygone = pvt->alreadygone;
1920 /* Send the hangup unless we have had a transmission error or are already gone */
1921 if (!pvt->error && !alreadygone)
1922 send_command_final(pvt, AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, NULL, 0, -1);
1923 /* Explicitly predestroy it */
1924 iax2_predestroy_nolock(callno);
1925 /* If we were already gone to begin with, destroy us now */
1927 ast_log(LOG_DEBUG, "Really destroying %s now...\n", c->name);
1928 iax2_destroy_nolock(callno);
1930 ast_mutex_unlock(&iaxsl[callno]);
1932 if (option_verbose > 2)
1933 ast_verbose(VERBOSE_PREFIX_3 "Hungup '%s'\n", c->name);
1937 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
1939 struct ast_option_header *h;
1941 h = malloc(datalen + sizeof(struct ast_option_header));
1943 h->flag = AST_OPTION_FLAG_REQUEST;
1944 h->option = htons(option);
1945 memcpy(h->data, data, datalen);
1946 res = send_command_locked((struct chan_iax2_pvt *)c->pvt->pvt, AST_FRAME_CONTROL,
1947 AST_CONTROL_OPTION, 0, (char *)h, datalen + sizeof(struct ast_option_header), -1);
1951 ast_log(LOG_WARNING, "Out of memory\n");
1954 static struct ast_frame *iax2_read(struct ast_channel *c)
1956 static struct ast_frame f = { AST_FRAME_NULL, };
1957 ast_log(LOG_NOTICE, "I should never be called!\n");
1961 static int iax2_start_transfer(struct ast_channel *c0, struct ast_channel *c1)
1964 struct iax_ie_data ied0;
1965 struct iax_ie_data ied1;
1966 struct chan_iax2_pvt *p0 = c0->pvt->pvt;
1967 struct chan_iax2_pvt *p1 = c1->pvt->pvt;
1968 unsigned int transferid = rand();
1969 memset(&ied0, 0, sizeof(ied0));
1970 iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &p1->addr);
1971 iax_ie_append_short(&ied0, IAX_IE_CALLNO, p1->peercallno);
1972 iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, transferid);
1974 memset(&ied1, 0, sizeof(ied1));
1975 iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &p0->addr);
1976 iax_ie_append_short(&ied1, IAX_IE_CALLNO, p0->peercallno);
1977 iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, transferid);
1979 res = send_command(p0, AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
1982 res = send_command(p1, AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
1985 p0->transferring = TRANSFER_BEGIN;
1986 p1->transferring = TRANSFER_BEGIN;
1990 static void lock_both(struct chan_iax2_pvt *p0, struct chan_iax2_pvt *p1)
1992 ast_mutex_lock(&iaxsl[p0->callno]);
1993 while (ast_mutex_trylock(&iaxsl[p1->callno])) {
1994 ast_mutex_unlock(&iaxsl[p0->callno]);
1996 ast_mutex_lock(&iaxsl[p0->callno]);
2000 static void unlock_both(struct chan_iax2_pvt *p0, struct chan_iax2_pvt *p1)
2002 ast_mutex_unlock(&iaxsl[p1->callno]);
2003 ast_mutex_unlock(&iaxsl[p0->callno]);
2006 static int iax2_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
2008 struct ast_channel *cs[3];
2009 struct ast_channel *who;
2012 int transferstarted=0;
2013 struct ast_frame *f;
2014 struct chan_iax2_pvt *p0 = c0->pvt->pvt;
2015 struct chan_iax2_pvt *p1 = c1->pvt->pvt;
2016 struct timeval waittimer = {0, 0}, tv;
2019 /* Put them in native bridge mode */
2020 p0->bridgecallno = p1->callno;
2021 p1->bridgecallno = p0->callno;
2022 unlock_both(p0, p1);
2024 /* If not, try to bridge until we can execute a transfer, if we can */
2027 for (/* ever */;;) {
2028 /* Check in case we got masqueraded into */
2029 if ((c0->type != type) || (c1->type != type)) {
2030 if (option_verbose > 2)
2031 ast_verbose(VERBOSE_PREFIX_3 "Can't masquerade, we're different...\n");
2032 /* Remove from native mode */
2033 if (c0->type == type) {
2034 ast_mutex_lock(&iaxsl[p0->callno]);
2035 p0->bridgecallno = 0;
2036 ast_mutex_unlock(&iaxsl[p0->callno]);
2038 if (c1->type == type) {
2039 ast_mutex_lock(&iaxsl[p1->callno]);
2040 p1->bridgecallno = 0;
2041 ast_mutex_unlock(&iaxsl[p1->callno]);
2045 if (c0->nativeformats != c1->nativeformats) {
2046 ast_verbose(VERBOSE_PREFIX_3 "Operating with different codecs, can't native bridge...\n");
2047 /* Remove from native mode */
2049 p0->bridgecallno = 0;
2050 p1->bridgecallno = 0;
2051 unlock_both(p0, p1);
2054 /* check if transfered and if we really want native bridging */
2055 if (!transferstarted && !p0->notransfer && !p1->notransfer) {
2056 /* Try the transfer */
2057 if (iax2_start_transfer(c0, c1))
2058 ast_log(LOG_WARNING, "Unable to start the transfer\n");
2059 transferstarted = 1;
2061 if ((p0->transferring == TRANSFER_RELEASED) && (p1->transferring == TRANSFER_RELEASED)) {
2062 /* Call has been transferred. We're no longer involved */
2063 gettimeofday(&tv, NULL);
2064 if (!waittimer.tv_sec && !waittimer.tv_usec) {
2065 waittimer.tv_sec = tv.tv_sec;
2066 waittimer.tv_usec = tv.tv_usec;
2067 } else if (tv.tv_sec - waittimer.tv_sec > IAX_LINGER_TIMEOUT) {
2068 c0->_softhangup |= AST_SOFTHANGUP_DEV;
2069 c1->_softhangup |= AST_SOFTHANGUP_DEV;
2077 who = ast_waitfor_n(cs, 2, &to);
2079 if (ast_check_hangup(c0) || ast_check_hangup(c1)) {
2092 if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
2098 if ((f->frametype == AST_FRAME_VOICE) ||
2099 (f->frametype == AST_FRAME_TEXT) ||
2100 (f->frametype == AST_FRAME_VIDEO) ||
2101 (f->frametype == AST_FRAME_IMAGE) ||
2102 (f->frametype == AST_FRAME_DTMF)) {
2103 if ((f->frametype == AST_FRAME_DTMF) &&
2104 (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
2106 if ((flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
2109 /* Take out of conference mode */
2111 /* Remove from native mode */
2117 if (flags & AST_BRIDGE_DTMF_CHANNEL_1) {
2121 /* Remove from native mode */
2128 ast_log(LOG_DEBUG, "Read from %s\n", who->name);
2130 ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
2142 /* Swap who gets priority */
2148 p0->bridgecallno = 0;
2149 p1->bridgecallno = 0;
2150 unlock_both(p0, p1);
2154 static int iax2_answer(struct ast_channel *c)
2156 struct chan_iax2_pvt *pvt = c->pvt->pvt;
2158 ast_log(LOG_DEBUG, "Answering\n");
2159 return send_command(pvt, AST_FRAME_CONTROL, AST_CONTROL_ANSWER, 0, NULL, 0, -1);
2162 static int iax2_indicate(struct ast_channel *c, int condition)
2164 struct chan_iax2_pvt *pvt = c->pvt->pvt;
2166 ast_log(LOG_DEBUG, "Indicating condition %d\n", condition);
2167 return send_command(pvt, AST_FRAME_CONTROL, condition, 0, NULL, 0, -1);
2170 static int iax2_transfer(struct ast_channel *c, char *dest)
2172 struct chan_iax2_pvt *pvt = c->pvt->pvt;
2173 struct iax_ie_data ied;
2174 char tmp[256] = "", *context;
2175 strncpy(tmp, dest, sizeof(tmp) - 1);
2176 context = strchr(tmp, '@');
2181 memset(&ied, 0, sizeof(ied));
2182 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, tmp);
2184 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, context);
2186 ast_log(LOG_DEBUG, "Transferring '%s' to '%s'\n", c->name, dest);
2187 return send_command(pvt, AST_FRAME_IAX, IAX_COMMAND_TRANSFER, 0, ied.buf, ied.pos, -1);
2191 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
2193 static int iax2_getpeertrunk(struct sockaddr_in sin)
2195 struct iax2_peer *peer;
2197 ast_mutex_lock(&peerl.lock);
2200 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
2201 (peer->addr.sin_port == sin.sin_port)) {
2207 ast_mutex_unlock(&peerl.lock);
2211 static struct ast_channel *ast_iax2_new(struct chan_iax2_pvt *i, int state, int capability)
2213 struct ast_channel *tmp;
2214 tmp = ast_channel_alloc(1);
2216 if (strlen(i->username))
2217 snprintf(tmp->name, sizeof(tmp->name), "IAX2[%s@%s]/%d", i->username, i->host, i->callno);
2219 snprintf(tmp->name, sizeof(tmp->name), "IAX2[%s]/%d", i->host, i->callno);
2221 /* We can support any format by default, until we get restricted */
2222 tmp->nativeformats = capability;
2223 tmp->readformat = 0;
2224 tmp->writeformat = 0;
2226 tmp->pvt->send_digit = iax2_digit;
2227 tmp->pvt->send_text = iax2_sendtext;
2228 tmp->pvt->send_image = iax2_sendimage;
2229 tmp->pvt->send_html = iax2_sendhtml;
2230 tmp->pvt->call = iax2_call;
2231 tmp->pvt->hangup = iax2_hangup;
2232 tmp->pvt->answer = iax2_answer;
2233 tmp->pvt->read = iax2_read;
2234 tmp->pvt->write = iax2_write;
2235 tmp->pvt->write_video = iax2_write;
2236 tmp->pvt->indicate = iax2_indicate;
2237 tmp->pvt->setoption = iax2_setoption;
2238 tmp->pvt->bridge = iax2_bridge;
2239 tmp->pvt->transfer = iax2_transfer;
2240 if (strlen(i->callerid))
2241 tmp->callerid = strdup(i->callerid);
2243 tmp->ani = strdup(i->ani);
2244 if (strlen(i->language))
2245 strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
2246 if (strlen(i->dnid))
2247 tmp->dnid = strdup(i->dnid);
2248 if (strlen(i->accountcode))
2249 strncpy(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode)-1);
2251 tmp->amaflags = i->amaflags;
2252 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
2253 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
2254 tmp->adsicpe = i->peeradsicpe;
2255 tmp->pvt->fixup = iax2_fixup;
2257 i->capability = capability;
2258 ast_setstate(tmp, state);
2259 ast_mutex_lock(&usecnt_lock);
2261 ast_mutex_unlock(&usecnt_lock);
2262 ast_update_use_count();
2263 if (state != AST_STATE_DOWN) {
2264 if (ast_pbx_start(tmp)) {
2265 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
2274 static unsigned int calc_txpeerstamp(struct iax2_peer *peer)
2277 unsigned int mssincetx;
2279 gettimeofday(&tv, NULL);
2280 mssincetx = (tv.tv_sec - peer->lasttxtime.tv_sec) * 1000 + (tv.tv_usec - peer->lasttxtime.tv_usec) / 1000;
2281 if (mssincetx > 5000) {
2282 /* If it's been at least 5 seconds since the last time we transmitted on this trunk, reset our timers */
2283 peer->txtrunktime.tv_sec = tv.tv_sec;
2284 peer->txtrunktime.tv_usec = tv.tv_usec;
2286 /* Update last transmit time now */
2287 peer->lasttxtime.tv_sec = tv.tv_sec;
2288 peer->lasttxtime.tv_usec = tv.tv_usec;
2290 /* Calculate ms offset */
2291 ms = (tv.tv_sec - peer->txtrunktime.tv_sec) * 1000 + (tv.tv_usec - peer->txtrunktime.tv_usec) / 1000;
2293 /* We never send the same timestamp twice, so fudge a little if we must */
2294 if (ms == peer->lastsent)
2295 ms = peer->lastsent + 1;
2296 peer->lastsent = ms;
2300 static unsigned int fix_peerts(struct iax2_peer *peer, int callno, unsigned int ts)
2302 long ms; /* NOT unsigned */
2303 if (!iaxs[callno]->rxcore.tv_sec && !iaxs[callno]->rxcore.tv_usec) {
2304 /* Initialize rxcore time if appropriate */
2305 gettimeofday(&iaxs[callno]->rxcore, NULL);
2307 /* Calculate difference between trunk and channel */
2308 ms = (peer->rxtrunktime.tv_sec - iaxs[callno]->rxcore.tv_sec) * 1000 +
2309 (peer->rxtrunktime.tv_usec - iaxs[callno]->rxcore.tv_usec) / 1000;
2310 /* Return as the sum of trunk time and the difference between trunk and real time */
2314 static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts)
2318 if (!p->offset.tv_sec && !p->offset.tv_usec)
2319 gettimeofday(&p->offset, NULL);
2320 /* If the timestamp is specified, just send it as is */
2323 gettimeofday(&tv, NULL);
2324 ms = (tv.tv_sec - p->offset.tv_sec) * 1000 + (tv.tv_usec - p->offset.tv_usec) / 1000;
2325 /* We never send the same timestamp twice, so fudge a little if we must */
2326 if (ms <= p->lastsent)
2327 ms = p->lastsent + 1;
2332 #ifdef BRIDGE_OPTIMIZATION
2333 static unsigned int calc_fakestamp(struct chan_iax2_pvt *p1, struct chan_iax2_pvt *p2, unsigned int fakets)
2336 /* Receive from p1, send to p2 */
2338 /* Setup rxcore if necessary on outgoing channel */
2339 if (!p1->rxcore.tv_sec && !p1->rxcore.tv_usec)
2340 gettimeofday(&p1->rxcore, NULL);
2342 /* Setup txcore if necessary on outgoing channel */
2343 if (!p2->offset.tv_sec && !p2->offset.tv_usec)
2344 gettimeofday(&p2->offset, NULL);
2346 /* Now, ts is the timestamp of the original packet in the orignal context.
2347 Adding rxcore to it gives us when we would want the packet to be delivered normally.
2348 Subtracting txcore of the outgoing channel gives us what we'd expect */
2350 ms = (p1->rxcore.tv_sec - p2->offset.tv_sec) * 1000 + (p1->rxcore.tv_usec - p2->offset.tv_usec) / 1000;
2352 if (fakets <= p2->lastsent)
2353 fakets = p2->lastsent + 1;
2354 p2->lastsent = fakets;
2359 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p)
2361 /* Returns where in "receive time" we are */
2364 /* Setup rxcore if necessary */
2365 if (!p->rxcore.tv_sec && !p->rxcore.tv_usec)
2366 gettimeofday(&p->rxcore, NULL);
2368 gettimeofday(&tv, NULL);
2369 ms = (tv.tv_sec - p->rxcore.tv_sec) * 1000 + (tv.tv_usec - p->rxcore.tv_usec) / 1000;
2373 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final)
2375 /* Queue a packet for delivery on a given private structure. Use "ts" for
2376 timestamp, or calculate if ts is 0. Send immediately without retransmission
2377 or delayed, with retransmission */
2378 struct ast_iax2_full_hdr *fh;
2379 struct ast_iax2_mini_hdr *mh;
2380 struct ast_iax2_video_hdr *vh;
2382 struct iax_frame fr2;
2383 unsigned char buffer[4096];
2385 struct iax_frame *fr;
2388 unsigned int lastsent;
2392 ast_log(LOG_WARNING, "No private structure for packet?\n");
2396 lastsent = pvt->lastsent;
2398 /* Calculate actual timestamp */
2399 fts = calc_timestamp(pvt, ts);
2401 if ((pvt->trunk || ((fts & 0xFFFF0000L) == (lastsent & 0xFFFF0000L)))
2402 /* High two bits are the same on timestamp, or sending on a trunk */ &&
2403 (f->frametype == AST_FRAME_VOICE)
2404 /* is a voice frame */ &&
2405 (f->subclass == pvt->svoiceformat)
2406 /* is the same type */ ) {
2407 /* Force immediate rather than delayed transmission */
2409 /* Mark that mini-style frame is appropriate */
2412 if (((fts & 0xFFFF8000L) == (lastsent & 0xFFFF8000L)) &&
2413 (f->frametype == AST_FRAME_VIDEO) &&
2414 ((f->subclass & ~0x1) == pvt->svideoformat)) {
2418 /* Allocate an iax_frame */
2422 fr = iax_frame_new(DIRECTION_OUTGRESS, f->datalen);
2424 ast_log(LOG_WARNING, "Out of memory\n");
2427 /* Copy our prospective frame into our immediate or retransmitted wrapper */
2428 iax_frame_wrap(fr, f);
2432 ast_log(LOG_WARNING, "timestamp is 0?\n");
2434 iax2_frame_free(fr);
2437 fr->callno = pvt->callno;
2438 fr->transfer = transfer;
2441 /* We need a full frame */
2445 fr->oseqno = pvt->oseqno++;
2446 fr->iseqno = pvt->iseqno;
2447 fh = (struct ast_iax2_full_hdr *)(fr->af.data - sizeof(struct ast_iax2_full_hdr));
2448 fh->scallno = htons(fr->callno | IAX_FLAG_FULL);
2449 fh->ts = htonl(fr->ts);
2450 fh->oseqno = fr->oseqno;
2454 fh->iseqno = fr->iseqno;
2455 /* Keep track of the last thing we've acknowledged */
2457 pvt->aseqno = fr->iseqno;
2458 fh->type = fr->af.frametype & 0xFF;
2459 if (fr->af.frametype == AST_FRAME_VIDEO)
2460 fh->csub = compress_subclass(fr->af.subclass & ~0x1) | ((fr->af.subclass & 0x1) << 6);
2462 fh->csub = compress_subclass(fr->af.subclass);
2464 fr->dcallno = pvt->transfercallno;
2466 fr->dcallno = pvt->peercallno;
2467 fh->dcallno = htons(fr->dcallno);
2468 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_full_hdr);
2471 /* Retry after 2x the ping time has passed */
2472 fr->retrytime = pvt->pingtime * 2;
2473 if (fr->retrytime < MIN_RETRY_TIME)
2474 fr->retrytime = MIN_RETRY_TIME;
2475 if (fr->retrytime > MAX_RETRY_TIME)
2476 fr->retrytime = MAX_RETRY_TIME;
2477 /* Acks' don't get retried */
2478 if ((f->frametype == AST_FRAME_IAX) && (f->subclass == IAX_COMMAND_ACK))
2480 if (f->frametype == AST_FRAME_VOICE) {
2481 pvt->svoiceformat = f->subclass;
2483 if (f->frametype == AST_FRAME_VIDEO) {
2484 pvt->svideoformat = f->subclass & ~0x1;
2487 res = send_packet(fr);
2489 res = iax2_transmit(fr);
2492 /* Queue for transmission in a meta frame */
2493 if ((sizeof(pvt->trunkdata) - pvt->trunkdatalen) >= fr->af.datalen) {
2494 memcpy(pvt->trunkdata + pvt->trunkdatalen, fr->af.data, fr->af.datalen);
2495 pvt->trunkdatalen += fr->af.datalen;
2497 pvt->trunkerror = 0;
2499 if (!pvt->trunkerror)
2500 ast_log(LOG_WARNING, "Out of trunk data space on call number %d, dropping\n", pvt->callno);
2501 pvt->trunkerror = 1;
2504 } else if (fr->af.frametype == AST_FRAME_VIDEO) {
2505 /* Video frame have no sequence number */
2508 vh = (struct ast_iax2_video_hdr *)(fr->af.data - sizeof(struct ast_iax2_video_hdr));
2510 vh->callno = htons(0x8000 | fr->callno);
2511 vh->ts = htons((fr->ts & 0x7FFF) | (fr->af.subclass & 0x1 ? 0x8000 : 0));
2512 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_video_hdr);
2515 res = send_packet(fr);
2517 /* Mini-frames have no sequence number */
2520 /* Mini frame will do */
2521 mh = (struct ast_iax2_mini_hdr *)(fr->af.data - sizeof(struct ast_iax2_mini_hdr));
2522 mh->callno = htons(fr->callno);
2523 mh->ts = htons(fr->ts & 0xFFFF);
2524 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_mini_hdr);
2527 res = send_packet(fr);
2535 static int iax2_show_users(int fd, int argc, char *argv[])
2537 #define FORMAT "%-15.15s %-15.15s %-15.15s %-15.15s %-5.5s\n"
2538 #define FORMAT2 "%-15.15s %-15.15s %-15.15d %-15.15s %-5.5s\n"
2539 struct iax2_user *user;
2541 return RESULT_SHOWUSAGE;
2542 ast_mutex_lock(&userl.lock);
2543 ast_cli(fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C");
2544 for(user=userl.users;user;user=user->next) {
2545 ast_cli(fd, FORMAT2, user->name, user->secret, user->authmethods,
2546 user->contexts ? user->contexts->context : context,
2547 user->ha ? "Yes" : "No");
2549 ast_mutex_unlock(&userl.lock);
2550 return RESULT_SUCCESS;
2555 static int iax2_show_peers(int fd, int argc, char *argv[])
2557 #define FORMAT2 "%-15.15s %-15.15s %s %-15.15s %-8s %-10s\n"
2558 #define FORMAT "%-15.15s %-15.15s %s %-15.15s %-5d%s %-10s\n"
2559 struct iax2_peer *peer;
2560 char name[256] = "";
2561 int registeredonly=0;
2562 if ((argc != 3) && (argc != 4))
2563 return RESULT_SHOWUSAGE;
2565 if (!strcasecmp(argv[3], "registered")) {
2568 return RESULT_SHOWUSAGE;
2570 ast_mutex_lock(&peerl.lock);
2571 ast_cli(fd, FORMAT2, "Name/Username", "Host", " ", "Mask", "Port", "Status");
2572 for (peer = peerl.peers;peer;peer = peer->next) {
2575 if (registeredonly && !peer->addr.sin_addr.s_addr)
2577 if (strlen(peer->username))
2578 snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
2580 strncpy(name, peer->name, sizeof(name) - 1);
2582 if (peer->lastms < 0)
2583 strcpy(status, "UNREACHABLE");
2584 else if (peer->lastms > peer->maxms)
2585 snprintf(status, sizeof(status), "LAGGED (%d ms)", peer->lastms);
2586 else if (peer->lastms)
2587 snprintf(status, sizeof(status), "OK (%d ms)", peer->lastms);
2589 strcpy(status, "UNKNOWN");
2591 strcpy(status, "Unmonitored");
2592 strncpy(nm, inet_ntoa(peer->mask), sizeof(nm)-1);
2593 ast_cli(fd, FORMAT, name,
2594 peer->addr.sin_addr.s_addr ? inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
2595 peer->dynamic ? "(D)" : "(S)",
2597 ntohs(peer->addr.sin_port), peer->trunk ? "(T)" : " ", status);
2599 ast_mutex_unlock(&peerl.lock);
2600 return RESULT_SUCCESS;
2605 /* JDG: callback to display iax peers in manager */
2606 static int manager_iax2_show_peers( struct mansession *s, struct message *m )
2608 char *a[] = { "iax2", "show", "users" };
2610 ret = iax2_show_peers( s->fd, 3, a );
2611 ast_cli( s->fd, "\r\n" );
2615 static char *regstate2str(int regstate)
2618 case REG_STATE_UNREGISTERED:
2619 return "Unregistered";
2620 case REG_STATE_REGSENT:
2621 return "Request Sent";
2622 case REG_STATE_AUTHSENT:
2623 return "Auth. Sent";
2624 case REG_STATE_REGISTERED:
2625 return "Registered";
2626 case REG_STATE_REJECTED:
2628 case REG_STATE_TIMEOUT:
2630 case REG_STATE_NOAUTH:
2631 return "No Authentication";
2637 static int iax2_show_registry(int fd, int argc, char *argv[])
2639 #define FORMAT2 "%-20.20s %-10.10s %-20.20s %8.8s %s\n"
2640 #define FORMAT "%-20.20s %-10.10s %-20.20s %8d %s\n"
2641 struct iax2_registry *reg;
2645 return RESULT_SHOWUSAGE;
2646 ast_mutex_lock(&peerl.lock);
2647 ast_cli(fd, FORMAT2, "Host", "Username", "Perceived", "Refresh", "State");
2648 for (reg = registrations;reg;reg = reg->next) {
2649 snprintf(host, sizeof(host), "%s:%d", inet_ntoa(reg->addr.sin_addr), ntohs(reg->addr.sin_port));
2650 if (reg->us.sin_addr.s_addr)
2651 snprintf(perceived, sizeof(perceived), "%s:%d", inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
2653 strcpy(perceived, "<Unregistered>");
2654 ast_cli(fd, FORMAT, host,
2655 reg->username, perceived, reg->refresh, regstate2str(reg->regstate));
2657 ast_mutex_unlock(&peerl.lock);
2658 return RESULT_SUCCESS;
2663 static int iax2_show_channels(int fd, int argc, char *argv[])
2665 #define FORMAT2 "%-15.15s %-10.10s %-11.11s %-11.11s %-7.7s %-6.6s %s\n"
2666 #define FORMAT "%-15.15s %-10.10s %5.5d/%5.5d %5.5d/%5.5d %-5.5dms %-4.4dms %-6.6s\n"
2670 return RESULT_SHOWUSAGE;
2671 ast_cli(fd, FORMAT2, "Peer", "Username", "ID (Lo/Rem)", "Seq (Tx/Rx)", "Lag", "Jitter", "Format");
2672 for (x=0;x<IAX_MAX_CALLS;x++) {
2673 ast_mutex_lock(&iaxsl[x]);
2675 ast_cli(fd, FORMAT, inet_ntoa(iaxs[x]->addr.sin_addr),
2676 strlen(iaxs[x]->username) ? iaxs[x]->username : "(None)",
2677 iaxs[x]->callno, iaxs[x]->peercallno,
2678 iaxs[x]->oseqno, iaxs[x]->iseqno,
2681 ast_getformatname(iaxs[x]->voiceformat) );
2684 ast_mutex_unlock(&iaxsl[x]);
2686 ast_cli(fd, "%d active IAX channel(s)\n", numchans);
2687 return RESULT_SUCCESS;
2692 static int iax2_do_trunk_debug(int fd, int argc, char *argv[])
2695 return RESULT_SHOWUSAGE;
2697 ast_cli(fd, "IAX2 Trunk Debug Requested\n");
2698 return RESULT_SUCCESS;
2701 static int iax2_do_debug(int fd, int argc, char *argv[])
2704 return RESULT_SHOWUSAGE;
2706 ast_cli(fd, "IAX2 Debugging Enabled\n");
2707 return RESULT_SUCCESS;
2710 static int iax2_no_debug(int fd, int argc, char *argv[])
2713 return RESULT_SHOWUSAGE;
2715 ast_cli(fd, "IAX2 Debugging Disabled\n");
2716 return RESULT_SUCCESS;
2721 static char show_users_usage[] =
2722 "Usage: iax2 show users\n"
2723 " Lists all users known to the IAX (Inter-Asterisk eXchange rev 2) subsystem.\n";
2725 static char show_channels_usage[] =
2726 "Usage: iax2 show channels\n"
2727 " Lists all currently active IAX channels.\n";
2729 static char show_peers_usage[] =
2730 "Usage: iax2 show peers\n"
2731 " Lists all known IAX peers.\n";
2733 static char show_reg_usage[] =
2734 "Usage: iax2 show registry\n"
2735 " Lists all registration requests and status.\n";
2737 static char debug_usage[] =
2738 "Usage: iax2 debug\n"
2739 " Enables dumping of IAX packets for debugging purposes\n";
2741 static char no_debug_usage[] =
2742 "Usage: iax2 no debug\n"
2743 " Disables dumping of IAX packets for debugging purposes\n";
2745 static char debug_trunk_usage[] =
2746 "Usage: iax2 trunk debug\n"
2747 " Requests current status of IAX trunking\n";
2749 static struct ast_cli_entry cli_show_users =
2750 { { "iax2", "show", "users", NULL }, iax2_show_users, "Show defined IAX users", show_users_usage };
2751 static struct ast_cli_entry cli_show_channels =
2752 { { "iax2", "show", "channels", NULL }, iax2_show_channels, "Show active IAX channels", show_channels_usage };
2753 static struct ast_cli_entry cli_show_peers =
2754 { { "iax2", "show", "peers", NULL }, iax2_show_peers, "Show defined IAX peers", show_peers_usage };
2755 static struct ast_cli_entry cli_show_registry =
2756 { { "iax2", "show", "registry", NULL }, iax2_show_registry, "Show IAX registration status", show_reg_usage };
2757 static struct ast_cli_entry cli_debug =
2758 { { "iax2", "debug", NULL }, iax2_do_debug, "Enable IAX debugging", debug_usage };
2759 static struct ast_cli_entry cli_trunk_debug =
2760 { { "iax2", "trunk", "debug", NULL }, iax2_do_trunk_debug, "Request IAX trunk debug", debug_trunk_usage };
2761 static struct ast_cli_entry cli_no_debug =
2762 { { "iax2", "no", "debug", NULL }, iax2_no_debug, "Disable IAX debugging", no_debug_usage };
2764 static int iax2_write(struct ast_channel *c, struct ast_frame *f)
2766 struct chan_iax2_pvt *i = c->pvt->pvt;
2769 /* If there's an outstanding error, return failure now */
2771 ast_log(LOG_DEBUG, "Write error: %s\n", strerror(errno));
2774 /* If it's already gone, just return */
2777 /* Don't waste bandwidth sending null frames */
2778 if (f->frametype == AST_FRAME_NULL)
2780 /* If we're quelching voice, don't bother sending it */
2781 if ((f->frametype == AST_FRAME_VOICE) && i->quelch)
2783 if (!(i->state & IAX_STATE_STARTED))
2785 /* Simple, just queue for transmission */
2786 return iax2_send(i, f, 0, -1, 0, 0, 0);
2789 static int __send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno,
2790 int now, int transfer, int final)
2794 f.subclass = command;
2795 f.datalen = datalen;
2799 f.src = __FUNCTION__;
2801 return iax2_send(i, &f, ts, seqno, now, transfer, final);
2804 static int send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2806 return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 0);
2809 static int send_command_locked(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2812 ast_mutex_lock(&iaxsl[i->callno]);
2813 res = send_command(i, type, command, ts, data, datalen, seqno);
2814 ast_mutex_unlock(&iaxsl[i->callno]);
2818 #ifdef BRIDGE_OPTIMIZATION
2819 static int forward_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2821 return __send_command(iaxs[i->bridgecallno], type, command, ts, data, datalen, seqno, 0, 0, 0);
2825 static int send_command_final(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2827 /* It is assumed that the callno has already been locked */
2828 iax2_predestroy_nolock(i->callno);
2829 return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 1);
2832 static int send_command_immediate(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2834 return __send_command(i, type, command, ts, data, datalen, seqno, 1, 0, 0);
2837 static int send_command_transfer(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen)
2839 return __send_command(i, type, command, ts, data, datalen, 0, 0, 1, 0);
2842 static int apply_context(struct iax2_context *con, char *context)
2845 if (!strcmp(con->context, context))
2853 static int check_access(int callno, struct sockaddr_in *sin, struct iax_ies *ies)
2855 /* Start pessimistic */
2858 struct iax2_user *user;
2859 int gotcapability=0;
2862 if (ies->called_number)
2863 strncpy(iaxs[callno]->exten, ies->called_number, sizeof(iaxs[callno]->exten) - 1);
2864 if (ies->calling_number) {
2865 if (ies->calling_name)
2866 snprintf(iaxs[callno]->callerid, sizeof(iaxs[callno]->callerid), "\"%s\" <%s>", ies->calling_name, ies->calling_number);
2868 strncpy(iaxs[callno]->callerid, ies->calling_number, sizeof(iaxs[callno]->callerid) - 1);
2869 } else if (ies->calling_name)
2870 strncpy(iaxs[callno]->callerid, ies->calling_name, sizeof(iaxs[callno]->callerid) - 1);
2871 if (ies->calling_ani)
2872 strncpy(iaxs[callno]->ani, ies->calling_ani, sizeof(iaxs[callno]->ani) - 1);
2874 strncpy(iaxs[callno]->dnid, ies->dnid, sizeof(iaxs[callno]->dnid)-1);
2875 if (ies->called_context)
2876 strncpy(iaxs[callno]->context, ies->called_context, sizeof(iaxs[callno]->context)-1);
2878 strncpy(iaxs[callno]->language, ies->language, sizeof(iaxs[callno]->language)-1);
2880 strncpy(iaxs[callno]->username, ies->username, sizeof(iaxs[callno]->username)-1);
2882 iaxs[callno]->peerformat = ies->format;
2884 iaxs[callno]->peeradsicpe = ies->adsicpe;
2885 if (ies->capability) {
2887 iaxs[callno]->peercapability = ies->capability;
2890 version = ies->version;
2892 iaxs[callno]->peercapability = iaxs[callno]->peerformat;
2893 if (version > IAX_PROTO_VERSION) {
2894 ast_log(LOG_WARNING, "Peer '%s' has too new a protocol version (%d) for me\n",
2895 inet_ntoa(sin->sin_addr), version);
2898 ast_mutex_lock(&userl.lock);
2899 /* Search the userlist for a compatible entry, and fill in the rest */
2902 if ((!strlen(iaxs[callno]->username) || /* No username specified */
2903 !strcmp(iaxs[callno]->username, user->name)) /* Or this username specified */
2904 && ast_apply_ha(user->ha, sin) /* Access is permitted from this IP */
2905 && (!strlen(iaxs[callno]->context) || /* No context specified */
2906 apply_context(user->contexts, iaxs[callno]->context))) { /* Context is permitted */
2911 ast_mutex_unlock(&userl.lock);
2912 #ifdef MYSQL_FRIENDS
2913 if (!user && mysql && strlen(iaxs[callno]->username) && (strlen(iaxs[callno]->username) < 128)) {
2914 user = mysql_user(iaxs[callno]->username);
2915 if (user && strlen(iaxs[callno]->context) && /* No context specified */
2916 !apply_context(user->contexts, iaxs[callno]->context)) { /* Context is permitted */
2918 free(user->contexts);
2925 /* We found our match (use the first) */
2927 /* Store the requested username if not specified */
2928 if (!strlen(iaxs[callno]->username))
2929 strncpy(iaxs[callno]->username, user->name, sizeof(iaxs[callno]->username)-1);
2930 /* Store whether this is a trunked call, too, of course, and move if appropriate */
2931 iaxs[callno]->trunk = user->trunk;
2932 iaxs[callno]->capability = user->capability;
2933 /* And use the default context */
2934 if (!strlen(iaxs[callno]->context)) {
2936 strncpy(iaxs[callno]->context, user->contexts->context, sizeof(iaxs[callno]->context)-1);
2938 strncpy(iaxs[callno]->context, context, sizeof(iaxs[callno]->context)-1);
2940 /* Copy the secret */
2941 strncpy(iaxs[callno]->secret, user->secret, sizeof(iaxs[callno]->secret)-1);
2942 /* And any input keys */
2943 strncpy(iaxs[callno]->inkeys, user->inkeys, sizeof(iaxs[callno]->inkeys));
2944 /* And the permitted authentication methods */
2945 iaxs[callno]->authmethods = user->authmethods;
2946 /* If they have callerid, override the given caller id. Always store the ANI */
2947 if (strlen(iaxs[callno]->callerid)) {
2948 if (user->hascallerid)
2949 strncpy(iaxs[callno]->callerid, user->callerid, sizeof(iaxs[callno]->callerid)-1);
2950 strncpy(iaxs[callno]->ani, user->callerid, sizeof(iaxs[callno]->ani)-1);
2952 if (strlen(user->accountcode))
2953 strncpy(iaxs[callno]->accountcode, user->accountcode, sizeof(iaxs[callno]->accountcode)-1);
2955 iaxs[callno]->amaflags = user->amaflags;
2956 iaxs[callno]->notransfer = user->notransfer;
2959 iaxs[callno]->trunk = iax2_getpeertrunk(*sin);
2963 static int raw_hangup(struct sockaddr_in *sin, unsigned short src, unsigned short dst)
2965 struct ast_iax2_full_hdr fh;
2966 fh.scallno = htons(src | IAX_FLAG_FULL);
2967 fh.dcallno = htons(dst);
2971 fh.type = AST_FRAME_IAX;
2972 fh.csub = compress_subclass(IAX_COMMAND_INVAL);
2976 ast_log(LOG_DEBUG, "Raw Hangup %s:%d, src=%d, dst=%d\n",
2977 inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), src, dst);
2978 return sendto(netsocket, &fh, sizeof(fh), 0, (struct sockaddr *)sin, sizeof(*sin));
2981 static int authenticate_request(struct chan_iax2_pvt *p)
2983 struct iax_ie_data ied;
2984 memset(&ied, 0, sizeof(ied));
2985 iax_ie_append_short(&ied, IAX_IE_AUTHMETHODS, p->authmethods);
2986 if (p->authmethods & (IAX_AUTH_MD5 | IAX_AUTH_RSA)) {
2987 snprintf(p->challenge, sizeof(p->challenge), "%d", rand());
2988 iax_ie_append_str(&ied, IAX_IE_CHALLENGE, p->challenge);
2990 iax_ie_append_str(&ied,IAX_IE_USERNAME, p->username);
2991 return send_command(p, AST_FRAME_IAX, IAX_COMMAND_AUTHREQ, 0, ied.buf, ied.pos, -1);
2994 static int authenticate_verify(struct chan_iax2_pvt *p, struct iax_ies *ies)
2996 char requeststr[256] = "";
2997 char md5secret[256] = "";
2998 char secret[256] = "";
2999 char rsasecret[256] = "";
3003 if (!(p->state & IAX_STATE_AUTHENTICATED))
3006 strncpy(secret, ies->password, sizeof(secret) - 1);
3007 if (ies->md5_result)
3008 strncpy(md5secret, ies->md5_result, sizeof(md5secret)-1);
3009 if (ies->rsa_result)
3010 strncpy(rsasecret, ies->rsa_result, sizeof(rsasecret)-1);
3011 if ((p->authmethods & IAX_AUTH_RSA) && strlen(rsasecret) && strlen(p->inkeys)) {
3012 struct ast_key *key;
3016 strncpy(tmpkey, p->inkeys, sizeof(tmpkey));
3018 keyn = strsep(&stringp, ":");
3020 key = ast_key_get(keyn, AST_KEY_PUBLIC);
3021 if (key && !ast_check_signature(key, p->challenge, rsasecret)) {
3025 ast_log(LOG_WARNING, "requested inkey '%s' for RSA authentication does not exist\n", keyn);
3026 keyn = strsep(&stringp, ":");
3028 } else if (p->authmethods & IAX_AUTH_MD5) {
3029 struct MD5Context md5;
3030 unsigned char digest[16];
3032 MD5Update(&md5, p->challenge, strlen(p->challenge));
3033 MD5Update(&md5, p->secret, strlen(p->secret));
3034 MD5Final(digest, &md5);
3035 /* If they support md5, authenticate with it. */
3037 sprintf(requeststr + (x << 1), "%2.2x", digest[x]);
3038 if (!strcasecmp(requeststr, md5secret))
3040 } else if (p->authmethods & IAX_AUTH_PLAINTEXT) {
3041 if (!strcmp(secret, p->secret))
3047 static int register_verify(int callno, struct sockaddr_in *sin, struct iax_ies *ies)
3049 char requeststr[256] = "";
3050 char peer[256] = "";
3051 char md5secret[256] = "";
3052 char rsasecret[256] = "";
3053 char secret[256] = "";
3054 struct iax2_peer *p;
3055 struct ast_key *key;