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 <arpa/inet.h>
34 #include <sys/socket.h>
35 #include <netinet/in.h>
36 #include <netinet/ip.h>
38 #include <sys/signal.h>
50 * Uncomment to try experimental IAX bridge optimization,
51 * designed to reduce latency when IAX calls cannot
55 #define BRIDGE_OPTIMIZATION
58 #define DEFAULT_RETRY_TIME 1000
59 #define MEMORY_SIZE 100
60 #define DEFAULT_DROP 3
64 /* Sample over last 100 units to determine historic jitter */
67 static char *desc = "Inter Asterisk eXchange (Ver 2)";
68 static char *tdesc = "Inter Asterisk eXchange Drver (Ver 2)";
69 static char *type = "IAX2";
71 static char context[80] = "default";
73 static int max_retries = 4;
74 static int ping_time = 20;
75 static int lagrq_time = 10;
76 static int nextcallno = 0;
77 static int maxjitterbuffer=3000;
79 static int iaxdefaultdpcache=10 * 60; /* Cache dialplan entries for 10 minutes by default */
81 static int iaxdefaulttimeout = 5; /* Default to wait no more than 5 seconds for a reply to come back */
83 static int netsocket = -1;
87 static int expirey = AST_DEFAULT_REG_EXPIRE;
90 static pthread_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
92 int (*regfunk)(char *username, int onoff) = NULL;
95 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
97 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
98 ~AST_FORMAT_SLINEAR & \
102 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
106 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
110 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
111 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
112 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
114 static struct io_context *io;
115 static struct sched_context *sched;
117 static int iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
119 static int iax2_dropcount = DEFAULT_DROP;
121 static int use_jitterbuffer = 1;
123 static int iaxdebug = 0;
125 static char accountcode[20];
126 static int amaflags = 0;
128 static pthread_t netthreadid;
130 #define IAX_STATE_STARTED (1 << 0)
131 #define IAX_STATE_AUTHENTICATED (1 << 1)
132 #define IAX_STATE_TBD (1 << 2)
134 struct iax2_context {
135 char context[AST_MAX_EXTENSION];
136 struct iax2_context *next;
143 char accountcode[20];
144 char inkeys[80]; /* Key(s) this user can use to authenticate to us */
147 char callerid[AST_MAX_EXTENSION];
149 struct iax2_context *contexts;
150 struct iax2_user *next;
157 char outkey[80]; /* What key we use to talk to this peer */
158 char context[AST_MAX_EXTENSION]; /* Default context (for transfer really) */
159 struct sockaddr_in addr;
163 /* Dynamic Registration fields */
164 int dynamic; /* If this is a dynamic peer */
165 struct sockaddr_in defaddr; /* Default address if there is one */
166 char challenge[80]; /* Challenge used to authenticate the secret */
167 int authmethods; /* Authentication methods (IAX_AUTH_*) */
168 char inkeys[80]; /* Key(s) this peer can use to authenticate to us */
171 /* Suggested caller id if registering */
172 char callerid[AST_MAX_EXTENSION];
173 /* Whether or not to send ANI */
175 int expire; /* Schedule entry for expirey */
176 int expirey; /* How soon to expire */
177 int capability; /* Capability */
178 int delme; /* I need to be deleted */
181 int callno; /* Call number of POKE request */
182 int pokeexpire; /* When to expire poke */
183 int lastms; /* How long last response took (in ms), or -1 for no response */
184 int maxms; /* Max ms we will accept for the host to be up, 0 to not monitor */
187 struct iax2_peer *next;
190 #define REG_STATE_UNREGISTERED 0
191 #define REG_STATE_REGSENT 1
192 #define REG_STATE_AUTHSENT 2
193 #define REG_STATE_REGISTERED 3
194 #define REG_STATE_REJECTED 4
195 #define REG_STATE_TIMEOUT 5
196 #define REG_STATE_NOAUTH 6
198 #define TRANSFER_NONE 0
199 #define TRANSFER_BEGIN 1
200 #define TRANSFER_READY 2
201 #define TRANSFER_RELEASED 3
202 #define TRANSFER_PASSTHROUGH 4
204 struct iax2_registry {
205 struct sockaddr_in addr; /* Who we connect to for registration purposes */
207 char secret[80]; /* Password or key name in []'s */
209 int expire; /* Sched ID of expiration */
210 int refresh; /* How often to refresh */
212 int callno; /* Associated call number if applicable */
213 struct sockaddr_in us; /* Who the server thinks we are */
214 struct iax2_registry *next;
217 struct iax2_registry *registrations;
219 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
220 #define MIN_RETRY_TIME 10
221 #define MAX_RETRY_TIME 10000
222 #define MAX_JITTER_BUFFER 50
224 /* If we have more than this much excess real jitter buffer, srhink it. */
225 static int max_jitter_buffer = MAX_JITTER_BUFFER;
227 struct chan_iax2_pvt {
228 /* Pipes for communication. pipe[1] belongs to the
229 network thread (write), and pipe[0] belongs to the individual
231 /* Whether or not we Quelch audio */
233 /* Last received voice format */
235 /* Last sent voice format */
237 /* What we are capable of sending */
239 /* Last received timestamp */
241 /* Last sent timestamp - never send the same timestamp twice in a single call */
242 unsigned int lastsent;
244 unsigned int pingtime;
245 /* Max time for initial response */
248 struct sockaddr_in addr;
249 /* Our call number */
250 unsigned short callno;
252 unsigned short peercallno;
253 /* Peer selected format */
255 /* Peer capability */
257 /* timeval that we base our transmission on */
258 struct timeval offset;
259 /* timeval that we base our delivery on */
260 struct timeval rxcore;
261 /* Historical delivery time */
262 int history[MEMORY_SIZE];
263 /* Current base jitterbuffer */
265 /* Current jitter measure */
267 /* Historic jitter value */
271 /* Error, as discovered by the manager */
273 /* Owner if we have one */
274 struct ast_channel *owner;
275 /* What's our state? */
277 /* Expirey (optional) */
279 /* Next outgoing sequence number */
280 unsigned short oseqno;
281 /* Next sequence number they have not yet acknowledged */
282 unsigned short rseqno;
283 /* Next incoming sequence number */
284 unsigned short iseqno;
285 /* Last incoming sequence number we have acknowledged */
286 unsigned short aseqno;
289 /* Default Context */
291 /* Caller ID if available */
293 /* Hidden Caller ID (i.e. ANI) if appropriate */
295 /* Whether or not ani should be transmitted in addition to Caller*ID */
299 /* Requested Extension */
300 char exten[AST_MAX_EXTENSION];
301 /* Expected Username */
303 /* Expected Secret */
305 /* permitted authentication methods */
309 /* Public keys permitted keys for incoming authentication */
311 /* Private key for outgoing authentication */
313 /* Preferred language */
315 /* Associated registry */
316 struct iax2_registry *reg;
317 /* Associated peer for poking */
318 struct iax2_peer *peerpoke;
320 /* Transferring status */
322 /* Already disconnected */
324 /* Who we are IAX transfering to */
325 struct sockaddr_in transfer;
326 /* What's the new call number for the transfer */
327 unsigned short transfercallno;
329 /* Status of knowledge of peer ADSI capability */
332 /* Who we are bridged to */
333 unsigned short bridgecallno;
334 int pingid; /* Transmit PING request */
335 int lagid; /* Retransmit lag request */
336 int autoid; /* Auto hangup for Dialplan requestor */
337 int initid; /* Initial peer auto-congest ID (based on qualified peers) */
338 char dproot[AST_MAX_EXTENSION];
339 char accountcode[20];
341 struct iax2_dpcache *dpentries;
344 #define DIRECTION_INGRESS 1
345 #define DIRECTION_OUTGRESS 2
347 struct ast_iax2_frame {
348 /* Actual, isolated frame */
350 /* /Our/ call number */
351 unsigned short callno;
352 /* /Their/ call number */
353 unsigned short dcallno;
354 /* Start of raw frame (outgoing only) */
356 /* Length of frame (outgoing only) */
358 /* How many retries so far? */
360 /* Outgoing relative timestamp (ms) */
362 /* How long to wait before retrying */
364 /* Are we received out of order? */
366 /* Have we been sent at all yet? */
368 /* Outgoing Packet sequence number */
370 /* Next expected incoming packet sequence number */
372 /* Non-zero if should be sent to transfer peer */
374 /* Non-zero if this is the final message */
376 /* Ingress or outgres */
378 /* Retransmission ID */
383 struct ast_iax2_frame *next;
384 struct ast_iax2_frame *prev;
389 char *calling_number;
392 char *called_context;
405 struct sockaddr_in *apparent_addr;
406 unsigned short refresh;
407 unsigned short dpstatus;
408 unsigned short callno;
413 unsigned char buf[1024];
417 static struct ast_iax2_queue {
418 struct ast_iax2_frame *head;
419 struct ast_iax2_frame *tail;
421 pthread_mutex_t lock;
424 static struct ast_user_list {
425 struct iax2_user *users;
426 pthread_mutex_t lock;
429 static struct ast_peer_list {
430 struct iax2_peer *peers;
431 pthread_mutex_t lock;
434 /* Extension exists */
435 #define CACHE_FLAG_EXISTS (1 << 0)
436 /* Extension is non-existant */
437 #define CACHE_FLAG_NONEXISTANT (1 << 1)
438 /* Extension can exist */
439 #define CACHE_FLAG_CANEXIST (1 << 2)
440 /* Waiting to hear back response */
441 #define CACHE_FLAG_PENDING (1 << 3)
443 #define CACHE_FLAG_TIMEOUT (1 << 4)
444 /* Request transmitted */
445 #define CACHE_FLAG_TRANSMITTED (1 << 5)
447 #define CACHE_FLAG_UNKNOWN (1 << 6)
449 #define CACHE_FLAG_MATCHMORE (1 << 7)
451 static struct iax2_dpcache {
452 char peercontext[AST_MAX_EXTENSION];
453 char exten[AST_MAX_EXTENSION];
455 struct timeval expirey;
457 unsigned short callno;
459 struct iax2_dpcache *next;
460 struct iax2_dpcache *peer; /* For linking in peers */
463 pthread_mutex_t dpcache_lock;
465 static struct iax2_ie {
469 { IAX_IE_CALLED_NUMBER, "CALLED NUMBER" },
470 { IAX_IE_CALLING_NUMBER, "CALLING NUMBER" },
471 { IAX_IE_CALLING_NUMBER, "ANI" },
472 { IAX_IE_CALLING_NAME, "CALLING NAME" },
473 { IAX_IE_CALLED_CONTEXT, "CALLED CONTEXT" },
474 { IAX_IE_USERNAME, "USERNAME" },
475 { IAX_IE_PASSWORD, "PASSWORD" },
476 { IAX_IE_CAPABILITY, "CAPABILITY" },
477 { IAX_IE_FORMAT, "FORMAT" },
478 { IAX_IE_LANGUAGE, "LANGUAGE" },
479 { IAX_IE_VERSION, "VERSION" },
480 { IAX_IE_ADSICPE, "ADSICPE" },
481 { IAX_IE_DNID, "DNID" },
482 { IAX_IE_AUTHMETHODS, "AUTHMETHODS" },
483 { IAX_IE_CHALLENGE, "CHALLENGE" },
484 { IAX_IE_MD5_RESULT, "MD5 RESULT" },
485 { IAX_IE_RSA_RESULT, "RSA RESULT" },
486 { IAX_IE_APPARENT_ADDR, "APPARENT ADDRESS" },
487 { IAX_IE_REFRESH, "REFRESH" },
488 { IAX_IE_DPSTATUS, "DIALPLAN STATUS" },
489 { IAX_IE_CALLNO, "CALL NUMBER" },
490 { IAX_IE_CAUSE, "CAUSE" },
493 static char *ie2str(int ie)
496 for (x=0;x<sizeof(ies) / sizeof(ies[0]); x++) {
504 void showframe(struct ast_iax2_frame *f, struct ast_iax2_full_hdr *fhi, int rx, struct sockaddr_in *sin)
561 struct ast_iax2_full_hdr *fh;
569 snprintf(retries, sizeof(retries), "%03d", f->retries);
572 if (ntohs(fh->dcallno) & AST_FLAG_RETRANS)
573 strcpy(retries, "Yes");
575 strcpy(retries, "No");
577 if (!(ntohs(fh->scallno) & AST_FLAG_FULL)) {
578 /* Don't mess with mini-frames */
581 if (fh->type > sizeof(frames)/sizeof(char *)) {
582 snprintf(class2, sizeof(class2), "(%d?)", fh->type);
585 class = frames[(int)fh->type];
587 if (fh->type == AST_FRAME_DTMF) {
588 sprintf(subclass2, "%c", fh->csub);
589 subclass = subclass2;
590 } else if (fh->type == AST_FRAME_IAX) {
591 if (fh->csub >= sizeof(iaxs)/sizeof(iaxs[0])) {
592 snprintf(subclass2, sizeof(subclass2), "(%d?)", fh->csub);
593 subclass = subclass2;
595 subclass = iaxs[(int)fh->csub];
597 } else if (fh->type == AST_FRAME_CONTROL) {
598 if (fh->csub > sizeof(cmds)/sizeof(char *)) {
599 snprintf(subclass2, sizeof(subclass2), "(%d?)", fh->csub);
600 subclass = subclass2;
602 subclass = cmds[(int)fh->csub];
605 snprintf(subclass2, sizeof(subclass2), "%d", fh->csub);
606 subclass = subclass2;
609 "%s-Frame Retry[%s] -- OSeqno: %4.4d ISeqno: %4.4d Type: %s Subclass: %s\n",
611 retries, ntohs(fh->oseqno), ntohs(fh->iseqno), class, subclass);
613 " Timestamp: %05dms SCall: %5.5d DCall: %5.5d [%s:%d]\n",
615 ntohs(fh->scallno) & ~AST_FLAG_FULL, ntohs(fh->dcallno),
616 inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
620 /* XXX We probably should use a mutex when working with this XXX */
621 static struct chan_iax2_pvt *iaxs[AST_IAX2_MAX_CALLS];
622 static pthread_mutex_t iaxsl[AST_IAX2_MAX_CALLS];
624 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, char *, int, int);
625 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, char *, int, int);
626 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, char *, int, int);
627 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, char *, int);
629 static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts);
631 static int send_ping(void *data)
633 int callno = (long)data;
634 /* Ping only if it's real, not if it's bridged */
636 #ifdef BRIDGE_OPTIMIZATION
637 if (!iaxs[callno]->bridgecallno)
639 send_command(iaxs[callno], AST_FRAME_IAX, AST_IAX2_COMMAND_PING, 0, NULL, 0, -1);
645 static int send_lagrq(void *data)
647 int callno = (long)data;
648 /* Ping only if it's real not if it's bridged */
650 #ifdef BRIDGE_OPTIMIZATION
651 if (!iaxs[callno]->bridgecallno)
653 send_command(iaxs[callno], AST_FRAME_IAX, AST_IAX2_COMMAND_LAGRQ, 0, NULL, 0, -1);
659 static unsigned char compress_subclass(int subclass)
663 /* If it's 128 or smaller, just return it */
664 if (subclass < AST_FLAG_SC_LOG)
666 /* Otherwise find its power */
667 for (x = 0; x < AST_MAX_SHIFT; x++) {
668 if (subclass & (1 << x)) {
670 ast_log(LOG_WARNING, "Can't compress subclass %d\n", subclass);
676 return power | AST_FLAG_SC_LOG;
679 static int uncompress_subclass(unsigned char csub)
681 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
682 if (csub & AST_FLAG_SC_LOG) {
683 /* special case for 'compressed' -1 */
687 return 1 << (csub & ~AST_FLAG_SC_LOG & AST_MAX_SHIFT);
693 static struct chan_iax2_pvt *new_iax(void)
695 struct chan_iax2_pvt *tmp;
696 tmp = malloc(sizeof(struct chan_iax2_pvt));
698 memset(tmp, 0, sizeof(struct chan_iax2_pvt));
701 tmp->transfercallno = 0;
702 tmp->bridgecallno = 0;
707 /* strncpy(tmp->context, context, sizeof(tmp->context)-1); */
708 strncpy(tmp->exten, "s", sizeof(tmp->exten)-1);
713 static int get_samples(struct ast_frame *f)
716 switch(f->subclass) {
717 case AST_FORMAT_G723_1:
718 samples = 240 /* XXX Not necessarily true XXX */;
721 samples = 160 * (f->datalen / 33);
723 case AST_FORMAT_SLINEAR:
724 samples = f->datalen / 2;
726 case AST_FORMAT_LPC10:
728 samples += (((char *)(f->data))[7] & 0x1) * 8;
730 case AST_FORMAT_ULAW:
731 samples = f->datalen;
733 case AST_FORMAT_ALAW:
734 samples = f->datalen;
736 case AST_FORMAT_ADPCM:
737 samples = f->datalen *2;
740 ast_log(LOG_WARNING, "Don't know how to calculate samples on %d packets\n", f->subclass);
745 static int frames = 0;
746 static int iframes = 0;
747 static int oframes = 0;
749 static struct ast_iax2_frame *ast_iax2_frame_new(int direction)
751 struct ast_iax2_frame *fr;
752 fr = malloc(sizeof(struct ast_iax2_frame));
754 fr->direction = direction;
757 if (fr->direction == DIRECTION_INGRESS)
765 static void ast_iax2_frame_free(struct ast_iax2_frame *fr)
767 if (fr->retrans > -1)
768 ast_sched_del(sched, fr->retrans);
769 if (fr->direction == DIRECTION_INGRESS)
771 else if (fr->direction == DIRECTION_OUTGRESS)
774 ast_log(LOG_WARNING, "Attempt to double free frame detected\n");
783 static struct ast_iax2_frame *iaxfrdup2(struct ast_iax2_frame *fr, int ch)
785 /* Malloc() a copy of a frame */
786 struct ast_iax2_frame *new = ast_iax2_frame_new(DIRECTION_INGRESS);
788 memcpy(new, fr, sizeof(struct ast_iax2_frame));
789 new->f = ast_frdup(fr->f);
790 /* Copy full header */
792 memcpy(new->f->data - sizeof(struct ast_iax2_full_hdr),
793 fr->f->data - sizeof(struct ast_iax2_full_hdr),
794 sizeof(struct ast_iax2_full_hdr));
795 /* Grab new data pointer */
796 new->data = new->f->data - (fr->f->data - fr->data);
801 new->direction = DIRECTION_INGRESS;
807 #define NEW_PREVENT 0
811 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, struct chan_iax2_pvt *cur)
813 if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
814 (cur->addr.sin_port == sin->sin_port)) {
815 /* This is the main host */
816 if ((cur->peercallno == callno) ||
817 ((dcallno == cur->callno) && !cur->peercallno)) {
818 /* That's us. Be sure we keep track of the peer call number */
822 if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
823 (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
824 /* We're transferring */
825 if (dcallno == cur->callno)
831 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new)
836 if (new <= NEW_ALLOW) {
837 /* Look for an existing connection first */
838 for (x=0;(res < 0) && (x<AST_IAX2_MAX_CALLS);x++) {
839 ast_pthread_mutex_lock(&iaxsl[x]);
841 /* Look for an exact match */
842 if (match(sin, callno, dcallno, iaxs[x])) {
846 ast_pthread_mutex_unlock(&iaxsl[x]);
849 if ((res < 0) && (new >= NEW_ALLOW)) {
850 /* Create a new one */
852 for (x = ((nextcallno + 1) % (AST_IAX2_MAX_CALLS - 1)) + 1; iaxs[x] && (x != start); x = (x + 1) % AST_IAX2_MAX_CALLS)
854 ast_log(LOG_WARNING, "Unable to accept more calls\n");
857 ast_pthread_mutex_lock(&iaxsl[x]);
859 ast_pthread_mutex_unlock(&iaxsl[x]);
862 ast_log(LOG_DEBUG, "Creating new call structure %d\n", x);
863 iaxs[x]->addr.sin_port = sin->sin_port;
864 iaxs[x]->addr.sin_family = sin->sin_family;
865 iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
866 iaxs[x]->peercallno = callno;
868 iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
869 iaxs[x]->expirey = expirey;
870 iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)x);
871 iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)x);
872 iaxs[x]->amaflags = amaflags;
873 strncpy(iaxs[x]->accountcode, accountcode, sizeof(iaxs[x]->accountcode)-1);
875 ast_log(LOG_WARNING, "Out of resources\n");
884 static int iax2_queue_frame(int callno, struct ast_frame *f)
887 /* Assumes lock for callno is already held... */
890 if (!pthread_mutex_trylock(&iaxsl[callno])) {
891 ast_log(LOG_WARNING, "Lock is not held on pass %d of iax2_queue_frame\n", pass);
894 if (iaxs[callno] && iaxs[callno]->owner) {
895 if (pthread_mutex_trylock(&iaxs[callno]->owner->lock)) {
896 /* Avoid deadlock by pausing and trying again */
897 ast_pthread_mutex_unlock(&iaxsl[callno]);
899 ast_pthread_mutex_lock(&iaxsl[callno]);
901 ast_queue_frame(iaxs[callno]->owner, f, 0);
902 ast_pthread_mutex_unlock(&iaxs[callno]->owner->lock);
911 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
913 static int __do_deliver(void *data)
915 /* Just deliver the packet by using queueing. This is called by
916 the IAX thread with the iaxsl lock held. */
917 struct ast_iax2_frame *fr = data;
920 if (iaxs[fr->callno] && !iaxs[fr->callno]->alreadygone) {
921 if (fr->f->frametype == AST_FRAME_IAX) {
922 /* We have to treat some of these packets specially because
923 they're LAG measurement packets */
924 if (fr->f->subclass == AST_IAX2_COMMAND_LAGRQ) {
925 /* If we got a queued request, build a reply and send it */
926 fr->f->subclass = AST_IAX2_COMMAND_LAGRP;
927 iax2_send(iaxs[fr->callno], fr->f, fr->ts, -1, 0, 0, 0);
928 } else if (fr->f->subclass == AST_IAX2_COMMAND_LAGRP) {
929 /* This is a reply we've been given, actually measure the difference */
930 ts = calc_timestamp(iaxs[fr->callno], 0);
931 iaxs[fr->callno]->lag = ts - fr->ts;
934 iax2_queue_frame(fr->callno, fr->f);
937 /* Free the packet */
939 /* And our iax frame */
940 ast_iax2_frame_free(fr);
941 /* And don't run again */
945 static int do_deliver(void *data)
947 /* Locking version of __do_deliver */
948 struct ast_iax2_frame *fr = data;
949 int callno = fr->callno;
951 ast_pthread_mutex_lock(&iaxsl[callno]);
952 res = __do_deliver(data);
953 ast_pthread_mutex_unlock(&iaxsl[callno]);
957 static int handle_error(void)
959 /* XXX Ideally we should figure out why an error occured and then abort those
960 rather than continuing to try. Unfortunately, the published interface does
961 not seem to work XXX */
963 struct sockaddr_in *sin;
966 struct sock_extended_err e;
971 m.msg_controllen = sizeof(e);
973 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
975 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
977 if (m.msg_controllen) {
978 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
980 ast_log(LOG_WARNING, "Receive error from %s\n", inet_ntoa(sin->sin_addr));
982 ast_log(LOG_WARNING, "No address detected??\n");
984 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
991 static int send_packet(struct ast_iax2_frame *f)
994 /* Called with iaxsl held */
996 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));
997 /* Don't send if there was an error, but return error instead */
999 ast_log(LOG_WARNING, "Call number = %d\n", f->callno);
1002 if (!iaxs[f->callno])
1004 if (iaxs[f->callno]->error)
1007 #ifdef DEBUG_SUPPORT
1009 showframe(f, NULL, 0, &iaxs[f->callno]->transfer);
1011 res = sendto(netsocket, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[f->callno]->transfer,
1012 sizeof(iaxs[f->callno]->transfer));
1014 #ifdef DEBUG_SUPPORT
1016 showframe(f, NULL, 0, &iaxs[f->callno]->addr);
1018 res = sendto(netsocket, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[f->callno]->addr,
1019 sizeof(iaxs[f->callno]->addr));
1023 ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
1031 static int iax2_predestroy(int callno)
1033 struct ast_channel *c;
1034 struct chan_iax2_pvt *pvt;
1035 ast_pthread_mutex_lock(&iaxsl[callno]);
1038 ast_pthread_mutex_unlock(&iaxsl[callno]);
1041 if (!pvt->alreadygone) {
1042 /* No more pings or lagrq's */
1043 if (pvt->pingid > -1)
1044 ast_sched_del(sched, pvt->pingid);
1045 if (pvt->lagid > -1)
1046 ast_sched_del(sched, pvt->lagid);
1047 if (pvt->autoid > -1)
1048 ast_sched_del(sched, pvt->autoid);
1049 if (pvt->initid > -1)
1050 ast_sched_del(sched, pvt->initid);
1055 pvt->alreadygone = 1;
1059 c->_softhangup |= AST_SOFTHANGUP_DEV;
1061 ast_queue_hangup(c, 0);
1063 ast_pthread_mutex_lock(&usecnt_lock);
1066 ast_log(LOG_WARNING, "Usecnt < 0???\n");
1067 ast_pthread_mutex_unlock(&usecnt_lock);
1068 ast_update_use_count();
1070 ast_pthread_mutex_unlock(&iaxsl[callno]);
1074 static int iax2_predestroy_nolock(int callno)
1077 ast_pthread_mutex_unlock(&iaxsl[callno]);
1078 res = iax2_predestroy(callno);
1079 ast_pthread_mutex_lock(&iaxsl[callno]);
1083 static void iax2_destroy(int callno)
1085 struct chan_iax2_pvt *pvt;
1086 struct ast_iax2_frame *cur;
1087 struct ast_channel *owner;
1090 ast_pthread_mutex_lock(&iaxsl[callno]);
1092 iaxs[callno] = NULL;
1099 if (pthread_mutex_trylock(&owner->lock)) {
1100 ast_log(LOG_NOTICE, "Avoiding IAX destroy deadlock\n");
1101 ast_pthread_mutex_unlock(&iaxsl[callno]);
1108 /* No more pings or lagrq's */
1109 if (pvt->pingid > -1)
1110 ast_sched_del(sched, pvt->pingid);
1111 if (pvt->lagid > -1)
1112 ast_sched_del(sched, pvt->lagid);
1113 if (pvt->autoid > -1)
1114 ast_sched_del(sched, pvt->autoid);
1115 if (pvt->initid > -1)
1116 ast_sched_del(sched, pvt->initid);
1123 pvt->alreadygone = 1;
1126 /* If there's an owner, prod it to give up */
1127 owner->pvt->pvt = NULL;
1128 owner->_softhangup |= AST_SOFTHANGUP_DEV;
1129 ast_queue_hangup(owner, 0);
1132 for (cur = iaxq.head; cur ; cur = cur->next) {
1133 /* Cancel any pending transmissions */
1134 if (cur->callno == pvt->callno)
1138 pvt->reg->callno = 0;
1143 ast_pthread_mutex_unlock(&owner->lock);
1145 ast_pthread_mutex_unlock(&iaxsl[callno]);
1147 static void iax2_destroy_nolock(int callno)
1149 /* Actually it's easier to unlock, kill it, and relock */
1150 ast_pthread_mutex_unlock(&iaxsl[callno]);
1151 iax2_destroy(callno);
1152 ast_pthread_mutex_lock(&iaxsl[callno]);
1155 static int update_packet(struct ast_iax2_frame *f)
1157 /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
1158 struct ast_iax2_full_hdr *fh = f->data;
1159 /* Mark this as a retransmission */
1160 fh->dcallno = ntohs(AST_FLAG_RETRANS | f->dcallno);
1162 f->iseqno = iaxs[f->callno]->iseqno;
1163 fh->iseqno = ntohs(f->iseqno);
1167 static int attempt_transmit(void *data)
1169 /* Attempt to transmit the frame to the remote peer...
1170 Called without iaxsl held. */
1171 struct ast_iax2_frame *f = data;
1173 int callno = f->callno;
1174 /* Make sure this call is still active */
1176 ast_pthread_mutex_lock(&iaxsl[callno]);
1177 if ((f->callno) && iaxs[f->callno]) {
1178 if ((f->retries < 0) /* Already ACK'd */ ||
1179 (f->retries >= max_retries) /* Too many attempts */) {
1180 /* Record an error if we've transmitted too many times */
1181 if (f->retries >= max_retries) {
1183 /* Transfer timeout */
1184 send_command(iaxs[f->callno], AST_FRAME_IAX, AST_IAX2_COMMAND_TXREJ, 0, NULL, 0, -1);
1185 } else if (f->final) {
1187 iax2_destroy_nolock(f->callno);
1189 if (iaxs[f->callno]->owner)
1190 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->oseqno);
1191 iaxs[f->callno]->error = ETIMEDOUT;
1192 if (iaxs[f->callno]->owner) {
1193 struct ast_frame fr = { 0, };
1195 fr.frametype = AST_FRAME_CONTROL;
1196 fr.subclass = AST_CONTROL_HANGUP;
1197 iax2_queue_frame(f->callno, &fr);
1199 if (iaxs[f->callno]->reg) {
1200 memset(&iaxs[f->callno]->reg->us, 0, sizeof(iaxs[f->callno]->reg->us));
1201 iaxs[f->callno]->reg->regstate = REG_STATE_TIMEOUT;
1202 iaxs[f->callno]->reg->refresh = AST_DEFAULT_REG_EXPIRE;
1204 iax2_destroy_nolock(f->callno);
1211 /* Update it if it needs it */
1213 /* Attempt transmission */
1216 /* Try again later after 10 times as long */
1218 if (f->retrytime > MAX_RETRY_TIME)
1219 f->retrytime = MAX_RETRY_TIME;
1220 /* Transfer messages max out at one second */
1221 if (f->transfer && (f->retrytime > 1000))
1222 f->retrytime = 1000;
1223 f->retrans = ast_sched_add(sched, f->retrytime, attempt_transmit, f);
1226 /* Make sure it gets freed */
1231 ast_pthread_mutex_unlock(&iaxsl[callno]);
1232 /* Do not try again */
1234 /* Don't attempt delivery, just remove it from the queue */
1235 ast_pthread_mutex_lock(&iaxq.lock);
1237 f->prev->next = f->next;
1239 iaxq.head = f->next;
1241 f->next->prev = f->prev;
1243 iaxq.tail = f->prev;
1245 ast_pthread_mutex_unlock(&iaxq.lock);
1246 /* Free the frame */
1249 ast_iax2_frame_free(f);
1254 static int iax2_set_jitter(int fd, int argc, char *argv[])
1256 if ((argc != 4) && (argc != 5))
1257 return RESULT_SHOWUSAGE;
1259 max_jitter_buffer = atoi(argv[3]);
1260 if (max_jitter_buffer < 0)
1261 max_jitter_buffer = 0;
1264 if ((atoi(argv[3]) >= 0) && (atoi(argv[3]) < AST_IAX2_MAX_CALLS)) {
1265 if (iaxs[atoi(argv[3])]) {
1266 iaxs[atoi(argv[3])]->jitterbuffer = atoi(argv[4]);
1267 if (iaxs[atoi(argv[3])]->jitterbuffer < 0)
1268 iaxs[atoi(argv[3])]->jitterbuffer = 0;
1270 ast_cli(fd, "No such call '%d'\n", atoi(argv[3]));
1272 ast_cli(fd, "%d is not a valid call number\n", atoi(argv[3]));
1275 return RESULT_SUCCESS;
1278 static char jitter_usage[] =
1279 "Usage: iax set jitter [callid] <value>\n"
1280 " If used with a callid, it sets the jitter buffer to the given static\n"
1281 "value (until its next calculation). If used without a callid, the value is used\n"
1282 "to establish the maximum excess jitter buffer that is permitted before the jitter\n"
1283 "buffer size is reduced.";
1285 static int iax2_show_stats(int fd, int argc, char *argv[])
1287 struct ast_iax2_frame *cur;
1288 int cnt = 0, dead=0, final=0;
1290 return RESULT_SHOWUSAGE;
1291 for (cur = iaxq.head; cur ; cur = cur->next) {
1292 if (cur->retries < 0)
1298 ast_cli(fd, " IAX Statistics\n");
1299 ast_cli(fd, "---------------------\n");
1300 ast_cli(fd, "Outstanding frames: %d (%d ingress, %d outgress)\n", frames, iframes, oframes);
1301 ast_cli(fd, "Packets in transmit queue: %d dead, %d final, %d total\n", dead, final, cnt);
1302 return RESULT_SUCCESS;
1305 static int iax2_show_cache(int fd, int argc, char *argv[])
1307 struct iax2_dpcache *dp;
1308 char tmp[1024], *pc;
1312 gettimeofday(&tv, NULL);
1313 ast_pthread_mutex_lock(&dpcache_lock);
1315 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
1317 s = dp->expirey.tv_sec - tv.tv_sec;
1319 if (dp->flags & CACHE_FLAG_EXISTS)
1320 strcat(tmp, "EXISTS|");
1321 if (dp->flags & CACHE_FLAG_NONEXISTANT)
1322 strcat(tmp, "NONEXISTANT|");
1323 if (dp->flags & CACHE_FLAG_CANEXIST)
1324 strcat(tmp, "CANEXIST|");
1325 if (dp->flags & CACHE_FLAG_PENDING)
1326 strcat(tmp, "PENDING|");
1327 if (dp->flags & CACHE_FLAG_TIMEOUT)
1328 strcat(tmp, "TIMEOUT|");
1329 if (dp->flags & CACHE_FLAG_TRANSMITTED)
1330 strcat(tmp, "TRANSMITTED|");
1331 if (dp->flags & CACHE_FLAG_MATCHMORE)
1332 strcat(tmp, "MATCHMORE|");
1333 if (dp->flags & CACHE_FLAG_UNKNOWN)
1334 strcat(tmp, "UNKNOWN|");
1335 /* Trim trailing pipe */
1337 tmp[strlen(tmp) - 1] = '\0';
1339 strcpy(tmp, "(none)");
1341 pc = strchr(dp->peercontext, '@');
1343 pc = dp->peercontext;
1346 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
1347 if (dp->waiters[x] > -1)
1350 ast_cli(fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
1352 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
1355 ast_pthread_mutex_unlock(&dpcache_lock);
1356 return RESULT_SUCCESS;
1359 static char show_stats_usage[] =
1360 "Usage: iax show stats\n"
1361 " Display statistics on IAX channel driver.\n";
1364 static char show_cache_usage[] =
1365 "Usage: iax show cache\n"
1366 " Display currently cached IAX Dialplan results.\n";
1368 static struct ast_cli_entry cli_set_jitter =
1369 { { "iax2", "set", "jitter", NULL }, iax2_set_jitter, "Sets IAX jitter buffer", jitter_usage };
1371 static struct ast_cli_entry cli_show_stats =
1372 { { "iax2", "show", "stats", NULL }, iax2_show_stats, "Display IAX statistics", show_stats_usage };
1374 static struct ast_cli_entry cli_show_cache =
1375 { { "iax2", "show", "cache", NULL }, iax2_show_cache, "Display IAX cached dialplan", show_cache_usage };
1377 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p);
1379 #ifdef BRIDGE_OPTIMIZATION
1380 static unsigned int calc_fakestamp(struct chan_iax2_pvt *from, struct chan_iax2_pvt *to, unsigned int ts);
1382 static int forward_delivery(struct ast_iax2_frame *fr)
1384 struct chan_iax2_pvt *p1, *p2;
1385 p1 = iaxs[fr->callno];
1386 p2 = iaxs[p1->bridgecallno];
1391 /* Fix relative timestamp */
1392 fr->ts = calc_fakestamp(p1, p2, fr->ts);
1393 /* Now just send it send on the 2nd one
1394 with adjusted timestamp */
1395 return iax2_send(p2, fr->f, fr->ts, -1, 0, 0, 0);
1399 static int schedule_delivery(struct ast_iax2_frame *fr, int reallydeliver)
1402 int drops[MEMORY_SIZE];
1403 int min, max=0, maxone=0,y,z, match;
1404 /* ms is a measure of the "lateness" of the packet relative to the first
1405 packet we received, which always has a lateness of 1. Called by
1406 IAX thread, with iaxsl lock held. */
1407 ms = calc_rxstamp(iaxs[fr->callno]) - fr->ts;
1410 /* What likely happened here is that our counter has circled but we haven't
1411 gotten the update from the main packet. We'll just pretend that we did, and
1412 update the timestamp appropriately. */
1417 /* We got this packet out of order. Lets add 65536 to it to bring it into our new
1422 /* Rotate our history queue of "lateness". Don't worry about those initial
1423 zeros because the first entry will always be zero */
1424 for (x=0;x<MEMORY_SIZE - 1;x++)
1425 iaxs[fr->callno]->history[x] = iaxs[fr->callno]->history[x+1];
1426 /* Add a history entry for this one */
1427 iaxs[fr->callno]->history[x] = ms;
1429 /* Initialize the minimum to reasonable values. It's too much
1430 work to do the same for the maximum, repeatedly */
1431 min=iaxs[fr->callno]->history[0];
1432 for (z=0;z < iax2_dropcount + 1;z++) {
1433 /* Start very optimistic ;-) */
1435 for (x=0;x<MEMORY_SIZE;x++) {
1436 if (max < iaxs[fr->callno]->history[x]) {
1437 /* We have a candidate new maximum value. Make
1438 sure it's not in our drop list */
1440 for (y=0;!match && (y<z);y++)
1441 match |= (drops[y] == x);
1443 /* It's not in our list, use it as the new maximum */
1444 max = iaxs[fr->callno]->history[x];
1450 /* On our first pass, find the minimum too */
1451 if (min > iaxs[fr->callno]->history[x])
1452 min = iaxs[fr->callno]->history[x];
1459 /* Just for reference, keep the "jitter" value, the difference between the
1460 earliest and the latest. */
1461 iaxs[fr->callno]->jitter = max - min;
1463 /* IIR filter for keeping track of historic jitter, but always increase
1464 historic jitter immediately for increase */
1466 if (iaxs[fr->callno]->jitter > iaxs[fr->callno]->historicjitter )
1467 iaxs[fr->callno]->historicjitter = iaxs[fr->callno]->jitter;
1469 iaxs[fr->callno]->historicjitter = GAMMA * (double)iaxs[fr->callno]->jitter + (1-GAMMA) *
1470 iaxs[fr->callno]->historicjitter;
1472 /* If our jitter buffer is too big (by a significant margin), then we slowly
1473 shrink it by about 1 ms each time to avoid letting the change be perceived */
1474 if (max < iaxs[fr->callno]->jitterbuffer - max_jitter_buffer)
1475 iaxs[fr->callno]->jitterbuffer -= 2;
1479 /* Constrain our maximum jitter buffer appropriately */
1480 if (max > min + maxjitterbuffer) {
1482 ast_log(LOG_DEBUG, "Constraining buffer from %d to %d + %d\n", max, min , maxjitterbuffer);
1483 max = min + maxjitterbuffer;
1487 /* If our jitter buffer is smaller than our maximum delay, grow the jitter
1488 buffer immediately to accomodate it (and a little more). */
1489 if (max > iaxs[fr->callno]->jitterbuffer)
1490 iaxs[fr->callno]->jitterbuffer = max
1491 /* + ((float)iaxs[fr->callno]->jitter) * 0.1 */;
1495 ast_log(LOG_DEBUG, "min = %d, max = %d, jb = %d, lateness = %d\n", min, max, iaxs[fr->callno]->jitterbuffer, ms);
1497 /* Subtract the lateness from our jitter buffer to know how long to wait
1498 before sending our packet. */
1499 ms = iaxs[fr->callno]->jitterbuffer - ms;
1501 if (!use_jitterbuffer)
1504 /* If the caller just wanted us to update, return now */
1510 ast_log(LOG_DEBUG, "Calculated ms is %d\n", ms);
1511 /* Don't deliver it more than 4 ms late */
1512 if ((ms > -4) || (fr->f->frametype != AST_FRAME_VOICE)) {
1516 ast_log(LOG_DEBUG, "Dropping voice packet since %d ms is, too old\n", ms);
1517 /* Free the packet */
1519 /* And our iax frame */
1520 ast_iax2_frame_free(fr);
1524 ast_log(LOG_DEBUG, "Scheduling delivery in %d ms\n", ms);
1525 fr->retrans = ast_sched_add(sched, ms, do_deliver, fr);
1530 static int iax2_transmit(struct ast_iax2_frame *fr)
1532 /* Lock the queue and place this packet at the end */
1535 /* By setting this to 0, the network thread will send it for us, and
1536 queue retransmission if necessary */
1538 ast_pthread_mutex_lock(&iaxq.lock);
1545 iaxq.tail->next = fr;
1546 fr->prev = iaxq.tail;
1550 ast_pthread_mutex_unlock(&iaxq.lock);
1551 /* Wake up the network thread */
1552 pthread_kill(netthreadid, SIGURG);
1558 static int iax2_digit(struct ast_channel *c, char digit)
1560 return send_command(c->pvt->pvt, AST_FRAME_DTMF, digit, 0, NULL, 0, -1);
1563 static int iax2_sendtext(struct ast_channel *c, char *text)
1566 return send_command(c->pvt->pvt, AST_FRAME_TEXT,
1567 0, 0, text, strlen(text) + 1, -1);
1570 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
1572 return send_command(c->pvt->pvt, AST_FRAME_IMAGE, img->subclass, 0, img->data, img->datalen, -1);
1575 static int iax2_sendhtml(struct ast_channel *c, int subclass, char *data, int datalen)
1577 return send_command(c->pvt->pvt, AST_FRAME_HTML, subclass, 0, data, datalen, -1);
1580 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
1582 struct chan_iax2_pvt *pvt = newchan->pvt->pvt;
1583 pvt->owner = newchan;
1587 static int create_addr(struct sockaddr_in *sin, int *capability, int *sendani, int *maxtime, char *peer, char *context)
1590 struct iax2_peer *p;
1596 sin->sin_family = AF_INET;
1597 ast_pthread_mutex_lock(&peerl.lock);
1600 if (!strcasecmp(p->name, peer)) {
1603 *capability = p->capability;
1604 if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
1605 (!p->maxms || ((p->lastms > 0) && (p->lastms <= p->maxms)))) {
1607 *sendani = p->sendani; /* Whether we transmit ANI */
1609 *maxtime = p->maxms; /* Max time they should take */
1611 strncpy(context, p->context, AST_MAX_EXTENSION - 1);
1612 if (p->addr.sin_addr.s_addr) {
1613 sin->sin_addr = p->addr.sin_addr;
1614 sin->sin_port = p->addr.sin_port;
1616 sin->sin_addr = p->defaddr.sin_addr;
1617 sin->sin_port = p->defaddr.sin_port;
1624 ast_pthread_mutex_unlock(&peerl.lock);
1626 hp = gethostbyname(peer);
1628 memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
1629 sin->sin_port = htons(AST_DEFAULT_IAX_PORTNO);
1632 ast_log(LOG_WARNING, "No such host: %s\n", peer);
1641 static int auto_congest(void *nothing)
1643 int callno = (int)(long)(nothing);
1644 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_CONGESTION };
1645 ast_pthread_mutex_lock(&iaxsl[callno]);
1647 iaxs[callno]->initid = -1;
1648 iax2_queue_frame(callno, &f);
1649 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
1651 ast_pthread_mutex_unlock(&iaxsl[callno]);
1655 static int iax_ie_append_raw(struct iax_ie_data *ied, unsigned char ie, void *data, int datalen)
1657 if (datalen > (sizeof(ied->buf) - ied->pos)) {
1658 ast_log(LOG_WARNING, "Out of space for ie '%s' (%d), need %d have %d\n", ie2str(ie), ie, datalen, sizeof(ied->buf) - ied->pos);
1661 ied->buf[ied->pos++] = ie;
1662 ied->buf[ied->pos++] = datalen;
1663 memcpy(ied->buf + ied->pos, data, datalen);
1664 ied->pos += datalen;
1668 static int iax_ie_append_addr(struct iax_ie_data *ied, unsigned char ie, struct sockaddr_in *sin)
1670 return iax_ie_append_raw(ied, ie, sin, sizeof(struct sockaddr_in));
1673 static int iax_ie_append_int(struct iax_ie_data *ied, unsigned char ie, unsigned int value)
1675 unsigned int newval;
1676 newval = htonl(value);
1677 return iax_ie_append_raw(ied, ie, &newval, sizeof(newval));
1680 static int iax_ie_append_short(struct iax_ie_data *ied, unsigned char ie, unsigned short value)
1682 unsigned short newval;
1683 newval = htons(value);
1684 return iax_ie_append_raw(ied, ie, &newval, sizeof(newval));
1687 static int iax_ie_append_str(struct iax_ie_data *ied, unsigned char ie, unsigned char *str)
1689 return iax_ie_append_raw(ied, ie, str, strlen(str));
1692 static int iax2_call(struct ast_channel *c, char *dest, int timeout)
1694 struct sockaddr_in sin;
1699 char *secret = NULL;
1702 char *l=NULL, *n=NULL;
1703 struct iax_ie_data ied;
1704 char myrdest [5] = "s";
1705 char context[AST_MAX_EXTENSION] ="";
1706 char *portno = NULL;
1707 struct chan_iax2_pvt *p = c->pvt->pvt;
1709 if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
1710 ast_log(LOG_WARNING, "Line is already in use (%s)?\n", c->name);
1713 strncpy(host, dest, sizeof(host)-1);
1715 strsep(&stringp, "/");
1716 /* If no destination extension specified, use 's' */
1717 rdest = strsep(&stringp, "/");
1721 strsep(&stringp, "@");
1722 rcontext = strsep(&stringp, "@");
1724 strsep(&stringp, "@");
1725 username = strsep(&stringp, "@");
1727 /* Really the second argument is the host, not the username */
1735 username = strsep(&stringp, ":");
1736 secret = strsep(&stringp, ":");
1739 if (strsep(&stringp, ":")) {
1741 strsep(&stringp, ":");
1742 portno = strsep(&stringp, ":");
1744 if (create_addr(&sin, NULL, NULL, NULL, hname, context)) {
1745 ast_log(LOG_WARNING, "No address associated with '%s'\n", hname);
1748 /* Keep track of the context for outgoing calls too */
1749 strncpy(c->context, context, sizeof(c->context) - 1);
1751 sin.sin_port = htons(atoi(portno));
1754 strncpy(cid, c->callerid, sizeof(cid) - 1);
1755 ast_callerid_parse(cid, &n, &l);
1757 ast_shrink_phone_number(l);
1759 /* Now build request */
1760 memset(&ied, 0, sizeof(ied));
1761 /* On new call, first IE MUST be IAX version of caller */
1762 iax_ie_append_short(&ied, IAX_IE_VERSION, AST_IAX2_PROTO_VERSION);
1763 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, rdest);
1765 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
1767 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n);
1768 if (p->sendani && c->ani) {
1770 strncpy(cid, c->ani, sizeof(cid) - 1);
1771 ast_callerid_parse(cid, &n, &l);
1773 ast_shrink_phone_number(l);
1774 iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, l);
1777 if (c->language && strlen(c->language))
1778 iax_ie_append_str(&ied, IAX_IE_LANGUAGE, c->language);
1779 if (c->dnid && strlen(c->dnid))
1780 iax_ie_append_str(&ied, IAX_IE_DNID, c->dnid);
1782 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, rcontext);
1784 iax_ie_append_str(&ied, IAX_IE_USERNAME, username);
1786 if (secret[0] == '[') {
1787 /* This is an RSA key, not a normal secret */
1788 strncpy(p->outkey, secret + 1, sizeof(p->secret)-1);
1789 if (strlen(p->outkey)) {
1790 p->outkey[strlen(p->outkey) - 1] = '\0';
1793 strncpy(p->secret, secret, sizeof(p->secret)-1);
1795 iax_ie_append_int(&ied, IAX_IE_FORMAT, c->nativeformats);
1796 iax_ie_append_int(&ied, IAX_IE_CAPABILITY, p->capability);
1797 iax_ie_append_int(&ied, IAX_IE_ADSICPE, c->adsicpe);
1798 /* Transmit the string in a "NEW" request */
1800 /* XXX We have no equivalent XXX */
1801 if (option_verbose > 2)
1802 ast_verbose(VERBOSE_PREFIX_3 "Calling using options '%s'\n", requeststr);
1805 /* Initialize pingtime and auto-congest time */
1806 p->pingtime = p->maxtime / 2;
1807 p->initid = ast_sched_add(sched, p->maxtime * 2, auto_congest, (void *)(long)p->callno);
1809 send_command(p, AST_FRAME_IAX,
1810 AST_IAX2_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
1811 ast_setstate(c, AST_STATE_RINGING);
1815 static int iax2_hangup(struct ast_channel *c)
1817 struct chan_iax2_pvt *pvt = c->pvt->pvt;
1821 callno = pvt->callno;
1822 ast_pthread_mutex_lock(&iaxsl[callno]);
1823 ast_log(LOG_DEBUG, "We're hanging up %s now...\n", c->name);
1824 alreadygone = pvt->alreadygone;
1825 /* Send the hangup unless we have had a transmission error or are already gone */
1826 if (!pvt->error && !alreadygone)
1827 send_command_final(pvt, AST_FRAME_IAX, AST_IAX2_COMMAND_HANGUP, 0, NULL, 0, -1);
1828 /* Explicitly predestroy it */
1829 iax2_predestroy_nolock(callno);
1830 /* If we were already gone to begin with, destroy us now */
1832 ast_log(LOG_DEBUG, "Really destroying %s now...\n", c->name);
1833 iax2_destroy_nolock(callno);
1835 ast_pthread_mutex_unlock(&iaxsl[callno]);
1837 if (option_verbose > 2)
1838 ast_verbose(VERBOSE_PREFIX_3 "Hungup '%s'\n", c->name);
1842 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
1844 struct ast_option_header *h;
1846 h = malloc(datalen + sizeof(struct ast_option_header));
1848 h->flag = AST_OPTION_FLAG_REQUEST;
1849 h->option = htons(option);
1850 memcpy(h->data, data, datalen);
1851 res = send_command((struct chan_iax2_pvt *)c->pvt->pvt, AST_FRAME_CONTROL,
1852 AST_CONTROL_OPTION, 0, (char *)h, datalen + sizeof(struct ast_option_header), -1);
1856 ast_log(LOG_WARNING, "Out of memory\n");
1859 static struct ast_frame *iax2_read(struct ast_channel *c)
1861 static struct ast_frame f = { AST_FRAME_NULL, };
1862 ast_log(LOG_NOTICE, "I should never be called!\n");
1866 static int iax2_start_transfer(struct ast_channel *c0, struct ast_channel *c1)
1869 struct iax_ie_data ied0;
1870 struct iax_ie_data ied1;
1871 struct chan_iax2_pvt *p0 = c0->pvt->pvt;
1872 struct chan_iax2_pvt *p1 = c1->pvt->pvt;
1873 memset(&ied0, 0, sizeof(ied0));
1874 iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &p1->addr);
1875 iax_ie_append_short(&ied0, IAX_IE_CALLNO, p1->peercallno);
1877 memset(&ied1, 0, sizeof(ied1));
1878 iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &p0->addr);
1879 iax_ie_append_short(&ied1, IAX_IE_CALLNO, p0->peercallno);
1881 res = send_command(p0, AST_FRAME_IAX, AST_IAX2_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
1884 res = send_command(p1, AST_FRAME_IAX, AST_IAX2_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
1887 p0->transferring = TRANSFER_BEGIN;
1888 p1->transferring = TRANSFER_BEGIN;
1892 static int iax2_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
1894 struct ast_channel *cs[3];
1895 struct ast_channel *who;
1898 int transferstarted=0;
1899 struct ast_frame *f;
1900 struct chan_iax2_pvt *p0 = c0->pvt->pvt;
1901 struct chan_iax2_pvt *p1 = c1->pvt->pvt;
1903 /* Put them in native bridge mode */
1904 p0->bridgecallno = p1->callno;
1905 p1->bridgecallno = p0->callno;
1907 /* If not, try to bridge until we can execute a transfer, if we can */
1910 for (/* ever */;;) {
1911 /* Check in case we got masqueraded into */
1912 if ((c0->type != type) || (c1->type != type)) {
1913 if (option_verbose > 2)
1914 ast_verbose(VERBOSE_PREFIX_3 "Can't masquerade, we're different...\n");
1917 if (c0->nativeformats != c1->nativeformats) {
1918 ast_verbose(VERBOSE_PREFIX_3 "Operating with different codecs, can't native bridge...\n");
1921 if (!transferstarted) {
1922 /* Try the transfer */
1923 if (iax2_start_transfer(c0, c1))
1924 ast_log(LOG_WARNING, "Unable to start the transfer\n");
1925 transferstarted = 1;
1928 if ((p0->transferring == TRANSFER_RELEASED) && (p1->transferring == TRANSFER_RELEASED)) {
1929 /* Call has been transferred. We're no longer involved */
1931 c0->_softhangup |= AST_SOFTHANGUP_DEV;
1932 c1->_softhangup |= AST_SOFTHANGUP_DEV;
1939 who = ast_waitfor_n(cs, 2, &to);
1950 if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
1956 if ((f->frametype == AST_FRAME_VOICE) ||
1957 (f->frametype == AST_FRAME_TEXT) ||
1958 (f->frametype == AST_FRAME_VIDEO) ||
1959 (f->frametype == AST_FRAME_IMAGE) ||
1960 (f->frametype == AST_FRAME_DTMF)) {
1961 if ((f->frametype == AST_FRAME_DTMF) &&
1962 (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
1964 if ((flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
1967 /* Take out of conference mode */
1974 if (flags & AST_BRIDGE_DTMF_CHANNEL_1) {
1984 ast_log(LOG_DEBUG, "Read from %s\n", who->name);
1986 ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
1998 /* Swap who gets priority */
2003 p0->bridgecallno = 0;
2004 p1->bridgecallno = 0;
2008 static int iax2_answer(struct ast_channel *c)
2010 struct chan_iax2_pvt *pvt = c->pvt->pvt;
2012 ast_log(LOG_DEBUG, "Answering\n");
2013 return send_command(pvt, AST_FRAME_CONTROL, AST_CONTROL_ANSWER, 0, NULL, 0, -1);
2016 static int iax2_indicate(struct ast_channel *c, int condition)
2018 struct chan_iax2_pvt *pvt = c->pvt->pvt;
2020 ast_log(LOG_DEBUG, "Indicating condition %d\n", condition);
2021 return send_command(pvt, AST_FRAME_CONTROL, condition, 0, NULL, 0, -1);
2025 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
2027 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len)
2029 struct iax2_peer *peer;
2031 ast_pthread_mutex_lock(&peerl.lock);
2034 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
2035 (peer->addr.sin_port == sin.sin_port)) {
2036 strncpy(host, peer->name, len-1);
2042 ast_pthread_mutex_unlock(&peerl.lock);
2046 static struct ast_channel *ast_iax2_new(struct chan_iax2_pvt *i, int state, int capability)
2049 struct ast_channel *tmp;
2050 tmp = ast_channel_alloc(1);
2052 if (!iax2_getpeername(i->addr, host, sizeof(host)))
2053 snprintf(host, sizeof(host), "%s:%d", inet_ntoa(i->addr.sin_addr), ntohs(i->addr.sin_port));
2054 if (strlen(i->username))
2055 snprintf(tmp->name, sizeof(tmp->name), "IAX2[%s@%s]/%d", i->username, host, i->callno);
2057 snprintf(tmp->name, sizeof(tmp->name), "IAX2[%s]/%d", host, i->callno);
2059 /* We can support any format by default, until we get restricted */
2060 tmp->nativeformats = capability;
2061 tmp->readformat = 0;
2062 tmp->writeformat = 0;
2064 tmp->pvt->send_digit = iax2_digit;
2065 tmp->pvt->send_text = iax2_sendtext;
2066 tmp->pvt->send_image = iax2_sendimage;
2067 tmp->pvt->send_html = iax2_sendhtml;
2068 tmp->pvt->call = iax2_call;
2069 tmp->pvt->hangup = iax2_hangup;
2070 tmp->pvt->answer = iax2_answer;
2071 tmp->pvt->read = iax2_read;
2072 tmp->pvt->write = iax2_write;
2073 tmp->pvt->indicate = iax2_indicate;
2074 tmp->pvt->setoption = iax2_setoption;
2075 tmp->pvt->bridge = iax2_bridge;
2076 if (strlen(i->callerid))
2077 tmp->callerid = strdup(i->callerid);
2079 tmp->ani = strdup(i->ani);
2080 if (strlen(i->language))
2081 strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
2082 if (strlen(i->dnid))
2083 tmp->dnid = strdup(i->dnid);
2084 if (strlen(i->accountcode))
2085 strncpy(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode)-1);
2087 tmp->amaflags = i->amaflags;
2088 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
2089 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
2090 tmp->adsicpe = i->peeradsicpe;
2091 tmp->pvt->fixup = iax2_fixup;
2093 i->capability = capability;
2094 ast_setstate(tmp, state);
2095 ast_pthread_mutex_lock(&usecnt_lock);
2097 ast_pthread_mutex_unlock(&usecnt_lock);
2098 ast_update_use_count();
2099 if (state != AST_STATE_DOWN) {
2100 if (ast_pbx_start(tmp)) {
2101 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
2110 static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts)
2114 if (!p->offset.tv_sec && !p->offset.tv_usec)
2115 gettimeofday(&p->offset, NULL);
2116 /* If the timestamp is specified, just send it as is */
2119 gettimeofday(&tv, NULL);
2120 ms = (tv.tv_sec - p->offset.tv_sec) * 1000 + (tv.tv_usec - p->offset.tv_usec) / 1000;
2121 /* We never send the same timestamp twice, so fudge a little if we must */
2122 if (ms <= p->lastsent)
2123 ms = p->lastsent + 1;
2128 #ifdef BRIDGE_OPTIMIZATION
2129 static unsigned int calc_fakestamp(struct chan_iax2_pvt *p1, struct chan_iax2_pvt *p2, unsigned int fakets)
2132 /* Receive from p1, send to p2 */
2134 /* Setup rxcore if necessary on outgoing channel */
2135 if (!p1->rxcore.tv_sec && !p1->rxcore.tv_usec)
2136 gettimeofday(&p1->rxcore, NULL);
2138 /* Setup txcore if necessary on outgoing channel */
2139 if (!p2->offset.tv_sec && !p2->offset.tv_usec)
2140 gettimeofday(&p2->offset, NULL);
2142 /* Now, ts is the timestamp of the original packet in the orignal context.
2143 Adding rxcore to it gives us when we would want the packet to be delivered normally.
2144 Subtracting txcore of the outgoing channel gives us what we'd expect */
2146 ms = (p1->rxcore.tv_sec - p2->offset.tv_sec) * 1000 + (p1->rxcore.tv_usec - p1->offset.tv_usec) / 1000;
2148 if (fakets <= p2->lastsent)
2149 fakets = p2->lastsent + 1;
2150 p2->lastsent = fakets;
2155 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p)
2157 /* Returns where in "receive time" we are */
2160 /* Setup rxcore if necessary */
2161 if (!p->rxcore.tv_sec && !p->rxcore.tv_usec)
2162 gettimeofday(&p->rxcore, NULL);
2164 gettimeofday(&tv, NULL);
2165 ms = (tv.tv_sec - p->rxcore.tv_sec) * 1000 + (tv.tv_usec - p->rxcore.tv_usec) / 1000;
2169 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final)
2171 /* Queue a packet for delivery on a given private structure. Use "ts" for
2172 timestamp, or calculate if ts is 0. Send immediately without retransmission
2173 or delayed, with retransmission */
2174 struct ast_iax2_full_hdr *fh;
2175 struct ast_iax2_mini_hdr *mh;
2176 struct ast_iax2_frame *fr, fr2;
2178 unsigned int lastsent;
2179 /* Allocate an ast_iax2_frame */
2183 fr = ast_iax2_frame_new(DIRECTION_OUTGRESS);
2185 ast_log(LOG_WARNING, "Out of memory\n");
2189 ast_log(LOG_WARNING, "No private structure for packet (%d)?\n", fr->callno);
2191 ast_iax2_frame_free(fr);
2194 /* Isolate our frame for transmission */
2195 fr->f = ast_frdup(f);
2198 ast_log(LOG_WARNING, "Out of memory\n");
2200 ast_iax2_frame_free(fr);
2203 if (fr->f->offset < sizeof(struct ast_iax2_full_hdr)) {
2204 ast_log(LOG_WARNING, "Packet from '%s' not friendly\n", fr->f->src);
2208 lastsent = pvt->lastsent;
2209 fr->ts = calc_timestamp(pvt, ts);
2211 ast_log(LOG_WARNING, "timestamp is 0?\n");
2213 ast_iax2_frame_free(fr);
2216 fr->callno = pvt->callno;
2217 fr->transfer = transfer;
2219 if (((fr->ts & 0xFFFF0000L) != (lastsent & 0xFFFF0000L))
2220 /* High two bits of timestamp differ */ ||
2221 (fr->f->frametype != AST_FRAME_VOICE)
2222 /* or not a voice frame */ ||
2223 (fr->f->subclass != pvt->svoiceformat)
2224 /* or new voice format */ ) {
2225 /* We need a full frame */
2229 fr->oseqno = pvt->oseqno++;
2230 fr->iseqno = pvt->iseqno;
2231 fh = (struct ast_iax2_full_hdr *)(fr->f->data - sizeof(struct ast_iax2_full_hdr));
2232 fh->scallno = htons(fr->callno | AST_FLAG_FULL);
2233 fh->ts = htonl(fr->ts);
2234 fh->oseqno = htons(fr->oseqno);
2235 fh->iseqno = htons(fr->iseqno);
2236 /* Keep track of the last thing we've acknowledged */
2237 pvt->aseqno = fr->iseqno;
2238 fh->type = fr->f->frametype & 0xFF;
2239 fh->csub = compress_subclass(fr->f->subclass);
2241 fr->dcallno = pvt->transfercallno;
2243 fr->dcallno = pvt->peercallno;
2244 fh->dcallno = htons(fr->dcallno);
2245 fr->datalen = fr->f->datalen + sizeof(struct ast_iax2_full_hdr);
2248 /* Retry after 2x the ping time has passed */
2249 fr->retrytime = pvt->pingtime * 2;
2250 if (fr->retrytime < MIN_RETRY_TIME)
2251 fr->retrytime = MIN_RETRY_TIME;
2252 if (fr->retrytime > MAX_RETRY_TIME)
2253 fr->retrytime = MAX_RETRY_TIME;
2254 /* Acks' don't get retried */
2255 if ((f->frametype == AST_FRAME_IAX) && (f->subclass == AST_IAX2_COMMAND_ACK))
2257 if (f->frametype == AST_FRAME_VOICE) {
2258 pvt->svoiceformat = f->subclass;
2261 res = send_packet(fr);
2264 res = iax2_transmit(fr);
2266 /* Mini-frames have no sequence number */
2269 /* Mini frame will do */
2270 mh = (struct ast_iax2_mini_hdr *)(fr->f->data - sizeof(struct ast_iax2_mini_hdr));
2271 mh->callno = htons(fr->callno);
2272 mh->ts = htons(fr->ts & 0xFFFF);
2273 fr->datalen = fr->f->datalen + sizeof(struct ast_iax2_mini_hdr);
2277 res = send_packet(fr);
2280 res = iax2_transmit(fr);
2287 static int iax2_show_users(int fd, int argc, char *argv[])
2289 #define FORMAT "%-15.15s %-15.15s %-15.15s %-15.15s %-5.5s\n"
2290 #define FORMAT2 "%-15.15s %-15.15s %-15.15d %-15.15s %-5.5s\n"
2291 struct iax2_user *user;
2293 return RESULT_SHOWUSAGE;
2294 ast_pthread_mutex_lock(&userl.lock);
2295 ast_cli(fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C");
2296 for(user=userl.users;user;user=user->next) {
2297 ast_cli(fd, FORMAT2, user->name, user->secret, user->authmethods,
2298 user->contexts ? user->contexts->context : context,
2299 user->ha ? "Yes" : "No");
2301 ast_pthread_mutex_unlock(&userl.lock);
2302 return RESULT_SUCCESS;
2307 static int iax2_show_peers(int fd, int argc, char *argv[])
2309 #define FORMAT2 "%-15.15s %-15.15s %s %-15.15s %-8s %-10s\n"
2310 #define FORMAT "%-15.15s %-15.15s %s %-15.15s %-8d %-10s\n"
2311 struct iax2_peer *peer;
2312 char name[256] = "";
2314 return RESULT_SHOWUSAGE;
2315 ast_pthread_mutex_lock(&peerl.lock);
2316 ast_cli(fd, FORMAT2, "Name/Username", "Host", " ", "Mask", "Port", "Status");
2317 for (peer = peerl.peers;peer;peer = peer->next) {
2320 if (strlen(peer->username))
2321 snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
2323 strncpy(name, peer->name, sizeof(name) - 1);
2325 if (peer->lastms < 0)
2326 strcpy(status, "UNREACHABLE");
2327 else if (peer->lastms > peer->maxms)
2328 snprintf(status, sizeof(status), "LAGGED (%d ms)", peer->lastms);
2329 else if (peer->lastms)
2330 snprintf(status, sizeof(status), "OK (%d ms)", peer->lastms);
2332 strcpy(status, "UNKNOWN");
2334 strcpy(status, "Unmonitored");
2335 strncpy(nm, inet_ntoa(peer->mask), sizeof(nm)-1);
2336 ast_cli(fd, FORMAT, name,
2337 peer->addr.sin_addr.s_addr ? inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
2338 peer->dynamic ? "(D)" : "(S)",
2340 ntohs(peer->addr.sin_port), status);
2342 ast_pthread_mutex_unlock(&peerl.lock);
2343 return RESULT_SUCCESS;
2348 /* JDG: callback to display iax peers in manager */
2349 static int manager_iax2_show_peers( struct mansession *s, struct message *m )
2351 char *a[] = { "iax2", "show", "users" };
2353 ret = iax2_show_peers( s->fd, 3, a );
2354 ast_cli( s->fd, "\r\n" );
2358 static char *regstate2str(int regstate)
2361 case REG_STATE_UNREGISTERED:
2362 return "Unregistered";
2363 case REG_STATE_REGSENT:
2364 return "Request Sent";
2365 case REG_STATE_AUTHSENT:
2366 return "Auth. Sent";
2367 case REG_STATE_REGISTERED:
2368 return "Registered";
2369 case REG_STATE_REJECTED:
2371 case REG_STATE_TIMEOUT:
2373 case REG_STATE_NOAUTH:
2374 return "No Authentication";
2380 static int iax2_show_registry(int fd, int argc, char *argv[])
2382 #define FORMAT2 "%-20.20s %-10.10s %-20.20s %8.8s %s\n"
2383 #define FORMAT "%-20.20s %-10.10s %-20.20s %8d %s\n"
2384 struct iax2_registry *reg;
2388 return RESULT_SHOWUSAGE;
2389 ast_pthread_mutex_lock(&peerl.lock);
2390 ast_cli(fd, FORMAT2, "Host", "Username", "Perceived", "Refresh", "State");
2391 for (reg = registrations;reg;reg = reg->next) {
2392 snprintf(host, sizeof(host), "%s:%d", inet_ntoa(reg->addr.sin_addr), ntohs(reg->addr.sin_port));
2393 if (reg->us.sin_addr.s_addr)
2394 snprintf(perceived, sizeof(perceived), "%s:%d", inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
2396 strcpy(perceived, "<Unregistered>");
2397 ast_cli(fd, FORMAT, host,
2398 reg->username, perceived, reg->refresh, regstate2str(reg->regstate));
2400 ast_pthread_mutex_unlock(&peerl.lock);
2401 return RESULT_SUCCESS;
2406 static int iax2_show_channels(int fd, int argc, char *argv[])
2408 #define FORMAT2 "%-15.15s %-10.10s %-11.11s %-11.11s %-7.7s %-6.6s %s\n"
2409 #define FORMAT "%-15.15s %-10.10s %5.5d/%5.5d %5.5d/%5.5d %-5.5dms %-4.4dms %d\n"
2413 return RESULT_SHOWUSAGE;
2414 ast_cli(fd, FORMAT2, "Peer", "Username", "ID (Lo/Rem)", "Seq (Tx/Rx)", "Lag", "Jitter", "Format");
2415 for (x=0;x<AST_IAX2_MAX_CALLS;x++) {
2416 ast_pthread_mutex_lock(&iaxsl[x]);
2418 ast_cli(fd, FORMAT, inet_ntoa(iaxs[x]->addr.sin_addr),
2419 strlen(iaxs[x]->username) ? iaxs[x]->username : "(None)",
2420 iaxs[x]->callno, iaxs[x]->peercallno,
2421 iaxs[x]->oseqno, iaxs[x]->iseqno,
2424 iaxs[x]->voiceformat);
2427 ast_pthread_mutex_unlock(&iaxsl[x]);
2429 ast_cli(fd, "%d active IAX channel(s)\n", numchans);
2430 return RESULT_SUCCESS;
2435 static int iax2_do_debug(int fd, int argc, char *argv[])
2438 return RESULT_SHOWUSAGE;
2440 ast_cli(fd, "IAX2 Debugging Enabled\n");
2441 return RESULT_SUCCESS;
2444 static int iax2_no_debug(int fd, int argc, char *argv[])
2447 return RESULT_SHOWUSAGE;
2449 ast_cli(fd, "IAX2 Debugging Disabled\n");
2450 return RESULT_SUCCESS;
2455 static char show_users_usage[] =
2456 "Usage: iax2 show users\n"
2457 " Lists all users known to the IAX2 (Inter-Asterisk eXchange rev 2) subsystem.\n";
2459 static char show_channels_usage[] =
2460 "Usage: iax2 show channels\n"
2461 " Lists all currently active IAX2 channels.\n";
2463 static char show_peers_usage[] =
2464 "Usage: iax2 show peers\n"
2465 " Lists all known IAX peers.\n";
2467 static char show_reg_usage[] =
2468 "Usage: iax2 show registry\n"
2469 " Lists all registration requests and status.\n";
2471 #ifdef DEBUG_SUPPORT
2473 static char debug_usage[] =
2474 "Usage: iax2 debug\n"
2475 " Enables dumping of IAX2 packets for debugging purposes\n";
2477 static char no_debug_usage[] =
2478 "Usage: iax2 no debug\n"
2479 " Disables dumping of IAX2 packets for debugging purposes\n";
2483 static struct ast_cli_entry cli_show_users =
2484 { { "iax2", "show", "users", NULL }, iax2_show_users, "Show defined IAX2 users", show_users_usage };
2485 static struct ast_cli_entry cli_show_channels =
2486 { { "iax2", "show", "channels", NULL }, iax2_show_channels, "Show active IAX2 channels", show_channels_usage };
2487 static struct ast_cli_entry cli_show_peers =
2488 { { "iax2", "show", "peers", NULL }, iax2_show_peers, "Show defined IAX2 peers", show_peers_usage };
2489 static struct ast_cli_entry cli_show_registry =
2490 { { "iax2", "show", "registry", NULL }, iax2_show_registry, "Show IAX2 registration status", show_reg_usage };
2491 static struct ast_cli_entry cli_debug =
2492 { { "iax2", "debug", NULL }, iax2_do_debug, "Enable IAX2 debugging", debug_usage };
2493 static struct ast_cli_entry cli_no_debug =
2494 { { "iax2", "no", "debug", NULL }, iax2_no_debug, "Disable IAX2 debugging", no_debug_usage };
2496 static int iax2_write(struct ast_channel *c, struct ast_frame *f)
2498 struct chan_iax2_pvt *i = c->pvt->pvt;
2501 /* If there's an outstanding error, return failure now */
2503 ast_log(LOG_DEBUG, "Write error: %s\n", strerror(errno));
2506 /* If it's already gone, just return */
2509 /* Don't waste bandwidth sending null frames */
2510 if (f->frametype == AST_FRAME_NULL)
2512 /* If we're quelching voice, don't bother sending it */
2513 if ((f->frametype == AST_FRAME_VOICE) && i->quelch)
2515 /* Simple, just queue for transmission */
2516 return iax2_send(i, f, 0, -1, 0, 0, 0);
2519 static int __send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno,
2520 int now, int transfer, int final)
2524 f.subclass = command;
2525 f.datalen = datalen;
2529 f.src = __FUNCTION__;
2531 return iax2_send(i, &f, ts, seqno, now, transfer, final);
2534 static int send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2536 return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 0);
2539 #ifdef BRIDGE_OPTIMIZATION
2540 static int forward_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2542 return __send_command(iaxs[i->bridgecallno], type, command, ts, data, datalen, seqno, 0, 0, 0);
2546 static int send_command_final(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2548 /* It is assumed that the callno has already been locked */
2549 iax2_predestroy_nolock(i->callno);
2550 return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 1);
2553 static int send_command_immediate(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2555 return __send_command(i, type, command, ts, data, datalen, seqno, 1, 0, 0);
2558 static int send_command_transfer(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen)
2560 return __send_command(i, type, command, ts, data, datalen, 0, 0, 1, 0);
2563 static int apply_context(struct iax2_context *con, char *context)
2566 if (!strcmp(con->context, context))
2574 static int check_access(int callno, struct sockaddr_in *sin, struct iax_ies *ies)
2576 /* Start pessimistic */
2579 struct iax2_user *user;
2580 int gotcapability=0;
2583 if (ies->called_number)
2584 strncpy(iaxs[callno]->exten, ies->called_number, sizeof(iaxs[callno]->exten) - 1);
2585 if (ies->calling_number) {
2586 if (ies->calling_name)
2587 snprintf(iaxs[callno]->callerid, sizeof(iaxs[callno]->callerid), "\"%s\" <%s>", ies->calling_name, ies->calling_number);
2589 strncpy(iaxs[callno]->callerid, ies->calling_number, sizeof(iaxs[callno]->callerid) - 1);
2590 } else if (ies->calling_name)
2591 strncpy(iaxs[callno]->callerid, ies->calling_name, sizeof(iaxs[callno]->callerid) - 1);
2592 if (ies->calling_ani)
2593 strncpy(iaxs[callno]->ani, ies->calling_ani, sizeof(iaxs[callno]->ani) - 1);
2595 strncpy(iaxs[callno]->dnid, ies->dnid, sizeof(iaxs[callno]->dnid)-1);
2596 if (ies->called_context)
2597 strncpy(iaxs[callno]->context, ies->called_context, sizeof(iaxs[callno]->context)-1);
2599 strncpy(iaxs[callno]->language, ies->language, sizeof(iaxs[callno]->language)-1);
2601 strncpy(iaxs[callno]->username, ies->username, sizeof(iaxs[callno]->username)-1);
2603 iaxs[callno]->peerformat = ies->format;
2605 iaxs[callno]->peeradsicpe = ies->adsicpe;
2606 if (ies->capability) {
2608 iaxs[callno]->peercapability = ies->capability;
2611 version = ies->version;
2613 iaxs[callno]->peercapability = iaxs[callno]->peerformat;
2614 if (version > AST_IAX2_PROTO_VERSION) {
2615 ast_log(LOG_WARNING, "Peer '%s' has too new a protocol version (%d) for me\n",
2616 inet_ntoa(sin->sin_addr), version);
2619 ast_pthread_mutex_lock(&userl.lock);
2620 /* Search the userlist for a compatible entry, and fill in the rest */
2623 if ((!strlen(iaxs[callno]->username) || /* No username specified */
2624 !strcmp(iaxs[callno]->username, user->name)) /* Or this username specified */
2625 && ast_apply_ha(user->ha, sin) /* Access is permitted from this IP */
2626 && (!strlen(iaxs[callno]->context) || /* No context specified */
2627 apply_context(user->contexts, iaxs[callno]->context))) { /* Context is permitted */
2628 /* We found our match (use the first) */
2630 /* Store the requested username if not specified */
2631 if (!strlen(iaxs[callno]->username))
2632 strncpy(iaxs[callno]->username, user->name, sizeof(iaxs[callno]->username)-1);
2633 /* And use the default context */
2634 if (!strlen(iaxs[callno]->context)) {
2636 strncpy(iaxs[callno]->context, user->contexts->context, sizeof(iaxs[callno]->context)-1);
2638 strncpy(iaxs[callno]->context, context, sizeof(iaxs[callno]->context)-1);
2640 /* Copy the secret */
2641 strncpy(iaxs[callno]->secret, user->secret, sizeof(iaxs[callno]->secret)-1);
2642 /* And any input keys */
2643 strncpy(iaxs[callno]->inkeys, user->inkeys, sizeof(iaxs[callno]->inkeys));
2644 /* And the permitted authentication methods */
2645 iaxs[callno]->authmethods = user->authmethods;
2646 /* If they have callerid, override the given caller id. Always store the ANI */
2647 if (strlen(iaxs[callno]->callerid)) {
2648 if (user->hascallerid)
2649 strncpy(iaxs[callno]->callerid, user->callerid, sizeof(iaxs[callno]->callerid)-1);
2650 strncpy(iaxs[callno]->ani, user->callerid, sizeof(iaxs[callno]->ani)-1);
2652 if (strlen(user->accountcode))
2653 strncpy(iaxs[callno]->accountcode, user->accountcode, sizeof(iaxs[callno]->accountcode)-1);
2655 iaxs[callno]->amaflags = user->amaflags;
2661 ast_pthread_mutex_unlock(&userl.lock);
2665 static int raw_hangup(struct sockaddr_in *sin, short src, short dst)
2667 struct ast_iax2_full_hdr fh;
2668 fh.scallno = htons(src | AST_FLAG_FULL);
2669 fh.dcallno = htons(dst);
2672 fh.type = AST_FRAME_IAX;
2673 fh.csub = compress_subclass(AST_IAX2_COMMAND_INVAL);
2677 ast_log(LOG_DEBUG, "Raw Hangup %s:%d, src=%d, dst=%d\n",
2678 inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), src, dst);
2679 return sendto(netsocket, &fh, sizeof(fh), 0, (struct sockaddr *)sin, sizeof(*sin));
2682 static int authenticate_request(struct chan_iax2_pvt *p)
2684 struct iax_ie_data ied;
2685 memset(&ied, 0, sizeof(ied));
2686 iax_ie_append_short(&ied, IAX_IE_AUTHMETHODS, p->authmethods);
2687 if (p->authmethods & (IAX_AUTH_MD5 | IAX_AUTH_RSA)) {
2688 snprintf(p->challenge, sizeof(p->challenge), "%d", rand());
2689 iax_ie_append_str(&ied, IAX_IE_CHALLENGE, p->challenge);
2691 iax_ie_append_str(&ied,IAX_IE_USERNAME, p->username);
2692 return send_command(p, AST_FRAME_IAX, AST_IAX2_COMMAND_AUTHREQ, 0, ied.buf, ied.pos, -1);
2695 static int authenticate_verify(struct chan_iax2_pvt *p, struct iax_ies *ies)
2697 char requeststr[256] = "";
2698 char md5secret[256] = "";
2699 char secret[256] = "";
2700 char rsasecret[256] = "";
2704 if (!(p->state & IAX_STATE_AUTHENTICATED))
2707 strncpy(secret, ies->password, sizeof(secret) - 1);
2708 if (ies->md5_result)
2709 strncpy(md5secret, ies->md5_result, sizeof(md5secret)-1);
2710 if (ies->rsa_result)
2711 strncpy(rsasecret, ies->rsa_result, sizeof(rsasecret)-1);
2712 if ((p->authmethods & IAX_AUTH_RSA) && strlen(rsasecret) && strlen(p->inkeys)) {
2713 struct ast_key *key;
2717 strncpy(tmpkey, p->inkeys, sizeof(tmpkey));
2719 keyn = strsep(&stringp, ":");
2721 key = ast_key_get(keyn, AST_KEY_PUBLIC);
2722 if (key && !ast_check_signature(key, p->challenge, rsasecret)) {
2726 ast_log(LOG_WARNING, "requested inkey '%s' for RSA authentication does not exist\n", keyn);
2727 keyn = strsep(&stringp, ":");
2729 } else if (p->authmethods & IAX_AUTH_MD5) {
2730 struct MD5Context md5;
2731 unsigned char digest[16];
2733 MD5Update(&md5, p->challenge, strlen(p->challenge));
2734 MD5Update(&md5, p->secret, strlen(p->secret));
2735 MD5Final(digest, &md5);
2736 /* If they support md5, authenticate with it. */
2738 sprintf(requeststr + (x << 1), "%2.2x", digest[x]);
2739 if (!strcasecmp(requeststr, md5secret))
2741 } else if (p->authmethods & IAX_AUTH_PLAINTEXT) {
2742 if (!strcmp(secret, p->secret))
2748 static int register_verify(int callno, struct sockaddr_in *sin, struct iax_ies *ies)
2750 char requeststr[256] = "";
2751 char peer[256] = "";
2752 char md5secret[256] = "";
2753 char rsasecret[256] = "";
2754 char secret[256] = "";
2755 struct iax2_peer *p;
2756 struct ast_key *key;
2761 iaxs[callno]->state &= ~IAX_STATE_AUTHENTICATED;
2762 strcpy(iaxs[callno]->peer, "");
2764 strncpy(peer, ies->username, sizeof(peer) - 1);
2766 strncpy(secret, ies->password, sizeof(secret) - 1);
2767 if (ies->md5_result)
2768 strncpy(md5secret, ies->md5_result, sizeof(md5secret)-1);
2769 if (ies->rsa_result)
2770 strncpy(rsasecret, ies->rsa_result, sizeof(rsasecret)-1);
2772 expire = ies->refresh;
2774 if (!strlen(peer)) {
2775 ast_log(LOG_NOTICE, "Empty registration from %s\n", inet_ntoa(sin->sin_addr));
2779 for (p = peerl.peers; p ; p = p->next)
2780 if (!strcasecmp(p->name, peer))
2784 ast_log(LOG_NOTICE, "No registration for peer '%s' (from %s)\n", peer, inet_ntoa(sin->sin_addr));
2789 ast_log(LOG_NOTICE, "Peer '%s' is not dynamic (from %s)\n", peer, inet_ntoa(sin->sin_addr));
2793 if (!ast_apply_ha(p->ha, sin)) {
2794 ast_log(LOG_NOTICE, "Host %s denied access to register peer '%s'\n", inet_ntoa(sin->sin_addr), p->name);
2797 strncpy(iaxs[callno]->secret, p->secret, sizeof(iaxs[callno]->secret)-1);
2798 strncpy(iaxs[callno]->inkeys, p->inkeys, sizeof(iaxs[callno]->inkeys)-1);
2799 /* Check secret against what we have on file */
2800 if (strlen(rsasecret) && (p->authmethods & IAX_AUTH_RSA) && strlen(p->challenge)) {
2801 if (strlen(p->inkeys)) {
2804 strncpy(tmpkeys, p->inkeys, sizeof(tmpkeys));
2806 keyn = strsep(&stringp, ":");
2808 key = ast_key_get(keyn, AST_KEY_PUBLIC);
2809 if (key && !ast_check_signature(key, p->challenge, rsasecret)) {
2810 iaxs[callno]->state |= IAX_STATE_AUTHENTICATED;
2813 ast_log(LOG_WARNING, "requested inkey '%s' does not exist\n", keyn);
2814 keyn = strsep(&stringp, ":");
2817 ast_log(LOG_NOTICE, "Host %s failed RSA authentication with inkeys '%s'\n", peer, p->inkeys);
2821 ast_log(LOG_NOTICE, "Host '%s' trying to do RSA authentication, but we have no inkeys\n", peer);
2824 } else if (strlen(secret) && (p->authmethods & IAX_AUTH_PLAINTEXT)) {
2825 /* They've provided a plain text password and we support that */
2826 if (strcmp(secret, p->secret)) {
2827 ast_log(LOG_NOTICE, "Host %s did not provide proper plaintext password for '%s'\n", inet_ntoa(sin->sin_addr), p->name);
2830 iaxs[callno]->state |= IAX_STATE_AUTHENTICATED;
2831 } else if (strlen(md5secret) && (p->authmethods & IAX_AUTH_MD5) && strlen(p->challenge)) {
2832 struct MD5Context md5;
2833 unsigned char digest[16];
2835 MD5Update(&md5, p->challenge, strlen(p->challenge));
2836 MD5Update(&md5, p->secret, strlen(p->secret));
2837 MD5Final(digest, &md5);
2839 sprintf(requeststr + (x << 1), "%2.2x", digest[x]);
2840 if (strcasecmp(requeststr, md5secret)) {
2841 ast_log(LOG_NOTICE, "Host %s failed MD5 authentication for '%s' (%s != %s)\n", inet_ntoa(sin->sin_addr), p->name, requeststr, md5secret);
2844 iaxs[callno]->state |= IAX_STATE_AUTHENTICATED;
2845 } else if (strlen(md5secret) || strlen(secret)) {
2846 ast_log(LOG_NOTICE, "Inappropriate authentication received\n");
2849 strncpy(iaxs[callno]->peer, peer, sizeof(iaxs[callno]->peer)-1);
2850 /* Choose lowest expirey number */
2851 if (expire && (expire < iaxs[callno]->expirey))
2852 iaxs[callno]->expirey = expire;
2857 static int authenticate(char *challenge, char *secret, char *keyn, int authmethods, struct iax_ie_data *ied, struct sockaddr_in *sin)
2861 if (keyn && strlen(keyn)) {
2862 if (!(authmethods & IAX_AUTH_RSA)) {
2863 if (!secret || !strlen(secret))
2864 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));
2865 } else if (!strlen(challenge)) {
2866 ast_log(LOG_NOTICE, "No challenge provided for RSA authentication to %s\n", inet_ntoa(sin->sin_addr));
2869 struct ast_key *key;
2870 key = ast_key_get(keyn, AST_KEY_PRIVATE);
2872 ast_log(LOG_NOTICE, "Unable to find private key '%s'\n", keyn);
2874 if (ast_sign(key, challenge, sig)) {
2875 ast_log(LOG_NOTICE, "Unable to sign challenge withy key\n");
2878 iax_ie_append_str(ied, IAX_IE_RSA_RESULT, sig);
2885 if (res && secret && strlen(secret)) {
2886 if ((authmethods & IAX_AUTH_MD5) && strlen(challenge)) {
2887 struct MD5Context md5;
2888 unsigned char digest[16];
2889 char digres[128] = "";
2891 MD5Update(&md5, challenge, strlen(challenge));
2892 MD5Update(&md5, secret, strlen(secret));
2893 MD5Final(digest, &md5);
2894 /* If they support md5, authenticate with it. */
2896 sprintf(digres + (x << 1), "%2.2x", digest[x]);
2897 iax_ie_append_str(ied, IAX_IE_MD5_RESULT, digres);
2899 } else if (authmethods & IAX_AUTH_PLAINTEXT) {
2900 iax_ie_append_str(ied, IAX_IE_PASSWORD, secret);
2903 ast_log(LOG_NOTICE, "No way to send secret to peer '%s' (their methods: %d)\n", inet_ntoa(sin->sin_addr), authmethods);
2908 static int authenticate_reply(struct chan_iax2_pvt *p, struct sockaddr_in *sin, struct iax_ies *ies, char *override, char *okey)
2910 struct iax2_peer *peer;
2911 /* Start pessimistic */
2913 int authmethods = 0;
2914 struct iax_ie_data ied;
2916 memset(&ied, 0, sizeof(ied));
2919 strncpy(p->username, ies->username, sizeof(p->username) - 1);
2921 strncpy(p->challenge, ies->challenge, sizeof(p->challenge)-1);
2922 if (ies->authmethods)
2923 authmethods = ies->authmethods;
2925 /* Check for override RSA authentication first */
2926 if ((override && strlen(override)) || (okey && strlen(okey))) {
2927 /* Normal password authentication */
2928 res = authenticate(p->challenge, override, okey, authmethods, &ied, sin);
2930 ast_pthread_mutex_lock(&peerl.lock);
2933 if ((!strlen(p->peer) || !strcmp(p->peer, peer->name))
2934 /* No peer specified at our end, or this is the peer */
2935 && (!strlen(peer->username) || (!strcmp(peer->username, p->username)))
2936 /* No username specified in peer rule, or this is the right username */
2937 && (!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)))
2938 /* No specified host, or this is our host */
2940 res = authenticate(p->challenge, peer->secret, peer->outkey, authmethods, &ied, sin);
2946 ast_pthread_mutex_unlock(&peerl.lock);
2949 res = send_command(p, AST_FRAME_IAX, AST_IAX2_COMMAND_AUTHREP, 0, ied.buf, ied.pos, -1);
2953 static int iax2_do_register(struct iax2_registry *reg);
2955 static int iax2_do_register_s(void *data)
2957 struct iax2_registry *reg = data;
2959 iax2_do_register(reg);
2963 static int try_transfer(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
2966 char newip[256] = "";
2968 struct sockaddr_in new;
2970 if (ies->apparent_addr)
2971 memcpy(&new, ies->apparent_addr, sizeof(new));
2973 newcall = ies->callno;
2974 if (!newcall || !new.sin_addr.s_addr || !new.sin_port) {
2975 ast_log(LOG_WARNING, "Invalid transfer request\n");
2978 pvt->transfercallno = newcall;
2979 memcpy(&pvt->transfer, &new, sizeof(pvt->transfer));
2980 inet_aton(newip, &pvt->transfer.sin_addr);
2981 pvt->transfer.sin_family = AF_INET;
2982 pvt->transferring = TRANSFER_BEGIN;
2983 send_command_transfer(pvt, AST_FRAME_IAX, AST_IAX2_COMMAND_TXCNT, 0, NULL, 0);
2987 static int complete_dpreply(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
2989 char exten[256] = "";
2990 int status = CACHE_FLAG_UNKNOWN;
2991 int expirey = iaxdefaultdpcache;
2994 struct iax2_dpcache *dp, *prev;
2996 if (ies->called_number)
2997 strncpy(exten, ies->called_number, sizeof(exten)-1);
2999 if (ies->dpstatus & IAX_DPSTATUS_EXISTS)
3000 status = CACHE_FLAG_EXISTS;
3001 else if (ies->dpstatus & IAX_DPSTATUS_CANEXIST)
3002 status = CACHE_FLAG_CANEXIST;
3003 else if (ies->dpstatus & IAX_DPSTATUS_NONEXISTANT)
3004 status = CACHE_FLAG_NONEXISTANT;
3006 if (ies->dpstatus & IAX_DPSTATUS_IGNOREPAT) {
3007 /* Don't really do anything with this */
3010 expirey = ies->refresh;
3011 if (ies->dpstatus & IAX_DPSTATUS_MATCHMORE)
3012 matchmore = CACHE_FLAG_MATCHMORE;
3013 ast_pthread_mutex_lock(&dpcache_lock);
3015 dp = pvt->dpentries;
3017 if (!strcmp(dp->exten, exten)) {
3020 prev->peer = dp->peer;
3022 pvt->dpentries = dp->peer;
3025 dp->expirey.tv_sec = dp->orig.tv_sec + expirey;
3026 if (dp->flags & CACHE_FLAG_PENDING) {
3027 dp->flags &= ~CACHE_FLAG_PENDING;
3028 dp->flags |= status;
3029 dp->flags |= CACHE_FLAG_MATCHMORE;
3031 /* Wake up waiters */
3032 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
3033 if (dp->waiters[x] > -1)
3034 write(dp->waiters[x], "asdf", 4);
3039 ast_pthread_mutex_unlock(&dpcache_lock);
3043 static int complete_transfer(int callno, struct iax_ies *ies)
3046 struct chan_iax2_pvt *pvt = iaxs[callno];
3047 struct ast_iax2_frame *cur;
3050 peercallno = ies->callno;
3052 if (peercallno < 1) {
3053 ast_log(LOG_WARNING, "Invalid transfer request\n");
3056 memcpy(&pvt->addr, &pvt->transfer, sizeof(pvt->addr));
3057 memset(&pvt->transfer, 0, sizeof(pvt->transfer));
3058 /* Reset sequence numbers */
3061 pvt->peercallno = peercallno;
3062 pvt->transferring = TRANSFER_NONE;
3063 pvt->svoiceformat = -1;
3064 pvt->voiceformat = 0;
3065 pvt->transfercallno = -1;
3066 memset(&pvt->rxcore, 0, sizeof(pvt->rxcore));
3067 memset(&pvt->offset, 0, sizeof(pvt->offset));
3068 memset(&pvt->history, 0, sizeof(pvt->history));
3069 pvt->jitterbuffer = 0;
3071 pvt->historicjitter = 0;
3075 pvt->pingtime = DEFAULT_RETRY_TIME;