Update so that "users" are implemented as well
[asterisk/asterisk.git] / channels / chan_iax.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * Implementation of Inter-Asterisk eXchange
5  *
6  * Copyright (C) 1999, Mark Spencer
7  *
8  * Mark Spencer <markster@linux-support.net>
9  *
10  * This program is free software, distributed under the terms of
11  * the GNU General Public License
12  */
13
14 #include <asterisk/lock.h>
15 #include <asterisk/frame.h> 
16 #include <asterisk/channel.h>
17 #include <asterisk/channel_pvt.h>
18 #include <asterisk/logger.h>
19 #include <asterisk/module.h>
20 #include <asterisk/pbx.h>
21 #include <asterisk/sched.h>
22 #include <asterisk/io.h>
23 #include <asterisk/config.h>
24 #include <asterisk/options.h>
25 #include <asterisk/cli.h>
26 #include <asterisk/translate.h>
27 #include <asterisk/md5.h>
28 #include <asterisk/cdr.h>
29 #include <asterisk/crypto.h>
30 #include <asterisk/acl.h>
31 #include <asterisk/manager.h>
32 #include <arpa/inet.h>
33 #include <sys/socket.h>
34 #include <netinet/in.h>
35 #include <netinet/in_systm.h>
36 #include <netinet/ip.h>
37 #include <sys/time.h>
38 #include <sys/signal.h>
39 #include <stdlib.h>
40 #include <stdio.h>
41 #include <string.h>
42 #include <errno.h>
43 #include <unistd.h>
44 #include <netdb.h>
45 #include <fcntl.h>
46
47 #ifdef MYSQL_FRIENDS
48 #include <mysql/mysql.h>
49 #endif
50
51 #include "iax.h"
52
53 #ifndef IPTOS_MINCOST
54 #define IPTOS_MINCOST 0x02
55 #endif
56
57 /*
58  * Uncomment to try experimental IAX bridge optimization,
59  * designed to reduce latency when IAX calls cannot
60  * be trasnferred
61  */
62
63 #define BRIDGE_OPTIMIZATION 
64
65
66 #define DEFAULT_RETRY_TIME 1000
67 #define MEMORY_SIZE 100
68 #define DEFAULT_DROP 3
69
70 #define DEBUG_SUPPORT
71
72 /* Sample over last 100 units to determine historic jitter */
73 #define GAMMA (0.01)
74
75 #ifdef MYSQL_FRIENDS
76 static ast_mutex_t mysqllock = AST_MUTEX_INITIALIZER;
77 static MYSQL *mysql;
78 static char mydbuser[80];
79 static char mydbpass[80];
80 static char mydbhost[80];
81 static char mydbname[80];
82 #endif
83
84 static char *desc = "Inter Asterisk eXchange";
85 static char *tdesc = "Inter Asterisk eXchange Drver";
86 static char *type = "IAX";
87
88 static char context[80] = "default";
89
90 static int max_retries = 4;
91 static int ping_time = 20;
92 static int lagrq_time = 10;
93 static int nextcallno = 0;
94 static int maxjitterbuffer=3000;
95
96 static int iaxdefaultdpcache=10 * 60;   /* Cache dialplan entries for 10 minutes by default */
97
98 static int iaxdefaulttimeout = 5;               /* Default to wait no more than 5 seconds for a reply to come back */
99
100 static int netsocket = -1;
101
102 static int tos = 0;
103
104 static int expirey = AST_DEFAULT_REG_EXPIRE;
105
106 static int usecnt;
107 static ast_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
108
109 int (*iax_regfunk)(char *username, int onoff) = NULL;
110
111 /* Ethernet, etc */
112 #define IAX_CAPABILITY_FULLBANDWIDTH    0xFFFF
113 /* T1, maybe ISDN */
114 #define IAX_CAPABILITY_MEDBANDWIDTH     (IAX_CAPABILITY_FULLBANDWIDTH & \
115                                                                         ~AST_FORMAT_SLINEAR & \
116                                                                         ~AST_FORMAT_ULAW & \
117                                                                         ~AST_FORMAT_ALAW) 
118 /* A modem */
119 #define IAX_CAPABILITY_LOWBANDWIDTH             (IAX_CAPABILITY_MEDBANDWIDTH & \
120                                                                         ~AST_FORMAT_ADPCM & \
121                                                                         ~AST_FORMAT_G726)
122
123 #define IAX_CAPABILITY_LOWFREE          (IAX_CAPABILITY_LOWBANDWIDTH & \
124                                                                          ~AST_FORMAT_G723_1)
125
126
127 #define DEFAULT_MAXMS           2000            /* Must be faster than 2 seconds by default */
128 #define DEFAULT_FREQ_OK         60 * 1000               /* How often to check for the host to be up */
129 #define DEFAULT_FREQ_NOTOK      10 * 1000               /* How often to check, if the host is down... */
130
131 static  struct io_context *io;
132 static  struct sched_context *sched;
133
134 static int iax_capability = IAX_CAPABILITY_FULLBANDWIDTH;
135
136 static int iax_dropcount = DEFAULT_DROP;
137
138 static int use_jitterbuffer = 1;
139
140 static int iaxdebug = 0;
141
142 static char accountcode[20];
143 static int amaflags = 0;
144
145 static pthread_t netthreadid;
146
147 #define IAX_STATE_STARTED               (1 << 0)
148 #define IAX_STATE_AUTHENTICATED (1 << 1)
149 #define IAX_STATE_TBD                   (1 << 2)
150
151 struct iax_context {
152         char context[AST_MAX_EXTENSION];
153         struct iax_context *next;
154 };
155
156 struct iax_user {
157         char name[80];
158         char secret[80];
159         char methods[80];
160         char accountcode[20];
161         char inkeys[80];                                /* Key(s) this user can use to authenticate to us */
162         int amaflags;
163         int hascallerid;
164         int delme;
165         char callerid[AST_MAX_EXTENSION];
166         struct ast_ha *ha;
167         struct iax_context *contexts;
168         struct iax_user *next;
169 };
170
171 struct iax_peer {
172         char name[80];
173         char username[80];              
174         char secret[80];
175         char outkey[80];                /* What key we use to talk to this peer */
176         char context[AST_MAX_EXTENSION];        /* Default context (for transfer really) */
177         struct sockaddr_in addr;
178         int formats;
179         struct in_addr mask;
180
181         /* Dynamic Registration fields */
182         int dynamic;                                    /* If this is a dynamic peer */
183         struct sockaddr_in defaddr;             /* Default address if there is one */
184         char methods[80];
185         char inkeys[80];                                /* Key(s) this peer can use to authenticate to us */
186
187         int hascallerid;
188         /* Suggested caller id if registering */
189         char callerid[AST_MAX_EXTENSION];
190         /* Whether or not to send ANI */
191         int sendani;
192         int expire;                                             /* Schedule entry for expirey */
193         int expirey;                                    /* How soon to expire */
194         int capability;                                 /* Capability */
195         int delme;                                              /* I need to be deleted */
196
197         /* Qualification */
198         int callno;                                     /* Call number of POKE request */
199         int pokeexpire;                                 /* When to expire poke */
200         int lastms;                                     /* How long last response took (in ms), or -1 for no response */
201         int maxms;                                      /* Max ms we will accept for the host to be up, 0 to not monitor */
202         
203         struct ast_ha *ha;
204         struct iax_peer *next;
205 };
206
207 #define REG_STATE_UNREGISTERED 0
208 #define REG_STATE_REGSENT          1
209 #define REG_STATE_AUTHSENT         2
210 #define REG_STATE_REGISTERED   3
211 #define REG_STATE_REJECTED         4
212 #define REG_STATE_TIMEOUT          5
213 #define REG_STATE_NOAUTH           6
214
215 #define TRANSFER_NONE                   0
216 #define TRANSFER_BEGIN                  1
217 #define TRANSFER_READY                  2
218 #define TRANSFER_RELEASED               3
219 #define TRANSFER_PASSTHROUGH    4
220
221 struct iax_registry {
222         struct sockaddr_in addr;                /* Who we connect to for registration purposes */
223         char username[80];
224         char secret[80];                        /* Password or key name in []'s */
225         char random[80];
226         int expire;                                             /* Sched ID of expiration */
227         int refresh;                                    /* How often to refresh */
228         int regstate;
229         int callno;                                             /* Associated call number if applicable */
230         struct sockaddr_in us;                  /* Who the server thinks we are */
231         struct iax_registry *next;
232 };
233
234 static struct iax_registry *registrations;
235
236 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
237 #define MIN_RETRY_TIME  10
238 #define MAX_RETRY_TIME  10000
239 #define MAX_JITTER_BUFFER 50
240
241 /* If we have more than this much excess real jitter buffer, srhink it. */
242 static int max_jitter_buffer = MAX_JITTER_BUFFER;
243
244 struct chan_iax_pvt {
245         /* Pipes for communication.  pipe[1] belongs to the
246            network thread (write), and pipe[0] belongs to the individual 
247            channel (read) */
248         /* Whether or not we Quelch audio */
249         int quelch;
250         /* Last received voice format */
251         int voiceformat;
252         /* Last sent voice format */
253         int svoiceformat;
254         /* What we are capable of sending */
255         int capability;
256         /* Last received timestamp */
257         unsigned int last;
258         /* Last sent timestamp - never send the same timestamp twice in a single call */
259         unsigned int lastsent;
260         /* Ping time */
261         unsigned int pingtime;
262         /* Max time for initial response */
263         int maxtime;
264         /* Peer Address */
265         struct sockaddr_in addr;
266         /* Our call number */
267         int callno;
268         /* Peer callno */
269         int peercallno;
270         /* Peer selected format */
271         int peerformat;
272         /* Peer capability */
273         int peercapability;
274         /* timeval that we base our transmission on */
275         struct timeval offset;
276         /* timeval that we base our delivery on */
277         struct timeval rxcore;
278         /* Historical delivery time */
279         int history[MEMORY_SIZE];
280         /* Current base jitterbuffer */
281         int jitterbuffer;
282         /* Current jitter measure */
283         int jitter;
284         /* Historic jitter value */
285         int historicjitter;
286         /* LAG */
287         int lag;
288         /* Error, as discovered by the manager */
289         int error;
290         /* Owner if we have one */
291         struct ast_channel *owner;
292         /* What's our state? */
293         int state;
294         /* Expirey (optional) */
295         int expirey;
296         /* Next outgoing sequence number */
297         unsigned short oseqno;
298         /* Next incoming sequence number */
299         unsigned short iseqno;
300         /* Peer name */
301         char peer[80];
302         /* Default Context */
303         char context[80];
304         /* Caller ID if available */
305         char callerid[80];
306         /* Hidden Caller ID (i.e. ANI) if appropriate */
307         char ani[80];
308         /* Whether or not ani should be transmitted in addition to Caller*ID */
309         int sendani;
310         /* DNID */
311         char dnid[80];
312         /* Requested Extension */
313         char exten[AST_MAX_EXTENSION];
314         /* Expected Username */
315         char username[80];
316         /* Expected Secret */
317         char secret[80];
318         /* permitted authentication methods */
319         char methods[80];
320         /* MD5 challenge */
321         char challenge[10];
322         /* Public keys permitted keys for incoming authentication */
323         char inkeys[80];
324         /* Private key for outgoing authentication */
325         char outkey[80];
326         /* Preferred language */
327         char language[80];
328         /* Associated registry */
329         struct iax_registry *reg;
330         /* Associated peer for poking */
331         struct iax_peer *peerpoke;
332
333         /* Transferring status */
334         int transferring;
335         /* Already disconnected */
336         int alreadygone;
337         /* Who we are IAX transfering to */
338         struct sockaddr_in transfer;
339         /* What's the new call number for the transfer */
340         int transfercallno;
341
342         /* Status of knowledge of peer ADSI capability */
343         int peeradsicpe;
344         
345         /* Who we are bridged to */
346         int bridgecallno;
347         int pingid;                     /* Transmit PING request */
348         int lagid;                      /* Retransmit lag request */
349         int autoid;                     /* Auto hangup for Dialplan requestor */
350         int initid;                     /* Initial peer auto-congest ID (based on qualified peers) */
351         char dproot[AST_MAX_EXTENSION];
352         char accountcode[20];
353         int amaflags;
354         struct iax_dpcache *dpentries;
355 };
356
357 #define DIRECTION_INGRESS 1
358 #define DIRECTION_OUTGRESS 2
359
360 struct ast_iax_frame {
361         /* Actual, isolated frame */
362         struct ast_frame *f;
363         /* /Our/ call number */
364         short callno;
365         /* Start of raw frame (outgoing only) */
366         void *data;
367         /* Length of frame (outgoing only) */
368         int datalen;
369         /* How many retries so far? */
370         int retries;
371         /* Outgoing relative timestamp (ms) */
372         unsigned int ts;
373         /* How long to wait before retrying */
374         int retrytime;
375         /* Are we received out of order?  */
376         int outoforder;
377         /* Have we been sent at all yet? */
378         int sentyet;
379         /* Packet sequence number */
380         int seqno;
381         /* Non-zero if should be sent to transfer peer */
382         int transfer;
383         /* Non-zero if this is the final message */
384         int final;
385         /* Ingress or outgres */
386         int direction;
387         /* Retransmission ID */
388         int retrans;
389
390
391         /* Easy linking */
392         struct ast_iax_frame *next;
393         struct ast_iax_frame *prev;
394 };
395
396 static struct ast_iax_queue {
397         struct ast_iax_frame *head;
398         struct ast_iax_frame *tail;
399         int count;
400         ast_mutex_t lock;
401 } iaxq;
402
403 static struct ast_user_list {
404         struct iax_user *users;
405         ast_mutex_t lock;
406 } userl;
407
408 static struct ast_peer_list {
409         struct iax_peer *peers;
410         ast_mutex_t lock;
411 } peerl;
412
413 /* Extension exists */
414 #define CACHE_FLAG_EXISTS               (1 << 0)
415 /* Extension is non-existant */
416 #define CACHE_FLAG_NONEXISTANT  (1 << 1)
417 /* Extension can exist */
418 #define CACHE_FLAG_CANEXIST             (1 << 2)
419 /* Waiting to hear back response */
420 #define CACHE_FLAG_PENDING              (1 << 3)
421 /* Timed out */
422 #define CACHE_FLAG_TIMEOUT              (1 << 4)
423 /* Request transmitted */
424 #define CACHE_FLAG_TRANSMITTED  (1 << 5)
425 /* Timeout */
426 #define CACHE_FLAG_UNKNOWN              (1 << 6)
427 /* Matchmore */
428 #define CACHE_FLAG_MATCHMORE    (1 << 7)
429
430 static struct iax_dpcache {
431         char peercontext[AST_MAX_EXTENSION];
432         char exten[AST_MAX_EXTENSION];
433         struct timeval orig;
434         struct timeval expirey;
435         int flags;
436         int callno;
437         int waiters[256];
438         struct iax_dpcache *next;
439         struct iax_dpcache *peer;       /* For linking in peers */
440 } *dpcache;
441
442 static ast_mutex_t dpcache_lock;
443
444 #ifdef DEBUG_SUPPORT
445 static void showframe(struct ast_iax_frame *f, struct ast_iax_full_hdr *fhi, int rx, struct sockaddr_in *sin)
446 {
447         char *frames[] = {
448                 "(0?)",
449                 "DTMF   ",
450                 "VOICE  ",
451                 "VIDEO  ",
452                 "CONTROL",
453                 "NULL   ",
454                 "IAX    ",
455                 "TEXT   ",
456                 "IMAGE  " };
457         char *iaxs[] = {
458                 "(0?)",
459                 "NEW    ",
460                 "PING   ",
461                 "PONG   ",
462                 "ACK    ",
463                 "HANGUP ",
464                 "REJECT ",
465                 "ACCEPT ",
466                 "AUTHREQ",
467                 "AUTHREP",
468                 "INVAL  ",
469                 "LAGRQ  ",
470                 "LAGRP  ",
471                 "REGREQ ",
472                 "REGAUTH",
473                 "REGACK ",
474                 "REGREJ ",
475                 "REGREL ",
476                 "VNAK   ",
477                 "DPREQ  ",
478                 "DPREP  ",
479                 "DIAL   ",
480                 "TXREQ  ",
481                 "TXCNT  ",
482                 "TXACC  ",
483                 "TXREADY",
484                 "TXREL  ",
485                 "TXREJ  ",
486                 "QUELCH ",
487                 "UNQULCH",
488                 "POKE",
489         };
490         char *cmds[] = {
491                 "(0?)",
492                 "HANGUP ",
493                 "RING   ",
494                 "RINGING",
495                 "ANSWER ",
496                 "BUSY   ",
497                 "TKOFFHK ",
498                 "OFFHOOK" };
499         struct ast_iax_full_hdr *fh;
500         char retries[20];
501         char class2[20];
502         char subclass2[20];
503         char *class;
504         char *subclass;
505         if (f) {
506                 fh = f->data;
507                 snprintf(retries, sizeof(retries), "%03d", f->retries);
508         } else {
509                 strcpy(retries, "N/A");
510                 fh = fhi;
511         }
512         if (!(ntohs(fh->callno) & AST_FLAG_FULL)) {
513                 /* Don't mess with mini-frames */
514                 return;
515         }
516         if (fh->type > sizeof(frames)/sizeof(char *)) {
517                 snprintf(class2, sizeof(class2), "(%d?)", fh->type);
518                 class = class2;
519         } else {
520                 class = frames[(int)fh->type];
521         }
522         if (fh->type == AST_FRAME_DTMF) {
523                 sprintf(subclass2, "%c", fh->csub);
524                 subclass = subclass2;
525         } else if (fh->type == AST_FRAME_IAX) {
526                 if (fh->csub >= sizeof(iaxs)/sizeof(iaxs[0])) {
527                         snprintf(subclass2, sizeof(subclass2), "(%d?)", fh->csub);
528                         subclass = subclass2;
529                 } else {
530                         subclass = iaxs[(int)fh->csub];
531                 }
532         } else if (fh->type == AST_FRAME_CONTROL) {
533                 if (fh->csub > sizeof(cmds)/sizeof(char *)) {
534                         snprintf(subclass2, sizeof(subclass2), "(%d?)", fh->csub);
535                         subclass = subclass2;
536                 } else {
537                         subclass = cmds[(int)fh->csub];
538                 }
539         } else {
540                 snprintf(subclass2, sizeof(subclass2), "%d", fh->csub);
541                 subclass = subclass2;
542         }
543         ast_verbose(
544 "%s-Frame Retry[%s] -- Seqno: %2.2d  Type: %s Subclass: %s\n",
545         (rx ? "Rx" : "Tx"),
546         retries, ntohs(fh->seqno), class, subclass);
547                 fprintf(stderr,
548 "   Timestamp: %05ldms  Callno: %5.5d  DCall: %5.5d [%s:%d]\n",
549         (long)ntohl(fh->ts),
550         (short)(ntohs(fh->callno) & ~AST_FLAG_FULL), (short) ntohs(fh->dcallno),
551                 inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
552 }
553 #endif
554
555 /* XXX We probably should use a mutex when working with this XXX */
556 static struct chan_iax_pvt *iaxs[AST_IAX_MAX_CALLS];
557 static ast_mutex_t iaxsl[AST_IAX_MAX_CALLS];
558
559 static int send_command(struct chan_iax_pvt *, char, int, unsigned int, char *, int, int);
560 static int send_command_immediate(struct chan_iax_pvt *, char, int, unsigned int, char *, int, int);
561 static int send_command_final(struct chan_iax_pvt *, char, int, unsigned int, char *, int, int);
562 static int send_command_transfer(struct chan_iax_pvt *, char, int, unsigned int, char *, int);
563
564 static unsigned int calc_timestamp(struct chan_iax_pvt *p, unsigned int ts);
565
566 static int send_ping(void *data)
567 {
568         int callno = (long)data;
569         /* Ping only if it's real, not if it's bridged */
570         if (iaxs[callno]) {
571 #ifdef BRIDGE_OPTIMIZATION
572                 if (iaxs[callno]->bridgecallno < 0)
573 #endif
574                         send_command(iaxs[callno], AST_FRAME_IAX, AST_IAX_COMMAND_PING, 0, NULL, 0, -1);
575                 return 1;
576         } else
577                 return 0;
578 }
579
580 static int send_lagrq(void *data)
581 {
582         int callno = (long)data;
583         /* Ping only if it's real not if it's bridged */
584         if (iaxs[callno]) {
585 #ifdef BRIDGE_OPTIMIZATION
586                 if (iaxs[callno]->bridgecallno < 0)
587 #endif          
588                         send_command(iaxs[callno], AST_FRAME_IAX, AST_IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
589                 return 1;
590         } else
591                 return 0;
592 }
593
594 static unsigned char compress_subclass(int subclass)
595 {
596         int x;
597         int power=-1;
598         /* If it's 128 or smaller, just return it */
599         if (subclass < AST_FLAG_SC_LOG)
600                 return subclass;
601         /* Otherwise find its power */
602         for (x = 0; x < AST_MAX_SHIFT; x++) {
603                 if (subclass & (1 << x)) {
604                         if (power > -1) {
605                                 ast_log(LOG_WARNING, "Can't compress subclass %d\n", subclass);
606                                 return 0;
607                         } else
608                                 power = x;
609                 }
610         }
611         return power | AST_FLAG_SC_LOG;
612 }
613
614 static int uncompress_subclass(unsigned char csub)
615 {
616         /* If the SC_LOG flag is set, return 2^csub otherwise csub */
617         if (csub & AST_FLAG_SC_LOG) {
618                 /* special case for 'compressed' -1 */
619                 if (csub == 0xff)
620                         return -1;
621                 else
622                         return 1 << (csub & ~AST_FLAG_SC_LOG & AST_MAX_SHIFT);
623         }
624         else
625                 return csub;
626 }
627
628 static struct chan_iax_pvt *new_iax(void)
629 {
630         struct chan_iax_pvt *tmp;
631         tmp = malloc(sizeof(struct chan_iax_pvt));
632         if (tmp) {
633                 memset(tmp, 0, sizeof(struct chan_iax_pvt));
634                 tmp->callno = -1;
635                 tmp->peercallno = -1;
636                 tmp->transfercallno = -1;
637                 tmp->bridgecallno = -1;
638                 tmp->pingid = -1;
639                 tmp->lagid = -1;
640                 tmp->autoid = -1;
641                 tmp->initid = -1;
642                 /* strncpy(tmp->context, context, sizeof(tmp->context)-1); */
643                 strncpy(tmp->exten, "s", sizeof(tmp->exten)-1);
644         }
645         return tmp;
646 }
647
648 static int get_samples(struct ast_frame *f)
649 {
650         int samples=0;
651         switch(f->subclass) {
652         case AST_FORMAT_G723_1:
653                 samples = 240 /* XXX Not necessarily true XXX */;
654                 break;
655         case AST_FORMAT_GSM:
656                 samples = 160 * (f->datalen / 33);
657                 break;
658         case AST_FORMAT_ILBC:
659                 samples = 240 * (f->datalen / 50);
660                 break;
661         case AST_FORMAT_G729A:
662                 samples = 160 * (f->datalen / 20);
663                 break;
664         case AST_FORMAT_SLINEAR:
665                 samples = f->datalen / 2;
666                 break;
667         case AST_FORMAT_LPC10:
668                 samples = 22 * 8;
669                 samples += (((char *)(f->data))[7] & 0x1) * 8;
670                 break;
671         case AST_FORMAT_ULAW:
672                 samples = f->datalen;
673                 break;
674         case AST_FORMAT_ALAW:
675                 samples = f->datalen;
676                 break;
677         case AST_FORMAT_ADPCM:
678                 samples = f->datalen *2;
679                 break;
680         case AST_FORMAT_SPEEX:
681                 samples = (f->datalen/39)*160;
682                 break;
683         default:
684                 ast_log(LOG_WARNING, "Don't know how to calculate samples on %d packets\n", f->subclass);
685         }
686         return samples;
687 }
688
689 static int frames = 0;
690 static int iframes = 0;
691 static int oframes = 0;
692
693 static struct ast_iax_frame *ast_iax_frame_new(int direction)
694 {
695         struct ast_iax_frame *fr;
696         fr = malloc(sizeof(struct ast_iax_frame));
697         if (fr) {
698                 fr->direction = direction;
699                 fr->retrans = -1;
700                 frames++;
701                 if (fr->direction == DIRECTION_INGRESS)
702                         iframes++;
703                 else
704                         oframes++;
705         }
706         return fr;
707 }
708
709 static void ast_iax_frame_free(struct ast_iax_frame *fr)
710 {
711         if (fr->retrans > -1)
712                 ast_sched_del(sched, fr->retrans);
713         if (fr->direction == DIRECTION_INGRESS)
714                 iframes--;
715         else if (fr->direction == DIRECTION_OUTGRESS)
716                 oframes--;
717         else {
718                 ast_log(LOG_WARNING, "Attempt to double free frame detected\n");
719                 CRASH;
720                 return;
721         }
722         fr->direction = 0;
723         free(fr);
724         frames--;
725 }
726
727 static struct ast_iax_frame *iaxfrdup2(struct ast_iax_frame *fr, int ch)
728 {
729         /* Malloc() a copy of a frame */
730         struct ast_iax_frame *new = ast_iax_frame_new(DIRECTION_INGRESS);
731         if (new) {
732                 memcpy(new, fr, sizeof(struct ast_iax_frame));  
733                 new->f = ast_frdup(fr->f);
734                 /* Copy full header */
735                 if (ch) {
736                         memcpy(new->f->data - sizeof(struct ast_iax_full_hdr),
737                                         fr->f->data - sizeof(struct ast_iax_full_hdr), 
738                                                 sizeof(struct ast_iax_full_hdr));
739                         /* Grab new data pointer */
740                         new->data = new->f->data - (fr->f->data - fr->data);
741                 } else {
742                         new->data = NULL;
743                         new->datalen = 0;
744                 }
745                 new->direction = DIRECTION_INGRESS;
746                 new->retrans = -1;
747         }
748         return new;
749 }
750
751 #define NEW_PREVENT 0
752 #define NEW_ALLOW       1
753 #define NEW_FORCE       2
754
755 static int match(struct sockaddr_in *sin, short callno, short dcallno, struct chan_iax_pvt *cur)
756 {
757         if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
758                 (cur->addr.sin_port == sin->sin_port)) {
759                 /* This is the main host */
760                 if ((cur->peercallno == callno) ||
761                         ((dcallno == cur->callno) && (cur->peercallno) == -1)) {
762                         /* That's us.  Be sure we keep track of the peer call number */
763                         return 1;
764                 }
765         }
766         if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
767             (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
768                 /* We're transferring */
769                 if (dcallno == cur->callno)
770                         return 1;
771         }
772         return 0;
773 }
774
775 static int find_callno(short callno, short dcallno ,struct sockaddr_in *sin, int new)
776 {
777         int res = -1;
778         int x;
779         int start;
780         if (new <= NEW_ALLOW) {
781                 /* Look for an existing connection first */
782                 for (x=0;(res < 0) && (x<AST_IAX_MAX_CALLS);x++) {
783                         ast_mutex_lock(&iaxsl[x]);
784                         if (iaxs[x]) {
785                                 /* Look for an exact match */
786                                 if (match(sin, callno, dcallno, iaxs[x])) {
787                                         res = x;
788                                 }
789                         }
790                         ast_mutex_unlock(&iaxsl[x]);
791                 }
792         }
793         if ((res < 0) && (new >= NEW_ALLOW)) {
794                 /* Create a new one */
795                 start = nextcallno;
796                 for (x = (nextcallno + 1) % AST_IAX_MAX_CALLS; iaxs[x] && (x != start); x = (x + 1) % AST_IAX_MAX_CALLS)
797                 if (x == start) {
798                         ast_log(LOG_WARNING, "Unable to accept more calls\n");
799                         return -1;
800                 }
801                 ast_mutex_lock(&iaxsl[x]);
802                 iaxs[x] = new_iax();
803                 ast_mutex_unlock(&iaxsl[x]);
804                 if (iaxs[x]) {
805                         if (option_debug)
806                                 ast_log(LOG_DEBUG, "Creating new call structure %d\n", x);
807                         iaxs[x]->addr.sin_port = sin->sin_port;
808                         iaxs[x]->addr.sin_family = sin->sin_family;
809                         iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
810                         iaxs[x]->peercallno = callno;
811                         iaxs[x]->callno = x;
812                         iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
813                         iaxs[x]->expirey = expirey;
814                         iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)x);
815                         iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)x);
816                         iaxs[x]->amaflags = amaflags;
817                         strncpy(iaxs[x]->accountcode, accountcode, sizeof(iaxs[x]->accountcode)-1);
818                 } else {
819                         ast_log(LOG_WARNING, "Out of resources\n");
820                         return -1;
821                 }
822                 res = x;
823                 nextcallno = x;
824         }
825         return res;
826 }
827
828 static int iax_queue_frame(int callno, struct ast_frame *f)
829 {
830         int pass =0;
831         /* Assumes lock for callno is already held... */
832         for (;;) {
833                 pass++;
834                 if (!ast_mutex_trylock(&iaxsl[callno])) {
835                         ast_log(LOG_WARNING, "Lock is not held on pass %d of iax_queue_frame\n", pass);
836                         CRASH;
837                 }
838                 if (iaxs[callno] && iaxs[callno]->owner) {
839                         if (ast_mutex_trylock(&iaxs[callno]->owner->lock)) {
840                                 /* Avoid deadlock by pausing and trying again */
841                                 ast_mutex_unlock(&iaxsl[callno]);
842                                 usleep(1);
843                                 ast_mutex_lock(&iaxsl[callno]);
844                         } else {
845                                 ast_queue_frame(iaxs[callno]->owner, f, 0);
846                                 ast_mutex_unlock(&iaxs[callno]->owner->lock);
847                                 break;
848                         }
849                 } else
850                         break;
851         }
852         return 0;
853 }
854
855 static int iax_send(struct chan_iax_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
856
857 static int __do_deliver(void *data)
858 {
859         /* Just deliver the packet by using queueing.  This is called by
860           the IAX thread with the iaxsl lock held. */
861         struct ast_iax_frame *fr = data;
862         unsigned int ts;
863         fr->retrans = -1;
864         if (iaxs[fr->callno] && !iaxs[fr->callno]->alreadygone) {
865                 if (fr->f->frametype == AST_FRAME_IAX) {
866                         /* We have to treat some of these packets specially because
867                            they're LAG measurement packets */
868                         if (fr->f->subclass == AST_IAX_COMMAND_LAGRQ) {
869                                 /* If we got a queued request, build a reply and send it */
870                                 fr->f->subclass = AST_IAX_COMMAND_LAGRP;
871                                 iax_send(iaxs[fr->callno], fr->f, fr->ts, -1, 0, 0, 0);
872                         } else if (fr->f->subclass == AST_IAX_COMMAND_LAGRP) {
873                                 /* This is a reply we've been given, actually measure the difference */
874                                 ts = calc_timestamp(iaxs[fr->callno], 0);
875                                 iaxs[fr->callno]->lag = ts - fr->ts;
876                         }
877                 } else {
878                         iax_queue_frame(fr->callno, fr->f);
879                 }
880         }
881         /* Free the packet */
882         ast_frfree(fr->f);
883         /* And our iax frame */
884         ast_iax_frame_free(fr);
885         /* And don't run again */
886         return 0;
887 }
888
889 static int do_deliver(void *data)
890 {
891         /* Locking version of __do_deliver */
892         struct ast_iax_frame *fr = data;
893         int callno = fr->callno;
894         int res;
895         ast_mutex_lock(&iaxsl[callno]);
896         res = __do_deliver(data);
897         ast_mutex_unlock(&iaxsl[callno]);
898         return res;
899 }
900
901 static int handle_error(void)
902 {
903         /* XXX Ideally we should figure out why an error occured and then abort those
904            rather than continuing to try.  Unfortunately, the published interface does
905            not seem to work XXX */
906 #if 0
907         struct sockaddr_in *sin;
908         int res;
909         struct msghdr m;
910         struct sock_extended_err e;
911         m.msg_name = NULL;
912         m.msg_namelen = 0;
913         m.msg_iov = NULL;
914         m.msg_control = &e;
915         m.msg_controllen = sizeof(e);
916         m.msg_flags = 0;
917         res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
918         if (res < 0)
919                 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
920         else {
921                 if (m.msg_controllen) {
922                         sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
923                         if (sin) 
924                                 ast_log(LOG_WARNING, "Receive error from %s\n", inet_ntoa(sin->sin_addr));
925                         else
926                                 ast_log(LOG_WARNING, "No address detected??\n");
927                 } else {
928                         ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
929                 }
930         }
931 #endif
932         return 0;
933 }
934
935 static int send_packet(struct ast_iax_frame *f)
936 {
937         int res;
938         /* Called with iaxsl held */
939         if (option_debug)
940                 ast_log(LOG_DEBUG, "Sending %d on %d/%d to %s:%d\n", f->ts, f->callno, iaxs[f->callno]->peercallno, inet_ntoa(iaxs[f->callno]->addr.sin_addr), ntohs(iaxs[f->callno]->addr.sin_port));
941         /* Don't send if there was an error, but return error instead */
942         if (f->callno < 0) {
943                 ast_log(LOG_WARNING, "Call number = %d\n", f->callno);
944                 return -1;
945         }
946         if (!iaxs[f->callno])
947                 return -1;
948         if (iaxs[f->callno]->error)
949                 return -1;
950         if (f->transfer) {
951 #ifdef DEBUG_SUPPORT
952                 if (iaxdebug)
953                         showframe(f, NULL, 0, &iaxs[f->callno]->transfer);
954 #endif
955                 res = sendto(netsocket, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[f->callno]->transfer,
956                                         sizeof(iaxs[f->callno]->transfer));
957         } else {
958 #ifdef DEBUG_SUPPORT
959                 if (iaxdebug)
960                         showframe(f, NULL, 0, &iaxs[f->callno]->addr);
961 #endif
962                 res = sendto(netsocket, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[f->callno]->addr,
963                                         sizeof(iaxs[f->callno]->addr));
964         }
965         if (res < 0) {
966                 if (option_debug)
967                         ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
968                 handle_error();
969         } else
970                 res = 0;
971         return res;
972 }
973
974
975 static int iax_predestroy(int callno)
976 {
977         struct ast_channel *c;
978         struct chan_iax_pvt *pvt;
979         ast_mutex_lock(&iaxsl[callno]);
980         pvt = iaxs[callno];
981         if (!pvt) {
982                 ast_mutex_unlock(&iaxsl[callno]);
983                 return -1;
984         }
985         if (!pvt->alreadygone) {
986                 /* No more pings or lagrq's */
987                 if (pvt->pingid > -1)
988                         ast_sched_del(sched, pvt->pingid);
989                 if (pvt->lagid > -1)
990                         ast_sched_del(sched, pvt->lagid);
991                 if (pvt->autoid > -1)
992                         ast_sched_del(sched, pvt->autoid);
993                 if (pvt->initid > -1)
994                         ast_sched_del(sched, pvt->initid);
995                 pvt->pingid = -1;
996                 pvt->lagid = -1;
997                 pvt->autoid = -1;
998                 pvt->initid = -1;
999                 pvt->alreadygone = 1;
1000         }
1001         c = pvt->owner;
1002         if (c) {
1003                 c->_softhangup |= AST_SOFTHANGUP_DEV;
1004                 c->pvt->pvt = NULL;
1005                 pvt->owner = NULL;
1006                 ast_mutex_lock(&usecnt_lock);
1007                 usecnt--;
1008                 if (usecnt < 0) 
1009                         ast_log(LOG_WARNING, "Usecnt < 0???\n");
1010                 ast_mutex_unlock(&usecnt_lock);
1011                 ast_update_use_count();
1012         }
1013         ast_mutex_unlock(&iaxsl[callno]);
1014         return 0;
1015 }
1016
1017 static int iax_predestroy_nolock(int callno)
1018 {
1019         int res;
1020         ast_mutex_unlock(&iaxsl[callno]);
1021         res = iax_predestroy(callno);
1022         ast_mutex_lock(&iaxsl[callno]);
1023         return res;
1024 }
1025
1026 static void iax_destroy(int callno)
1027 {
1028         struct chan_iax_pvt *pvt;
1029         struct ast_iax_frame *cur;
1030         struct ast_channel *owner;
1031
1032 retry:
1033         ast_mutex_lock(&iaxsl[callno]);
1034         pvt = iaxs[callno];
1035         iaxs[callno] = NULL;
1036
1037         if (pvt)
1038                 owner = pvt->owner;
1039         else
1040                 owner = NULL;
1041         if (owner) {
1042                 if (ast_mutex_trylock(&owner->lock)) {
1043                         ast_log(LOG_NOTICE, "Avoiding IAX destroy deadlock\n");
1044                         ast_mutex_unlock(&iaxsl[callno]);
1045                         usleep(1);
1046                         goto retry;
1047                 }
1048         }
1049         if (pvt) {
1050                 pvt->owner = NULL;
1051                 /* No more pings or lagrq's */
1052                 if (pvt->pingid > -1)
1053                         ast_sched_del(sched, pvt->pingid);
1054                 if (pvt->lagid > -1)
1055                         ast_sched_del(sched, pvt->lagid);
1056                 if (pvt->autoid > -1)
1057                         ast_sched_del(sched, pvt->autoid);
1058                 if (pvt->initid > -1)
1059                         ast_sched_del(sched, pvt->initid);
1060                 pvt->pingid = -1;
1061                 pvt->lagid = -1;
1062                 pvt->autoid = -1;
1063                 pvt->initid = -1;
1064
1065                 /* Already gone */
1066                 pvt->alreadygone = 1;
1067
1068                 if (owner) {
1069                         /* If there's an owner, prod it to give up */
1070                         owner->pvt->pvt = NULL;
1071                         owner->_softhangup |= AST_SOFTHANGUP_DEV;
1072                         ast_queue_hangup(owner, 0);
1073                 }
1074
1075                 for (cur = iaxq.head; cur ; cur = cur->next) {
1076                         /* Cancel any pending transmissions */
1077                         if (cur->callno == pvt->callno) 
1078                                 cur->retries = -1;
1079                 }
1080                 if (pvt->reg) {
1081                         pvt->reg->callno = -1;
1082                 }
1083                 free(pvt);
1084         }
1085         if (owner) {
1086                 ast_mutex_unlock(&owner->lock);
1087         }
1088         ast_mutex_unlock(&iaxsl[callno]);
1089 }
1090 static void iax_destroy_nolock(int callno)
1091 {       
1092         /* Actually it's easier to unlock, kill it, and relock */
1093         ast_mutex_unlock(&iaxsl[callno]);
1094         iax_destroy(callno);
1095         ast_mutex_lock(&iaxsl[callno]);
1096 }
1097
1098
1099
1100 static int attempt_transmit(void *data)
1101 {
1102         /* Attempt to transmit the frame to the remote peer...
1103            Called without iaxsl held. */
1104         struct ast_iax_frame *f = data;
1105         int freeme=0;
1106         int callno = f->callno;
1107         /* Make sure this call is still active */
1108         if (callno > -1) 
1109                 ast_mutex_lock(&iaxsl[callno]);
1110         if ((f->callno > -1) && iaxs[f->callno]) {
1111                 if ((f->retries < 0) /* Already ACK'd */ ||
1112                     (f->retries >= max_retries) /* Too many attempts */) {
1113                                 /* Record an error if we've transmitted too many times */
1114                                 if (f->retries >= max_retries) {
1115                                         if (f->transfer) {
1116                                                 /* Transfer timeout */
1117                                                 send_command(iaxs[f->callno], AST_FRAME_IAX, AST_IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
1118                                         } else if (f->final) {
1119                                                 if (f->final) 
1120                                                         iax_destroy_nolock(f->callno);
1121                                         } else {
1122                                                 if (iaxs[f->callno]->owner)
1123                                                         ast_log(LOG_WARNING, "Max retries exceeded to host %s on %s (type = %d, subclass = %d, ts=%d, seqno=%d)\n", inet_ntoa(iaxs[f->callno]->addr.sin_addr),iaxs[f->callno]->owner->name , f->f->frametype, f->f->subclass, f->ts, f->seqno);
1124                                                 iaxs[f->callno]->error = ETIMEDOUT;
1125                                                 if (iaxs[f->callno]->owner) {
1126                                                         struct ast_frame fr = { 0, };
1127                                                         /* Hangup the fd */
1128                                                         fr.frametype = AST_FRAME_CONTROL;
1129                                                         fr.subclass = AST_CONTROL_HANGUP;
1130                                                         iax_queue_frame(f->callno, &fr);
1131                                                 } else {
1132                                                         if (iaxs[f->callno]->reg) {
1133                                                                 memset(&iaxs[f->callno]->reg->us, 0, sizeof(iaxs[f->callno]->reg->us));
1134                                                                 iaxs[f->callno]->reg->regstate = REG_STATE_TIMEOUT;
1135                                                                 iaxs[f->callno]->reg->refresh = AST_DEFAULT_REG_EXPIRE;
1136                                                         }
1137                                                         iax_destroy_nolock(f->callno);
1138                                                 }
1139                                         }
1140
1141                                 }
1142                                 freeme++;
1143                 } else {
1144                         /* Attempt transmission */
1145                         send_packet(f);
1146                         f->retries++;
1147                         /* Try again later after 10 times as long */
1148                         f->retrytime *= 10;
1149                         if (f->retrytime > MAX_RETRY_TIME)
1150                                 f->retrytime = MAX_RETRY_TIME;
1151                         /* Transfer messages max out at one second */
1152                         if (f->transfer && (f->retrytime > 1000))
1153                                 f->retrytime = 1000;
1154                         f->retrans = ast_sched_add(sched, f->retrytime, attempt_transmit, f);
1155                 }
1156         } else {
1157                 /* Make sure it gets freed */
1158                 f->retries = -1;
1159                 freeme++;
1160         }
1161         if (callno > -1)
1162                 ast_mutex_unlock(&iaxsl[callno]);
1163         /* Do not try again */
1164         if (freeme) {
1165                 /* Don't attempt delivery, just remove it from the queue */
1166                 ast_mutex_lock(&iaxq.lock);
1167                 if (f->prev) 
1168                         f->prev->next = f->next;
1169                 else
1170                         iaxq.head = f->next;
1171                 if (f->next)
1172                         f->next->prev = f->prev;
1173                 else
1174                         iaxq.tail = f->prev;
1175                 iaxq.count--;
1176                 ast_mutex_unlock(&iaxq.lock);
1177                 /* Free the frame */
1178                 ast_frfree(f->f);
1179                 f->retrans = -1;
1180                 ast_iax_frame_free(f);
1181         }
1182         return 0;
1183 }
1184
1185 static int iax_set_jitter(int fd, int argc, char *argv[])
1186 {
1187         if ((argc != 4) && (argc != 5))
1188                 return RESULT_SHOWUSAGE;
1189         if (argc == 4) {
1190                 max_jitter_buffer = atoi(argv[3]);
1191                 if (max_jitter_buffer < 0)
1192                         max_jitter_buffer = 0;
1193         } else {
1194                 if (argc == 5) {
1195                         if ((atoi(argv[3]) >= 0) && (atoi(argv[3]) < AST_IAX_MAX_CALLS)) {
1196                                 if (iaxs[atoi(argv[3])]) {
1197                                         iaxs[atoi(argv[3])]->jitterbuffer = atoi(argv[4]);
1198                                         if (iaxs[atoi(argv[3])]->jitterbuffer < 0)
1199                                                 iaxs[atoi(argv[3])]->jitterbuffer = 0;
1200                                 } else
1201                                         ast_cli(fd, "No such call '%d'\n", atoi(argv[3]));
1202                         } else
1203                                 ast_cli(fd, "%d is not a valid call number\n", atoi(argv[3]));
1204                 }
1205         }
1206         return RESULT_SUCCESS;
1207 }
1208
1209 static char jitter_usage[] = 
1210 "Usage: iax set jitter [callid] <value>\n"
1211 "       If used with a callid, it sets the jitter buffer to the given static\n"
1212 "value (until its next calculation).  If used without a callid, the value is used\n"
1213 "to establish the maximum excess jitter buffer that is permitted before the jitter\n"
1214 "buffer size is reduced.";
1215
1216 static int iax_show_stats(int fd, int argc, char *argv[])
1217 {
1218         struct ast_iax_frame *cur;
1219         int cnt = 0, dead=0, final=0;
1220         if (argc != 3)
1221                 return RESULT_SHOWUSAGE;
1222         for (cur = iaxq.head; cur ; cur = cur->next) {
1223                 if (cur->retries < 0)
1224                         dead++;
1225                 if (cur->final)
1226                         final++;
1227                 cnt++;
1228         }
1229         ast_cli(fd, "    IAX Statistics\n");
1230         ast_cli(fd, "---------------------\n");
1231         ast_cli(fd, "Outstanding frames: %d (%d ingress, %d outgress)\n", frames, iframes, oframes);
1232         ast_cli(fd, "Packets in transmit queue: %d dead, %d final, %d total\n", dead, final, cnt);
1233         return RESULT_SUCCESS;
1234 }
1235
1236 static int iax_show_cache(int fd, int argc, char *argv[])
1237 {
1238         struct iax_dpcache *dp;
1239         char tmp[1024], *pc;
1240         int s;
1241         int x,y;
1242         struct timeval tv;
1243         gettimeofday(&tv, NULL);
1244         ast_mutex_lock(&dpcache_lock);
1245         dp = dpcache;
1246         ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
1247         while(dp) {
1248                 s = dp->expirey.tv_sec - tv.tv_sec;
1249                 strcpy(tmp, "");
1250                 if (dp->flags & CACHE_FLAG_EXISTS)
1251                         strcat(tmp, "EXISTS|");
1252                 if (dp->flags & CACHE_FLAG_NONEXISTANT)
1253                         strcat(tmp, "NONEXISTANT|");
1254                 if (dp->flags & CACHE_FLAG_CANEXIST)
1255                         strcat(tmp, "CANEXIST|");
1256                 if (dp->flags & CACHE_FLAG_PENDING)
1257                         strcat(tmp, "PENDING|");
1258                 if (dp->flags & CACHE_FLAG_TIMEOUT)
1259                         strcat(tmp, "TIMEOUT|");
1260                 if (dp->flags & CACHE_FLAG_TRANSMITTED)
1261                         strcat(tmp, "TRANSMITTED|");
1262                 if (dp->flags & CACHE_FLAG_MATCHMORE)
1263                         strcat(tmp, "MATCHMORE|");
1264                 if (dp->flags & CACHE_FLAG_UNKNOWN)
1265                         strcat(tmp, "UNKNOWN|");
1266                 /* Trim trailing pipe */
1267                 if (strlen(tmp))
1268                         tmp[strlen(tmp) - 1] = '\0';
1269                 else
1270                         strcpy(tmp, "(none)");
1271                 y=0;
1272                 pc = strchr(dp->peercontext, '@');
1273                 if (!pc)
1274                         pc = dp->peercontext;
1275                 else
1276                         pc++;
1277                 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
1278                         if (dp->waiters[x] > -1)
1279                                 y++;
1280                 if (s > 0)
1281                         ast_cli(fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
1282                 else
1283                         ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
1284                 dp = dp->next;
1285         }
1286         ast_mutex_unlock(&dpcache_lock);
1287         return RESULT_SUCCESS;
1288 }
1289
1290 static char show_stats_usage[] =
1291 "Usage: iax show stats\n"
1292 "       Display statistics on IAX channel driver.\n";
1293
1294
1295 static char show_cache_usage[] =
1296 "Usage: iax show cache\n"
1297 "       Display currently cached IAX Dialplan results.\n";
1298
1299 static struct ast_cli_entry cli_set_jitter = 
1300 { { "iax", "set", "jitter", NULL }, iax_set_jitter, "Sets IAX jitter buffer", jitter_usage };
1301
1302 static struct ast_cli_entry cli_show_stats =
1303 { { "iax", "show", "stats", NULL }, iax_show_stats, "Display IAX statistics", show_stats_usage };
1304
1305 static struct ast_cli_entry cli_show_cache =
1306 { { "iax", "show", "cache", NULL }, iax_show_cache, "Display IAX cached dialplan", show_cache_usage };
1307
1308 static unsigned int calc_rxstamp(struct chan_iax_pvt *p);
1309
1310 #ifdef BRIDGE_OPTIMIZATION
1311 static unsigned int calc_fakestamp(struct chan_iax_pvt *from, struct chan_iax_pvt *to, unsigned int ts);
1312
1313 static int forward_delivery(struct ast_iax_frame *fr)
1314 {
1315         struct chan_iax_pvt *p1, *p2;
1316         p1 = iaxs[fr->callno];
1317         p2 = iaxs[p1->bridgecallno];
1318         if (!p1)
1319                 return -1;
1320         if (!p2)
1321                 return -1;
1322         /* Fix relative timestamp */
1323         fr->ts = calc_fakestamp(p1, p2, fr->ts);
1324         /* Now just send it send on the 2nd one 
1325            with adjusted timestamp */
1326         return iax_send(p2, fr->f, fr->ts, -1, 0, 0, 0);
1327 }
1328 #endif
1329
1330 static int schedule_delivery(struct ast_iax_frame *fr, int reallydeliver)
1331 {
1332         int ms,x;
1333         int drops[MEMORY_SIZE];
1334         int min, max=0, maxone=0,y,z, match;
1335         /* ms is a measure of the "lateness" of the packet relative to the first
1336            packet we received, which always has a lateness of 1.  Called by
1337            IAX thread, with iaxsl lock held. */
1338         ms = calc_rxstamp(iaxs[fr->callno]) - fr->ts;
1339
1340         if (ms > 32767) {
1341                 /* What likely happened here is that our counter has circled but we haven't
1342                    gotten the update from the main packet.  We'll just pretend that we did, and
1343                    update the timestamp appropriately. */
1344                 ms -= 65536;
1345         }
1346
1347         if (ms < -32768) {
1348                 /* We got this packet out of order.  Lets add 65536 to it to bring it into our new
1349                    time frame */
1350                 ms += 65536;
1351         }
1352         
1353         /* Rotate our history queue of "lateness".  Don't worry about those initial
1354            zeros because the first entry will always be zero */
1355         for (x=0;x<MEMORY_SIZE - 1;x++) 
1356                 iaxs[fr->callno]->history[x] = iaxs[fr->callno]->history[x+1];
1357         /* Add a history entry for this one */
1358         iaxs[fr->callno]->history[x] = ms;
1359
1360         /* Initialize the minimum to reasonable values.  It's too much
1361            work to do the same for the maximum, repeatedly */
1362         min=iaxs[fr->callno]->history[0];
1363         for (z=0;z < iax_dropcount + 1;z++) {
1364                 /* Start very optimistic ;-) */
1365                 max=-999999999;
1366                 for (x=0;x<MEMORY_SIZE;x++) {
1367                         if (max < iaxs[fr->callno]->history[x]) {
1368                                 /* We have a candidate new maximum value.  Make
1369                                    sure it's not in our drop list */
1370                                 match = 0;
1371                                 for (y=0;!match && (y<z);y++)
1372                                         match |= (drops[y] == x);
1373                                 if (!match) {
1374                                         /* It's not in our list, use it as the new maximum */
1375                                         max = iaxs[fr->callno]->history[x];
1376                                         maxone = x;
1377                                 }
1378                                 
1379                         }
1380                         if (!z) {
1381                                 /* On our first pass, find the minimum too */
1382                                 if (min > iaxs[fr->callno]->history[x])
1383                                         min = iaxs[fr->callno]->history[x];
1384                         }
1385                 }
1386 #if 1
1387                 drops[z] = maxone;
1388 #endif
1389         }
1390         /* Just for reference, keep the "jitter" value, the difference between the
1391            earliest and the latest. */
1392         iaxs[fr->callno]->jitter = max - min;   
1393         
1394         /* IIR filter for keeping track of historic jitter, but always increase
1395            historic jitter immediately for increase */
1396         
1397         if (iaxs[fr->callno]->jitter > iaxs[fr->callno]->historicjitter )
1398                 iaxs[fr->callno]->historicjitter = iaxs[fr->callno]->jitter;
1399         else
1400                 iaxs[fr->callno]->historicjitter = GAMMA * (double)iaxs[fr->callno]->jitter + (1-GAMMA) * 
1401                         iaxs[fr->callno]->historicjitter;
1402
1403         /* If our jitter buffer is too big (by a significant margin), then we slowly
1404            shrink it by about 1 ms each time to avoid letting the change be perceived */
1405         if (max < iaxs[fr->callno]->jitterbuffer - max_jitter_buffer)
1406                 iaxs[fr->callno]->jitterbuffer -= 2;
1407
1408
1409 #if 1
1410         /* Constrain our maximum jitter buffer appropriately */
1411         if (max > min + maxjitterbuffer) {
1412                 if (option_debug)
1413                         ast_log(LOG_DEBUG, "Constraining buffer from %d to %d + %d\n", max, min , maxjitterbuffer);
1414                 max = min + maxjitterbuffer;
1415         }
1416 #endif
1417
1418         /* If our jitter buffer is smaller than our maximum delay, grow the jitter
1419            buffer immediately to accomodate it (and a little more).  */
1420         if (max > iaxs[fr->callno]->jitterbuffer)
1421                 iaxs[fr->callno]->jitterbuffer = max 
1422                         /* + ((float)iaxs[fr->callno]->jitter) * 0.1 */;
1423                 
1424
1425         if (option_debug)
1426                 ast_log(LOG_DEBUG, "min = %d, max = %d, jb = %d, lateness = %d\n", min, max, iaxs[fr->callno]->jitterbuffer, ms);
1427         
1428         /* Subtract the lateness from our jitter buffer to know how long to wait
1429            before sending our packet.  */
1430         ms = iaxs[fr->callno]->jitterbuffer - ms;
1431         
1432         if (!use_jitterbuffer)
1433                 ms = 0;
1434
1435         /* If the caller just wanted us to update, return now */
1436         if (!reallydeliver)
1437                 return 0;
1438                 
1439         if (ms < 1) {
1440                 if (option_debug)
1441                         ast_log(LOG_DEBUG, "Calculated ms is %d\n", ms);
1442                 /* Don't deliver it more than 4 ms late */
1443                 if ((ms > -4) || (fr->f->frametype != AST_FRAME_VOICE)) {
1444                         __do_deliver(fr);
1445                 } else {
1446                         if (option_debug)
1447                                 ast_log(LOG_DEBUG, "Dropping voice packet since %d ms is, too old\n", ms);
1448                         /* Free the packet */
1449                         ast_frfree(fr->f);
1450                         /* And our iax frame */
1451                         ast_iax_frame_free(fr);
1452                 }
1453         } else {
1454                 if (option_debug)
1455                         ast_log(LOG_DEBUG, "Scheduling delivery in %d ms\n", ms);
1456                 fr->retrans = ast_sched_add(sched, ms, do_deliver, fr);
1457         }
1458         return 0;
1459 }
1460
1461 static int iax_transmit(struct ast_iax_frame *fr)
1462 {
1463         /* Lock the queue and place this packet at the end */
1464         fr->next = NULL;
1465         fr->prev = NULL;
1466         /* By setting this to 0, the network thread will send it for us, and
1467            queue retransmission if necessary */
1468         fr->sentyet = 0;
1469         ast_mutex_lock(&iaxq.lock);
1470         if (!iaxq.head) {
1471                 /* Empty queue */
1472                 iaxq.head = fr;
1473                 iaxq.tail = fr;
1474         } else {
1475                 /* Double link */
1476                 iaxq.tail->next = fr;
1477                 fr->prev = iaxq.tail;
1478                 iaxq.tail = fr;
1479         }
1480         iaxq.count++;
1481         ast_mutex_unlock(&iaxq.lock);
1482         /* Wake up the network thread */
1483         pthread_kill(netthreadid, SIGURG);
1484         return 0;
1485 }
1486
1487
1488
1489 static int iax_digit(struct ast_channel *c, char digit)
1490 {
1491         return send_command(c->pvt->pvt, AST_FRAME_DTMF, digit, 0, NULL, 0, -1);
1492 }
1493
1494 static int iax_sendtext(struct ast_channel *c, char *text)
1495 {
1496         
1497         return send_command(c->pvt->pvt, AST_FRAME_TEXT,
1498                 0, 0, text, strlen(text) + 1, -1);
1499 }
1500
1501 static int iax_sendimage(struct ast_channel *c, struct ast_frame *img)
1502 {
1503         return send_command(c->pvt->pvt, AST_FRAME_IMAGE, img->subclass, 0, img->data, img->datalen, -1);
1504 }
1505
1506 static int iax_sendhtml(struct ast_channel *c, int subclass, char *data, int datalen)
1507 {
1508         return send_command(c->pvt->pvt, AST_FRAME_HTML, subclass, 0, data, datalen, -1);
1509 }
1510
1511 static int iax_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
1512 {
1513         struct chan_iax_pvt *pvt = newchan->pvt->pvt;
1514         pvt->owner = newchan;
1515         return 0;
1516 }
1517
1518 #ifdef MYSQL_FRIENDS
1519
1520 static void mysql_update_peer(char *peer, struct sockaddr_in *sin)
1521 {
1522         if (mysql && (strlen(peer) < 128)) {
1523                 char query[512];
1524                 char *name;
1525                 time_t nowtime;
1526                 name = alloca(strlen(peer) * 2 + 1);
1527                 time(&nowtime);
1528                 mysql_real_escape_string(mysql, name, peer, strlen(peer));
1529                 snprintf(query, sizeof(query), "UPDATE iax1friends SET ipaddr=\"%s\", port=\"%d\", regseconds=\"%ld\" WHERE name=\"%s\"", 
1530                         inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), nowtime, name);
1531                 ast_mutex_lock(&mysqllock);
1532                 if (mysql_real_query(mysql, query, strlen(query))) 
1533                         ast_log(LOG_WARNING, "Unable to update database\n");
1534                         
1535                 ast_mutex_unlock(&mysqllock);
1536         }
1537 }
1538
1539 static struct iax_peer *mysql_peer(char *peer)
1540 {
1541         struct iax_peer *p;
1542         int success = 0;
1543         
1544         p = malloc(sizeof(struct iax_peer));
1545         memset(p, 0, sizeof(struct iax_peer));
1546         if (mysql && (strlen(peer) < 128)) {
1547                 char query[512];
1548                 char *name;
1549                 int numfields, x;
1550                 int port;
1551                 time_t regseconds, nowtime;
1552                 MYSQL_RES *result;
1553                 MYSQL_FIELD *fields;
1554                 MYSQL_ROW rowval;
1555                 name = alloca(strlen(peer) * 2 + 1);
1556                 mysql_real_escape_string(mysql, name, peer, strlen(peer));
1557                 snprintf(query, sizeof(query), "SELECT * FROM iax1friends WHERE name=\"%s\"", name);
1558                 ast_mutex_lock(&mysqllock);
1559                 mysql_query(mysql, query);
1560                 if ((result = mysql_store_result(mysql))) {
1561                         if ((rowval = mysql_fetch_row(result))) {
1562                                 numfields = mysql_num_fields(result);
1563                                 fields = mysql_fetch_fields(result);
1564                                 success = 1;
1565                                 for (x=0;x<numfields;x++) {
1566                                         if (rowval[x]) {
1567                                                 if (!strcasecmp(fields[x].name, "secret")) {
1568                                                         strncpy(p->secret, rowval[x], sizeof(p->secret));
1569                                                 } else if (!strcasecmp(fields[x].name, "context")) {
1570                                                         strncpy(p->context, rowval[x], sizeof(p->context) - 1);
1571                                                 } else if (!strcasecmp(fields[x].name, "ipaddr")) {
1572                                                         inet_aton(rowval[x], &p->addr.sin_addr);
1573                                                 } else if (!strcasecmp(fields[x].name, "port")) {
1574                                                         if (sscanf(rowval[x], "%i", &port) != 1)
1575                                                                 port = 0;
1576                                                         p->addr.sin_port = htons(port);
1577                                                 } else if (!strcasecmp(fields[x].name, "regseconds")) {
1578                                                         if (sscanf(rowval[x], "%li", &regseconds) != 1)
1579                                                                 regseconds = 0;
1580                                                 }
1581                                         }
1582                                 }
1583                                 time(&nowtime);
1584                                 if ((nowtime - regseconds) > AST_DEFAULT_REG_EXPIRE) 
1585                                         memset(&p->addr, 0, sizeof(p->addr));
1586                         }
1587                 }
1588                 ast_mutex_unlock(&mysqllock);
1589         }
1590         if (!success) {
1591                 free(p);
1592                 p = NULL;
1593         } else {
1594                 strncpy(p->name, peer, sizeof(p->name) - 1);
1595                 p->dynamic = 1;
1596                 p->delme = 1;
1597                 p->capability = iax_capability;
1598                 strcpy(p->methods, "md5,plaintext");
1599         }
1600         return p;
1601 }
1602
1603 static struct iax_user *mysql_user(char *user)
1604 {
1605         struct iax_user *p;
1606         struct iax_context *con;
1607         int success = 0;
1608         
1609         p = malloc(sizeof(struct iax_user));
1610         memset(p, 0, sizeof(struct iax_user));
1611         con = malloc(sizeof(struct iax_context));
1612         memset(con, 0, sizeof(struct iax_context));
1613         strcpy(con->context, "default");
1614         p->contexts = con;
1615         if (mysql && (strlen(user) < 128)) {
1616                 char query[512];
1617                 char *name;
1618                 int numfields, x;
1619                 MYSQL_RES *result;
1620                 MYSQL_FIELD *fields;
1621                 MYSQL_ROW rowval;
1622                 name = alloca(strlen(user) * 2 + 1);
1623                 mysql_real_escape_string(mysql, name, user, strlen(user));
1624                 snprintf(query, sizeof(query), "SELECT * FROM iax1friends WHERE name=\"%s\"", name);
1625                 ast_mutex_lock(&mysqllock);
1626                 mysql_query(mysql, query);
1627                 if ((result = mysql_store_result(mysql))) {
1628                         if ((rowval = mysql_fetch_row(result))) {
1629                                 numfields = mysql_num_fields(result);
1630                                 fields = mysql_fetch_fields(result);
1631                                 success = 1;
1632                                 for (x=0;x<numfields;x++) {
1633                                         if (rowval[x]) {
1634                                                 if (!strcasecmp(fields[x].name, "secret")) {
1635                                                         strncpy(p->secret, rowval[x], sizeof(p->secret));
1636                                                 } else if (!strcasecmp(fields[x].name, "context")) {
1637                                                         strncpy(p->contexts->context, rowval[x], sizeof(p->contexts->context) - 1);
1638                                                 }
1639                                         }
1640                                 }
1641                         }
1642                 }
1643                 ast_mutex_unlock(&mysqllock);
1644         }
1645         if (!success) {
1646                 if (p->contexts)
1647                         free(p->contexts);
1648                 free(p);
1649                 p = NULL;
1650         } else {
1651                 strncpy(p->name, user, sizeof(p->name) - 1);
1652                 p->delme = 1;
1653                 strcpy(p->methods, "md5,plaintext");
1654         }
1655         return p;
1656 }
1657 #endif /* MYSQL_FRIENDS */
1658
1659 static int create_addr(struct sockaddr_in *sin, int *capability, int *sendani, int *maxtime, char *peer, char *context)
1660 {
1661         struct hostent *hp;
1662         struct iax_peer *p;
1663         int found=0;
1664         if (sendani)
1665                 *sendani = 0;
1666         if (maxtime)
1667                 *maxtime = 0;
1668         sin->sin_family = AF_INET;
1669         ast_mutex_lock(&peerl.lock);
1670         p = peerl.peers;
1671         while(p) {
1672                 if (!strcasecmp(p->name, peer)) {
1673                         break;
1674                 }
1675                 p = p->next;
1676         }
1677 #ifdef MYSQL_FRIENDS
1678         if (!p)
1679                 p = mysql_peer(peer);
1680 #endif          
1681         if (p) {
1682                 found++;
1683                 if (capability)
1684                         *capability = p->capability;
1685                 if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
1686                         (!p->maxms || ((p->lastms > 0)  && (p->lastms <= p->maxms)))) {
1687                         if (sendani)
1688                                 *sendani = p->sendani;          /* Whether we transmit ANI */
1689                         if (maxtime)
1690                                 *maxtime = p->maxms;            /* Max time they should take */
1691                         if (context)
1692                                 strncpy(context, p->context, AST_MAX_EXTENSION - 1);
1693                         if (p->addr.sin_addr.s_addr) {
1694                                 sin->sin_addr = p->addr.sin_addr;
1695                                 sin->sin_port = p->addr.sin_port;
1696                         } else {
1697                                 sin->sin_addr = p->defaddr.sin_addr;
1698                                 sin->sin_port = p->defaddr.sin_port;
1699                         }
1700                 } else {
1701                         if (p->delme) 
1702                                 free(p);
1703                         p = NULL;
1704                 }
1705         }
1706         ast_mutex_unlock(&peerl.lock);
1707         if (!p && !found) {
1708                 hp = gethostbyname(peer);
1709                 if (hp) {
1710                         memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
1711                         sin->sin_port = htons(AST_DEFAULT_IAX_PORTNO);
1712                         return 0;
1713                 } else {
1714                         ast_log(LOG_WARNING, "No such host: %s\n", peer);
1715                         return -1;
1716                 }
1717         } else if (!p)
1718                 return -1;
1719         if (p->delme)
1720                 free(p);
1721         return 0;
1722 }
1723
1724 static int auto_congest(void *nothing)
1725 {
1726         int callno = (int)(long)(nothing);
1727         struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_CONGESTION };
1728         ast_mutex_lock(&iaxsl[callno]);
1729         if (iaxs[callno]) {
1730                 iaxs[callno]->initid = -1;
1731                 iax_queue_frame(callno, &f);
1732                 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
1733         }
1734         ast_mutex_unlock(&iaxsl[callno]);
1735         return 0;
1736 }
1737
1738 static int iax_call(struct ast_channel *c, char *dest, int timeout)
1739 {
1740         struct sockaddr_in sin;
1741         char host[256];
1742         char *rdest;
1743         char *rcontext;
1744         char *username;
1745         char *secret = NULL;
1746         char *hname;
1747         char requeststr[256] = "";
1748         char myrdest [5] = "s";
1749         char context[AST_MAX_EXTENSION] ="";
1750         char *portno = NULL;
1751         struct chan_iax_pvt *p = c->pvt->pvt;
1752         char *stringp=NULL;
1753         if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
1754                 ast_log(LOG_WARNING, "Line is already in use (%s)?\n", c->name);
1755                 return -1;
1756         }
1757         strncpy(host, dest, sizeof(host)-1);
1758         stringp=host;
1759         strsep(&stringp, "/");
1760         /* If no destination extension specified, use 's' */
1761         rdest = strsep(&stringp, "/");
1762         if (!rdest) 
1763                 rdest = myrdest;
1764         stringp=rdest;
1765         strsep(&stringp, "@");
1766         rcontext = strsep(&stringp, "@");
1767         stringp=host;
1768         strsep(&stringp, "@");
1769         username = strsep(&stringp, "@");
1770         if (username) {
1771                 /* Really the second argument is the host, not the username */
1772                 hname = username;
1773                 username = host;
1774         } else {
1775                 hname = host;
1776         }
1777         if (username) {
1778                 stringp=username;
1779                 username = strsep(&stringp, ":");
1780                 secret = strsep(&stringp, ":");
1781         }
1782         stringp=hname;
1783         if (strsep(&stringp, ":")) {
1784                 stringp=hname;
1785                 strsep(&stringp, ":");
1786                 portno = strsep(&stringp, ":");
1787         }
1788         if (create_addr(&sin, NULL, NULL, NULL, hname, context)) {
1789                 ast_log(LOG_WARNING, "No address associated with '%s'\n", hname);
1790                 return -1;
1791         }
1792         /* Keep track of the context for outgoing calls too */
1793         strncpy(c->context, context, sizeof(c->context) - 1);
1794         if (portno) {
1795                 sin.sin_port = htons(atoi(portno));
1796         }
1797         /* Now we build our request string */
1798 #define MYSNPRINTF snprintf(requeststr + strlen(requeststr), sizeof(requeststr) - strlen(requeststr), 
1799 #define MYSNPRINTF2 snprintf(requeststr + strlen(requeststr), reqsize - strlen(requeststr), 
1800         MYSNPRINTF "exten=%s;", rdest);
1801         if (c->callerid)
1802                 MYSNPRINTF "callerid=%s;", c->callerid);
1803         if (p->sendani && c->ani)
1804                 MYSNPRINTF "ani=%s;", c->ani);
1805         if (c->language && strlen(c->language))
1806                 MYSNPRINTF "language=%s;", c->language);
1807         if (c->dnid)
1808                 MYSNPRINTF "dnid=%s;", c->dnid);
1809         if (rcontext)
1810                 MYSNPRINTF "context=%s;", rcontext);
1811         if (username)
1812                 MYSNPRINTF "username=%s;", username);
1813         if (secret) {
1814                 if (secret[0] == '[') {
1815                         /* This is an RSA key, not a normal secret */
1816                         strncpy(p->outkey, secret + 1, sizeof(p->secret)-1);
1817                         if (strlen(p->outkey)) {
1818                                 p->outkey[strlen(p->outkey) - 1] = '\0';
1819                         }
1820                 } else
1821                         strncpy(p->secret, secret, sizeof(p->secret)-1);
1822         }
1823         MYSNPRINTF "formats=%d;", c->nativeformats);
1824         MYSNPRINTF "capability=%d;", p->capability);
1825         MYSNPRINTF "version=%d;", AST_IAX_PROTO_VERSION);
1826         MYSNPRINTF "adsicpe=%d;", c->adsicpe);
1827         /* Trim the trailing ";" */
1828         if (strlen(requeststr))
1829                 requeststr[strlen(requeststr) - 1] = '\0';
1830         /* Transmit the string in a "NEW" request */
1831         if (option_verbose > 2)
1832                 ast_verbose(VERBOSE_PREFIX_3 "Calling using options '%s'\n", requeststr);
1833         if (p->maxtime) {
1834                 /* Initialize pingtime and auto-congest time */
1835                 p->pingtime = p->maxtime / 2;
1836                 p->initid = ast_sched_add(sched, p->maxtime * 2, auto_congest, (void *)p->callno);
1837         }
1838         send_command(p, AST_FRAME_IAX,
1839                 AST_IAX_COMMAND_NEW, 0, requeststr, strlen(requeststr) + 1, -1);
1840         ast_setstate(c, AST_STATE_RINGING);
1841         return 0;
1842 }
1843
1844 static int iax_hangup(struct ast_channel *c) 
1845 {
1846         struct chan_iax_pvt *pvt = c->pvt->pvt;
1847         int alreadygone;
1848         int callno;
1849         if (pvt) {
1850                 callno = pvt->callno;
1851                 ast_mutex_lock(&iaxsl[callno]);
1852                 ast_log(LOG_DEBUG, "We're hanging up %s now...\n", c->name);
1853                 alreadygone = pvt->alreadygone;
1854                 /* Send the hangup unless we have had a transmission error or are already gone */
1855                 if (!pvt->error && !alreadygone) 
1856                         send_command_final(pvt, AST_FRAME_IAX, AST_IAX_COMMAND_HANGUP, 0, NULL, 0, -1);
1857                 /* Explicitly predestroy it */
1858                 iax_predestroy_nolock(callno);
1859                 /* If we were already gone to begin with, destroy us now */
1860                 if (alreadygone) {
1861                         ast_log(LOG_DEBUG, "Really destroying %s now...\n", c->name);
1862                         iax_destroy_nolock(callno);
1863                 }
1864                 ast_mutex_unlock(&iaxsl[callno]);
1865         }
1866         if (option_verbose > 2) 
1867                 ast_verbose(VERBOSE_PREFIX_3 "Hungup '%s'\n", c->name);
1868         return 0;
1869 }
1870
1871 static int iax_setoption(struct ast_channel *c, int option, void *data, int datalen)
1872 {
1873         struct ast_option_header *h;
1874         int res;
1875         h = malloc(datalen + sizeof(struct ast_option_header));
1876         if (h) {
1877                 h->flag = AST_OPTION_FLAG_REQUEST;
1878                 h->option = htons(option);
1879                 memcpy(h->data, data, datalen);
1880                 res = send_command((struct chan_iax_pvt *)c->pvt->pvt, AST_FRAME_CONTROL,
1881                         AST_CONTROL_OPTION, 0, (char *)h, datalen + sizeof(struct ast_option_header), -1);
1882                 free(h);
1883                 return res;
1884         } else 
1885                 ast_log(LOG_WARNING, "Out of memory\n");
1886         return -1;
1887 }
1888 static struct ast_frame *iax_read(struct ast_channel *c) 
1889 {
1890         static struct ast_frame f = { AST_FRAME_NULL, };
1891         ast_log(LOG_NOTICE, "I should never be called!\n");
1892         return &f;
1893 }
1894
1895 static int iax_start_transfer(struct ast_channel *c0, struct ast_channel *c1)
1896 {
1897         int res;
1898         char req0[256];
1899         char req1[256];
1900         struct chan_iax_pvt *p0 = c0->pvt->pvt;
1901         struct chan_iax_pvt *p1 = c1->pvt->pvt;
1902         snprintf(req0, sizeof(req0), "remip=%s;remport=%d;remcall=%d;", inet_ntoa(p1->addr.sin_addr), ntohs(p1->addr.sin_port), p1->peercallno);
1903         snprintf(req1, sizeof(req1), "remip=%s;remport=%d;remcall=%d;", inet_ntoa(p0->addr.sin_addr), ntohs(p0->addr.sin_port), p0->peercallno);
1904         res = send_command(p0, AST_FRAME_IAX, AST_IAX_COMMAND_TXREQ, 0, req0, strlen(req0) + 1, -1);
1905         if (res)
1906                 return -1;
1907         res = send_command(p1, AST_FRAME_IAX, AST_IAX_COMMAND_TXREQ, 0, req1, strlen(req1) + 1, -1);
1908         if (res)
1909                 return -1;
1910         p0->transferring = TRANSFER_BEGIN;
1911         p1->transferring = TRANSFER_BEGIN;
1912         return 0;
1913 }
1914
1915 static int iax_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
1916 {
1917         struct ast_channel *cs[3];
1918         struct ast_channel *who;
1919         int to = -1;
1920         int res;
1921         int transferstarted=0;
1922         struct ast_frame *f;
1923         struct chan_iax_pvt *p0 = c0->pvt->pvt;
1924         struct chan_iax_pvt *p1 = c1->pvt->pvt;
1925
1926         /* Put them in native bridge mode */
1927         p0->bridgecallno = p1->callno;
1928         p1->bridgecallno = p0->callno;
1929
1930         /* If not, try to bridge until we can execute a transfer, if we can */
1931         cs[0] = c0;
1932         cs[1] = c1;
1933         for (/* ever */;;) {
1934                 /* Check in case we got masqueraded into */
1935                 if ((c0->type != type) || (c1->type != type)) {
1936                         if (option_verbose > 2)
1937                                 ast_verbose(VERBOSE_PREFIX_3 "Can't masquerade, we're different...\n");
1938                         return -2;
1939                 }
1940                 if (c0->nativeformats != c1->nativeformats) {
1941                         ast_verbose(VERBOSE_PREFIX_3 "Operating with different codecs, can't native bridge...\n");
1942                         return -2;
1943                 }
1944                 if (!transferstarted) {
1945                         /* Try the transfer */
1946                         if (iax_start_transfer(c0, c1))
1947                                 ast_log(LOG_WARNING, "Unable to start the transfer\n");
1948                         transferstarted = 1;
1949                 }
1950                 
1951                 if ((p0->transferring == TRANSFER_RELEASED) && (p1->transferring == TRANSFER_RELEASED)) {
1952                         /* Call has been transferred.  We're no longer involved */
1953                         sleep(1);
1954                         c0->_softhangup |= AST_SOFTHANGUP_DEV;
1955                         c1->_softhangup |= AST_SOFTHANGUP_DEV;
1956                         *fo = NULL;
1957                         *rc = c0;
1958                         res = 0;
1959                         break;
1960                 }
1961                 to = 1000;
1962                 who = ast_waitfor_n(cs, 2, &to);
1963                 if (!who) {
1964                         continue;
1965                 }
1966                 f = ast_read(who);
1967                 if (!f) {
1968                         *fo = NULL;
1969                         *rc = who;
1970                         res = 0;
1971                         break;
1972                 }
1973                 if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
1974                         *fo = f;
1975                         *rc = who;
1976                         res =  0;
1977                         break;
1978                 }
1979                 if ((f->frametype == AST_FRAME_VOICE) ||
1980                         (f->frametype == AST_FRAME_TEXT) ||
1981                         (f->frametype == AST_FRAME_VIDEO) || 
1982                         (f->frametype == AST_FRAME_IMAGE) ||
1983                         (f->frametype == AST_FRAME_DTMF)) {
1984                         if ((f->frametype == AST_FRAME_DTMF) && 
1985                                 (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
1986                                 if ((who == c0)) {
1987                                         if  ((flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
1988                                                 *rc = c0;
1989                                                 *fo = f;
1990                                                 /* Take out of conference mode */
1991                                                 res = 0;
1992                                                 break;
1993                                         } else 
1994                                                 goto tackygoto;
1995                                 } else
1996                                 if ((who == c1)) {
1997                                         if (flags & AST_BRIDGE_DTMF_CHANNEL_1) {
1998                                                 *rc = c1;
1999                                                 *fo = f;
2000                                                 res =  0;
2001                                                 break;
2002                                         } else
2003                                                 goto tackygoto;
2004                                 }
2005                         } else {
2006 #if 0
2007                                 ast_log(LOG_DEBUG, "Read from %s\n", who->name);
2008                                 if (who == last) 
2009                                         ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
2010                                 last = who;
2011 #endif
2012 tackygoto:
2013                                 if (who == c0) 
2014                                         ast_write(c1, f);
2015                                 else 
2016                                         ast_write(c0, f);
2017                         }
2018                         ast_frfree(f);
2019                 } else
2020                         ast_frfree(f);
2021                 /* Swap who gets priority */
2022                 cs[2] = cs[0];
2023                 cs[0] = cs[1];
2024                 cs[1] = cs[2];
2025         }
2026         p0->bridgecallno = -1;
2027         p1->bridgecallno = -1;
2028         return res;
2029 }
2030
2031 static int iax_answer(struct ast_channel *c)
2032 {
2033         struct chan_iax_pvt *pvt = c->pvt->pvt;
2034         if (option_debug)
2035                 ast_log(LOG_DEBUG, "Answering\n");
2036         return send_command(pvt, AST_FRAME_CONTROL, AST_CONTROL_ANSWER, 0, NULL, 0, -1);
2037 }
2038
2039 static int iax_indicate(struct ast_channel *c, int condition)
2040 {
2041         struct chan_iax_pvt *pvt = c->pvt->pvt;
2042         if (option_debug)
2043                 ast_log(LOG_DEBUG, "Indicating condition %d\n", condition);
2044         return send_command(pvt, AST_FRAME_CONTROL, condition, 0, NULL, 0, -1);
2045 }
2046         
2047
2048 static int iax_write(struct ast_channel *c, struct ast_frame *f);
2049
2050 static int iax_getpeername(struct sockaddr_in sin, char *host, int len)
2051 {
2052         struct iax_peer *peer;
2053         int res = 0;
2054         ast_mutex_lock(&peerl.lock);
2055         peer = peerl.peers;
2056         while(peer) {
2057                 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
2058                                 (peer->addr.sin_port == sin.sin_port)) {
2059                                         strncpy(host, peer->name, len-1);
2060                                         res = 1;
2061                                         break;
2062                 }
2063                 peer = peer->next;
2064         }
2065         ast_mutex_unlock(&peerl.lock);
2066         return res;
2067 }
2068
2069 static struct ast_channel *ast_iax_new(struct chan_iax_pvt *i, int state, int capability)
2070 {
2071         char host[256];
2072         struct ast_channel *tmp;
2073         tmp = ast_channel_alloc(1);
2074         if (tmp) {
2075                 if (!iax_getpeername(i->addr, host, sizeof(host)))
2076                         snprintf(host, sizeof(host), "%s:%d", inet_ntoa(i->addr.sin_addr), ntohs(i->addr.sin_port));
2077                 if (strlen(i->username))
2078                         snprintf(tmp->name, sizeof(tmp->name), "IAX[%s@%s]/%d", i->username, host, i->callno);
2079                 else
2080                         snprintf(tmp->name, sizeof(tmp->name), "IAX[%s]/%d", host, i->callno);
2081                 tmp->type = type;
2082                 /* We can support any format by default, until we get restricted */
2083                 tmp->nativeformats = capability;
2084                 tmp->readformat = 0;
2085                 tmp->writeformat = 0;
2086                 tmp->pvt->pvt = i;
2087                 tmp->pvt->send_digit = iax_digit;
2088                 tmp->pvt->send_text = iax_sendtext;
2089                 tmp->pvt->send_image = iax_sendimage;
2090                 tmp->pvt->send_html = iax_sendhtml;
2091                 tmp->pvt->call = iax_call;
2092                 tmp->pvt->hangup = iax_hangup;
2093                 tmp->pvt->answer = iax_answer;
2094                 tmp->pvt->read = iax_read;
2095                 tmp->pvt->write = iax_write;
2096                 tmp->pvt->indicate = iax_indicate;
2097                 tmp->pvt->setoption = iax_setoption;
2098                 tmp->pvt->bridge = iax_bridge;
2099                 if (strlen(i->callerid))
2100                         tmp->callerid = strdup(i->callerid);
2101                 if (strlen(i->ani))
2102                         tmp->ani = strdup(i->ani);
2103                 if (strlen(i->language))
2104                         strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
2105                 if (strlen(i->dnid))
2106                         tmp->dnid = strdup(i->dnid);
2107                 if (strlen(i->accountcode))
2108                         strncpy(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode)-1);
2109                 if (i->amaflags)
2110                         tmp->amaflags = i->amaflags;
2111                 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
2112                 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
2113                 tmp->adsicpe = i->peeradsicpe;
2114                 tmp->pvt->fixup = iax_fixup;
2115                 i->owner = tmp;
2116                 i->capability = capability;
2117                 ast_setstate(tmp, state);
2118                 ast_mutex_lock(&usecnt_lock);
2119                 usecnt++;
2120                 ast_mutex_unlock(&usecnt_lock);
2121                 ast_update_use_count();
2122                 if (state != AST_STATE_DOWN) {
2123                         if (ast_pbx_start(tmp)) {
2124                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
2125                                 ast_hangup(tmp);
2126                                 tmp = NULL;
2127                         }
2128                 }
2129         }
2130         return tmp;
2131 }
2132
2133 static unsigned int calc_timestamp(struct chan_iax_pvt *p, unsigned int ts)
2134 {
2135         struct timeval tv;
2136         unsigned int ms;
2137         if (!p->offset.tv_sec && !p->offset.tv_usec)
2138                 gettimeofday(&p->offset, NULL);
2139         /* If the timestamp is specified, just send it as is */
2140         if (ts)
2141                 return ts;
2142         gettimeofday(&tv, NULL);
2143         ms = (tv.tv_sec - p->offset.tv_sec) * 1000 + (tv.tv_usec - p->offset.tv_usec) / 1000;
2144         /* We never send the same timestamp twice, so fudge a little if we must */
2145         if (ms <= p->lastsent)
2146                 ms = p->lastsent + 1;
2147         p->lastsent = ms;
2148         return ms;
2149 }
2150
2151 #ifdef BRIDGE_OPTIMIZATION
2152 static unsigned int calc_fakestamp(struct chan_iax_pvt *p1, struct chan_iax_pvt *p2, unsigned int fakets)
2153 {
2154         int ms;
2155         /* Receive from p1, send to p2 */
2156         
2157         /* Setup rxcore if necessary on outgoing channel */
2158         if (!p1->rxcore.tv_sec && !p1->rxcore.tv_usec)
2159                 gettimeofday(&p1->rxcore, NULL);
2160
2161         /* Setup txcore if necessary on outgoing channel */
2162         if (!p2->offset.tv_sec && !p2->offset.tv_usec)
2163                 gettimeofday(&p2->offset, NULL);
2164         
2165         /* Now, ts is the timestamp of the original packet in the orignal context.
2166            Adding rxcore to it gives us when we would want the packet to be delivered normally.
2167            Subtracting txcore of the outgoing channel gives us what we'd expect */
2168         
2169         ms = (p1->rxcore.tv_sec - p2->offset.tv_sec) * 1000 + (p1->rxcore.tv_usec - p1->offset.tv_usec) / 1000;
2170         fakets += ms;
2171         if (fakets <= p2->lastsent)
2172                 fakets = p2->lastsent + 1;
2173         p2->lastsent = fakets;
2174         return fakets;
2175 }
2176 #endif
2177
2178 static unsigned int calc_rxstamp(struct chan_iax_pvt *p)
2179 {
2180         /* Returns where in "receive time" we are */
2181         struct timeval tv;
2182         unsigned int ms;
2183         /* Setup rxcore if necessary */
2184         if (!p->rxcore.tv_sec && !p->rxcore.tv_usec)
2185                 gettimeofday(&p->rxcore, NULL);
2186
2187         gettimeofday(&tv, NULL);
2188         ms = (tv.tv_sec - p->rxcore.tv_sec) * 1000 + (tv.tv_usec - p->rxcore.tv_usec) / 1000;
2189         return ms;
2190 }
2191
2192 static int iax_send(struct chan_iax_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final)
2193 {
2194         /* Queue a packet for delivery on a given private structure.  Use "ts" for
2195            timestamp, or calculate if ts is 0.  Send immediately without retransmission
2196            or delayed, with retransmission */
2197         struct ast_iax_full_hdr *fh;
2198         struct ast_iax_mini_hdr *mh;
2199         struct ast_iax_frame *fr, fr2;
2200         int res;
2201         unsigned int lastsent;
2202         /* Allocate an ast_iax_frame */
2203         if (now)
2204                 fr = &fr2;
2205         else
2206                 fr = ast_iax_frame_new(DIRECTION_OUTGRESS);
2207         if (!fr) {
2208                 ast_log(LOG_WARNING, "Out of memory\n");
2209                 return -1;
2210         }
2211         if (!pvt) {
2212                 ast_log(LOG_WARNING, "No private structure for packet (%d)?\n", fr->callno);
2213                 if (!now)
2214                         ast_iax_frame_free(fr);
2215                 return -1;
2216         }
2217         /* Isolate our frame for transmission */
2218         fr->f = ast_frdup(f);
2219
2220         if (!fr->f) {
2221                 ast_log(LOG_WARNING, "Out of memory\n");
2222                 if (!now)
2223                         ast_iax_frame_free(fr);
2224                 return -1;
2225         }
2226         if (fr->f->offset < sizeof(struct ast_iax_full_hdr)) {
2227                 ast_log(LOG_WARNING, "Packet from '%s' not friendly\n", fr->f->src);
2228                 free(fr);
2229                 return -1;
2230         }
2231         lastsent = pvt->lastsent;
2232         fr->ts = calc_timestamp(pvt, ts);
2233         if (!fr->ts) {
2234                 ast_log(LOG_WARNING, "timestamp is 0?\n");
2235                 if (!now)
2236                         ast_iax_frame_free(fr);
2237                 return -1;
2238         }
2239         fr->callno = pvt->callno;
2240         fr->transfer = transfer;
2241         fr->final = final;
2242         if (((fr->ts & 0xFFFF0000L) != (lastsent & 0xFFFF0000L))
2243                 /* High two bits of timestamp differ */ ||
2244             (fr->f->frametype != AST_FRAME_VOICE) 
2245                 /* or not a voice frame */ || 
2246                 (fr->f->subclass != pvt->svoiceformat) 
2247                 /* or new voice format */ ) {
2248                 /* We need a full frame */
2249                 if (seqno > -1)
2250                         fr->seqno = seqno;
2251                 else
2252                         fr->seqno = pvt->oseqno++;
2253                 fh = (struct ast_iax_full_hdr *)(fr->f->data - sizeof(struct ast_iax_full_hdr));
2254                 fh->callno = htons(fr->callno | AST_FLAG_FULL);
2255                 fh->ts = htonl(fr->ts);
2256                 fh->seqno = htons(fr->seqno);
2257                 fh->type = fr->f->frametype & 0xFF;
2258                 fh->csub = compress_subclass(fr->f->subclass);
2259                 if (transfer) {
2260                         fh->dcallno = htons(pvt->transfercallno);
2261                 } else
2262                         fh->dcallno = htons(pvt->peercallno);
2263                 fr->datalen = fr->f->datalen + sizeof(struct ast_iax_full_hdr);
2264                 fr->data = fh;
2265                 fr->retries = 0;
2266                 /* Retry after 2x the ping time has passed */
2267                 fr->retrytime = pvt->pingtime * 2;
2268                 if (fr->retrytime < MIN_RETRY_TIME)
2269                         fr->retrytime = MIN_RETRY_TIME;
2270                 if (fr->retrytime > MAX_RETRY_TIME)
2271                         fr->retrytime = MAX_RETRY_TIME;
2272                 /* Acks' don't get retried */
2273                 if ((f->frametype == AST_FRAME_IAX) && (f->subclass == AST_IAX_COMMAND_ACK))
2274                         fr->retries = -1;
2275                 if (f->frametype == AST_FRAME_VOICE) {
2276                         pvt->svoiceformat = f->subclass;
2277                 }
2278                 if (now) {
2279                         res = send_packet(fr);
2280                         ast_frfree(fr->f);
2281                 } else
2282                         res = iax_transmit(fr);
2283         } else {
2284                 /* Mini-frames have no sequence number */
2285                 fr->seqno = -1;
2286                 /* Mini frame will do */
2287                 mh = (struct ast_iax_mini_hdr *)(fr->f->data - sizeof(struct ast_iax_mini_hdr));
2288                 mh->callno = htons(fr->callno);
2289                 mh->ts = htons(fr->ts & 0xFFFF);
2290                 fr->datalen = fr->f->datalen + sizeof(struct ast_iax_mini_hdr);
2291                 fr->data = mh;
2292                 fr->retries = -1;
2293                 if (now) {
2294                         res = send_packet(fr);
2295                         ast_frfree(fr->f);
2296                 } else
2297                         res = iax_transmit(fr);
2298         }
2299         return res;
2300 }
2301
2302
2303
2304 static int iax_show_users(int fd, int argc, char *argv[])
2305 {
2306 #define FORMAT "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-5.5s\n"
2307         struct iax_user *user;
2308         if (argc != 3) 
2309                 return RESULT_SHOWUSAGE;
2310         ast_mutex_lock(&userl.lock);
2311         ast_cli(fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C");
2312         for(user=userl.users;user;user=user->next) {
2313                 ast_cli(fd, FORMAT, user->name, user->secret, user->methods, 
2314                                 user->contexts ? user->contexts->context : context,
2315                                 user->ha ? "Yes" : "No");
2316         }
2317         ast_mutex_unlock(&userl.lock);
2318         return RESULT_SUCCESS;
2319 #undef FORMAT
2320 }
2321
2322 static int iax_show_peers(int fd, int argc, char *argv[])
2323 {
2324 #define FORMAT2 "%-15.15s  %-15.15s %s  %-15.15s  %-8s  %-10s\n"
2325 #define FORMAT "%-15.15s  %-15.15s %s  %-15.15s  %-8d  %-10s\n"
2326         struct iax_peer *peer;
2327         char name[256] = "";
2328         if (argc != 3)
2329                 return RESULT_SHOWUSAGE;
2330         ast_mutex_lock(&peerl.lock);
2331         ast_cli(fd, FORMAT2, "Name/Username", "Host", "   ", "Mask", "Port", "Status");
2332         for (peer = peerl.peers;peer;peer = peer->next) {
2333                 char nm[20];
2334                 char status[20];
2335                 if (strlen(peer->username))
2336                         snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
2337                 else
2338                         strncpy(name, peer->name, sizeof(name) - 1);
2339                 if (peer->maxms) {
2340                         if (peer->lastms < 0)
2341                                 strcpy(status, "UNREACHABLE");
2342                         else if (peer->lastms > peer->maxms) 
2343                                 snprintf(status, sizeof(status), "LAGGED (%d ms)", peer->lastms);
2344                         else if (peer->lastms) 
2345                                 snprintf(status, sizeof(status), "OK (%d ms)", peer->lastms);
2346                         else 
2347                                 strcpy(status, "UNKNOWN");
2348                 } else 
2349                         strcpy(status, "Unmonitored");
2350                 strncpy(nm, inet_ntoa(peer->mask), sizeof(nm)-1);
2351                 ast_cli(fd, FORMAT, name, 
2352                                         peer->addr.sin_addr.s_addr ? inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
2353                                         peer->dynamic ? "(D)" : "(S)",
2354                                         nm,
2355                                         ntohs(peer->addr.sin_port), status);
2356         }
2357         ast_mutex_unlock(&peerl.lock);
2358         return RESULT_SUCCESS;
2359 #undef FORMAT
2360 #undef FORMAT2
2361 }
2362
2363 /* JDG: callback to display iax peers in manager */
2364 static int manager_iax_show_peers( struct mansession *s, struct message *m )
2365 {
2366         char *a[] = { "iax", "show", "users" };
2367         int ret;
2368         ret = iax_show_peers( s->fd, 3, a );
2369         ast_cli( s->fd, "\r\n" );
2370         return ret;
2371 } /* /JDG */
2372
2373 static char *regstate2str(int regstate)
2374 {
2375         switch(regstate) {
2376         case REG_STATE_UNREGISTERED:
2377                 return "Unregistered";
2378         case REG_STATE_REGSENT:
2379                 return "Request Sent";
2380         case REG_STATE_AUTHSENT:
2381                 return "Auth. Sent";
2382         case REG_STATE_REGISTERED:
2383                 return "Registered";
2384         case REG_STATE_REJECTED:
2385                 return "Rejected";
2386         case REG_STATE_TIMEOUT:
2387                 return "Timeout";
2388         case REG_STATE_NOAUTH:
2389                 return "No Authentication";
2390         default:
2391                 return "Unknown";
2392         }
2393 }
2394
2395 static int iax_show_registry(int fd, int argc, char *argv[])
2396 {
2397 #define FORMAT2 "%-20.20s  %-10.10s  %-20.20s %8.8s  %s\n"
2398 #define FORMAT "%-20.20s  %-10.10s  %-20.20s %8d  %s\n"
2399         struct iax_registry *reg;
2400         char host[80];
2401         char perceived[80];
2402         if (argc != 3)
2403                 return RESULT_SHOWUSAGE;
2404         ast_mutex_lock(&peerl.lock);
2405         ast_cli(fd, FORMAT2, "Host", "Username", "Perceived", "Refresh", "State");
2406         for (reg = registrations;reg;reg = reg->next) {
2407                 snprintf(host, sizeof(host), "%s:%d", inet_ntoa(reg->addr.sin_addr), ntohs(reg->addr.sin_port));
2408                 if (reg->us.sin_addr.s_addr) 
2409                         snprintf(perceived, sizeof(perceived), "%s:%d", inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
2410                 else
2411                         strcpy(perceived, "<Unregistered>");
2412                 ast_cli(fd, FORMAT, host, 
2413                                         reg->username, perceived, reg->refresh, regstate2str(reg->regstate));
2414         }
2415         ast_mutex_unlock(&peerl.lock);
2416         return RESULT_SUCCESS;
2417 #undef FORMAT
2418 #undef FORMAT2
2419 }
2420
2421 static int iax_show_channels(int fd, int argc, char *argv[])
2422 {
2423 #define FORMAT2 "%-15.15s  %-10.10s  %-11.11s  %-11.11s  %-7.7s  %-6.6s  %s\n"
2424 #define FORMAT  "%-15.15s  %-10.10s  %5.5d/%5.5d  %5.5d/%5.5d  %-5.5dms  %-4.4dms  %-6.6s\n"
2425         int x;
2426         int numchans = 0;
2427         if (argc != 3)
2428                 return RESULT_SHOWUSAGE;
2429         ast_cli(fd, FORMAT2, "Peer", "Username", "ID (Lo/Rem)", "Seq (Tx/Rx)", "Lag", "Jitter", "Format");
2430         for (x=0;x<AST_IAX_MAX_CALLS;x++) {
2431                 ast_mutex_lock(&iaxsl[x]);
2432                 if (iaxs[x]) {
2433                         ast_cli(fd, FORMAT, inet_ntoa(iaxs[x]->addr.sin_addr), 
2434                                                 strlen(iaxs[x]->username) ? iaxs[x]->username : "(None)", 
2435                                                 iaxs[x]->callno, iaxs[x]->peercallno, 
2436                                                 iaxs[x]->oseqno, iaxs[x]->iseqno, 
2437                                                 iaxs[x]->lag,
2438                                                 iaxs[x]->jitter,
2439                                                 ast_getformatname(iaxs[x]->voiceformat) );
2440                         numchans++;
2441                 }
2442                 ast_mutex_unlock(&iaxsl[x]);
2443         }
2444         ast_cli(fd, "%d active IAX channel(s)\n", numchans);
2445         return RESULT_SUCCESS;
2446 #undef FORMAT
2447 #undef FORMAT2
2448 }
2449
2450 static int iax_do_debug(int fd, int argc, char *argv[])
2451 {
2452         if (argc != 2)
2453                 return RESULT_SHOWUSAGE;
2454         iaxdebug = 1;
2455         ast_cli(fd, "IAX Debugging Enabled\n");
2456         return RESULT_SUCCESS;
2457 }
2458
2459 static int iax_no_debug(int fd, int argc, char *argv[])
2460 {
2461         if (argc != 3)
2462                 return RESULT_SHOWUSAGE;
2463         iaxdebug = 0;
2464         ast_cli(fd, "IAX Debugging Disabled\n");
2465         return RESULT_SUCCESS;
2466 }
2467
2468
2469
2470 static char show_users_usage[] = 
2471 "Usage: iax show users\n"
2472 "       Lists all users known to the IAX (Inter-Asterisk eXchange) subsystem.\n";
2473
2474 static char show_channels_usage[] = 
2475 "Usage: iax show channels\n"
2476 "       Lists all currently active IAX channels.\n";
2477
2478 static char show_peers_usage[] = 
2479 "Usage: iax show peers\n"
2480 "       Lists all known IAX peers.\n";
2481
2482 static char show_reg_usage[] =
2483 "Usage: iax show registry\n"
2484 "       Lists all registration requests and status.\n";
2485
2486 #ifdef DEBUG_SUPPORT
2487
2488 static char debug_usage[] = 
2489 "Usage: iax debug\n"
2490 "       Enables dumping of IAX packets for debugging purposes\n";
2491
2492 static char no_debug_usage[] = 
2493 "Usage: iax no debug\n"
2494 "       Disables dumping of IAX packets for debugging purposes\n";
2495
2496 #endif
2497
2498 static struct ast_cli_entry  cli_show_users = 
2499         { { "iax", "show", "users", NULL }, iax_show_users, "Show defined IAX users", show_users_usage };
2500 static struct ast_cli_entry  cli_show_channels =
2501         { { "iax", "show", "channels", NULL }, iax_show_channels, "Show active IAX channels", show_channels_usage };
2502 static struct ast_cli_entry  cli_show_peers =
2503         { { "iax", "show", "peers", NULL }, iax_show_peers, "Show defined IAX peers", show_peers_usage };
2504 static struct ast_cli_entry  cli_show_registry =
2505         { { "iax", "show", "registry", NULL }, iax_show_registry, "Show IAX registration status", show_reg_usage };
2506 static struct ast_cli_entry  cli_debug =
2507         { { "iax", "debug", NULL }, iax_do_debug, "Enable IAX debugging", debug_usage };
2508 static struct ast_cli_entry  cli_no_debug =
2509         { { "iax", "no", "debug", NULL }, iax_no_debug, "Disable IAX debugging", no_debug_usage };
2510
2511 static int iax_write(struct ast_channel *c, struct ast_frame *f)
2512 {
2513         struct chan_iax_pvt *i = c->pvt->pvt;
2514         if (!i)
2515                 return -1;
2516         /* If there's an outstanding error, return failure now */
2517         if (i->error) {
2518                 ast_log(LOG_DEBUG, "Write error: %s\n", strerror(errno));
2519                 return -1;
2520         }
2521         /* If it's already gone, just return */
2522         if (i->alreadygone)
2523                 return 0;
2524         /* Don't waste bandwidth sending null frames */
2525         if (f->frametype == AST_FRAME_NULL)
2526                 return 0;
2527         /* If we're quelching voice, don't bother sending it */
2528         if ((f->frametype == AST_FRAME_VOICE) && i->quelch)
2529                 return 0;
2530         /* Simple, just queue for transmission */
2531         return iax_send(i, f, 0, -1, 0, 0, 0);
2532 }
2533
2534 static int __send_command(struct chan_iax_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno, 
2535                 int now, int transfer, int final)
2536 {
2537         struct ast_frame f;
2538         f.frametype = type;
2539         f.subclass = command;
2540         f.datalen = datalen;
2541         f.samples = 0;
2542         f.mallocd = 0;
2543         f.offset = 0;
2544         f.src = __FUNCTION__;
2545         f.data = data;
2546         return iax_send(i, &f, ts, seqno, now, transfer, final);
2547 }
2548
2549 static int send_command(struct chan_iax_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2550 {
2551         return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 0);
2552 }
2553
2554 #ifdef BRIDGE_OPTIMIZATION
2555 static int forward_command(struct chan_iax_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2556 {
2557         return __send_command(iaxs[i->bridgecallno], type, command, ts, data, datalen, seqno, 0, 0, 0);
2558 }
2559 #endif
2560
2561 static int send_command_final(struct chan_iax_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2562 {
2563         /* It is assumed that the callno has already been locked */
2564         iax_predestroy_nolock(i->callno);
2565         return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 1);
2566 }
2567
2568 static int send_command_immediate(struct chan_iax_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2569 {
2570         return __send_command(i, type, command, ts, data, datalen, seqno, 1, 0, 0);
2571 }
2572
2573 static int send_command_transfer(struct chan_iax_pvt *i, char type, int command, unsigned int ts, char *data, int datalen)
2574 {
2575         return __send_command(i, type, command, ts, data, datalen, 0, 0, 1, 0);
2576 }
2577
2578 static int apply_context(struct iax_context *con, char *context)
2579 {
2580         while(con) {
2581                 if (!strcmp(con->context, context))
2582                         return -1;
2583                 con = con->next;
2584         }
2585         return 0;
2586 }
2587
2588 static int iax_getformats(int callno, char *orequest)
2589 {
2590         char *var, *value;
2591         char request[256];
2592         char *stringp=NULL;
2593         strncpy(request, orequest, sizeof(request)-1);
2594         stringp=request;
2595         var = strsep(&stringp, ";");
2596         while(var) {
2597                 value = strchr(var, '=');
2598                 if (value) {
2599                         *value='\0';
2600                         value++;
2601                         if (!strcmp(var, "formats")) {
2602                                 iaxs[callno]->peerformat = atoi(value);
2603                         } else 
2604                                 ast_log(LOG_WARNING, "Unknown variable '%s' with value '%s'\n", var, value);
2605                 }
2606                 var = strsep(&stringp, ";");
2607         }
2608         return 0;
2609 }
2610
2611
2612 static int check_access(int callno, struct sockaddr_in *sin, char *orequest, int requestl)
2613 {
2614         /* Start pessimistic */
2615         int res = -1;
2616         int version = 1;
2617         char *var, *value;
2618         struct iax_user *user;
2619         char request[256];
2620         int gotcapability=0;
2621         char *stringp=NULL;
2622         strncpy(request, orequest, sizeof(request)-1);
2623         if (!iaxs[callno])
2624                 return res;
2625         stringp=request;
2626         var = strsep(&stringp, ";");
2627         while(var) {
2628                 value = strchr(var, '=');
2629                 if (value) { 
2630                         *value='\0';
2631                         value++;
2632                         if (!strcmp(var, "exten")) 
2633                                 strncpy(iaxs[callno]->exten, value, sizeof(iaxs[callno]->exten)-1);
2634                         else if (!strcmp(var, "callerid"))
2635                                 strncpy(iaxs[callno]->callerid, value, sizeof(iaxs[callno]->callerid)-1);
2636                         else if (!strcmp(var, "ani"))
2637                                 strncpy(iaxs[callno]->ani, value, sizeof(iaxs[callno]->ani) - 1);
2638                         else if (!strcmp(var, "dnid"))
2639                                 strncpy(iaxs[callno]->dnid, value, sizeof(iaxs[callno]->dnid)-1);
2640                         else if (!strcmp(var, "context"))
2641                                 strncpy(iaxs[callno]->context, value, sizeof(iaxs[callno]->context)-1);
2642                         else if (!strcmp(var, "language"))
2643                                 strncpy(iaxs[callno]->language, value, sizeof(iaxs[callno]->language)-1);
2644                         else if (!strcmp(var, "username"))
2645                                 strncpy(iaxs[callno]->username, value, sizeof(iaxs[callno]->username)-1);
2646                         else if (!strcmp(var, "formats")) 
2647                                 iaxs[callno]->peerformat = atoi(value);
2648                         else if (!strcmp(var, "adsicpe"))
2649                                 iaxs[callno]->peeradsicpe = atoi(value);
2650                         else if (!strcmp(var, "capability")) {
2651                                 gotcapability = 1;
2652                                 iaxs[callno]->peercapability = atoi(value);
2653                         } else if (!strcmp(var, "version"))
2654                                 version = atoi(value);
2655                         else 
2656                                 ast_log(LOG_WARNING, "Unknown variable '%s' with value '%s'\n", var, value);
2657                 }
2658                 var = strsep(&stringp, ";");
2659         }
2660         if (!gotcapability) 
2661                 iaxs[callno]->peercapability = iaxs[callno]->peerformat;
2662         if (version > AST_IAX_PROTO_VERSION) {
2663                 ast_log(LOG_WARNING, "Peer '%s' has too new a protocol version (%d) for me\n", 
2664                         inet_ntoa(sin->sin_addr), version);
2665                 return res;
2666         }
2667         ast_mutex_lock(&userl.lock);
2668         /* Search the userlist for a compatible entry, and fill in the rest */
2669         user = userl.users;
2670         while(user) {
2671                 if ((!strlen(iaxs[callno]->username) ||                         /* No username specified */
2672                         !strcmp(iaxs[callno]->username, user->name))    /* Or this username specified */
2673                         && ast_apply_ha(user->ha, sin)  /* Access is permitted from this IP */
2674                         && (!strlen(iaxs[callno]->context) ||                   /* No context specified */
2675                              apply_context(user->contexts, iaxs[callno]->context))) {                   /* Context is permitted */
2676                         break;
2677                 }
2678                 user = user->next;      
2679         }
2680 #ifdef MYSQL_FRIENDS
2681         if (!user && mysql && strlen(iaxs[callno]->username) && (strlen(iaxs[callno]->username) < 128)) {
2682                 user = mysql_user(iaxs[callno]->username);
2683                 if (user && strlen(iaxs[callno]->context) &&                    /* No context specified */
2684                              !apply_context(user->contexts, iaxs[callno]->context)) {                   /* Context is permitted */
2685                         if (user->contexts)
2686                                 free(user->contexts);
2687                         free(user);
2688                         user = NULL;
2689                 }
2690         }
2691 #endif  
2692         ast_mutex_unlock(&userl.lock);
2693         if (user) {
2694                 /* We found our match (use the first) */
2695                 
2696                 /* Store the requested username if not specified */
2697                 if (!strlen(iaxs[callno]->username))
2698                         strncpy(iaxs[callno]->username, user->name, sizeof(iaxs[callno]->username)-1);
2699                 /* And use the default context */
2700                 if (!strlen(iaxs[callno]->context)) {
2701                         if (user->contexts)
2702                                 strncpy(iaxs[callno]->context, user->contexts->context, sizeof(iaxs[callno]->context)-1);
2703                         else
2704                                 strncpy(iaxs[callno]->context, context, sizeof(iaxs[callno]->context)-1);
2705                 }
2706                 /* Copy the secret */
2707                 strncpy(iaxs[callno]->secret, user->secret, sizeof(iaxs[callno]->secret)-1);
2708                 /* And any input keys */
2709                 strncpy(iaxs[callno]->inkeys, user->inkeys, sizeof(iaxs[callno]->inkeys));
2710                 /* And the permitted authentication methods */
2711                 strncpy(iaxs[callno]->methods, user->methods, sizeof(iaxs[callno]->methods)-1);
2712                 /* If they have callerid, override the given caller id.  Always store the ANI */
2713                 if (strlen(iaxs[callno]->callerid)) {
2714                         if (user->hascallerid)
2715                                 strncpy(iaxs[callno]->callerid, user->callerid, sizeof(iaxs[callno]->callerid)-1);
2716                         strncpy(iaxs[callno]->ani, user->callerid, sizeof(iaxs[callno]->ani)-1);
2717                 }
2718                 if (strlen(user->accountcode))
2719                         strncpy(iaxs[callno]->accountcode, user->accountcode, sizeof(iaxs[callno]->accountcode)-1);
2720                 if (user->amaflags)
2721                         iaxs[callno]->amaflags = user->amaflags;
2722                 res = 0;
2723         }
2724         return res;
2725 }
2726
2727 static int raw_hangup(struct sockaddr_in *sin, short src, short dst)
2728 {
2729         struct ast_iax_full_hdr fh;
2730         fh.callno = htons(src | AST_FLAG_FULL);
2731         fh.dcallno = htons(dst);
2732         fh.ts = 0;
2733         fh.seqno = 0;
2734         fh.type = AST_FRAME_IAX;
2735         fh.csub = compress_subclass(AST_IAX_COMMAND_INVAL);
2736 #if 0
2737         if (option_debug)
2738 #endif  
2739                 ast_log(LOG_DEBUG, "Raw Hangup %s:%d, src=%d, dst=%d\n",
2740                         inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), src, dst);
2741         return sendto(netsocket, &fh, sizeof(fh), 0, (struct sockaddr *)sin, sizeof(*sin));
2742 }
2743
2744 static int authenticate_request(struct chan_iax_pvt *p)
2745 {
2746         char requeststr[256] = "";
2747         MYSNPRINTF "methods=%s;", p->methods);
2748         if (strstr(p->methods, "md5") || strstr(p->methods, "rsa")) {
2749                 /* Build the challenge */
2750                 snprintf(p->challenge, sizeof(p->challenge), "%d", rand());
2751                 MYSNPRINTF "challenge=%s;", p->challenge);
2752         }
2753         MYSNPRINTF "username=%s;", p->username);
2754         if (strlen(requeststr))
2755                 requeststr[strlen(requeststr) - 1] = '\0';
2756         return send_command(p, AST_FRAME_IAX, AST_IAX_COMMAND_AUTHREQ, 0, requeststr, strlen(requeststr) + 1, -1);
2757 }
2758
2759 static int authenticate_verify(struct chan_iax_pvt *p, char *orequest)
2760 {
2761         char requeststr[256] = "";
2762         char *var, *value, request[256];
2763         char md5secret[256] = "";
2764         char secret[256] = "";
2765         char rsasecret[256] = "";
2766         int res = -1; 
2767         int x;
2768         char *stringp=NULL;
2769         
2770         if (!(p->state & IAX_STATE_AUTHENTICATED))
2771                 return res;
2772         strncpy(request, orequest, sizeof(request)-1);
2773         stringp=request;
2774         var = strsep(&stringp, ";");
2775         while(var) {
2776                 value = strchr(var, '=');
2777                 if (value) { 
2778                         *value='\0';
2779                         value++;
2780                         if (!strcmp(var, "secret")) 
2781                                 strncpy(secret, value, sizeof(secret)-1);
2782                         else if (!strcmp(var, "md5secret"))
2783                                 strncpy(md5secret, value, sizeof(md5secret)-1);
2784                         else if (!strcmp(var, "rsasecret"))
2785                                 strncpy(rsasecret, value, sizeof(rsasecret)-1);
2786                         else
2787                                 ast_log(LOG_WARNING, "Unknown variable '%s' with value '%s'\n", var, value);
2788                 }
2789                 var = strsep(&stringp, ";");
2790         }
2791         if (strstr(p->methods, "rsa") && strlen(rsasecret) && strlen(p->inkeys)) {
2792                 struct ast_key *key;
2793                 char *keyn;
2794                 char tmpkey[256];
2795                 char *stringp=NULL;
2796                 strncpy(tmpkey, p->inkeys, sizeof(tmpkey));
2797                 stringp=tmpkey;
2798                 keyn = strsep(&stringp, ":");
2799                 while(keyn) {
2800                         key = ast_key_get(keyn, AST_KEY_PUBLIC);
2801                         if (key && !ast_check_signature(key, p->challenge, rsasecret)) {
2802                                 res = 0;
2803                                 break;
2804                         } else if (!key)
2805                                 ast_log(LOG_WARNING, "requested inkey '%s' for RSA authentication does not exist\n", keyn);
2806                         keyn = strsep(&stringp, ":");
2807                 }
2808         } else if (strstr(p->methods, "md5")) {
2809                 struct MD5Context md5;
2810                 unsigned char digest[16];
2811                 MD5Init(&md5);
2812                 MD5Update(&md5, p->challenge, strlen(p->challenge));
2813                 MD5Update(&md5, p->secret, strlen(p->secret));
2814                 MD5Final(digest, &md5);
2815                 /* If they support md5, authenticate with it.  */
2816                 for (x=0;x<16;x++)
2817                         MYSNPRINTF "%2.2x", digest[x]);
2818                 if (!strcasecmp(requeststr, md5secret))
2819                         res = 0;
2820         } else if (strstr(p->methods, "plaintext")) {
2821                 if (!strcmp(secret, p->secret))
2822                         res = 0;
2823         }
2824         return res;
2825 }
2826
2827 static int register_verify(int callno, struct sockaddr_in *sin, char *orequest)
2828 {
2829         char request[256];
2830         char requeststr[256] = "";
2831         char peer[256] = "";
2832         char md5secret[256] = "";
2833         char rsasecret[256] = "";
2834         char secret[256] = "";
2835         struct iax_peer *p;
2836         struct ast_key *key;
2837         char *var;
2838         char *value;
2839         char *keyn;
2840         int x;
2841         int expire = 0;
2842         char *stringp=NULL;
2843
2844         iaxs[callno]->state &= ~IAX_STATE_AUTHENTICATED;
2845         strcpy(iaxs[callno]->peer, "");
2846         if (!orequest)
2847                 return -1;
2848         strncpy(request, orequest, sizeof(request)-1);
2849         stringp=request;
2850         var = strsep(&stringp, ";");
2851         while(var) {
2852                 value = strchr(var, '=');
2853                 if (value) { 
2854                         *value='\0';
2855                         value++;
2856                         if (!strcmp(var, "peer")) 
2857                                 strncpy(peer, value, sizeof(peer)-1);
2858                         else if (!strcmp(var, "md5secret"))
2859                                 strncpy(md5secret, value, sizeof(md5secret)-1);
2860                         else if (!strcmp(var, "rsasecret"))
2861                                 strncpy(rsasecret, value, sizeof(rsasecret)-1);
2862                         else if (!strcmp(var, "secret"))
2863                                 strncpy(secret, value, sizeof(secret)-1);
2864                         else if (!strcmp(var, "refresh"))
2865                                 expire = atoi(value);
2866                         else 
2867                                 ast_log(LOG_WARNING, "Unknown variable '%s' with value '%s'\n", var, value);
2868                 }
2869                 var = strsep(&stringp, ";");
2870         }
2871
2872         if (!strlen(peer)) {
2873                 ast_log(LOG_NOTICE, "Empty registration from %s\n", inet_ntoa(sin->sin_addr));
2874                 return -1;
2875         }
2876
2877         for (p = peerl.peers; p ; p = p->next) 
2878                 if (!strcasecmp(p->name, peer))
2879                         break;
2880
2881 #ifdef MYSQL_FRIENDS
2882         if (!p) 
2883                 p = mysql_peer(peer);
2884 #endif
2885         if (!p) {
2886                 ast_log(LOG_NOTICE, "No registration for peer '%s' (from %s)\n", peer, inet_ntoa(sin->sin_addr));
2887                 return -1;
2888         }
2889
2890         if (!p->dynamic) {
2891                 ast_log(LOG_NOTICE, "Peer '%s' is not dynamic (from %s)\n", peer, inet_ntoa(sin->sin_addr));
2892                 if (p->delme)
2893                         free(p);
2894                 return -1;
2895         }
2896
2897         if (!ast_apply_ha(p->ha, sin)) {
2898                 ast_log(LOG_NOTICE, "Host %s denied access to register peer '%s'\n", inet_ntoa(sin->sin_addr), p->name);
2899                 if (p->delme)
2900                         free(p);
2901                 return -1;
2902         }
2903         strncpy(iaxs[callno]->secret, p->secret, sizeof(iaxs[callno]->secret)-1);
2904         strncpy(iaxs[callno]->inkeys, p->inkeys, sizeof(iaxs[callno]->inkeys)-1);
2905         /* Check secret against what we have on file */
2906         if (strlen(rsasecret) && strstr(p->methods, "rsa") && strlen(iaxs[callno]->challenge)) {
2907                 if (strlen(p->inkeys)) {
2908                         char tmpkeys[256];
2909                         char *stringp=NULL;
2910                         strncpy(tmpkeys, p->inkeys, sizeof(tmpkeys));
2911                         stringp=tmpkeys;
2912                         keyn = strsep(&stringp, ":");
2913                         while(keyn) {
2914                                 key = ast_key_get(keyn, AST_KEY_PUBLIC);
2915                                 if (key && !ast_check_signature(key, iaxs[callno]->challenge, rsasecret)) {
2916                                         iaxs[callno]->state |= IAX_STATE_AUTHENTICATED;
2917                                         break;
2918                                 } else if (!key) 
2919                                         ast_log(LOG_WARNING, "requested inkey '%s' does not exist\n", keyn);
2920                                 keyn = strsep(&stringp, ":");
2921                         }
2922                         if (!keyn) {
2923                                 ast_log(LOG_NOTICE, "Host %s failed RSA authentication with inkeys '%s'\n", peer, p->inkeys);
2924                                 if (p->delme)
2925                                         free(p);
2926                                 return -1;
2927                         }
2928                 } else {
2929                         ast_log(LOG_NOTICE, "Host '%s' trying to do RSA authentication, but we have no inkeys\n", peer);
2930                         if (p->delme)
2931                                 free(p);
2932                         return -1;
2933                 }
2934         } else if (strlen(secret) && strstr(p->methods, "plaintext")) {
2935                 /* They've provided a plain text password and we support that */
2936                 if (strcmp(secret, p->secret)) {
2937                         ast_log(LOG_NOTICE, "Host %s did not provide proper plaintext password for '%s'\n", inet_ntoa(sin->sin_addr), p->name);
2938                         if (p->delme)
2939                                 free(p);
2940                         return -1;
2941                 } else
2942                         iaxs[callno]->state |= IAX_STATE_AUTHENTICATED;
2943         } else if (strlen(md5secret) && strstr(p->methods, "md5") && strlen(iaxs[callno]->challenge)) {
2944                 struct MD5Context md5;
2945                 unsigned char digest[16];
2946                 MD5Init(&md5);
2947                 MD5Update(&md5, iaxs[callno]->challenge, strlen(iaxs[callno]->challenge));
2948                 MD5Update(&md5, p->secret, strlen(p->secret));
2949                 MD5Final(digest, &md5);
2950                 for (x=0;x<16;x++)
2951                         MYSNPRINTF "%2.2x", digest[x]);
2952                 if (strcasecmp(requeststr, md5secret)) {
2953                         ast_log(LOG_NOTICE, "Host %s failed MD5 authentication for '%s' (%s != %s)\n", inet_ntoa(sin->sin_addr), p->name, requeststr, md5secret);
2954                         if (p->delme)
2955                                 free(p);
2956                         return -1;
2957                 } else
2958                         iaxs[callno]->state |= IAX_STATE_AUTHENTICATED;
2959         } else if (strlen(md5secret) || strlen(secret)) {
2960                 ast_log(LOG_NOTICE, "Inappropriate authentication received\n");
2961                 if (p->delme)
2962                         free(p);
2963                 return -1;
2964         }
2965         strncpy(iaxs[callno]->peer, peer, sizeof(iaxs[callno]->peer)-1);
2966         /* Choose lowest expirey number */
2967         if (expire && (expire < iaxs[callno]->expirey)) 
2968                 iaxs[callno]->expirey = expire;
2969         if (p->delme)
2970                 free(p);
2971         return 0;
2972         
2973 }
2974
2975 static int authenticate(char *challenge, char *secret, char *keyn, char *methods, char *requeststr, int reqsize, struct sockaddr_in *sin)
2976 {
2977         int res = -1;
2978         int x;
2979         if (keyn && strlen(keyn)) {
2980                 if (!strstr(methods, "rsa")) {
2981                         if (!secret || !strlen(secret)) 
2982                                 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));
2983                 } else if (!strlen(challenge)) {
2984                         ast_log(LOG_NOTICE, "No challenge provided for RSA authentication to %s\n", inet_ntoa(sin->sin_addr));
2985                 } else {
2986                         char sig[256];
2987                         struct ast_key *key;
2988                         key = ast_key_get(keyn, AST_KEY_PRIVATE);
2989                         if (!key) {
2990                                 ast_log(LOG_NOTICE, "Unable to find private key '%s'\n", keyn);
2991                         } else {
2992                                 if (ast_sign(key, challenge, sig)) {
2993                                         ast_log(LOG_NOTICE, "Unable to sign challenge withy key\n");
2994                                         res = -1;
2995                                 } else {
2996                                         MYSNPRINTF2 "rsasecret=%s;", sig);
2997                                         res = 0;
2998                                 }
2999                         }
3000                 }
3001         } 
3002         /* Fall back */
3003         if (res && secret && strlen(secret)) {
3004                 if (strstr(methods, "md5") && strlen(challenge)) {
3005                         struct MD5Context md5;
3006                         unsigned char digest[16];
3007                         MD5Init(&md5);
3008                         MD5Update(&md5, challenge, strlen(challenge));
3009                         MD5Update(&md5, secret, strlen(secret));
3010                         MD5Final(digest, &md5);
3011                         /* If they support md5, authenticate with it.  */
3012                         MYSNPRINTF2 "md5secret=");
3013                         for (x=0;x<16;x++)
3014                                 MYSNPRINTF2 "%2.2x", digest[x]);
3015                         MYSNPRINTF2 ";");
3016                         res = 0;
3017                 } else if (strstr(methods, "plaintext")) {
3018                         MYSNPRINTF2 "secret=%s;", secret);
3019                         res = 0;
3020                 } else
3021                         ast_log(LOG_NOTICE, "No way to send secret to peer '%s' (their methods: %s)\n", inet_ntoa(sin->sin_addr), methods);
3022         }
3023         return res;
3024 }
3025
3026 static int authenticate_reply(struct chan_iax_pvt *p, struct sockaddr_in *sin, char *orequest, char *override, char *okey)
3027 {
3028         struct iax_peer *peer;
3029         /* Start pessimistic */
3030         int res = -1;
3031         char request[256];
3032         char methods[80] = "";
3033         char requeststr[256] = "";
3034         char *var, *value;
3035         char *stringp=NULL;
3036         
3037         strncpy(request, orequest, sizeof(request)-1);
3038         stringp=request;
3039         var = strsep(&stringp, ";");
3040         while(var) {
3041                 value = strchr(var, '=');
3042                 if (value) { 
3043                         *value='\0';
3044                         value++;
3045                         if (!strcmp(var, "username")) 
3046                                 strncpy(p->username, value, sizeof(p->username)-1);
3047                         else if (!strcmp(var, "challenge"))
3048                                 strncpy(p->challenge, value, sizeof(p->challenge)-1);
3049                         else if (!strcmp(var, "methods"))
3050                                 strncpy(methods, value, sizeof(methods)-1);
3051                         else 
3052                                 ast_log(LOG_WARNING, "Unknown variable&n