2 * Asterisk -- A telephony toolkit for Linux.
4 * Implementation of Inter-Asterisk eXchange Version 2
6 * Copyright (C) 2003, Digium
8 * Mark Spencer <markster@digium.com>
10 * This program is free software, distributed under the terms of
11 * the GNU General Public License
14 #include <asterisk/lock.h>
15 #include <asterisk/frame.h>
16 #include <asterisk/channel.h>
17 #include <asterisk/channel_pvt.h>
18 #include <asterisk/logger.h>
19 #include <asterisk/module.h>
20 #include <asterisk/pbx.h>
21 #include <asterisk/sched.h>
22 #include <asterisk/io.h>
23 #include <asterisk/config.h>
24 #include <asterisk/options.h>
25 #include <asterisk/cli.h>
26 #include <asterisk/translate.h>
27 #include <asterisk/md5.h>
28 #include <asterisk/cdr.h>
29 #include <asterisk/crypto.h>
30 #include <asterisk/acl.h>
31 #include <asterisk/manager.h>
32 #include <asterisk/callerid.h>
33 #include <asterisk/app.h>
34 #include <asterisk/astdb.h>
35 #include <asterisk/musiconhold.h>
36 #include <arpa/inet.h>
37 #include <sys/socket.h>
38 #include <netinet/in.h>
39 #include <netinet/in_systm.h>
40 #include <netinet/ip.h>
42 #include <sys/signal.h>
51 #include <sys/ioctl.h>
52 #include <linux/zaptel.h>
55 #include <mysql/mysql.h>
58 #include "iax2-parser.h"
61 #define IPTOS_MINCOST 0x02
65 * Uncomment to try experimental IAX bridge optimization,
66 * designed to reduce latency when IAX calls cannot
70 #define BRIDGE_OPTIMIZATION
73 #define DEFAULT_RETRY_TIME 1000
74 #define MEMORY_SIZE 100
75 #define DEFAULT_DROP 3
76 /* Flag to use with trunk calls, keeping these calls high up. It halves our effective use
77 but keeps the division between trunked and non-trunked better. */
78 #define TRUNK_CALL_START 0x4000
82 #define MIN_REUSE_TIME 60 /* Don't reuse a call number within 60 seconds */
84 /* Sample over last 100 units to determine historic jitter */
88 static ast_mutex_t mysqllock = AST_MUTEX_INITIALIZER;
90 static char mydbuser[80];
91 static char mydbpass[80];
92 static char mydbhost[80];
93 static char mydbname[80];
95 static char *desc = "Inter Asterisk eXchange (Ver 2)";
96 static char *tdesc = "Inter Asterisk eXchange Driver (Ver 2)";
97 static char *type = "IAX2";
99 static char context[80] = "default";
101 static int max_retries = 4;
102 static int ping_time = 20;
103 static int lagrq_time = 10;
104 static int maxtrunkcall = TRUNK_CALL_START;
105 static int maxnontrunkcall = 1;
106 static int maxjitterbuffer=3000;
107 static int trunkfreq = 20;
109 static int iaxdefaultdpcache=10 * 60; /* Cache dialplan entries for 10 minutes by default */
111 static int iaxdefaulttimeout = 5; /* Default to wait no more than 5 seconds for a reply to come back */
113 static int netsocket = -1;
117 static int expirey = IAX_DEFAULT_REG_EXPIRE;
119 static int timingfd = -1; /* Timing file descriptor */
122 static ast_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
124 int (*iax2_regfunk)(char *username, int onoff) = NULL;
127 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
129 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
130 ~AST_FORMAT_SLINEAR & \
134 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
138 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
142 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
143 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
144 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
146 static struct io_context *io;
147 static struct sched_context *sched;
149 static int iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
151 static int iax2_dropcount = DEFAULT_DROP;
153 static int use_jitterbuffer = 0;
155 static int iaxdebug = 0;
157 static int iaxtrunkdebug = 0;
159 static char accountcode[20];
160 static int amaflags = 0;
161 static int notransfer = 0;
163 static pthread_t netthreadid;
165 #define IAX_STATE_STARTED (1 << 0)
166 #define IAX_STATE_AUTHENTICATED (1 << 1)
167 #define IAX_STATE_TBD (1 << 2)
169 struct iax2_context {
170 char context[AST_MAX_EXTENSION];
171 struct iax2_context *next;
178 char accountcode[20];
179 char inkeys[80]; /* Key(s) this user can use to authenticate to us */
185 char callerid[AST_MAX_EXTENSION];
187 struct iax2_context *contexts;
188 struct iax2_user *next;
196 char outkey[80]; /* What key we use to talk to this peer */
197 char context[AST_MAX_EXTENSION]; /* Default context (for transfer really) */
198 char mailbox[AST_MAX_EXTENSION]; /* Mailbox */
199 struct sockaddr_in addr;
203 /* Dynamic Registration fields */
204 int dynamic; /* If this is a dynamic peer */
205 struct sockaddr_in defaddr; /* Default address if there is one */
206 int authmethods; /* Authentication methods (IAX_AUTH_*) */
207 char inkeys[80]; /* Key(s) this peer can use to authenticate to us */
210 /* Suggested caller id if registering */
211 char callerid[AST_MAX_EXTENSION];
212 /* Whether or not to send ANI */
214 int expire; /* Schedule entry for expirey */
215 int expirey; /* How soon to expire */
216 int capability; /* Capability */
217 int delme; /* I need to be deleted */
218 int trunk; /* Treat as an IAX trunking */
219 struct timeval txtrunktime; /* Transmit trunktime */
220 struct timeval rxtrunktime; /* Receive trunktime */
221 struct timeval lasttxtime; /* Last transmitted trunktime */
222 unsigned int lastsent; /* Last sent time */
225 int callno; /* Call number of POKE request */
226 int pokeexpire; /* When to expire poke */
227 int lastms; /* How long last response took (in ms), or -1 for no response */
228 int maxms; /* Max ms we will accept for the host to be up, 0 to not monitor */
231 struct iax2_peer *next;
235 #define REG_STATE_UNREGISTERED 0
236 #define REG_STATE_REGSENT 1
237 #define REG_STATE_AUTHSENT 2
238 #define REG_STATE_REGISTERED 3
239 #define REG_STATE_REJECTED 4
240 #define REG_STATE_TIMEOUT 5
241 #define REG_STATE_NOAUTH 6
243 #define TRANSFER_NONE 0
244 #define TRANSFER_BEGIN 1
245 #define TRANSFER_READY 2
246 #define TRANSFER_RELEASED 3
247 #define TRANSFER_PASSTHROUGH 4
249 struct iax2_registry {
250 struct sockaddr_in addr; /* Who we connect to for registration purposes */
252 char secret[80]; /* Password or key name in []'s */
254 int expire; /* Sched ID of expiration */
255 int refresh; /* How often to refresh */
257 int messages; /* Message count */
258 int callno; /* Associated call number if applicable */
259 struct sockaddr_in us; /* Who the server thinks we are */
260 struct iax2_registry *next;
263 static struct iax2_registry *registrations;
265 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
266 #define MIN_RETRY_TIME 100
267 #define MAX_RETRY_TIME 10000
268 #define MAX_JITTER_BUFFER 50
270 #define MAX_TRUNKDATA 640 /* 40ms, uncompressed linear */
272 /* If we have more than this much excess real jitter buffer, srhink it. */
273 static int max_jitter_buffer = MAX_JITTER_BUFFER;
275 struct chan_iax2_pvt {
276 /* Pipes for communication. pipe[1] belongs to the
277 network thread (write), and pipe[0] belongs to the individual
279 /* Whether or not we Quelch audio */
281 /* Last received voice format */
283 /* Last received voice format */
285 /* Last sent voice format */
287 /* Last sent video format */
289 /* What we are capable of sending */
291 /* Last received timestamp */
293 /* Last sent timestamp - never send the same timestamp twice in a single call */
294 unsigned int lastsent;
296 unsigned int pingtime;
297 /* Max time for initial response */
300 struct sockaddr_in addr;
301 /* Our call number */
302 unsigned short callno;
304 unsigned short peercallno;
305 /* Peer selected format */
307 /* Peer capability */
309 /* timeval that we base our transmission on */
310 struct timeval offset;
311 /* timeval that we base our delivery on */
312 struct timeval rxcore;
313 /* Historical delivery time */
314 int history[MEMORY_SIZE];
315 /* Current base jitterbuffer */
317 /* Current jitter measure */
319 /* Historic jitter value */
323 /* Error, as discovered by the manager */
325 /* Owner if we have one */
326 struct ast_channel *owner;
327 /* What's our state? */
329 /* Expirey (optional) */
331 /* Next outgoing sequence number */
332 unsigned char oseqno;
333 /* Next sequence number they have not yet acknowledged */
334 unsigned char rseqno;
335 /* Next incoming sequence number */
336 unsigned char iseqno;
337 /* Last incoming sequence number we have acknowledged */
338 unsigned char aseqno;
341 /* Default Context */
343 /* Caller ID if available */
345 /* Hidden Caller ID (i.e. ANI) if appropriate */
347 /* Whether or not ani should be transmitted in addition to Caller*ID */
349 /* Whether to request autoanswer */
353 /* Requested Extension */
354 char exten[AST_MAX_EXTENSION];
355 /* Expected Username */
357 /* Expected Secret */
359 /* permitted authentication methods */
363 /* Public keys permitted keys for incoming authentication */
365 /* Private key for outgoing authentication */
367 /* Preferred language */
369 /* Hostname/peername for naming purposes */
371 /* Associated registry */
372 struct iax2_registry *reg;
373 /* Associated peer for poking */
374 struct iax2_peer *peerpoke;
376 /* Transferring status */
378 /* Transfer identifier */
380 /* Already disconnected */
382 /* Who we are IAX transfering to */
383 struct sockaddr_in transfer;
384 /* What's the new call number for the transfer */
385 unsigned short transfercallno;
387 /* Status of knowledge of peer ADSI capability */
390 /* Who we are bridged to */
391 unsigned short bridgecallno;
392 unsigned int bridgesfmt;
393 struct ast_trans_pvt *bridgetrans;
395 int pingid; /* Transmit PING request */
396 int lagid; /* Retransmit lag request */
397 int autoid; /* Auto hangup for Dialplan requestor */
398 int initid; /* Initial peer auto-congest ID (based on qualified peers) */
399 char dproot[AST_MAX_EXTENSION];
400 char accountcode[20];
402 /* This is part of a trunk interface */
404 /* Trunk data and length */
405 unsigned char trunkdata[MAX_TRUNKDATA];
406 unsigned int trunkdatalen;
408 struct iax2_dpcache *dpentries;
409 int notransfer; /* do we want native bridging */
412 static struct ast_iax2_queue {
413 struct iax_frame *head;
414 struct iax_frame *tail;
419 static struct ast_user_list {
420 struct iax2_user *users;
424 static struct ast_peer_list {
425 struct iax2_peer *peers;
429 /* Extension exists */
430 #define CACHE_FLAG_EXISTS (1 << 0)
431 /* Extension is non-existant */
432 #define CACHE_FLAG_NONEXISTANT (1 << 1)
433 /* Extension can exist */
434 #define CACHE_FLAG_CANEXIST (1 << 2)
435 /* Waiting to hear back response */
436 #define CACHE_FLAG_PENDING (1 << 3)
438 #define CACHE_FLAG_TIMEOUT (1 << 4)
439 /* Request transmitted */
440 #define CACHE_FLAG_TRANSMITTED (1 << 5)
442 #define CACHE_FLAG_UNKNOWN (1 << 6)
444 #define CACHE_FLAG_MATCHMORE (1 << 7)
446 static struct iax2_dpcache {
447 char peercontext[AST_MAX_EXTENSION];
448 char exten[AST_MAX_EXTENSION];
450 struct timeval expirey;
452 unsigned short callno;
454 struct iax2_dpcache *next;
455 struct iax2_dpcache *peer; /* For linking in peers */
458 static ast_mutex_t dpcache_lock;
460 static void iax_debug_output(const char *data)
465 static void iax_error_output(const char *data)
467 ast_log(LOG_WARNING, data);
470 /* XXX We probably should use a mutex when working with this XXX */
471 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS];
472 static ast_mutex_t iaxsl[IAX_MAX_CALLS];
473 static struct timeval lastused[IAX_MAX_CALLS];
476 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, char *, int, int);
477 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, char *, int, int);
478 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, char *, int, int);
479 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, char *, int);
481 static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts);
483 static int send_ping(void *data)
485 int callno = (long)data;
486 /* Ping only if it's real, not if it's bridged */
488 #ifdef BRIDGE_OPTIMIZATION
489 if (!iaxs[callno]->bridgecallno)
491 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
497 static int send_lagrq(void *data)
499 int callno = (long)data;
500 /* Ping only if it's real not if it's bridged */
502 #ifdef BRIDGE_OPTIMIZATION
503 if (!iaxs[callno]->bridgecallno)
505 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
511 static unsigned char compress_subclass(int subclass)
515 /* If it's 128 or smaller, just return it */
516 if (subclass < IAX_FLAG_SC_LOG)
518 /* Otherwise find its power */
519 for (x = 0; x < IAX_MAX_SHIFT; x++) {
520 if (subclass & (1 << x)) {
522 ast_log(LOG_WARNING, "Can't compress subclass %d\n", subclass);
528 return power | IAX_FLAG_SC_LOG;
531 static int uncompress_subclass(unsigned char csub)
533 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
534 if (csub & IAX_FLAG_SC_LOG) {
535 /* special case for 'compressed' -1 */
539 return 1 << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
545 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len, int lockpeer)
547 struct iax2_peer *peer;
550 ast_mutex_lock(&peerl.lock);
553 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
554 (peer->addr.sin_port == sin.sin_port)) {
555 strncpy(host, peer->name, len-1);
562 ast_mutex_unlock(&peerl.lock);
566 static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, int lockpeer)
568 struct chan_iax2_pvt *tmp;
569 tmp = malloc(sizeof(struct chan_iax2_pvt));
571 memset(tmp, 0, sizeof(struct chan_iax2_pvt));
574 tmp->transfercallno = 0;
575 tmp->bridgecallno = 0;
580 /* strncpy(tmp->context, context, sizeof(tmp->context)-1); */
581 strncpy(tmp->exten, "s", sizeof(tmp->exten)-1);
582 if (!iax2_getpeername(*sin, tmp->host, sizeof(tmp->host), lockpeer))
583 snprintf(tmp->host, sizeof(tmp->host), "%s:%d", inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
588 static int get_samples(struct ast_frame *f)
591 switch(f->subclass) {
592 case AST_FORMAT_SPEEX:
593 samples = 160; /* XXX Not necessarily true XXX */
595 case AST_FORMAT_G723_1:
596 samples = 240 /* XXX Not necessarily true XXX */;
598 case AST_FORMAT_ILBC:
599 samples = 240 * (f->datalen / 50);
602 samples = 160 * (f->datalen / 33);
604 case AST_FORMAT_G729A:
605 samples = 160 * (f->datalen / 20);
607 case AST_FORMAT_SLINEAR:
608 samples = f->datalen / 2;
610 case AST_FORMAT_LPC10:
612 samples += (((char *)(f->data))[7] & 0x1) * 8;
614 case AST_FORMAT_ULAW:
615 samples = f->datalen;
617 case AST_FORMAT_ALAW:
618 samples = f->datalen;
620 case AST_FORMAT_ADPCM:
621 samples = f->datalen *2;
624 ast_log(LOG_WARNING, "Don't know how to calculate samples on %d packets\n", f->subclass);
629 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
631 /* Malloc() a copy of a frame */
632 struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen);
634 memcpy(new, fr, sizeof(struct iax_frame));
635 iax_frame_wrap(new, &fr->af);
638 new->direction = DIRECTION_INGRESS;
644 #define NEW_PREVENT 0
648 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, struct chan_iax2_pvt *cur)
650 if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
651 (cur->addr.sin_port == sin->sin_port)) {
652 /* This is the main host */
653 if ((cur->peercallno == callno) ||
654 ((dcallno == cur->callno) && !cur->peercallno)) {
655 /* That's us. Be sure we keep track of the peer call number */
659 if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
660 (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
661 /* We're transferring */
662 if (dcallno == cur->callno)
668 static void update_max_trunk(void)
670 int max = TRUNK_CALL_START;
672 /* XXX Prolly don't need locks here XXX */
673 for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
679 ast_log(LOG_DEBUG, "New max trunk callno is %d\n", max);
682 static void update_max_nontrunk(void)
686 /* XXX Prolly don't need locks here XXX */
687 for (x=1;x<TRUNK_CALL_START - 1; x++) {
691 maxnontrunkcall = max;
693 ast_log(LOG_DEBUG, "New max nontrunk callno is %d\n", max);
696 static int make_trunk(unsigned short callno, int locked)
701 if (iaxs[callno]->oseqno) {
702 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
705 if (callno & TRUNK_CALL_START) {
706 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
709 gettimeofday(&now, NULL);
710 for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
711 ast_mutex_lock(&iaxsl[x]);
712 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) {
713 iaxs[x] = iaxs[callno];
716 /* Update the two timers that should have been started */
717 if (iaxs[x]->pingid > -1)
718 ast_sched_del(sched, iaxs[x]->pingid);
719 if (iaxs[x]->lagid > -1)
720 ast_sched_del(sched, iaxs[x]->lagid);
721 iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)x);
722 iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)x);
724 ast_mutex_unlock(&iaxsl[callno]);
727 ast_mutex_unlock(&iaxsl[x]);
730 ast_mutex_unlock(&iaxsl[x]);
732 if (x >= IAX_MAX_CALLS - 1) {
733 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
736 ast_log(LOG_DEBUG, "Made call %d into trunk call %d\n", callno, x);
737 /* We move this call from a non-trunked to a trunked call */
739 update_max_nontrunk();
743 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int lockpeer)
748 if (new <= NEW_ALLOW) {
749 /* Look for an existing connection first */
750 for (x=1;(res < 1) && (x<maxnontrunkcall);x++) {
751 ast_mutex_lock(&iaxsl[x]);
753 /* Look for an exact match */
754 if (match(sin, callno, dcallno, iaxs[x])) {
758 ast_mutex_unlock(&iaxsl[x]);
760 for (x=TRUNK_CALL_START;(res < 1) && (x<maxtrunkcall);x++) {
761 ast_mutex_lock(&iaxsl[x]);
763 /* Look for an exact match */
764 if (match(sin, callno, dcallno, iaxs[x])) {
768 ast_mutex_unlock(&iaxsl[x]);
771 if ((res < 1) && (new >= NEW_ALLOW)) {
772 gettimeofday(&now, NULL);
773 for (x=1;x<TRUNK_CALL_START;x++) {
774 /* Find first unused call number that hasn't been used in a while */
775 ast_mutex_lock(&iaxsl[x]);
776 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) break;
777 ast_mutex_unlock(&iaxsl[x]);
779 /* We've still got lock held if we found a spot */
780 if (x >= TRUNK_CALL_START) {
781 ast_log(LOG_WARNING, "No more space\n");
784 iaxs[x] = new_iax(sin, lockpeer);
785 ast_mutex_unlock(&iaxsl[x]);
786 update_max_nontrunk();
789 ast_log(LOG_DEBUG, "Creating new call structure %d\n", x);
790 iaxs[x]->addr.sin_port = sin->sin_port;
791 iaxs[x]->addr.sin_family = sin->sin_family;
792 iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
793 iaxs[x]->peercallno = callno;
795 iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
796 iaxs[x]->expirey = expirey;
797 iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)x);
798 iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)x);
799 iaxs[x]->amaflags = amaflags;
800 iaxs[x]->notransfer = notransfer;
801 strncpy(iaxs[x]->accountcode, accountcode, sizeof(iaxs[x]->accountcode)-1);
803 ast_log(LOG_WARNING, "Out of resources\n");
811 static void iax2_frame_free(struct iax_frame *fr)
813 if (fr->retrans > -1)
814 ast_sched_del(sched, fr->retrans);
818 static int iax2_queue_frame(int callno, struct ast_frame *f)
821 /* Assumes lock for callno is already held... */
824 if (!ast_mutex_trylock(&iaxsl[callno])) {
825 ast_log(LOG_WARNING, "Lock is not held on pass %d of iax2_queue_frame\n", pass);
828 if (iaxs[callno] && iaxs[callno]->owner) {
829 if (ast_mutex_trylock(&iaxs[callno]->owner->lock)) {
830 /* Avoid deadlock by pausing and trying again */
831 ast_mutex_unlock(&iaxsl[callno]);
833 ast_mutex_lock(&iaxsl[callno]);
835 ast_queue_frame(iaxs[callno]->owner, f, 0);
836 ast_mutex_unlock(&iaxs[callno]->owner->lock);
845 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
847 static int __do_deliver(void *data)
849 /* Just deliver the packet by using queueing. This is called by
850 the IAX thread with the iaxsl lock held. */
851 struct iax_frame *fr = data;
854 if (iaxs[fr->callno] && !iaxs[fr->callno]->alreadygone) {
855 if (fr->af.frametype == AST_FRAME_IAX) {
856 /* We have to treat some of these packets specially because
857 they're LAG measurement packets */
858 if (fr->af.subclass == IAX_COMMAND_LAGRQ) {
859 /* If we got a queued request, build a reply and send it */
860 fr->af.subclass = IAX_COMMAND_LAGRP;
861 iax2_send(iaxs[fr->callno], &fr->af, fr->ts, -1, 0, 0, 0);
862 } else if (fr->af.subclass == IAX_COMMAND_LAGRP) {
863 /* This is a reply we've been given, actually measure the difference */
864 ts = calc_timestamp(iaxs[fr->callno], 0);
865 iaxs[fr->callno]->lag = ts - fr->ts;
868 iax2_queue_frame(fr->callno, &fr->af);
871 /* Free our iax frame */
873 /* And don't run again */
877 static int do_deliver(void *data)
879 /* Locking version of __do_deliver */
880 struct iax_frame *fr = data;
881 int callno = fr->callno;
883 ast_mutex_lock(&iaxsl[callno]);
884 res = __do_deliver(data);
885 ast_mutex_unlock(&iaxsl[callno]);
889 static int handle_error(void)
891 /* XXX Ideally we should figure out why an error occured and then abort those
892 rather than continuing to try. Unfortunately, the published interface does
893 not seem to work XXX */
895 struct sockaddr_in *sin;
898 struct sock_extended_err e;
903 m.msg_controllen = sizeof(e);
905 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
907 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
909 if (m.msg_controllen) {
910 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
912 ast_log(LOG_WARNING, "Receive error from %s\n", inet_ntoa(sin->sin_addr));
914 ast_log(LOG_WARNING, "No address detected??\n");
916 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
923 static int send_packet(struct iax_frame *f)
926 /* Called with iaxsl held */
928 ast_log(LOG_DEBUG, "Sending %d on %d/%d to %s:%d\n", f->ts, f->callno, iaxs[f->callno]->peercallno, inet_ntoa(iaxs[f->callno]->addr.sin_addr), ntohs(iaxs[f->callno]->addr.sin_port));
929 /* Don't send if there was an error, but return error instead */
931 ast_log(LOG_WARNING, "Call number = %d\n", f->callno);
934 if (!iaxs[f->callno])
936 if (iaxs[f->callno]->error)
940 iax_showframe(f, NULL, 0, &iaxs[f->callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
941 res = sendto(netsocket, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[f->callno]->transfer,
942 sizeof(iaxs[f->callno]->transfer));
945 iax_showframe(f, NULL, 0, &iaxs[f->callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
946 res = sendto(netsocket, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[f->callno]->addr,
947 sizeof(iaxs[f->callno]->addr));
951 ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
959 static int iax2_predestroy(int callno)
961 struct ast_channel *c;
962 struct chan_iax2_pvt *pvt;
963 ast_mutex_lock(&iaxsl[callno]);
966 ast_mutex_unlock(&iaxsl[callno]);
969 if (!pvt->alreadygone) {
970 /* No more pings or lagrq's */
971 if (pvt->pingid > -1)
972 ast_sched_del(sched, pvt->pingid);
974 ast_sched_del(sched, pvt->lagid);
975 if (pvt->autoid > -1)
976 ast_sched_del(sched, pvt->autoid);
977 if (pvt->initid > -1)
978 ast_sched_del(sched, pvt->initid);
983 pvt->alreadygone = 1;
987 c->_softhangup |= AST_SOFTHANGUP_DEV;
989 ast_queue_hangup(c, 0);
991 ast_mutex_lock(&usecnt_lock);
994 ast_log(LOG_WARNING, "Usecnt < 0???\n");
995 ast_mutex_unlock(&usecnt_lock);
996 ast_update_use_count();
998 ast_mutex_unlock(&iaxsl[callno]);
1002 static int iax2_predestroy_nolock(int callno)
1005 ast_mutex_unlock(&iaxsl[callno]);
1006 res = iax2_predestroy(callno);
1007 ast_mutex_lock(&iaxsl[callno]);
1011 static void iax2_destroy(int callno)
1013 struct chan_iax2_pvt *pvt;
1014 struct iax_frame *cur;
1015 struct ast_channel *owner;
1018 ast_mutex_lock(&iaxsl[callno]);
1020 gettimeofday(&lastused[callno], NULL);
1027 if (ast_mutex_trylock(&owner->lock)) {
1028 ast_log(LOG_NOTICE, "Avoiding IAX destroy deadlock\n");
1029 ast_mutex_unlock(&iaxsl[callno]);
1034 iaxs[callno] = NULL;
1037 /* No more pings or lagrq's */
1038 if (pvt->pingid > -1)
1039 ast_sched_del(sched, pvt->pingid);
1040 if (pvt->lagid > -1)
1041 ast_sched_del(sched, pvt->lagid);
1042 if (pvt->autoid > -1)
1043 ast_sched_del(sched, pvt->autoid);
1044 if (pvt->initid > -1)
1045 ast_sched_del(sched, pvt->initid);
1050 if (pvt->bridgetrans)
1051 ast_translator_free_path(pvt->bridgetrans);
1052 pvt->bridgetrans = NULL;
1055 pvt->alreadygone = 1;
1058 /* If there's an owner, prod it to give up */
1059 owner->pvt->pvt = NULL;
1060 owner->_softhangup |= AST_SOFTHANGUP_DEV;
1061 ast_queue_hangup(owner, 0);
1064 for (cur = iaxq.head; cur ; cur = cur->next) {
1065 /* Cancel any pending transmissions */
1066 if (cur->callno == pvt->callno)
1070 pvt->reg->callno = 0;
1075 ast_mutex_unlock(&owner->lock);
1077 ast_mutex_unlock(&iaxsl[callno]);
1078 if (callno & 0x4000)
1081 static void iax2_destroy_nolock(int callno)
1083 /* Actually it's easier to unlock, kill it, and relock */
1084 ast_mutex_unlock(&iaxsl[callno]);
1085 iax2_destroy(callno);
1086 ast_mutex_lock(&iaxsl[callno]);
1089 static int update_packet(struct iax_frame *f)
1091 /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
1092 struct ast_iax2_full_hdr *fh = f->data;
1093 /* Mark this as a retransmission */
1094 fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
1096 f->iseqno = iaxs[f->callno]->iseqno;
1097 fh->iseqno = f->iseqno;
1101 static int attempt_transmit(void *data)
1103 /* Attempt to transmit the frame to the remote peer...
1104 Called without iaxsl held. */
1105 struct iax_frame *f = data;
1107 int callno = f->callno;
1108 /* Make sure this call is still active */
1110 ast_mutex_lock(&iaxsl[callno]);
1111 if ((f->callno) && iaxs[f->callno]) {
1112 if ((f->retries < 0) /* Already ACK'd */ ||
1113 (f->retries >= max_retries) /* Too many attempts */) {
1114 /* Record an error if we've transmitted too many times */
1115 if (f->retries >= max_retries) {
1117 /* Transfer timeout */
1118 send_command(iaxs[f->callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
1119 } else if (f->final) {
1121 iax2_destroy_nolock(f->callno);
1123 if (iaxs[f->callno]->owner)
1124 ast_log(LOG_WARNING, "Max retries exceeded to host %s on %s (type = %d, subclass = %d, ts=%d, seqno=%d)\n", inet_ntoa(iaxs[f->callno]->addr.sin_addr),iaxs[f->callno]->owner->name , f->af.frametype, f->af.subclass, f->ts, f->oseqno);
1125 iaxs[f->callno]->error = ETIMEDOUT;
1126 if (iaxs[f->callno]->owner) {
1127 struct ast_frame fr = { 0, };
1129 fr.frametype = AST_FRAME_CONTROL;
1130 fr.subclass = AST_CONTROL_HANGUP;
1131 iax2_queue_frame(f->callno, &fr);
1133 if (iaxs[f->callno]->reg) {
1134 memset(&iaxs[f->callno]->reg->us, 0, sizeof(iaxs[f->callno]->reg->us));
1135 iaxs[f->callno]->reg->regstate = REG_STATE_TIMEOUT;
1136 iaxs[f->callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
1138 iax2_destroy_nolock(f->callno);
1145 /* Update it if it needs it */
1147 /* Attempt transmission */
1150 /* Try again later after 10 times as long */
1152 if (f->retrytime > MAX_RETRY_TIME)
1153 f->retrytime = MAX_RETRY_TIME;
1154 /* Transfer messages max out at one second */
1155 if (f->transfer && (f->retrytime > 1000))
1156 f->retrytime = 1000;
1157 f->retrans = ast_sched_add(sched, f->retrytime, attempt_transmit, f);
1160 /* Make sure it gets freed */
1165 ast_mutex_unlock(&iaxsl[callno]);
1166 /* Do not try again */
1168 /* Don't attempt delivery, just remove it from the queue */
1169 ast_mutex_lock(&iaxq.lock);
1171 f->prev->next = f->next;
1173 iaxq.head = f->next;
1175 f->next->prev = f->prev;
1177 iaxq.tail = f->prev;
1179 ast_mutex_unlock(&iaxq.lock);
1181 /* Free the IAX frame */
1187 static int iax2_set_jitter(int fd, int argc, char *argv[])
1189 if ((argc != 4) && (argc != 5))
1190 return RESULT_SHOWUSAGE;
1192 max_jitter_buffer = atoi(argv[3]);
1193 if (max_jitter_buffer < 0)
1194 max_jitter_buffer = 0;
1197 if ((atoi(argv[3]) >= 0) && (atoi(argv[3]) < IAX_MAX_CALLS)) {
1198 if (iaxs[atoi(argv[3])]) {
1199 iaxs[atoi(argv[3])]->jitterbuffer = atoi(argv[4]);
1200 if (iaxs[atoi(argv[3])]->jitterbuffer < 0)
1201 iaxs[atoi(argv[3])]->jitterbuffer = 0;
1203 ast_cli(fd, "No such call '%d'\n", atoi(argv[3]));
1205 ast_cli(fd, "%d is not a valid call number\n", atoi(argv[3]));
1208 return RESULT_SUCCESS;
1211 static char jitter_usage[] =
1212 "Usage: iax set jitter [callid] <value>\n"
1213 " If used with a callid, it sets the jitter buffer to the given static\n"
1214 "value (until its next calculation). If used without a callid, the value is used\n"
1215 "to establish the maximum excess jitter buffer that is permitted before the jitter\n"
1216 "buffer size is reduced.";
1218 static int iax2_show_stats(int fd, int argc, char *argv[])
1220 struct iax_frame *cur;
1221 int cnt = 0, dead=0, final=0;
1223 return RESULT_SHOWUSAGE;
1224 for (cur = iaxq.head; cur ; cur = cur->next) {
1225 if (cur->retries < 0)
1231 ast_cli(fd, " IAX Statistics\n");
1232 ast_cli(fd, "---------------------\n");
1233 ast_cli(fd, "Outstanding frames: %d (%d ingress, %d outgress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
1234 ast_cli(fd, "Packets in transmit queue: %d dead, %d final, %d total\n", dead, final, cnt);
1235 return RESULT_SUCCESS;
1238 static int iax2_show_cache(int fd, int argc, char *argv[])
1240 struct iax2_dpcache *dp;
1241 char tmp[1024], *pc;
1245 gettimeofday(&tv, NULL);
1246 ast_mutex_lock(&dpcache_lock);
1248 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
1250 s = dp->expirey.tv_sec - tv.tv_sec;
1252 if (dp->flags & CACHE_FLAG_EXISTS)
1253 strcat(tmp, "EXISTS|");
1254 if (dp->flags & CACHE_FLAG_NONEXISTANT)
1255 strcat(tmp, "NONEXISTANT|");
1256 if (dp->flags & CACHE_FLAG_CANEXIST)
1257 strcat(tmp, "CANEXIST|");
1258 if (dp->flags & CACHE_FLAG_PENDING)
1259 strcat(tmp, "PENDING|");
1260 if (dp->flags & CACHE_FLAG_TIMEOUT)
1261 strcat(tmp, "TIMEOUT|");
1262 if (dp->flags & CACHE_FLAG_TRANSMITTED)
1263 strcat(tmp, "TRANSMITTED|");
1264 if (dp->flags & CACHE_FLAG_MATCHMORE)
1265 strcat(tmp, "MATCHMORE|");
1266 if (dp->flags & CACHE_FLAG_UNKNOWN)
1267 strcat(tmp, "UNKNOWN|");
1268 /* Trim trailing pipe */
1270 tmp[strlen(tmp) - 1] = '\0';
1272 strcpy(tmp, "(none)");
1274 pc = strchr(dp->peercontext, '@');
1276 pc = dp->peercontext;
1279 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
1280 if (dp->waiters[x] > -1)
1283 ast_cli(fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
1285 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
1288 ast_mutex_unlock(&dpcache_lock);
1289 return RESULT_SUCCESS;
1292 static char show_stats_usage[] =
1293 "Usage: iax show stats\n"
1294 " Display statistics on IAX channel driver.\n";
1297 static char show_cache_usage[] =
1298 "Usage: iax show cache\n"
1299 " Display currently cached IAX Dialplan results.\n";
1301 static struct ast_cli_entry cli_set_jitter =
1302 { { "iax2", "set", "jitter", NULL }, iax2_set_jitter, "Sets IAX jitter buffer", jitter_usage };
1304 static struct ast_cli_entry cli_show_stats =
1305 { { "iax2", "show", "stats", NULL }, iax2_show_stats, "Display IAX statistics", show_stats_usage };
1307 static struct ast_cli_entry cli_show_cache =
1308 { { "iax2", "show", "cache", NULL }, iax2_show_cache, "Display IAX cached dialplan", show_cache_usage };
1310 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p);
1312 #ifdef BRIDGE_OPTIMIZATION
1313 static unsigned int calc_fakestamp(struct chan_iax2_pvt *from, struct chan_iax2_pvt *to, unsigned int ts);
1315 static int forward_delivery(struct iax_frame *fr)
1317 struct chan_iax2_pvt *p1, *p2;
1318 p1 = iaxs[fr->callno];
1319 p2 = iaxs[p1->bridgecallno];
1324 /* Fix relative timestamp */
1325 fr->ts = calc_fakestamp(p1, p2, fr->ts);
1326 /* Now just send it send on the 2nd one
1327 with adjusted timestamp */
1328 return iax2_send(p2, &fr->af, fr->ts, -1, 0, 0, 0);
1332 static int schedule_delivery(struct iax_frame *fr, int reallydeliver, int updatehistory)
1335 int drops[MEMORY_SIZE];
1336 int min, max=0, maxone=0,y,z, match;
1337 /* ms is a measure of the "lateness" of the packet relative to the first
1338 packet we received, which always has a lateness of 1. Called by
1339 IAX thread, with iaxsl lock held. */
1340 ms = calc_rxstamp(iaxs[fr->callno]) - fr->ts;
1343 /* What likely happened here is that our counter has circled but we haven't
1344 gotten the update from the main packet. We'll just pretend that we did, and
1345 update the timestamp appropriately. */
1350 /* We got this packet out of order. Lets add 65536 to it to bring it into our new
1355 /* Rotate our history queue of "lateness". Don't worry about those initial
1356 zeros because the first entry will always be zero */
1357 if (updatehistory) {
1358 for (x=0;x<MEMORY_SIZE - 1;x++)
1359 iaxs[fr->callno]->history[x] = iaxs[fr->callno]->history[x+1];
1360 /* Add a history entry for this one */
1361 iaxs[fr->callno]->history[x] = ms;
1364 /* Initialize the minimum to reasonable values. It's too much
1365 work to do the same for the maximum, repeatedly */
1366 min=iaxs[fr->callno]->history[0];
1367 for (z=0;z < iax2_dropcount + 1;z++) {
1368 /* Start very optimistic ;-) */
1370 for (x=0;x<MEMORY_SIZE;x++) {
1371 if (max < iaxs[fr->callno]->history[x]) {
1372 /* We have a candidate new maximum value. Make
1373 sure it's not in our drop list */
1375 for (y=0;!match && (y<z);y++)
1376 match |= (drops[y] == x);
1378 /* It's not in our list, use it as the new maximum */
1379 max = iaxs[fr->callno]->history[x];
1385 /* On our first pass, find the minimum too */
1386 if (min > iaxs[fr->callno]->history[x])
1387 min = iaxs[fr->callno]->history[x];
1394 /* Just for reference, keep the "jitter" value, the difference between the
1395 earliest and the latest. */
1396 iaxs[fr->callno]->jitter = max - min;
1398 /* IIR filter for keeping track of historic jitter, but always increase
1399 historic jitter immediately for increase */
1401 if (iaxs[fr->callno]->jitter > iaxs[fr->callno]->historicjitter )
1402 iaxs[fr->callno]->historicjitter = iaxs[fr->callno]->jitter;
1404 iaxs[fr->callno]->historicjitter = GAMMA * (double)iaxs[fr->callno]->jitter + (1-GAMMA) *
1405 iaxs[fr->callno]->historicjitter;
1407 /* If our jitter buffer is too big (by a significant margin), then we slowly
1408 shrink it by about 1 ms each time to avoid letting the change be perceived */
1409 if (max < iaxs[fr->callno]->jitterbuffer - max_jitter_buffer)
1410 iaxs[fr->callno]->jitterbuffer -= 2;
1414 /* Constrain our maximum jitter buffer appropriately */
1415 if (max > min + maxjitterbuffer) {
1417 ast_log(LOG_DEBUG, "Constraining buffer from %d to %d + %d\n", max, min , maxjitterbuffer);
1418 max = min + maxjitterbuffer;
1422 /* If our jitter buffer is smaller than our maximum delay, grow the jitter
1423 buffer immediately to accomodate it (and a little more). */
1424 if (max > iaxs[fr->callno]->jitterbuffer)
1425 iaxs[fr->callno]->jitterbuffer = max
1426 /* + ((float)iaxs[fr->callno]->jitter) * 0.1 */;
1430 ast_log(LOG_DEBUG, "min = %d, max = %d, jb = %d, lateness = %d\n", min, max, iaxs[fr->callno]->jitterbuffer, ms);
1432 /* Subtract the lateness from our jitter buffer to know how long to wait
1433 before sending our packet. */
1434 ms = iaxs[fr->callno]->jitterbuffer - ms;
1436 if (!use_jitterbuffer)
1439 /* If the caller just wanted us to update, return now */
1445 ast_log(LOG_DEBUG, "Calculated ms is %d\n", ms);
1446 /* Don't deliver it more than 4 ms late */
1447 if ((ms > -4) || (fr->af.frametype != AST_FRAME_VOICE)) {
1451 ast_log(LOG_DEBUG, "Dropping voice packet since %d ms is, too old\n", ms);
1452 /* Free our iax frame */
1453 iax2_frame_free(fr);
1457 ast_log(LOG_DEBUG, "Scheduling delivery in %d ms\n", ms);
1458 fr->retrans = ast_sched_add(sched, ms, do_deliver, fr);
1463 static int iax2_transmit(struct iax_frame *fr)
1465 /* Lock the queue and place this packet at the end */
1468 /* By setting this to 0, the network thread will send it for us, and
1469 queue retransmission if necessary */
1471 ast_mutex_lock(&iaxq.lock);
1478 iaxq.tail->next = fr;
1479 fr->prev = iaxq.tail;
1483 ast_mutex_unlock(&iaxq.lock);
1484 /* Wake up the network thread */
1485 pthread_kill(netthreadid, SIGURG);
1491 static int iax2_digit(struct ast_channel *c, char digit)
1493 return send_command(c->pvt->pvt, AST_FRAME_DTMF, digit, 0, NULL, 0, -1);
1496 static int iax2_sendtext(struct ast_channel *c, char *text)
1499 return send_command(c->pvt->pvt, AST_FRAME_TEXT,
1500 0, 0, text, strlen(text) + 1, -1);
1503 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
1505 return send_command(c->pvt->pvt, AST_FRAME_IMAGE, img->subclass, 0, img->data, img->datalen, -1);
1508 static int iax2_sendhtml(struct ast_channel *c, int subclass, char *data, int datalen)
1510 return send_command(c->pvt->pvt, AST_FRAME_HTML, subclass, 0, data, datalen, -1);
1513 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
1515 struct chan_iax2_pvt *pvt = newchan->pvt->pvt;
1516 pvt->owner = newchan;
1520 #ifdef MYSQL_FRIENDS
1522 static void mysql_update_peer(char *peer, struct sockaddr_in *sin)
1524 if (mysql && (strlen(peer) < 128)) {
1528 name = alloca(strlen(peer) * 2 + 1);
1530 mysql_real_escape_string(mysql, name, peer, strlen(peer));
1531 snprintf(query, sizeof(query), "UPDATE iaxfriends SET ipaddr=\"%s\", port=\"%d\", regseconds=\"%ld\" WHERE name=\"%s\"",
1532 inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), nowtime, name);
1533 ast_mutex_lock(&mysqllock);
1534 if (mysql_real_query(mysql, query, strlen(query)))
1535 ast_log(LOG_WARNING, "Unable to update database\n");
1537 ast_mutex_unlock(&mysqllock);
1541 static struct iax2_peer *mysql_peer(char *peer)
1543 struct iax2_peer *p;
1546 p = malloc(sizeof(struct iax2_peer));
1547 memset(p, 0, sizeof(struct iax2_peer));
1548 if (mysql && (strlen(peer) < 128)) {
1553 time_t regseconds, nowtime;
1555 MYSQL_FIELD *fields;
1557 name = alloca(strlen(peer) * 2 + 1);
1558 mysql_real_escape_string(mysql, name, peer, strlen(peer));
1559 snprintf(query, sizeof(query), "SELECT * FROM iaxfriends WHERE name=\"%s\"", name);
1560 ast_mutex_lock(&mysqllock);
1561 mysql_query(mysql, query);
1562 if ((result = mysql_store_result(mysql))) {
1563 if ((rowval = mysql_fetch_row(result))) {
1564 numfields = mysql_num_fields(result);
1565 fields = mysql_fetch_fields(result);
1567 for (x=0;x<numfields;x++) {
1569 if (!strcasecmp(fields[x].name, "secret")) {
1570 strncpy(p->secret, rowval[x], sizeof(p->secret));
1571 } else if (!strcasecmp(fields[x].name, "context")) {
1572 strncpy(p->context, rowval[x], sizeof(p->context) - 1);
1573 } else if (!strcasecmp(fields[x].name, "ipaddr")) {
1574 inet_aton(rowval[x], &p->addr.sin_addr);
1575 } else if (!strcasecmp(fields[x].name, "port")) {
1576 if (sscanf(rowval[x], "%i", &port) != 1)
1578 p->addr.sin_port = htons(port);
1579 } else if (!strcasecmp(fields[x].name, "regseconds")) {
1580 if (sscanf(rowval[x], "%li", ®seconds) != 1)
1586 if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE)
1587 memset(&p->addr, 0, sizeof(p->addr));
1590 ast_mutex_unlock(&mysqllock);
1596 strncpy(p->name, peer, sizeof(p->name) - 1);
1600 p->capability = iax2_capability;
1601 p->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
1605 static struct iax2_user *mysql_user(char *user)
1607 struct iax2_user *p;
1608 struct iax2_context *con;
1611 p = malloc(sizeof(struct iax2_user));
1612 memset(p, 0, sizeof(struct iax2_user));
1613 con = malloc(sizeof(struct iax2_context));
1614 memset(con, 0, sizeof(struct iax2_context));
1615 strcpy(con->context, "default");
1617 if (mysql && (strlen(user) < 128)) {
1622 MYSQL_FIELD *fields;
1624 name = alloca(strlen(user) * 2 + 1);
1625 mysql_real_escape_string(mysql, name, user, strlen(user));
1626 snprintf(query, sizeof(query), "SELECT * FROM iaxfriends WHERE name=\"%s\"", name);
1627 ast_mutex_lock(&mysqllock);
1628 mysql_query(mysql, query);
1629 if ((result = mysql_store_result(mysql))) {
1630 if ((rowval = mysql_fetch_row(result))) {
1631 numfields = mysql_num_fields(result);
1632 fields = mysql_fetch_fields(result);
1634 for (x=0;x<numfields;x++) {
1636 if (!strcasecmp(fields[x].name, "secret")) {
1637 strncpy(p->secret, rowval[x], sizeof(p->secret));
1638 } else if (!strcasecmp(fields[x].name, "context")) {
1639 strncpy(p->contexts->context, rowval[x], sizeof(p->contexts->context) - 1);
1645 ast_mutex_unlock(&mysqllock);
1653 strncpy(p->name, user, sizeof(p->name) - 1);
1655 p->capability = iax2_capability;
1656 p->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
1660 #endif /* MYSQL_FRIENDS */
1662 static int create_addr(struct sockaddr_in *sin, int *capability, int *sendani, int *maxtime, char *peer, char *context, int *trunk, int *notransfer, char *secret, int seclen)
1665 struct iax2_peer *p;
1673 sin->sin_family = AF_INET;
1674 ast_mutex_lock(&peerl.lock);
1677 if (!strcasecmp(p->name, peer)) {
1682 ast_mutex_unlock(&peerl.lock);
1683 #ifdef MYSQL_FRIENDS
1685 p = mysql_peer(peer);
1689 if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
1690 (!p->maxms || ((p->lastms > 0) && (p->lastms <= p->maxms)))) {
1692 *sendani = p->sendani; /* Whether we transmit ANI */
1694 *maxtime = p->maxms; /* Max time they should take */
1696 strncpy(context, p->context, AST_MAX_EXTENSION - 1);
1700 *capability = p->capability;
1702 strncpy(secret, p->secret, seclen);
1703 if (p->addr.sin_addr.s_addr) {
1704 sin->sin_addr = p->addr.sin_addr;
1705 sin->sin_port = p->addr.sin_port;
1707 sin->sin_addr = p->defaddr.sin_addr;
1708 sin->sin_port = p->defaddr.sin_port;
1711 *notransfer=p->notransfer;
1719 hp = gethostbyname(peer);
1721 memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
1722 sin->sin_port = htons(IAX_DEFAULT_PORTNO);
1725 ast_log(LOG_WARNING, "No such host: %s\n", peer);
1735 static int auto_congest(void *nothing)
1737 int callno = (int)(long)(nothing);
1738 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_CONGESTION };
1739 ast_mutex_lock(&iaxsl[callno]);
1741 iaxs[callno]->initid = -1;
1742 iax2_queue_frame(callno, &f);
1743 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
1745 ast_mutex_unlock(&iaxsl[callno]);
1749 static unsigned int iax2_datetime(void)
1755 localtime_r(&t, &tm);
1756 tmp = (tm.tm_sec >> 1) & 0x1f; /* 5 bits of seconds */
1757 tmp |= (tm.tm_min & 0x3f) << 5; /* 6 bits of minutes */
1758 tmp |= (tm.tm_hour & 0x1f) << 11; /* 5 bits of hours */
1759 tmp |= (tm.tm_mday & 0x1f) << 16; /* 5 bits of day of month */
1760 tmp |= ((tm.tm_mon + 1) & 0xf) << 21; /* 4 bits of month */
1761 tmp |= ((tm.tm_year - 100) & 0x7f) << 25; /* 7 bits of year */
1765 static int iax2_call(struct ast_channel *c, char *dest, int timeout)
1767 struct sockaddr_in sin;
1772 char *secret = NULL;
1775 char *l=NULL, *n=NULL;
1776 struct iax_ie_data ied;
1777 char myrdest [5] = "s";
1778 char context[AST_MAX_EXTENSION] ="";
1779 char *portno = NULL;
1781 struct chan_iax2_pvt *p = c->pvt->pvt;
1783 char storedsecret[80];
1784 if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
1785 ast_log(LOG_WARNING, "Line is already in use (%s)?\n", c->name);
1788 strncpy(host, dest, sizeof(host)-1);
1790 strsep(&stringp, "/");
1791 /* If no destination extension specified, use 's' */
1792 rdest = strsep(&stringp, "/");
1796 /* Check for trailing options */
1797 opts = strsep(&stringp, "/");
1802 strsep(&stringp, "@");
1803 rcontext = strsep(&stringp, "@");
1805 strsep(&stringp, "@");
1806 username = strsep(&stringp, "@");
1808 /* Really the second argument is the host, not the username */
1816 username = strsep(&stringp, ":");
1817 secret = strsep(&stringp, ":");
1820 if (strsep(&stringp, ":")) {
1822 strsep(&stringp, ":");
1823 portno = strsep(&stringp, ":");
1825 if (create_addr(&sin, NULL, NULL, NULL, hname, context, NULL, NULL, storedsecret, sizeof(storedsecret) - 1)) {
1826 ast_log(LOG_WARNING, "No address associated with '%s'\n", hname);
1829 /* Keep track of the context for outgoing calls too */
1830 strncpy(c->context, context, sizeof(c->context) - 1);
1832 sin.sin_port = htons(atoi(portno));
1835 strncpy(cid, c->callerid, sizeof(cid) - 1);
1836 ast_callerid_parse(cid, &n, &l);
1838 ast_shrink_phone_number(l);
1840 /* Now build request */
1841 memset(&ied, 0, sizeof(ied));
1842 /* On new call, first IE MUST be IAX version of caller */
1843 iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
1844 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, rdest);
1845 if (strchr(opts, 'a')) {
1846 /* Request auto answer */
1847 iax_ie_append(&ied, IAX_IE_AUTOANSWER);
1850 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
1852 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n);
1853 if (p->sendani && c->ani) {
1855 strncpy(cid, c->ani, sizeof(cid) - 1);
1856 ast_callerid_parse(cid, &n, &l);
1858 ast_shrink_phone_number(l);
1859 iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, l);
1862 if (c->language && strlen(c->language))
1863 iax_ie_append_str(&ied, IAX_IE_LANGUAGE, c->language);
1864 if (c->dnid && strlen(c->dnid))
1865 iax_ie_append_str(&ied, IAX_IE_DNID, c->dnid);
1867 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, rcontext);
1869 iax_ie_append_str(&ied, IAX_IE_USERNAME, username);
1870 if (!secret && strlen(storedsecret))
1871 secret = storedsecret;
1873 if (secret[0] == '[') {
1874 /* This is an RSA key, not a normal secret */
1875 strncpy(p->outkey, secret + 1, sizeof(p->secret)-1);
1876 if (strlen(p->outkey)) {
1877 p->outkey[strlen(p->outkey) - 1] = '\0';
1880 strncpy(p->secret, secret, sizeof(p->secret)-1);
1882 iax_ie_append_int(&ied, IAX_IE_FORMAT, c->nativeformats);
1883 iax_ie_append_int(&ied, IAX_IE_CAPABILITY, p->capability);
1884 iax_ie_append_short(&ied, IAX_IE_ADSICPE, c->adsicpe);
1885 iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime());
1886 /* Transmit the string in a "NEW" request */
1888 /* XXX We have no equivalent XXX */
1889 if (option_verbose > 2)
1890 ast_verbose(VERBOSE_PREFIX_3 "Calling using options '%s'\n", requeststr);
1893 /* Initialize pingtime and auto-congest time */
1894 p->pingtime = p->maxtime / 2;
1895 p->initid = ast_sched_add(sched, p->maxtime * 2, auto_congest, (void *)(long)p->callno);
1897 send_command(p, AST_FRAME_IAX,
1898 IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
1899 ast_setstate(c, AST_STATE_RINGING);
1903 static int iax2_hangup(struct ast_channel *c)
1905 struct chan_iax2_pvt *pvt = c->pvt->pvt;
1909 callno = pvt->callno;
1910 ast_mutex_lock(&iaxsl[callno]);
1911 ast_log(LOG_DEBUG, "We're hanging up %s now...\n", c->name);
1912 alreadygone = pvt->alreadygone;
1913 /* Send the hangup unless we have had a transmission error or are already gone */
1914 if (!pvt->error && !alreadygone)
1915 send_command_final(pvt, AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, NULL, 0, -1);
1916 /* Explicitly predestroy it */
1917 iax2_predestroy_nolock(callno);
1918 /* If we were already gone to begin with, destroy us now */
1920 ast_log(LOG_DEBUG, "Really destroying %s now...\n", c->name);
1921 iax2_destroy_nolock(callno);
1923 ast_mutex_unlock(&iaxsl[callno]);
1925 if (option_verbose > 2)
1926 ast_verbose(VERBOSE_PREFIX_3 "Hungup '%s'\n", c->name);
1930 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
1932 struct ast_option_header *h;
1934 h = malloc(datalen + sizeof(struct ast_option_header));
1936 h->flag = AST_OPTION_FLAG_REQUEST;
1937 h->option = htons(option);
1938 memcpy(h->data, data, datalen);
1939 res = send_command((struct chan_iax2_pvt *)c->pvt->pvt, AST_FRAME_CONTROL,
1940 AST_CONTROL_OPTION, 0, (char *)h, datalen + sizeof(struct ast_option_header), -1);
1944 ast_log(LOG_WARNING, "Out of memory\n");
1947 static struct ast_frame *iax2_read(struct ast_channel *c)
1949 static struct ast_frame f = { AST_FRAME_NULL, };
1950 ast_log(LOG_NOTICE, "I should never be called!\n");
1954 static int iax2_start_transfer(struct ast_channel *c0, struct ast_channel *c1)
1957 struct iax_ie_data ied0;
1958 struct iax_ie_data ied1;
1959 struct chan_iax2_pvt *p0 = c0->pvt->pvt;
1960 struct chan_iax2_pvt *p1 = c1->pvt->pvt;
1961 unsigned int transferid = rand();
1962 memset(&ied0, 0, sizeof(ied0));
1963 iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &p1->addr);
1964 iax_ie_append_short(&ied0, IAX_IE_CALLNO, p1->peercallno);
1965 iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, transferid);
1967 memset(&ied1, 0, sizeof(ied1));
1968 iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &p0->addr);
1969 iax_ie_append_short(&ied1, IAX_IE_CALLNO, p0->peercallno);
1970 iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, transferid);
1972 res = send_command(p0, AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
1975 res = send_command(p1, AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
1978 p0->transferring = TRANSFER_BEGIN;
1979 p1->transferring = TRANSFER_BEGIN;
1983 static int iax2_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
1985 struct ast_channel *cs[3];
1986 struct ast_channel *who;
1989 int transferstarted=0;
1990 struct ast_frame *f;
1991 struct chan_iax2_pvt *p0 = c0->pvt->pvt;
1992 struct chan_iax2_pvt *p1 = c1->pvt->pvt;
1993 struct timeval waittimer = {0, 0}, tv;
1995 /* Put them in native bridge mode */
1996 p0->bridgecallno = p1->callno;
1997 p1->bridgecallno = p0->callno;
1999 /* If not, try to bridge until we can execute a transfer, if we can */
2002 for (/* ever */;;) {
2003 /* Check in case we got masqueraded into */
2004 if ((c0->type != type) || (c1->type != type)) {
2005 if (option_verbose > 2)
2006 ast_verbose(VERBOSE_PREFIX_3 "Can't masquerade, we're different...\n");
2007 /* Remove from native mode */
2008 p0->bridgecallno = 0;
2009 p1->bridgecallno = 0;
2012 if (c0->nativeformats != c1->nativeformats) {
2013 ast_verbose(VERBOSE_PREFIX_3 "Operating with different codecs, can't native bridge...\n");
2014 /* Remove from native mode */
2015 p0->bridgecallno = 0;
2016 p1->bridgecallno = 0;
2019 /* check if transfered and if we really want native bridging */
2020 if (!transferstarted && !p0->notransfer && !p1->notransfer) {
2021 /* Try the transfer */
2022 if (iax2_start_transfer(c0, c1))
2023 ast_log(LOG_WARNING, "Unable to start the transfer\n");
2024 transferstarted = 1;
2026 if ((p0->transferring == TRANSFER_RELEASED) && (p1->transferring == TRANSFER_RELEASED)) {
2027 /* Call has been transferred. We're no longer involved */
2028 gettimeofday(&tv, NULL);
2029 if (!waittimer.tv_sec && !waittimer.tv_usec) {
2030 waittimer.tv_sec = tv.tv_sec;
2031 waittimer.tv_usec = tv.tv_usec;
2032 } else if (tv.tv_sec - waittimer.tv_sec > IAX_LINGER_TIMEOUT) {
2033 c0->_softhangup |= AST_SOFTHANGUP_DEV;
2034 c1->_softhangup |= AST_SOFTHANGUP_DEV;
2042 who = ast_waitfor_n(cs, 2, &to);
2044 if (ast_check_hangup(c0) || ast_check_hangup(c1)) {
2057 if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
2063 if ((f->frametype == AST_FRAME_VOICE) ||
2064 (f->frametype == AST_FRAME_TEXT) ||
2065 (f->frametype == AST_FRAME_VIDEO) ||
2066 (f->frametype == AST_FRAME_IMAGE) ||
2067 (f->frametype == AST_FRAME_DTMF)) {
2068 if ((f->frametype == AST_FRAME_DTMF) &&
2069 (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
2071 if ((flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
2074 /* Take out of conference mode */
2076 /* Remove from native mode */
2082 if (flags & AST_BRIDGE_DTMF_CHANNEL_1) {
2086 /* Remove from native mode */
2093 ast_log(LOG_DEBUG, "Read from %s\n", who->name);
2095 ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
2107 /* Swap who gets priority */
2112 p0->bridgecallno = 0;
2113 p1->bridgecallno = 0;
2117 static int iax2_answer(struct ast_channel *c)
2119 struct chan_iax2_pvt *pvt = c->pvt->pvt;
2121 ast_log(LOG_DEBUG, "Answering\n");
2122 return send_command(pvt, AST_FRAME_CONTROL, AST_CONTROL_ANSWER, 0, NULL, 0, -1);
2125 static int iax2_indicate(struct ast_channel *c, int condition)
2127 struct chan_iax2_pvt *pvt = c->pvt->pvt;
2129 ast_log(LOG_DEBUG, "Indicating condition %d\n", condition);
2130 return send_command(pvt, AST_FRAME_CONTROL, condition, 0, NULL, 0, -1);
2133 static int iax2_transfer(struct ast_channel *c, char *dest)
2135 struct chan_iax2_pvt *pvt = c->pvt->pvt;
2136 struct iax_ie_data ied;
2137 char tmp[256] = "", *context;
2138 strncpy(tmp, dest, sizeof(tmp) - 1);
2139 context = strchr(tmp, '@');
2144 memset(&ied, 0, sizeof(ied));
2145 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, tmp);
2147 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, context);
2149 ast_log(LOG_DEBUG, "Transferring '%s' to '%s'\n", c->name, dest);
2150 return send_command(pvt, AST_FRAME_IAX, IAX_COMMAND_TRANSFER, 0, ied.buf, ied.pos, -1);
2154 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
2156 static int iax2_getpeertrunk(struct sockaddr_in sin)
2158 struct iax2_peer *peer;
2160 ast_mutex_lock(&peerl.lock);
2163 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
2164 (peer->addr.sin_port == sin.sin_port)) {
2170 ast_mutex_unlock(&peerl.lock);
2174 static struct ast_channel *ast_iax2_new(struct chan_iax2_pvt *i, int state, int capability)
2176 struct ast_channel *tmp;
2177 tmp = ast_channel_alloc(1);
2179 if (strlen(i->username))
2180 snprintf(tmp->name, sizeof(tmp->name), "IAX2[%s@%s]/%d", i->username, i->host, i->callno);
2182 snprintf(tmp->name, sizeof(tmp->name), "IAX2[%s]/%d", i->host, i->callno);
2184 /* We can support any format by default, until we get restricted */
2185 tmp->nativeformats = capability;
2186 tmp->readformat = 0;
2187 tmp->writeformat = 0;
2189 tmp->pvt->send_digit = iax2_digit;
2190 tmp->pvt->send_text = iax2_sendtext;
2191 tmp->pvt->send_image = iax2_sendimage;
2192 tmp->pvt->send_html = iax2_sendhtml;
2193 tmp->pvt->call = iax2_call;
2194 tmp->pvt->hangup = iax2_hangup;
2195 tmp->pvt->answer = iax2_answer;
2196 tmp->pvt->read = iax2_read;
2197 tmp->pvt->write = iax2_write;
2198 tmp->pvt->write_video = iax2_write;
2199 tmp->pvt->indicate = iax2_indicate;
2200 tmp->pvt->setoption = iax2_setoption;
2201 tmp->pvt->bridge = iax2_bridge;
2202 tmp->pvt->transfer = iax2_transfer;
2203 if (strlen(i->callerid))
2204 tmp->callerid = strdup(i->callerid);
2206 tmp->ani = strdup(i->ani);
2207 if (strlen(i->language))
2208 strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
2209 if (strlen(i->dnid))
2210 tmp->dnid = strdup(i->dnid);
2211 if (strlen(i->accountcode))
2212 strncpy(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode)-1);
2214 tmp->amaflags = i->amaflags;
2215 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
2216 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
2217 tmp->adsicpe = i->peeradsicpe;
2218 tmp->pvt->fixup = iax2_fixup;
2220 i->capability = capability;
2221 ast_setstate(tmp, state);
2222 ast_mutex_lock(&usecnt_lock);
2224 ast_mutex_unlock(&usecnt_lock);
2225 ast_update_use_count();
2226 if (state != AST_STATE_DOWN) {
2227 if (ast_pbx_start(tmp)) {
2228 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
2237 static unsigned int calc_txpeerstamp(struct iax2_peer *peer)
2240 unsigned int mssincetx;
2242 gettimeofday(&tv, NULL);
2243 mssincetx = (tv.tv_sec - peer->lasttxtime.tv_sec) * 1000 + (tv.tv_usec - peer->lasttxtime.tv_usec) / 1000;
2244 if (mssincetx > 5000) {
2245 /* If it's been at least 5 seconds since the last time we transmitted on this trunk, reset our timers */
2246 peer->txtrunktime.tv_sec = tv.tv_sec;
2247 peer->txtrunktime.tv_usec = tv.tv_usec;
2249 /* Update last transmit time now */
2250 peer->lasttxtime.tv_sec = tv.tv_sec;
2251 peer->lasttxtime.tv_usec = tv.tv_usec;
2253 /* Calculate ms offset */
2254 ms = (tv.tv_sec - peer->txtrunktime.tv_sec) * 1000 + (tv.tv_usec - peer->txtrunktime.tv_usec) / 1000;
2256 /* We never send the same timestamp twice, so fudge a little if we must */
2257 if (ms == peer->lastsent)
2258 ms = peer->lastsent + 1;
2259 peer->lastsent = ms;
2263 static unsigned int fix_peerts(struct iax2_peer *peer, int callno, unsigned int ts)
2265 long ms; /* NOT unsigned */
2266 if (!iaxs[callno]->rxcore.tv_sec && !iaxs[callno]->rxcore.tv_usec) {
2267 /* Initialize rxcore time if appropriate */
2268 gettimeofday(&iaxs[callno]->rxcore, NULL);
2270 /* Calculate difference between trunk and channel */
2271 ms = (peer->rxtrunktime.tv_sec - iaxs[callno]->rxcore.tv_sec) * 1000 +
2272 (peer->rxtrunktime.tv_usec - iaxs[callno]->rxcore.tv_usec) / 1000;
2273 /* Return as the sum of trunk time and the difference between trunk and real time */
2277 static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts)
2281 if (!p->offset.tv_sec && !p->offset.tv_usec)
2282 gettimeofday(&p->offset, NULL);
2283 /* If the timestamp is specified, just send it as is */
2286 gettimeofday(&tv, NULL);
2287 ms = (tv.tv_sec - p->offset.tv_sec) * 1000 + (tv.tv_usec - p->offset.tv_usec) / 1000;
2288 /* We never send the same timestamp twice, so fudge a little if we must */
2289 if (ms <= p->lastsent)
2290 ms = p->lastsent + 1;
2295 #ifdef BRIDGE_OPTIMIZATION
2296 static unsigned int calc_fakestamp(struct chan_iax2_pvt *p1, struct chan_iax2_pvt *p2, unsigned int fakets)
2299 /* Receive from p1, send to p2 */
2301 /* Setup rxcore if necessary on outgoing channel */
2302 if (!p1->rxcore.tv_sec && !p1->rxcore.tv_usec)
2303 gettimeofday(&p1->rxcore, NULL);
2305 /* Setup txcore if necessary on outgoing channel */
2306 if (!p2->offset.tv_sec && !p2->offset.tv_usec)
2307 gettimeofday(&p2->offset, NULL);
2309 /* Now, ts is the timestamp of the original packet in the orignal context.
2310 Adding rxcore to it gives us when we would want the packet to be delivered normally.
2311 Subtracting txcore of the outgoing channel gives us what we'd expect */
2313 ms = (p1->rxcore.tv_sec - p2->offset.tv_sec) * 1000 + (p1->rxcore.tv_usec - p2->offset.tv_usec) / 1000;
2315 if (fakets <= p2->lastsent)
2316 fakets = p2->lastsent + 1;
2317 p2->lastsent = fakets;
2322 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p)
2324 /* Returns where in "receive time" we are */
2327 /* Setup rxcore if necessary */
2328 if (!p->rxcore.tv_sec && !p->rxcore.tv_usec)
2329 gettimeofday(&p->rxcore, NULL);
2331 gettimeofday(&tv, NULL);
2332 ms = (tv.tv_sec - p->rxcore.tv_sec) * 1000 + (tv.tv_usec - p->rxcore.tv_usec) / 1000;
2336 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final)
2338 /* Queue a packet for delivery on a given private structure. Use "ts" for
2339 timestamp, or calculate if ts is 0. Send immediately without retransmission
2340 or delayed, with retransmission */
2341 struct ast_iax2_full_hdr *fh;
2342 struct ast_iax2_mini_hdr *mh;
2343 struct ast_iax2_video_hdr *vh;
2345 struct iax_frame fr2;
2346 unsigned char buffer[4096];
2348 struct iax_frame *fr;
2351 unsigned int lastsent;
2355 ast_log(LOG_WARNING, "No private structure for packet?\n");
2359 lastsent = pvt->lastsent;
2361 /* Calculate actual timestamp */
2362 fts = calc_timestamp(pvt, ts);
2364 if ((pvt->trunk || ((fts & 0xFFFF0000L) == (lastsent & 0xFFFF0000L)))
2365 /* High two bits are the same on timestamp, or sending on a trunk */ &&
2366 (f->frametype == AST_FRAME_VOICE)
2367 /* is a voice frame */ &&
2368 (f->subclass == pvt->svoiceformat)
2369 /* is the same type */ ) {
2370 /* Force immediate rather than delayed transmission */
2372 /* Mark that mini-style frame is appropriate */
2375 if (((fts & 0xFFFF8000L) == (lastsent & 0xFFFF8000L)) &&
2376 (f->frametype == AST_FRAME_VIDEO) &&
2377 ((f->subclass & ~0x1) == pvt->svideoformat)) {
2381 /* Allocate an iax_frame */
2385 fr = iax_frame_new(DIRECTION_OUTGRESS, f->datalen);
2387 ast_log(LOG_WARNING, "Out of memory\n");
2390 /* Copy our prospective frame into our immediate or retransmitted wrapper */
2391 iax_frame_wrap(fr, f);
2395 ast_log(LOG_WARNING, "timestamp is 0?\n");
2397 iax2_frame_free(fr);
2400 fr->callno = pvt->callno;
2401 fr->transfer = transfer;
2404 /* We need a full frame */
2408 fr->oseqno = pvt->oseqno++;
2409 fr->iseqno = pvt->iseqno;
2410 fh = (struct ast_iax2_full_hdr *)(fr->af.data - sizeof(struct ast_iax2_full_hdr));
2411 fh->scallno = htons(fr->callno | IAX_FLAG_FULL);
2412 fh->ts = htonl(fr->ts);
2413 fh->oseqno = fr->oseqno;
2417 fh->iseqno = fr->iseqno;
2418 /* Keep track of the last thing we've acknowledged */
2420 pvt->aseqno = fr->iseqno;
2421 fh->type = fr->af.frametype & 0xFF;
2422 if (fr->af.frametype == AST_FRAME_VIDEO)
2423 fh->csub = compress_subclass(fr->af.subclass & ~0x1) | ((fr->af.subclass & 0x1) << 6);
2425 fh->csub = compress_subclass(fr->af.subclass);
2427 fr->dcallno = pvt->transfercallno;
2429 fr->dcallno = pvt->peercallno;
2430 fh->dcallno = htons(fr->dcallno);
2431 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_full_hdr);
2434 /* Retry after 2x the ping time has passed */
2435 fr->retrytime = pvt->pingtime * 2;
2436 if (fr->retrytime < MIN_RETRY_TIME)
2437 fr->retrytime = MIN_RETRY_TIME;
2438 if (fr->retrytime > MAX_RETRY_TIME)
2439 fr->retrytime = MAX_RETRY_TIME;
2440 /* Acks' don't get retried */
2441 if ((f->frametype == AST_FRAME_IAX) && (f->subclass == IAX_COMMAND_ACK))
2443 if (f->frametype == AST_FRAME_VOICE) {
2444 pvt->svoiceformat = f->subclass;
2446 if (f->frametype == AST_FRAME_VIDEO) {
2447 pvt->svideoformat = f->subclass & ~0x1;
2450 res = send_packet(fr);
2452 res = iax2_transmit(fr);
2455 /* Queue for transmission in a meta frame */
2456 if ((sizeof(pvt->trunkdata) - pvt->trunkdatalen) >= fr->af.datalen) {
2457 memcpy(pvt->trunkdata + pvt->trunkdatalen, fr->af.data, fr->af.datalen);
2458 pvt->trunkdatalen += fr->af.datalen;
2460 pvt->trunkerror = 0;
2462 if (!pvt->trunkerror)
2463 ast_log(LOG_WARNING, "Out of trunk data space on call number %d, dropping\n", pvt->callno);
2464 pvt->trunkerror = 1;
2467 } else if (fr->af.frametype == AST_FRAME_VIDEO) {
2468 /* Video frame have no sequence number */
2471 vh = (struct ast_iax2_video_hdr *)(fr->af.data - sizeof(struct ast_iax2_video_hdr));
2473 vh->callno = htons(0x8000 | fr->callno);
2474 vh->ts = htons((fr->ts & 0x7FFF) | (fr->af.subclass & 0x1 ? 0x8000 : 0));
2475 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_video_hdr);
2478 res = send_packet(fr);
2480 /* Mini-frames have no sequence number */
2483 /* Mini frame will do */
2484 mh = (struct ast_iax2_mini_hdr *)(fr->af.data - sizeof(struct ast_iax2_mini_hdr));
2485 mh->callno = htons(fr->callno);
2486 mh->ts = htons(fr->ts & 0xFFFF);
2487 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_mini_hdr);
2490 res = send_packet(fr);
2498 static int iax2_show_users(int fd, int argc, char *argv[])
2500 #define FORMAT "%-15.15s %-15.15s %-15.15s %-15.15s %-5.5s\n"
2501 #define FORMAT2 "%-15.15s %-15.15s %-15.15d %-15.15s %-5.5s\n"
2502 struct iax2_user *user;
2504 return RESULT_SHOWUSAGE;
2505 ast_mutex_lock(&userl.lock);
2506 ast_cli(fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C");
2507 for(user=userl.users;user;user=user->next) {
2508 ast_cli(fd, FORMAT2, user->name, user->secret, user->authmethods,
2509 user->contexts ? user->contexts->context : context,
2510 user->ha ? "Yes" : "No");
2512 ast_mutex_unlock(&userl.lock);
2513 return RESULT_SUCCESS;
2518 static int iax2_show_peers(int fd, int argc, char *argv[])
2520 #define FORMAT2 "%-15.15s %-15.15s %s %-15.15s %-8s %-10s\n"
2521 #define FORMAT "%-15.15s %-15.15s %s %-15.15s %-5d%s %-10s\n"
2522 struct iax2_peer *peer;
2523 char name[256] = "";
2524 int registeredonly=0;
2525 if ((argc != 3) && (argc != 4))
2526 return RESULT_SHOWUSAGE;
2528 if (!strcasecmp(argv[3], "registered")) {
2531 return RESULT_SHOWUSAGE;
2533 ast_mutex_lock(&peerl.lock);
2534 ast_cli(fd, FORMAT2, "Name/Username", "Host", " ", "Mask", "Port", "Status");
2535 for (peer = peerl.peers;peer;peer = peer->next) {
2538 if (registeredonly && !peer->addr.sin_addr.s_addr)
2540 if (strlen(peer->username))
2541 snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
2543 strncpy(name, peer->name, sizeof(name) - 1);
2545 if (peer->lastms < 0)
2546 strcpy(status, "UNREACHABLE");
2547 else if (peer->lastms > peer->maxms)
2548 snprintf(status, sizeof(status), "LAGGED (%d ms)", peer->lastms);
2549 else if (peer->lastms)
2550 snprintf(status, sizeof(status), "OK (%d ms)", peer->lastms);
2552 strcpy(status, "UNKNOWN");
2554 strcpy(status, "Unmonitored");
2555 strncpy(nm, inet_ntoa(peer->mask), sizeof(nm)-1);
2556 ast_cli(fd, FORMAT, name,
2557 peer->addr.sin_addr.s_addr ? inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
2558 peer->dynamic ? "(D)" : "(S)",
2560 ntohs(peer->addr.sin_port), peer->trunk ? "(T)" : " ", status);
2562 ast_mutex_unlock(&peerl.lock);
2563 return RESULT_SUCCESS;
2568 /* JDG: callback to display iax peers in manager */
2569 static int manager_iax2_show_peers( struct mansession *s, struct message *m )
2571 char *a[] = { "iax2", "show", "users" };
2573 ret = iax2_show_peers( s->fd, 3, a );
2574 ast_cli( s->fd, "\r\n" );
2578 static char *regstate2str(int regstate)
2581 case REG_STATE_UNREGISTERED:
2582 return "Unregistered";
2583 case REG_STATE_REGSENT:
2584 return "Request Sent";
2585 case REG_STATE_AUTHSENT:
2586 return "Auth. Sent";
2587 case REG_STATE_REGISTERED:
2588 return "Registered";
2589 case REG_STATE_REJECTED:
2591 case REG_STATE_TIMEOUT:
2593 case REG_STATE_NOAUTH:
2594 return "No Authentication";
2600 static int iax2_show_registry(int fd, int argc, char *argv[])
2602 #define FORMAT2 "%-20.20s %-10.10s %-20.20s %8.8s %s\n"
2603 #define FORMAT "%-20.20s %-10.10s %-20.20s %8d %s\n"
2604 struct iax2_registry *reg;
2608 return RESULT_SHOWUSAGE;
2609 ast_mutex_lock(&peerl.lock);
2610 ast_cli(fd, FORMAT2, "Host", "Username", "Perceived", "Refresh", "State");
2611 for (reg = registrations;reg;reg = reg->next) {
2612 snprintf(host, sizeof(host), "%s:%d", inet_ntoa(reg->addr.sin_addr), ntohs(reg->addr.sin_port));
2613 if (reg->us.sin_addr.s_addr)
2614 snprintf(perceived, sizeof(perceived), "%s:%d", inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
2616 strcpy(perceived, "<Unregistered>");
2617 ast_cli(fd, FORMAT, host,
2618 reg->username, perceived, reg->refresh, regstate2str(reg->regstate));
2620 ast_mutex_unlock(&peerl.lock);
2621 return RESULT_SUCCESS;
2626 static int iax2_show_channels(int fd, int argc, char *argv[])
2628 #define FORMAT2 "%-15.15s %-10.10s %-11.11s %-11.11s %-7.7s %-6.6s %s\n"
2629 #define FORMAT "%-15.15s %-10.10s %5.5d/%5.5d %5.5d/%5.5d %-5.5dms %-4.4dms %-6.6s\n"
2633 return RESULT_SHOWUSAGE;
2634 ast_cli(fd, FORMAT2, "Peer", "Username", "ID (Lo/Rem)", "Seq (Tx/Rx)", "Lag", "Jitter", "Format");
2635 for (x=0;x<IAX_MAX_CALLS;x++) {
2636 ast_mutex_lock(&iaxsl[x]);
2638 ast_cli(fd, FORMAT, inet_ntoa(iaxs[x]->addr.sin_addr),
2639 strlen(iaxs[x]->username) ? iaxs[x]->username : "(None)",
2640 iaxs[x]->callno, iaxs[x]->peercallno,
2641 iaxs[x]->oseqno, iaxs[x]->iseqno,
2644 ast_getformatname(iaxs[x]->voiceformat) );
2647 ast_mutex_unlock(&iaxsl[x]);
2649 ast_cli(fd, "%d active IAX channel(s)\n", numchans);
2650 return RESULT_SUCCESS;
2655 static int iax2_do_trunk_debug(int fd, int argc, char *argv[])
2658 return RESULT_SHOWUSAGE;
2660 ast_cli(fd, "IAX2 Trunk Debug Requested\n");
2661 return RESULT_SUCCESS;
2664 static int iax2_do_debug(int fd, int argc, char *argv[])
2667 return RESULT_SHOWUSAGE;
2669 ast_cli(fd, "IAX2 Debugging Enabled\n");
2670 return RESULT_SUCCESS;
2673 static int iax2_no_debug(int fd, int argc, char *argv[])
2676 return RESULT_SHOWUSAGE;
2678 ast_cli(fd, "IAX2 Debugging Disabled\n");
2679 return RESULT_SUCCESS;
2684 static char show_users_usage[] =
2685 "Usage: iax2 show users\n"
2686 " Lists all users known to the IAX (Inter-Asterisk eXchange rev 2) subsystem.\n";
2688 static char show_channels_usage[] =
2689 "Usage: iax2 show channels\n"
2690 " Lists all currently active IAX channels.\n";
2692 static char show_peers_usage[] =
2693 "Usage: iax2 show peers\n"
2694 " Lists all known IAX peers.\n";
2696 static char show_reg_usage[] =
2697 "Usage: iax2 show registry\n"
2698 " Lists all registration requests and status.\n";
2700 static char debug_usage[] =
2701 "Usage: iax2 debug\n"
2702 " Enables dumping of IAX packets for debugging purposes\n";
2704 static char no_debug_usage[] =
2705 "Usage: iax2 no debug\n"
2706 " Disables dumping of IAX packets for debugging purposes\n";
2708 static char debug_trunk_usage[] =
2709 "Usage: iax2 trunk debug\n"
2710 " Requests current status of IAX trunking\n";
2712 static struct ast_cli_entry cli_show_users =
2713 { { "iax2", "show", "users", NULL }, iax2_show_users, "Show defined IAX users", show_users_usage };
2714 static struct ast_cli_entry cli_show_channels =
2715 { { "iax2", "show", "channels", NULL }, iax2_show_channels, "Show active IAX channels", show_channels_usage };
2716 static struct ast_cli_entry cli_show_peers =
2717 { { "iax2", "show", "peers", NULL }, iax2_show_peers, "Show defined IAX peers", show_peers_usage };
2718 static struct ast_cli_entry cli_show_registry =
2719 { { "iax2", "show", "registry", NULL }, iax2_show_registry, "Show IAX registration status", show_reg_usage };
2720 static struct ast_cli_entry cli_debug =
2721 { { "iax2", "debug", NULL }, iax2_do_debug, "Enable IAX debugging", debug_usage };
2722 static struct ast_cli_entry cli_trunk_debug =
2723 { { "iax2", "trunk", "debug", NULL }, iax2_do_trunk_debug, "Request IAX trunk debug", debug_trunk_usage };
2724 static struct ast_cli_entry cli_no_debug =
2725 { { "iax2", "no", "debug", NULL }, iax2_no_debug, "Disable IAX debugging", no_debug_usage };
2727 static int iax2_write(struct ast_channel *c, struct ast_frame *f)
2729 struct chan_iax2_pvt *i = c->pvt->pvt;
2732 /* If there's an outstanding error, return failure now */
2734 ast_log(LOG_DEBUG, "Write error: %s\n", strerror(errno));
2737 /* If it's already gone, just return */
2740 /* Don't waste bandwidth sending null frames */
2741 if (f->frametype == AST_FRAME_NULL)
2743 /* If we're quelching voice, don't bother sending it */
2744 if ((f->frametype == AST_FRAME_VOICE) && i->quelch)
2746 if (!(i->state & IAX_STATE_STARTED))
2748 /* Simple, just queue for transmission */
2749 return iax2_send(i, f, 0, -1, 0, 0, 0);
2752 static int __send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno,
2753 int now, int transfer, int final)
2757 f.subclass = command;
2758 f.datalen = datalen;
2762 f.src = __FUNCTION__;
2764 return iax2_send(i, &f, ts, seqno, now, transfer, final);
2767 static int send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2769 return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 0);
2772 #ifdef BRIDGE_OPTIMIZATION
2773 static int forward_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2775 return __send_command(iaxs[i->bridgecallno], type, command, ts, data, datalen, seqno, 0, 0, 0);
2779 static int send_command_final(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2781 /* It is assumed that the callno has already been locked */
2782 iax2_predestroy_nolock(i->callno);
2783 return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 1);
2786 static int send_command_immediate(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2788 return __send_command(i, type, command, ts, data, datalen, seqno, 1, 0, 0);
2791 static int send_command_transfer(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen)
2793 return __send_command(i, type, command, ts, data, datalen, 0, 0, 1, 0);
2796 static int apply_context(struct iax2_context *con, char *context)
2799 if (!strcmp(con->context, context))
2807 static int check_access(int callno, struct sockaddr_in *sin, struct iax_ies *ies)
2809 /* Start pessimistic */
2812 struct iax2_user *user;
2813 int gotcapability=0;
2816 if (ies->called_number)
2817 strncpy(iaxs[callno]->exten, ies->called_number, sizeof(iaxs[callno]->exten) - 1);
2818 if (ies->calling_number) {
2819 if (ies->calling_name)
2820 snprintf(iaxs[callno]->callerid, sizeof(iaxs[callno]->callerid), "\"%s\" <%s>", ies->calling_name, ies->calling_number);
2822 strncpy(iaxs[callno]->callerid, ies->calling_number, sizeof(iaxs[callno]->callerid) - 1);
2823 } else if (ies->calling_name)
2824 strncpy(iaxs[callno]->callerid, ies->calling_name, sizeof(iaxs[callno]->callerid) - 1);
2825 if (ies->calling_ani)
2826 strncpy(iaxs[callno]->ani, ies->calling_ani, sizeof(iaxs[callno]->ani) - 1);
2828 strncpy(iaxs[callno]->dnid, ies->dnid, sizeof(iaxs[callno]->dnid)-1);
2829 if (ies->called_context)
2830 strncpy(iaxs[callno]->context, ies->called_context, sizeof(iaxs[callno]->context)-1);
2832 strncpy(iaxs[callno]->language, ies->language, sizeof(iaxs[callno]->language)-1);
2834 strncpy(iaxs[callno]->username, ies->username, sizeof(iaxs[callno]->username)-1);
2836 iaxs[callno]->peerformat = ies->format;
2838 iaxs[callno]->peeradsicpe = ies->adsicpe;
2839 if (ies->capability) {
2841 iaxs[callno]->peercapability = ies->capability;
2844 version = ies->version;
2846 iaxs[callno]->peercapability = iaxs[callno]->peerformat;
2847 if (version > IAX_PROTO_VERSION) {
2848 ast_log(LOG_WARNING, "Peer '%s' has too new a protocol version (%d) for me\n",
2849 inet_ntoa(sin->sin_addr), version);
2852 ast_mutex_lock(&userl.lock);
2853 /* Search the userlist for a compatible entry, and fill in the rest */
2856 if ((!strlen(iaxs[callno]->username) || /* No username specified */
2857 !strcmp(iaxs[callno]->username, user->name)) /* Or this username specified */
2858 && ast_apply_ha(user->ha, sin) /* Access is permitted from this IP */
2859 && (!strlen(iaxs[callno]->context) || /* No context specified */
2860 apply_context(user->contexts, iaxs[callno]->context))) { /* Context is permitted */
2865 ast_mutex_unlock(&userl.lock);
2866 #ifdef MYSQL_FRIENDS
2867 if (!user && mysql && strlen(iaxs[callno]->username) && (strlen(iaxs[callno]->username) < 128)) {
2868 user = mysql_user(iaxs[callno]->username);
2869 if (user && strlen(iaxs[callno]->context) && /* No context specified */
2870 !apply_context(user->contexts, iaxs[callno]->context)) { /* Context is permitted */
2872 free(user->contexts);
2879 /* We found our match (use the first) */
2881 /* Store the requested username if not specified */
2882 if (!strlen(iaxs[callno]->username))
2883 strncpy(iaxs[callno]->username, user->name, sizeof(iaxs[callno]->username)-1);
2884 /* Store whether this is a trunked call, too, of course, and move if appropriate */
2885 iaxs[callno]->trunk = user->trunk;
2886 iaxs[callno]->capability = user->capability;
2887 /* And use the default context */
2888 if (!strlen(iaxs[callno]->context)) {
2890 strncpy(iaxs[callno]->context, user->contexts->context, sizeof(iaxs[callno]->context)-1);
2892 strncpy(iaxs[callno]->context, context, sizeof(iaxs[callno]->context)-1);
2894 /* Copy the secret */
2895 strncpy(iaxs[callno]->secret, user->secret, sizeof(iaxs[callno]->secret)-1);
2896 /* And any input keys */
2897 strncpy(iaxs[callno]->inkeys, user->inkeys, sizeof(iaxs[callno]->inkeys));
2898 /* And the permitted authentication methods */
2899 iaxs[callno]->authmethods = user->authmethods;
2900 /* If they have callerid, override the given caller id. Always store the ANI */
2901 if (strlen(iaxs[callno]->callerid)) {
2902 if (user->hascallerid)
2903 strncpy(iaxs[callno]->callerid, user->callerid, sizeof(iaxs[callno]->callerid)-1);
2904 strncpy(iaxs[callno]->ani, user->callerid, sizeof(iaxs[callno]->ani)-1);
2906 if (strlen(user->accountcode))
2907 strncpy(iaxs[callno]->accountcode, user->accountcode, sizeof(iaxs[callno]->accountcode)-1);
2909 iaxs[callno]->amaflags = user->amaflags;
2910 iaxs[callno]->notransfer = user->notransfer;
2913 iaxs[callno]->trunk = iax2_getpeertrunk(*sin);
2917 static int raw_hangup(struct sockaddr_in *sin, unsigned short src, unsigned short dst)
2919 struct ast_iax2_full_hdr fh;
2920 fh.scallno = htons(src | IAX_FLAG_FULL);
2921 fh.dcallno = htons(dst);
2925 fh.type = AST_FRAME_IAX;
2926 fh.csub = compress_subclass(IAX_COMMAND_INVAL);
2930 ast_log(LOG_DEBUG, "Raw Hangup %s:%d, src=%d, dst=%d\n",
2931 inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), src, dst);
2932 return sendto(netsocket, &fh, sizeof(fh), 0, (struct sockaddr *)sin, sizeof(*sin));
2935 static int authenticate_request(struct chan_iax2_pvt *p)
2937 struct iax_ie_data ied;
2938 memset(&ied, 0, sizeof(ied));
2939 iax_ie_append_short(&ied, IAX_IE_AUTHMETHODS, p->authmethods);
2940 if (p->authmethods & (IAX_AUTH_MD5 | IAX_AUTH_RSA)) {
2941 snprintf(p->challenge, sizeof(p->challenge), "%d", rand());
2942 iax_ie_append_str(&ied, IAX_IE_CHALLENGE, p->challenge);
2944 iax_ie_append_str(&ied,IAX_IE_USERNAME, p->username);
2945 return send_command(p, AST_FRAME_IAX, IAX_COMMAND_AUTHREQ, 0, ied.buf, ied.pos, -1);
2948 static int authenticate_verify(struct chan_iax2_pvt *p, struct iax_ies *ies)
2950 char requeststr[256] = "";
2951 char md5secret[256] = "";
2952 char secret[256] = "";
2953 char rsasecret[256] = "";
2957 if (!(p->state & IAX_STATE_AUTHENTICATED))
2960 strncpy(secret, ies->password, sizeof(secret) - 1);
2961 if (ies->md5_result)
2962 strncpy(md5secret, ies->md5_result, sizeof(md5secret)-1);
2963 if (ies->rsa_result)
2964 strncpy(rsasecret, ies->rsa_result, sizeof(rsasecret)-1);
2965 if ((p->authmethods & IAX_AUTH_RSA) && strlen(rsasecret) && strlen(p->inkeys)) {
2966 struct ast_key *key;
2970 strncpy(tmpkey, p->inkeys, sizeof(tmpkey));
2972 keyn = strsep(&stringp, ":");
2974 key = ast_key_get(keyn, AST_KEY_PUBLIC);
2975 if (key && !ast_check_signature(key, p->challenge, rsasecret)) {
2979 ast_log(LOG_WARNING, "requested inkey '%s' for RSA authentication does not exist\n", keyn);
2980 keyn = strsep(&stringp, ":");
2982 } else if (p->authmethods & IAX_AUTH_MD5) {
2983 struct MD5Context md5;
2984 unsigned char digest[16];
2986 MD5Update(&md5, p->challenge, strlen(p->challenge));
2987 MD5Update(&md5, p->secret, strlen(p->secret));
2988 MD5Final(digest, &md5);
2989 /* If they support md5, authenticate with it. */
2991 sprintf(requeststr + (x << 1), "%2.2x", digest[x]);
2992 if (!strcasecmp(requeststr, md5secret))
2994 } else if (p->authmethods & IAX_AUTH_PLAINTEXT) {
2995 if (!strcmp(secret, p->secret))
3001 static int register_verify(int callno, struct sockaddr_in *sin, struct iax_ies *ies)
3003 char requeststr[256] = "";
3004 char peer[256] = "";
3005 char md5secret[256] = "";
3006 char rsasecret[256] = "";
3007 char secret[256] = "";
3008 struct iax2_peer *p;
3009 struct ast_key *key;
3014 iaxs[callno]->state &= ~IAX_STATE_AUTHENTICATED;
3015 strcpy(iaxs[callno]->peer, "");
3017 strncpy(peer, ies->username, sizeof(peer) - 1);
3019 strncpy(secret, ies->password, sizeof(secret) - 1);
3020 if (ies->md5_result)
3021 strncpy(md5secret, ies->md5_result, sizeof(md5secret)-1);
3022 if (ies->rsa_result)
3023 strncpy(rsasecret, ies->rsa_result, sizeof(rsasecret)-1);
3025 expire = ies->refresh;
3027 if (!strlen(peer)) {
3028 ast_log(LOG_NOTICE, "Empty registration from %s\n", inet_ntoa(sin->sin_addr));
3032 ast_mutex_lock(&peerl.lock);
3033 for (p = peerl.peers; p ; p = p->next)
3034 if (!strcasecmp(p->name, peer))
3036 ast_mutex_unlock(&peerl.lock);
3037 #ifdef MYSQL_FRIENDS
3039 p = mysql_peer(peer);
3043 ast_log(LOG_NOTICE, "No registration for peer '%s' (from %s)\n", peer, inet_ntoa(sin->sin_addr));
3048 ast_log(LOG_NOTICE, "Peer '%s' is not dynamic (from %s)\n", peer, inet_ntoa(sin->sin_addr));
3054 if (!ast_apply_ha(p->