2 * Asterisk -- A telephony toolkit for Linux.
4 * Implementation of Inter-Asterisk eXchange
6 * Copyright (C) 1999, Mark Spencer
8 * Mark Spencer <markster@linux-support.net>
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 <arpa/inet.h>
33 #include <sys/socket.h>
34 #include <netinet/in.h>
35 #include <netinet/in_systm.h>
36 #include <netinet/ip.h>
38 #include <sys/signal.h>
50 #define IPTOS_MINCOST 0x02
54 * Uncomment to try experimental IAX bridge optimization,
55 * designed to reduce latency when IAX calls cannot
59 #define BRIDGE_OPTIMIZATION
62 #define DEFAULT_RETRY_TIME 1000
63 #define MEMORY_SIZE 100
64 #define DEFAULT_DROP 3
68 /* Sample over last 100 units to determine historic jitter */
71 static char *desc = "Inter Asterisk eXchange";
72 static char *tdesc = "Inter Asterisk eXchange Drver";
73 static char *type = "IAX";
75 static char context[80] = "default";
77 static int max_retries = 4;
78 static int ping_time = 20;
79 static int lagrq_time = 10;
80 static int nextcallno = 0;
81 static int maxjitterbuffer=3000;
83 static int iaxdefaultdpcache=10 * 60; /* Cache dialplan entries for 10 minutes by default */
85 static int iaxdefaulttimeout = 5; /* Default to wait no more than 5 seconds for a reply to come back */
87 static int netsocket = -1;
91 static int expirey = AST_DEFAULT_REG_EXPIRE;
94 static pthread_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
96 int (*iax_regfunk)(char *username, int onoff) = NULL;
99 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
101 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
102 ~AST_FORMAT_SLINEAR & \
106 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
110 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
114 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
115 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
116 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
118 static struct io_context *io;
119 static struct sched_context *sched;
121 static int iax_capability = IAX_CAPABILITY_FULLBANDWIDTH;
123 static int iax_dropcount = DEFAULT_DROP;
125 static int use_jitterbuffer = 1;
127 static int iaxdebug = 0;
129 static char accountcode[20];
130 static int amaflags = 0;
132 static pthread_t netthreadid;
134 #define IAX_STATE_STARTED (1 << 0)
135 #define IAX_STATE_AUTHENTICATED (1 << 1)
136 #define IAX_STATE_TBD (1 << 2)
139 char context[AST_MAX_EXTENSION];
140 struct iax_context *next;
147 char accountcode[20];
148 char inkeys[80]; /* Key(s) this user can use to authenticate to us */
151 char callerid[AST_MAX_EXTENSION];
153 struct iax_context *contexts;
154 struct iax_user *next;
161 char outkey[80]; /* What key we use to talk to this peer */
162 char context[AST_MAX_EXTENSION]; /* Default context (for transfer really) */
163 struct sockaddr_in addr;
167 /* Dynamic Registration fields */
168 int dynamic; /* If this is a dynamic peer */
169 struct sockaddr_in defaddr; /* Default address if there is one */
170 char challenge[80]; /* Challenge used to authenticate the secret */
172 char inkeys[80]; /* Key(s) this peer can use to authenticate to us */
175 /* Suggested caller id if registering */
176 char callerid[AST_MAX_EXTENSION];
177 /* Whether or not to send ANI */
179 int expire; /* Schedule entry for expirey */
180 int expirey; /* How soon to expire */
181 int capability; /* Capability */
182 int delme; /* I need to be deleted */
185 int callno; /* Call number of POKE request */
186 int pokeexpire; /* When to expire poke */
187 int lastms; /* How long last response took (in ms), or -1 for no response */
188 int maxms; /* Max ms we will accept for the host to be up, 0 to not monitor */
191 struct iax_peer *next;
194 #define REG_STATE_UNREGISTERED 0
195 #define REG_STATE_REGSENT 1
196 #define REG_STATE_AUTHSENT 2
197 #define REG_STATE_REGISTERED 3
198 #define REG_STATE_REJECTED 4
199 #define REG_STATE_TIMEOUT 5
200 #define REG_STATE_NOAUTH 6
202 #define TRANSFER_NONE 0
203 #define TRANSFER_BEGIN 1
204 #define TRANSFER_READY 2
205 #define TRANSFER_RELEASED 3
206 #define TRANSFER_PASSTHROUGH 4
208 struct iax_registry {
209 struct sockaddr_in addr; /* Who we connect to for registration purposes */
211 char secret[80]; /* Password or key name in []'s */
213 int expire; /* Sched ID of expiration */
214 int refresh; /* How often to refresh */
216 int callno; /* Associated call number if applicable */
217 struct sockaddr_in us; /* Who the server thinks we are */
218 struct iax_registry *next;
221 static struct iax_registry *registrations;
223 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
224 #define MIN_RETRY_TIME 10
225 #define MAX_RETRY_TIME 10000
226 #define MAX_JITTER_BUFFER 50
228 /* If we have more than this much excess real jitter buffer, srhink it. */
229 static int max_jitter_buffer = MAX_JITTER_BUFFER;
231 struct chan_iax_pvt {
232 /* Pipes for communication. pipe[1] belongs to the
233 network thread (write), and pipe[0] belongs to the individual
235 /* Whether or not we Quelch audio */
237 /* Last received voice format */
239 /* Last sent voice format */
241 /* What we are capable of sending */
243 /* Last received timestamp */
245 /* Last sent timestamp - never send the same timestamp twice in a single call */
246 unsigned int lastsent;
248 unsigned int pingtime;
249 /* Max time for initial response */
252 struct sockaddr_in addr;
253 /* Our call number */
257 /* Peer selected format */
259 /* Peer capability */
261 /* timeval that we base our transmission on */
262 struct timeval offset;
263 /* timeval that we base our delivery on */
264 struct timeval rxcore;
265 /* Historical delivery time */
266 int history[MEMORY_SIZE];
267 /* Current base jitterbuffer */
269 /* Current jitter measure */
271 /* Historic jitter value */
275 /* Error, as discovered by the manager */
277 /* Owner if we have one */
278 struct ast_channel *owner;
279 /* What's our state? */
281 /* Expirey (optional) */
283 /* Next outgoing sequence number */
284 unsigned short oseqno;
285 /* Next incoming sequence number */
286 unsigned short iseqno;
289 /* Default Context */
291 /* Caller ID if available */
293 /* Hidden Caller ID (i.e. ANI) if appropriate */
295 /* Whether or not ani should be transmitted in addition to Caller*ID */
299 /* Requested Extension */
300 char exten[AST_MAX_EXTENSION];
301 /* Expected Username */
303 /* Expected Secret */
305 /* permitted authentication methods */
309 /* Public keys permitted keys for incoming authentication */
311 /* Private key for outgoing authentication */
313 /* Preferred language */
315 /* Associated registry */
316 struct iax_registry *reg;
317 /* Associated peer for poking */
318 struct iax_peer *peerpoke;
320 /* Transferring status */
322 /* Already disconnected */
324 /* Who we are IAX transfering to */
325 struct sockaddr_in transfer;
326 /* What's the new call number for the transfer */
329 /* Status of knowledge of peer ADSI capability */
332 /* Who we are bridged to */
334 int pingid; /* Transmit PING request */
335 int lagid; /* Retransmit lag request */
336 int autoid; /* Auto hangup for Dialplan requestor */
337 int initid; /* Initial peer auto-congest ID (based on qualified peers) */
338 char dproot[AST_MAX_EXTENSION];
339 char accountcode[20];
341 struct iax_dpcache *dpentries;
344 #define DIRECTION_INGRESS 1
345 #define DIRECTION_OUTGRESS 2
347 struct ast_iax_frame {
348 /* Actual, isolated frame */
350 /* /Our/ call number */
352 /* Start of raw frame (outgoing only) */
354 /* Length of frame (outgoing only) */
356 /* How many retries so far? */
358 /* Outgoing relative timestamp (ms) */
360 /* How long to wait before retrying */
362 /* Are we received out of order? */
364 /* Have we been sent at all yet? */
366 /* Packet sequence number */
368 /* Non-zero if should be sent to transfer peer */
370 /* Non-zero if this is the final message */
372 /* Ingress or outgres */
374 /* Retransmission ID */
379 struct ast_iax_frame *next;
380 struct ast_iax_frame *prev;
383 static struct ast_iax_queue {
384 struct ast_iax_frame *head;
385 struct ast_iax_frame *tail;
387 pthread_mutex_t lock;
390 static struct ast_user_list {
391 struct iax_user *users;
392 pthread_mutex_t lock;
395 static struct ast_peer_list {
396 struct iax_peer *peers;
397 pthread_mutex_t lock;
400 /* Extension exists */
401 #define CACHE_FLAG_EXISTS (1 << 0)
402 /* Extension is non-existant */
403 #define CACHE_FLAG_NONEXISTANT (1 << 1)
404 /* Extension can exist */
405 #define CACHE_FLAG_CANEXIST (1 << 2)
406 /* Waiting to hear back response */
407 #define CACHE_FLAG_PENDING (1 << 3)
409 #define CACHE_FLAG_TIMEOUT (1 << 4)
410 /* Request transmitted */
411 #define CACHE_FLAG_TRANSMITTED (1 << 5)
413 #define CACHE_FLAG_UNKNOWN (1 << 6)
415 #define CACHE_FLAG_MATCHMORE (1 << 7)
417 static struct iax_dpcache {
418 char peercontext[AST_MAX_EXTENSION];
419 char exten[AST_MAX_EXTENSION];
421 struct timeval expirey;
425 struct iax_dpcache *next;
426 struct iax_dpcache *peer; /* For linking in peers */
429 static pthread_mutex_t dpcache_lock;
432 static void showframe(struct ast_iax_frame *f, struct ast_iax_full_hdr *fhi, int rx, struct sockaddr_in *sin)
486 struct ast_iax_full_hdr *fh;
494 snprintf(retries, sizeof(retries), "%03d", f->retries);
496 strcpy(retries, "N/A");
499 if (!(ntohs(fh->callno) & AST_FLAG_FULL)) {
500 /* Don't mess with mini-frames */
503 if (fh->type > sizeof(frames)/sizeof(char *)) {
504 snprintf(class2, sizeof(class2), "(%d?)", fh->type);
507 class = frames[(int)fh->type];
509 if (fh->type == AST_FRAME_DTMF) {
510 sprintf(subclass2, "%c", fh->csub);
511 subclass = subclass2;
512 } else if (fh->type == AST_FRAME_IAX) {
513 if (fh->csub >= sizeof(iaxs)/sizeof(iaxs[0])) {
514 snprintf(subclass2, sizeof(subclass2), "(%d?)", fh->csub);
515 subclass = subclass2;
517 subclass = iaxs[(int)fh->csub];
519 } else if (fh->type == AST_FRAME_CONTROL) {
520 if (fh->csub > sizeof(cmds)/sizeof(char *)) {
521 snprintf(subclass2, sizeof(subclass2), "(%d?)", fh->csub);
522 subclass = subclass2;
524 subclass = cmds[(int)fh->csub];
527 snprintf(subclass2, sizeof(subclass2), "%d", fh->csub);
528 subclass = subclass2;
531 "%s-Frame Retry[%s] -- Seqno: %2.2d Type: %s Subclass: %s\n",
533 retries, ntohs(fh->seqno), class, subclass);
535 " Timestamp: %05dms Callno: %5.5d DCall: %5.5d [%s:%d]\n",
537 (short)(ntohs(fh->callno) & ~AST_FLAG_FULL), (short) ntohs(fh->dcallno),
538 inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
542 /* XXX We probably should use a mutex when working with this XXX */
543 static struct chan_iax_pvt *iaxs[AST_IAX_MAX_CALLS];
544 static pthread_mutex_t iaxsl[AST_IAX_MAX_CALLS];
546 static int send_command(struct chan_iax_pvt *, char, int, unsigned int, char *, int, int);
547 static int send_command_immediate(struct chan_iax_pvt *, char, int, unsigned int, char *, int, int);
548 static int send_command_final(struct chan_iax_pvt *, char, int, unsigned int, char *, int, int);
549 static int send_command_transfer(struct chan_iax_pvt *, char, int, unsigned int, char *, int);
551 static unsigned int calc_timestamp(struct chan_iax_pvt *p, unsigned int ts);
553 static int send_ping(void *data)
555 int callno = (long)data;
556 /* Ping only if it's real, not if it's bridged */
558 #ifdef BRIDGE_OPTIMIZATION
559 if (iaxs[callno]->bridgecallno < 0)
561 send_command(iaxs[callno], AST_FRAME_IAX, AST_IAX_COMMAND_PING, 0, NULL, 0, -1);
567 static int send_lagrq(void *data)
569 int callno = (long)data;
570 /* Ping only if it's real not if it's bridged */
572 #ifdef BRIDGE_OPTIMIZATION
573 if (iaxs[callno]->bridgecallno < 0)
575 send_command(iaxs[callno], AST_FRAME_IAX, AST_IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
581 static unsigned char compress_subclass(int subclass)
585 /* If it's 128 or smaller, just return it */
586 if (subclass < AST_FLAG_SC_LOG)
588 /* Otherwise find its power */
589 for (x = 0; x < AST_MAX_SHIFT; x++) {
590 if (subclass & (1 << x)) {
592 ast_log(LOG_WARNING, "Can't compress subclass %d\n", subclass);
598 return power | AST_FLAG_SC_LOG;
601 static int uncompress_subclass(unsigned char csub)
603 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
604 if (csub & AST_FLAG_SC_LOG) {
605 /* special case for 'compressed' -1 */
609 return 1 << (csub & ~AST_FLAG_SC_LOG & AST_MAX_SHIFT);
615 static struct chan_iax_pvt *new_iax(void)
617 struct chan_iax_pvt *tmp;
618 tmp = malloc(sizeof(struct chan_iax_pvt));
620 memset(tmp, 0, sizeof(struct chan_iax_pvt));
622 tmp->peercallno = -1;
623 tmp->transfercallno = -1;
624 tmp->bridgecallno = -1;
629 /* strncpy(tmp->context, context, sizeof(tmp->context)-1); */
630 strncpy(tmp->exten, "s", sizeof(tmp->exten)-1);
635 static int get_samples(struct ast_frame *f)
638 switch(f->subclass) {
639 case AST_FORMAT_G723_1:
640 samples = 240 /* XXX Not necessarily true XXX */;
643 samples = 160 * (f->datalen / 33);
645 case AST_FORMAT_ILBC:
646 samples = 240 * (f->datalen / 50);
648 case AST_FORMAT_G729A:
649 samples = 160 * (f->datalen / 20);
651 case AST_FORMAT_SLINEAR:
652 samples = f->datalen / 2;
654 case AST_FORMAT_LPC10:
656 samples += (((char *)(f->data))[7] & 0x1) * 8;
658 case AST_FORMAT_ULAW:
659 samples = f->datalen;
661 case AST_FORMAT_ALAW:
662 samples = f->datalen;
664 case AST_FORMAT_ADPCM:
665 samples = f->datalen *2;
667 case AST_FORMAT_SPEEX:
668 samples = (f->datalen/39)*160;
671 ast_log(LOG_WARNING, "Don't know how to calculate samples on %d packets\n", f->subclass);
676 static int frames = 0;
677 static int iframes = 0;
678 static int oframes = 0;
680 static struct ast_iax_frame *ast_iax_frame_new(int direction)
682 struct ast_iax_frame *fr;
683 fr = malloc(sizeof(struct ast_iax_frame));
685 fr->direction = direction;
688 if (fr->direction == DIRECTION_INGRESS)
696 static void ast_iax_frame_free(struct ast_iax_frame *fr)
698 if (fr->retrans > -1)
699 ast_sched_del(sched, fr->retrans);
700 if (fr->direction == DIRECTION_INGRESS)
702 else if (fr->direction == DIRECTION_OUTGRESS)
705 ast_log(LOG_WARNING, "Attempt to double free frame detected\n");
714 static struct ast_iax_frame *iaxfrdup2(struct ast_iax_frame *fr, int ch)
716 /* Malloc() a copy of a frame */
717 struct ast_iax_frame *new = ast_iax_frame_new(DIRECTION_INGRESS);
719 memcpy(new, fr, sizeof(struct ast_iax_frame));
720 new->f = ast_frdup(fr->f);
721 /* Copy full header */
723 memcpy(new->f->data - sizeof(struct ast_iax_full_hdr),
724 fr->f->data - sizeof(struct ast_iax_full_hdr),
725 sizeof(struct ast_iax_full_hdr));
726 /* Grab new data pointer */
727 new->data = new->f->data - (fr->f->data - fr->data);
732 new->direction = DIRECTION_INGRESS;
738 #define NEW_PREVENT 0
742 static int match(struct sockaddr_in *sin, short callno, short dcallno, struct chan_iax_pvt *cur)
744 if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
745 (cur->addr.sin_port == sin->sin_port)) {
746 /* This is the main host */
747 if ((cur->peercallno == callno) ||
748 ((dcallno == cur->callno) && (cur->peercallno) == -1)) {
749 /* That's us. Be sure we keep track of the peer call number */
753 if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
754 (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
755 /* We're transferring */
756 if (dcallno == cur->callno)
762 static int find_callno(short callno, short dcallno ,struct sockaddr_in *sin, int new)
767 if (new <= NEW_ALLOW) {
768 /* Look for an existing connection first */
769 for (x=0;(res < 0) && (x<AST_IAX_MAX_CALLS);x++) {
770 ast_pthread_mutex_lock(&iaxsl[x]);
772 /* Look for an exact match */
773 if (match(sin, callno, dcallno, iaxs[x])) {
777 ast_pthread_mutex_unlock(&iaxsl[x]);
780 if ((res < 0) && (new >= NEW_ALLOW)) {
781 /* Create a new one */
783 for (x = (nextcallno + 1) % AST_IAX_MAX_CALLS; iaxs[x] && (x != start); x = (x + 1) % AST_IAX_MAX_CALLS)
785 ast_log(LOG_WARNING, "Unable to accept more calls\n");
788 ast_pthread_mutex_lock(&iaxsl[x]);
790 ast_pthread_mutex_unlock(&iaxsl[x]);
793 ast_log(LOG_DEBUG, "Creating new call structure %d\n", x);
794 iaxs[x]->addr.sin_port = sin->sin_port;
795 iaxs[x]->addr.sin_family = sin->sin_family;
796 iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
797 iaxs[x]->peercallno = callno;
799 iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
800 iaxs[x]->expirey = expirey;
801 iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)x);
802 iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)x);
803 iaxs[x]->amaflags = amaflags;
804 strncpy(iaxs[x]->accountcode, accountcode, sizeof(iaxs[x]->accountcode)-1);
806 ast_log(LOG_WARNING, "Out of resources\n");
815 static int iax_queue_frame(int callno, struct ast_frame *f)
818 /* Assumes lock for callno is already held... */
821 if (!pthread_mutex_trylock(&iaxsl[callno])) {
822 ast_log(LOG_WARNING, "Lock is not held on pass %d of iax_queue_frame\n", pass);
825 if (iaxs[callno] && iaxs[callno]->owner) {
826 if (pthread_mutex_trylock(&iaxs[callno]->owner->lock)) {
827 /* Avoid deadlock by pausing and trying again */
828 ast_pthread_mutex_unlock(&iaxsl[callno]);
830 ast_pthread_mutex_lock(&iaxsl[callno]);
832 ast_queue_frame(iaxs[callno]->owner, f, 0);
833 ast_pthread_mutex_unlock(&iaxs[callno]->owner->lock);
842 static int iax_send(struct chan_iax_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
844 static int __do_deliver(void *data)
846 /* Just deliver the packet by using queueing. This is called by
847 the IAX thread with the iaxsl lock held. */
848 struct ast_iax_frame *fr = data;
851 if (iaxs[fr->callno] && !iaxs[fr->callno]->alreadygone) {
852 if (fr->f->frametype == AST_FRAME_IAX) {
853 /* We have to treat some of these packets specially because
854 they're LAG measurement packets */
855 if (fr->f->subclass == AST_IAX_COMMAND_LAGRQ) {
856 /* If we got a queued request, build a reply and send it */
857 fr->f->subclass = AST_IAX_COMMAND_LAGRP;
858 iax_send(iaxs[fr->callno], fr->f, fr->ts, -1, 0, 0, 0);
859 } else if (fr->f->subclass == AST_IAX_COMMAND_LAGRP) {
860 /* This is a reply we've been given, actually measure the difference */
861 ts = calc_timestamp(iaxs[fr->callno], 0);
862 iaxs[fr->callno]->lag = ts - fr->ts;
865 iax_queue_frame(fr->callno, fr->f);
868 /* Free the packet */
870 /* And our iax frame */
871 ast_iax_frame_free(fr);
872 /* And don't run again */
876 static int do_deliver(void *data)
878 /* Locking version of __do_deliver */
879 struct ast_iax_frame *fr = data;
880 int callno = fr->callno;
882 ast_pthread_mutex_lock(&iaxsl[callno]);
883 res = __do_deliver(data);
884 ast_pthread_mutex_unlock(&iaxsl[callno]);
888 static int handle_error(void)
890 /* XXX Ideally we should figure out why an error occured and then abort those
891 rather than continuing to try. Unfortunately, the published interface does
892 not seem to work XXX */
894 struct sockaddr_in *sin;
897 struct sock_extended_err e;
902 m.msg_controllen = sizeof(e);
904 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
906 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
908 if (m.msg_controllen) {
909 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
911 ast_log(LOG_WARNING, "Receive error from %s\n", inet_ntoa(sin->sin_addr));
913 ast_log(LOG_WARNING, "No address detected??\n");
915 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
922 static int send_packet(struct ast_iax_frame *f)
925 /* Called with iaxsl held */
927 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));
928 /* Don't send if there was an error, but return error instead */
930 ast_log(LOG_WARNING, "Call number = %d\n", f->callno);
933 if (!iaxs[f->callno])
935 if (iaxs[f->callno]->error)
940 showframe(f, NULL, 0, &iaxs[f->callno]->transfer);
942 res = sendto(netsocket, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[f->callno]->transfer,
943 sizeof(iaxs[f->callno]->transfer));
947 showframe(f, NULL, 0, &iaxs[f->callno]->addr);
949 res = sendto(netsocket, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[f->callno]->addr,
950 sizeof(iaxs[f->callno]->addr));
954 ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
962 static int iax_predestroy(int callno)
964 struct ast_channel *c;
965 struct chan_iax_pvt *pvt;
966 ast_pthread_mutex_lock(&iaxsl[callno]);
969 ast_pthread_mutex_unlock(&iaxsl[callno]);
972 if (!pvt->alreadygone) {
973 /* No more pings or lagrq's */
974 if (pvt->pingid > -1)
975 ast_sched_del(sched, pvt->pingid);
977 ast_sched_del(sched, pvt->lagid);
978 if (pvt->autoid > -1)
979 ast_sched_del(sched, pvt->autoid);
980 if (pvt->initid > -1)
981 ast_sched_del(sched, pvt->initid);
986 pvt->alreadygone = 1;
990 c->_softhangup |= AST_SOFTHANGUP_DEV;
993 ast_pthread_mutex_lock(&usecnt_lock);
996 ast_log(LOG_WARNING, "Usecnt < 0???\n");
997 ast_pthread_mutex_unlock(&usecnt_lock);
998 ast_update_use_count();
1000 ast_pthread_mutex_unlock(&iaxsl[callno]);
1004 static int iax_predestroy_nolock(int callno)
1007 ast_pthread_mutex_unlock(&iaxsl[callno]);
1008 res = iax_predestroy(callno);
1009 ast_pthread_mutex_lock(&iaxsl[callno]);
1013 static void iax_destroy(int callno)
1015 struct chan_iax_pvt *pvt;
1016 struct ast_iax_frame *cur;
1017 struct ast_channel *owner;
1020 ast_pthread_mutex_lock(&iaxsl[callno]);
1022 iaxs[callno] = NULL;
1029 if (pthread_mutex_trylock(&owner->lock)) {
1030 ast_log(LOG_NOTICE, "Avoiding IAX destroy deadlock\n");
1031 ast_pthread_mutex_unlock(&iaxsl[callno]);
1038 /* No more pings or lagrq's */
1039 if (pvt->pingid > -1)
1040 ast_sched_del(sched, pvt->pingid);
1041 if (pvt->lagid > -1)
1042 ast_sched_del(sched, pvt->lagid);
1043 if (pvt->autoid > -1)
1044 ast_sched_del(sched, pvt->autoid);
1045 if (pvt->initid > -1)
1046 ast_sched_del(sched, pvt->initid);
1053 pvt->alreadygone = 1;
1056 /* If there's an owner, prod it to give up */
1057 owner->pvt->pvt = NULL;
1058 owner->_softhangup |= AST_SOFTHANGUP_DEV;
1059 ast_queue_hangup(owner, 0);
1062 for (cur = iaxq.head; cur ; cur = cur->next) {
1063 /* Cancel any pending transmissions */
1064 if (cur->callno == pvt->callno)
1068 pvt->reg->callno = -1;
1073 ast_pthread_mutex_unlock(&owner->lock);
1075 ast_pthread_mutex_unlock(&iaxsl[callno]);
1077 static void iax_destroy_nolock(int callno)
1079 /* Actually it's easier to unlock, kill it, and relock */
1080 ast_pthread_mutex_unlock(&iaxsl[callno]);
1081 iax_destroy(callno);
1082 ast_pthread_mutex_lock(&iaxsl[callno]);
1087 static int attempt_transmit(void *data)
1089 /* Attempt to transmit the frame to the remote peer...
1090 Called without iaxsl held. */
1091 struct ast_iax_frame *f = data;
1093 int callno = f->callno;
1094 /* Make sure this call is still active */
1096 ast_pthread_mutex_lock(&iaxsl[callno]);
1097 if ((f->callno > -1) && iaxs[f->callno]) {
1098 if ((f->retries < 0) /* Already ACK'd */ ||
1099 (f->retries >= max_retries) /* Too many attempts */) {
1100 /* Record an error if we've transmitted too many times */
1101 if (f->retries >= max_retries) {
1103 /* Transfer timeout */
1104 send_command(iaxs[f->callno], AST_FRAME_IAX, AST_IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
1105 } else if (f->final) {
1107 iax_destroy_nolock(f->callno);
1109 if (iaxs[f->callno]->owner)
1110 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->f->frametype, f->f->subclass, f->ts, f->seqno);
1111 iaxs[f->callno]->error = ETIMEDOUT;
1112 if (iaxs[f->callno]->owner) {
1113 struct ast_frame fr = { 0, };
1115 fr.frametype = AST_FRAME_CONTROL;
1116 fr.subclass = AST_CONTROL_HANGUP;
1117 iax_queue_frame(f->callno, &fr);
1119 if (iaxs[f->callno]->reg) {
1120 memset(&iaxs[f->callno]->reg->us, 0, sizeof(iaxs[f->callno]->reg->us));
1121 iaxs[f->callno]->reg->regstate = REG_STATE_TIMEOUT;
1122 iaxs[f->callno]->reg->refresh = AST_DEFAULT_REG_EXPIRE;
1124 iax_destroy_nolock(f->callno);
1131 /* Attempt transmission */
1134 /* Try again later after 10 times as long */
1136 if (f->retrytime > MAX_RETRY_TIME)
1137 f->retrytime = MAX_RETRY_TIME;
1138 /* Transfer messages max out at one second */
1139 if (f->transfer && (f->retrytime > 1000))
1140 f->retrytime = 1000;
1141 f->retrans = ast_sched_add(sched, f->retrytime, attempt_transmit, f);
1144 /* Make sure it gets freed */
1149 ast_pthread_mutex_unlock(&iaxsl[callno]);
1150 /* Do not try again */
1152 /* Don't attempt delivery, just remove it from the queue */
1153 ast_pthread_mutex_lock(&iaxq.lock);
1155 f->prev->next = f->next;
1157 iaxq.head = f->next;
1159 f->next->prev = f->prev;
1161 iaxq.tail = f->prev;
1163 ast_pthread_mutex_unlock(&iaxq.lock);
1164 /* Free the frame */
1167 ast_iax_frame_free(f);
1172 static int iax_set_jitter(int fd, int argc, char *argv[])
1174 if ((argc != 4) && (argc != 5))
1175 return RESULT_SHOWUSAGE;
1177 max_jitter_buffer = atoi(argv[3]);
1178 if (max_jitter_buffer < 0)
1179 max_jitter_buffer = 0;
1182 if ((atoi(argv[3]) >= 0) && (atoi(argv[3]) < AST_IAX_MAX_CALLS)) {
1183 if (iaxs[atoi(argv[3])]) {
1184 iaxs[atoi(argv[3])]->jitterbuffer = atoi(argv[4]);
1185 if (iaxs[atoi(argv[3])]->jitterbuffer < 0)
1186 iaxs[atoi(argv[3])]->jitterbuffer = 0;
1188 ast_cli(fd, "No such call '%d'\n", atoi(argv[3]));
1190 ast_cli(fd, "%d is not a valid call number\n", atoi(argv[3]));
1193 return RESULT_SUCCESS;
1196 static char jitter_usage[] =
1197 "Usage: iax set jitter [callid] <value>\n"
1198 " If used with a callid, it sets the jitter buffer to the given static\n"
1199 "value (until its next calculation). If used without a callid, the value is used\n"
1200 "to establish the maximum excess jitter buffer that is permitted before the jitter\n"
1201 "buffer size is reduced.";
1203 static int iax_show_stats(int fd, int argc, char *argv[])
1205 struct ast_iax_frame *cur;
1206 int cnt = 0, dead=0, final=0;
1208 return RESULT_SHOWUSAGE;
1209 for (cur = iaxq.head; cur ; cur = cur->next) {
1210 if (cur->retries < 0)
1216 ast_cli(fd, " IAX Statistics\n");
1217 ast_cli(fd, "---------------------\n");
1218 ast_cli(fd, "Outstanding frames: %d (%d ingress, %d outgress)\n", frames, iframes, oframes);
1219 ast_cli(fd, "Packets in transmit queue: %d dead, %d final, %d total\n", dead, final, cnt);
1220 return RESULT_SUCCESS;
1223 static int iax_show_cache(int fd, int argc, char *argv[])
1225 struct iax_dpcache *dp;
1226 char tmp[1024], *pc;
1230 gettimeofday(&tv, NULL);
1231 ast_pthread_mutex_lock(&dpcache_lock);
1233 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
1235 s = dp->expirey.tv_sec - tv.tv_sec;
1237 if (dp->flags & CACHE_FLAG_EXISTS)
1238 strcat(tmp, "EXISTS|");
1239 if (dp->flags & CACHE_FLAG_NONEXISTANT)
1240 strcat(tmp, "NONEXISTANT|");
1241 if (dp->flags & CACHE_FLAG_CANEXIST)
1242 strcat(tmp, "CANEXIST|");
1243 if (dp->flags & CACHE_FLAG_PENDING)
1244 strcat(tmp, "PENDING|");
1245 if (dp->flags & CACHE_FLAG_TIMEOUT)
1246 strcat(tmp, "TIMEOUT|");
1247 if (dp->flags & CACHE_FLAG_TRANSMITTED)
1248 strcat(tmp, "TRANSMITTED|");
1249 if (dp->flags & CACHE_FLAG_MATCHMORE)
1250 strcat(tmp, "MATCHMORE|");
1251 if (dp->flags & CACHE_FLAG_UNKNOWN)
1252 strcat(tmp, "UNKNOWN|");
1253 /* Trim trailing pipe */
1255 tmp[strlen(tmp) - 1] = '\0';
1257 strcpy(tmp, "(none)");
1259 pc = strchr(dp->peercontext, '@');
1261 pc = dp->peercontext;
1264 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
1265 if (dp->waiters[x] > -1)
1268 ast_cli(fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
1270 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
1273 ast_pthread_mutex_unlock(&dpcache_lock);
1274 return RESULT_SUCCESS;
1277 static char show_stats_usage[] =
1278 "Usage: iax show stats\n"
1279 " Display statistics on IAX channel driver.\n";
1282 static char show_cache_usage[] =
1283 "Usage: iax show cache\n"
1284 " Display currently cached IAX Dialplan results.\n";
1286 static struct ast_cli_entry cli_set_jitter =
1287 { { "iax", "set", "jitter", NULL }, iax_set_jitter, "Sets IAX jitter buffer", jitter_usage };
1289 static struct ast_cli_entry cli_show_stats =
1290 { { "iax", "show", "stats", NULL }, iax_show_stats, "Display IAX statistics", show_stats_usage };
1292 static struct ast_cli_entry cli_show_cache =
1293 { { "iax", "show", "cache", NULL }, iax_show_cache, "Display IAX cached dialplan", show_cache_usage };
1295 static unsigned int calc_rxstamp(struct chan_iax_pvt *p);
1297 #ifdef BRIDGE_OPTIMIZATION
1298 static unsigned int calc_fakestamp(struct chan_iax_pvt *from, struct chan_iax_pvt *to, unsigned int ts);
1300 static int forward_delivery(struct ast_iax_frame *fr)
1302 struct chan_iax_pvt *p1, *p2;
1303 p1 = iaxs[fr->callno];
1304 p2 = iaxs[p1->bridgecallno];
1309 /* Fix relative timestamp */
1310 fr->ts = calc_fakestamp(p1, p2, fr->ts);
1311 /* Now just send it send on the 2nd one
1312 with adjusted timestamp */
1313 return iax_send(p2, fr->f, fr->ts, -1, 0, 0, 0);
1317 static int schedule_delivery(struct ast_iax_frame *fr, int reallydeliver)
1320 int drops[MEMORY_SIZE];
1321 int min, max=0, maxone=0,y,z, match;
1322 /* ms is a measure of the "lateness" of the packet relative to the first
1323 packet we received, which always has a lateness of 1. Called by
1324 IAX thread, with iaxsl lock held. */
1325 ms = calc_rxstamp(iaxs[fr->callno]) - fr->ts;
1328 /* What likely happened here is that our counter has circled but we haven't
1329 gotten the update from the main packet. We'll just pretend that we did, and
1330 update the timestamp appropriately. */
1335 /* We got this packet out of order. Lets add 65536 to it to bring it into our new
1340 /* Rotate our history queue of "lateness". Don't worry about those initial
1341 zeros because the first entry will always be zero */
1342 for (x=0;x<MEMORY_SIZE - 1;x++)
1343 iaxs[fr->callno]->history[x] = iaxs[fr->callno]->history[x+1];
1344 /* Add a history entry for this one */
1345 iaxs[fr->callno]->history[x] = ms;
1347 /* Initialize the minimum to reasonable values. It's too much
1348 work to do the same for the maximum, repeatedly */
1349 min=iaxs[fr->callno]->history[0];
1350 for (z=0;z < iax_dropcount + 1;z++) {
1351 /* Start very optimistic ;-) */
1353 for (x=0;x<MEMORY_SIZE;x++) {
1354 if (max < iaxs[fr->callno]->history[x]) {
1355 /* We have a candidate new maximum value. Make
1356 sure it's not in our drop list */
1358 for (y=0;!match && (y<z);y++)
1359 match |= (drops[y] == x);
1361 /* It's not in our list, use it as the new maximum */
1362 max = iaxs[fr->callno]->history[x];
1368 /* On our first pass, find the minimum too */
1369 if (min > iaxs[fr->callno]->history[x])
1370 min = iaxs[fr->callno]->history[x];
1377 /* Just for reference, keep the "jitter" value, the difference between the
1378 earliest and the latest. */
1379 iaxs[fr->callno]->jitter = max - min;
1381 /* IIR filter for keeping track of historic jitter, but always increase
1382 historic jitter immediately for increase */
1384 if (iaxs[fr->callno]->jitter > iaxs[fr->callno]->historicjitter )
1385 iaxs[fr->callno]->historicjitter = iaxs[fr->callno]->jitter;
1387 iaxs[fr->callno]->historicjitter = GAMMA * (double)iaxs[fr->callno]->jitter + (1-GAMMA) *
1388 iaxs[fr->callno]->historicjitter;
1390 /* If our jitter buffer is too big (by a significant margin), then we slowly
1391 shrink it by about 1 ms each time to avoid letting the change be perceived */
1392 if (max < iaxs[fr->callno]->jitterbuffer - max_jitter_buffer)
1393 iaxs[fr->callno]->jitterbuffer -= 2;
1397 /* Constrain our maximum jitter buffer appropriately */
1398 if (max > min + maxjitterbuffer) {
1400 ast_log(LOG_DEBUG, "Constraining buffer from %d to %d + %d\n", max, min , maxjitterbuffer);
1401 max = min + maxjitterbuffer;
1405 /* If our jitter buffer is smaller than our maximum delay, grow the jitter
1406 buffer immediately to accomodate it (and a little more). */
1407 if (max > iaxs[fr->callno]->jitterbuffer)
1408 iaxs[fr->callno]->jitterbuffer = max
1409 /* + ((float)iaxs[fr->callno]->jitter) * 0.1 */;
1413 ast_log(LOG_DEBUG, "min = %d, max = %d, jb = %d, lateness = %d\n", min, max, iaxs[fr->callno]->jitterbuffer, ms);
1415 /* Subtract the lateness from our jitter buffer to know how long to wait
1416 before sending our packet. */
1417 ms = iaxs[fr->callno]->jitterbuffer - ms;
1419 if (!use_jitterbuffer)
1422 /* If the caller just wanted us to update, return now */
1428 ast_log(LOG_DEBUG, "Calculated ms is %d\n", ms);
1429 /* Don't deliver it more than 4 ms late */
1430 if ((ms > -4) || (fr->f->frametype != AST_FRAME_VOICE)) {
1434 ast_log(LOG_DEBUG, "Dropping voice packet since %d ms is, too old\n", ms);
1435 /* Free the packet */
1437 /* And our iax frame */
1438 ast_iax_frame_free(fr);
1442 ast_log(LOG_DEBUG, "Scheduling delivery in %d ms\n", ms);
1443 fr->retrans = ast_sched_add(sched, ms, do_deliver, fr);
1448 static int iax_transmit(struct ast_iax_frame *fr)
1450 /* Lock the queue and place this packet at the end */
1453 /* By setting this to 0, the network thread will send it for us, and
1454 queue retransmission if necessary */
1456 ast_pthread_mutex_lock(&iaxq.lock);
1463 iaxq.tail->next = fr;
1464 fr->prev = iaxq.tail;
1468 ast_pthread_mutex_unlock(&iaxq.lock);
1469 /* Wake up the network thread */
1470 pthread_kill(netthreadid, SIGURG);
1476 static int iax_digit(struct ast_channel *c, char digit)
1478 return send_command(c->pvt->pvt, AST_FRAME_DTMF, digit, 0, NULL, 0, -1);
1481 static int iax_sendtext(struct ast_channel *c, char *text)
1484 return send_command(c->pvt->pvt, AST_FRAME_TEXT,
1485 0, 0, text, strlen(text) + 1, -1);
1488 static int iax_sendimage(struct ast_channel *c, struct ast_frame *img)
1490 return send_command(c->pvt->pvt, AST_FRAME_IMAGE, img->subclass, 0, img->data, img->datalen, -1);
1493 static int iax_sendhtml(struct ast_channel *c, int subclass, char *data, int datalen)
1495 return send_command(c->pvt->pvt, AST_FRAME_HTML, subclass, 0, data, datalen, -1);
1498 static int iax_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
1500 struct chan_iax_pvt *pvt = newchan->pvt->pvt;
1501 pvt->owner = newchan;
1505 static int create_addr(struct sockaddr_in *sin, int *capability, int *sendani, int *maxtime, char *peer, char *context)
1514 sin->sin_family = AF_INET;
1515 ast_pthread_mutex_lock(&peerl.lock);
1518 if (!strcasecmp(p->name, peer)) {
1521 *capability = p->capability;
1522 if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
1523 (!p->maxms || ((p->lastms > 0) && (p->lastms <= p->maxms)))) {
1525 *sendani = p->sendani; /* Whether we transmit ANI */
1527 *maxtime = p->maxms; /* Max time they should take */
1529 strncpy(context, p->context, AST_MAX_EXTENSION - 1);
1530 if (p->addr.sin_addr.s_addr) {
1531 sin->sin_addr = p->addr.sin_addr;
1532 sin->sin_port = p->addr.sin_port;
1534 sin->sin_addr = p->defaddr.sin_addr;
1535 sin->sin_port = p->defaddr.sin_port;
1542 ast_pthread_mutex_unlock(&peerl.lock);
1544 hp = gethostbyname(peer);
1546 memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
1547 sin->sin_port = htons(AST_DEFAULT_IAX_PORTNO);
1550 ast_log(LOG_WARNING, "No such host: %s\n", peer);
1559 static int auto_congest(void *nothing)
1561 int callno = (int)(long)(nothing);
1562 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_CONGESTION };
1563 ast_pthread_mutex_lock(&iaxsl[callno]);
1565 iaxs[callno]->initid = -1;
1566 iax_queue_frame(callno, &f);
1567 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
1569 ast_pthread_mutex_unlock(&iaxsl[callno]);
1573 static int iax_call(struct ast_channel *c, char *dest, int timeout)
1575 struct sockaddr_in sin;
1580 char *secret = NULL;
1582 char requeststr[256] = "";
1583 char myrdest [5] = "s";
1584 char context[AST_MAX_EXTENSION] ="";
1585 char *portno = NULL;
1586 struct chan_iax_pvt *p = c->pvt->pvt;
1588 if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
1589 ast_log(LOG_WARNING, "Line is already in use (%s)?\n", c->name);
1592 strncpy(host, dest, sizeof(host)-1);
1594 strsep(&stringp, "/");
1595 /* If no destination extension specified, use 's' */
1596 rdest = strsep(&stringp, "/");
1600 strsep(&stringp, "@");
1601 rcontext = strsep(&stringp, "@");
1603 strsep(&stringp, "@");
1604 username = strsep(&stringp, "@");
1606 /* Really the second argument is the host, not the username */
1614 username = strsep(&stringp, ":");
1615 secret = strsep(&stringp, ":");
1618 if (strsep(&stringp, ":")) {
1620 strsep(&stringp, ":");
1621 portno = strsep(&stringp, ":");
1623 if (create_addr(&sin, NULL, NULL, NULL, hname, context)) {
1624 ast_log(LOG_WARNING, "No address associated with '%s'\n", hname);
1627 /* Keep track of the context for outgoing calls too */
1628 strncpy(c->context, context, sizeof(c->context) - 1);
1630 sin.sin_port = htons(atoi(portno));
1632 /* Now we build our request string */
1633 #define MYSNPRINTF snprintf(requeststr + strlen(requeststr), sizeof(requeststr) - strlen(requeststr),
1634 #define MYSNPRINTF2 snprintf(requeststr + strlen(requeststr), reqsize - strlen(requeststr),
1635 MYSNPRINTF "exten=%s;", rdest);
1637 MYSNPRINTF "callerid=%s;", c->callerid);
1638 if (p->sendani && c->ani)
1639 MYSNPRINTF "ani=%s;", c->ani);
1640 if (c->language && strlen(c->language))
1641 MYSNPRINTF "language=%s;", c->language);
1643 MYSNPRINTF "dnid=%s;", c->dnid);
1645 MYSNPRINTF "context=%s;", rcontext);
1647 MYSNPRINTF "username=%s;", username);
1649 if (secret[0] == '[') {
1650 /* This is an RSA key, not a normal secret */
1651 strncpy(p->outkey, secret + 1, sizeof(p->secret)-1);
1652 if (strlen(p->outkey)) {
1653 p->outkey[strlen(p->outkey) - 1] = '\0';
1656 strncpy(p->secret, secret, sizeof(p->secret)-1);
1658 MYSNPRINTF "formats=%d;", c->nativeformats);
1659 MYSNPRINTF "capability=%d;", p->capability);
1660 MYSNPRINTF "version=%d;", AST_IAX_PROTO_VERSION);
1661 MYSNPRINTF "adsicpe=%d;", c->adsicpe);
1662 /* Trim the trailing ";" */
1663 if (strlen(requeststr))
1664 requeststr[strlen(requeststr) - 1] = '\0';
1665 /* Transmit the string in a "NEW" request */
1666 if (option_verbose > 2)
1667 ast_verbose(VERBOSE_PREFIX_3 "Calling using options '%s'\n", requeststr);
1669 /* Initialize pingtime and auto-congest time */
1670 p->pingtime = p->maxtime / 2;
1671 p->initid = ast_sched_add(sched, p->maxtime * 2, auto_congest, (void *)p->callno);
1673 send_command(p, AST_FRAME_IAX,
1674 AST_IAX_COMMAND_NEW, 0, requeststr, strlen(requeststr) + 1, -1);
1675 ast_setstate(c, AST_STATE_RINGING);
1679 static int iax_hangup(struct ast_channel *c)
1681 struct chan_iax_pvt *pvt = c->pvt->pvt;
1685 callno = pvt->callno;
1686 ast_pthread_mutex_lock(&iaxsl[callno]);
1687 ast_log(LOG_DEBUG, "We're hanging up %s now...\n", c->name);
1688 alreadygone = pvt->alreadygone;
1689 /* Send the hangup unless we have had a transmission error or are already gone */
1690 if (!pvt->error && !alreadygone)
1691 send_command_final(pvt, AST_FRAME_IAX, AST_IAX_COMMAND_HANGUP, 0, NULL, 0, -1);
1692 /* Explicitly predestroy it */
1693 iax_predestroy_nolock(callno);
1694 /* If we were already gone to begin with, destroy us now */
1696 ast_log(LOG_DEBUG, "Really destroying %s now...\n", c->name);
1697 iax_destroy_nolock(callno);
1699 ast_pthread_mutex_unlock(&iaxsl[callno]);
1701 if (option_verbose > 2)
1702 ast_verbose(VERBOSE_PREFIX_3 "Hungup '%s'\n", c->name);
1706 static int iax_setoption(struct ast_channel *c, int option, void *data, int datalen)
1708 struct ast_option_header *h;
1710 h = malloc(datalen + sizeof(struct ast_option_header));
1712 h->flag = AST_OPTION_FLAG_REQUEST;
1713 h->option = htons(option);
1714 memcpy(h->data, data, datalen);
1715 res = send_command((struct chan_iax_pvt *)c->pvt->pvt, AST_FRAME_CONTROL,
1716 AST_CONTROL_OPTION, 0, (char *)h, datalen + sizeof(struct ast_option_header), -1);
1720 ast_log(LOG_WARNING, "Out of memory\n");
1723 static struct ast_frame *iax_read(struct ast_channel *c)
1725 static struct ast_frame f = { AST_FRAME_NULL, };
1726 ast_log(LOG_NOTICE, "I should never be called!\n");
1730 static int iax_start_transfer(struct ast_channel *c0, struct ast_channel *c1)
1735 struct chan_iax_pvt *p0 = c0->pvt->pvt;
1736 struct chan_iax_pvt *p1 = c1->pvt->pvt;
1737 snprintf(req0, sizeof(req0), "remip=%s;remport=%d;remcall=%d;", inet_ntoa(p1->addr.sin_addr), ntohs(p1->addr.sin_port), p1->peercallno);
1738 snprintf(req1, sizeof(req1), "remip=%s;remport=%d;remcall=%d;", inet_ntoa(p0->addr.sin_addr), ntohs(p0->addr.sin_port), p0->peercallno);
1739 res = send_command(p0, AST_FRAME_IAX, AST_IAX_COMMAND_TXREQ, 0, req0, strlen(req0) + 1, -1);
1742 res = send_command(p1, AST_FRAME_IAX, AST_IAX_COMMAND_TXREQ, 0, req1, strlen(req1) + 1, -1);
1745 p0->transferring = TRANSFER_BEGIN;
1746 p1->transferring = TRANSFER_BEGIN;
1750 static int iax_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
1752 struct ast_channel *cs[3];
1753 struct ast_channel *who;
1756 int transferstarted=0;
1757 struct ast_frame *f;
1758 struct chan_iax_pvt *p0 = c0->pvt->pvt;
1759 struct chan_iax_pvt *p1 = c1->pvt->pvt;
1761 /* Put them in native bridge mode */
1762 p0->bridgecallno = p1->callno;
1763 p1->bridgecallno = p0->callno;
1765 /* If not, try to bridge until we can execute a transfer, if we can */
1768 for (/* ever */;;) {
1769 /* Check in case we got masqueraded into */
1770 if ((c0->type != type) || (c1->type != type)) {
1771 if (option_verbose > 2)
1772 ast_verbose(VERBOSE_PREFIX_3 "Can't masquerade, we're different...\n");
1775 if (c0->nativeformats != c1->nativeformats) {
1776 ast_verbose(VERBOSE_PREFIX_3 "Operating with different codecs, can't native bridge...\n");
1779 if (!transferstarted) {
1780 /* Try the transfer */
1781 if (iax_start_transfer(c0, c1))
1782 ast_log(LOG_WARNING, "Unable to start the transfer\n");
1783 transferstarted = 1;
1786 if ((p0->transferring == TRANSFER_RELEASED) && (p1->transferring == TRANSFER_RELEASED)) {
1787 /* Call has been transferred. We're no longer involved */
1789 c0->_softhangup |= AST_SOFTHANGUP_DEV;
1790 c1->_softhangup |= AST_SOFTHANGUP_DEV;
1797 who = ast_waitfor_n(cs, 2, &to);
1808 if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
1814 if ((f->frametype == AST_FRAME_VOICE) ||
1815 (f->frametype == AST_FRAME_TEXT) ||
1816 (f->frametype == AST_FRAME_VIDEO) ||
1817 (f->frametype == AST_FRAME_IMAGE) ||
1818 (f->frametype == AST_FRAME_DTMF)) {
1819 if ((f->frametype == AST_FRAME_DTMF) &&
1820 (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
1822 if ((flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
1825 /* Take out of conference mode */
1832 if (flags & AST_BRIDGE_DTMF_CHANNEL_1) {
1842 ast_log(LOG_DEBUG, "Read from %s\n", who->name);
1844 ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
1856 /* Swap who gets priority */
1861 p0->bridgecallno = -1;
1862 p1->bridgecallno = -1;
1866 static int iax_answer(struct ast_channel *c)
1868 struct chan_iax_pvt *pvt = c->pvt->pvt;
1870 ast_log(LOG_DEBUG, "Answering\n");
1871 return send_command(pvt, AST_FRAME_CONTROL, AST_CONTROL_ANSWER, 0, NULL, 0, -1);
1874 static int iax_indicate(struct ast_channel *c, int condition)
1876 struct chan_iax_pvt *pvt = c->pvt->pvt;
1878 ast_log(LOG_DEBUG, "Indicating condition %d\n", condition);
1879 return send_command(pvt, AST_FRAME_CONTROL, condition, 0, NULL, 0, -1);
1883 static int iax_write(struct ast_channel *c, struct ast_frame *f);
1885 static int iax_getpeername(struct sockaddr_in sin, char *host, int len)
1887 struct iax_peer *peer;
1889 ast_pthread_mutex_lock(&peerl.lock);
1892 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
1893 (peer->addr.sin_port == sin.sin_port)) {
1894 strncpy(host, peer->name, len-1);
1900 ast_pthread_mutex_unlock(&peerl.lock);
1904 static struct ast_channel *ast_iax_new(struct chan_iax_pvt *i, int state, int capability)
1907 struct ast_channel *tmp;
1908 tmp = ast_channel_alloc(1);
1910 if (!iax_getpeername(i->addr, host, sizeof(host)))
1911 snprintf(host, sizeof(host), "%s:%d", inet_ntoa(i->addr.sin_addr), ntohs(i->addr.sin_port));
1912 if (strlen(i->username))
1913 snprintf(tmp->name, sizeof(tmp->name), "IAX[%s@%s]/%d", i->username, host, i->callno);
1915 snprintf(tmp->name, sizeof(tmp->name), "IAX[%s]/%d", host, i->callno);
1917 /* We can support any format by default, until we get restricted */
1918 tmp->nativeformats = capability;
1919 tmp->readformat = 0;
1920 tmp->writeformat = 0;
1922 tmp->pvt->send_digit = iax_digit;
1923 tmp->pvt->send_text = iax_sendtext;
1924 tmp->pvt->send_image = iax_sendimage;
1925 tmp->pvt->send_html = iax_sendhtml;
1926 tmp->pvt->call = iax_call;
1927 tmp->pvt->hangup = iax_hangup;
1928 tmp->pvt->answer = iax_answer;
1929 tmp->pvt->read = iax_read;
1930 tmp->pvt->write = iax_write;
1931 tmp->pvt->indicate = iax_indicate;
1932 tmp->pvt->setoption = iax_setoption;
1933 tmp->pvt->bridge = iax_bridge;
1934 if (strlen(i->callerid))
1935 tmp->callerid = strdup(i->callerid);
1937 tmp->ani = strdup(i->ani);
1938 if (strlen(i->language))
1939 strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
1940 if (strlen(i->dnid))
1941 tmp->dnid = strdup(i->dnid);
1942 if (strlen(i->accountcode))
1943 strncpy(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode)-1);
1945 tmp->amaflags = i->amaflags;
1946 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
1947 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
1948 tmp->adsicpe = i->peeradsicpe;
1949 tmp->pvt->fixup = iax_fixup;
1951 i->capability = capability;
1952 ast_setstate(tmp, state);
1953 ast_pthread_mutex_lock(&usecnt_lock);
1955 ast_pthread_mutex_unlock(&usecnt_lock);
1956 ast_update_use_count();
1957 if (state != AST_STATE_DOWN) {
1958 if (ast_pbx_start(tmp)) {
1959 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
1968 static unsigned int calc_timestamp(struct chan_iax_pvt *p, unsigned int ts)
1972 if (!p->offset.tv_sec && !p->offset.tv_usec)
1973 gettimeofday(&p->offset, NULL);
1974 /* If the timestamp is specified, just send it as is */
1977 gettimeofday(&tv, NULL);
1978 ms = (tv.tv_sec - p->offset.tv_sec) * 1000 + (tv.tv_usec - p->offset.tv_usec) / 1000;
1979 /* We never send the same timestamp twice, so fudge a little if we must */
1980 if (ms <= p->lastsent)
1981 ms = p->lastsent + 1;
1986 #ifdef BRIDGE_OPTIMIZATION
1987 static unsigned int calc_fakestamp(struct chan_iax_pvt *p1, struct chan_iax_pvt *p2, unsigned int fakets)
1990 /* Receive from p1, send to p2 */
1992 /* Setup rxcore if necessary on outgoing channel */
1993 if (!p1->rxcore.tv_sec && !p1->rxcore.tv_usec)
1994 gettimeofday(&p1->rxcore, NULL);
1996 /* Setup txcore if necessary on outgoing channel */
1997 if (!p2->offset.tv_sec && !p2->offset.tv_usec)
1998 gettimeofday(&p2->offset, NULL);
2000 /* Now, ts is the timestamp of the original packet in the orignal context.
2001 Adding rxcore to it gives us when we would want the packet to be delivered normally.
2002 Subtracting txcore of the outgoing channel gives us what we'd expect */
2004 ms = (p1->rxcore.tv_sec - p2->offset.tv_sec) * 1000 + (p1->rxcore.tv_usec - p1->offset.tv_usec) / 1000;
2006 if (fakets <= p2->lastsent)
2007 fakets = p2->lastsent + 1;
2008 p2->lastsent = fakets;
2013 static unsigned int calc_rxstamp(struct chan_iax_pvt *p)
2015 /* Returns where in "receive time" we are */
2018 /* Setup rxcore if necessary */
2019 if (!p->rxcore.tv_sec && !p->rxcore.tv_usec)
2020 gettimeofday(&p->rxcore, NULL);
2022 gettimeofday(&tv, NULL);
2023 ms = (tv.tv_sec - p->rxcore.tv_sec) * 1000 + (tv.tv_usec - p->rxcore.tv_usec) / 1000;
2027 static int iax_send(struct chan_iax_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final)
2029 /* Queue a packet for delivery on a given private structure. Use "ts" for
2030 timestamp, or calculate if ts is 0. Send immediately without retransmission
2031 or delayed, with retransmission */
2032 struct ast_iax_full_hdr *fh;
2033 struct ast_iax_mini_hdr *mh;
2034 struct ast_iax_frame *fr, fr2;
2036 unsigned int lastsent;
2037 /* Allocate an ast_iax_frame */
2041 fr = ast_iax_frame_new(DIRECTION_OUTGRESS);
2043 ast_log(LOG_WARNING, "Out of memory\n");
2047 ast_log(LOG_WARNING, "No private structure for packet (%d)?\n", fr->callno);
2049 ast_iax_frame_free(fr);
2052 /* Isolate our frame for transmission */
2053 fr->f = ast_frdup(f);
2056 ast_log(LOG_WARNING, "Out of memory\n");
2058 ast_iax_frame_free(fr);
2061 if (fr->f->offset < sizeof(struct ast_iax_full_hdr)) {
2062 ast_log(LOG_WARNING, "Packet from '%s' not friendly\n", fr->f->src);
2066 lastsent = pvt->lastsent;
2067 fr->ts = calc_timestamp(pvt, ts);
2069 ast_log(LOG_WARNING, "timestamp is 0?\n");
2071 ast_iax_frame_free(fr);
2074 fr->callno = pvt->callno;
2075 fr->transfer = transfer;
2077 if (((fr->ts & 0xFFFF0000L) != (lastsent & 0xFFFF0000L))
2078 /* High two bits of timestamp differ */ ||
2079 (fr->f->frametype != AST_FRAME_VOICE)
2080 /* or not a voice frame */ ||
2081 (fr->f->subclass != pvt->svoiceformat)
2082 /* or new voice format */ ) {
2083 /* We need a full frame */
2087 fr->seqno = pvt->oseqno++;
2088 fh = (struct ast_iax_full_hdr *)(fr->f->data - sizeof(struct ast_iax_full_hdr));
2089 fh->callno = htons(fr->callno | AST_FLAG_FULL);
2090 fh->ts = htonl(fr->ts);
2091 fh->seqno = htons(fr->seqno);
2092 fh->type = fr->f->frametype & 0xFF;
2093 fh->csub = compress_subclass(fr->f->subclass);
2095 fh->dcallno = htons(pvt->transfercallno);
2097 fh->dcallno = htons(pvt->peercallno);
2098 fr->datalen = fr->f->datalen + sizeof(struct ast_iax_full_hdr);
2101 /* Retry after 2x the ping time has passed */
2102 fr->retrytime = pvt->pingtime * 2;
2103 if (fr->retrytime < MIN_RETRY_TIME)
2104 fr->retrytime = MIN_RETRY_TIME;
2105 if (fr->retrytime > MAX_RETRY_TIME)
2106 fr->retrytime = MAX_RETRY_TIME;
2107 /* Acks' don't get retried */
2108 if ((f->frametype == AST_FRAME_IAX) && (f->subclass == AST_IAX_COMMAND_ACK))
2110 if (f->frametype == AST_FRAME_VOICE) {
2111 pvt->svoiceformat = f->subclass;
2114 res = send_packet(fr);
2117 res = iax_transmit(fr);
2119 /* Mini-frames have no sequence number */
2121 /* Mini frame will do */
2122 mh = (struct ast_iax_mini_hdr *)(fr->f->data - sizeof(struct ast_iax_mini_hdr));
2123 mh->callno = htons(fr->callno);
2124 mh->ts = htons(fr->ts & 0xFFFF);
2125 fr->datalen = fr->f->datalen + sizeof(struct ast_iax_mini_hdr);
2129 res = send_packet(fr);
2132 res = iax_transmit(fr);
2139 static int iax_show_users(int fd, int argc, char *argv[])
2141 #define FORMAT "%-15.15s %-15.15s %-15.15s %-15.15s %-5.5s\n"
2142 struct iax_user *user;
2144 return RESULT_SHOWUSAGE;
2145 ast_pthread_mutex_lock(&userl.lock);
2146 ast_cli(fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C");
2147 for(user=userl.users;user;user=user->next) {
2148 ast_cli(fd, FORMAT, user->name, user->secret, user->methods,
2149 user->contexts ? user->contexts->context : context,
2150 user->ha ? "Yes" : "No");
2152 ast_pthread_mutex_unlock(&userl.lock);
2153 return RESULT_SUCCESS;
2157 static int iax_show_peers(int fd, int argc, char *argv[])
2159 #define FORMAT2 "%-15.15s %-15.15s %s %-15.15s %-8s %-10s\n"
2160 #define FORMAT "%-15.15s %-15.15s %s %-15.15s %-8d %-10s\n"
2161 struct iax_peer *peer;
2162 char name[256] = "";
2164 return RESULT_SHOWUSAGE;
2165 ast_pthread_mutex_lock(&peerl.lock);
2166 ast_cli(fd, FORMAT2, "Name/Username", "Host", " ", "Mask", "Port", "Status");
2167 for (peer = peerl.peers;peer;peer = peer->next) {
2170 if (strlen(peer->username))
2171 snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
2173 strncpy(name, peer->name, sizeof(name) - 1);
2175 if (peer->lastms < 0)
2176 strcpy(status, "UNREACHABLE");
2177 else if (peer->lastms > peer->maxms)
2178 snprintf(status, sizeof(status), "LAGGED (%d ms)", peer->lastms);
2179 else if (peer->lastms)
2180 snprintf(status, sizeof(status), "OK (%d ms)", peer->lastms);
2182 strcpy(status, "UNKNOWN");
2184 strcpy(status, "Unmonitored");
2185 strncpy(nm, inet_ntoa(peer->mask), sizeof(nm)-1);
2186 ast_cli(fd, FORMAT, name,
2187 peer->addr.sin_addr.s_addr ? inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
2188 peer->dynamic ? "(D)" : "(S)",
2190 ntohs(peer->addr.sin_port), status);
2192 ast_pthread_mutex_unlock(&peerl.lock);
2193 return RESULT_SUCCESS;
2198 /* JDG: callback to display iax peers in manager */
2199 static int manager_iax_show_peers( struct mansession *s, struct message *m )
2201 char *a[] = { "iax", "show", "users" };
2203 ret = iax_show_peers( s->fd, 3, a );
2204 ast_cli( s->fd, "\r\n" );
2208 static char *regstate2str(int regstate)
2211 case REG_STATE_UNREGISTERED:
2212 return "Unregistered";
2213 case REG_STATE_REGSENT:
2214 return "Request Sent";
2215 case REG_STATE_AUTHSENT:
2216 return "Auth. Sent";
2217 case REG_STATE_REGISTERED:
2218 return "Registered";
2219 case REG_STATE_REJECTED:
2221 case REG_STATE_TIMEOUT:
2223 case REG_STATE_NOAUTH:
2224 return "No Authentication";
2230 static int iax_show_registry(int fd, int argc, char *argv[])
2232 #define FORMAT2 "%-20.20s %-10.10s %-20.20s %8.8s %s\n"
2233 #define FORMAT "%-20.20s %-10.10s %-20.20s %8d %s\n"
2234 struct iax_registry *reg;
2238 return RESULT_SHOWUSAGE;
2239 ast_pthread_mutex_lock(&peerl.lock);
2240 ast_cli(fd, FORMAT2, "Host", "Username", "Perceived", "Refresh", "State");
2241 for (reg = registrations;reg;reg = reg->next) {
2242 snprintf(host, sizeof(host), "%s:%d", inet_ntoa(reg->addr.sin_addr), ntohs(reg->addr.sin_port));
2243 if (reg->us.sin_addr.s_addr)
2244 snprintf(perceived, sizeof(perceived), "%s:%d", inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
2246 strcpy(perceived, "<Unregistered>");
2247 ast_cli(fd, FORMAT, host,
2248 reg->username, perceived, reg->refresh, regstate2str(reg->regstate));
2250 ast_pthread_mutex_unlock(&peerl.lock);
2251 return RESULT_SUCCESS;
2256 static int iax_show_channels(int fd, int argc, char *argv[])
2258 #define FORMAT2 "%-15.15s %-10.10s %-11.11s %-11.11s %-7.7s %-6.6s %s\n"
2259 #define FORMAT "%-15.15s %-10.10s %5.5d/%5.5d %5.5d/%5.5d %-5.5dms %-4.4dms %d\n"
2263 return RESULT_SHOWUSAGE;
2264 ast_cli(fd, FORMAT2, "Peer", "Username", "ID (Lo/Rem)", "Seq (Tx/Rx)", "Lag", "Jitter", "Format");
2265 for (x=0;x<AST_IAX_MAX_CALLS;x++) {
2266 ast_pthread_mutex_lock(&iaxsl[x]);
2268 ast_cli(fd, FORMAT, inet_ntoa(iaxs[x]->addr.sin_addr),
2269 strlen(iaxs[x]->username) ? iaxs[x]->username : "(None)",
2270 iaxs[x]->callno, iaxs[x]->peercallno,
2271 iaxs[x]->oseqno, iaxs[x]->iseqno,
2274 iaxs[x]->voiceformat);
2277 ast_pthread_mutex_unlock(&iaxsl[x]);
2279 ast_cli(fd, "%d active IAX channel(s)\n", numchans);
2280 return RESULT_SUCCESS;
2285 static int iax_do_debug(int fd, int argc, char *argv[])
2288 return RESULT_SHOWUSAGE;
2290 ast_cli(fd, "IAX Debugging Enabled\n");
2291 return RESULT_SUCCESS;
2294 static int iax_no_debug(int fd, int argc, char *argv[])
2297 return RESULT_SHOWUSAGE;
2299 ast_cli(fd, "IAX Debugging Disabled\n");
2300 return RESULT_SUCCESS;
2305 static char show_users_usage[] =
2306 "Usage: iax show users\n"
2307 " Lists all users known to the IAX (Inter-Asterisk eXchange) subsystem.\n";
2309 static char show_channels_usage[] =
2310 "Usage: iax show channels\n"
2311 " Lists all currently active IAX channels.\n";
2313 static char show_peers_usage[] =
2314 "Usage: iax show peers\n"
2315 " Lists all known IAX peers.\n";
2317 static char show_reg_usage[] =
2318 "Usage: iax show registry\n"
2319 " Lists all registration requests and status.\n";
2321 #ifdef DEBUG_SUPPORT
2323 static char debug_usage[] =
2324 "Usage: iax debug\n"
2325 " Enables dumping of IAX packets for debugging purposes\n";
2327 static char no_debug_usage[] =
2328 "Usage: iax no debug\n"
2329 " Disables dumping of IAX packets for debugging purposes\n";
2333 static struct ast_cli_entry cli_show_users =
2334 { { "iax", "show", "users", NULL }, iax_show_users, "Show defined IAX users", show_users_usage };
2335 static struct ast_cli_entry cli_show_channels =
2336 { { "iax", "show", "channels", NULL }, iax_show_channels, "Show active IAX channels", show_channels_usage };
2337 static struct ast_cli_entry cli_show_peers =
2338 { { "iax", "show", "peers", NULL }, iax_show_peers, "Show defined IAX peers", show_peers_usage };
2339 static struct ast_cli_entry cli_show_registry =
2340 { { "iax", "show", "registry", NULL }, iax_show_registry, "Show IAX registration status", show_reg_usage };
2341 static struct ast_cli_entry cli_debug =
2342 { { "iax", "debug", NULL }, iax_do_debug, "Enable IAX debugging", debug_usage };
2343 static struct ast_cli_entry cli_no_debug =
2344 { { "iax", "no", "debug", NULL }, iax_no_debug, "Disable IAX debugging", no_debug_usage };
2346 static int iax_write(struct ast_channel *c, struct ast_frame *f)
2348 struct chan_iax_pvt *i = c->pvt->pvt;
2351 /* If there's an outstanding error, return failure now */
2353 ast_log(LOG_DEBUG, "Write error: %s\n", strerror(errno));
2356 /* If it's already gone, just return */
2359 /* Don't waste bandwidth sending null frames */
2360 if (f->frametype == AST_FRAME_NULL)
2362 /* If we're quelching voice, don't bother sending it */
2363 if ((f->frametype == AST_FRAME_VOICE) && i->quelch)
2365 /* Simple, just queue for transmission */
2366 return iax_send(i, f, 0, -1, 0, 0, 0);
2369 static int __send_command(struct chan_iax_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno,
2370 int now, int transfer, int final)
2374 f.subclass = command;
2375 f.datalen = datalen;
2379 f.src = __FUNCTION__;
2381 return iax_send(i, &f, ts, seqno, now, transfer, final);
2384 static int send_command(struct chan_iax_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2386 return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 0);
2389 #ifdef BRIDGE_OPTIMIZATION
2390 static int forward_command(struct chan_iax_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2392 return __send_command(iaxs[i->bridgecallno], type, command, ts, data, datalen, seqno, 0, 0, 0);
2396 static int send_command_final(struct chan_iax_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2398 /* It is assumed that the callno has already been locked */
2399 iax_predestroy_nolock(i->callno);
2400 return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 1);
2403 static int send_command_immediate(struct chan_iax_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2405 return __send_command(i, type, command, ts, data, datalen, seqno, 1, 0, 0);
2408 static int send_command_transfer(struct chan_iax_pvt *i, char type, int command, unsigned int ts, char *data, int datalen)
2410 return __send_command(i, type, command, ts, data, datalen, 0, 0, 1, 0);
2413 static int apply_context(struct iax_context *con, char *context)
2416 if (!strcmp(con->context, context))
2423 static int iax_getformats(int callno, char *orequest)
2428 strncpy(request, orequest, sizeof(request)-1);
2430 var = strsep(&stringp, ";");
2432 value = strchr(var, '=');
2436 if (!strcmp(var, "formats")) {
2437 iaxs[callno]->peerformat = atoi(value);
2439 ast_log(LOG_WARNING, "Unknown variable '%s' with value '%s'\n", var, value);
2441 var = strsep(&stringp, ";");
2447 static int check_access(int callno, struct sockaddr_in *sin, char *orequest, int requestl)
2449 /* Start pessimistic */
2453 struct iax_user *user;
2455 int gotcapability=0;
2457 strncpy(request, orequest, sizeof(request)-1);
2461 var = strsep(&stringp, ";");
2463 value = strchr(var, '=');
2467 if (!strcmp(var, "exten"))
2468 strncpy(iaxs[callno]->exten, value, sizeof(iaxs[callno]->exten)-1);
2469 else if (!strcmp(var, "callerid"))
2470 strncpy(iaxs[callno]->callerid, value, sizeof(iaxs[callno]->callerid)-1);
2471 else if (!strcmp(var, "ani"))
2472 strncpy(iaxs[callno]->ani, value, sizeof(iaxs[callno]->ani) - 1);
2473 else if (!strcmp(var, "dnid"))
2474 strncpy(iaxs[callno]->dnid, value, sizeof(iaxs[callno]->dnid)-1);
2475 else if (!strcmp(var, "context"))
2476 strncpy(iaxs[callno]->context, value, sizeof(iaxs[callno]->context)-1);
2477 else if (!strcmp(var, "language"))
2478 strncpy(iaxs[callno]->language, value, sizeof(iaxs[callno]->language)-1);
2479 else if (!strcmp(var, "username"))
2480 strncpy(iaxs[callno]->username, value, sizeof(iaxs[callno]->username)-1);
2481 else if (!strcmp(var, "formats"))
2482 iaxs[callno]->peerformat = atoi(value);
2483 else if (!strcmp(var, "adsicpe"))
2484 iaxs[callno]->peeradsicpe = atoi(value);
2485 else if (!strcmp(var, "capability")) {
2487 iaxs[callno]->peercapability = atoi(value);
2488 } else if (!strcmp(var, "version"))
2489 version = atoi(value);
2491 ast_log(LOG_WARNING, "Unknown variable '%s' with value '%s'\n", var, value);
2493 var = strsep(&stringp, ";");
2496 iaxs[callno]->peercapability = iaxs[callno]->peerformat;
2497 if (version > AST_IAX_PROTO_VERSION) {
2498 ast_log(LOG_WARNING, "Peer '%s' has too new a protocol version (%d) for me\n",
2499 inet_ntoa(sin->sin_addr), version);
2502 ast_pthread_mutex_lock(&userl.lock);
2503 /* Search the userlist for a compatible entry, and fill in the rest */
2506 if ((!strlen(iaxs[callno]->username) || /* No username specified */
2507 !strcmp(iaxs[callno]->username, user->name)) /* Or this username specified */
2508 && ast_apply_ha(user->ha, sin) /* Access is permitted from this IP */
2509 && (!strlen(iaxs[callno]->context) || /* No context specified */
2510 apply_context(user->contexts, iaxs[callno]->context))) { /* Context is permitted */
2511 /* We found our match (use the first) */
2513 /* Store the requested username if not specified */
2514 if (!strlen(iaxs[callno]->username))
2515 strncpy(iaxs[callno]->username, user->name, sizeof(iaxs[callno]->username)-1);
2516 /* And use the default context */
2517 if (!strlen(iaxs[callno]->context)) {
2519 strncpy(iaxs[callno]->context, user->contexts->context, sizeof(iaxs[callno]->context)-1);
2521 strncpy(iaxs[callno]->context, context, sizeof(iaxs[callno]->context)-1);
2523 /* Copy the secret */
2524 strncpy(iaxs[callno]->secret, user->secret, sizeof(iaxs[callno]->secret)-1);
2525 /* And any input keys */
2526 strncpy(iaxs[callno]->inkeys, user->inkeys, sizeof(iaxs[callno]->inkeys));
2527 /* And the permitted authentication methods */
2528 strncpy(iaxs[callno]->methods, user->methods, sizeof(iaxs[callno]->methods)-1);
2529 /* If they have callerid, override the given caller id. Always store the ANI */
2530 if (strlen(iaxs[callno]->callerid)) {
2531 if (user->hascallerid)
2532 strncpy(iaxs[callno]->callerid, user->callerid, sizeof(iaxs[callno]->callerid)-1);
2533 strncpy(iaxs[callno]->ani, user->callerid, sizeof(iaxs[callno]->ani)-1);
2535 if (strlen(user->accountcode))
2536 strncpy(iaxs[callno]->accountcode, user->accountcode, sizeof(iaxs[callno]->accountcode)-1);
2538 iaxs[callno]->amaflags = user->amaflags;
2544 ast_pthread_mutex_unlock(&userl.lock);
2548 static int raw_hangup(struct sockaddr_in *sin, short src, short dst)
2550 struct ast_iax_full_hdr fh;
2551 fh.callno = htons(src | AST_FLAG_FULL);
2552 fh.dcallno = htons(dst);
2555 fh.type = AST_FRAME_IAX;
2556 fh.csub = compress_subclass(AST_IAX_COMMAND_INVAL);
2560 ast_log(LOG_DEBUG, "Raw Hangup %s:%d, src=%d, dst=%d\n",
2561 inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), src, dst);
2562 return sendto(netsocket, &fh, sizeof(fh), 0, (struct sockaddr *)sin, sizeof(*sin));
2565 static int authenticate_request(struct chan_iax_pvt *p)
2567 char requeststr[256] = "";
2568 MYSNPRINTF "methods=%s;", p->methods);
2569 if (strstr(p->methods, "md5") || strstr(p->methods, "rsa")) {
2570 /* Build the challenge */
2571 snprintf(p->challenge, sizeof(p->challenge), "%d", rand());
2572 MYSNPRINTF "challenge=%s;", p->challenge);
2574 MYSNPRINTF "username=%s;", p->username);
2575 if (strlen(requeststr))
2576 requeststr[strlen(requeststr) - 1] = '\0';
2577 return send_command(p, AST_FRAME_IAX, AST_IAX_COMMAND_AUTHREQ, 0, requeststr, strlen(requeststr) + 1, -1);
2580 static int authenticate_verify(struct chan_iax_pvt *p, char *orequest)
2582 char requeststr[256] = "";
2583 char *var, *value, request[256];
2584 char md5secret[256] = "";
2585 char secret[256] = "";
2586 char rsasecret[256] = "";
2591 if (!(p->state & IAX_STATE_AUTHENTICATED))
2593 strncpy(request, orequest, sizeof(request)-1);
2595 var = strsep(&stringp, ";");
2597 value = strchr(var, '=');
2601 if (!strcmp(var, "secret"))
2602 strncpy(secret, value, sizeof(secret)-1);
2603 else if (!strcmp(var, "md5secret"))
2604 strncpy(md5secret, value, sizeof(md5secret)-1);
2605 else if (!strcmp(var, "rsasecret"))
2606 strncpy(rsasecret, value, sizeof(rsasecret)-1);
2608 ast_log(LOG_WARNING, "Unknown variable '%s' with value '%s'\n", var, value);
2610 var = strsep(&stringp, ";");
2612 if (strstr(p->methods, "rsa") && strlen(rsasecret) && strlen(p->inkeys)) {
2613 struct ast_key *key;
2617 strncpy(tmpkey, p->inkeys, sizeof(tmpkey));
2619 keyn = strsep(&stringp, ":");
2621 key = ast_key_get(keyn, AST_KEY_PUBLIC);
2622 if (key && !ast_check_signature(key, p->challenge, rsasecret)) {
2626 ast_log(LOG_WARNING, "requested inkey '%s' for RSA authentication does not exist\n", keyn);
2627 keyn = strsep(&stringp, ":");
2629 } else if (strstr(p->methods, "md5")) {
2630 struct MD5Context md5;
2631 unsigned char digest[16];
2633 MD5Update(&md5, p->challenge, strlen(p->challenge));
2634 MD5Update(&md5, p->secret, strlen(p->secret));
2635 MD5Final(digest, &md5);
2636 /* If they support md5, authenticate with it. */
2638 MYSNPRINTF "%2.2x", digest[x]);
2639 if (!strcasecmp(requeststr, md5secret))
2641 } else if (strstr(p->methods, "plaintext")) {
2642 if (!strcmp(secret, p->secret))
2648 static int register_verify(int callno, struct sockaddr_in *sin, char *orequest)
2651 char requeststr[256] = "";
2652 char peer[256] = "";
2653 char md5secret[256] = "";
2654 char rsasecret[256] = "";
2655 char secret[256] = "";
2657 struct ast_key *key;
2665 iaxs[callno]->state &= ~IAX_STATE_AUTHENTICATED;
2666 strcpy(iaxs[callno]->peer, "");
2669 strncpy(request, orequest, sizeof(request)-1);
2671 var = strsep(&stringp, ";");
2673 value = strchr(var, '=');
2677 if (!strcmp(var, "peer"))
2678 strncpy(peer, value, sizeof(peer)-1);
2679 else if (!strcmp(var, "md5secret"))
2680 strncpy(md5secret, value, sizeof(md5secret)-1);
2681 else if (!strcmp(var, "rsasecret"))
2682 strncpy(rsasecret, value, sizeof(rsasecret)-1);
2683 else if (!strcmp(var, "secret"))
2684 strncpy(secret, value, sizeof(secret)-1);
2685 else if (!strcmp(var, "refresh"))
2686 expire = atoi(value);
2688 ast_log(LOG_WARNING, "Unknown variable '%s' with value '%s'\n", var, value);
2690 var = strsep(&stringp, ";");
2693 if (!strlen(peer)) {
2694 ast_log(LOG_NOTICE, "Empty registration from %s\n", inet_ntoa(sin->sin_addr));
2698 for (p = peerl.peers; p ; p = p->next)
2699 if (!strcasecmp(p->name, peer))
2703 ast_log(LOG_NOTICE, "No registration for peer '%s' (from %s)\n", peer, inet_ntoa(sin->sin_addr));
2708 ast_log(LOG_NOTICE, "Peer '%s' is not dynamic (from %s)\n", peer, inet_ntoa(sin->sin_addr));
2712 if (!ast_apply_ha(p->ha, sin)) {
2713 ast_log(LOG_NOTICE, "Host %s denied access to register peer '%s'\n", inet_ntoa(sin->sin_addr), p->name);
2716 strncpy(iaxs[callno]->secret, p->secret, sizeof(iaxs[callno]->secret)-1);
2717 strncpy(iaxs[callno]->inkeys, p->inkeys, sizeof(iaxs[callno]->inkeys)-1);
2718 /* Check secret against what we have on file */
2719 if (strlen(rsasecret) && strstr(p->methods, "rsa") && strlen(p->challenge)) {
2720 if (strlen(p->inkeys)) {
2723 strncpy(tmpkeys, p->inkeys, sizeof(tmpkeys));
2725 keyn = strsep(&stringp, ":");
2727 key = ast_key_get(keyn, AST_KEY_PUBLIC);
2728 if (key && !ast_check_signature(key, p->challenge, rsasecret)) {
2729 iaxs[callno]->state |= IAX_STATE_AUTHENTICATED;
2732 ast_log(LOG_WARNING, "requested inkey '%s' does not exist\n", keyn);
2733 keyn = strsep(&stringp, ":");
2736 ast_log(LOG_NOTICE, "Host %s failed RSA authentication with inkeys '%s'\n", peer, p->inkeys);
2740 ast_log(LOG_NOTICE, "Host '%s' trying to do RSA authentication, but we have no inkeys\n", peer);
2743 } else if (strlen(secret) && strstr(p->methods, "plaintext")) {
2744 /* They've provided a plain text password and we support that */
2745 if (strcmp(secret, p->secret)) {
2746 ast_log(LOG_NOTICE, "Host %s did not provide proper plaintext password for '%s'\n", inet_ntoa(sin->sin_addr), p->name);
2749 iaxs[callno]->state |= IAX_STATE_AUTHENTICATED;
2750 } else if (strlen(md5secret) && strstr(p->methods, "md5") && strlen(p->challenge)) {
2751 struct MD5Context md5;
2752 unsigned char digest[16];
2754 MD5Update(&md5, p->challenge, strlen(p->challenge));
2755 MD5Update(&md5, p->secret, strlen(p->secret));
2756 MD5Final(digest, &md5);
2758 MYSNPRINTF "%2.2x", digest[x]);
2759 if (strcasecmp(requeststr, md5secret)) {
2760 ast_log(LOG_NOTICE, "Host %s failed MD5 authentication for '%s' (%s != %s)\n", inet_ntoa(sin->sin_addr), p->name, requeststr, md5secret);
2763 iaxs[callno]->state |= IAX_STATE_AUTHENTICATED;
2764 } else if (strlen(md5secret) || strlen(secret)) {
2765 ast_log(LOG_NOTICE, "Inappropriate authentication received\n");
2768 strncpy(iaxs[callno]->peer, peer, sizeof(iaxs[callno]->peer)-1);
2769 /* Choose lowest expirey number */
2770 if (expire && (expire < iaxs[callno]->expirey))
2771 iaxs[callno]->expirey = expire;
2776 static int authenticate(char *challenge, char *secret, char *keyn, char *methods, char *requeststr, int reqsize, struct sockaddr_in *sin)
2780 if (keyn && strlen(keyn)) {
2781 if (!strstr(methods, "rsa")) {
2782 if (!secret || !strlen(secret))
2783 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));
2784 } else if (!strlen(challenge)) {
2785 ast_log(LOG_NOTICE, "No challenge provided for RSA authentication to %s\n", inet_ntoa(sin->sin_addr));
2788 struct ast_key *key;
2789 key = ast_key_get(keyn, AST_KEY_PRIVATE);
2791 ast_log(LOG_NOTICE, "Unable to find private key '%s'\n", keyn);
2793 if (ast_sign(key, challenge, sig)) {
2794 ast_log(LOG_NOTICE, "Unable to sign challenge withy key\n");
2797 MYSNPRINTF2 "rsasecret=%s;", sig);
2804 if (res && secret && strlen(secret)) {
2805 if (strstr(methods, "md5") && strlen(challenge)) {
2806 struct MD5Context md5;
2807 unsigned char digest[16];
2809 MD5Update(&md5, challenge, strlen(challenge));
2810 MD5Update(&md5, secret, strlen(secret));
2811 MD5Final(digest, &md5);
2812 /* If they support md5, authenticate with it. */
2813 MYSNPRINTF2 "md5secret=");
2815 MYSNPRINTF2 "%2.2x", digest[x]);
2818 } else if (strstr(methods, "plaintext")) {
2819 MYSNPRINTF2 "secret=%s;", secret);
2822 ast_log(LOG_NOTICE, "No way to send secret to peer '%s' (their methods: %s)\n", inet_ntoa(sin->sin_addr), methods);
2827 static int authenticate_reply(struct chan_iax_pvt *p, struct sockaddr_in *sin, char *orequest, char *override, char *okey)
2829 struct iax_peer *peer;
2830 /* Start pessimistic */
2833 char methods[80] = "";
2834 char requeststr[256] = "";
2838 strncpy(request, orequest, sizeof(request)-1);
2840 var = strsep(&stringp, ";");
2842 value = strchr(var, '=');
2846 if (!strcmp(var, "username"))
2847 strncpy(p->username, value, sizeof(p->username)-1);
2848 else if (!strcmp(var, "challenge"))
2849 strncpy(p->challenge, value, sizeof(p->challenge)-1);
2850 else if (!strcmp(var, "methods"))
2851 strncpy(methods, value, sizeof(methods)-1);
2853 ast_log(LOG_WARNING, "Unknown variable '%s' with value '%s'\n", var, value);
2855 var = strsep(&stringp, ";");
2858 /* Check for override RSA authentication first */
2859 if ((override && strlen(override)) || (okey && strlen(okey))) {
2860 /* Normal password authentication */
2861 res = authenticate(p->challenge, override, okey, methods, requeststr, sizeof(requeststr), sin);
2863 ast_pthread_mutex_lock(&peerl.lock);
2866 if ((!strlen(p->peer) || !strcmp(p->peer, peer->name))
2867 /* No peer specified at our end, or this is the peer */
2868 && (!strlen(peer->username) || (!strcmp(peer->username, p->username)))
2869 /* No username specified in peer rule, or this is the right username */
2870 && (!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)))
2871 /* No specified host, or this is our host */
2873 res = authenticate(p->challenge, peer->secret, peer->outkey, methods, requeststr, sizeof(requeststr), sin);
2879 ast_pthread_mutex_unlock(&peerl.lock);
2881 if (strlen(requeststr))
2882 requeststr[strlen(requeststr)-1] = '\0';
2884 res = send_command(p, AST_FRAME_IAX, AST_IAX_COMMAND_AUTHREP, 0, requeststr, strlen(requeststr) + 1, -1);
2888 static int iax_do_register(struct iax_registry *reg);
2890 static int iax_do_register_s(void *data)
2892 struct iax_registry *reg = data;
2894 iax_do_register(reg);
2898 static int try_transfer(struct chan_iax_pvt *pvt, char *orequest)
2902 char newip[256] = "";
2903 char request[256] = "";
2906 struct sockaddr_in new;
2912 strncpy(request, orequest, sizeof(request)-1);
2914 var = strsep(&stringp, ";");
2916 value = strchr(var, '=');
2920 if (!strcmp(var, "remip"))
2921 strncpy(newip, value, sizeof(newip)-1);
2922 else if (!strcmp(var, "remport"))
2923 newport = atoi(value);
2924 else if (!strcmp(var, "remcall"))
2925 newcall = atoi(value);
2927 ast_log(LOG_WARNING, "Unknown variable '%s' with value '%s'\n", var, value);
2929 var = strsep(&stringp, ";");
2931 if (!newcall || !inet_aton(newip, &new.sin_addr) || !newport) {
2932 ast_log(LOG_WARNING, "Invalid transfer request\n");
2935 pvt->transfercallno = newcall;
2936 inet_aton(newip, &pvt->transfer.sin_addr);
2937 pvt->transfer.sin_port = htons(newport);
2938 pvt->transfer.sin_family = AF_INET;
2939 pvt->transferring = TRANSFER_BEGIN;
2940 send_command_transfer(pvt, AST_FRAME_IAX, AST_IAX_COMMAND_TXCNT, 0, NULL, 0);
2944 static int complete_dpreply(struct chan_iax_pvt *pvt, char *orequest)
2947 char request[256] = "";
2948 char exten[256] = "";
2949 int status = CACHE_FLAG_UNKNOWN;
2950 int expirey = iaxdefaultdpcache;
2953 struct iax_dpcache *dp, *prev;
2956 strncpy(request, orequest, sizeof(request)-1);
2958 var = strsep(&stringp, ";");
2960 value = strchr(var, '=');
2964 if (!strcmp(var, "number"))
2965 strncpy(exten, value, sizeof(exten)-1);
2966 else if (!strcmp(var, "status")) {
2967 if (!strcasecmp(value, "exists"))
2968 status = CACHE_FLAG_EXISTS;
2969 else if (!strcasecmp(value, "nonexistant"))
2970 status = CACHE_FLAG_NONEXISTANT;
2971 else if (!strcasecmp(value, "canexist"))
2972 status = CACHE_FLAG_CANEXIST;
2974 ast_log(LOG_WARNING, "Unknown status '%s'\n", value);
2975 } else if (!strcmp(var, "expirey"))
2976 expirey = atoi(value);
2977 else if (!strcmp(var, "ignorepat")) {
2978 /* Don' really do much with it */
2979 } else if (!strcmp(var, "matchmore")) {
2980 matchmore = CACHE_FLAG_MATCHMORE;
2982 ast_log(LOG_WARNING, "Unknown variable '%s' with value '%s'\n", var, value);
2984 var = strsep(&stringp, ";");
2986 ast_pthread_mutex_lock(&dpcache_lock);
2988 dp = pvt->dpentries;
2990 if (!strcmp(dp->exten, exten)) {
2993 prev->peer = dp->peer;
2995 pvt->dpentries = dp->peer;
2998 dp->expirey.tv_sec = dp->orig.tv_sec + expirey;
2999 if (dp->flags & CACHE_FLAG_PENDING) {
3000 dp->flags &= ~CACHE_FLAG_PENDING;
3001 dp->flags |= status;
3002 dp->flags |= CACHE_FLAG_MATCHMORE;
3004 /* Wake up waiters */
3005 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
3006 if (dp->waiters[x] > -1)
3007 write(dp->waiters[x], "asdf", 4);
3012 ast_pthread_mutex_unlock(&dpcache_lock);
3016 static int complete_transfer(int callno, char *orequest)
3018 int peercallno = -1;
3019 char request[256] = "";
3021 struct chan_iax_pvt *pvt = iaxs[callno];
3022 struct ast_iax_frame *cur;
3027 strncpy(request, orequest, sizeof(request)-1);
3029 var = strsep(&stringp, ";");
3031 value = strchr(var, '=');
3035 if (!strcmp(var, "peercallno"))
3036 peercallno = atoi(value);
3038 ast_log(LOG_WARNING, "Unknown variable '%s' with value '%s'\n", var, value);
3040 var = strsep(&stringp, ";");
3042 if (peercallno < 0) {
3043 ast_log(LOG_WARNING, "Invalid transfer request\n");
3046 memcpy(&pvt->addr, &pvt->transfer, sizeof(pvt->addr));
3047 memset(&pvt->transfer, 0, sizeof(pvt->transfer));
3048 /* Reset sequence numbers */
3051 pvt->peercallno = peercallno;
3052 pvt->transferring = TRANSFER_NONE;
3053 pvt->svoiceformat = -1;
3054 pvt->voiceformat = 0;
3055 pvt->transfercallno = -1;
3056 memset(&pvt->rxcore, 0, sizeof(pvt->rxcore));
3057 memset(&pvt->offset, 0, sizeof(pvt->offset));
3058 memset(&pvt->history, 0, sizeof(pvt->history));
3059 pvt->jitterbuffer = 0;
3061 pvt->historicjitter = 0;
3065 pvt->pingtime = DEFAULT_RETRY_TIME;
3066 ast_pthread_mutex_lock(&iaxq.lock);
3067 for (cur = iaxq.head; cur ; cur = cur->next) {
3068 /* We must cancel any packets that would have been transmitted
3069 because now we're talking to someone new. It's okay, they
3070 were transmitted to someone that didn't care anyway. */
3071 if (callno == cur->callno)
3074 ast_pthread_mutex_unlock(&iaxq.lock);
3078 static int iax_ack_registry(char *orequest, struct sockaddr_in *sin, int callno)
3080 struct iax_registry *reg;
3081 /* Start pessimistic */
3082 char request[256] = "";
3083 char peer[256] = "";
3086 char ourip[256] = "<Unspecified>";
3087 struct sockaddr_in oldus;
3094 strncpy(request, orequest, sizeof(request)-1);
3096 var = strsep(&stringp, ";");
3098 value = strchr(var, '=');
3102 if (!strcmp(var, "yourip"))
3103 strncpy(ourip, value, sizeof(ourip)-1);
3104 else if (!strcmp(var, "peer"))
3105 strncpy(peer, value, sizeof(peer)-1);
3106 else if (!strcmp(var, "yourport"))
3107 ourport = atoi(value);
3108 else if (!strcmp(var, "refresh"))
3109 refresh = atoi(value);
3110 else if (!strcmp(var, "callerid")) {
3111 /* We don't really care about suggested Caller*ID, that's more for phones */
3113 ast_log(LOG_WARNING, "Unknown variable '%s' with value '%s'\n", var, value);
3115 var = strsep(&stringp, ";");
3117 reg = iaxs[callno]->reg;
3118 memcpy(&oldus, ®->us, sizeof(oldus));
3119 if (memcmp(®->addr, sin, sizeof(®->addr))) {
3120 ast_log(LOG_WARNING, "Received unsolicited registry ack from '%s'\n", inet_ntoa(sin->sin_addr));
3123 if (!inet_aton(ourip, ®->us.sin_addr)) {
3124 ast_log(LOG_WARNING, "Registry ack from '%s' contains invalid IP '%s'\n", inet_ntoa(sin->sin_addr), ourip);
3127 reg->us.sin_port = htons(ourport);
3128 if (refresh && (reg->refresh < refresh)) {
3129 /* Refresh faster if necessary */
3130 reg->refresh = refresh;
3131 if (reg->expire > -1)
3132 ast_sched_del(sched, reg->expire);
3133 reg->expire = ast_sched_add(sched, (5 * reg->refresh / 6) * 1000, iax_do_register_s, reg);
3135 if (memcmp(&oldus, ®->us, sizeof(oldus)) && (option_verbose > 2)) {
3136 snprintf(ourip, sizeof(ourip), "%s:%d", inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
3137 ast_verbose(VERBOSE_PREFIX_3 "Registered to '%s', who sees us as %s\n", inet_ntoa(sin->sin_addr), ourip);
3139 reg->regstate = REG_STATE_REGISTERED;
3141 ast_log(LOG_WARNING, "Registry acknowledge on unknown registery '%s'\n", peer);
3145 static int iax_register(char *value, int lineno)
3147 struct iax_registry *reg;
3149 char *username, *hostname, *secret;
3156 strncpy(copy, value, sizeof(copy)-1);
3158 username = strsep(&stringp, "@");
3159 hostname = strsep(&stringp, "@");
3161 ast_log(LOG_WARNING, "Format for registration is user[:secret]@host[:port] at line %d", lineno);
3165 username = strsep(&stringp, ":");
3166 secret = strsep(&stringp, ":");
3168 hostname = strsep(&stringp, ":");
3169 porta = strsep(&stringp, ":");
3171 if (porta && !atoi(porta)) {
3172 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
3175 hp = gethostbyname(hostname);
3177 ast_log(LOG_WARNING, "Host '%s' not found at line %d\n", hostname, lineno);
3180 reg = malloc(sizeof(struct iax_registry));
3182 memset(reg, 0, sizeof(struct iax_registry));
3183 strncpy(reg->username, username, sizeof(reg->username)-1);
3185 strncpy(reg->secret, secret, sizeof(reg->secret)-1);
3187 reg->refresh = AST_DEFAULT_REG_EXPIRE;
3188 reg->addr.sin_family = AF_INET;
3189 memcpy(®->addr.sin_addr, hp->h_addr, sizeof(®->addr.sin_addr));
3190 reg->addr.sin_port = porta ? htons(atoi(porta)) : htons(AST_DEFAULT_IAX_PORTNO);
3191 reg->next = registrations;
3193 registrations = reg;
3195 ast_log(LOG_ERROR, "Out of memory\n");
3201 static int expire_registry(void *data)
3203 struct iax_peer *p = data;
3204 /* Reset the address */
3205 memset(&p->addr, 0, sizeof(p->addr));
3206 /* Reset expire notice */
3208 /* Reset expirey value */
3209 p->expirey = expirey;
3211 iax_regfunk(p->name, 0);
3216 static int iax_poke_peer(struct iax_peer *peer);
3219 static int update_registry(char *name, struct sockaddr_in *sin, int callno)
3221 /* Called from IAX thread only, with proper iaxsl lock */
3222 char requeststr[256] = "";
3224 for (p = peerl.peers;p;p = p->next) {
3225 if (!strcasecmp(name, p->name)) {
3226 if (memcmp(&p->addr, sin, sizeof(p->addr))) {
3228 iax_regfunk(p->name, 1);
3229 if (option_verbose > 2)
3230 ast_verbose(VERBOSE_PREFIX_3 "Registered '%s' (%s) at %s:%d\n", p->name,
3231 iaxs[callno]->state & IAX_STATE_AUTHENTICATED ? "AUTHENTICATED" : "UNAUTHENTICATED", inet_ntoa(sin->sin_addr), htons(sin->sin_port));
3234 /* Update the host */
3235 memcpy(&p->addr, sin, sizeof(p->addr));
3236 /* Setup the expirey */
3238 ast_sched_del(sched, p->expire);
3239 p->expire = ast_sched_add(sched, p->expirey * 1000, expire_registry, (void *)p);
3240 MYSNPRINTF "peer=%s;yourip=%s;yourport=%d;refresh=%d;",
3241 p->name, inet_ntoa(p->addr.sin_addr), ntohs(p->addr.sin_port), p->expirey);
3243 MYSNPRINTF "callerid=%s;", p->callerid);
3244 requeststr[strlen(requeststr)-1] = '\0';
3245 return send_command_final(iaxs[callno], AST_FRAME_IAX, AST_IAX_COMMAND_REGACK, 0, requeststr, strlen(requeststr) + 1, -1);;
3248 ast_log(LOG_WARNING, "No such peer '%s'\n", name);
3252 static int registry_authrequest(char *name, int callno)
3254 char requeststr[256] = "";
3256 for (p = peerl.peers;p;p = p->next) {
3257 if (!strcasecmp(name, p->name)) {
3258 MYSNPRINTF "methods=%s;", p->methods);
3259 if (strstr(p->methods, "md5") || strstr(p->methods, "rsa")) {
3260 /* Build the challenge */
3261 snprintf(p->challenge, sizeof(p->challenge), "%d", rand());
3262 MYSNPRINTF "challenge=%s;", p->challenge);
3264 MYSNPRINTF "peer=%s;", name);
3265 requeststr[strlen(requeststr)-1] = '\0';
3266 return send_command(iaxs[callno], AST_FRAME_IAX, AST_IAX_COMMAND_REGAUTH, 0, requeststr, strlen(requeststr) + 1, -1);;
3269 ast_log(LOG_WARNING, "No such peer '%s'\n", name);
3273 static int registry_rerequest(char *orequest, int callno, struct sockaddr_in *sin)
3275 struct iax_registry *reg;
3276 /* Start pessimistic */
3277 char request[256] = "";
3278 char requeststr[256] = "";
3279 char peer[256] = "";
3280 char methods[256] = "";
3281 char challenge[256] = "";
3289 strncpy(request, orequest, sizeof(request)-1);
3291 var = strsep(&stringp, ";");
3293 value = strchr(var, '=');
3297 if (!strcmp(var, "methods"))
3298 strncpy(methods, value, sizeof(methods)-1);
3299 else if (!strcmp(var, "peer"))
3300 strncpy(peer, value, sizeof(peer)-1);
3301 else if (!strcmp(var, "challenge"))
3302 strncpy(challenge, value, sizeof(challenge)-1);
3304 ast_log(LOG_WARNING, "Unknown variable '%s' with value '%s'\n", var, value);
3306 var = strsep(&stringp, ";");
3308 reg = iaxs[callno]->reg;
3309 if (memcmp(®->addr, sin, sizeof(®->addr))) {
3310 ast_log(LOG_WARNING, "Received unsolicited registry authenticate request from '%s'\n", inet_ntoa(sin->sin_addr));
3313 if (!strlen(reg->secret)) {
3314 ast_log(LOG_NOTICE, "No secret associated with peer '%s'\n", reg->username);
3315 reg->regstate = REG_STATE_NOAUTH;
3318 MYSNPRINTF "peer=%s;refresh=%d;", reg->username, reg->refresh);
3319 if (reg->secret[0] == '[') {
3321 strncpy(tmpkey, reg->secret + 1, sizeof(tmpkey) - 1);
3322 tmpkey[strlen(tmpkey) - 1] = '\0';
3323 res = authenticate(challenge, NULL, tmpkey, methods, requeststr, sizeof(requeststr), sin);
3325 res = authenticate(challenge, reg->secret, NULL, methods, requeststr, sizeof(requeststr), sin);
3327 reg->regstate = REG_STATE_AUTHSENT;
3328 return send_command(iaxs[callno], AST_FRAME_IAX, AST_IAX_COMMAND_REGREQ, 0, requeststr, strlen(requeststr) + 1, -1);
3331 ast_log(LOG_WARNING, "Registry acknowledge on unknown registery '%s'\n", peer);
3335 static int stop_stuff(int callno)
3337 if (iaxs[callno]->lagid > -1)
3338 ast_sched_del(sched, iaxs[callno]->lagid);
3339 iaxs[callno]->lagid = -1;
3340 if (iaxs[callno]->pingid > -1)
3341 ast_sched_del(sched, iaxs[callno]->pingid);
3342 iaxs[callno]->pingid = -1;
3343 if (iaxs[callno]->autoid > -1)
3344 ast_sched_del(sched, iaxs[callno]->autoid);
3345 iaxs[callno]->autoid = -1;
3346 if (iaxs[callno]->initid > -1)
3347 ast_sched_del(sched, iaxs[callno]->initid);
3348 iaxs[callno]->initid = -1;
3352 static int auto_hangup(void *nothing)
3354 /* Called from IAX thread only, without iaxs lock */
3355 int callno = (int)(long)(nothing);
3356 ast_pthread_mutex_lock(&iaxsl[callno]);
3358 iaxs[callno]->autoid = -1;
3359 send_command_final(iaxs[callno], AST_FRAME_IAX, AST_IAX_COMMAND_HANGUP, 0, "Timeout", strlen("Timeout") + 1, -1);
3361 ast_pthread_mutex_unlock(&iaxsl[callno]);
3365 static void iax_dprequest(struct iax_dpcache *dp, int callno)
3367 /* Auto-hangup with 30 seconds of inactivity */
3368 if (iaxs[callno]->autoid > -1)
3369 ast_sched_del(sched, iaxs[callno]->autoid);
3370 iaxs[callno]->autoid = ast_sched_add(sched, 30000, auto_hangup, (void *)callno);
3371 send_command(iaxs[callno], AST_FRAME_IAX, AST_IAX_COMMAND_DPREQ, 0, dp->exten, strlen(dp->exten) + 1, -1);
3372 dp->flags |= CACHE_FLAG_TRANSMITTED;
3375 static int iax_vnak(int callno)
3377 return send_command_immediate(iaxs[callno], AST_FRAME_IAX, AST_IAX_COMMAND_VNAK, 0, NULL, 0, iaxs[callno]->iseqno);
3380 static void vnak_retransmit(int callno, int last)
3382 struct ast_iax_frame *f;
3383 ast_pthread_mutex_lock(&iaxq.lock);
3386 /* Send a copy immediately */
3387 if ((f->callno == callno) && iaxs[f->callno] &&
3388 (f->seqno >= last)) {
3393 ast_pthread_mutex_unlock(&iaxq.lock);
3396 static int iax_poke_peer_s(void *data)
3398 struct iax_peer *peer = data;
3399 peer->pokeexpire = -1;
3400 iax_poke_peer(peer);
3404 static int socket_read(int *id, int fd, short events, void *cbdata)
3406 struct sockaddr_in sin;
3408 int new = NEW_PREVENT;
3411 int len = sizeof(sin);
3413 struct ast_iax_full_hdr *fh = (struct ast_iax_full_hdr *)buf;
3414 struct ast_iax_mini_hdr *mh = (struct ast_iax_mini_hdr *)buf;
3415 struct ast_iax_frame fr, *cur;
3417 struct ast_channel *c;
3418 struct iax_dpcache *dp;
3419 struct iax_peer *peer;
3425 char empty[32]=""; /* Safety measure */
3426 res = recvfrom(netsocket, buf, sizeof(buf), 0,(struct sockaddr *) &sin, &len);
3428 if (errno != ECONNREFUSED)
3429 ast_log(LOG_WARNING, "Error: %s\n", strerror(errno));
3433 if (res < sizeof(struct ast_iax_mini_hdr)) {
3434 ast_log(LOG_WARNING, "midget packet received (%d of %d min)\n", res, sizeof(struct ast_iax_mini_hdr));
3437 #ifdef DEBUG_SUPPORT
3439 showframe(NULL, fh, 1, &sin);
3441 if (ntohs(mh->callno) & AST_FLAG_FULL) {
3442 /* Get the destination call number */
3443 dcallno = ntohs(fh->dcallno);
3444 /* Retrieve the type and subclass */
3445 f.frametype = fh->type;
3446 f.subclass = uncompress_subclass(fh->csub);
3448 f.subclass = fh->subclasshigh << 16;
3449 f.subclass += ntohs(fh->subclasslow);
3451 if ((f.frametype == AST_FRAME_IAX) && ((f.subclass == AST_IAX_COMMAND_NEW) || (f.subclass == AST_IAX_COMMAND_REGREQ)
3452 || (f.subclass == AST_IAX_COMMAND_POKE)))
3455 /* Don't knwo anything about it yet */
3456 f.frametype = AST_FRAME_NULL;
3460 fr.callno = find_callno(ntohs(mh->callno) & ~AST_FLAG_FULL, dcallno, &sin, new);
3463 ast_pthread_mutex_lock(&iaxsl[fr.callno]);
3465 if ((fr.callno < 0) || !iaxs[fr.callno]) {
3466 /* A call arrived for a non-existant destination. Unless it's an "inval"
3467 frame, reply with an inval */
3468 if (ntohs(mh->callno) & AST_FLAG_FULL) {
3469 /* We can only raw hangup control frames */
3470 if (((f.subclass != AST_IAX_COMMAND_INVAL) &&
3471 (f.subclass != AST_IAX_COMMAND_TXCNT) &&
3472 (f.subclass != AST_IAX_COMMAND_TXACC))||
3473 (f.frametype != AST_FRAME_IAX))
3474 raw_hangup(&sin, ntohs(fh->dcallno), ntohs(mh->callno) & ~AST_FLAG_FULL
3478 ast_pthread_mutex_unlock(&iaxsl[fr.callno]);
3481 if (((f.subclass != AST_IAX_COMMAND_TXCNT) &&
3482 (f.subclass != AST_IAX_COMMAND_TXACC)) || (f.frametype != AST_FRAME_IAX))
3483 iaxs[fr.callno]->peercallno = (short)(ntohs(mh->callno) & ~AST_FLAG_FULL);
3484 if (ntohs(mh->callno) & AST_FLAG_FULL) {
3486 ast_log(LOG_DEBUG, "Received packet %d, (%d, %d)\n", ntohs(fh->seqno), f.frametype, f.subclass);
3487 /* Check if it's out of order (and not an ACK or INVAL) */
3488 fr.seqno = ntohs(fh->seqno);
3489 fr.ts = ntohl(fh->ts);
3490 if ((iaxs[fr.callno]->iseqno != fr.seqno) &&