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>
51 #include <sys/ioctl.h>
52 #include <linux/zaptel.h>
55 #include <mysql/mysql.h>
58 #include "iax2-parser.h"
61 #define IPTOS_MINCOST 0x02
65 * Uncomment to try experimental IAX bridge optimization,
66 * designed to reduce latency when IAX calls cannot
70 #define BRIDGE_OPTIMIZATION
73 #define DEFAULT_RETRY_TIME 1000
74 #define MEMORY_SIZE 100
75 #define DEFAULT_DROP 3
76 /* Flag to use with trunk calls, keeping these calls high up. It halves our effective use
77 but keeps the division between trunked and non-trunked better. */
78 #define TRUNK_CALL_START 0x4000
82 #define MIN_REUSE_TIME 60 /* Don't reuse a call number within 60 seconds */
84 /* Sample over last 100 units to determine historic jitter */
88 static ast_mutex_t mysqllock = AST_MUTEX_INITIALIZER;
90 static char mydbuser[80];
91 static char mydbpass[80];
92 static char mydbhost[80];
93 static char mydbname[80];
95 static char *desc = "Inter Asterisk eXchange (Ver 2)";
96 static char *tdesc = "Inter Asterisk eXchange Driver (Ver 2)";
97 static char *type = "IAX2";
99 static char context[80] = "default";
101 static int max_retries = 4;
102 static int ping_time = 20;
103 static int lagrq_time = 10;
104 static int maxtrunkcall = TRUNK_CALL_START;
105 static int maxnontrunkcall = 1;
106 static int maxjitterbuffer=3000;
107 static int trunkfreq = 20;
109 static int iaxdefaultdpcache=10 * 60; /* Cache dialplan entries for 10 minutes by default */
111 static int iaxdefaulttimeout = 5; /* Default to wait no more than 5 seconds for a reply to come back */
113 static int netsocket = -1;
117 static int expirey = IAX_DEFAULT_REG_EXPIRE;
119 static int timingfd = -1; /* Timing file descriptor */
122 static ast_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
124 int (*iax2_regfunk)(char *username, int onoff) = NULL;
127 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
129 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
130 ~AST_FORMAT_SLINEAR & \
134 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
138 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
142 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
143 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
144 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
146 static struct io_context *io;
147 static struct sched_context *sched;
149 static int iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
151 static int iax2_dropcount = DEFAULT_DROP;
153 static int use_jitterbuffer = 0;
155 static int iaxdebug = 0;
157 static int iaxtrunkdebug = 0;
159 static char accountcode[20];
160 static int amaflags = 0;
161 static int notransfer = 0;
163 static pthread_t netthreadid;
165 #define IAX_STATE_STARTED (1 << 0)
166 #define IAX_STATE_AUTHENTICATED (1 << 1)
167 #define IAX_STATE_TBD (1 << 2)
169 struct iax2_context {
170 char context[AST_MAX_EXTENSION];
171 struct iax2_context *next;
178 char accountcode[20];
179 char inkeys[80]; /* Key(s) this user can use to authenticate to us */
185 char callerid[AST_MAX_EXTENSION];
187 struct iax2_context *contexts;
188 struct iax2_user *next;
196 char outkey[80]; /* What key we use to talk to this peer */
197 char context[AST_MAX_EXTENSION]; /* Default context (for transfer really) */
198 char mailbox[AST_MAX_EXTENSION]; /* Mailbox */
199 struct sockaddr_in addr;
203 /* Dynamic Registration fields */
204 int dynamic; /* If this is a dynamic peer */
205 struct sockaddr_in defaddr; /* Default address if there is one */
206 int authmethods; /* Authentication methods (IAX_AUTH_*) */
207 char inkeys[80]; /* Key(s) this peer can use to authenticate to us */
210 /* Suggested caller id if registering */
211 char callerid[AST_MAX_EXTENSION];
212 /* Whether or not to send ANI */
214 int expire; /* Schedule entry for expirey */
215 int expirey; /* How soon to expire */
216 int capability; /* Capability */
217 int delme; /* I need to be deleted */
218 int trunk; /* Treat as an IAX trunking */
219 struct timeval txtrunktime; /* Transmit trunktime */
220 struct timeval rxtrunktime; /* Receive trunktime */
221 struct timeval lasttxtime; /* Last transmitted trunktime */
222 unsigned int lastsent; /* Last sent time */
225 int callno; /* Call number of POKE request */
226 int pokeexpire; /* When to expire poke */
227 int lastms; /* How long last response took (in ms), or -1 for no response */
228 int maxms; /* Max ms we will accept for the host to be up, 0 to not monitor */
231 struct iax2_peer *next;
235 #define REG_STATE_UNREGISTERED 0
236 #define REG_STATE_REGSENT 1
237 #define REG_STATE_AUTHSENT 2
238 #define REG_STATE_REGISTERED 3
239 #define REG_STATE_REJECTED 4
240 #define REG_STATE_TIMEOUT 5
241 #define REG_STATE_NOAUTH 6
243 #define TRANSFER_NONE 0
244 #define TRANSFER_BEGIN 1
245 #define TRANSFER_READY 2
246 #define TRANSFER_RELEASED 3
247 #define TRANSFER_PASSTHROUGH 4
249 struct iax2_registry {
250 struct sockaddr_in addr; /* Who we connect to for registration purposes */
252 char secret[80]; /* Password or key name in []'s */
254 int expire; /* Sched ID of expiration */
255 int refresh; /* How often to refresh */
257 int messages; /* Message count */
258 int callno; /* Associated call number if applicable */
259 struct sockaddr_in us; /* Who the server thinks we are */
260 struct iax2_registry *next;
263 static struct iax2_registry *registrations;
265 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
266 #define MIN_RETRY_TIME 100
267 #define MAX_RETRY_TIME 10000
268 #define MAX_JITTER_BUFFER 50
270 #define MAX_TRUNKDATA 640 /* 40ms, uncompressed linear */
272 /* If we have more than this much excess real jitter buffer, srhink it. */
273 static int max_jitter_buffer = MAX_JITTER_BUFFER;
275 struct chan_iax2_pvt {
276 /* Pipes for communication. pipe[1] belongs to the
277 network thread (write), and pipe[0] belongs to the individual
279 /* Whether or not we Quelch audio */
281 /* Last received voice format */
283 /* Last received voice format */
285 /* Last sent voice format */
287 /* Last sent video format */
289 /* What we are capable of sending */
291 /* Last received timestamp */
293 /* Last sent timestamp - never send the same timestamp twice in a single call */
294 unsigned int lastsent;
296 unsigned int pingtime;
297 /* Max time for initial response */
300 struct sockaddr_in addr;
301 /* Our call number */
302 unsigned short callno;
304 unsigned short peercallno;
305 /* Peer selected format */
307 /* Peer capability */
309 /* timeval that we base our transmission on */
310 struct timeval offset;
311 /* timeval that we base our delivery on */
312 struct timeval rxcore;
313 /* Historical delivery time */
314 int history[MEMORY_SIZE];
315 /* Current base jitterbuffer */
317 /* Current jitter measure */
319 /* Historic jitter value */
323 /* Error, as discovered by the manager */
325 /* Owner if we have one */
326 struct ast_channel *owner;
327 /* What's our state? */
329 /* Expirey (optional) */
331 /* Next outgoing sequence number */
332 unsigned char oseqno;
333 /* Next sequence number they have not yet acknowledged */
334 unsigned char rseqno;
335 /* Next incoming sequence number */
336 unsigned char iseqno;
337 /* Last incoming sequence number we have acknowledged */
338 unsigned char aseqno;
341 /* Default Context */
343 /* Caller ID if available */
345 /* Hidden Caller ID (i.e. ANI) if appropriate */
347 /* Whether or not ani should be transmitted in addition to Caller*ID */
349 /* Whether to request autoanswer */
353 /* Requested Extension */
354 char exten[AST_MAX_EXTENSION];
355 /* Expected Username */
357 /* Expected Secret */
359 /* permitted authentication methods */
363 /* Public keys permitted keys for incoming authentication */
365 /* Private key for outgoing authentication */
367 /* Preferred language */
369 /* Hostname/peername for naming purposes */
371 /* Associated registry */
372 struct iax2_registry *reg;
373 /* Associated peer for poking */
374 struct iax2_peer *peerpoke;
376 /* Transferring status */
378 /* Transfer identifier */
380 /* Already disconnected */
382 /* Who we are IAX transfering to */
383 struct sockaddr_in transfer;
384 /* What's the new call number for the transfer */
385 unsigned short transfercallno;
387 /* Status of knowledge of peer ADSI capability */
390 /* Who we are bridged to */
391 unsigned short bridgecallno;
392 unsigned int bridgesfmt;
393 struct ast_trans_pvt *bridgetrans;
395 int pingid; /* Transmit PING request */
396 int lagid; /* Retransmit lag request */
397 int autoid; /* Auto hangup for Dialplan requestor */
398 int initid; /* Initial peer auto-congest ID (based on qualified peers) */
399 char dproot[AST_MAX_EXTENSION];
400 char accountcode[20];
402 /* This is part of a trunk interface */
404 /* Trunk data and length */
405 unsigned char trunkdata[MAX_TRUNKDATA];
406 unsigned int trunkdatalen;
408 struct iax2_dpcache *dpentries;
409 int notransfer; /* do we want native bridging */
412 static struct ast_iax2_queue {
413 struct iax_frame *head;
414 struct iax_frame *tail;
419 static struct ast_user_list {
420 struct iax2_user *users;
424 static struct ast_peer_list {
425 struct iax2_peer *peers;
429 /* Extension exists */
430 #define CACHE_FLAG_EXISTS (1 << 0)
431 /* Extension is non-existant */
432 #define CACHE_FLAG_NONEXISTANT (1 << 1)
433 /* Extension can exist */
434 #define CACHE_FLAG_CANEXIST (1 << 2)
435 /* Waiting to hear back response */
436 #define CACHE_FLAG_PENDING (1 << 3)
438 #define CACHE_FLAG_TIMEOUT (1 << 4)
439 /* Request transmitted */
440 #define CACHE_FLAG_TRANSMITTED (1 << 5)
442 #define CACHE_FLAG_UNKNOWN (1 << 6)
444 #define CACHE_FLAG_MATCHMORE (1 << 7)
446 static struct iax2_dpcache {
447 char peercontext[AST_MAX_EXTENSION];
448 char exten[AST_MAX_EXTENSION];
450 struct timeval expirey;
452 unsigned short callno;
454 struct iax2_dpcache *next;
455 struct iax2_dpcache *peer; /* For linking in peers */
458 static ast_mutex_t dpcache_lock;
460 static void iax_debug_output(const char *data)
465 static void iax_error_output(const char *data)
467 ast_log(LOG_WARNING, data);
470 /* XXX We probably should use a mutex when working with this XXX */
471 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS];
472 static ast_mutex_t iaxsl[IAX_MAX_CALLS];
473 static struct timeval lastused[IAX_MAX_CALLS];
476 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, char *, int, int);
477 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, char *, int, int);
478 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, char *, int, int);
479 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, char *, int);
481 static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts);
483 static int send_ping(void *data)
485 int callno = (long)data;
486 /* Ping only if it's real, not if it's bridged */
488 #ifdef BRIDGE_OPTIMIZATION
489 if (!iaxs[callno]->bridgecallno)
491 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
497 static int send_lagrq(void *data)
499 int callno = (long)data;
500 /* Ping only if it's real not if it's bridged */
502 #ifdef BRIDGE_OPTIMIZATION
503 if (!iaxs[callno]->bridgecallno)
505 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
511 static unsigned char compress_subclass(int subclass)
515 /* If it's 128 or smaller, just return it */
516 if (subclass < IAX_FLAG_SC_LOG)
518 /* Otherwise find its power */
519 for (x = 0; x < IAX_MAX_SHIFT; x++) {
520 if (subclass & (1 << x)) {
522 ast_log(LOG_WARNING, "Can't compress subclass %d\n", subclass);
528 return power | IAX_FLAG_SC_LOG;
531 static int uncompress_subclass(unsigned char csub)
533 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
534 if (csub & IAX_FLAG_SC_LOG) {
535 /* special case for 'compressed' -1 */
539 return 1 << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
545 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len, int lockpeer)
547 struct iax2_peer *peer;
550 ast_mutex_lock(&peerl.lock);
553 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
554 (peer->addr.sin_port == sin.sin_port)) {
555 strncpy(host, peer->name, len-1);
562 ast_mutex_unlock(&peerl.lock);
566 static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, int lockpeer)
568 struct chan_iax2_pvt *tmp;
569 tmp = malloc(sizeof(struct chan_iax2_pvt));
571 memset(tmp, 0, sizeof(struct chan_iax2_pvt));
574 tmp->transfercallno = 0;
575 tmp->bridgecallno = 0;
580 /* strncpy(tmp->context, context, sizeof(tmp->context)-1); */
581 strncpy(tmp->exten, "s", sizeof(tmp->exten)-1);
582 if (!iax2_getpeername(*sin, tmp->host, sizeof(tmp->host), lockpeer))
583 snprintf(tmp->host, sizeof(tmp->host), "%s:%d", inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
588 static int get_samples(struct ast_frame *f)
591 switch(f->subclass) {
592 case AST_FORMAT_SPEEX:
593 samples = 160; /* XXX Not necessarily true XXX */
595 case AST_FORMAT_G723_1:
596 samples = 240 /* XXX Not necessarily true XXX */;
598 case AST_FORMAT_ILBC:
599 samples = 240 * (f->datalen / 50);
602 samples = 160 * (f->datalen / 33);
604 case AST_FORMAT_G729A:
605 samples = 160 * (f->datalen / 20);
607 case AST_FORMAT_SLINEAR:
608 samples = f->datalen / 2;
610 case AST_FORMAT_LPC10:
612 samples += (((char *)(f->data))[7] & 0x1) * 8;
614 case AST_FORMAT_ULAW:
615 samples = f->datalen;
617 case AST_FORMAT_ALAW:
618 samples = f->datalen;
620 case AST_FORMAT_ADPCM:
621 samples = f->datalen *2;
624 ast_log(LOG_WARNING, "Don't know how to calculate samples on %d packets\n", f->subclass);
629 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
631 /* Malloc() a copy of a frame */
632 struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen);
634 memcpy(new, fr, sizeof(struct iax_frame));
635 iax_frame_wrap(new, &fr->af);
638 new->direction = DIRECTION_INGRESS;
644 #define NEW_PREVENT 0
648 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, struct chan_iax2_pvt *cur)
650 if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
651 (cur->addr.sin_port == sin->sin_port)) {
652 /* This is the main host */
653 if ((cur->peercallno == callno) ||
654 ((dcallno == cur->callno) && !cur->peercallno)) {
655 /* That's us. Be sure we keep track of the peer call number */
659 if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
660 (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
661 /* We're transferring */
662 if (dcallno == cur->callno)
668 static void update_max_trunk(void)
670 int max = TRUNK_CALL_START;
672 /* XXX Prolly don't need locks here XXX */
673 for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
679 ast_log(LOG_DEBUG, "New max trunk callno is %d\n", max);
682 static void update_max_nontrunk(void)
686 /* XXX Prolly don't need locks here XXX */
687 for (x=1;x<TRUNK_CALL_START - 1; x++) {
691 maxnontrunkcall = max;
693 ast_log(LOG_DEBUG, "New max nontrunk callno is %d\n", max);
696 static int make_trunk(unsigned short callno, int locked)
701 if (iaxs[callno]->oseqno) {
702 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
705 if (callno & TRUNK_CALL_START) {
706 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
709 gettimeofday(&now, NULL);
710 for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
711 ast_mutex_lock(&iaxsl[x]);
712 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) {
713 iaxs[x] = iaxs[callno];
716 /* Update the two timers that should have been started */
717 if (iaxs[x]->pingid > -1)
718 ast_sched_del(sched, iaxs[x]->pingid);
719 if (iaxs[x]->lagid > -1)
720 ast_sched_del(sched, iaxs[x]->lagid);
721 iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)x);
722 iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)x);
724 ast_mutex_unlock(&iaxsl[callno]);
727 ast_mutex_unlock(&iaxsl[x]);
730 ast_mutex_unlock(&iaxsl[x]);
732 if (x >= IAX_MAX_CALLS - 1) {
733 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
736 ast_log(LOG_DEBUG, "Made call %d into trunk call %d\n", callno, x);
737 /* We move this call from a non-trunked to a trunked call */
739 update_max_nontrunk();
743 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int lockpeer)
748 if (new <= NEW_ALLOW) {
749 /* Look for an existing connection first */
750 for (x=1;(res < 1) && (x<maxnontrunkcall);x++) {
751 ast_mutex_lock(&iaxsl[x]);
753 /* Look for an exact match */
754 if (match(sin, callno, dcallno, iaxs[x])) {
758 ast_mutex_unlock(&iaxsl[x]);
760 for (x=TRUNK_CALL_START;(res < 1) && (x<maxtrunkcall);x++) {
761 ast_mutex_lock(&iaxsl[x]);
763 /* Look for an exact match */
764 if (match(sin, callno, dcallno, iaxs[x])) {
768 ast_mutex_unlock(&iaxsl[x]);
771 if ((res < 1) && (new >= NEW_ALLOW)) {
772 gettimeofday(&now, NULL);
773 for (x=1;x<TRUNK_CALL_START;x++) {
774 /* Find first unused call number that hasn't been used in a while */
775 ast_mutex_lock(&iaxsl[x]);
776 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) break;
777 ast_mutex_unlock(&iaxsl[x]);
779 /* We've still got lock held if we found a spot */
780 if (x >= TRUNK_CALL_START) {
781 ast_log(LOG_WARNING, "No more space\n");
784 iaxs[x] = new_iax(sin, lockpeer);
785 ast_mutex_unlock(&iaxsl[x]);
786 update_max_nontrunk();
789 ast_log(LOG_DEBUG, "Creating new call structure %d\n", x);
790 iaxs[x]->addr.sin_port = sin->sin_port;
791 iaxs[x]->addr.sin_family = sin->sin_family;
792 iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
793 iaxs[x]->peercallno = callno;
795 iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
796 iaxs[x]->expirey = expirey;
797 iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)x);
798 iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)x);
799 iaxs[x]->amaflags = amaflags;
800 iaxs[x]->notransfer = notransfer;
801 strncpy(iaxs[x]->accountcode, accountcode, sizeof(iaxs[x]->accountcode)-1);
803 ast_log(LOG_WARNING, "Out of resources\n");
811 static void iax2_frame_free(struct iax_frame *fr)
813 if (fr->retrans > -1)
814 ast_sched_del(sched, fr->retrans);
818 static int iax2_queue_frame(int callno, struct ast_frame *f)
821 /* Assumes lock for callno is already held... */
824 if (!ast_mutex_trylock(&iaxsl[callno])) {
825 ast_log(LOG_WARNING, "Lock is not held on pass %d of iax2_queue_frame\n", pass);
828 if (iaxs[callno] && iaxs[callno]->owner) {
829 if (ast_mutex_trylock(&iaxs[callno]->owner->lock)) {
830 /* Avoid deadlock by pausing and trying again */
831 ast_mutex_unlock(&iaxsl[callno]);
833 ast_mutex_lock(&iaxsl[callno]);
835 ast_queue_frame(iaxs[callno]->owner, f, 0);
836 ast_mutex_unlock(&iaxs[callno]->owner->lock);
845 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
847 static int __do_deliver(void *data)
849 /* Just deliver the packet by using queueing. This is called by
850 the IAX thread with the iaxsl lock held. */
851 struct iax_frame *fr = data;
854 if (iaxs[fr->callno] && !iaxs[fr->callno]->alreadygone) {
855 if (fr->af.frametype == AST_FRAME_IAX) {
856 /* We have to treat some of these packets specially because
857 they're LAG measurement packets */
858 if (fr->af.subclass == IAX_COMMAND_LAGRQ) {
859 /* If we got a queued request, build a reply and send it */
860 fr->af.subclass = IAX_COMMAND_LAGRP;
861 iax2_send(iaxs[fr->callno], &fr->af, fr->ts, -1, 0, 0, 0);
862 } else if (fr->af.subclass == IAX_COMMAND_LAGRP) {
863 /* This is a reply we've been given, actually measure the difference */
864 ts = calc_timestamp(iaxs[fr->callno], 0);
865 iaxs[fr->callno]->lag = ts - fr->ts;
868 iax2_queue_frame(fr->callno, &fr->af);
871 /* Free our iax frame */
873 /* And don't run again */
877 static int do_deliver(void *data)
879 /* Locking version of __do_deliver */
880 struct iax_frame *fr = data;
881 int callno = fr->callno;
883 ast_mutex_lock(&iaxsl[callno]);
884 res = __do_deliver(data);
885 ast_mutex_unlock(&iaxsl[callno]);
889 static int handle_error(void)
891 /* XXX Ideally we should figure out why an error occured and then abort those
892 rather than continuing to try. Unfortunately, the published interface does
893 not seem to work XXX */
895 struct sockaddr_in *sin;
898 struct sock_extended_err e;
903 m.msg_controllen = sizeof(e);
905 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
907 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
909 if (m.msg_controllen) {
910 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
912 ast_log(LOG_WARNING, "Receive error from %s\n", inet_ntoa(sin->sin_addr));
914 ast_log(LOG_WARNING, "No address detected??\n");
916 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
923 static int send_packet(struct iax_frame *f)
926 /* Called with iaxsl held */
928 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));
929 /* Don't send if there was an error, but return error instead */
931 ast_log(LOG_WARNING, "Call number = %d\n", f->callno);
934 if (!iaxs[f->callno])
936 if (iaxs[f->callno]->error)
940 iax_showframe(f, NULL, 0, &iaxs[f->callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
941 res = sendto(netsocket, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[f->callno]->transfer,
942 sizeof(iaxs[f->callno]->transfer));
945 iax_showframe(f, NULL, 0, &iaxs[f->callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
946 res = sendto(netsocket, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[f->callno]->addr,
947 sizeof(iaxs[f->callno]->addr));
951 ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
959 static int iax2_predestroy(int callno)
961 struct ast_channel *c;
962 struct chan_iax2_pvt *pvt;
963 ast_mutex_lock(&iaxsl[callno]);
966 ast_mutex_unlock(&iaxsl[callno]);
969 if (!pvt->alreadygone) {
970 /* No more pings or lagrq's */
971 if (pvt->pingid > -1)
972 ast_sched_del(sched, pvt->pingid);
974 ast_sched_del(sched, pvt->lagid);
975 if (pvt->autoid > -1)
976 ast_sched_del(sched, pvt->autoid);
977 if (pvt->initid > -1)
978 ast_sched_del(sched, pvt->initid);
983 pvt->alreadygone = 1;
987 c->_softhangup |= AST_SOFTHANGUP_DEV;
989 ast_queue_hangup(c, 0);
991 ast_mutex_lock(&usecnt_lock);
994 ast_log(LOG_WARNING, "Usecnt < 0???\n");
995 ast_mutex_unlock(&usecnt_lock);
996 ast_update_use_count();
998 ast_mutex_unlock(&iaxsl[callno]);
1002 static int iax2_predestroy_nolock(int callno)
1005 ast_mutex_unlock(&iaxsl[callno]);
1006 res = iax2_predestroy(callno);
1007 ast_mutex_lock(&iaxsl[callno]);
1011 static void iax2_destroy(int callno)
1013 struct chan_iax2_pvt *pvt;
1014 struct iax_frame *cur;
1015 struct ast_channel *owner;
1018 ast_mutex_lock(&iaxsl[callno]);
1020 gettimeofday(&lastused[callno], NULL);
1027 if (ast_mutex_trylock(&owner->lock)) {
1028 ast_log(LOG_NOTICE, "Avoiding IAX destroy deadlock\n");
1029 ast_mutex_unlock(&iaxsl[callno]);
1034 iaxs[callno] = NULL;
1037 /* No more pings or lagrq's */
1038 if (pvt->pingid > -1)
1039 ast_sched_del(sched, pvt->pingid);
1040 if (pvt->lagid > -1)
1041 ast_sched_del(sched, pvt->lagid);
1042 if (pvt->autoid > -1)
1043 ast_sched_del(sched, pvt->autoid);
1044 if (pvt->initid > -1)
1045 ast_sched_del(sched, pvt->initid);
1050 if (pvt->bridgetrans)
1051 ast_translator_free_path(pvt->bridgetrans);
1052 pvt->bridgetrans = NULL;
1055 pvt->alreadygone = 1;
1058 /* If there's an owner, prod it to give up */
1059 owner->pvt->pvt = NULL;
1060 owner->_softhangup |= AST_SOFTHANGUP_DEV;
1061 ast_queue_hangup(owner, 0);
1064 for (cur = iaxq.head; cur ; cur = cur->next) {
1065 /* Cancel any pending transmissions */
1066 if (cur->callno == pvt->callno)
1070 pvt->reg->callno = 0;
1075 ast_mutex_unlock(&owner->lock);
1077 ast_mutex_unlock(&iaxsl[callno]);
1078 if (callno & 0x4000)
1081 static void iax2_destroy_nolock(int callno)
1083 /* Actually it's easier to unlock, kill it, and relock */
1084 ast_mutex_unlock(&iaxsl[callno]);
1085 iax2_destroy(callno);
1086 ast_mutex_lock(&iaxsl[callno]);
1089 static int update_packet(struct iax_frame *f)
1091 /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
1092 struct ast_iax2_full_hdr *fh = f->data;
1093 /* Mark this as a retransmission */
1094 fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
1096 f->iseqno = iaxs[f->callno]->iseqno;
1097 fh->iseqno = f->iseqno;
1101 static int attempt_transmit(void *data)
1103 /* Attempt to transmit the frame to the remote peer...
1104 Called without iaxsl held. */
1105 struct iax_frame *f = data;
1107 int callno = f->callno;
1108 /* Make sure this call is still active */
1110 ast_mutex_lock(&iaxsl[callno]);
1111 if ((f->callno) && iaxs[f->callno]) {
1112 if ((f->retries < 0) /* Already ACK'd */ ||
1113 (f->retries >= max_retries) /* Too many attempts */) {
1114 /* Record an error if we've transmitted too many times */
1115 if (f->retries >= max_retries) {
1117 /* Transfer timeout */
1118 send_command(iaxs[f->callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
1119 } else if (f->final) {
1121 iax2_destroy_nolock(f->callno);
1123 if (iaxs[f->callno]->owner)
1124 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);
1125 iaxs[f->callno]->error = ETIMEDOUT;
1126 if (iaxs[f->callno]->owner) {
1127 struct ast_frame fr = { 0, };
1129 fr.frametype = AST_FRAME_CONTROL;
1130 fr.subclass = AST_CONTROL_HANGUP;
1131 iax2_queue_frame(f->callno, &fr);
1133 if (iaxs[f->callno]->reg) {
1134 memset(&iaxs[f->callno]->reg->us, 0, sizeof(iaxs[f->callno]->reg->us));
1135 iaxs[f->callno]->reg->regstate = REG_STATE_TIMEOUT;
1136 iaxs[f->callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
1138 iax2_destroy_nolock(f->callno);
1145 /* Update it if it needs it */
1147 /* Attempt transmission */
1150 /* Try again later after 10 times as long */
1152 if (f->retrytime > MAX_RETRY_TIME)
1153 f->retrytime = MAX_RETRY_TIME;
1154 /* Transfer messages max out at one second */
1155 if (f->transfer && (f->retrytime > 1000))
1156 f->retrytime = 1000;
1157 f->retrans = ast_sched_add(sched, f->retrytime, attempt_transmit, f);
1160 /* Make sure it gets freed */
1165 ast_mutex_unlock(&iaxsl[callno]);
1166 /* Do not try again */
1168 /* Don't attempt delivery, just remove it from the queue */
1169 ast_mutex_lock(&iaxq.lock);
1171 f->prev->next = f->next;
1173 iaxq.head = f->next;
1175 f->next->prev = f->prev;
1177 iaxq.tail = f->prev;
1179 ast_mutex_unlock(&iaxq.lock);
1181 /* Free the IAX frame */
1187 static int iax2_set_jitter(int fd, int argc, char *argv[])
1189 if ((argc != 4) && (argc != 5))
1190 return RESULT_SHOWUSAGE;
1192 max_jitter_buffer = atoi(argv[3]);
1193 if (max_jitter_buffer < 0)
1194 max_jitter_buffer = 0;
1197 if ((atoi(argv[3]) >= 0) && (atoi(argv[3]) < IAX_MAX_CALLS)) {
1198 if (iaxs[atoi(argv[3])]) {
1199 iaxs[atoi(argv[3])]->jitterbuffer = atoi(argv[4]);
1200 if (iaxs[atoi(argv[3])]->jitterbuffer < 0)
1201 iaxs[atoi(argv[3])]->jitterbuffer = 0;
1203 ast_cli(fd, "No such call '%d'\n", atoi(argv[3]));
1205 ast_cli(fd, "%d is not a valid call number\n", atoi(argv[3]));
1208 return RESULT_SUCCESS;
1211 static char jitter_usage[] =
1212 "Usage: iax set jitter [callid] <value>\n"
1213 " If used with a callid, it sets the jitter buffer to the given static\n"
1214 "value (until its next calculation). If used without a callid, the value is used\n"
1215 "to establish the maximum excess jitter buffer that is permitted before the jitter\n"
1216 "buffer size is reduced.";
1218 static int iax2_show_stats(int fd, int argc, char *argv[])
1220 struct iax_frame *cur;
1221 int cnt = 0, dead=0, final=0;
1223 return RESULT_SHOWUSAGE;
1224 for (cur = iaxq.head; cur ; cur = cur->next) {
1225 if (cur->retries < 0)
1231 ast_cli(fd, " IAX Statistics\n");
1232 ast_cli(fd, "---------------------\n");
1233 ast_cli(fd, "Outstanding frames: %d (%d ingress, %d outgress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
1234 ast_cli(fd, "Packets in transmit queue: %d dead, %d final, %d total\n", dead, final, cnt);
1235 return RESULT_SUCCESS;
1238 static int iax2_show_cache(int fd, int argc, char *argv[])
1240 struct iax2_dpcache *dp;
1241 char tmp[1024], *pc;
1245 gettimeofday(&tv, NULL);
1246 ast_mutex_lock(&dpcache_lock);
1248 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
1250 s = dp->expirey.tv_sec - tv.tv_sec;
1252 if (dp->flags & CACHE_FLAG_EXISTS)
1253 strcat(tmp, "EXISTS|");
1254 if (dp->flags & CACHE_FLAG_NONEXISTANT)
1255 strcat(tmp, "NONEXISTANT|");
1256 if (dp->flags & CACHE_FLAG_CANEXIST)
1257 strcat(tmp, "CANEXIST|");
1258 if (dp->flags & CACHE_FLAG_PENDING)
1259 strcat(tmp, "PENDING|");
1260 if (dp->flags & CACHE_FLAG_TIMEOUT)
1261 strcat(tmp, "TIMEOUT|");
1262 if (dp->flags & CACHE_FLAG_TRANSMITTED)
1263 strcat(tmp, "TRANSMITTED|");
1264 if (dp->flags & CACHE_FLAG_MATCHMORE)
1265 strcat(tmp, "MATCHMORE|");
1266 if (dp->flags & CACHE_FLAG_UNKNOWN)
1267 strcat(tmp, "UNKNOWN|");
1268 /* Trim trailing pipe */
1270 tmp[strlen(tmp) - 1] = '\0';
1272 strcpy(tmp, "(none)");
1274 pc = strchr(dp->peercontext, '@');
1276 pc = dp->peercontext;
1279 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
1280 if (dp->waiters[x] > -1)
1283 ast_cli(fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
1285 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
1288 ast_mutex_unlock(&dpcache_lock);
1289 return RESULT_SUCCESS;
1292 static char show_stats_usage[] =
1293 "Usage: iax show stats\n"
1294 " Display statistics on IAX channel driver.\n";
1297 static char show_cache_usage[] =
1298 "Usage: iax show cache\n"
1299 " Display currently cached IAX Dialplan results.\n";
1301 static struct ast_cli_entry cli_set_jitter =
1302 { { "iax2", "set", "jitter", NULL }, iax2_set_jitter, "Sets IAX jitter buffer", jitter_usage };
1304 static struct ast_cli_entry cli_show_stats =
1305 { { "iax2", "show", "stats", NULL }, iax2_show_stats, "Display IAX statistics", show_stats_usage };
1307 static struct ast_cli_entry cli_show_cache =
1308 { { "iax2", "show", "cache", NULL }, iax2_show_cache, "Display IAX cached dialplan", show_cache_usage };
1310 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p);
1312 #ifdef BRIDGE_OPTIMIZATION
1313 static unsigned int calc_fakestamp(struct chan_iax2_pvt *from, struct chan_iax2_pvt *to, unsigned int ts);
1315 static int forward_delivery(struct iax_frame *fr)
1317 struct chan_iax2_pvt *p1, *p2;
1318 p1 = iaxs[fr->callno];
1319 p2 = iaxs[p1->bridgecallno];
1324 /* Fix relative timestamp */
1325 fr->ts = calc_fakestamp(p1, p2, fr->ts);
1326 /* Now just send it send on the 2nd one
1327 with adjusted timestamp */
1328 return iax2_send(p2, &fr->af, fr->ts, -1, 0, 0, 0);
1332 static int schedule_delivery(struct iax_frame *fr, int reallydeliver, int updatehistory)
1335 int drops[MEMORY_SIZE];
1336 int min, max=0, maxone=0,y,z, match;
1337 /* ms is a measure of the "lateness" of the packet relative to the first
1338 packet we received, which always has a lateness of 1. Called by
1339 IAX thread, with iaxsl lock held. */
1340 ms = calc_rxstamp(iaxs[fr->callno]) - fr->ts;
1343 /* What likely happened here is that our counter has circled but we haven't
1344 gotten the update from the main packet. We'll just pretend that we did, and
1345 update the timestamp appropriately. */
1350 /* We got this packet out of order. Lets add 65536 to it to bring it into our new
1355 /* Rotate our history queue of "lateness". Don't worry about those initial
1356 zeros because the first entry will always be zero */
1357 if (updatehistory) {
1358 for (x=0;x<MEMORY_SIZE - 1;x++)
1359 iaxs[fr->callno]->history[x] = iaxs[fr->callno]->history[x+1];
1360 /* Add a history entry for this one */
1361 iaxs[fr->callno]->history[x] = ms;
1364 /* Initialize the minimum to reasonable values. It's too much
1365 work to do the same for the maximum, repeatedly */
1366 min=iaxs[fr->callno]->history[0];
1367 for (z=0;z < iax2_dropcount + 1;z++) {
1368 /* Start very optimistic ;-) */
1370 for (x=0;x<MEMORY_SIZE;x++) {
1371 if (max < iaxs[fr->callno]->history[x]) {
1372 /* We have a candidate new maximum value. Make
1373 sure it's not in our drop list */
1375 for (y=0;!match && (y<z);y++)
1376 match |= (drops[y] == x);
1378 /* It's not in our list, use it as the new maximum */
1379 max = iaxs[fr->callno]->history[x];
1385 /* On our first pass, find the minimum too */
1386 if (min > iaxs[fr->callno]->history[x])
1387 min = iaxs[fr->callno]->history[x];
1394 /* Just for reference, keep the "jitter" value, the difference between the
1395 earliest and the latest. */
1396 iaxs[fr->callno]->jitter = max - min;
1398 /* IIR filter for keeping track of historic jitter, but always increase
1399 historic jitter immediately for increase */
1401 if (iaxs[fr->callno]->jitter > iaxs[fr->callno]->historicjitter )
1402 iaxs[fr->callno]->historicjitter = iaxs[fr->callno]->jitter;
1404 iaxs[fr->callno]->historicjitter = GAMMA * (double)iaxs[fr->callno]->jitter + (1-GAMMA) *
1405 iaxs[fr->callno]->historicjitter;
1407 /* If our jitter buffer is too big (by a significant margin), then we slowly
1408 shrink it by about 1 ms each time to avoid letting the change be perceived */
1409 if (max < iaxs[fr->callno]->jitterbuffer - max_jitter_buffer)
1410 iaxs[fr->callno]->jitterbuffer -= 2;
1414 /* Constrain our maximum jitter buffer appropriately */
1415 if (max > min + maxjitterbuffer) {
1417 ast_log(LOG_DEBUG, "Constraining buffer from %d to %d + %d\n", max, min , maxjitterbuffer);
1418 max = min + maxjitterbuffer;
1422 /* If our jitter buffer is smaller than our maximum delay, grow the jitter
1423 buffer immediately to accomodate it (and a little more). */
1424 if (max > iaxs[fr->callno]->jitterbuffer)
1425 iaxs[fr->callno]->jitterbuffer = max
1426 /* + ((float)iaxs[fr->callno]->jitter) * 0.1 */;
1430 ast_log(LOG_DEBUG, "min = %d, max = %d, jb = %d, lateness = %d\n", min, max, iaxs[fr->callno]->jitterbuffer, ms);
1432 /* Subtract the lateness from our jitter buffer to know how long to wait
1433 before sending our packet. */
1434 ms = iaxs[fr->callno]->jitterbuffer - ms;
1436 if (!use_jitterbuffer)
1439 /* If the caller just wanted us to update, return now */
1445 ast_log(LOG_DEBUG, "Calculated ms is %d\n", ms);
1446 /* Don't deliver it more than 4 ms late */
1447 if ((ms > -4) || (fr->af.frametype != AST_FRAME_VOICE)) {
1451 ast_log(LOG_DEBUG, "Dropping voice packet since %d ms is, too old\n", ms);
1452 /* Free our iax frame */
1453 iax2_frame_free(fr);
1457 ast_log(LOG_DEBUG, "Scheduling delivery in %d ms\n", ms);
1458 fr->retrans = ast_sched_add(sched, ms, do_deliver, fr);
1463 static int iax2_transmit(struct iax_frame *fr)
1465 /* Lock the queue and place this packet at the end */
1468 /* By setting this to 0, the network thread will send it for us, and
1469 queue retransmission if necessary */
1471 ast_mutex_lock(&iaxq.lock);
1478 iaxq.tail->next = fr;
1479 fr->prev = iaxq.tail;
1483 ast_mutex_unlock(&iaxq.lock);
1484 /* Wake up the network thread */
1485 pthread_kill(netthreadid, SIGURG);
1491 static int iax2_digit(struct ast_channel *c, char digit)
1493 return send_command(c->pvt->pvt, AST_FRAME_DTMF, digit, 0, NULL, 0, -1);
1496 static int iax2_sendtext(struct ast_channel *c, char *text)
1499 return send_command(c->pvt->pvt, AST_FRAME_TEXT,
1500 0, 0, text, strlen(text) + 1, -1);
1503 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
1505 return send_command(c->pvt->pvt, AST_FRAME_IMAGE, img->subclass, 0, img->data, img->datalen, -1);
1508 static int iax2_sendhtml(struct ast_channel *c, int subclass, char *data, int datalen)
1510 return send_command(c->pvt->pvt, AST_FRAME_HTML, subclass, 0, data, datalen, -1);
1513 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
1515 struct chan_iax2_pvt *pvt = newchan->pvt->pvt;
1516 pvt->owner = newchan;
1520 #ifdef MYSQL_FRIENDS
1522 static void mysql_update_peer(char *peer, struct sockaddr_in *sin)
1524 if (mysql && (strlen(peer) < 128)) {
1528 name = alloca(strlen(peer) * 2 + 1);
1530 mysql_real_escape_string(mysql, name, peer, strlen(peer));
1531 snprintf(query, sizeof(query), "UPDATE iaxfriends SET ipaddr=\"%s\", port=\"%d\", regseconds=\"%ld\" WHERE name=\"%s\"",
1532 inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), nowtime, name);
1533 ast_mutex_lock(&mysqllock);
1534 if (mysql_real_query(mysql, query, strlen(query)))
1535 ast_log(LOG_WARNING, "Unable to update database\n");
1537 ast_mutex_unlock(&mysqllock);
1541 static struct iax2_peer *mysql_peer(char *peer)
1543 struct iax2_peer *p;
1546 p = malloc(sizeof(struct iax2_peer));
1547 memset(p, 0, sizeof(struct iax2_peer));
1548 if (mysql && (strlen(peer) < 128)) {
1553 time_t regseconds, nowtime;
1555 MYSQL_FIELD *fields;
1557 name = alloca(strlen(peer) * 2 + 1);
1558 mysql_real_escape_string(mysql, name, peer, strlen(peer));
1559 snprintf(query, sizeof(query), "SELECT * FROM iaxfriends WHERE name=\"%s\"", name);
1560 ast_mutex_lock(&mysqllock);
1561 mysql_query(mysql, query);
1562 if ((result = mysql_store_result(mysql))) {
1563 if ((rowval = mysql_fetch_row(result))) {
1564 numfields = mysql_num_fields(result);
1565 fields = mysql_fetch_fields(result);
1567 for (x=0;x<numfields;x++) {
1569 if (!strcasecmp(fields[x].name, "secret")) {
1570 strncpy(p->secret, rowval[x], sizeof(p->secret));
1571 } else if (!strcasecmp(fields[x].name, "context")) {
1572 strncpy(p->context, rowval[x], sizeof(p->context) - 1);
1573 } else if (!strcasecmp(fields[x].name, "ipaddr")) {
1574 inet_aton(rowval[x], &p->addr.sin_addr);
1575 } else if (!strcasecmp(fields[x].name, "port")) {
1576 if (sscanf(rowval[x], "%i", &port) != 1)
1578 p->addr.sin_port = htons(port);
1579 } else if (!strcasecmp(fields[x].name, "regseconds")) {
1580 if (sscanf(rowval[x], "%li", ®seconds) != 1)
1586 if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE)
1587 memset(&p->addr, 0, sizeof(p->addr));
1590 ast_mutex_unlock(&mysqllock);
1596 strncpy(p->name, peer, sizeof(p->name) - 1);
1600 p->capability = iax2_capability;
1601 p->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
1605 static struct iax2_user *mysql_user(char *user)
1607 struct iax2_user *p;
1608 struct iax2_context *con;
1611 p = malloc(sizeof(struct iax2_user));
1612 memset(p, 0, sizeof(struct iax2_user));
1613 con = malloc(sizeof(struct iax2_context));
1614 memset(con, 0, sizeof(struct iax2_context));
1615 strcpy(con->context, "default");
1617 if (mysql && (strlen(user) < 128)) {
1622 MYSQL_FIELD *fields;
1624 name = alloca(strlen(user) * 2 + 1);
1625 mysql_real_escape_string(mysql, name, user, strlen(user));
1626 snprintf(query, sizeof(query), "SELECT * FROM iaxfriends WHERE name=\"%s\"", name);
1627 ast_mutex_lock(&mysqllock);
1628 mysql_query(mysql, query);
1629 if ((result = mysql_store_result(mysql))) {
1630 if ((rowval = mysql_fetch_row(result))) {
1631 numfields = mysql_num_fields(result);
1632 fields = mysql_fetch_fields(result);
1634 for (x=0;x<numfields;x++) {
1636 if (!strcasecmp(fields[x].name, "secret")) {
1637 strncpy(p->secret, rowval[x], sizeof(p->secret));
1638 } else if (!strcasecmp(fields[x].name, "context")) {
1639 strncpy(p->contexts->context, rowval[x], sizeof(p->contexts->context) - 1);
1645 ast_mutex_unlock(&mysqllock);
1653 strncpy(p->name, user, sizeof(p->name) - 1);
1655 p->capability = iax2_capability;
1656 p->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
1660 #endif /* MYSQL_FRIENDS */
1662 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)
1665 struct iax2_peer *p;
1673 sin->sin_family = AF_INET;
1674 ast_mutex_lock(&peerl.lock);
1677 if (!strcasecmp(p->name, peer)) {
1682 ast_mutex_unlock(&peerl.lock);
1683 #ifdef MYSQL_FRIENDS
1685 p = mysql_peer(peer);
1689 if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
1690 (!p->maxms || ((p->lastms > 0) && (p->lastms <= p->maxms)))) {
1692 *sendani = p->sendani; /* Whether we transmit ANI */
1694 *maxtime = p->maxms; /* Max time they should take */
1696 strncpy(context, p->context, AST_MAX_EXTENSION - 1);
1700 *capability = p->capability;
1702 strncpy(secret, p->secret, seclen);
1703 if (p->addr.sin_addr.s_addr) {
1704 sin->sin_addr = p->addr.sin_addr;
1705 sin->sin_port = p->addr.sin_port;
1707 sin->sin_addr = p->defaddr.sin_addr;
1708 sin->sin_port = p->defaddr.sin_port;
1711 *notransfer=p->notransfer;
1719 hp = gethostbyname(peer);
1721 memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
1722 sin->sin_port = htons(IAX_DEFAULT_PORTNO);
1725 ast_log(LOG_WARNING, "No such host: %s\n", peer);
1735 static int auto_congest(void *nothing)
1737 int callno = (int)(long)(nothing);
1738 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_CONGESTION };
1739 ast_mutex_lock(&iaxsl[callno]);
1741 iaxs[callno]->initid = -1;
1742 iax2_queue_frame(callno, &f);
1743 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
1745 ast_mutex_unlock(&iaxsl[callno]);
1749 static unsigned int iax2_datetime(void)
1755 localtime_r(&t, &tm);
1756 tmp = (tm.tm_sec >> 1) & 0x1f; /* 5 bits of seconds */
1757 tmp |= (tm.tm_min & 0x3f) << 5; /* 6 bits of minutes */
1758 tmp |= (tm.tm_hour & 0x1f) << 11; /* 5 bits of hours */
1759 tmp |= (tm.tm_mday & 0x1f) << 16; /* 5 bits of day of month */
1760 tmp |= ((tm.tm_mon + 1) & 0xf) << 21; /* 4 bits of month */
1761 tmp |= ((tm.tm_year - 100) & 0x7f) << 25; /* 7 bits of year */
1765 static int iax2_call(struct ast_channel *c, char *dest, int timeout)
1767 struct sockaddr_in sin;
1772 char *secret = NULL;
1775 char *l=NULL, *n=NULL;
1776 struct iax_ie_data ied;
1777 char myrdest [5] = "s";
1778 char context[AST_MAX_EXTENSION] ="";
1779 char *portno = NULL;
1781 struct chan_iax2_pvt *p = c->pvt->pvt;
1783 char storedsecret[80];
1784 if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
1785 ast_log(LOG_WARNING, "Line is already in use (%s)?\n", c->name);
1788 strncpy(host, dest, sizeof(host)-1);
1790 strsep(&stringp, "/");
1791 /* If no destination extension specified, use 's' */
1792 rdest = strsep(&stringp, "/");
1796 /* Check for trailing options */
1797 opts = strsep(&stringp, "/");
1802 strsep(&stringp, "@");
1803 rcontext = strsep(&stringp, "@");
1805 strsep(&stringp, "@");
1806 username = strsep(&stringp, "@");
1808 /* Really the second argument is the host, not the username */
1816 username = strsep(&stringp, ":");
1817 secret = strsep(&stringp, ":");
1820 if (strsep(&stringp, ":")) {
1822 strsep(&stringp, ":");
1823 portno = strsep(&stringp, ":");
1825 if (create_addr(&sin, NULL, NULL, NULL, hname, context, NULL, NULL, storedsecret, sizeof(storedsecret) - 1)) {
1826 ast_log(LOG_WARNING, "No address associated with '%s'\n", hname);
1829 /* Keep track of the context for outgoing calls too */
1830 strncpy(c->context, context, sizeof(c->context) - 1);
1832 sin.sin_port = htons(atoi(portno));
1835 strncpy(cid, c->callerid, sizeof(cid) - 1);
1836 ast_callerid_parse(cid, &n, &l);
1838 ast_shrink_phone_number(l);
1840 /* Now build request */
1841 memset(&ied, 0, sizeof(ied));
1842 /* On new call, first IE MUST be IAX version of caller */
1843 iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
1844 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, rdest);
1845 if (strchr(opts, 'a')) {
1846 /* Request auto answer */
1847 iax_ie_append(&ied, IAX_IE_AUTOANSWER);
1850 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
1852 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n);
1853 if (p->sendani && c->ani) {
1855 strncpy(cid, c->ani, sizeof(cid) - 1);
1856 ast_callerid_parse(cid, &n, &l);
1858 ast_shrink_phone_number(l);
1859 iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, l);
1862 if (c->language && strlen(c->language))
1863 iax_ie_append_str(&ied, IAX_IE_LANGUAGE, c->language);
1864 if (c->dnid && strlen(c->dnid))
1865 iax_ie_append_str(&ied, IAX_IE_DNID, c->dnid);
1867 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, rcontext);
1869 iax_ie_append_str(&ied, IAX_IE_USERNAME, username);
1870 if (!secret && strlen(storedsecret))
1871 secret = storedsecret;
1873 if (secret[0] == '[') {
1874 /* This is an RSA key, not a normal secret */
1875 strncpy(p->outkey, secret + 1, sizeof(p->secret)-1);
1876 if (strlen(p->outkey)) {
1877 p->outkey[strlen(p->outkey) - 1] = '\0';
1880 strncpy(p->secret, secret, sizeof(p->secret)-1);
1882 iax_ie_append_int(&ied, IAX_IE_FORMAT, c->nativeformats);
1883 iax_ie_append_int(&ied, IAX_IE_CAPABILITY, p->capability);
1884 iax_ie_append_short(&ied, IAX_IE_ADSICPE, c->adsicpe);
1885 iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime());
1886 /* Transmit the string in a "NEW" request */
1888 /* XXX We have no equivalent XXX */
1889 if (option_verbose > 2)
1890 ast_verbose(VERBOSE_PREFIX_3 "Calling using options '%s'\n", requeststr);
1893 /* Initialize pingtime and auto-congest time */
1894 p->pingtime = p->maxtime / 2;
1895 p->initid = ast_sched_add(sched, p->maxtime * 2, auto_congest, (void *)(long)p->callno);
1897 send_command(p, AST_FRAME_IAX,
1898 IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
1899 ast_setstate(c, AST_STATE_RINGING);
1903 static int iax2_hangup(struct ast_channel *c)
1905 struct chan_iax2_pvt *pvt = c->pvt->pvt;
1909 callno = pvt->callno;
1910 ast_mutex_lock(&iaxsl[callno]);
1911 ast_log(LOG_DEBUG, "We're hanging up %s now...\n", c->name);
1912 alreadygone = pvt->alreadygone;
1913 /* Send the hangup unless we have had a transmission error or are already gone */
1914 if (!pvt->error && !alreadygone)
1915 send_command_final(pvt, AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, NULL, 0, -1);
1916 /* Explicitly predestroy it */
1917 iax2_predestroy_nolock(callno);
1918 /* If we were already gone to begin with, destroy us now */
1920 ast_log(LOG_DEBUG, "Really destroying %s now...\n", c->name);
1921 iax2_destroy_nolock(callno);
1923 ast_mutex_unlock(&iaxsl[callno]);
1925 if (option_verbose > 2)
1926 ast_verbose(VERBOSE_PREFIX_3 "Hungup '%s'\n", c->name);
1930 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
1932 struct ast_option_header *h;
1934 h = malloc(datalen + sizeof(struct ast_option_header));
1936 h->flag = AST_OPTION_FLAG_REQUEST;
1937 h->option = htons(option);
1938 memcpy(h->data, data, datalen);
1939 res = send_command((struct chan_iax2_pvt *)c->pvt->pvt, AST_FRAME_CONTROL,
1940 AST_CONTROL_OPTION, 0, (char *)h, datalen + sizeof(struct ast_option_header), -1);
1944 ast_log(LOG_WARNING, "Out of memory\n");
1947 static struct ast_frame *iax2_read(struct ast_channel *c)
1949 static struct ast_frame f = { AST_FRAME_NULL, };
1950 ast_log(LOG_NOTICE, "I should never be called!\n");
1954 static int iax2_start_transfer(struct ast_channel *c0, struct ast_channel *c1)
1957 struct iax_ie_data ied0;
1958 struct iax_ie_data ied1;
1959 struct chan_iax2_pvt *p0 = c0->pvt->pvt;
1960 struct chan_iax2_pvt *p1 = c1->pvt->pvt;
1961 unsigned int transferid = rand();
1962 memset(&ied0, 0, sizeof(ied0));
1963 iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &p1->addr);
1964 iax_ie_append_short(&ied0, IAX_IE_CALLNO, p1->peercallno);
1965 iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, transferid);
1967 memset(&ied1, 0, sizeof(ied1));
1968 iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &p0->addr);
1969 iax_ie_append_short(&ied1, IAX_IE_CALLNO, p0->peercallno);
1970 iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, transferid);
1972 res = send_command(p0, AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
1975 res = send_command(p1, AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
1978 p0->transferring = TRANSFER_BEGIN;
1979 p1->transferring = TRANSFER_BEGIN;
1983 static int iax2_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
1985 struct ast_channel *cs[3];
1986 struct ast_channel *who;
1989 int transferstarted=0;
1990 struct ast_frame *f;
1991 struct chan_iax2_pvt *p0 = c0->pvt->pvt;
1992 struct chan_iax2_pvt *p1 = c1->pvt->pvt;
1993 struct timeval waittimer = {0, 0}, tv;
1995 /* Put them in native bridge mode */
1996 p0->bridgecallno = p1->callno;
1997 p1->bridgecallno = p0->callno;
1999 /* If not, try to bridge until we can execute a transfer, if we can */
2002 for (/* ever */;;) {
2003 /* Check in case we got masqueraded into */
2004 if ((c0->type != type) || (c1->type != type)) {
2005 if (option_verbose > 2)
2006 ast_verbose(VERBOSE_PREFIX_3 "Can't masquerade, we're different...\n");
2007 /* Remove from native mode */
2008 p0->bridgecallno = 0;
2009 p1->bridgecallno = 0;
2012 if (c0->nativeformats != c1->nativeformats) {
2013 ast_verbose(VERBOSE_PREFIX_3 "Operating with different codecs, can't native bridge...\n");
2014 /* Remove from native mode */
2015 p0->bridgecallno = 0;
2016 p1->bridgecallno = 0;
2019 /* check if transfered and if we really want native bridging */
2020 if (!transferstarted && !p0->notransfer && !p1->notransfer) {
2021 /* Try the transfer */
2022 if (iax2_start_transfer(c0, c1))
2023 ast_log(LOG_WARNING, "Unable to start the transfer\n");
2024 transferstarted = 1;
2027 if ((p0->transferring == TRANSFER_RELEASED) && (p1->transferring == TRANSFER_RELEASED)) {
2028 /* Call has been transferred. We're no longer involved */
2029 gettimeofday(&tv, NULL);
2030 if (!waittimer.tv_sec && !waittimer.tv_usec) {
2031 waittimer.tv_sec = tv.tv_sec;
2032 waittimer.tv_usec = tv.tv_usec;
2033 } else if (tv.tv_sec - waittimer.tv_sec > IAX_LINGER_TIMEOUT) {
2034 c0->_softhangup |= AST_SOFTHANGUP_DEV;
2035 c1->_softhangup |= AST_SOFTHANGUP_DEV;
2043 who = ast_waitfor_n(cs, 2, &to);
2054 if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
2060 if ((f->frametype == AST_FRAME_VOICE) ||
2061 (f->frametype == AST_FRAME_TEXT) ||
2062 (f->frametype == AST_FRAME_VIDEO) ||
2063 (f->frametype == AST_FRAME_IMAGE) ||
2064 (f->frametype == AST_FRAME_DTMF)) {
2065 if ((f->frametype == AST_FRAME_DTMF) &&
2066 (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
2068 if ((flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
2071 /* Take out of conference mode */
2073 /* Remove from native mode */
2079 if (flags & AST_BRIDGE_DTMF_CHANNEL_1) {
2083 /* Remove from native mode */
2090 ast_log(LOG_DEBUG, "Read from %s\n", who->name);
2092 ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
2104 /* Swap who gets priority */
2109 p0->bridgecallno = 0;
2110 p1->bridgecallno = 0;
2114 static int iax2_answer(struct ast_channel *c)
2116 struct chan_iax2_pvt *pvt = c->pvt->pvt;
2118 ast_log(LOG_DEBUG, "Answering\n");
2119 return send_command(pvt, AST_FRAME_CONTROL, AST_CONTROL_ANSWER, 0, NULL, 0, -1);
2122 static int iax2_indicate(struct ast_channel *c, int condition)
2124 struct chan_iax2_pvt *pvt = c->pvt->pvt;
2126 ast_log(LOG_DEBUG, "Indicating condition %d\n", condition);
2127 return send_command(pvt, AST_FRAME_CONTROL, condition, 0, NULL, 0, -1);
2130 static int iax2_transfer(struct ast_channel *c, char *dest)
2132 struct chan_iax2_pvt *pvt = c->pvt->pvt;
2133 struct iax_ie_data ied;
2134 char tmp[256] = "", *context;
2135 strncpy(tmp, dest, sizeof(tmp) - 1);
2136 context = strchr(tmp, '@');
2141 memset(&ied, 0, sizeof(ied));
2142 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, tmp);
2144 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, context);
2146 ast_log(LOG_DEBUG, "Transferring '%s' to '%s'\n", c->name, dest);
2147 return send_command(pvt, AST_FRAME_IAX, IAX_COMMAND_TRANSFER, 0, ied.buf, ied.pos, -1);
2151 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
2153 static int iax2_getpeertrunk(struct sockaddr_in sin)
2155 struct iax2_peer *peer;
2157 ast_mutex_lock(&peerl.lock);
2160 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
2161 (peer->addr.sin_port == sin.sin_port)) {
2167 ast_mutex_unlock(&peerl.lock);
2171 static struct ast_channel *ast_iax2_new(struct chan_iax2_pvt *i, int state, int capability)
2173 struct ast_channel *tmp;
2174 tmp = ast_channel_alloc(1);
2176 if (strlen(i->username))
2177 snprintf(tmp->name, sizeof(tmp->name), "IAX2[%s@%s]/%d", i->username, i->host, i->callno);
2179 snprintf(tmp->name, sizeof(tmp->name), "IAX2[%s]/%d", i->host, i->callno);
2181 /* We can support any format by default, until we get restricted */
2182 tmp->nativeformats = capability;
2183 tmp->readformat = 0;
2184 tmp->writeformat = 0;
2186 tmp->pvt->send_digit = iax2_digit;
2187 tmp->pvt->send_text = iax2_sendtext;
2188 tmp->pvt->send_image = iax2_sendimage;
2189 tmp->pvt->send_html = iax2_sendhtml;
2190 tmp->pvt->call = iax2_call;
2191 tmp->pvt->hangup = iax2_hangup;
2192 tmp->pvt->answer = iax2_answer;
2193 tmp->pvt->read = iax2_read;
2194 tmp->pvt->write = iax2_write;
2195 tmp->pvt->write_video = iax2_write;
2196 tmp->pvt->indicate = iax2_indicate;
2197 tmp->pvt->setoption = iax2_setoption;
2198 tmp->pvt->bridge = iax2_bridge;
2199 tmp->pvt->transfer = iax2_transfer;
2200 if (strlen(i->callerid))
2201 tmp->callerid = strdup(i->callerid);
2203 tmp->ani = strdup(i->ani);
2204 if (strlen(i->language))
2205 strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
2206 if (strlen(i->dnid))
2207 tmp->dnid = strdup(i->dnid);
2208 if (strlen(i->accountcode))
2209 strncpy(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode)-1);
2211 tmp->amaflags = i->amaflags;
2212 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
2213 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
2214 tmp->adsicpe = i->peeradsicpe;
2215 tmp->pvt->fixup = iax2_fixup;
2217 i->capability = capability;
2218 ast_setstate(tmp, state);
2219 ast_mutex_lock(&usecnt_lock);
2221 ast_mutex_unlock(&usecnt_lock);
2222 ast_update_use_count();
2223 if (state != AST_STATE_DOWN) {
2224 if (ast_pbx_start(tmp)) {
2225 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
2234 static unsigned int calc_txpeerstamp(struct iax2_peer *peer)
2237 unsigned int mssincetx;
2239 gettimeofday(&tv, NULL);
2240 mssincetx = (tv.tv_sec - peer->lasttxtime.tv_sec) * 1000 + (tv.tv_usec - peer->lasttxtime.tv_usec) / 1000;
2241 if (mssincetx > 5000) {
2242 /* If it's been at least 5 seconds since the last time we transmitted on this trunk, reset our timers */
2243 peer->txtrunktime.tv_sec = tv.tv_sec;
2244 peer->txtrunktime.tv_usec = tv.tv_usec;
2246 /* Update last transmit time now */
2247 peer->lasttxtime.tv_sec = tv.tv_sec;
2248 peer->lasttxtime.tv_usec = tv.tv_usec;
2250 /* Calculate ms offset */
2251 ms = (tv.tv_sec - peer->txtrunktime.tv_sec) * 1000 + (tv.tv_usec - peer->txtrunktime.tv_usec) / 1000;
2253 /* We never send the same timestamp twice, so fudge a little if we must */
2254 if (ms == peer->lastsent)
2255 ms = peer->lastsent + 1;
2256 peer->lastsent = ms;
2260 static unsigned int fix_peerts(struct iax2_peer *peer, int callno, unsigned int ts)
2262 long ms; /* NOT unsigned */
2263 if (!iaxs[callno]->rxcore.tv_sec && !iaxs[callno]->rxcore.tv_usec) {
2264 /* Initialize rxcore time if appropriate */
2265 gettimeofday(&iaxs[callno]->rxcore, NULL);
2267 /* Calculate difference between trunk and channel */
2268 ms = (peer->rxtrunktime.tv_sec - iaxs[callno]->rxcore.tv_sec) * 1000 +
2269 (peer->rxtrunktime.tv_usec - iaxs[callno]->rxcore.tv_usec) / 1000;
2270 /* Return as the sum of trunk time and the difference between trunk and real time */
2274 static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts)
2278 if (!p->offset.tv_sec && !p->offset.tv_usec)
2279 gettimeofday(&p->offset, NULL);
2280 /* If the timestamp is specified, just send it as is */
2283 gettimeofday(&tv, NULL);
2284 ms = (tv.tv_sec - p->offset.tv_sec) * 1000 + (tv.tv_usec - p->offset.tv_usec) / 1000;
2285 /* We never send the same timestamp twice, so fudge a little if we must */
2286 if (ms <= p->lastsent)
2287 ms = p->lastsent + 1;
2292 #ifdef BRIDGE_OPTIMIZATION
2293 static unsigned int calc_fakestamp(struct chan_iax2_pvt *p1, struct chan_iax2_pvt *p2, unsigned int fakets)
2296 /* Receive from p1, send to p2 */
2298 /* Setup rxcore if necessary on outgoing channel */
2299 if (!p1->rxcore.tv_sec && !p1->rxcore.tv_usec)
2300 gettimeofday(&p1->rxcore, NULL);
2302 /* Setup txcore if necessary on outgoing channel */
2303 if (!p2->offset.tv_sec && !p2->offset.tv_usec)
2304 gettimeofday(&p2->offset, NULL);
2306 /* Now, ts is the timestamp of the original packet in the orignal context.
2307 Adding rxcore to it gives us when we would want the packet to be delivered normally.
2308 Subtracting txcore of the outgoing channel gives us what we'd expect */
2310 ms = (p1->rxcore.tv_sec - p2->offset.tv_sec) * 1000 + (p1->rxcore.tv_usec - p2->offset.tv_usec) / 1000;
2312 if (fakets <= p2->lastsent)
2313 fakets = p2->lastsent + 1;
2314 p2->lastsent = fakets;
2319 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p)
2321 /* Returns where in "receive time" we are */
2324 /* Setup rxcore if necessary */
2325 if (!p->rxcore.tv_sec && !p->rxcore.tv_usec)
2326 gettimeofday(&p->rxcore, NULL);
2328 gettimeofday(&tv, NULL);
2329 ms = (tv.tv_sec - p->rxcore.tv_sec) * 1000 + (tv.tv_usec - p->rxcore.tv_usec) / 1000;
2333 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final)
2335 /* Queue a packet for delivery on a given private structure. Use "ts" for
2336 timestamp, or calculate if ts is 0. Send immediately without retransmission
2337 or delayed, with retransmission */
2338 struct ast_iax2_full_hdr *fh;
2339 struct ast_iax2_mini_hdr *mh;
2340 struct ast_iax2_video_hdr *vh;
2342 struct iax_frame fr2;
2343 unsigned char buffer[4096];
2345 struct iax_frame *fr;
2348 unsigned int lastsent;
2352 ast_log(LOG_WARNING, "No private structure for packet?\n");
2356 lastsent = pvt->lastsent;
2358 /* Calculate actual timestamp */
2359 fts = calc_timestamp(pvt, ts);
2361 if ((pvt->trunk || ((fts & 0xFFFF0000L) == (lastsent & 0xFFFF0000L)))
2362 /* High two bits are the same on timestamp, or sending on a trunk */ &&
2363 (f->frametype == AST_FRAME_VOICE)
2364 /* is a voice frame */ &&
2365 (f->subclass == pvt->svoiceformat)
2366 /* is the same type */ ) {
2367 /* Force immediate rather than delayed transmission */
2369 /* Mark that mini-style frame is appropriate */
2372 if (((fts & 0xFFFF8000L) == (lastsent & 0xFFFF8000L)) &&
2373 (f->frametype == AST_FRAME_VIDEO) &&
2374 ((f->subclass & ~0x1) == pvt->svideoformat)) {
2378 /* Allocate an iax_frame */
2382 fr = iax_frame_new(DIRECTION_OUTGRESS, f->datalen);
2384 ast_log(LOG_WARNING, "Out of memory\n");
2387 /* Copy our prospective frame into our immediate or retransmitted wrapper */
2388 iax_frame_wrap(fr, f);
2392 ast_log(LOG_WARNING, "timestamp is 0?\n");
2394 iax2_frame_free(fr);
2397 fr->callno = pvt->callno;
2398 fr->transfer = transfer;
2401 /* We need a full frame */
2405 fr->oseqno = pvt->oseqno++;
2406 fr->iseqno = pvt->iseqno;
2407 fh = (struct ast_iax2_full_hdr *)(fr->af.data - sizeof(struct ast_iax2_full_hdr));
2408 fh->scallno = htons(fr->callno | IAX_FLAG_FULL);
2409 fh->ts = htonl(fr->ts);
2410 fh->oseqno = fr->oseqno;
2414 fh->iseqno = fr->iseqno;
2415 /* Keep track of the last thing we've acknowledged */
2417 pvt->aseqno = fr->iseqno;
2418 fh->type = fr->af.frametype & 0xFF;
2419 if (fr->af.frametype == AST_FRAME_VIDEO)
2420 fh->csub = compress_subclass(fr->af.subclass & ~0x1) | ((fr->af.subclass & 0x1) << 6);
2422 fh->csub = compress_subclass(fr->af.subclass);
2424 fr->dcallno = pvt->transfercallno;
2426 fr->dcallno = pvt->peercallno;
2427 fh->dcallno = htons(fr->dcallno);
2428 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_full_hdr);
2431 /* Retry after 2x the ping time has passed */
2432 fr->retrytime = pvt->pingtime * 2;
2433 if (fr->retrytime < MIN_RETRY_TIME)
2434 fr->retrytime = MIN_RETRY_TIME;
2435 if (fr->retrytime > MAX_RETRY_TIME)
2436 fr->retrytime = MAX_RETRY_TIME;
2437 /* Acks' don't get retried */
2438 if ((f->frametype == AST_FRAME_IAX) && (f->subclass == IAX_COMMAND_ACK))
2440 if (f->frametype == AST_FRAME_VOICE) {
2441 pvt->svoiceformat = f->subclass;
2443 if (f->frametype == AST_FRAME_VIDEO) {
2444 pvt->svideoformat = f->subclass & ~0x1;
2447 res = send_packet(fr);
2449 res = iax2_transmit(fr);
2452 /* Queue for transmission in a meta frame */
2453 if ((sizeof(pvt->trunkdata) - pvt->trunkdatalen) >= fr->af.datalen) {
2454 memcpy(pvt->trunkdata + pvt->trunkdatalen, fr->af.data, fr->af.datalen);
2455 pvt->trunkdatalen += fr->af.datalen;
2457 pvt->trunkerror = 0;
2459 if (!pvt->trunkerror)
2460 ast_log(LOG_WARNING, "Out of trunk data space on call number %d, dropping\n", pvt->callno);
2461 pvt->trunkerror = 1;
2464 } else if (fr->af.frametype == AST_FRAME_VIDEO) {
2465 /* Video frame have no sequence number */
2468 vh = (struct ast_iax2_video_hdr *)(fr->af.data - sizeof(struct ast_iax2_video_hdr));
2470 vh->callno = htons(0x8000 | fr->callno);
2471 vh->ts = htons((fr->ts & 0x7FFF) | (fr->af.subclass & 0x1 ? 0x8000 : 0));
2472 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_video_hdr);
2475 res = send_packet(fr);
2477 /* Mini-frames have no sequence number */
2480 /* Mini frame will do */
2481 mh = (struct ast_iax2_mini_hdr *)(fr->af.data - sizeof(struct ast_iax2_mini_hdr));
2482 mh->callno = htons(fr->callno);
2483 mh->ts = htons(fr->ts & 0xFFFF);
2484 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_mini_hdr);
2487 res = send_packet(fr);
2495 static int iax2_show_users(int fd, int argc, char *argv[])
2497 #define FORMAT "%-15.15s %-15.15s %-15.15s %-15.15s %-5.5s\n"
2498 #define FORMAT2 "%-15.15s %-15.15s %-15.15d %-15.15s %-5.5s\n"
2499 struct iax2_user *user;
2501 return RESULT_SHOWUSAGE;
2502 ast_mutex_lock(&userl.lock);
2503 ast_cli(fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C");
2504 for(user=userl.users;user;user=user->next) {
2505 ast_cli(fd, FORMAT2, user->name, user->secret, user->authmethods,
2506 user->contexts ? user->contexts->context : context,
2507 user->ha ? "Yes" : "No");
2509 ast_mutex_unlock(&userl.lock);
2510 return RESULT_SUCCESS;
2515 static int iax2_show_peers(int fd, int argc, char *argv[])
2517 #define FORMAT2 "%-15.15s %-15.15s %s %-15.15s %-8s %-10s\n"
2518 #define FORMAT "%-15.15s %-15.15s %s %-15.15s %-5d%s %-10s\n"
2519 struct iax2_peer *peer;
2520 char name[256] = "";
2521 int registeredonly=0;
2522 if ((argc != 3) && (argc != 4))
2523 return RESULT_SHOWUSAGE;
2525 if (!strcasecmp(argv[3], "registered")) {
2528 return RESULT_SHOWUSAGE;
2530 ast_mutex_lock(&peerl.lock);
2531 ast_cli(fd, FORMAT2, "Name/Username", "Host", " ", "Mask", "Port", "Status");
2532 for (peer = peerl.peers;peer;peer = peer->next) {
2535 if (registeredonly && !peer->addr.sin_addr.s_addr)
2537 if (strlen(peer->username))
2538 snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
2540 strncpy(name, peer->name, sizeof(name) - 1);
2542 if (peer->lastms < 0)
2543 strcpy(status, "UNREACHABLE");
2544 else if (peer->lastms > peer->maxms)
2545 snprintf(status, sizeof(status), "LAGGED (%d ms)", peer->lastms);
2546 else if (peer->lastms)
2547 snprintf(status, sizeof(status), "OK (%d ms)", peer->lastms);
2549 strcpy(status, "UNKNOWN");
2551 strcpy(status, "Unmonitored");
2552 strncpy(nm, inet_ntoa(peer->mask), sizeof(nm)-1);
2553 ast_cli(fd, FORMAT, name,
2554 peer->addr.sin_addr.s_addr ? inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
2555 peer->dynamic ? "(D)" : "(S)",
2557 ntohs(peer->addr.sin_port), peer->trunk ? "(T)" : " ", status);
2559 ast_mutex_unlock(&peerl.lock);
2560 return RESULT_SUCCESS;
2565 /* JDG: callback to display iax peers in manager */
2566 static int manager_iax2_show_peers( struct mansession *s, struct message *m )
2568 char *a[] = { "iax2", "show", "users" };
2570 ret = iax2_show_peers( s->fd, 3, a );
2571 ast_cli( s->fd, "\r\n" );
2575 static char *regstate2str(int regstate)
2578 case REG_STATE_UNREGISTERED:
2579 return "Unregistered";
2580 case REG_STATE_REGSENT:
2581 return "Request Sent";
2582 case REG_STATE_AUTHSENT:
2583 return "Auth. Sent";
2584 case REG_STATE_REGISTERED:
2585 return "Registered";
2586 case REG_STATE_REJECTED:
2588 case REG_STATE_TIMEOUT:
2590 case REG_STATE_NOAUTH:
2591 return "No Authentication";
2597 static int iax2_show_registry(int fd, int argc, char *argv[])
2599 #define FORMAT2 "%-20.20s %-10.10s %-20.20s %8.8s %s\n"
2600 #define FORMAT "%-20.20s %-10.10s %-20.20s %8d %s\n"
2601 struct iax2_registry *reg;
2605 return RESULT_SHOWUSAGE;
2606 ast_mutex_lock(&peerl.lock);
2607 ast_cli(fd, FORMAT2, "Host", "Username", "Perceived", "Refresh", "State");
2608 for (reg = registrations;reg;reg = reg->next) {
2609 snprintf(host, sizeof(host), "%s:%d", inet_ntoa(reg->addr.sin_addr), ntohs(reg->addr.sin_port));
2610 if (reg->us.sin_addr.s_addr)
2611 snprintf(perceived, sizeof(perceived), "%s:%d", inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
2613 strcpy(perceived, "<Unregistered>");
2614 ast_cli(fd, FORMAT, host,
2615 reg->username, perceived, reg->refresh, regstate2str(reg->regstate));
2617 ast_mutex_unlock(&peerl.lock);
2618 return RESULT_SUCCESS;
2623 static int iax2_show_channels(int fd, int argc, char *argv[])
2625 #define FORMAT2 "%-15.15s %-10.10s %-11.11s %-11.11s %-7.7s %-6.6s %s\n"
2626 #define FORMAT "%-15.15s %-10.10s %5.5d/%5.5d %5.5d/%5.5d %-5.5dms %-4.4dms %-6.6s\n"
2630 return RESULT_SHOWUSAGE;
2631 ast_cli(fd, FORMAT2, "Peer", "Username", "ID (Lo/Rem)", "Seq (Tx/Rx)", "Lag", "Jitter", "Format");
2632 for (x=0;x<IAX_MAX_CALLS;x++) {
2633 ast_mutex_lock(&iaxsl[x]);
2635 ast_cli(fd, FORMAT, inet_ntoa(iaxs[x]->addr.sin_addr),
2636 strlen(iaxs[x]->username) ? iaxs[x]->username : "(None)",
2637 iaxs[x]->callno, iaxs[x]->peercallno,
2638 iaxs[x]->oseqno, iaxs[x]->iseqno,
2641 ast_getformatname(iaxs[x]->voiceformat) );
2644 ast_mutex_unlock(&iaxsl[x]);
2646 ast_cli(fd, "%d active IAX channel(s)\n", numchans);
2647 return RESULT_SUCCESS;
2652 static int iax2_do_trunk_debug(int fd, int argc, char *argv[])
2655 return RESULT_SHOWUSAGE;
2657 ast_cli(fd, "IAX2 Trunk Debug Requested\n");
2658 return RESULT_SUCCESS;
2661 static int iax2_do_debug(int fd, int argc, char *argv[])
2664 return RESULT_SHOWUSAGE;
2666 ast_cli(fd, "IAX2 Debugging Enabled\n");
2667 return RESULT_SUCCESS;
2670 static int iax2_no_debug(int fd, int argc, char *argv[])
2673 return RESULT_SHOWUSAGE;
2675 ast_cli(fd, "IAX2 Debugging Disabled\n");
2676 return RESULT_SUCCESS;
2681 static char show_users_usage[] =
2682 "Usage: iax2 show users\n"
2683 " Lists all users known to the IAX (Inter-Asterisk eXchange rev 2) subsystem.\n";
2685 static char show_channels_usage[] =
2686 "Usage: iax2 show channels\n"
2687 " Lists all currently active IAX channels.\n";
2689 static char show_peers_usage[] =
2690 "Usage: iax2 show peers\n"
2691 " Lists all known IAX peers.\n";
2693 static char show_reg_usage[] =
2694 "Usage: iax2 show registry\n"
2695 " Lists all registration requests and status.\n";
2697 static char debug_usage[] =
2698 "Usage: iax2 debug\n"
2699 " Enables dumping of IAX packets for debugging purposes\n";
2701 static char no_debug_usage[] =
2702 "Usage: iax2 no debug\n"
2703 " Disables dumping of IAX packets for debugging purposes\n";
2705 static char debug_trunk_usage[] =
2706 "Usage: iax2 trunk debug\n"
2707 " Requests current status of IAX trunking\n";
2709 static struct ast_cli_entry cli_show_users =
2710 { { "iax2", "show", "users", NULL }, iax2_show_users, "Show defined IAX users", show_users_usage };
2711 static struct ast_cli_entry cli_show_channels =
2712 { { "iax2", "show", "channels", NULL }, iax2_show_channels, "Show active IAX channels", show_channels_usage };
2713 static struct ast_cli_entry cli_show_peers =
2714 { { "iax2", "show", "peers", NULL }, iax2_show_peers, "Show defined IAX peers", show_peers_usage };
2715 static struct ast_cli_entry cli_show_registry =
2716 { { "iax2", "show", "registry", NULL }, iax2_show_registry, "Show IAX registration status", show_reg_usage };
2717 static struct ast_cli_entry cli_debug =
2718 { { "iax2", "debug", NULL }, iax2_do_debug, "Enable IAX debugging", debug_usage };
2719 static struct ast_cli_entry cli_trunk_debug =
2720 { { "iax2", "trunk", "debug", NULL }, iax2_do_trunk_debug, "Request IAX trunk debug", debug_trunk_usage };
2721 static struct ast_cli_entry cli_no_debug =
2722 { { "iax2", "no", "debug", NULL }, iax2_no_debug, "Disable IAX debugging", no_debug_usage };
2724 static int iax2_write(struct ast_channel *c, struct ast_frame *f)
2726 struct chan_iax2_pvt *i = c->pvt->pvt;
2729 /* If there's an outstanding error, return failure now */
2731 ast_log(LOG_DEBUG, "Write error: %s\n", strerror(errno));
2734 /* If it's already gone, just return */
2737 /* Don't waste bandwidth sending null frames */
2738 if (f->frametype == AST_FRAME_NULL)
2740 /* If we're quelching voice, don't bother sending it */
2741 if ((f->frametype == AST_FRAME_VOICE) && i->quelch)
2743 if (!(i->state & IAX_STATE_STARTED))
2745 /* Simple, just queue for transmission */
2746 return iax2_send(i, f, 0, -1, 0, 0, 0);
2749 static int __send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno,
2750 int now, int transfer, int final)
2754 f.subclass = command;
2755 f.datalen = datalen;
2759 f.src = __FUNCTION__;
2761 return iax2_send(i, &f, ts, seqno, now, transfer, final);
2764 static int send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2766 return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 0);
2769 #ifdef BRIDGE_OPTIMIZATION
2770 static int forward_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2772 return __send_command(iaxs[i->bridgecallno], type, command, ts, data, datalen, seqno, 0, 0, 0);
2776 static int send_command_final(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2778 /* It is assumed that the callno has already been locked */
2779 iax2_predestroy_nolock(i->callno);
2780 return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 1);
2783 static int send_command_immediate(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2785 return __send_command(i, type, command, ts, data, datalen, seqno, 1, 0, 0);
2788 static int send_command_transfer(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen)
2790 return __send_command(i, type, command, ts, data, datalen, 0, 0, 1, 0);
2793 static int apply_context(struct iax2_context *con, char *context)
2796 if (!strcmp(con->context, context))
2804 static int check_access(int callno, struct sockaddr_in *sin, struct iax_ies *ies)
2806 /* Start pessimistic */
2809 struct iax2_user *user;
2810 int gotcapability=0;
2813 if (ies->called_number)
2814 strncpy(iaxs[callno]->exten, ies->called_number, sizeof(iaxs[callno]->exten) - 1);
2815 if (ies->calling_number) {
2816 if (ies->calling_name)
2817 snprintf(iaxs[callno]->callerid, sizeof(iaxs[callno]->callerid), "\"%s\" <%s>", ies->calling_name, ies->calling_number);
2819 strncpy(iaxs[callno]->callerid, ies->calling_number, sizeof(iaxs[callno]->callerid) - 1);
2820 } else if (ies->calling_name)
2821 strncpy(iaxs[callno]->callerid, ies->calling_name, sizeof(iaxs[callno]->callerid) - 1);
2822 if (ies->calling_ani)
2823 strncpy(iaxs[callno]->ani, ies->calling_ani, sizeof(iaxs[callno]->ani) - 1);
2825 strncpy(iaxs[callno]->dnid, ies->dnid, sizeof(iaxs[callno]->dnid)-1);
2826 if (ies->called_context)
2827 strncpy(iaxs[callno]->context, ies->called_context, sizeof(iaxs[callno]->context)-1);
2829 strncpy(iaxs[callno]->language, ies->language, sizeof(iaxs[callno]->language)-1);
2831 strncpy(iaxs[callno]->username, ies->username, sizeof(iaxs[callno]->username)-1);
2833 iaxs[callno]->peerformat = ies->format;
2835 iaxs[callno]->peeradsicpe = ies->adsicpe;
2836 if (ies->capability) {
2838 iaxs[callno]->peercapability = ies->capability;
2841 version = ies->version;
2843 iaxs[callno]->peercapability = iaxs[callno]->peerformat;
2844 if (version > IAX_PROTO_VERSION) {
2845 ast_log(LOG_WARNING, "Peer '%s' has too new a protocol version (%d) for me\n",
2846 inet_ntoa(sin->sin_addr), version);
2849 ast_mutex_lock(&userl.lock);
2850 /* Search the userlist for a compatible entry, and fill in the rest */
2853 if ((!strlen(iaxs[callno]->username) || /* No username specified */
2854 !strcmp(iaxs[callno]->username, user->name)) /* Or this username specified */
2855 && ast_apply_ha(user->ha, sin) /* Access is permitted from this IP */
2856 && (!strlen(iaxs[callno]->context) || /* No context specified */
2857 apply_context(user->contexts, iaxs[callno]->context))) { /* Context is permitted */
2862 ast_mutex_unlock(&userl.lock);
2863 #ifdef MYSQL_FRIENDS
2864 if (!user && mysql && strlen(iaxs[callno]->username) && (strlen(iaxs[callno]->username) < 128)) {
2865 user = mysql_user(iaxs[callno]->username);
2866 if (user && strlen(iaxs[callno]->context) && /* No context specified */
2867 !apply_context(user->contexts, iaxs[callno]->context)) { /* Context is permitted */
2869 free(user->contexts);
2876 /* We found our match (use the first) */
2878 /* Store the requested username if not specified */
2879 if (!strlen(iaxs[callno]->username))
2880 strncpy(iaxs[callno]->username, user->name, sizeof(iaxs[callno]->username)-1);
2881 /* Store whether this is a trunked call, too, of course, and move if appropriate */
2882 iaxs[callno]->trunk = user->trunk;
2883 iaxs[callno]->capability = user->capability;
2884 /* And use the default context */
2885 if (!strlen(iaxs[callno]->context)) {
2887 strncpy(iaxs[callno]->context, user->contexts->context, sizeof(iaxs[callno]->context)-1);
2889 strncpy(iaxs[callno]->context, context, sizeof(iaxs[callno]->context)-1);
2891 /* Copy the secret */
2892 strncpy(iaxs[callno]->secret, user->secret, sizeof(iaxs[callno]->secret)-1);
2893 /* And any input keys */
2894 strncpy(iaxs[callno]->inkeys, user->inkeys, sizeof(iaxs[callno]->inkeys));
2895 /* And the permitted authentication methods */
2896 iaxs[callno]->authmethods = user->authmethods;
2897 /* If they have callerid, override the given caller id. Always store the ANI */
2898 if (strlen(iaxs[callno]->callerid)) {
2899 if (user->hascallerid)
2900 strncpy(iaxs[callno]->callerid, user->callerid, sizeof(iaxs[callno]->callerid)-1);
2901 strncpy(iaxs[callno]->ani, user->callerid, sizeof(iaxs[callno]->ani)-1);
2903 if (strlen(user->accountcode))
2904 strncpy(iaxs[callno]->accountcode, user->accountcode, sizeof(iaxs[callno]->accountcode)-1);
2906 iaxs[callno]->amaflags = user->amaflags;
2907 iaxs[callno]->notransfer = user->notransfer;
2910 iaxs[callno]->trunk = iax2_getpeertrunk(*sin);
2914 static int raw_hangup(struct sockaddr_in *sin, unsigned short src, unsigned short dst)
2916 struct ast_iax2_full_hdr fh;
2917 fh.scallno = htons(src | IAX_FLAG_FULL);
2918 fh.dcallno = htons(dst);
2922 fh.type = AST_FRAME_IAX;
2923 fh.csub = compress_subclass(IAX_COMMAND_INVAL);
2927 ast_log(LOG_DEBUG, "Raw Hangup %s:%d, src=%d, dst=%d\n",
2928 inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), src, dst);
2929 return sendto(netsocket, &fh, sizeof(fh), 0, (struct sockaddr *)sin, sizeof(*sin));
2932 static int authenticate_request(struct chan_iax2_pvt *p)
2934 struct iax_ie_data ied;
2935 memset(&ied, 0, sizeof(ied));
2936 iax_ie_append_short(&ied, IAX_IE_AUTHMETHODS, p->authmethods);
2937 if (p->authmethods & (IAX_AUTH_MD5 | IAX_AUTH_RSA)) {
2938 snprintf(p->challenge, sizeof(p->challenge), "%d", rand());
2939 iax_ie_append_str(&ied, IAX_IE_CHALLENGE, p->challenge);
2941 iax_ie_append_str(&ied,IAX_IE_USERNAME, p->username);
2942 return send_command(p, AST_FRAME_IAX, IAX_COMMAND_AUTHREQ, 0, ied.buf, ied.pos, -1);
2945 static int authenticate_verify(struct chan_iax2_pvt *p, struct iax_ies *ies)
2947 char requeststr[256] = "";
2948 char md5secret[256] = "";
2949 char secret[256] = "";
2950 char rsasecret[256] = "";
2954 if (!(p->state & IAX_STATE_AUTHENTICATED))
2957 strncpy(secret, ies->password, sizeof(secret) - 1);
2958 if (ies->md5_result)
2959 strncpy(md5secret, ies->md5_result, sizeof(md5secret)-1);
2960 if (ies->rsa_result)
2961 strncpy(rsasecret, ies->rsa_result, sizeof(rsasecret)-1);
2962 if ((p->authmethods & IAX_AUTH_RSA) && strlen(rsasecret) && strlen(p->inkeys)) {
2963 struct ast_key *key;
2967 strncpy(tmpkey, p->inkeys, sizeof(tmpkey));
2969 keyn = strsep(&stringp, ":");
2971 key = ast_key_get(keyn, AST_KEY_PUBLIC);
2972 if (key && !ast_check_signature(key, p->challenge, rsasecret)) {
2976 ast_log(LOG_WARNING, "requested inkey '%s' for RSA authentication does not exist\n", keyn);
2977 keyn = strsep(&stringp, ":");
2979 } else if (p->authmethods & IAX_AUTH_MD5) {
2980 struct MD5Context md5;
2981 unsigned char digest[16];
2983 MD5Update(&md5, p->challenge, strlen(p->challenge));
2984 MD5Update(&md5, p->secret, strlen(p->secret));
2985 MD5Final(digest, &md5);
2986 /* If they support md5, authenticate with it. */
2988 sprintf(requeststr + (x << 1), "%2.2x", digest[x]);
2989 if (!strcasecmp(requeststr, md5secret))
2991 } else if (p->authmethods & IAX_AUTH_PLAINTEXT) {
2992 if (!strcmp(secret, p->secret))
2998 static int register_verify(int callno, struct sockaddr_in *sin, struct iax_ies *ies)
3000 char requeststr[256] = "";
3001 char peer[256] = "";
3002 char md5secret[256] = "";
3003 char rsasecret[256] = "";
3004 char secret[256] = "";
3005 struct iax2_peer *p;
3006 struct ast_key *key;
3011 iaxs[callno]->state &= ~IAX_STATE_AUTHENTICATED;
3012 strcpy(iaxs[callno]->peer, "");
3014 strncpy(peer, ies->username, sizeof(peer) - 1);
3016 strncpy(secret, ies->password, sizeof(secret) - 1);
3017 if (ies->md5_result)
3018 strncpy(md5secret, ies->md5_result, sizeof(md5secret)-1);
3019 if (ies->rsa_result)
3020 strncpy(rsasecret, ies->rsa_result, sizeof(rsasecret)-1);
3022 expire = ies->refresh;
3024 if (!strlen(peer)) {
3025 ast_log(LOG_NOTICE, "Empty registration from %s\n", inet_ntoa(sin->sin_addr));
3029 ast_mutex_lock(&peerl.lock);
3030 for (p = peerl.peers; p ; p = p->next)
3031 if (!strcasecmp(p->name, peer))
3033 ast_mutex_unlock(&peerl.lock);
3034 #ifdef MYSQL_FRIENDS
3036 p = mysql_peer(peer);
3040 ast_log(LOG_NOTICE, "No registration for peer '%s' (from %s)\n", peer, inet_ntoa(sin->sin_addr));
3045 ast_log(LOG_NOTICE, "Peer '%s' is not dynamic (from %s)\n", peer, inet_ntoa(sin->sin_addr));
3051 if (!ast_apply_ha(p->ha, sin)) {
3052 ast_log(LOG_NOTICE, "Host %s denied access to register peer '%s'\n", inet_ntoa(sin->sin_addr), p->name);
3057 strncpy(iaxs[callno]->secret, p->secret, sizeof(iaxs[callno]->secret)-1);
3058 strncpy(iaxs[callno]->inkeys, p->inkeys, sizeof(iaxs[callno]->inkeys)-1);
3059 /* Check secret against what we have on file */
3060 if (strlen(rsasecret) && (p->authmethods & IAX_AUTH_RSA) && strlen(iaxs[callno]->challenge)) {
3061 if (strlen(p->inkeys)) {
3064 strncpy(tmpkeys, p->inkeys, sizeof(tmpkeys));
3066 keyn = strsep(&stringp, ":");
3068 key = ast_key_get(keyn, AST_KEY_PUBLIC);
3069 if (key && !ast_check_signature(key, iaxs[callno]->challenge, rsasecret)) {
3070 iaxs[callno]->state |= IAX_STATE_AUTHENTICATED;
3073 ast_log(LOG_WARNING, "requested inkey '%s' does not exist\n", keyn);
3074 keyn = strsep(&stringp, ":");
3077 ast_log(LOG_NOTICE, "Host %s failed RSA authentication with inkeys '%s'\n", peer, p->inkeys);
3083 ast_log(LOG_NOTICE, "Host '%s' trying to do RSA authentication, but we have no inkeys\n", peer);
3088 } else if (strlen(secret) && (p->authmethods & IAX_AUTH_PLAINTEXT)) {
3089 /* They've provided a plain text password and we support that */
3090 if (strcmp(secret, p->secret)) {
3091 ast_log(LOG_NOTICE, "Host %s did not provide proper plaintext password for '%s'\n", inet_ntoa(sin->sin_addr), p->name);
3096 iaxs[callno]->state |= IAX_STATE_AUTHENTICATED;
3097 } else if (strlen(md5secret) && (p->authmethods & IAX_AUTH_MD5) && strlen(iaxs[callno]->challenge)) {
3098 struct MD5Context md5;
3099 unsigned char digest[16];
3101 MD5Update(&md5, iaxs[callno]->challenge, strlen(iaxs[callno]->challenge));
3102 MD5Update(&md5, p->secret, strlen(p->secret));
3103 MD5Final(digest, &md5);
3105 sprintf(requeststr + (x << 1), "%2.2x", digest[x]);
3106 if (strcasecmp(requeststr, md5secret)) {
3107 ast_log(LOG_NOTICE, "Host %s failed MD5 authentication for '%s' (%s != %s)\n", inet_ntoa(sin->sin_addr), p->name, requeststr, md5secret);
3112 iaxs[callno]->state |= IAX_STATE_AUTHENTICATED;
3113 } else if (strlen(md5secret) || strlen(secret)) {
3114 ast_log(LOG_NOTICE, "Inappropriate authentication received\n");
3119 strncpy(iaxs[callno]->peer, peer, sizeof(iaxs[callno]->peer)-1);
3120 /* Choose lowest expirey number */
3121 if (expire && (expire < iaxs[callno]->expirey))
3122 iaxs[callno]->expirey = expire;
3129 static int authenticate(char *challenge, char *secret, char *keyn, int authmethods, struct iax_ie_data *ied, struct sockaddr_in *sin)
3133 if (keyn && strlen(keyn)) {
3134 if (!(authmethods & IAX_AUTH_RSA)) {
3135 if (!secret || !strlen(secret))
3136 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));
3137 } else if (!strlen(challenge)) {
3138 ast_log(LOG_NOTICE, "No challenge provided for RSA authentication to %s\n", inet_ntoa(sin->sin_addr));
3141 struct ast_key *key;
3142 key = ast_key_get(keyn, AST_KEY_PRIVATE);
3144 ast_log(LOG_NOTICE, "Unable to find private key '%s'\n", keyn);
3146 if (ast_sign(key, challenge, sig)) {
3147 ast_log(LOG_NOTICE, "Unable to sign challenge withy key\n");
3150 iax_ie_append_str(ied, IAX_IE_RSA_RESULT, sig);
3157 if (res && secret && strlen(secret)) {
3158 if ((authmethods & IAX_AUTH_MD5) && strlen(challenge)) {
3159 struct MD5Context md5;
3160 unsigned char digest[16];
3161 char digres[128] = "";
3163 MD5Update(&md5, challenge, strlen(challenge));
3164 MD5Update(&md5, secret, strlen(secret));
3165 MD5Final(digest, &md5);
3166 /* If they support md5, authenticate with it. */
3168 sprintf(digres + (x << 1), "%2.2x", digest[x]);
3169 iax_ie_append_str(ied, IAX_IE_MD5_RESULT, digres);
3171 } else if (authmethods & IAX_AUTH_PLAINTEXT) {
3172 iax_ie_append_str(ied, IAX_IE_PASSWORD, secret);
3175 ast_log(LOG_NOTICE, "No way to send secret to peer '%s' (their methods: %d)\n", inet_ntoa(sin->sin_addr), authmethods);
3180 static int authenticate_reply(struct chan_iax2_pvt *p, struct sockaddr_in *sin, struct iax_ies *ies, char *override, char *okey)
3182 struct iax2_peer *peer;
3183 /* Start pessimistic */
3185 int authmethods = 0;
3186 struct iax_ie_data ied;
3188 memset(&ied, 0, sizeof(ied));
3191 strncpy(p->username, ies->username, sizeof(p->username) - 1);
3193 strncpy(p->challenge, ies->challenge, sizeof(p->challenge)-1);
3194 if (ies->authmethods)
3195 authmethods = ies->authmethods;
3197 /* Check for override RSA authentication first */
3198 if ((override && strlen(override)) || (okey && strlen(okey))) {
3199 /* Normal password authentication */
3200 res = authenticate(p->challenge, override, okey, authmethods, &ied, sin);
3202 ast_mutex_lock(&peerl.lock);
3205 if ((!strlen(p->peer) || !strcmp(p->peer, peer->name))
3206 /* No peer specified at our end, or this is the peer */
3207 && (!strlen(peer->username) || (!strcmp(peer->username, p->username)))
3208 /* No username specified in peer rule, or this is the right username */
3209 && (!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)))
3210 /* No specified host, or this is our host */
3212 res = authenticate(p->challenge, peer->secret, peer->outkey, authmethods, &ied, sin);
3218 ast_mutex_unlock(&peerl.lock);
3221 res = send_command(p, AST_FRAME_IAX, IAX_COMMAND_AUTHREP, 0, ied.buf, ied.pos, -1);
3225 static int iax2_do_register(struct iax2_registry *reg);
3227 static int iax2_do_register_s(void *data)
3229 struct iax2_registry *reg = data;
3231 iax2_do_register(reg);
3235 static int try_transfer(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
3238 char newip[256] = "";
3239 struct iax_ie_data ied;
3240 struct sockaddr_in new;
3243 memset(&ied, 0, sizeof(ied));
3244 if (ies->apparent_addr)
3245 memcpy(&new, ies->apparent_addr, sizeof(new));
3247 newcall = ies->callno;
3248 if (!newcall || !new.sin_addr.s_addr || !new.sin_port) {
3249 ast_log(LOG_WARNING, "Invalid transfer request\n");
3252 pvt->transfercallno = newcall;
3253 memcpy(&pvt->transfer, &new, sizeof(pvt->transfer));
3254 inet_aton(newip, &pvt->transfer.sin_addr);
3255 pvt->transfer.sin_family = AF_INET;
3256 pvt->transferring = TRANSFER_BEGIN;
3257 pvt->transferid = ies->transferid;
3258 if (ies->transferid)
3259 iax_ie_append_int(&ied, IAX_IE_TRANSFERID, ies->transferid);
3260 send_command_transfer(pvt, AST_FRAME_IAX, IAX_COMMAND_TXCNT, 0, ied.buf, ied.pos);
3264 static int complete_dpreply(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
3266 char exten[256] = "";
3267 int status = CACHE_FLAG_UNKNOWN;
3268 int expirey = iaxdefaultdpcache;
3271 struct iax2_dpcache *dp, *prev;
3273 if (ies->called_number)
3274 strncpy(exten, ies->called_number, sizeof(exten)-1);
3276 if (ies->dpstatus & IAX_DPSTATUS_EXISTS)
3277 status = CACHE_FLAG_EXISTS;
3278 else if (ies->dpstatus & IAX_DPSTATUS_CANEXIST)
3279 status = CACHE_FLAG_CANEXIST;
3280 else if (ies->dpstatus & IAX_DPSTATUS_NONEXISTANT)
3281 status = CACHE_FLAG_NONEXISTANT;
3283 if (ies->dpstatus & IAX_DPSTATUS_IGNOREPAT) {
3284 /* Don't really do anything with this */
3287 expirey = ies->refresh;
3288 if (ies->dpstatus & IAX_DPSTATUS_MATCHMORE)
3289 matchmore = CACHE_FLAG_MATCHMORE;
3290 ast_mutex_lock(&dpcache_lock);
3292 dp = pvt->dpentries;
3294 if (!strcmp(dp->exten, exten)) {
3297 prev->peer = dp->peer;
3299 pvt->dpentries = dp->peer;
3302 dp->expirey.tv_sec = dp->orig.tv_sec + expirey;
3303 if (dp->flags & CACHE_FLAG_PENDING) {
3304 dp->flags &= ~CACHE_FLAG_PENDING;
3305 dp->flags |= status;
3306 dp->flags |= matchmore;
3308 /* Wake up waiters */
3309 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
3310 if (dp->waiters[x] > -1)
3311 write(dp->waiters[x], "asdf", 4);
3316 ast_mutex_unlock(&dpcache_lock);
3320 static int complete_transfer(int callno, struct iax_ies *ies)
3323 struct chan_iax2_pvt *pvt = iaxs[callno];
3324 struct iax_frame *cur;
3327 peercallno = ies->callno;
3329 if (peercallno < 1) {
3330 ast_log(LOG_WARNING, "Invalid transfer request\n");
3333 memcpy(&pvt->addr, &pvt->transfer, sizeof(pvt->addr));
3334 memset(&pvt->transfer, 0, sizeof(pvt->transfer));
3335 /* Reset sequence numbers */
3339 pvt->peercallno = peercallno;
3340 pvt->transferring = TRANSFER_NONE;
3341 pvt->svoiceformat = -1;
3342 pvt->voiceformat = 0;
3343 pvt->svideoformat = -1;
3344 pvt->videoformat = 0;
3345 pvt->transfercallno = -1;
3346 memset(&pvt->rxcore, 0, sizeof(pvt->rxcore));
3347 memset(&pvt->offset, 0, sizeof(pvt->offset));
3348 memset(&pvt->history, 0, sizeof(pvt->history));
3349 pvt->jitterbuffer = 0;
3351 pvt->historicjitter = 0;
3355 pvt->pingtime = DEFAULT_RETRY_TIME;
3356 ast_mutex_lock(&iaxq.lock);
3357 for (cur = iaxq.head; cur ; cur = cur->next) {
3358 /* We must cancel any packets that would have been transmitted
3359 because now we're talking to someone new. It's okay, they
3360 were transmitted to someone that didn't care anyway. */
3361 if (callno == cur->callno)
3364 ast_mutex_unlock(&iaxq.lock);
3368 static int iax2_ack_registry(struct iax_ies *ies, struct sockaddr_in *sin, int callno)
3370 struct iax2_registry *reg;
3371 /* Start pessimistic */
3372 char peer[256] = "";
3373 char msgstatus[40] = "";
3375 char ourip[256] = "<Unspecified>";
3376 struct sockaddr_in oldus;
3377 struct sockaddr_in us;
3380 memset(&us, 0, sizeof(us));
3381 if (ies->apparent_addr)
3382 memcpy(&us, ies->apparent_addr, sizeof(us));
3384 strncpy(peer, ies->username, sizeof(peer) - 1);
3386 refresh = ies->refresh;
3387 if (ies->calling_number) {
3388 /* We don't do anything with it really, but maybe we should */
3390 reg = iaxs[callno]->reg;
3392 ast_log(LOG_WARNING, "Registry acknowledge on unknown registery '%s'\n", peer);
3395 memcpy(&oldus, ®->us, sizeof(oldus));
3396 oldmsgs = reg->messages;
3397 if (inaddrcmp(®->addr, sin)) {
3398 ast_log(LOG_WARNING, "Received unsolicited registry ack from '%s'\n", inet_ntoa(sin->sin_addr));
3401 memcpy(®->us, &us, sizeof(reg->us));
3402 reg->messages = ies->msgcount;
3403 if (refresh && (reg->refresh < refresh)) {
3404 /* Refresh faster if necessary */
3405 reg->refresh = refresh;
3406 if (reg->expire > -1)
3407 ast_sched_del(sched, reg->expire);
3408 reg->expire = ast_sched_add(sched, (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
3410 if ((inaddrcmp(&oldus, ®->us) || (reg->messages != oldmsgs)) && (option_verbose > 2)) {
3411 if (reg->messages > 65534)
3412 snprintf(msgstatus, sizeof(msgstatus), " with message(s) waiting\n");
3413 else if (reg->messages > 1)
3414 snprintf(msgstatus, sizeof(msgstatus), " with %d messages waiting\n", reg->messages);
3415 else if (reg->messages > 0)
3416 snprintf(msgstatus, sizeof(msgstatus), " with 1 message waiting\n");
3417 else if (reg->messages > -1)
3418 snprintf(msgstatus, sizeof(msgstatus), " with no messages waiting\n");
3419 snprintf(ourip, sizeof(ourip), "%s:%d", inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
3420 ast_verbose(VERBOSE_PREFIX_3 "Registered to '%s', who sees us as %s%s\n", inet_ntoa(sin->sin_addr), ourip, msgstatus);
3422 reg->regstate = REG_STATE_REGISTERED;
3426 static int iax2_register(char *value, int lineno)
3428 struct iax2_registry *reg;
3430 char *username, *hostname, *secret;
3437 strncpy(copy, value, sizeof(copy)-1);
3439 username = strsep(&stringp, "@");
3440 hostname = strsep(&stringp, "@");
3442 ast_log(LOG_WARNING, "Format for registration is user[:secret]@host[:port] at line %d", lineno);
3446 username = strsep(&stringp, ":");
3447 secret = strsep(&stringp, ":");
3449 hostname = strsep(&stringp, ":");
3450 porta = strsep(&stringp, ":");
3452 if (porta && !atoi(porta)) {
3453 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
3456 hp = gethostbyname(hostname);
3458 ast_log(LOG_WARNING, "Host '%s' not found at line %d\n", hostname, lineno);
3461 reg = malloc(sizeof(struct iax2_registry));
3463 memset(reg, 0, sizeof(struct iax2_registry));
3464 strncpy(reg->username, username, sizeof(reg->username)-1);
3466 strncpy(reg->secret, secret, sizeof(reg->secret)-1);
3468 reg->refresh = IAX_DEFAULT_REG_EXPIRE;
3469 reg->addr.sin_family = AF_INET;
3470 memcpy(®->addr.sin_addr, hp->h_addr, sizeof(®->addr.sin_addr));
3471 reg->addr.sin_port = porta ? htons(atoi(porta)) : htons(IAX_DEFAULT_PORTNO);
3472 reg->next = registrations;
3474 registrations = reg;
3476 ast_log(LOG_ERROR, "Out of memory\n");
3482 static int expire_registry(void *data)
3484 struct iax2_peer *p = data;
3485 /* Reset the address */
3486 memset(&p->addr, 0, sizeof(p->addr));
3487 /* Reset expire notice */
3489 /* Reset expirey value */
3490 p->expirey = expirey;
3491 ast_db_del("IAX/Registry", p->name);