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