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>
48 #include <mysql/mysql.h>
54 #define IPTOS_MINCOST 0x02
58 * Uncomment to try experimental IAX bridge optimization,
59 * designed to reduce latency when IAX calls cannot
63 #define BRIDGE_OPTIMIZATION
66 #define DEFAULT_RETRY_TIME 1000
67 #define MEMORY_SIZE 100
68 #define DEFAULT_DROP 3
72 /* Sample over last 100 units to determine historic jitter */
76 static ast_mutex_t mysqllock = AST_MUTEX_INITIALIZER;
78 static char mydbuser[80];
79 static char mydbpass[80];
80 static char mydbhost[80];
81 static char mydbname[80];
84 static char *desc = "Inter Asterisk eXchange";
85 static char *tdesc = "Inter Asterisk eXchange Drver";
86 static char *type = "IAX";
88 static char context[80] = "default";
90 static int max_retries = 4;
91 static int ping_time = 20;
92 static int lagrq_time = 10;
93 static int nextcallno = 0;
94 static int maxjitterbuffer=3000;
96 static int iaxdefaultdpcache=10 * 60; /* Cache dialplan entries for 10 minutes by default */
98 static int iaxdefaulttimeout = 5; /* Default to wait no more than 5 seconds for a reply to come back */
100 static int netsocket = -1;
104 static int expirey = AST_DEFAULT_REG_EXPIRE;
107 static ast_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
109 int (*iax_regfunk)(char *username, int onoff) = NULL;
112 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
114 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
115 ~AST_FORMAT_SLINEAR & \
119 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
120 ~AST_FORMAT_ADPCM & \
123 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
127 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
128 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
129 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
131 static struct io_context *io;
132 static struct sched_context *sched;
134 static int iax_capability = IAX_CAPABILITY_FULLBANDWIDTH;
136 static int iax_dropcount = DEFAULT_DROP;
138 static int use_jitterbuffer = 1;
140 static int iaxdebug = 0;
142 static char accountcode[20];
143 static int amaflags = 0;
145 static pthread_t netthreadid;
147 #define IAX_STATE_STARTED (1 << 0)
148 #define IAX_STATE_AUTHENTICATED (1 << 1)
149 #define IAX_STATE_TBD (1 << 2)
152 char context[AST_MAX_EXTENSION];
153 struct iax_context *next;
160 char accountcode[20];
161 char inkeys[80]; /* Key(s) this user can use to authenticate to us */
165 char callerid[AST_MAX_EXTENSION];
167 struct iax_context *contexts;
168 struct iax_user *next;
175 char outkey[80]; /* What key we use to talk to this peer */
176 char context[AST_MAX_EXTENSION]; /* Default context (for transfer really) */
177 struct sockaddr_in addr;
181 /* Dynamic Registration fields */
182 int dynamic; /* If this is a dynamic peer */
183 struct sockaddr_in defaddr; /* Default address if there is one */
185 char inkeys[80]; /* Key(s) this peer can use to authenticate to us */
188 /* Suggested caller id if registering */
189 char callerid[AST_MAX_EXTENSION];
190 /* Whether or not to send ANI */
192 int expire; /* Schedule entry for expirey */
193 int expirey; /* How soon to expire */
194 int capability; /* Capability */
195 int delme; /* I need to be deleted */
198 int callno; /* Call number of POKE request */
199 int pokeexpire; /* When to expire poke */
200 int lastms; /* How long last response took (in ms), or -1 for no response */
201 int maxms; /* Max ms we will accept for the host to be up, 0 to not monitor */
204 struct iax_peer *next;
207 #define REG_STATE_UNREGISTERED 0
208 #define REG_STATE_REGSENT 1
209 #define REG_STATE_AUTHSENT 2
210 #define REG_STATE_REGISTERED 3
211 #define REG_STATE_REJECTED 4
212 #define REG_STATE_TIMEOUT 5
213 #define REG_STATE_NOAUTH 6
215 #define TRANSFER_NONE 0
216 #define TRANSFER_BEGIN 1
217 #define TRANSFER_READY 2
218 #define TRANSFER_RELEASED 3
219 #define TRANSFER_PASSTHROUGH 4
221 struct iax_registry {
222 struct sockaddr_in addr; /* Who we connect to for registration purposes */
224 char secret[80]; /* Password or key name in []'s */
226 int expire; /* Sched ID of expiration */
227 int refresh; /* How often to refresh */
229 int callno; /* Associated call number if applicable */
230 struct sockaddr_in us; /* Who the server thinks we are */
231 struct iax_registry *next;
234 static struct iax_registry *registrations;
236 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
237 #define MIN_RETRY_TIME 10
238 #define MAX_RETRY_TIME 10000
239 #define MAX_JITTER_BUFFER 50
241 /* If we have more than this much excess real jitter buffer, srhink it. */
242 static int max_jitter_buffer = MAX_JITTER_BUFFER;
244 struct chan_iax_pvt {
245 /* Pipes for communication. pipe[1] belongs to the
246 network thread (write), and pipe[0] belongs to the individual
248 /* Whether or not we Quelch audio */
250 /* Last received voice format */
252 /* Last sent voice format */
254 /* What we are capable of sending */
256 /* Last received timestamp */
258 /* Last sent timestamp - never send the same timestamp twice in a single call */
259 unsigned int lastsent;
261 unsigned int pingtime;
262 /* Max time for initial response */
265 struct sockaddr_in addr;
266 /* Our call number */
270 /* Peer selected format */
272 /* Peer capability */
274 /* timeval that we base our transmission on */
275 struct timeval offset;
276 /* timeval that we base our delivery on */
277 struct timeval rxcore;
278 /* Historical delivery time */
279 int history[MEMORY_SIZE];
280 /* Current base jitterbuffer */
282 /* Current jitter measure */
284 /* Historic jitter value */
288 /* Error, as discovered by the manager */
290 /* Owner if we have one */
291 struct ast_channel *owner;
292 /* What's our state? */
294 /* Expirey (optional) */
296 /* Next outgoing sequence number */
297 unsigned short oseqno;
298 /* Next incoming sequence number */
299 unsigned short iseqno;
302 /* Default Context */
304 /* Caller ID if available */
306 /* Hidden Caller ID (i.e. ANI) if appropriate */
308 /* Whether or not ani should be transmitted in addition to Caller*ID */
312 /* Requested Extension */
313 char exten[AST_MAX_EXTENSION];
314 /* Expected Username */
316 /* Expected Secret */
318 /* permitted authentication methods */
322 /* Public keys permitted keys for incoming authentication */
324 /* Private key for outgoing authentication */
326 /* Preferred language */
328 /* Associated registry */
329 struct iax_registry *reg;
330 /* Associated peer for poking */
331 struct iax_peer *peerpoke;
333 /* Transferring status */
335 /* Already disconnected */
337 /* Who we are IAX transfering to */
338 struct sockaddr_in transfer;
339 /* What's the new call number for the transfer */
342 /* Status of knowledge of peer ADSI capability */
345 /* Who we are bridged to */
347 int pingid; /* Transmit PING request */
348 int lagid; /* Retransmit lag request */
349 int autoid; /* Auto hangup for Dialplan requestor */
350 int initid; /* Initial peer auto-congest ID (based on qualified peers) */
351 char dproot[AST_MAX_EXTENSION];
352 char accountcode[20];
354 struct iax_dpcache *dpentries;
357 #define DIRECTION_INGRESS 1
358 #define DIRECTION_OUTGRESS 2
360 struct ast_iax_frame {
361 /* Actual, isolated frame */
363 /* /Our/ call number */
365 /* Start of raw frame (outgoing only) */
367 /* Length of frame (outgoing only) */
369 /* How many retries so far? */
371 /* Outgoing relative timestamp (ms) */
373 /* How long to wait before retrying */
375 /* Are we received out of order? */
377 /* Have we been sent at all yet? */
379 /* Packet sequence number */
381 /* Non-zero if should be sent to transfer peer */
383 /* Non-zero if this is the final message */
385 /* Ingress or outgres */
387 /* Retransmission ID */
392 struct ast_iax_frame *next;
393 struct ast_iax_frame *prev;
396 static struct ast_iax_queue {
397 struct ast_iax_frame *head;
398 struct ast_iax_frame *tail;
403 static struct ast_user_list {
404 struct iax_user *users;
408 static struct ast_peer_list {
409 struct iax_peer *peers;
413 /* Extension exists */
414 #define CACHE_FLAG_EXISTS (1 << 0)
415 /* Extension is non-existant */
416 #define CACHE_FLAG_NONEXISTANT (1 << 1)
417 /* Extension can exist */
418 #define CACHE_FLAG_CANEXIST (1 << 2)
419 /* Waiting to hear back response */
420 #define CACHE_FLAG_PENDING (1 << 3)
422 #define CACHE_FLAG_TIMEOUT (1 << 4)
423 /* Request transmitted */
424 #define CACHE_FLAG_TRANSMITTED (1 << 5)
426 #define CACHE_FLAG_UNKNOWN (1 << 6)
428 #define CACHE_FLAG_MATCHMORE (1 << 7)
430 static struct iax_dpcache {
431 char peercontext[AST_MAX_EXTENSION];
432 char exten[AST_MAX_EXTENSION];
434 struct timeval expirey;
438 struct iax_dpcache *next;
439 struct iax_dpcache *peer; /* For linking in peers */
442 static ast_mutex_t dpcache_lock;
445 static void showframe(struct ast_iax_frame *f, struct ast_iax_full_hdr *fhi, int rx, struct sockaddr_in *sin)
499 struct ast_iax_full_hdr *fh;
507 snprintf(retries, sizeof(retries), "%03d", f->retries);
509 strcpy(retries, "N/A");
512 if (!(ntohs(fh->callno) & AST_FLAG_FULL)) {
513 /* Don't mess with mini-frames */
516 if (fh->type > sizeof(frames)/sizeof(char *)) {
517 snprintf(class2, sizeof(class2), "(%d?)", fh->type);
520 class = frames[(int)fh->type];
522 if (fh->type == AST_FRAME_DTMF) {
523 sprintf(subclass2, "%c", fh->csub);
524 subclass = subclass2;
525 } else if (fh->type == AST_FRAME_IAX) {
526 if (fh->csub >= sizeof(iaxs)/sizeof(iaxs[0])) {
527 snprintf(subclass2, sizeof(subclass2), "(%d?)", fh->csub);
528 subclass = subclass2;
530 subclass = iaxs[(int)fh->csub];
532 } else if (fh->type == AST_FRAME_CONTROL) {
533 if (fh->csub > sizeof(cmds)/sizeof(char *)) {
534 snprintf(subclass2, sizeof(subclass2), "(%d?)", fh->csub);
535 subclass = subclass2;
537 subclass = cmds[(int)fh->csub];
540 snprintf(subclass2, sizeof(subclass2), "%d", fh->csub);
541 subclass = subclass2;
544 "%s-Frame Retry[%s] -- Seqno: %2.2d Type: %s Subclass: %s\n",
546 retries, ntohs(fh->seqno), class, subclass);
548 " Timestamp: %05ldms Callno: %5.5d DCall: %5.5d [%s:%d]\n",
550 (short)(ntohs(fh->callno) & ~AST_FLAG_FULL), (short) ntohs(fh->dcallno),
551 inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
555 /* XXX We probably should use a mutex when working with this XXX */
556 static struct chan_iax_pvt *iaxs[AST_IAX_MAX_CALLS];
557 static ast_mutex_t iaxsl[AST_IAX_MAX_CALLS];
559 static int send_command(struct chan_iax_pvt *, char, int, unsigned int, char *, int, int);
560 static int send_command_immediate(struct chan_iax_pvt *, char, int, unsigned int, char *, int, int);
561 static int send_command_final(struct chan_iax_pvt *, char, int, unsigned int, char *, int, int);
562 static int send_command_transfer(struct chan_iax_pvt *, char, int, unsigned int, char *, int);
564 static unsigned int calc_timestamp(struct chan_iax_pvt *p, unsigned int ts);
566 static int send_ping(void *data)
568 int callno = (long)data;
569 /* Ping only if it's real, not if it's bridged */
571 #ifdef BRIDGE_OPTIMIZATION
572 if (iaxs[callno]->bridgecallno < 0)
574 send_command(iaxs[callno], AST_FRAME_IAX, AST_IAX_COMMAND_PING, 0, NULL, 0, -1);
580 static int send_lagrq(void *data)
582 int callno = (long)data;
583 /* Ping only if it's real not if it's bridged */
585 #ifdef BRIDGE_OPTIMIZATION
586 if (iaxs[callno]->bridgecallno < 0)
588 send_command(iaxs[callno], AST_FRAME_IAX, AST_IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
594 static unsigned char compress_subclass(int subclass)
598 /* If it's 128 or smaller, just return it */
599 if (subclass < AST_FLAG_SC_LOG)
601 /* Otherwise find its power */
602 for (x = 0; x < AST_MAX_SHIFT; x++) {
603 if (subclass & (1 << x)) {
605 ast_log(LOG_WARNING, "Can't compress subclass %d\n", subclass);
611 return power | AST_FLAG_SC_LOG;
614 static int uncompress_subclass(unsigned char csub)
616 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
617 if (csub & AST_FLAG_SC_LOG) {
618 /* special case for 'compressed' -1 */
622 return 1 << (csub & ~AST_FLAG_SC_LOG & AST_MAX_SHIFT);
628 static struct chan_iax_pvt *new_iax(void)
630 struct chan_iax_pvt *tmp;
631 tmp = malloc(sizeof(struct chan_iax_pvt));
633 memset(tmp, 0, sizeof(struct chan_iax_pvt));
635 tmp->peercallno = -1;
636 tmp->transfercallno = -1;
637 tmp->bridgecallno = -1;
642 /* strncpy(tmp->context, context, sizeof(tmp->context)-1); */
643 strncpy(tmp->exten, "s", sizeof(tmp->exten)-1);
648 static int get_samples(struct ast_frame *f)
651 switch(f->subclass) {
652 case AST_FORMAT_G723_1:
653 samples = 240 /* XXX Not necessarily true XXX */;
656 samples = 160 * (f->datalen / 33);
658 case AST_FORMAT_ILBC:
659 samples = 240 * (f->datalen / 50);
661 case AST_FORMAT_G729A:
662 samples = 160 * (f->datalen / 20);
664 case AST_FORMAT_SLINEAR:
665 samples = f->datalen / 2;
667 case AST_FORMAT_LPC10:
669 samples += (((char *)(f->data))[7] & 0x1) * 8;
671 case AST_FORMAT_ULAW:
672 samples = f->datalen;
674 case AST_FORMAT_ALAW:
675 samples = f->datalen;
677 case AST_FORMAT_ADPCM:
678 samples = f->datalen *2;
680 case AST_FORMAT_SPEEX:
681 samples = (f->datalen/39)*160;
684 ast_log(LOG_WARNING, "Don't know how to calculate samples on %d packets\n", f->subclass);
689 static int frames = 0;
690 static int iframes = 0;
691 static int oframes = 0;
693 static struct ast_iax_frame *ast_iax_frame_new(int direction)
695 struct ast_iax_frame *fr;
696 fr = malloc(sizeof(struct ast_iax_frame));
698 fr->direction = direction;
701 if (fr->direction == DIRECTION_INGRESS)
709 static void ast_iax_frame_free(struct ast_iax_frame *fr)
711 if (fr->retrans > -1)
712 ast_sched_del(sched, fr->retrans);
713 if (fr->direction == DIRECTION_INGRESS)
715 else if (fr->direction == DIRECTION_OUTGRESS)
718 ast_log(LOG_WARNING, "Attempt to double free frame detected\n");
727 static struct ast_iax_frame *iaxfrdup2(struct ast_iax_frame *fr, int ch)
729 /* Malloc() a copy of a frame */
730 struct ast_iax_frame *new = ast_iax_frame_new(DIRECTION_INGRESS);
732 memcpy(new, fr, sizeof(struct ast_iax_frame));
733 new->f = ast_frdup(fr->f);
734 /* Copy full header */
736 memcpy(new->f->data - sizeof(struct ast_iax_full_hdr),
737 fr->f->data - sizeof(struct ast_iax_full_hdr),
738 sizeof(struct ast_iax_full_hdr));
739 /* Grab new data pointer */
740 new->data = new->f->data - (fr->f->data - fr->data);
745 new->direction = DIRECTION_INGRESS;
751 #define NEW_PREVENT 0
755 static int match(struct sockaddr_in *sin, short callno, short dcallno, struct chan_iax_pvt *cur)
757 if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
758 (cur->addr.sin_port == sin->sin_port)) {
759 /* This is the main host */
760 if ((cur->peercallno == callno) ||
761 ((dcallno == cur->callno) && (cur->peercallno) == -1)) {
762 /* That's us. Be sure we keep track of the peer call number */
766 if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
767 (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
768 /* We're transferring */
769 if (dcallno == cur->callno)
775 static int find_callno(short callno, short dcallno ,struct sockaddr_in *sin, int new)
780 if (new <= NEW_ALLOW) {
781 /* Look for an existing connection first */
782 for (x=0;(res < 0) && (x<AST_IAX_MAX_CALLS);x++) {
783 ast_mutex_lock(&iaxsl[x]);
785 /* Look for an exact match */
786 if (match(sin, callno, dcallno, iaxs[x])) {
790 ast_mutex_unlock(&iaxsl[x]);
793 if ((res < 0) && (new >= NEW_ALLOW)) {
794 /* Create a new one */
796 for (x = (nextcallno + 1) % AST_IAX_MAX_CALLS; iaxs[x] && (x != start); x = (x + 1) % AST_IAX_MAX_CALLS)
798 ast_log(LOG_WARNING, "Unable to accept more calls\n");
801 ast_mutex_lock(&iaxsl[x]);
803 ast_mutex_unlock(&iaxsl[x]);
806 ast_log(LOG_DEBUG, "Creating new call structure %d\n", x);
807 iaxs[x]->addr.sin_port = sin->sin_port;
808 iaxs[x]->addr.sin_family = sin->sin_family;
809 iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
810 iaxs[x]->peercallno = callno;
812 iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
813 iaxs[x]->expirey = expirey;
814 iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)x);
815 iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)x);
816 iaxs[x]->amaflags = amaflags;
817 strncpy(iaxs[x]->accountcode, accountcode, sizeof(iaxs[x]->accountcode)-1);
819 ast_log(LOG_WARNING, "Out of resources\n");
828 static int iax_queue_frame(int callno, struct ast_frame *f)
831 /* Assumes lock for callno is already held... */
834 if (!ast_mutex_trylock(&iaxsl[callno])) {
835 ast_log(LOG_WARNING, "Lock is not held on pass %d of iax_queue_frame\n", pass);
838 if (iaxs[callno] && iaxs[callno]->owner) {
839 if (ast_mutex_trylock(&iaxs[callno]->owner->lock)) {
840 /* Avoid deadlock by pausing and trying again */
841 ast_mutex_unlock(&iaxsl[callno]);
843 ast_mutex_lock(&iaxsl[callno]);
845 ast_queue_frame(iaxs[callno]->owner, f, 0);
846 ast_mutex_unlock(&iaxs[callno]->owner->lock);
855 static int iax_send(struct chan_iax_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
857 static int __do_deliver(void *data)
859 /* Just deliver the packet by using queueing. This is called by
860 the IAX thread with the iaxsl lock held. */
861 struct ast_iax_frame *fr = data;
864 if (iaxs[fr->callno] && !iaxs[fr->callno]->alreadygone) {
865 if (fr->f->frametype == AST_FRAME_IAX) {
866 /* We have to treat some of these packets specially because
867 they're LAG measurement packets */
868 if (fr->f->subclass == AST_IAX_COMMAND_LAGRQ) {
869 /* If we got a queued request, build a reply and send it */
870 fr->f->subclass = AST_IAX_COMMAND_LAGRP;
871 iax_send(iaxs[fr->callno], fr->f, fr->ts, -1, 0, 0, 0);
872 } else if (fr->f->subclass == AST_IAX_COMMAND_LAGRP) {
873 /* This is a reply we've been given, actually measure the difference */
874 ts = calc_timestamp(iaxs[fr->callno], 0);
875 iaxs[fr->callno]->lag = ts - fr->ts;
878 iax_queue_frame(fr->callno, fr->f);
881 /* Free the packet */
883 /* And our iax frame */
884 ast_iax_frame_free(fr);
885 /* And don't run again */
889 static int do_deliver(void *data)
891 /* Locking version of __do_deliver */
892 struct ast_iax_frame *fr = data;
893 int callno = fr->callno;
895 ast_mutex_lock(&iaxsl[callno]);
896 res = __do_deliver(data);
897 ast_mutex_unlock(&iaxsl[callno]);
901 static int handle_error(void)
903 /* XXX Ideally we should figure out why an error occured and then abort those
904 rather than continuing to try. Unfortunately, the published interface does
905 not seem to work XXX */
907 struct sockaddr_in *sin;
910 struct sock_extended_err e;
915 m.msg_controllen = sizeof(e);
917 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
919 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
921 if (m.msg_controllen) {
922 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
924 ast_log(LOG_WARNING, "Receive error from %s\n", inet_ntoa(sin->sin_addr));
926 ast_log(LOG_WARNING, "No address detected??\n");
928 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
935 static int send_packet(struct ast_iax_frame *f)
938 /* Called with iaxsl held */
940 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));
941 /* Don't send if there was an error, but return error instead */
943 ast_log(LOG_WARNING, "Call number = %d\n", f->callno);
946 if (!iaxs[f->callno])
948 if (iaxs[f->callno]->error)
953 showframe(f, NULL, 0, &iaxs[f->callno]->transfer);
955 res = sendto(netsocket, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[f->callno]->transfer,
956 sizeof(iaxs[f->callno]->transfer));
960 showframe(f, NULL, 0, &iaxs[f->callno]->addr);
962 res = sendto(netsocket, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[f->callno]->addr,
963 sizeof(iaxs[f->callno]->addr));
967 ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
975 static int iax_predestroy(int callno)
977 struct ast_channel *c;
978 struct chan_iax_pvt *pvt;
979 ast_mutex_lock(&iaxsl[callno]);
982 ast_mutex_unlock(&iaxsl[callno]);
985 if (!pvt->alreadygone) {
986 /* No more pings or lagrq's */
987 if (pvt->pingid > -1)
988 ast_sched_del(sched, pvt->pingid);
990 ast_sched_del(sched, pvt->lagid);
991 if (pvt->autoid > -1)
992 ast_sched_del(sched, pvt->autoid);
993 if (pvt->initid > -1)
994 ast_sched_del(sched, pvt->initid);
999 pvt->alreadygone = 1;
1003 c->_softhangup |= AST_SOFTHANGUP_DEV;
1006 ast_mutex_lock(&usecnt_lock);
1009 ast_log(LOG_WARNING, "Usecnt < 0???\n");
1010 ast_mutex_unlock(&usecnt_lock);
1011 ast_update_use_count();
1013 ast_mutex_unlock(&iaxsl[callno]);
1017 static int iax_predestroy_nolock(int callno)
1020 ast_mutex_unlock(&iaxsl[callno]);
1021 res = iax_predestroy(callno);
1022 ast_mutex_lock(&iaxsl[callno]);
1026 static void iax_destroy(int callno)
1028 struct chan_iax_pvt *pvt;
1029 struct ast_iax_frame *cur;
1030 struct ast_channel *owner;
1033 ast_mutex_lock(&iaxsl[callno]);
1035 iaxs[callno] = NULL;
1042 if (ast_mutex_trylock(&owner->lock)) {
1043 ast_log(LOG_NOTICE, "Avoiding IAX destroy deadlock\n");
1044 ast_mutex_unlock(&iaxsl[callno]);
1051 /* No more pings or lagrq's */
1052 if (pvt->pingid > -1)
1053 ast_sched_del(sched, pvt->pingid);
1054 if (pvt->lagid > -1)
1055 ast_sched_del(sched, pvt->lagid);
1056 if (pvt->autoid > -1)
1057 ast_sched_del(sched, pvt->autoid);
1058 if (pvt->initid > -1)
1059 ast_sched_del(sched, pvt->initid);
1066 pvt->alreadygone = 1;
1069 /* If there's an owner, prod it to give up */
1070 owner->pvt->pvt = NULL;
1071 owner->_softhangup |= AST_SOFTHANGUP_DEV;
1072 ast_queue_hangup(owner, 0);
1075 for (cur = iaxq.head; cur ; cur = cur->next) {
1076 /* Cancel any pending transmissions */
1077 if (cur->callno == pvt->callno)
1081 pvt->reg->callno = -1;
1086 ast_mutex_unlock(&owner->lock);
1088 ast_mutex_unlock(&iaxsl[callno]);
1090 static void iax_destroy_nolock(int callno)
1092 /* Actually it's easier to unlock, kill it, and relock */
1093 ast_mutex_unlock(&iaxsl[callno]);
1094 iax_destroy(callno);
1095 ast_mutex_lock(&iaxsl[callno]);
1100 static int attempt_transmit(void *data)
1102 /* Attempt to transmit the frame to the remote peer...
1103 Called without iaxsl held. */
1104 struct ast_iax_frame *f = data;
1106 int callno = f->callno;
1107 /* Make sure this call is still active */
1109 ast_mutex_lock(&iaxsl[callno]);
1110 if ((f->callno > -1) && iaxs[f->callno]) {
1111 if ((f->retries < 0) /* Already ACK'd */ ||
1112 (f->retries >= max_retries) /* Too many attempts */) {
1113 /* Record an error if we've transmitted too many times */
1114 if (f->retries >= max_retries) {
1116 /* Transfer timeout */
1117 send_command(iaxs[f->callno], AST_FRAME_IAX, AST_IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
1118 } else if (f->final) {
1120 iax_destroy_nolock(f->callno);
1122 if (iaxs[f->callno]->owner)
1123 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);
1124 iaxs[f->callno]->error = ETIMEDOUT;
1125 if (iaxs[f->callno]->owner) {
1126 struct ast_frame fr = { 0, };
1128 fr.frametype = AST_FRAME_CONTROL;
1129 fr.subclass = AST_CONTROL_HANGUP;
1130 iax_queue_frame(f->callno, &fr);
1132 if (iaxs[f->callno]->reg) {
1133 memset(&iaxs[f->callno]->reg->us, 0, sizeof(iaxs[f->callno]->reg->us));
1134 iaxs[f->callno]->reg->regstate = REG_STATE_TIMEOUT;
1135 iaxs[f->callno]->reg->refresh = AST_DEFAULT_REG_EXPIRE;
1137 iax_destroy_nolock(f->callno);
1144 /* Attempt transmission */
1147 /* Try again later after 10 times as long */
1149 if (f->retrytime > MAX_RETRY_TIME)
1150 f->retrytime = MAX_RETRY_TIME;
1151 /* Transfer messages max out at one second */
1152 if (f->transfer && (f->retrytime > 1000))
1153 f->retrytime = 1000;
1154 f->retrans = ast_sched_add(sched, f->retrytime, attempt_transmit, f);
1157 /* Make sure it gets freed */
1162 ast_mutex_unlock(&iaxsl[callno]);
1163 /* Do not try again */
1165 /* Don't attempt delivery, just remove it from the queue */
1166 ast_mutex_lock(&iaxq.lock);
1168 f->prev->next = f->next;
1170 iaxq.head = f->next;
1172 f->next->prev = f->prev;
1174 iaxq.tail = f->prev;
1176 ast_mutex_unlock(&iaxq.lock);
1177 /* Free the frame */
1180 ast_iax_frame_free(f);
1185 static int iax_set_jitter(int fd, int argc, char *argv[])
1187 if ((argc != 4) && (argc != 5))
1188 return RESULT_SHOWUSAGE;
1190 max_jitter_buffer = atoi(argv[3]);
1191 if (max_jitter_buffer < 0)
1192 max_jitter_buffer = 0;
1195 if ((atoi(argv[3]) >= 0) && (atoi(argv[3]) < AST_IAX_MAX_CALLS)) {
1196 if (iaxs[atoi(argv[3])]) {
1197 iaxs[atoi(argv[3])]->jitterbuffer = atoi(argv[4]);
1198 if (iaxs[atoi(argv[3])]->jitterbuffer < 0)
1199 iaxs[atoi(argv[3])]->jitterbuffer = 0;
1201 ast_cli(fd, "No such call '%d'\n", atoi(argv[3]));
1203 ast_cli(fd, "%d is not a valid call number\n", atoi(argv[3]));
1206 return RESULT_SUCCESS;
1209 static char jitter_usage[] =
1210 "Usage: iax set jitter [callid] <value>\n"
1211 " If used with a callid, it sets the jitter buffer to the given static\n"
1212 "value (until its next calculation). If used without a callid, the value is used\n"
1213 "to establish the maximum excess jitter buffer that is permitted before the jitter\n"
1214 "buffer size is reduced.";
1216 static int iax_show_stats(int fd, int argc, char *argv[])
1218 struct ast_iax_frame *cur;
1219 int cnt = 0, dead=0, final=0;
1221 return RESULT_SHOWUSAGE;
1222 for (cur = iaxq.head; cur ; cur = cur->next) {
1223 if (cur->retries < 0)
1229 ast_cli(fd, " IAX Statistics\n");
1230 ast_cli(fd, "---------------------\n");
1231 ast_cli(fd, "Outstanding frames: %d (%d ingress, %d outgress)\n", frames, iframes, oframes);
1232 ast_cli(fd, "Packets in transmit queue: %d dead, %d final, %d total\n", dead, final, cnt);
1233 return RESULT_SUCCESS;
1236 static int iax_show_cache(int fd, int argc, char *argv[])
1238 struct iax_dpcache *dp;
1239 char tmp[1024], *pc;
1243 gettimeofday(&tv, NULL);
1244 ast_mutex_lock(&dpcache_lock);
1246 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
1248 s = dp->expirey.tv_sec - tv.tv_sec;
1250 if (dp->flags & CACHE_FLAG_EXISTS)
1251 strcat(tmp, "EXISTS|");
1252 if (dp->flags & CACHE_FLAG_NONEXISTANT)
1253 strcat(tmp, "NONEXISTANT|");
1254 if (dp->flags & CACHE_FLAG_CANEXIST)
1255 strcat(tmp, "CANEXIST|");
1256 if (dp->flags & CACHE_FLAG_PENDING)
1257 strcat(tmp, "PENDING|");
1258 if (dp->flags & CACHE_FLAG_TIMEOUT)
1259 strcat(tmp, "TIMEOUT|");
1260 if (dp->flags & CACHE_FLAG_TRANSMITTED)
1261 strcat(tmp, "TRANSMITTED|");
1262 if (dp->flags & CACHE_FLAG_MATCHMORE)
1263 strcat(tmp, "MATCHMORE|");
1264 if (dp->flags & CACHE_FLAG_UNKNOWN)
1265 strcat(tmp, "UNKNOWN|");
1266 /* Trim trailing pipe */
1268 tmp[strlen(tmp) - 1] = '\0';
1270 strcpy(tmp, "(none)");
1272 pc = strchr(dp->peercontext, '@');
1274 pc = dp->peercontext;
1277 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
1278 if (dp->waiters[x] > -1)
1281 ast_cli(fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
1283 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
1286 ast_mutex_unlock(&dpcache_lock);
1287 return RESULT_SUCCESS;
1290 static char show_stats_usage[] =
1291 "Usage: iax show stats\n"
1292 " Display statistics on IAX channel driver.\n";
1295 static char show_cache_usage[] =
1296 "Usage: iax show cache\n"
1297 " Display currently cached IAX Dialplan results.\n";
1299 static struct ast_cli_entry cli_set_jitter =
1300 { { "iax", "set", "jitter", NULL }, iax_set_jitter, "Sets IAX jitter buffer", jitter_usage };
1302 static struct ast_cli_entry cli_show_stats =
1303 { { "iax", "show", "stats", NULL }, iax_show_stats, "Display IAX statistics", show_stats_usage };
1305 static struct ast_cli_entry cli_show_cache =
1306 { { "iax", "show", "cache", NULL }, iax_show_cache, "Display IAX cached dialplan", show_cache_usage };
1308 static unsigned int calc_rxstamp(struct chan_iax_pvt *p);
1310 #ifdef BRIDGE_OPTIMIZATION
1311 static unsigned int calc_fakestamp(struct chan_iax_pvt *from, struct chan_iax_pvt *to, unsigned int ts);
1313 static int forward_delivery(struct ast_iax_frame *fr)
1315 struct chan_iax_pvt *p1, *p2;
1316 p1 = iaxs[fr->callno];
1317 p2 = iaxs[p1->bridgecallno];
1322 /* Fix relative timestamp */
1323 fr->ts = calc_fakestamp(p1, p2, fr->ts);
1324 /* Now just send it send on the 2nd one
1325 with adjusted timestamp */
1326 return iax_send(p2, fr->f, fr->ts, -1, 0, 0, 0);
1330 static int schedule_delivery(struct ast_iax_frame *fr, int reallydeliver)
1333 int drops[MEMORY_SIZE];
1334 int min, max=0, maxone=0,y,z, match;
1335 /* ms is a measure of the "lateness" of the packet relative to the first
1336 packet we received, which always has a lateness of 1. Called by
1337 IAX thread, with iaxsl lock held. */
1338 ms = calc_rxstamp(iaxs[fr->callno]) - fr->ts;
1341 /* What likely happened here is that our counter has circled but we haven't
1342 gotten the update from the main packet. We'll just pretend that we did, and
1343 update the timestamp appropriately. */
1348 /* We got this packet out of order. Lets add 65536 to it to bring it into our new
1353 /* Rotate our history queue of "lateness". Don't worry about those initial
1354 zeros because the first entry will always be zero */
1355 for (x=0;x<MEMORY_SIZE - 1;x++)
1356 iaxs[fr->callno]->history[x] = iaxs[fr->callno]->history[x+1];
1357 /* Add a history entry for this one */
1358 iaxs[fr->callno]->history[x] = ms;
1360 /* Initialize the minimum to reasonable values. It's too much
1361 work to do the same for the maximum, repeatedly */
1362 min=iaxs[fr->callno]->history[0];
1363 for (z=0;z < iax_dropcount + 1;z++) {
1364 /* Start very optimistic ;-) */
1366 for (x=0;x<MEMORY_SIZE;x++) {
1367 if (max < iaxs[fr->callno]->history[x]) {
1368 /* We have a candidate new maximum value. Make
1369 sure it's not in our drop list */
1371 for (y=0;!match && (y<z);y++)
1372 match |= (drops[y] == x);
1374 /* It's not in our list, use it as the new maximum */
1375 max = iaxs[fr->callno]->history[x];
1381 /* On our first pass, find the minimum too */
1382 if (min > iaxs[fr->callno]->history[x])
1383 min = iaxs[fr->callno]->history[x];
1390 /* Just for reference, keep the "jitter" value, the difference between the
1391 earliest and the latest. */
1392 iaxs[fr->callno]->jitter = max - min;
1394 /* IIR filter for keeping track of historic jitter, but always increase
1395 historic jitter immediately for increase */
1397 if (iaxs[fr->callno]->jitter > iaxs[fr->callno]->historicjitter )
1398 iaxs[fr->callno]->historicjitter = iaxs[fr->callno]->jitter;
1400 iaxs[fr->callno]->historicjitter = GAMMA * (double)iaxs[fr->callno]->jitter + (1-GAMMA) *
1401 iaxs[fr->callno]->historicjitter;
1403 /* If our jitter buffer is too big (by a significant margin), then we slowly
1404 shrink it by about 1 ms each time to avoid letting the change be perceived */
1405 if (max < iaxs[fr->callno]->jitterbuffer - max_jitter_buffer)
1406 iaxs[fr->callno]->jitterbuffer -= 2;
1410 /* Constrain our maximum jitter buffer appropriately */
1411 if (max > min + maxjitterbuffer) {
1413 ast_log(LOG_DEBUG, "Constraining buffer from %d to %d + %d\n", max, min , maxjitterbuffer);
1414 max = min + maxjitterbuffer;
1418 /* If our jitter buffer is smaller than our maximum delay, grow the jitter
1419 buffer immediately to accomodate it (and a little more). */
1420 if (max > iaxs[fr->callno]->jitterbuffer)
1421 iaxs[fr->callno]->jitterbuffer = max
1422 /* + ((float)iaxs[fr->callno]->jitter) * 0.1 */;
1426 ast_log(LOG_DEBUG, "min = %d, max = %d, jb = %d, lateness = %d\n", min, max, iaxs[fr->callno]->jitterbuffer, ms);
1428 /* Subtract the lateness from our jitter buffer to know how long to wait
1429 before sending our packet. */
1430 ms = iaxs[fr->callno]->jitterbuffer - ms;
1432 if (!use_jitterbuffer)
1435 /* If the caller just wanted us to update, return now */
1441 ast_log(LOG_DEBUG, "Calculated ms is %d\n", ms);
1442 /* Don't deliver it more than 4 ms late */
1443 if ((ms > -4) || (fr->f->frametype != AST_FRAME_VOICE)) {
1447 ast_log(LOG_DEBUG, "Dropping voice packet since %d ms is, too old\n", ms);
1448 /* Free the packet */
1450 /* And our iax frame */
1451 ast_iax_frame_free(fr);
1455 ast_log(LOG_DEBUG, "Scheduling delivery in %d ms\n", ms);
1456 fr->retrans = ast_sched_add(sched, ms, do_deliver, fr);
1461 static int iax_transmit(struct ast_iax_frame *fr)
1463 /* Lock the queue and place this packet at the end */
1466 /* By setting this to 0, the network thread will send it for us, and
1467 queue retransmission if necessary */
1469 ast_mutex_lock(&iaxq.lock);
1476 iaxq.tail->next = fr;
1477 fr->prev = iaxq.tail;
1481 ast_mutex_unlock(&iaxq.lock);
1482 /* Wake up the network thread */
1483 pthread_kill(netthreadid, SIGURG);
1489 static int iax_digit(struct ast_channel *c, char digit)
1491 return send_command(c->pvt->pvt, AST_FRAME_DTMF, digit, 0, NULL, 0, -1);
1494 static int iax_sendtext(struct ast_channel *c, char *text)
1497 return send_command(c->pvt->pvt, AST_FRAME_TEXT,
1498 0, 0, text, strlen(text) + 1, -1);
1501 static int iax_sendimage(struct ast_channel *c, struct ast_frame *img)
1503 return send_command(c->pvt->pvt, AST_FRAME_IMAGE, img->subclass, 0, img->data, img->datalen, -1);
1506 static int iax_sendhtml(struct ast_channel *c, int subclass, char *data, int datalen)
1508 return send_command(c->pvt->pvt, AST_FRAME_HTML, subclass, 0, data, datalen, -1);
1511 static int iax_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
1513 struct chan_iax_pvt *pvt = newchan->pvt->pvt;
1514 pvt->owner = newchan;
1518 #ifdef MYSQL_FRIENDS
1520 static void mysql_update_peer(char *peer, struct sockaddr_in *sin)
1522 if (mysql && (strlen(peer) < 128)) {
1526 name = alloca(strlen(peer) * 2 + 1);
1528 mysql_real_escape_string(mysql, name, peer, strlen(peer));
1529 snprintf(query, sizeof(query), "UPDATE iax1friends SET ipaddr=\"%s\", port=\"%d\", regseconds=\"%ld\" WHERE name=\"%s\"",
1530 inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), nowtime, name);
1531 ast_mutex_lock(&mysqllock);
1532 if (mysql_real_query(mysql, query, strlen(query)))
1533 ast_log(LOG_WARNING, "Unable to update database\n");
1535 ast_mutex_unlock(&mysqllock);
1539 static struct iax_peer *mysql_peer(char *peer)
1544 p = malloc(sizeof(struct iax_peer));
1545 memset(p, 0, sizeof(struct iax_peer));
1546 if (mysql && (strlen(peer) < 128)) {
1551 time_t regseconds, nowtime;
1553 MYSQL_FIELD *fields;
1555 name = alloca(strlen(peer) * 2 + 1);
1556 mysql_real_escape_string(mysql, name, peer, strlen(peer));
1557 snprintf(query, sizeof(query), "SELECT * FROM iax1friends WHERE name=\"%s\"", name);
1558 ast_mutex_lock(&mysqllock);
1559 mysql_query(mysql, query);
1560 if ((result = mysql_store_result(mysql))) {
1561 if ((rowval = mysql_fetch_row(result))) {
1562 numfields = mysql_num_fields(result);
1563 fields = mysql_fetch_fields(result);
1565 for (x=0;x<numfields;x++) {
1567 if (!strcasecmp(fields[x].name, "secret")) {
1568 strncpy(p->secret, rowval[x], sizeof(p->secret));
1569 } else if (!strcasecmp(fields[x].name, "context")) {
1570 strncpy(p->context, rowval[x], sizeof(p->context) - 1);
1571 } else if (!strcasecmp(fields[x].name, "ipaddr")) {
1572 inet_aton(rowval[x], &p->addr.sin_addr);
1573 } else if (!strcasecmp(fields[x].name, "port")) {
1574 if (sscanf(rowval[x], "%i", &port) != 1)
1576 p->addr.sin_port = htons(port);
1577 } else if (!strcasecmp(fields[x].name, "regseconds")) {
1578 if (sscanf(rowval[x], "%li", ®seconds) != 1)
1584 if ((nowtime - regseconds) > AST_DEFAULT_REG_EXPIRE)
1585 memset(&p->addr, 0, sizeof(p->addr));
1588 ast_mutex_unlock(&mysqllock);
1594 strncpy(p->name, peer, sizeof(p->name) - 1);
1598 p->capability = iax_capability;
1599 strcpy(p->methods, "md5,plaintext");
1604 static struct iax_user *mysql_user(char *user)
1607 struct iax_context *con;
1610 p = malloc(sizeof(struct iax_user));
1611 memset(p, 0, sizeof(struct iax_user));
1612 con = malloc(sizeof(struct iax_context));
1613 memset(con, 0, sizeof(struct iax_context));
1614 strcpy(con->context, "default");
1616 if (mysql && (strlen(user) < 128)) {
1621 MYSQL_FIELD *fields;
1623 name = alloca(strlen(user) * 2 + 1);
1624 mysql_real_escape_string(mysql, name, user, strlen(user));
1625 snprintf(query, sizeof(query), "SELECT * FROM iax1friends WHERE name=\"%s\"", name);
1626 ast_mutex_lock(&mysqllock);
1627 mysql_query(mysql, query);
1628 if ((result = mysql_store_result(mysql))) {
1629 if ((rowval = mysql_fetch_row(result))) {
1630 numfields = mysql_num_fields(result);
1631 fields = mysql_fetch_fields(result);
1633 for (x=0;x<numfields;x++) {
1635 if (!strcasecmp(fields[x].name, "secret")) {
1636 strncpy(p->secret, rowval[x], sizeof(p->secret));
1637 } else if (!strcasecmp(fields[x].name, "context")) {
1638 strncpy(p->contexts->context, rowval[x], sizeof(p->contexts->context) - 1);
1644 ast_mutex_unlock(&mysqllock);
1652 strncpy(p->name, user, sizeof(p->name) - 1);
1654 strcpy(p->methods, "md5,plaintext");
1658 #endif /* MYSQL_FRIENDS */
1660 static int create_addr(struct sockaddr_in *sin, int *capability, int *sendani, int *maxtime, char *peer, char *context)
1669 sin->sin_family = AF_INET;
1670 ast_mutex_lock(&peerl.lock);
1673 if (!strcasecmp(p->name, peer)) {
1678 #ifdef MYSQL_FRIENDS
1680 p = mysql_peer(peer);
1685 *capability = p->capability;
1686 if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
1687 (!p->maxms || ((p->lastms > 0) && (p->lastms <= p->maxms)))) {
1689 *sendani = p->sendani; /* Whether we transmit ANI */
1691 *maxtime = p->maxms; /* Max time they should take */
1693 strncpy(context, p->context, AST_MAX_EXTENSION - 1);
1694 if (p->addr.sin_addr.s_addr) {
1695 sin->sin_addr = p->addr.sin_addr;
1696 sin->sin_port = p->addr.sin_port;
1698 sin->sin_addr = p->defaddr.sin_addr;
1699 sin->sin_port = p->defaddr.sin_port;
1707 ast_mutex_unlock(&peerl.lock);
1709 hp = gethostbyname(peer);
1711 memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
1712 sin->sin_port = htons(AST_DEFAULT_IAX_PORTNO);
1715 ast_log(LOG_WARNING, "No such host: %s\n", peer);
1725 static int auto_congest(void *nothing)
1727 int callno = (int)(long)(nothing);
1728 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_CONGESTION };
1729 ast_mutex_lock(&iaxsl[callno]);
1731 iaxs[callno]->initid = -1;
1732 iax_queue_frame(callno, &f);
1733 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
1735 ast_mutex_unlock(&iaxsl[callno]);
1739 static int iax_call(struct ast_channel *c, char *dest, int timeout)
1741 struct sockaddr_in sin;
1746 char *secret = NULL;
1748 char requeststr[256] = "";
1749 char myrdest [5] = "s";
1750 char context[AST_MAX_EXTENSION] ="";
1751 char *portno = NULL;
1752 struct chan_iax_pvt *p = c->pvt->pvt;
1754 if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
1755 ast_log(LOG_WARNING, "Line is already in use (%s)?\n", c->name);
1758 strncpy(host, dest, sizeof(host)-1);
1760 strsep(&stringp, "/");
1761 /* If no destination extension specified, use 's' */
1762 rdest = strsep(&stringp, "/");
1766 strsep(&stringp, "@");
1767 rcontext = strsep(&stringp, "@");
1769 strsep(&stringp, "@");
1770 username = strsep(&stringp, "@");
1772 /* Really the second argument is the host, not the username */
1780 username = strsep(&stringp, ":");
1781 secret = strsep(&stringp, ":");
1784 if (strsep(&stringp, ":")) {
1786 strsep(&stringp, ":");
1787 portno = strsep(&stringp, ":");
1789 if (create_addr(&sin, NULL, NULL, NULL, hname, context)) {
1790 ast_log(LOG_WARNING, "No address associated with '%s'\n", hname);
1793 /* Keep track of the context for outgoing calls too */
1794 strncpy(c->context, context, sizeof(c->context) - 1);
1796 sin.sin_port = htons(atoi(portno));
1798 /* Now we build our request string */
1799 #define MYSNPRINTF snprintf(requeststr + strlen(requeststr), sizeof(requeststr) - strlen(requeststr),
1800 #define MYSNPRINTF2 snprintf(requeststr + strlen(requeststr), reqsize - strlen(requeststr),
1801 MYSNPRINTF "exten=%s;", rdest);
1803 MYSNPRINTF "callerid=%s;", c->callerid);
1804 if (p->sendani && c->ani)
1805 MYSNPRINTF "ani=%s;", c->ani);
1806 if (c->language && strlen(c->language))
1807 MYSNPRINTF "language=%s;", c->language);
1809 MYSNPRINTF "dnid=%s;", c->dnid);
1811 MYSNPRINTF "context=%s;", rcontext);
1813 MYSNPRINTF "username=%s;", username);
1815 if (secret[0] == '[') {
1816 /* This is an RSA key, not a normal secret */
1817 strncpy(p->outkey, secret + 1, sizeof(p->secret)-1);
1818 if (strlen(p->outkey)) {
1819 p->outkey[strlen(p->outkey) - 1] = '\0';
1822 strncpy(p->secret, secret, sizeof(p->secret)-1);
1824 MYSNPRINTF "formats=%d;", c->nativeformats);
1825 MYSNPRINTF "capability=%d;", p->capability);
1826 MYSNPRINTF "version=%d;", AST_IAX_PROTO_VERSION);
1827 MYSNPRINTF "adsicpe=%d;", c->adsicpe);
1828 /* Trim the trailing ";" */
1829 if (strlen(requeststr))
1830 requeststr[strlen(requeststr) - 1] = '\0';
1831 /* Transmit the string in a "NEW" request */
1832 if (option_verbose > 2)
1833 ast_verbose(VERBOSE_PREFIX_3 "Calling using options '%s'\n", requeststr);
1835 /* Initialize pingtime and auto-congest time */
1836 p->pingtime = p->maxtime / 2;
1837 p->initid = ast_sched_add(sched, p->maxtime * 2, auto_congest, (void *)p->callno);
1839 send_command(p, AST_FRAME_IAX,
1840 AST_IAX_COMMAND_NEW, 0, requeststr, strlen(requeststr) + 1, -1);
1841 ast_setstate(c, AST_STATE_RINGING);
1845 static int iax_hangup(struct ast_channel *c)
1847 struct chan_iax_pvt *pvt = c->pvt->pvt;
1851 callno = pvt->callno;
1852 ast_mutex_lock(&iaxsl[callno]);
1853 ast_log(LOG_DEBUG, "We're hanging up %s now...\n", c->name);
1854 alreadygone = pvt->alreadygone;
1855 /* Send the hangup unless we have had a transmission error or are already gone */
1856 if (!pvt->error && !alreadygone)
1857 send_command_final(pvt, AST_FRAME_IAX, AST_IAX_COMMAND_HANGUP, 0, NULL, 0, -1);
1858 /* Explicitly predestroy it */
1859 iax_predestroy_nolock(callno);
1860 /* If we were already gone to begin with, destroy us now */
1862 ast_log(LOG_DEBUG, "Really destroying %s now...\n", c->name);
1863 iax_destroy_nolock(callno);
1865 ast_mutex_unlock(&iaxsl[callno]);
1867 if (option_verbose > 2)
1868 ast_verbose(VERBOSE_PREFIX_3 "Hungup '%s'\n", c->name);
1872 static int iax_setoption(struct ast_channel *c, int option, void *data, int datalen)
1874 struct ast_option_header *h;
1876 h = malloc(datalen + sizeof(struct ast_option_header));
1878 h->flag = AST_OPTION_FLAG_REQUEST;
1879 h->option = htons(option);
1880 memcpy(h->data, data, datalen);
1881 res = send_command((struct chan_iax_pvt *)c->pvt->pvt, AST_FRAME_CONTROL,
1882 AST_CONTROL_OPTION, 0, (char *)h, datalen + sizeof(struct ast_option_header), -1);
1886 ast_log(LOG_WARNING, "Out of memory\n");
1889 static struct ast_frame *iax_read(struct ast_channel *c)
1891 static struct ast_frame f = { AST_FRAME_NULL, };
1892 ast_log(LOG_NOTICE, "I should never be called!\n");
1896 static int iax_start_transfer(struct ast_channel *c0, struct ast_channel *c1)
1901 struct chan_iax_pvt *p0 = c0->pvt->pvt;
1902 struct chan_iax_pvt *p1 = c1->pvt->pvt;
1903 snprintf(req0, sizeof(req0), "remip=%s;remport=%d;remcall=%d;", inet_ntoa(p1->addr.sin_addr), ntohs(p1->addr.sin_port), p1->peercallno);
1904 snprintf(req1, sizeof(req1), "remip=%s;remport=%d;remcall=%d;", inet_ntoa(p0->addr.sin_addr), ntohs(p0->addr.sin_port), p0->peercallno);
1905 res = send_command(p0, AST_FRAME_IAX, AST_IAX_COMMAND_TXREQ, 0, req0, strlen(req0) + 1, -1);
1908 res = send_command(p1, AST_FRAME_IAX, AST_IAX_COMMAND_TXREQ, 0, req1, strlen(req1) + 1, -1);
1911 p0->transferring = TRANSFER_BEGIN;
1912 p1->transferring = TRANSFER_BEGIN;
1916 static int iax_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
1918 struct ast_channel *cs[3];
1919 struct ast_channel *who;
1922 int transferstarted=0;
1923 struct ast_frame *f;
1924 struct chan_iax_pvt *p0 = c0->pvt->pvt;
1925 struct chan_iax_pvt *p1 = c1->pvt->pvt;
1927 /* Put them in native bridge mode */
1928 p0->bridgecallno = p1->callno;
1929 p1->bridgecallno = p0->callno;
1931 /* If not, try to bridge until we can execute a transfer, if we can */
1934 for (/* ever */;;) {
1935 /* Check in case we got masqueraded into */
1936 if ((c0->type != type) || (c1->type != type)) {
1937 if (option_verbose > 2)
1938 ast_verbose(VERBOSE_PREFIX_3 "Can't masquerade, we're different...\n");
1941 if (c0->nativeformats != c1->nativeformats) {
1942 ast_verbose(VERBOSE_PREFIX_3 "Operating with different codecs, can't native bridge...\n");
1945 if (!transferstarted) {
1946 /* Try the transfer */
1947 if (iax_start_transfer(c0, c1))
1948 ast_log(LOG_WARNING, "Unable to start the transfer\n");
1949 transferstarted = 1;
1952 if ((p0->transferring == TRANSFER_RELEASED) && (p1->transferring == TRANSFER_RELEASED)) {
1953 /* Call has been transferred. We're no longer involved */
1955 c0->_softhangup |= AST_SOFTHANGUP_DEV;
1956 c1->_softhangup |= AST_SOFTHANGUP_DEV;
1963 who = ast_waitfor_n(cs, 2, &to);
1974 if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
1980 if ((f->frametype == AST_FRAME_VOICE) ||
1981 (f->frametype == AST_FRAME_TEXT) ||
1982 (f->frametype == AST_FRAME_VIDEO) ||
1983 (f->frametype == AST_FRAME_IMAGE) ||
1984 (f->frametype == AST_FRAME_DTMF)) {
1985 if ((f->frametype == AST_FRAME_DTMF) &&
1986 (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
1988 if ((flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
1991 /* Take out of conference mode */
1998 if (flags & AST_BRIDGE_DTMF_CHANNEL_1) {
2008 ast_log(LOG_DEBUG, "Read from %s\n", who->name);
2010 ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
2022 /* Swap who gets priority */
2027 p0->bridgecallno = -1;
2028 p1->bridgecallno = -1;
2032 static int iax_answer(struct ast_channel *c)
2034 struct chan_iax_pvt *pvt = c->pvt->pvt;
2036 ast_log(LOG_DEBUG, "Answering\n");
2037 return send_command(pvt, AST_FRAME_CONTROL, AST_CONTROL_ANSWER, 0, NULL, 0, -1);
2040 static int iax_indicate(struct ast_channel *c, int condition)
2042 struct chan_iax_pvt *pvt = c->pvt->pvt;
2044 ast_log(LOG_DEBUG, "Indicating condition %d\n", condition);
2045 return send_command(pvt, AST_FRAME_CONTROL, condition, 0, NULL, 0, -1);
2049 static int iax_write(struct ast_channel *c, struct ast_frame *f);
2051 static int iax_getpeername(struct sockaddr_in sin, char *host, int len)
2053 struct iax_peer *peer;
2055 ast_mutex_lock(&peerl.lock);
2058 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
2059 (peer->addr.sin_port == sin.sin_port)) {
2060 strncpy(host, peer->name, len-1);
2066 ast_mutex_unlock(&peerl.lock);
2070 static struct ast_channel *ast_iax_new(struct chan_iax_pvt *i, int state, int capability)
2073 struct ast_channel *tmp;
2074 tmp = ast_channel_alloc(1);
2076 if (!iax_getpeername(i->addr, host, sizeof(host)))
2077 snprintf(host, sizeof(host), "%s:%d", inet_ntoa(i->addr.sin_addr), ntohs(i->addr.sin_port));
2078 if (strlen(i->username))
2079 snprintf(tmp->name, sizeof(tmp->name), "IAX[%s@%s]/%d", i->username, host, i->callno);
2081 snprintf(tmp->name, sizeof(tmp->name), "IAX[%s]/%d", host, i->callno);
2083 /* We can support any format by default, until we get restricted */
2084 tmp->nativeformats = capability;
2085 tmp->readformat = 0;
2086 tmp->writeformat = 0;
2088 tmp->pvt->send_digit = iax_digit;
2089 tmp->pvt->send_text = iax_sendtext;
2090 tmp->pvt->send_image = iax_sendimage;
2091 tmp->pvt->send_html = iax_sendhtml;
2092 tmp->pvt->call = iax_call;
2093 tmp->pvt->hangup = iax_hangup;
2094 tmp->pvt->answer = iax_answer;
2095 tmp->pvt->read = iax_read;
2096 tmp->pvt->write = iax_write;
2097 tmp->pvt->indicate = iax_indicate;
2098 tmp->pvt->setoption = iax_setoption;
2099 tmp->pvt->bridge = iax_bridge;
2100 if (strlen(i->callerid))
2101 tmp->callerid = strdup(i->callerid);
2103 tmp->ani = strdup(i->ani);
2104 if (strlen(i->language))
2105 strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
2106 if (strlen(i->dnid))
2107 tmp->dnid = strdup(i->dnid);
2108 if (strlen(i->accountcode))
2109 strncpy(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode)-1);
2111 tmp->amaflags = i->amaflags;
2112 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
2113 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
2114 tmp->adsicpe = i->peeradsicpe;
2115 tmp->pvt->fixup = iax_fixup;
2117 i->capability = capability;
2118 ast_setstate(tmp, state);
2119 ast_mutex_lock(&usecnt_lock);
2121 ast_mutex_unlock(&usecnt_lock);
2122 ast_update_use_count();
2123 if (state != AST_STATE_DOWN) {
2124 if (ast_pbx_start(tmp)) {
2125 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
2134 static unsigned int calc_timestamp(struct chan_iax_pvt *p, unsigned int ts)
2138 if (!p->offset.tv_sec && !p->offset.tv_usec)
2139 gettimeofday(&p->offset, NULL);
2140 /* If the timestamp is specified, just send it as is */
2143 gettimeofday(&tv, NULL);
2144 ms = (tv.tv_sec - p->offset.tv_sec) * 1000 + (tv.tv_usec - p->offset.tv_usec) / 1000;
2145 /* We never send the same timestamp twice, so fudge a little if we must */
2146 if (ms <= p->lastsent)
2147 ms = p->lastsent + 1;
2152 #ifdef BRIDGE_OPTIMIZATION
2153 static unsigned int calc_fakestamp(struct chan_iax_pvt *p1, struct chan_iax_pvt *p2, unsigned int fakets)
2156 /* Receive from p1, send to p2 */
2158 /* Setup rxcore if necessary on outgoing channel */
2159 if (!p1->rxcore.tv_sec && !p1->rxcore.tv_usec)
2160 gettimeofday(&p1->rxcore, NULL);
2162 /* Setup txcore if necessary on outgoing channel */
2163 if (!p2->offset.tv_sec && !p2->offset.tv_usec)
2164 gettimeofday(&p2->offset, NULL);
2166 /* Now, ts is the timestamp of the original packet in the orignal context.
2167 Adding rxcore to it gives us when we would want the packet to be delivered normally.
2168 Subtracting txcore of the outgoing channel gives us what we'd expect */
2170 ms = (p1->rxcore.tv_sec - p2->offset.tv_sec) * 1000 + (p1->rxcore.tv_usec - p1->offset.tv_usec) / 1000;
2172 if (fakets <= p2->lastsent)
2173 fakets = p2->lastsent + 1;
2174 p2->lastsent = fakets;
2179 static unsigned int calc_rxstamp(struct chan_iax_pvt *p)
2181 /* Returns where in "receive time" we are */
2184 /* Setup rxcore if necessary */
2185 if (!p->rxcore.tv_sec && !p->rxcore.tv_usec)
2186 gettimeofday(&p->rxcore, NULL);
2188 gettimeofday(&tv, NULL);
2189 ms = (tv.tv_sec - p->rxcore.tv_sec) * 1000 + (tv.tv_usec - p->rxcore.tv_usec) / 1000;
2193 static int iax_send(struct chan_iax_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final)
2195 /* Queue a packet for delivery on a given private structure. Use "ts" for
2196 timestamp, or calculate if ts is 0. Send immediately without retransmission
2197 or delayed, with retransmission */
2198 struct ast_iax_full_hdr *fh;
2199 struct ast_iax_mini_hdr *mh;
2200 struct ast_iax_frame *fr, fr2;
2202 unsigned int lastsent;
2203 /* Allocate an ast_iax_frame */
2207 fr = ast_iax_frame_new(DIRECTION_OUTGRESS);
2209 ast_log(LOG_WARNING, "Out of memory\n");
2213 ast_log(LOG_WARNING, "No private structure for packet (%d)?\n", fr->callno);
2215 ast_iax_frame_free(fr);
2218 /* Isolate our frame for transmission */
2219 fr->f = ast_frdup(f);
2222 ast_log(LOG_WARNING, "Out of memory\n");
2224 ast_iax_frame_free(fr);
2227 if (fr->f->offset < sizeof(struct ast_iax_full_hdr)) {
2228 ast_log(LOG_WARNING, "Packet from '%s' not friendly\n", fr->f->src);
2232 lastsent = pvt->lastsent;
2233 fr->ts = calc_timestamp(pvt, ts);
2235 ast_log(LOG_WARNING, "timestamp is 0?\n");
2237 ast_iax_frame_free(fr);
2240 fr->callno = pvt->callno;
2241 fr->transfer = transfer;
2243 if (((fr->ts & 0xFFFF0000L) != (lastsent & 0xFFFF0000L))
2244 /* High two bits of timestamp differ */ ||
2245 (fr->f->frametype != AST_FRAME_VOICE)
2246 /* or not a voice frame */ ||
2247 (fr->f->subclass != pvt->svoiceformat)
2248 /* or new voice format */ ) {
2249 /* We need a full frame */
2253 fr->seqno = pvt->oseqno++;
2254 fh = (struct ast_iax_full_hdr *)(fr->f->data - sizeof(struct ast_iax_full_hdr));
2255 fh->callno = htons(fr->callno | AST_FLAG_FULL);
2256 fh->ts = htonl(fr->ts);
2257 fh->seqno = htons(fr->seqno);
2258 fh->type = fr->f->frametype & 0xFF;
2259 fh->csub = compress_subclass(fr->f->subclass);
2261 fh->dcallno = htons(pvt->transfercallno);
2263 fh->dcallno = htons(pvt->peercallno);
2264 fr->datalen = fr->f->datalen + sizeof(struct ast_iax_full_hdr);
2267 /* Retry after 2x the ping time has passed */
2268 fr->retrytime = pvt->pingtime * 2;
2269 if (fr->retrytime < MIN_RETRY_TIME)
2270 fr->retrytime = MIN_RETRY_TIME;
2271 if (fr->retrytime > MAX_RETRY_TIME)
2272 fr->retrytime = MAX_RETRY_TIME;
2273 /* Acks' don't get retried */
2274 if ((f->frametype == AST_FRAME_IAX) && (f->subclass == AST_IAX_COMMAND_ACK))
2276 if (f->frametype == AST_FRAME_VOICE) {
2277 pvt->svoiceformat = f->subclass;
2280 res = send_packet(fr);
2283 res = iax_transmit(fr);
2285 /* Mini-frames have no sequence number */
2287 /* Mini frame will do */
2288 mh = (struct ast_iax_mini_hdr *)(fr->f->data - sizeof(struct ast_iax_mini_hdr));
2289 mh->callno = htons(fr->callno);
2290 mh->ts = htons(fr->ts & 0xFFFF);
2291 fr->datalen = fr->f->datalen + sizeof(struct ast_iax_mini_hdr);
2295 res = send_packet(fr);
2298 res = iax_transmit(fr);
2305 static int iax_show_users(int fd, int argc, char *argv[])
2307 #define FORMAT "%-15.15s %-15.15s %-15.15s %-15.15s %-5.5s\n"
2308 struct iax_user *user;
2310 return RESULT_SHOWUSAGE;
2311 ast_mutex_lock(&userl.lock);
2312 ast_cli(fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C");
2313 for(user=userl.users;user;user=user->next) {
2314 ast_cli(fd, FORMAT, user->name, user->secret, user->methods,
2315 user->contexts ? user->contexts->context : context,
2316 user->ha ? "Yes" : "No");
2318 ast_mutex_unlock(&userl.lock);
2319 return RESULT_SUCCESS;
2323 static int iax_show_peers(int fd, int argc, char *argv[])
2325 #define FORMAT2 "%-15.15s %-15.15s %s %-15.15s %-8s %-10s\n"
2326 #define FORMAT "%-15.15s %-15.15s %s %-15.15s %-8d %-10s\n"
2327 struct iax_peer *peer;
2328 char name[256] = "";
2330 return RESULT_SHOWUSAGE;
2331 ast_mutex_lock(&peerl.lock);
2332 ast_cli(fd, FORMAT2, "Name/Username", "Host", " ", "Mask", "Port", "Status");
2333 for (peer = peerl.peers;peer;peer = peer->next) {
2336 if (strlen(peer->username))
2337 snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
2339 strncpy(name, peer->name, sizeof(name) - 1);
2341 if (peer->lastms < 0)
2342 strcpy(status, "UNREACHABLE");
2343 else if (peer->lastms > peer->maxms)
2344 snprintf(status, sizeof(status), "LAGGED (%d ms)", peer->lastms);
2345 else if (peer->lastms)
2346 snprintf(status, sizeof(status), "OK (%d ms)", peer->lastms);
2348 strcpy(status, "UNKNOWN");
2350 strcpy(status, "Unmonitored");
2351 strncpy(nm, inet_ntoa(peer->mask), sizeof(nm)-1);
2352 ast_cli(fd, FORMAT, name,
2353 peer->addr.sin_addr.s_addr ? inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
2354 peer->dynamic ? "(D)" : "(S)",
2356 ntohs(peer->addr.sin_port), status);
2358 ast_mutex_unlock(&peerl.lock);
2359 return RESULT_SUCCESS;
2364 /* JDG: callback to display iax peers in manager */
2365 static int manager_iax_show_peers( struct mansession *s, struct message *m )
2367 char *a[] = { "iax", "show", "users" };
2369 ret = iax_show_peers( s->fd, 3, a );
2370 ast_cli( s->fd, "\r\n" );
2374 static char *regstate2str(int regstate)
2377 case REG_STATE_UNREGISTERED:
2378 return "Unregistered";
2379 case REG_STATE_REGSENT:
2380 return "Request Sent";
2381 case REG_STATE_AUTHSENT:
2382 return "Auth. Sent";
2383 case REG_STATE_REGISTERED:
2384 return "Registered";
2385 case REG_STATE_REJECTED:
2387 case REG_STATE_TIMEOUT:
2389 case REG_STATE_NOAUTH:
2390 return "No Authentication";
2396 static int iax_show_registry(int fd, int argc, char *argv[])
2398 #define FORMAT2 "%-20.20s %-10.10s %-20.20s %8.8s %s\n"
2399 #define FORMAT "%-20.20s %-10.10s %-20.20s %8d %s\n"
2400 struct iax_registry *reg;
2404 return RESULT_SHOWUSAGE;
2405 ast_mutex_lock(&peerl.lock);
2406 ast_cli(fd, FORMAT2, "Host", "Username", "Perceived", "Refresh", "State");
2407 for (reg = registrations;reg;reg = reg->next) {
2408 snprintf(host, sizeof(host), "%s:%d", inet_ntoa(reg->addr.sin_addr), ntohs(reg->addr.sin_port));
2409 if (reg->us.sin_addr.s_addr)
2410 snprintf(perceived, sizeof(perceived), "%s:%d", inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
2412 strcpy(perceived, "<Unregistered>");
2413 ast_cli(fd, FORMAT, host,
2414 reg->username, perceived, reg->refresh, regstate2str(reg->regstate));
2416 ast_mutex_unlock(&peerl.lock);
2417 return RESULT_SUCCESS;
2422 static int iax_show_channels(int fd, int argc, char *argv[])
2424 #define FORMAT2 "%-15.15s %-10.10s %-11.11s %-11.11s %-7.7s %-6.6s %s\n"
2425 #define FORMAT "%-15.15s %-10.10s %5.5d/%5.5d %5.5d/%5.5d %-5.5dms %-4.4dms %-6.6s\n"
2429 return RESULT_SHOWUSAGE;
2430 ast_cli(fd, FORMAT2, "Peer", "Username", "ID (Lo/Rem)", "Seq (Tx/Rx)", "Lag", "Jitter", "Format");
2431 for (x=0;x<AST_IAX_MAX_CALLS;x++) {
2432 ast_mutex_lock(&iaxsl[x]);
2434 ast_cli(fd, FORMAT, inet_ntoa(iaxs[x]->addr.sin_addr),
2435 strlen(iaxs[x]->username) ? iaxs[x]->username : "(None)",
2436 iaxs[x]->callno, iaxs[x]->peercallno,
2437 iaxs[x]->oseqno, iaxs[x]->iseqno,
2440 ast_getformatname(iaxs[x]->voiceformat) );
2443 ast_mutex_unlock(&iaxsl[x]);
2445 ast_cli(fd, "%d active IAX channel(s)\n", numchans);
2446 return RESULT_SUCCESS;
2451 static int iax_do_debug(int fd, int argc, char *argv[])
2454 return RESULT_SHOWUSAGE;
2456 ast_cli(fd, "IAX Debugging Enabled\n");
2457 return RESULT_SUCCESS;
2460 static int iax_no_debug(int fd, int argc, char *argv[])
2463 return RESULT_SHOWUSAGE;
2465 ast_cli(fd, "IAX Debugging Disabled\n");
2466 return RESULT_SUCCESS;
2471 static char show_users_usage[] =
2472 "Usage: iax show users\n"
2473 " Lists all users known to the IAX (Inter-Asterisk eXchange) subsystem.\n";
2475 static char show_channels_usage[] =
2476 "Usage: iax show channels\n"
2477 " Lists all currently active IAX channels.\n";
2479 static char show_peers_usage[] =
2480 "Usage: iax show peers\n"
2481 " Lists all known IAX peers.\n";
2483 static char show_reg_usage[] =
2484 "Usage: iax show registry\n"
2485 " Lists all registration requests and status.\n";
2487 #ifdef DEBUG_SUPPORT
2489 static char debug_usage[] =
2490 "Usage: iax debug\n"
2491 " Enables dumping of IAX packets for debugging purposes\n";
2493 static char no_debug_usage[] =
2494 "Usage: iax no debug\n"
2495 " Disables dumping of IAX packets for debugging purposes\n";
2499 static struct ast_cli_entry cli_show_users =
2500 { { "iax", "show", "users", NULL }, iax_show_users, "Show defined IAX users", show_users_usage };
2501 static struct ast_cli_entry cli_show_channels =
2502 { { "iax", "show", "channels", NULL }, iax_show_channels, "Show active IAX channels", show_channels_usage };
2503 static struct ast_cli_entry cli_show_peers =
2504 { { "iax", "show", "peers", NULL }, iax_show_peers, "Show defined IAX peers", show_peers_usage };
2505 static struct ast_cli_entry cli_show_registry =
2506 { { "iax", "show", "registry", NULL }, iax_show_registry, "Show IAX registration status", show_reg_usage };
2507 static struct ast_cli_entry cli_debug =
2508 { { "iax", "debug", NULL }, iax_do_debug, "Enable IAX debugging", debug_usage };
2509 static struct ast_cli_entry cli_no_debug =
2510 { { "iax", "no", "debug", NULL }, iax_no_debug, "Disable IAX debugging", no_debug_usage };
2512 static int iax_write(struct ast_channel *c, struct ast_frame *f)
2514 struct chan_iax_pvt *i = c->pvt->pvt;
2517 /* If there's an outstanding error, return failure now */
2519 ast_log(LOG_DEBUG, "Write error: %s\n", strerror(errno));
2522 /* If it's already gone, just return */
2525 /* Don't waste bandwidth sending null frames */
2526 if (f->frametype == AST_FRAME_NULL)
2528 /* If we're quelching voice, don't bother sending it */
2529 if ((f->frametype == AST_FRAME_VOICE) && i->quelch)
2531 /* Simple, just queue for transmission */
2532 return iax_send(i, f, 0, -1, 0, 0, 0);
2535 static int __send_command(struct chan_iax_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno,
2536 int now, int transfer, int final)
2540 f.subclass = command;
2541 f.datalen = datalen;
2545 f.src = __FUNCTION__;
2547 return iax_send(i, &f, ts, seqno, now, transfer, final);
2550 static int send_command(struct chan_iax_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2552 return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 0);
2555 #ifdef BRIDGE_OPTIMIZATION
2556 static int forward_command(struct chan_iax_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2558 return __send_command(iaxs[i->bridgecallno], type, command, ts, data, datalen, seqno, 0, 0, 0);
2562 static int send_command_final(struct chan_iax_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2564 /* It is assumed that the callno has already been locked */
2565 iax_predestroy_nolock(i->callno);
2566 return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 1);
2569 static int send_command_immediate(struct chan_iax_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2571 return __send_command(i, type, command, ts, data, datalen, seqno, 1, 0, 0);
2574 static int send_command_transfer(struct chan_iax_pvt *i, char type, int command, unsigned int ts, char *data, int datalen)
2576 return __send_command(i, type, command, ts, data, datalen, 0, 0, 1, 0);
2579 static int apply_context(struct iax_context *con, char *context)
2582 if (!strcmp(con->context, context))
2589 static int iax_getformats(int callno, char *orequest)
2594 strncpy(request, orequest, sizeof(request)-1);
2596 var = strsep(&stringp, ";");
2598 value = strchr(var, '=');
2602 if (!strcmp(var, "formats")) {
2603 iaxs[callno]->peerformat = atoi(value);
2605 ast_log(LOG_WARNING, "Unknown variable '%s' with value '%s'\n", var, value);
2607 var = strsep(&stringp, ";");
2613 static int check_access(int callno, struct sockaddr_in *sin, char *orequest, int requestl)
2615 /* Start pessimistic */
2619 struct iax_user *user;
2621 int gotcapability=0;
2623 strncpy(request, orequest, sizeof(request)-1);
2627 var = strsep(&stringp, ";");
2629 value = strchr(var, '=');
2633 if (!strcmp(var, "exten"))
2634 strncpy(iaxs[callno]->exten, value, sizeof(iaxs[callno]->exten)-1);
2635 else if (!strcmp(var, "callerid"))
2636 strncpy(iaxs[callno]->callerid, value, sizeof(iaxs[callno]->callerid)-1);
2637 else if (!strcmp(var, "ani"))
2638 strncpy(iaxs[callno]->ani, value, sizeof(iaxs[callno]->ani) - 1);
2639 else if (!strcmp(var, "dnid"))
2640 strncpy(iaxs[callno]->dnid, value, sizeof(iaxs[callno]->dnid)-1);
2641 else if (!strcmp(var, "context"))
2642 strncpy(iaxs[callno]->context, value, sizeof(iaxs[callno]->context)-1);
2643 else if (!strcmp(var, "language"))
2644 strncpy(iaxs[callno]->language, value, sizeof(iaxs[callno]->language)-1);
2645 else if (!strcmp(var, "username"))
2646 strncpy(iaxs[callno]->username, value, sizeof(iaxs[callno]->username)-1);
2647 else if (!strcmp(var, "formats"))
2648 iaxs[callno]->peerformat = atoi(value);
2649 else if (!strcmp(var, "adsicpe"))
2650 iaxs[callno]->peeradsicpe = atoi(value);
2651 else if (!strcmp(var, "capability")) {
2653 iaxs[callno]->peercapability = atoi(value);
2654 } else if (!strcmp(var, "version"))
2655 version = atoi(value);
2657 ast_log(LOG_WARNING, "Unknown variable '%s' with value '%s'\n", var, value);
2659 var = strsep(&stringp, ";");
2662 iaxs[callno]->peercapability = iaxs[callno]->peerformat;
2663 if (version > AST_IAX_PROTO_VERSION) {
2664 ast_log(LOG_WARNING, "Peer '%s' has too new a protocol version (%d) for me\n",
2665 inet_ntoa(sin->sin_addr), version);
2668 ast_mutex_lock(&userl.lock);
2669 /* Search the userlist for a compatible entry, and fill in the rest */
2672 if ((!strlen(iaxs[callno]->username) || /* No username specified */
2673 !strcmp(iaxs[callno]->username, user->name)) /* Or this username specified */
2674 && ast_apply_ha(user->ha, sin) /* Access is permitted from this IP */
2675 && (!strlen(iaxs[callno]->context) || /* No context specified */
2676 apply_context(user->contexts, iaxs[callno]->context))) { /* Context is permitted */
2681 #ifdef MYSQL_FRIENDS
2682 if (!user && mysql && strlen(iaxs[callno]->username) && (strlen(iaxs[callno]->username) < 128)) {
2683 user = mysql_user(iaxs[callno]->username);
2684 if (user && strlen(iaxs[callno]->context) && /* No context specified */
2685 !apply_context(user->contexts, iaxs[callno]->context)) { /* Context is permitted */
2687 free(user->contexts);
2693 ast_mutex_unlock(&userl.lock);
2695 /* We found our match (use the first) */
2697 /* Store the requested username if not specified */
2698 if (!strlen(iaxs[callno]->username))
2699 strncpy(iaxs[callno]->username, user->name, sizeof(iaxs[callno]->username)-1);
2700 /* And use the default context */
2701 if (!strlen(iaxs[callno]->context)) {
2703 strncpy(iaxs[callno]->context, user->contexts->context, sizeof(iaxs[callno]->context)-1);
2705 strncpy(iaxs[callno]->context, context, sizeof(iaxs[callno]->context)-1);
2707 /* Copy the secret */
2708 strncpy(iaxs[callno]->secret, user->secret, sizeof(iaxs[callno]->secret)-1);
2709 /* And any input keys */
2710 strncpy(iaxs[callno]->inkeys, user->inkeys, sizeof(iaxs[callno]->inkeys));
2711 /* And the permitted authentication methods */
2712 strncpy(iaxs[callno]->methods, user->methods, sizeof(iaxs[callno]->methods)-1);
2713 /* If they have callerid, override the given caller id. Always store the ANI */
2714 if (strlen(iaxs[callno]->callerid)) {
2715 if (user->hascallerid)
2716 strncpy(iaxs[callno]->callerid, user->callerid, sizeof(iaxs[callno]->callerid)-1);
2717 strncpy(iaxs[callno]->ani, user->callerid, sizeof(iaxs[callno]->ani)-1);
2719 if (strlen(user->accountcode))
2720 strncpy(iaxs[callno]->accountcode, user->accountcode, sizeof(iaxs[callno]->accountcode)-1);
2722 iaxs[callno]->amaflags = user->amaflags;
2728 static int raw_hangup(struct sockaddr_in *sin, short src, short dst)
2730 struct ast_iax_full_hdr fh;
2731 fh.callno = htons(src | AST_FLAG_FULL);
2732 fh.dcallno = htons(dst);
2735 fh.type = AST_FRAME_IAX;
2736 fh.csub = compress_subclass(AST_IAX_COMMAND_INVAL);
2740 ast_log(LOG_DEBUG, "Raw Hangup %s:%d, src=%d, dst=%d\n",
2741 inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), src, dst);
2742 return sendto(netsocket, &fh, sizeof(fh), 0, (struct sockaddr *)sin, sizeof(*sin));
2745 static int authenticate_request(struct chan_iax_pvt *p)
2747 char requeststr[256] = "";
2748 MYSNPRINTF "methods=%s;", p->methods);
2749 if (strstr(p->methods, "md5") || strstr(p->methods, "rsa")) {
2750 /* Build the challenge */
2751 snprintf(p->challenge, sizeof(p->challenge), "%d", rand());
2752 MYSNPRINTF "challenge=%s;", p->challenge);
2754 MYSNPRINTF "username=%s;", p->username);
2755 if (strlen(requeststr))
2756 requeststr[strlen(requeststr) - 1] = '\0';
2757 return send_command(p, AST_FRAME_IAX, AST_IAX_COMMAND_AUTHREQ, 0, requeststr, strlen(requeststr) + 1, -1);
2760 static int authenticate_verify(struct chan_iax_pvt *p, char *orequest)
2762 char requeststr[256] = "";
2763 char *var, *value, request[256];
2764 char md5secret[256] = "";
2765 char secret[256] = "";
2766 char rsasecret[256] = "";
2771 if (!(p->state & IAX_STATE_AUTHENTICATED))
2773 strncpy(request, orequest, sizeof(request)-1);
2775 var = strsep(&stringp, ";");
2777 value = strchr(var, '=');
2781 if (!strcmp(var, "secret"))
2782 strncpy(secret, value, sizeof(secret)-1);
2783 else if (!strcmp(var, "md5secret"))
2784 strncpy(md5secret, value, sizeof(md5secret)-1);
2785 else if (!strcmp(var, "rsasecret"))
2786 strncpy(rsasecret, value, sizeof(rsasecret)-1);
2788 ast_log(LOG_WARNING, "Unknown variable '%s' with value '%s'\n", var, value);
2790 var = strsep(&stringp, ";");
2792 if (strstr(p->methods, "rsa") && strlen(rsasecret) && strlen(p->inkeys)) {
2793 struct ast_key *key;
2797 strncpy(tmpkey, p->inkeys, sizeof(tmpkey));
2799 keyn = strsep(&stringp, ":");
2801 key = ast_key_get(keyn, AST_KEY_PUBLIC);
2802 if (key && !ast_check_signature(key, p->challenge, rsasecret)) {
2806 ast_log(LOG_WARNING, "requested inkey '%s' for RSA authentication does not exist\n", keyn);
2807 keyn = strsep(&stringp, ":");
2809 } else if (strstr(p->methods, "md5")) {
2810 struct MD5Context md5;
2811 unsigned char digest[16];
2813 MD5Update(&md5, p->challenge, strlen(p->challenge));
2814 MD5Update(&md5, p->secret, strlen(p->secret));
2815 MD5Final(digest, &md5);
2816 /* If they support md5, authenticate with it. */
2818 MYSNPRINTF "%2.2x", digest[x]);
2819 if (!strcasecmp(requeststr, md5secret))
2821 } else if (strstr(p->methods, "plaintext")) {
2822 if (!strcmp(secret, p->secret))
2828 static int register_verify(int callno, struct sockaddr_in *sin, char *orequest)
2831 char requeststr[256] = "";
2832 char peer[256] = "";
2833 char md5secret[256] = "";
2834 char rsasecret[256] = "";
2835 char secret[256] = "";
2837 struct ast_key *key;
2845 iaxs[callno]->state &= ~IAX_STATE_AUTHENTICATED;
2846 strcpy(iaxs[callno]->peer, "");
2849 strncpy(request, orequest, sizeof(request)-1);
2851 var = strsep(&stringp, ";");
2853 value = strchr(var, '=');
2857 if (!strcmp(var, "peer"))
2858 strncpy(peer, value, sizeof(peer)-1);
2859 else if (!strcmp(var, "md5secret"))
2860 strncpy(md5secret, value, sizeof(md5secret)-1);
2861 else if (!strcmp(var, "rsasecret"))
2862 strncpy(rsasecret, value, sizeof(rsasecret)-1);
2863 else if (!strcmp(var, "secret"))
2864 strncpy(secret, value, sizeof(secret)-1);
2865 else if (!strcmp(var, "refresh"))
2866 expire = atoi(value);
2868 ast_log(LOG_WARNING, "Unknown variable '%s' with value '%s'\n", var, value);
2870 var = strsep(&stringp, ";");
2873 if (!strlen(peer)) {
2874 ast_log(LOG_NOTICE, "Empty registration from %s\n", inet_ntoa(sin->sin_addr));
2878 for (p = peerl.peers; p ; p = p->next)
2879 if (!strcasecmp(p->name, peer))
2882 #ifdef MYSQL_FRIENDS
2884 p = mysql_peer(peer);
2887 ast_log(LOG_NOTICE, "No registration for peer '%s' (from %s)\n", peer, inet_ntoa(sin->sin_addr));
2892 ast_log(LOG_NOTICE, "Peer '%s' is not dynamic (from %s)\n", peer, inet_ntoa(sin->sin_addr));
2898 if (!ast_apply_ha(p->ha, sin)) {
2899 ast_log(LOG_NOTICE, "Host %s denied access to register peer '%s'\n", inet_ntoa(sin->sin_addr), p->name);
2904 strncpy(iaxs[callno]->secret, p->secret, sizeof(iaxs[callno]->secret)-1);
2905 strncpy(iaxs[callno]->inkeys, p->inkeys, sizeof(iaxs[callno]->inkeys)-1);
2906 /* Check secret against what we have on file */
2907 if (strlen(rsasecret) && strstr(p->methods, "rsa") && strlen(iaxs[callno]->challenge)) {
2908 if (strlen(p->inkeys)) {
2911 strncpy(tmpkeys, p->inkeys, sizeof(tmpkeys));
2913 keyn = strsep(&stringp, ":");
2915 key = ast_key_get(keyn, AST_KEY_PUBLIC);
2916 if (key && !ast_check_signature(key, iaxs[callno]->challenge, rsasecret)) {
2917 iaxs[callno]->state |= IAX_STATE_AUTHENTICATED;
2920 ast_log(LOG_WARNING, "requested inkey '%s' does not exist\n", keyn);
2921 keyn = strsep(&stringp, ":");
2924 ast_log(LOG_NOTICE, "Host %s failed RSA authentication with inkeys '%s'\n", peer, p->inkeys);
2930 ast_log(LOG_NOTICE, "Host '%s' trying to do RSA authentication, but we have no inkeys\n", peer);
2935 } else if (strlen(secret) && strstr(p->methods, "plaintext")) {
2936 /* They've provided a plain text password and we support that */
2937 if (strcmp(secret, p->secret)) {
2938 ast_log(LOG_NOTICE, "Host %s did not provide proper plaintext password for '%s'\n", inet_ntoa(sin->sin_addr), p->name);
2943 iaxs[callno]->state |= IAX_STATE_AUTHENTICATED;
2944 } else if (strlen(md5secret) && strstr(p->methods, "md5") && strlen(iaxs[callno]->challenge)) {
2945 struct MD5Context md5;
2946 unsigned char digest[16];
2948 MD5Update(&md5, iaxs[callno]->challenge, strlen(iaxs[callno]->challenge));
2949 MD5Update(&md5, p->secret, strlen(p->secret));
2950 MD5Final(digest, &md5);
2952 MYSNPRINTF "%2.2x", digest[x]);
2953 if (strcasecmp(requeststr, md5secret)) {
2954 ast_log(LOG_NOTICE, "Host %s failed MD5 authentication for '%s' (%s != %s)\n", inet_ntoa(sin->sin_addr), p->name, requeststr, md5secret);
2959 iaxs[callno]->state |= IAX_STATE_AUTHENTICATED;
2960 } else if (strlen(md5secret) || strlen(secret)) {
2961 ast_log(LOG_NOTICE, "Inappropriate authentication received\n");
2966 strncpy(iaxs[callno]->peer, peer, sizeof(iaxs[callno]->peer)-1);
2967 /* Choose lowest expirey number */
2968 if (expire && (expire < iaxs[callno]->expirey))
2969 iaxs[callno]->expirey = expire;
2976 static int authenticate(char *challenge, char *secret, char *keyn, char *methods, char *requeststr, int reqsize, struct sockaddr_in *sin)
2980 if (keyn && strlen(keyn)) {
2981 if (!strstr(methods, "rsa")) {
2982 if (!secret || !strlen(secret))
2983 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));
2984 } else if (!strlen(challenge)) {
2985 ast_log(LOG_NOTICE, "No challenge provided for RSA authentication to %s\n", inet_ntoa(sin->sin_addr));
2988 struct ast_key *key;
2989 key = ast_key_get(keyn, AST_KEY_PRIVATE);
2991 ast_log(LOG_NOTICE, "Unable to find private key '%s'\n", keyn);
2993 if (ast_sign(key, challenge, sig)) {
2994 ast_log(LOG_NOTICE, "Unable to sign challenge withy key\n");
2997 MYSNPRINTF2 "rsasecret=%s;", sig);
3004 if (res && secret && strlen(secret)) {
3005 if (strstr(methods, "md5") && strlen(challenge)) {
3006 struct MD5Context md5;
3007 unsigned char digest[16];
3009 MD5Update(&md5, challenge, strlen(challenge));
3010 MD5Update(&md5, secret, strlen(secret));
3011 MD5Final(digest, &md5);
3012 /* If they support md5, authenticate with it. */
3013 MYSNPRINTF2 "md5secret=");
3015 MYSNPRINTF2 "%2.2x", digest[x]);
3018 } else if (strstr(methods, "plaintext")) {
3019 MYSNPRINTF2 "secret=%s;", secret);
3022 ast_log(LOG_NOTICE, "No way to send secret to peer '%s' (their methods: %s)\n", inet_ntoa(sin->sin_addr), methods);
3027 static int authenticate_reply(struct chan_iax_pvt *p, struct sockaddr_in *sin, char *orequest, char *override, char *okey)
3029 struct iax_peer *peer;
3030 /* Start pessimistic */
3033 char methods[80] = "";
3034 char requeststr[256] = "";
3038 strncpy(request, orequest, sizeof(request)-1);
3040 var = strsep(&stringp, ";");
3042 value = strchr(var, '=');
3046 if (!strcmp(var, "username"))
3047 strncpy(p->username, value, sizeof(p->username)-1);
3048 else if (!strcmp(var, "challenge"))
3049 strncpy(p->challenge, value, sizeof(p->challenge)-1);
3050 else if (!strcmp(var, "methods"))
3051 strncpy(methods, value, sizeof(methods)-1);
3053 ast_log(LOG_WARNING, "Unknown variable '%s' with value '%s'\n", var, value);
3055 var = strsep(&stringp, ";");
3058 /* Check for override RSA authentication first */
3059 if ((override && strlen(override)) || (okey && strlen(okey))) {
3060 /* Normal password authentication */
3061 res = authenticate(p->challenge, override, okey, methods, requeststr, sizeof(requeststr), sin);
3063 ast_mutex_lock(&peerl.lock);
3066 if ((!strlen(p->peer) || !strcmp(p->peer, peer->name))
3067 /* No peer specified at our end, or this is the peer */
3068 && (!strlen(peer->username) || (!strcmp(peer->username, p->username)))
3069 /* No username specified in peer rule, or this is the right username */
3070 && (!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)))
3071 /* No specified host, or this is our host */
3073 res = authenticate(p->challenge, peer->secret, peer->outkey, methods, requeststr, sizeof(requeststr), sin);
3079 ast_mutex_unlock(&peerl.lock);
3081 if (strlen(requeststr))
3082 requeststr[strlen(requeststr)-1] = '\0';
3084 res = send_command(p, AST_FRAME_IAX, AST_IAX_COMMAND_AUTHREP, 0, requeststr, strlen(requeststr) + 1, -1);
3088 static int iax_do_register(struct iax_registry *reg);
3090 static int iax_do_register_s(void *data)
3092 struct iax_registry *reg = data;
3094 iax_do_register(reg);
3098 static int try_transfer(struct chan_iax_pvt *pvt, char *orequest)
3102 char newip[256] = "";
3103 char request[256] = "";
3106 struct sockaddr_in new;
3112 strncpy(request, orequest, sizeof(request)-1);
3114 var = strsep(&stringp, ";");
3116 value = strchr(var, '=');
3120 if (!strcmp(var, "remip"))
3121 strncpy(newip, value, sizeof(newip)-1);
3122 else if (!strcmp(var, "remport"))
3123 newport = atoi(value);
3124 else if (!strcmp(var, "remcall"))
3125 newcall = atoi(value);
3127 ast_log(LOG_WARNING, "Unknown variable '%s' with value '%s'\n", var, value);
3129 var = strsep(&stringp, ";");
3131 if (!newcall || !inet_aton(newip, &new.sin_addr) || !newport) {
3132 ast_log(LOG_WARNING, "Invalid transfer request\n");
3135 pvt->transfercallno = newcall;
3136 inet_aton(newip, &pvt->transfer.sin_addr);
3137 pvt->transfer.sin_port = htons(newport);
3138 pvt->transfer.sin_family = AF_INET;
3139 pvt->transferring = TRANSFER_BEGIN;
3140 send_command_transfer(pvt, AST_FRAME_IAX, AST_IAX_COMMAND_TXCNT, 0, NULL, 0);
3144 static int complete_dpreply(struct chan_iax_pvt *pvt, char *orequest)
3147 char request[256] = "";
3148 char exten[256] = "";
3149 int status = CACHE_FLAG_UNKNOWN;
3150 int expirey = iaxdefaultdpcache;
3153 struct iax_dpcache *dp, *prev;
3156 strncpy(request, orequest, sizeof(request)-1);
3158 var = strsep(&stringp, ";");
3160 value = strchr(var, '=');
3164 if (!strcmp(var, "number"))
3165 strncpy(exten, value, sizeof(exten)-1);
3166 else if (!strcmp(var, "status")) {
3167 if (!strcasecmp(value, "exists"))
3168 status = CACHE_FLAG_EXISTS;
3169 else if (!strcasecmp(value, "nonexistant"))
3170 status = CACHE_FLAG_NONEXISTANT;
3171 else if (!strcasecmp(value, "canexist"))
3172 status = CACHE_FLAG_CANEXIST;
3174 ast_log(LOG_WARNING, "Unknown status '%s'\n", value);
3175 } else if (!strcmp(var, "expirey"))
3176 expirey = atoi(value);
3177 else if (!strcmp(var, "ignorepat")) {
3178 /* Don' really do much with it */
3179 } else if (!strcmp(var, "matchmore")) {
3180 matchmore = CACHE_FLAG_MATCHMORE;
3182 ast_log(LOG_WARNING, "Unknown variable '%s' with value '%s'\n", var, value);
3184 var = strsep(&stringp, ";");
3186 ast_mutex_lock(&dpcache_lock);
3188 dp = pvt->dpentries;
3190 if (!strcmp(dp->exten, exten)) {
3193 prev->peer = dp->peer;
3195 pvt->dpentries = dp->peer;
3198 dp->expirey.tv_sec = dp->orig.tv_sec + expirey;
3199 if (dp->flags & CACHE_FLAG_PENDING) {
3200 dp->flags &= ~CACHE_FLAG_PENDING;
3201 dp->flags |= status;
3202 dp->flags |= CACHE_FLAG_MATCHMORE;
3204 /* Wake up waiters */
3205 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
3206 if (dp->waiters[x] > -1)
3207 write(dp->waiters[x], "asdf", 4);
3212 ast_mutex_unlock(&dpcache_lock);
3216 static int complete_transfer(int callno, char *orequest)
3218 int peercallno = -1;
3219 char request[256] = "";
3221 struct chan_iax_pvt *pvt = iaxs[callno];
3222 struct ast_iax_frame *cur;
3227 strncpy(request, orequest, sizeof(request)-1);
3229 var = strsep(&stringp, ";");
3231 value = strchr(var, '=');
3235 if (!strcmp(var, "peercallno"))
3236 peercallno = atoi(value);
3238 ast_log(LOG_WARNING, "Unknown variable '%s' with value '%s'\n", var, value);
3240 var = strsep(&stringp, ";");
3242 if (peercallno < 0) {
3243 ast_log(LOG_WARNING, "Invalid transfer request\n");
3246 memcpy(&pvt->addr, &pvt->transfer, sizeof(pvt->addr));
3247 memset(&pvt->transfer, 0, sizeof(pvt->transfer));
3248 /* Reset sequence numbers */
3251 pvt->peercallno = peercallno;
3252 pvt->transferring = TRANSFER_NONE;
3253 pvt->svoiceformat = -1;
3254 pvt->voiceformat = 0;
3255 pvt->transfercallno = -1;
3256 memset(&pvt->rxcore, 0, sizeof(pvt->rxcore));
3257 memset(&pvt->offset, 0, sizeof(pvt->offset));
3258 memset(&pvt->history, 0, sizeof(pvt->history));
3259 pvt->jitterbuffer = 0;
3261 pvt->historicjitter = 0;
3265 pvt->pingtime = DEFAULT_RETRY_TIME;
3266 ast_mutex_lock(&iaxq.lock);
3267 for (cur = iaxq.head; cur ; cur = cur->next) {
3268 /* We must cancel any packets that would have been transmitted
3269 because now we're talking to someone new. It's okay, they
3270 were transmitted to someone that didn't care anyway. */
3271 if (callno == cur->callno)
3274 ast_mutex_unlock(&iaxq.lock);
3278 static int iax_ack_registry(char *orequest, struct sockaddr_in *sin, int callno)
3280 struct iax_registry *reg;
3281 /* Start pessimistic */
3282 char request[256] = "";
3283 char peer[256] = "";
3286 char ourip[256] = "<Unspecified>";
3287 struct sockaddr_in oldus;
3294 strncpy(request, orequest, sizeof(request)-1);
3296 var = strsep(&stringp, ";");
3298 value = strchr(var, '=');
3302 if (!strcmp(var, "yourip"))
3303 strncpy(ourip, value, sizeof(ourip)-1);
3304 else if (!strcmp(var, "peer"))
3305 strncpy(peer, value, sizeof(peer)-1);
3306 else if (!strcmp(var, "yourport"))
3307 ourport = atoi(value);
3308 else if (!strcmp(var, "refresh"))
3309 refresh = atoi(value);
3310 else if (!strcmp(var, "callerid")) {
3311 /* We don't really care about suggested Caller*ID, that's more for phones */
3313 ast_log(LOG_WARNING, "Unknown variable '%s' with value '%s'\n", var, value);
3315 var = strsep(&stringp, ";");
3317 reg = iaxs[callno]->reg;
3318 memcpy(&oldus, ®->us, sizeof(oldus));
3319 if (memcmp(®->addr, sin, sizeof(®->addr))) {
3320 ast_log(LOG_WARNING, "Received unsolicited registry ack from '%s'\n", inet_ntoa(sin->sin_addr));
3323 if (!inet_aton(ourip, ®->us.sin_addr)) {
3324 ast_log(LOG_WARNING, "Registry ack from '%s' contains invalid IP '%s'\n", inet_ntoa(sin->sin_addr), ourip);
3327 reg->us.sin_port = htons(ourport);
3328 if (refresh && (reg->refresh < refresh)) {
3329 /* Refresh faster if necessary */
3330 reg->refresh = refresh;
3331 if (reg->expire > -1)
3332 ast_sched_del(sched, reg->expire);
3333 reg->expire = ast_sched_add(sched, (5 * reg->refresh / 6) * 1000, iax_do_register_s, reg);
3335 if (memcmp(&oldus, ®->us, sizeof(oldus)) && (option_verbose > 2)) {
3336 snprintf(ourip, sizeof(ourip), "%s:%d", inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
3337 ast_verbose(VERBOSE_PREFIX_3 "Registered to '%s', who sees us as %s\n", inet_ntoa(sin->sin_addr), ourip);
3339 reg->regstate = REG_STATE_REGISTERED;
3341 ast_log(LOG_WARNING, "Registry acknowledge on unknown registery '%s'\n", peer);
3345 static int iax_register(char *value, int lineno)
3347 struct iax_registry *reg;
3349 char *username, *hostname, *secret;
3356 strncpy(copy, value, sizeof(copy)-1);
3358 username = strsep(&stringp, "@");
3359 hostname = strsep(&stringp, "@");
3361 ast_log(LOG_WARNING, "Format for registration is user[:secret]@host[:port] at line %d", lineno);
3365 username = strsep(&stringp, ":");
3366 secret = strsep(&stringp, ":");
3368 hostname = strsep(&stringp, ":");
3369 porta = strsep(&stringp, ":");
3371 if (porta && !atoi(porta)) {
3372 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
3375 hp = gethostbyname(hostname);
3377 ast_log(LOG_WARNING, "Host '%s' not found at line %d\n", hostname, lineno);
3380 reg = malloc(sizeof(struct iax_registry));
3382 memset(reg, 0, sizeof(struct iax_registry));
3383 strncpy(reg->username, username, sizeof(reg->username)-1);
3385 strncpy(reg->secret, secret, sizeof(reg->secret)-1);
3387 reg->refresh = AST_DEFAULT_REG_EXPIRE;
3388 reg->addr.sin_family = AF_INET;
3389 memcpy(®->addr.sin_addr, hp->h_addr, sizeof(®->addr.sin_addr));
3390 reg->addr.sin_port = porta ? htons(atoi(porta)) : htons(AST_DEFAULT_IAX_PORTNO);
3391 reg->next = registrations;
3393 registrations = reg;
3395 ast_log(LOG_ERROR, "Out of memory\n");
3401 static int expire_registry(void *data)
3403 struct iax_peer *p = data;
3404 /* Reset the address */
3405 memset(&p->addr, 0, sizeof(p->addr));
3406 /* Reset expire notice */
3408 /* Reset expirey value */
3409 p->expirey = expirey;
3411 iax_regfunk(p->name, 0);
3416 static int iax_poke_peer(struct iax_peer *peer);
3419 static int update_registry(char *name, struct sockaddr_in *sin, int callno)
3421 /* Called from IAX thread only, with proper iaxsl lock */
3422 char requeststr[256] = "";
3424 for (p = peerl.peers;p;p = p->next) {
3425 if (!strcasecmp(name, p->name)) {
3429 #ifdef MYSQL_FRIENDS
3431 p = mysql_peer(name);
3434 #ifdef MYSQL_FRIENDS
3436 mysql_update_peer(name, sin);
3438 if (memcmp(&p->addr, sin, sizeof(p->addr))) {
3440 iax_regfunk(p->name, 1);
3441 if (option_verbose > 2)
3442 ast_verbose(VERBOSE_PREFIX_3 "Registered '%s' (%s) at %s:%d\n", p->name,
3443 iaxs[callno]->state & IAX_STATE_AUTHENTICATED ? "AUTHENTICATED" : "UNAUTHENTICATED", inet_ntoa(sin->sin_addr), htons(sin->sin_port));
3446 /* Update the host */
3447 memcpy(&p->addr, sin, sizeof(p->addr));
3448 /* Setup the expirey */
3450 ast_sched_del(sched, p->expire);
3452 p->expire = ast_sched_add(sched, p->expirey * 1000, expire_registry, (void *)p);
3453 MYSNPRINTF "peer=%s;yourip=%s;yourport=%d;refresh=%d;",
3454 p->name, inet_ntoa(p->addr.sin_addr), ntohs(p->addr.sin_port), p->expirey);
3456 MYSNPRINTF "callerid=%s;", p->callerid);
3457 requeststr[strlen(requeststr)-1] = '\0';
3460 return send_command_final(iaxs[callno], AST_FRAME_IAX, AST_IAX_COMMAND_REGACK, 0, requeststr, strlen(requeststr) + 1, -1);;
3462 ast_log(LOG_WARNING, "No such peer '%s'\n", name);
3466 static int registry_authrequest(char *name, int callno)
3468 char requeststr[256] = "";
3470 for (p = peerl.peers;p;p = p->next) {
3471 if (!strcasecmp(name, p->name)) {
3475 #ifdef MYSQL_FRIENDS
3477 p = mysql_peer(name);
3480 MYSNPRINTF "methods=%s;", p->methods);
3481 if (strstr(p->methods, "md5") || strstr(p->methods, "rsa")) {
3482 /* Build the challenge */
3483 snprintf(iaxs[callno]->challenge, sizeof(iaxs[callno]->challenge), "%d", rand());
3484 MYSNPRINTF "challenge=%s;", iaxs[callno]->challenge);
3486 MYSNPRINTF "peer=%s;", name);
3487 requeststr[strlen(requeststr)-1] = '\0';
3490 return send_command(iaxs[callno], AST_FRAME_IAX, AST_IAX_COMMAND_REGAUTH, 0, requeststr, strlen(requeststr) + 1, -1);