Remove pthread.h from source. We should be using asterisk/lock.h everywhere instead...
[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 <asterisk/utils.h>
33 #include <arpa/inet.h>
34 #include <sys/socket.h>
35 #include <netinet/in.h>
36 #include <netinet/in_systm.h>
37 #include <netinet/ip.h>
38 #include <sys/time.h>
39 #include <stdlib.h>
40 #include <stdio.h>
41 #include <string.h>
42 #include <errno.h>
43 #include <unistd.h>
44 #include <netdb.h>
45 #include <fcntl.h>
46 #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 AST_MUTEX_DEFINE_STATIC(mysqllock);
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 AST_MUTEX_DEFINE_STATIC(usecnt_lock);
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 = AST_PTHREADT_NULL;
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 AST_MUTEX_DEFINE_STATIC(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         case AST_FORMAT_G726:
686                 samples = f->datalen *2;
687                 break;
688         case AST_FORMAT_SPEEX:
689                 samples = (f->datalen/39)*160;
690                 break;
691         default:
692                 ast_log(LOG_WARNING, "Don't know how to calculate samples on %d packets\n", f->subclass);
693         }
694         return samples;
695 }
696
697 static int frames = 0;
698 static int iframes = 0;
699 static int oframes = 0;
700
701 static struct ast_iax_frame *ast_iax_frame_new(int direction)
702 {
703         struct ast_iax_frame *fr;
704         fr = malloc(sizeof(struct ast_iax_frame));
705         if (fr) {
706                 fr->direction = direction;
707                 fr->retrans = -1;
708                 frames++;
709                 if (fr->direction == DIRECTION_INGRESS)
710                         iframes++;
711                 else
712                         oframes++;
713         }
714         return fr;
715 }
716
717 static void ast_iax_frame_free(struct ast_iax_frame *fr)
718 {
719         if (fr->retrans > -1)
720                 ast_sched_del(sched, fr->retrans);
721         if (fr->direction == DIRECTION_INGRESS)
722                 iframes--;
723         else if (fr->direction == DIRECTION_OUTGRESS)
724                 oframes--;
725         else {
726                 ast_log(LOG_WARNING, "Attempt to double free frame detected\n");
727                 CRASH;
728                 return;
729         }
730         fr->direction = 0;
731         free(fr);
732         frames--;
733 }
734
735 static struct ast_iax_frame *iaxfrdup2(struct ast_iax_frame *fr, int ch)
736 {
737         /* Malloc() a copy of a frame */
738         struct ast_iax_frame *new = ast_iax_frame_new(DIRECTION_INGRESS);
739         if (new) {
740                 memcpy(new, fr, sizeof(struct ast_iax_frame));  
741                 new->f = ast_frdup(fr->f);
742                 /* Copy full header */
743                 if (ch) {
744                         memcpy(new->f->data - sizeof(struct ast_iax_full_hdr),
745                                         fr->f->data - sizeof(struct ast_iax_full_hdr), 
746                                                 sizeof(struct ast_iax_full_hdr));
747                         /* Grab new data pointer */
748                         new->data = new->f->data - (fr->f->data - fr->data);
749                 } else {
750                         new->data = NULL;
751                         new->datalen = 0;
752                 }
753                 new->direction = DIRECTION_INGRESS;
754                 new->retrans = -1;
755         }
756         return new;
757 }
758
759 #define NEW_PREVENT 0
760 #define NEW_ALLOW       1
761 #define NEW_FORCE       2
762
763 static int match(struct sockaddr_in *sin, short callno, short dcallno, struct chan_iax_pvt *cur)
764 {
765         if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
766                 (cur->addr.sin_port == sin->sin_port)) {
767                 /* This is the main host */
768                 if ((cur->peercallno == callno) ||
769                         ((dcallno == cur->callno) && (cur->peercallno) == -1)) {
770                         /* That's us.  Be sure we keep track of the peer call number */
771                         return 1;
772                 }
773         }
774         if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
775             (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
776                 /* We're transferring */
777                 if (dcallno == cur->callno)
778                         return 1;
779         }
780         return 0;
781 }
782
783 static int find_callno(short callno, short dcallno ,struct sockaddr_in *sin, int new)
784 {
785         int res = -1;
786         int x;
787         int start;
788         if (new <= NEW_ALLOW) {
789                 /* Look for an existing connection first */
790                 for (x=0;(res < 0) && (x<AST_IAX_MAX_CALLS);x++) {
791                         ast_mutex_lock(&iaxsl[x]);
792                         if (iaxs[x]) {
793                                 /* Look for an exact match */
794                                 if (match(sin, callno, dcallno, iaxs[x])) {
795                                         res = x;
796                                 }
797                         }
798                         ast_mutex_unlock(&iaxsl[x]);
799                 }
800         }
801         if ((res < 0) && (new >= NEW_ALLOW)) {
802                 /* Create a new one */
803                 start = nextcallno;
804                 for (x = (nextcallno + 1) % AST_IAX_MAX_CALLS; iaxs[x] && (x != start); x = (x + 1) % AST_IAX_MAX_CALLS)
805                 if (x == start) {
806                         ast_log(LOG_WARNING, "Unable to accept more calls\n");
807                         return -1;
808                 }
809                 ast_mutex_lock(&iaxsl[x]);
810                 iaxs[x] = new_iax();
811                 ast_mutex_unlock(&iaxsl[x]);
812                 if (iaxs[x]) {
813                         if (option_debug)
814                                 ast_log(LOG_DEBUG, "Creating new call structure %d\n", x);
815                         iaxs[x]->addr.sin_port = sin->sin_port;
816                         iaxs[x]->addr.sin_family = sin->sin_family;
817                         iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
818                         iaxs[x]->peercallno = callno;
819                         iaxs[x]->callno = x;
820                         iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
821                         iaxs[x]->expirey = expirey;
822                         iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)x);
823                         iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)x);
824                         iaxs[x]->amaflags = amaflags;
825                         strncpy(iaxs[x]->accountcode, accountcode, sizeof(iaxs[x]->accountcode)-1);
826                 } else {
827                         ast_log(LOG_WARNING, "Out of resources\n");
828                         return -1;
829                 }
830                 res = x;
831                 nextcallno = x;
832         }
833         return res;
834 }
835
836 static int iax_queue_frame(int callno, struct ast_frame *f)
837 {
838         int pass =0;
839         /* Assumes lock for callno is already held... */
840         for (;;) {
841                 pass++;
842                 if (iaxs[callno] && iaxs[callno]->owner) {
843                         if (ast_mutex_trylock(&iaxs[callno]->owner->lock)) {
844                                 /* Avoid deadlock by pausing and trying again */
845                                 ast_mutex_unlock(&iaxsl[callno]);
846                                 usleep(1);
847                                 ast_mutex_lock(&iaxsl[callno]);
848                         } else {
849                                 ast_queue_frame(iaxs[callno]->owner, f);
850                                 ast_mutex_unlock(&iaxs[callno]->owner->lock);
851                                 break;
852                         }
853                 } else
854                         break;
855         }
856         return 0;
857 }
858
859 static int iax_send(struct chan_iax_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
860
861 static int __do_deliver(void *data)
862 {
863         /* Just deliver the packet by using queueing.  This is called by
864           the IAX thread with the iaxsl lock held. */
865         struct ast_iax_frame *fr = data;
866         unsigned int ts;
867         fr->retrans = -1;
868         if (iaxs[fr->callno] && !iaxs[fr->callno]->alreadygone) {
869                 if (fr->f->frametype == AST_FRAME_IAX) {
870                         /* We have to treat some of these packets specially because
871                            they're LAG measurement packets */
872                         if (fr->f->subclass == AST_IAX_COMMAND_LAGRQ) {
873                                 /* If we got a queued request, build a reply and send it */
874                                 fr->f->subclass = AST_IAX_COMMAND_LAGRP;
875                                 iax_send(iaxs[fr->callno], fr->f, fr->ts, -1, 0, 0, 0);
876                         } else if (fr->f->subclass == AST_IAX_COMMAND_LAGRP) {
877                                 /* This is a reply we've been given, actually measure the difference */
878                                 ts = calc_timestamp(iaxs[fr->callno], 0);
879                                 iaxs[fr->callno]->lag = ts - fr->ts;
880                         }
881                 } else {
882                         iax_queue_frame(fr->callno, fr->f);
883                 }
884         }
885         /* Free the packet */
886         ast_frfree(fr->f);
887         /* And our iax frame */
888         ast_iax_frame_free(fr);
889         /* And don't run again */
890         return 0;
891 }
892
893 static int do_deliver(void *data)
894 {
895         /* Locking version of __do_deliver */
896         struct ast_iax_frame *fr = data;
897         int callno = fr->callno;
898         int res;
899         ast_mutex_lock(&iaxsl[callno]);
900         res = __do_deliver(data);
901         ast_mutex_unlock(&iaxsl[callno]);
902         return res;
903 }
904
905 static int handle_error(void)
906 {
907         /* XXX Ideally we should figure out why an error occured and then abort those
908            rather than continuing to try.  Unfortunately, the published interface does
909            not seem to work XXX */
910 #if 0
911         struct sockaddr_in *sin;
912         int res;
913         struct msghdr m;
914         struct sock_extended_err e;
915         m.msg_name = NULL;
916         m.msg_namelen = 0;
917         m.msg_iov = NULL;
918         m.msg_control = &e;
919         m.msg_controllen = sizeof(e);
920         m.msg_flags = 0;
921         res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
922         if (res < 0)
923                 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
924         else {
925                 if (m.msg_controllen) {
926                         sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
927                         if (sin) 
928                                 ast_log(LOG_WARNING, "Receive error from %s\n", inet_ntoa(sin->sin_addr));
929                         else
930                                 ast_log(LOG_WARNING, "No address detected??\n");
931                 } else {
932                         ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
933                 }
934         }
935 #endif
936         return 0;
937 }
938
939 static int send_packet(struct ast_iax_frame *f)
940 {
941         int res;
942         /* Called with iaxsl held */
943         if (option_debug)
944                 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));
945         /* Don't send if there was an error, but return error instead */
946         if (f->callno < 0) {
947                 ast_log(LOG_WARNING, "Call number = %d\n", f->callno);
948                 return -1;
949         }
950         if (!iaxs[f->callno])
951                 return -1;
952         if (iaxs[f->callno]->error)
953                 return -1;
954         if (f->transfer) {
955 #ifdef DEBUG_SUPPORT
956                 if (iaxdebug)
957                         showframe(f, NULL, 0, &iaxs[f->callno]->transfer);
958 #endif
959                 res = sendto(netsocket, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[f->callno]->transfer,
960                                         sizeof(iaxs[f->callno]->transfer));
961         } else {
962 #ifdef DEBUG_SUPPORT
963                 if (iaxdebug)
964                         showframe(f, NULL, 0, &iaxs[f->callno]->addr);
965 #endif
966                 res = sendto(netsocket, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[f->callno]->addr,
967                                         sizeof(iaxs[f->callno]->addr));
968         }
969         if (res < 0) {
970                 if (option_debug)
971                         ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
972                 handle_error();
973         } else
974                 res = 0;
975         return res;
976 }
977
978
979 static int iax_predestroy(int callno)
980 {
981         struct ast_channel *c;
982         struct chan_iax_pvt *pvt;
983         ast_mutex_lock(&iaxsl[callno]);
984         pvt = iaxs[callno];
985         if (!pvt) {
986                 ast_mutex_unlock(&iaxsl[callno]);
987                 return -1;
988         }
989         if (!pvt->alreadygone) {
990                 /* No more pings or lagrq's */
991                 if (pvt->pingid > -1)
992                         ast_sched_del(sched, pvt->pingid);
993                 if (pvt->lagid > -1)
994                         ast_sched_del(sched, pvt->lagid);
995                 if (pvt->autoid > -1)
996                         ast_sched_del(sched, pvt->autoid);
997                 if (pvt->initid > -1)
998                         ast_sched_del(sched, pvt->initid);
999                 pvt->pingid = -1;
1000                 pvt->lagid = -1;
1001                 pvt->autoid = -1;
1002                 pvt->initid = -1;
1003                 pvt->alreadygone = 1;
1004         }
1005         c = pvt->owner;
1006         if (c) {
1007                 c->_softhangup |= AST_SOFTHANGUP_DEV;
1008                 c->pvt->pvt = NULL;
1009                 pvt->owner = NULL;
1010                 ast_mutex_lock(&usecnt_lock);
1011                 usecnt--;
1012                 if (usecnt < 0) 
1013                         ast_log(LOG_WARNING, "Usecnt < 0???\n");
1014                 ast_mutex_unlock(&usecnt_lock);
1015                 ast_update_use_count();
1016         }
1017         ast_mutex_unlock(&iaxsl[callno]);
1018         return 0;
1019 }
1020
1021 static int iax_predestroy_nolock(int callno)
1022 {
1023         int res;
1024         ast_mutex_unlock(&iaxsl[callno]);
1025         res = iax_predestroy(callno);
1026         ast_mutex_lock(&iaxsl[callno]);
1027         return res;
1028 }
1029
1030 static void iax_destroy(int callno)
1031 {
1032         struct chan_iax_pvt *pvt;
1033         struct ast_iax_frame *cur;
1034         struct ast_channel *owner;
1035
1036 retry:
1037         ast_mutex_lock(&iaxsl[callno]);
1038         pvt = iaxs[callno];
1039         iaxs[callno] = NULL;
1040
1041         if (pvt)
1042                 owner = pvt->owner;
1043         else
1044                 owner = NULL;
1045         if (owner) {
1046                 if (ast_mutex_trylock(&owner->lock)) {
1047                         ast_log(LOG_NOTICE, "Avoiding IAX destroy deadlock\n");
1048                         ast_mutex_unlock(&iaxsl[callno]);
1049                         usleep(1);
1050                         goto retry;
1051                 }
1052         }
1053         if (pvt) {
1054                 pvt->owner = NULL;
1055                 /* No more pings or lagrq's */
1056                 if (pvt->pingid > -1)
1057                         ast_sched_del(sched, pvt->pingid);
1058                 if (pvt->lagid > -1)
1059                         ast_sched_del(sched, pvt->lagid);
1060                 if (pvt->autoid > -1)
1061                         ast_sched_del(sched, pvt->autoid);
1062                 if (pvt->initid > -1)
1063                         ast_sched_del(sched, pvt->initid);
1064                 pvt->pingid = -1;
1065                 pvt->lagid = -1;
1066                 pvt->autoid = -1;
1067                 pvt->initid = -1;
1068
1069                 /* Already gone */
1070                 pvt->alreadygone = 1;
1071
1072                 if (owner) {
1073                         /* If there's an owner, prod it to give up */
1074                         owner->pvt->pvt = NULL;
1075                         owner->_softhangup |= AST_SOFTHANGUP_DEV;
1076                         ast_queue_hangup(owner);
1077                 }
1078
1079                 for (cur = iaxq.head; cur ; cur = cur->next) {
1080                         /* Cancel any pending transmissions */
1081                         if (cur->callno == pvt->callno) 
1082                                 cur->retries = -1;
1083                 }
1084                 if (pvt->reg) {
1085                         pvt->reg->callno = -1;
1086                 }
1087                 free(pvt);
1088         }
1089         if (owner) {
1090                 ast_mutex_unlock(&owner->lock);
1091         }
1092         ast_mutex_unlock(&iaxsl[callno]);
1093 }
1094 static void iax_destroy_nolock(int callno)
1095 {       
1096         /* Actually it's easier to unlock, kill it, and relock */
1097         ast_mutex_unlock(&iaxsl[callno]);
1098         iax_destroy(callno);
1099         ast_mutex_lock(&iaxsl[callno]);
1100 }
1101
1102
1103
1104 static int attempt_transmit(void *data)
1105 {
1106         /* Attempt to transmit the frame to the remote peer...
1107            Called without iaxsl held. */
1108         struct ast_iax_frame *f = data;
1109         int freeme=0;
1110         int callno = f->callno;
1111         /* Make sure this call is still active */
1112         if (callno > -1) 
1113                 ast_mutex_lock(&iaxsl[callno]);
1114         if ((f->callno > -1) && iaxs[f->callno]) {
1115                 if ((f->retries < 0) /* Already ACK'd */ ||
1116                     (f->retries >= max_retries) /* Too many attempts */) {
1117                                 /* Record an error if we've transmitted too many times */
1118                                 if (f->retries >= max_retries) {
1119                                         if (f->transfer) {
1120                                                 /* Transfer timeout */
1121                                                 send_command(iaxs[f->callno], AST_FRAME_IAX, AST_IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
1122                                         } else if (f->final) {
1123                                                 if (f->final) 
1124                                                         iax_destroy_nolock(f->callno);
1125                                         } else {
1126                                                 if (iaxs[f->callno]->owner)
1127                                                         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);
1128                                                 iaxs[f->callno]->error = ETIMEDOUT;
1129                                                 if (iaxs[f->callno]->owner) {
1130                                                         struct ast_frame fr = { 0, };
1131                                                         /* Hangup the fd */
1132                                                         fr.frametype = AST_FRAME_CONTROL;
1133                                                         fr.subclass = AST_CONTROL_HANGUP;
1134                                                         iax_queue_frame(f->callno, &fr);
1135                                                 } else {
1136                                                         if (iaxs[f->callno]->reg) {
1137                                                                 memset(&iaxs[f->callno]->reg->us, 0, sizeof(iaxs[f->callno]->reg->us));
1138                                                                 iaxs[f->callno]->reg->regstate = REG_STATE_TIMEOUT;
1139                                                                 iaxs[f->callno]->reg->refresh = AST_DEFAULT_REG_EXPIRE;
1140                                                         }
1141                                                         iax_destroy_nolock(f->callno);
1142                                                 }
1143                                         }
1144
1145                                 }
1146                                 freeme++;
1147                 } else {
1148                         /* Attempt transmission */
1149                         send_packet(f);
1150                         f->retries++;
1151                         /* Try again later after 10 times as long */
1152                         f->retrytime *= 10;
1153                         if (f->retrytime > MAX_RETRY_TIME)
1154                                 f->retrytime = MAX_RETRY_TIME;
1155                         /* Transfer messages max out at one second */
1156                         if (f->transfer && (f->retrytime > 1000))
1157                                 f->retrytime = 1000;
1158                         f->retrans = ast_sched_add(sched, f->retrytime, attempt_transmit, f);
1159                 }
1160         } else {
1161                 /* Make sure it gets freed */
1162                 f->retries = -1;
1163                 freeme++;
1164         }
1165         if (callno > -1)
1166                 ast_mutex_unlock(&iaxsl[callno]);
1167         /* Do not try again */
1168         if (freeme) {
1169                 /* Don't attempt delivery, just remove it from the queue */
1170                 ast_mutex_lock(&iaxq.lock);
1171                 if (f->prev) 
1172                         f->prev->next = f->next;
1173                 else
1174                         iaxq.head = f->next;
1175                 if (f->next)
1176                         f->next->prev = f->prev;
1177                 else
1178                         iaxq.tail = f->prev;
1179                 iaxq.count--;
1180                 ast_mutex_unlock(&iaxq.lock);
1181                 /* Free the frame */
1182                 ast_frfree(f->f);
1183                 f->retrans = -1;
1184                 ast_iax_frame_free(f);
1185         }
1186         return 0;
1187 }
1188
1189 static int iax_set_jitter(int fd, int argc, char *argv[])
1190 {
1191         if ((argc != 4) && (argc != 5))
1192                 return RESULT_SHOWUSAGE;
1193         if (argc == 4) {
1194                 max_jitter_buffer = atoi(argv[3]);
1195                 if (max_jitter_buffer < 0)
1196                         max_jitter_buffer = 0;
1197         } else {
1198                 if (argc == 5) {
1199                         if ((atoi(argv[3]) >= 0) && (atoi(argv[3]) < AST_IAX_MAX_CALLS)) {
1200                                 if (iaxs[atoi(argv[3])]) {
1201                                         iaxs[atoi(argv[3])]->jitterbuffer = atoi(argv[4]);
1202                                         if (iaxs[atoi(argv[3])]->jitterbuffer < 0)
1203                                                 iaxs[atoi(argv[3])]->jitterbuffer = 0;
1204                                 } else
1205                                         ast_cli(fd, "No such call '%d'\n", atoi(argv[3]));
1206                         } else
1207                                 ast_cli(fd, "%d is not a valid call number\n", atoi(argv[3]));
1208                 }
1209         }
1210         return RESULT_SUCCESS;
1211 }
1212
1213 static char jitter_usage[] = 
1214 "Usage: iax set jitter [callid] <value>\n"
1215 "       If used with a callid, it sets the jitter buffer to the given static\n"
1216 "value (until its next calculation).  If used without a callid, the value is used\n"
1217 "to establish the maximum excess jitter buffer that is permitted before the jitter\n"
1218 "buffer size is reduced.";
1219
1220 static int iax_show_stats(int fd, int argc, char *argv[])
1221 {
1222         struct ast_iax_frame *cur;
1223         int cnt = 0, dead=0, final=0;
1224         if (argc != 3)
1225                 return RESULT_SHOWUSAGE;
1226         for (cur = iaxq.head; cur ; cur = cur->next) {
1227                 if (cur->retries < 0)
1228                         dead++;
1229                 if (cur->final)
1230                         final++;
1231                 cnt++;
1232         }
1233         ast_cli(fd, "    IAX Statistics\n");
1234         ast_cli(fd, "---------------------\n");
1235         ast_cli(fd, "Outstanding frames: %d (%d ingress, %d outgress)\n", frames, iframes, oframes);
1236         ast_cli(fd, "Packets in transmit queue: %d dead, %d final, %d total\n", dead, final, cnt);
1237         return RESULT_SUCCESS;
1238 }
1239
1240 static int iax_show_cache(int fd, int argc, char *argv[])
1241 {
1242         struct iax_dpcache *dp;
1243         char tmp[1024], *pc;
1244         int s;
1245         int x,y;
1246         struct timeval tv;
1247         gettimeofday(&tv, NULL);
1248         ast_mutex_lock(&dpcache_lock);
1249         dp = dpcache;
1250         ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
1251         while(dp) {
1252                 s = dp->expirey.tv_sec - tv.tv_sec;
1253                 strcpy(tmp, "");
1254                 if (dp->flags & CACHE_FLAG_EXISTS)
1255                         strcat(tmp, "EXISTS|");
1256                 if (dp->flags & CACHE_FLAG_NONEXISTANT)
1257                         strcat(tmp, "NONEXISTANT|");
1258                 if (dp->flags & CACHE_FLAG_CANEXIST)
1259                         strcat(tmp, "CANEXIST|");
1260                 if (dp->flags & CACHE_FLAG_PENDING)
1261                         strcat(tmp, "PENDING|");
1262                 if (dp->flags & CACHE_FLAG_TIMEOUT)
1263                         strcat(tmp, "TIMEOUT|");
1264                 if (dp->flags & CACHE_FLAG_TRANSMITTED)
1265                         strcat(tmp, "TRANSMITTED|");
1266                 if (dp->flags & CACHE_FLAG_MATCHMORE)
1267                         strcat(tmp, "MATCHMORE|");
1268                 if (dp->flags & CACHE_FLAG_UNKNOWN)
1269                         strcat(tmp, "UNKNOWN|");
1270                 /* Trim trailing pipe */
1271                 if (strlen(tmp))
1272                         tmp[strlen(tmp) - 1] = '\0';
1273                 else
1274                         strcpy(tmp, "(none)");
1275                 y=0;
1276                 pc = strchr(dp->peercontext, '@');
1277                 if (!pc)
1278                         pc = dp->peercontext;
1279                 else
1280                         pc++;
1281                 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
1282                         if (dp->waiters[x] > -1)
1283                                 y++;
1284                 if (s > 0)
1285                         ast_cli(fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
1286                 else
1287                         ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
1288                 dp = dp->next;
1289         }
1290         ast_mutex_unlock(&dpcache_lock);
1291         return RESULT_SUCCESS;
1292 }
1293
1294 static char show_stats_usage[] =
1295 "Usage: iax1 show stats\n"
1296 "       Display statistics on IAX channel driver.\n";
1297
1298
1299 static char show_cache_usage[] =
1300 "Usage: iax1 show cache\n"
1301 "       Display currently cached IAX Dialplan results.\n";
1302
1303 static struct ast_cli_entry cli_set_jitter = 
1304 { { "iax1", "set", "jitter", NULL }, iax_set_jitter, "Sets IAX jitter buffer", jitter_usage };
1305
1306 static struct ast_cli_entry cli_show_stats =
1307 { { "iax1", "show", "stats", NULL }, iax_show_stats, "Display IAX statistics", show_stats_usage };
1308
1309 static struct ast_cli_entry cli_show_cache =
1310 { { "iax1", "show", "cache", NULL }, iax_show_cache, "Display IAX cached dialplan", show_cache_usage };
1311
1312 static unsigned int calc_rxstamp(struct chan_iax_pvt *p);
1313
1314 #ifdef BRIDGE_OPTIMIZATION
1315 static unsigned int calc_fakestamp(struct chan_iax_pvt *from, struct chan_iax_pvt *to, unsigned int ts);
1316
1317 static int forward_delivery(struct ast_iax_frame *fr)
1318 {
1319         struct chan_iax_pvt *p1, *p2;
1320         p1 = iaxs[fr->callno];
1321         p2 = iaxs[p1->bridgecallno];
1322         if (!p1)
1323                 return -1;
1324         if (!p2)
1325                 return -1;
1326         /* Fix relative timestamp */
1327         fr->ts = calc_fakestamp(p1, p2, fr->ts);
1328         /* Now just send it send on the 2nd one 
1329            with adjusted timestamp */
1330         return iax_send(p2, fr->f, fr->ts, -1, 0, 0, 0);
1331 }
1332 #endif
1333
1334 static int schedule_delivery(struct ast_iax_frame *fr, int reallydeliver)
1335 {
1336         int ms,x;
1337         int drops[MEMORY_SIZE];
1338         int min, max=0, maxone=0,y,z, match;
1339         /* ms is a measure of the "lateness" of the packet relative to the first
1340            packet we received, which always has a lateness of 1.  Called by
1341            IAX thread, with iaxsl lock held. */
1342         ms = calc_rxstamp(iaxs[fr->callno]) - fr->ts;
1343
1344         if (ms > 32767) {
1345                 /* What likely happened here is that our counter has circled but we haven't
1346                    gotten the update from the main packet.  We'll just pretend that we did, and
1347                    update the timestamp appropriately. */
1348                 ms -= 65536;
1349         }
1350
1351         if (ms < -32768) {
1352                 /* We got this packet out of order.  Lets add 65536 to it to bring it into our new
1353                    time frame */
1354                 ms += 65536;
1355         }
1356         
1357         /* Rotate our history queue of "lateness".  Don't worry about those initial
1358            zeros because the first entry will always be zero */
1359         for (x=0;x<MEMORY_SIZE - 1;x++) 
1360                 iaxs[fr->callno]->history[x] = iaxs[fr->callno]->history[x+1];
1361         /* Add a history entry for this one */
1362         iaxs[fr->callno]->history[x] = ms;
1363
1364         /* Initialize the minimum to reasonable values.  It's too much
1365            work to do the same for the maximum, repeatedly */
1366         min=iaxs[fr->callno]->history[0];
1367         for (z=0;z < iax_dropcount + 1;z++) {
1368                 /* Start very optimistic ;-) */
1369                 max=-999999999;
1370                 for (x=0;x<MEMORY_SIZE;x++) {
1371                         if (max < iaxs[fr->callno]->history[x]) {
1372                                 /* We have a candidate new maximum value.  Make
1373                                    sure it's not in our drop list */
1374                                 match = 0;
1375                                 for (y=0;!match && (y<z);y++)
1376                                         match |= (drops[y] == x);
1377                                 if (!match) {
1378                                         /* It's not in our list, use it as the new maximum */
1379                                         max = iaxs[fr->callno]->history[x];
1380                                         maxone = x;
1381                                 }
1382                                 
1383                         }
1384                         if (!z) {
1385                                 /* On our first pass, find the minimum too */
1386                                 if (min > iaxs[fr->callno]->history[x])
1387                                         min = iaxs[fr->callno]->history[x];
1388                         }
1389                 }
1390 #if 1
1391                 drops[z] = maxone;
1392 #endif
1393         }
1394         /* Just for reference, keep the "jitter" value, the difference between the
1395            earliest and the latest. */
1396         iaxs[fr->callno]->jitter = max - min;   
1397         
1398         /* IIR filter for keeping track of historic jitter, but always increase
1399            historic jitter immediately for increase */
1400         
1401         if (iaxs[fr->callno]->jitter > iaxs[fr->callno]->historicjitter )
1402                 iaxs[fr->callno]->historicjitter = iaxs[fr->callno]->jitter;
1403         else
1404                 iaxs[fr->callno]->historicjitter = GAMMA * (double)iaxs[fr->callno]->jitter + (1-GAMMA) * 
1405                         iaxs[fr->callno]->historicjitter;
1406
1407         /* If our jitter buffer is too big (by a significant margin), then we slowly
1408            shrink it by about 1 ms each time to avoid letting the change be perceived */
1409         if (max < iaxs[fr->callno]->jitterbuffer - max_jitter_buffer)
1410                 iaxs[fr->callno]->jitterbuffer -= 2;
1411
1412
1413 #if 1
1414         /* Constrain our maximum jitter buffer appropriately */
1415         if (max > min + maxjitterbuffer) {
1416                 if (option_debug)
1417                         ast_log(LOG_DEBUG, "Constraining buffer from %d to %d + %d\n", max, min , maxjitterbuffer);
1418                 max = min + maxjitterbuffer;
1419         }
1420 #endif
1421
1422         /* If our jitter buffer is smaller than our maximum delay, grow the jitter
1423            buffer immediately to accomodate it (and a little more).  */
1424         if (max > iaxs[fr->callno]->jitterbuffer)
1425                 iaxs[fr->callno]->jitterbuffer = max 
1426                         /* + ((float)iaxs[fr->callno]->jitter) * 0.1 */;
1427                 
1428
1429         if (option_debug)
1430                 ast_log(LOG_DEBUG, "min = %d, max = %d, jb = %d, lateness = %d\n", min, max, iaxs[fr->callno]->jitterbuffer, ms);
1431         
1432         /* Subtract the lateness from our jitter buffer to know how long to wait
1433            before sending our packet.  */
1434         ms = iaxs[fr->callno]->jitterbuffer - ms;
1435         
1436         if (!use_jitterbuffer)
1437                 ms = 0;
1438
1439         /* If the caller just wanted us to update, return now */
1440         if (!reallydeliver)
1441                 return 0;
1442                 
1443         if (ms < 1) {
1444                 if (option_debug)
1445                         ast_log(LOG_DEBUG, "Calculated ms is %d\n", ms);
1446                 /* Don't deliver it more than 4 ms late */
1447                 if ((ms > -4) || (fr->f->frametype != AST_FRAME_VOICE)) {
1448                         __do_deliver(fr);
1449                 } else {
1450                         if (option_debug)
1451                                 ast_log(LOG_DEBUG, "Dropping voice packet since %d ms is, too old\n", ms);
1452                         /* Free the packet */
1453                         ast_frfree(fr->f);
1454                         /* And our iax frame */
1455                         ast_iax_frame_free(fr);
1456                 }
1457         } else {
1458                 if (option_debug)
1459                         ast_log(LOG_DEBUG, "Scheduling delivery in %d ms\n", ms);
1460                 fr->retrans = ast_sched_add(sched, ms, do_deliver, fr);
1461         }
1462         return 0;
1463 }
1464
1465 static int iax_transmit(struct ast_iax_frame *fr)
1466 {
1467         /* Lock the queue and place this packet at the end */
1468         fr->next = NULL;
1469         fr->prev = NULL;
1470         /* By setting this to 0, the network thread will send it for us, and
1471            queue retransmission if necessary */
1472         fr->sentyet = 0;
1473         ast_mutex_lock(&iaxq.lock);
1474         if (!iaxq.head) {
1475                 /* Empty queue */
1476                 iaxq.head = fr;
1477                 iaxq.tail = fr;
1478         } else {
1479                 /* Double link */
1480                 iaxq.tail->next = fr;
1481                 fr->prev = iaxq.tail;
1482                 iaxq.tail = fr;
1483         }
1484         iaxq.count++;
1485         ast_mutex_unlock(&iaxq.lock);
1486         /* Wake up the network thread */
1487         pthread_kill(netthreadid, SIGURG);
1488         return 0;
1489 }
1490
1491
1492
1493 static int iax_digit(struct ast_channel *c, char digit)
1494 {
1495         return send_command(c->pvt->pvt, AST_FRAME_DTMF, digit, 0, NULL, 0, -1);
1496 }
1497
1498 static int iax_sendtext(struct ast_channel *c, char *text)
1499 {
1500         
1501         return send_command(c->pvt->pvt, AST_FRAME_TEXT,
1502                 0, 0, text, strlen(text) + 1, -1);
1503 }
1504
1505 static int iax_sendimage(struct ast_channel *c, struct ast_frame *img)
1506 {
1507         return send_command(c->pvt->pvt, AST_FRAME_IMAGE, img->subclass, 0, img->data, img->datalen, -1);
1508 }
1509
1510 static int iax_sendhtml(struct ast_channel *c, int subclass, char *data, int datalen)
1511 {
1512         return send_command(c->pvt->pvt, AST_FRAME_HTML, subclass, 0, data, datalen, -1);
1513 }
1514
1515 static int iax_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
1516 {
1517         struct chan_iax_pvt *pvt = newchan->pvt->pvt;
1518         pvt->owner = newchan;
1519         return 0;
1520 }
1521
1522 #ifdef MYSQL_FRIENDS
1523
1524 static void mysql_update_peer(char *peer, struct sockaddr_in *sin)
1525 {
1526         if (mysql && (strlen(peer) < 128)) {
1527                 char query[512];
1528                 char *name;
1529                 time_t nowtime;
1530                 name = alloca(strlen(peer) * 2 + 1);
1531                 time(&nowtime);
1532                 mysql_real_escape_string(mysql, name, peer, strlen(peer));
1533                 snprintf(query, sizeof(query), "UPDATE iax1friends SET ipaddr=\"%s\", port=\"%d\", regseconds=\"%ld\" WHERE name=\"%s\"", 
1534                         inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), nowtime, name);
1535                 ast_mutex_lock(&mysqllock);
1536                 if (mysql_real_query(mysql, query, strlen(query))) 
1537                         ast_log(LOG_WARNING, "Unable to update database\n");
1538                         
1539                 ast_mutex_unlock(&mysqllock);
1540         }
1541 }
1542
1543 static struct iax_peer *mysql_peer(char *peer)
1544 {
1545         struct iax_peer *p;
1546         int success = 0;
1547         
1548         p = malloc(sizeof(struct iax_peer));
1549         memset(p, 0, sizeof(struct iax_peer));
1550         if (mysql && (strlen(peer) < 128)) {
1551                 char query[512];
1552                 char *name;
1553                 int numfields, x;
1554                 int port;
1555                 time_t regseconds, nowtime;
1556                 MYSQL_RES *result;
1557                 MYSQL_FIELD *fields;
1558                 MYSQL_ROW rowval;
1559                 name = alloca(strlen(peer) * 2 + 1);
1560                 mysql_real_escape_string(mysql, name, peer, strlen(peer));
1561                 snprintf(query, sizeof(query), "SELECT name, secret, context, ipaddr, port, regseconds FROM iax1friends WHERE name=\"%s\"", name);
1562                 ast_mutex_lock(&mysqllock);
1563                 mysql_query(mysql, query);
1564                 if ((result = mysql_store_result(mysql))) {
1565                         if ((rowval = mysql_fetch_row(result))) {
1566                                 numfields = mysql_num_fields(result);
1567                                 fields = mysql_fetch_fields(result);
1568                                 success = 1;
1569                                 for (x=0;x<numfields;x++) {
1570                                         if (rowval[x]) {
1571                                                 if (!strcasecmp(fields[x].name, "secret")) {
1572                                                         strncpy(p->secret, rowval[x], sizeof(p->secret));
1573                                                 } else if (!strcasecmp(fields[x].name, "context")) {
1574                                                         strncpy(p->context, rowval[x], sizeof(p->context) - 1);
1575                                                 } else if (!strcasecmp(fields[x].name, "ipaddr")) {
1576                                                         inet_aton(rowval[x], &p->addr.sin_addr);
1577                                                 } else if (!strcasecmp(fields[x].name, "port")) {
1578                                                         if (sscanf(rowval[x], "%i", &port) != 1)
1579                                                                 port = 0;
1580                                                         p->addr.sin_port = htons(port);
1581                                                 } else if (!strcasecmp(fields[x].name, "regseconds")) {
1582                                                         if (sscanf(rowval[x], "%li", &regseconds) != 1)
1583                                                                 regseconds = 0;
1584                                                 }
1585                                         }
1586                                 }
1587                                 time(&nowtime);
1588                                 if ((nowtime - regseconds) > AST_DEFAULT_REG_EXPIRE) 
1589                                         memset(&p->addr, 0, sizeof(p->addr));
1590                         }
1591                 }
1592                 ast_mutex_unlock(&mysqllock);
1593         }
1594         if (!success) {
1595                 free(p);
1596                 p = NULL;
1597         } else {
1598                 strncpy(p->name, peer, sizeof(p->name) - 1);
1599                 p->dynamic = 1;
1600                 p->delme = 1;
1601                 p->expire = -1;
1602                 p->capability = iax_capability;
1603                 strcpy(p->methods, "md5,plaintext");
1604         }
1605         return p;
1606 }
1607
1608 static struct iax_user *mysql_user(char *user)
1609 {
1610         struct iax_user *p;
1611         struct iax_context *con;
1612         int success = 0;
1613         
1614         p = malloc(sizeof(struct iax_user));
1615         memset(p, 0, sizeof(struct iax_user));
1616         con = malloc(sizeof(struct iax_context));
1617         memset(con, 0, sizeof(struct iax_context));
1618         strcpy(con->context, "default");
1619         p->contexts = con;
1620         if (mysql && (strlen(user) < 128)) {
1621                 char query[512];
1622                 char *name;
1623                 int numfields, x;
1624                 MYSQL_RES *result;
1625                 MYSQL_FIELD *fields;
1626                 MYSQL_ROW rowval;
1627                 name = alloca(strlen(user) * 2 + 1);
1628                 mysql_real_escape_string(mysql, name, user, strlen(user));
1629                 snprintf(query, sizeof(query), "SELECT name, secret, context, ipaddr, port, regseconds FROM iax1friends WHERE name=\"%s\"", name);
1630                 ast_mutex_lock(&mysqllock);
1631                 mysql_query(mysql, query);
1632                 if ((result = mysql_store_result(mysql))) {
1633                         if ((rowval = mysql_fetch_row(result))) {
1634                                 numfields = mysql_num_fields(result);
1635                                 fields = mysql_fetch_fields(result);
1636                                 success = 1;
1637                                 for (x=0;x<numfields;x++) {
1638                                         if (rowval[x]) {
1639                                                 if (!strcasecmp(fields[x].name, "secret")) {
1640                                                         strncpy(p->secret, rowval[x], sizeof(p->secret));
1641                                                 } else if (!strcasecmp(fields[x].name, "context")) {
1642                                                         strncpy(p->contexts->context, rowval[x], sizeof(p->contexts->context) - 1);
1643                                                 }
1644                                         }
1645                                 }
1646                         }
1647                 }
1648                 ast_mutex_unlock(&mysqllock);
1649         }
1650         if (!success) {
1651                 if (p->contexts)
1652                         free(p->contexts);
1653                 free(p);
1654                 p = NULL;
1655         } else {
1656                 strncpy(p->name, user, sizeof(p->name) - 1);
1657                 p->delme = 1;
1658                 strcpy(p->methods, "md5,plaintext");
1659         }
1660         return p;
1661 }
1662 #endif /* MYSQL_FRIENDS */
1663
1664 static int create_addr(struct sockaddr_in *sin, int *capability, int *sendani, int *maxtime, char *peer, char *context)
1665 {
1666         struct ast_hostent ahp; struct hostent *hp;
1667         struct iax_peer *p;
1668         int found=0;
1669         if (sendani)
1670                 *sendani = 0;
1671         if (maxtime)
1672                 *maxtime = 0;
1673         sin->sin_family = AF_INET;
1674         ast_mutex_lock(&peerl.lock);
1675         p = peerl.peers;
1676         while(p) {
1677                 if (!strcasecmp(p->name, peer)) {
1678                         break;
1679                 }
1680                 p = p->next;
1681         }
1682 #ifdef MYSQL_FRIENDS
1683         if (!p)
1684                 p = mysql_peer(peer);
1685 #endif          
1686         if (p) {
1687                 found++;
1688                 if (capability)
1689                         *capability = p->capability;
1690                 if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
1691                         (!p->maxms || ((p->lastms > 0)  && (p->lastms <= p->maxms)))) {
1692                         if (sendani)
1693                                 *sendani = p->sendani;          /* Whether we transmit ANI */
1694                         if (maxtime)
1695                                 *maxtime = p->maxms;            /* Max time they should take */
1696                         if (context)
1697                                 strncpy(context, p->context, AST_MAX_EXTENSION - 1);
1698                         if (p->addr.sin_addr.s_addr) {
1699                                 sin->sin_addr = p->addr.sin_addr;
1700                                 sin->sin_port = p->addr.sin_port;
1701                         } else {
1702                                 sin->sin_addr = p->defaddr.sin_addr;
1703                                 sin->sin_port = p->defaddr.sin_port;
1704                         }
1705                 } else {
1706                         if (p->delme) 
1707                                 free(p);
1708                         p = NULL;
1709                 }
1710         }
1711         ast_mutex_unlock(&peerl.lock);
1712         if (!p && !found) {
1713                 hp = ast_gethostbyname(peer, &ahp);
1714                 if (hp) {
1715                         memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
1716                         sin->sin_port = htons(AST_DEFAULT_IAX_PORTNO);
1717                         return 0;
1718                 } else {
1719                         ast_log(LOG_WARNING, "No such host: %s\n", peer);
1720                         return -1;
1721                 }
1722         } else if (!p)
1723                 return -1;
1724         if (p->delme)
1725                 free(p);
1726         return 0;
1727 }
1728
1729 static int auto_congest(void *nothing)
1730 {
1731         int callno = (int)(long)(nothing);
1732         struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_CONGESTION };
1733         ast_mutex_lock(&iaxsl[callno]);
1734         if (iaxs[callno]) {
1735                 iaxs[callno]->initid = -1;
1736                 iax_queue_frame(callno, &f);
1737                 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
1738         }
1739         ast_mutex_unlock(&iaxsl[callno]);
1740         return 0;
1741 }
1742
1743 static int iax_call(struct ast_channel *c, char *dest, int timeout)
1744 {
1745         struct sockaddr_in sin;
1746         char host[256];
1747         char *rdest;
1748         char *rcontext;
1749         char *username;
1750         char *secret = NULL;
1751         char *hname;
1752         char requeststr[256] = "";
1753         char myrdest [5] = "s";
1754         char context[AST_MAX_EXTENSION] ="";
1755         char *portno = NULL;
1756         struct chan_iax_pvt *p = c->pvt->pvt;
1757         char *stringp=NULL;
1758         if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
1759                 ast_log(LOG_WARNING, "Line is already in use (%s)?\n", c->name);
1760                 return -1;
1761         }
1762         strncpy(host, dest, sizeof(host)-1);
1763         stringp=host;
1764         strsep(&stringp, "/");
1765         /* If no destination extension specified, use 's' */
1766         rdest = strsep(&stringp, "/");
1767         if (!rdest) 
1768                 rdest = myrdest;
1769         stringp=rdest;
1770         strsep(&stringp, "@");
1771         rcontext = strsep(&stringp, "@");
1772         stringp=host;
1773         strsep(&stringp, "@");
1774         username = strsep(&stringp, "@");
1775         if (username) {
1776                 /* Really the second argument is the host, not the username */
1777                 hname = username;
1778                 username = host;
1779         } else {
1780                 hname = host;
1781         }
1782         if (username) {
1783                 stringp=username;
1784                 username = strsep(&stringp, ":");
1785                 secret = strsep(&stringp, ":");
1786         }
1787         stringp=hname;
1788         if (strsep(&stringp, ":")) {
1789                 stringp=hname;
1790                 strsep(&stringp, ":");
1791                 portno = strsep(&stringp, ":");
1792         }
1793         if (create_addr(&sin, NULL, NULL, NULL, hname, context)) {
1794                 ast_log(LOG_WARNING, "No address associated with '%s'\n", hname);
1795                 return -1;
1796         }
1797         /* Keep track of the context for outgoing calls too */
1798         strncpy(c->context, context, sizeof(c->context) - 1);
1799         if (portno) {
1800                 sin.sin_port = htons(atoi(portno));
1801         }
1802         /* Now we build our request string */
1803 #define MYSNPRINTF snprintf(requeststr + strlen(requeststr), sizeof(requeststr) - strlen(requeststr), 
1804 #define MYSNPRINTF2 snprintf(requeststr + strlen(requeststr), reqsize - strlen(requeststr), 
1805         MYSNPRINTF "exten=%s;", rdest);
1806         if (c->callerid)
1807                 MYSNPRINTF "callerid=%s;", c->callerid);
1808         if (p->sendani && c->ani)
1809                 MYSNPRINTF "ani=%s;", c->ani);
1810         if (c->language && strlen(c->language))
1811                 MYSNPRINTF "language=%s;", c->language);
1812         if (c->dnid)
1813                 MYSNPRINTF "dnid=%s;", c->dnid);
1814         if (rcontext)
1815                 MYSNPRINTF "context=%s;", rcontext);
1816         if (username)
1817                 MYSNPRINTF "username=%s;", username);
1818         if (secret) {
1819                 if (secret[0] == '[') {
1820                         /* This is an RSA key, not a normal secret */
1821                         strncpy(p->outkey, secret + 1, sizeof(p->secret)-1);
1822                         if (strlen(p->outkey)) {
1823                                 p->outkey[strlen(p->outkey) - 1] = '\0';
1824                         }
1825                 } else
1826                         strncpy(p->secret, secret, sizeof(p->secret)-1);
1827         }
1828         MYSNPRINTF "formats=%d;", c->nativeformats);
1829         MYSNPRINTF "capability=%d;", p->capability);
1830         MYSNPRINTF "version=%d;", AST_IAX_PROTO_VERSION);
1831         MYSNPRINTF "adsicpe=%d;", c->adsicpe);
1832         /* Trim the trailing ";" */
1833         if (strlen(requeststr))
1834                 requeststr[strlen(requeststr) - 1] = '\0';
1835         /* Transmit the string in a "NEW" request */
1836         if (option_verbose > 2)
1837                 ast_verbose(VERBOSE_PREFIX_3 "Calling using options '%s'\n", requeststr);
1838         if (p->maxtime) {
1839                 /* Initialize pingtime and auto-congest time */
1840                 p->pingtime = p->maxtime / 2;
1841                 p->initid = ast_sched_add(sched, p->maxtime * 2, auto_congest, (void *)p->callno);
1842         }
1843         send_command(p, AST_FRAME_IAX,
1844                 AST_IAX_COMMAND_NEW, 0, requeststr, strlen(requeststr) + 1, -1);
1845         ast_setstate(c, AST_STATE_RINGING);
1846         return 0;
1847 }
1848
1849 static int iax_hangup(struct ast_channel *c) 
1850 {
1851         struct chan_iax_pvt *pvt = c->pvt->pvt;
1852         int alreadygone;
1853         int callno;
1854         if (pvt) {
1855                 callno = pvt->callno;
1856                 ast_mutex_lock(&iaxsl[callno]);
1857                 ast_log(LOG_DEBUG, "We're hanging up %s now...\n", c->name);
1858                 alreadygone = pvt->alreadygone;
1859                 /* Send the hangup unless we have had a transmission error or are already gone */
1860                 if (!pvt->error && !alreadygone) 
1861                         send_command_final(pvt, AST_FRAME_IAX, AST_IAX_COMMAND_HANGUP, 0, NULL, 0, -1);
1862                 /* Explicitly predestroy it */
1863                 iax_predestroy_nolock(callno);
1864                 /* If we were already gone to begin with, destroy us now */
1865                 if (alreadygone) {
1866                         ast_log(LOG_DEBUG, "Really destroying %s now...\n", c->name);
1867                         iax_destroy_nolock(callno);
1868                 }
1869                 ast_mutex_unlock(&iaxsl[callno]);
1870         }
1871         if (option_verbose > 2) 
1872                 ast_verbose(VERBOSE_PREFIX_3 "Hungup '%s'\n", c->name);
1873         return 0;
1874 }
1875
1876 static int iax_setoption(struct ast_channel *c, int option, void *data, int datalen)
1877 {
1878         struct ast_option_header *h;
1879         int res;
1880         h = malloc(datalen + sizeof(struct ast_option_header));
1881         if (h) {
1882                 h->flag = AST_OPTION_FLAG_REQUEST;
1883                 h->option = htons(option);
1884                 memcpy(h->data, data, datalen);
1885                 res = send_command((struct chan_iax_pvt *)c->pvt->pvt, AST_FRAME_CONTROL,
1886                         AST_CONTROL_OPTION, 0, (char *)h, datalen + sizeof(struct ast_option_header), -1);
1887                 free(h);
1888                 return res;
1889         } else 
1890                 ast_log(LOG_WARNING, "Out of memory\n");
1891         return -1;
1892 }
1893 static struct ast_frame *iax_read(struct ast_channel *c) 
1894 {
1895         static struct ast_frame f = { AST_FRAME_NULL, };
1896         ast_log(LOG_NOTICE, "I should never be called!\n");
1897         return &f;
1898 }
1899
1900 static int iax_start_transfer(struct ast_channel *c0, struct ast_channel *c1)
1901 {
1902         int res;
1903         char req0[256];
1904         char req1[256];
1905         struct chan_iax_pvt *p0 = c0->pvt->pvt;
1906         struct chan_iax_pvt *p1 = c1->pvt->pvt;
1907         snprintf(req0, sizeof(req0), "remip=%s;remport=%d;remcall=%d;", inet_ntoa(p1->addr.sin_addr), ntohs(p1->addr.sin_port), p1->peercallno);
1908         snprintf(req1, sizeof(req1), "remip=%s;remport=%d;remcall=%d;", inet_ntoa(p0->addr.sin_addr), ntohs(p0->addr.sin_port), p0->peercallno);
1909         res = send_command(p0, AST_FRAME_IAX, AST_IAX_COMMAND_TXREQ, 0, req0, strlen(req0) + 1, -1);
1910         if (res)
1911                 return -1;
1912         res = send_command(p1, AST_FRAME_IAX, AST_IAX_COMMAND_TXREQ, 0, req1, strlen(req1) + 1, -1);
1913         if (res)
1914                 return -1;
1915         p0->transferring = TRANSFER_BEGIN;
1916         p1->transferring = TRANSFER_BEGIN;
1917         return 0;
1918 }
1919
1920 static int iax_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
1921 {
1922         struct ast_channel *cs[3];
1923         struct ast_channel *who;
1924         int to = -1;
1925         int res = -1;
1926         int transferstarted=0;
1927         struct ast_frame *f;
1928         struct chan_iax_pvt *p0 = c0->pvt->pvt;
1929         struct chan_iax_pvt *p1 = c1->pvt->pvt;
1930
1931         /* Put them in native bridge mode */
1932         p0->bridgecallno = p1->callno;
1933         p1->bridgecallno = p0->callno;
1934
1935         /* If not, try to bridge until we can execute a transfer, if we can */
1936         cs[0] = c0;
1937         cs[1] = c1;
1938         for (/* ever */;;) {
1939                 /* Check in case we got masqueraded into */
1940                 if ((c0->type != type) || (c1->type != type)) {
1941                         if (option_verbose > 2)
1942                                 ast_verbose(VERBOSE_PREFIX_3 "Can't masquerade, we're different...\n");
1943                         return -2;
1944                 }
1945                 if (c0->nativeformats != c1->nativeformats) {
1946                         ast_verbose(VERBOSE_PREFIX_3 "Operating with different codecs, can't native bridge...\n");
1947                         return -2;
1948                 }
1949                 if (!transferstarted) {
1950                         /* Try the transfer */
1951                         if (iax_start_transfer(c0, c1))
1952                                 ast_log(LOG_WARNING, "Unable to start the transfer\n");
1953                         transferstarted = 1;
1954                 }
1955                 
1956                 if ((p0->transferring == TRANSFER_RELEASED) && (p1->transferring == TRANSFER_RELEASED)) {
1957                         /* Call has been transferred.  We're no longer involved */
1958                         sleep(1);
1959                         c0->_softhangup |= AST_SOFTHANGUP_DEV;
1960                         c1->_softhangup |= AST_SOFTHANGUP_DEV;
1961                         *fo = NULL;
1962                         *rc = c0;
1963                         res = 0;
1964                         break;
1965                 }
1966                 to = 1000;
1967                 who = ast_waitfor_n(cs, 2, &to);
1968                 if (!who) {
1969                         if (ast_check_hangup(c0) || ast_check_hangup(c1)) {
1970                                 res = -1;
1971                                 break;
1972                         }
1973                         continue;
1974                 }
1975                 f = ast_read(who);
1976                 if (!f) {
1977                         *fo = NULL;
1978                         *rc = who;
1979                         res = 0;
1980                         break;
1981                 }
1982                 if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
1983                         *fo = f;
1984                         *rc = who;
1985                         res =  0;
1986                         break;
1987                 }
1988                 if ((f->frametype == AST_FRAME_VOICE) ||
1989                         (f->frametype == AST_FRAME_TEXT) ||
1990                         (f->frametype == AST_FRAME_VIDEO) || 
1991                         (f->frametype == AST_FRAME_IMAGE) ||
1992                         (f->frametype == AST_FRAME_DTMF)) {
1993                         if ((f->frametype == AST_FRAME_DTMF) && 
1994                                 (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
1995                                 if ((who == c0)) {
1996                                         if  ((flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
1997                                                 *rc = c0;
1998                                                 *fo = f;
1999                                                 /* Take out of conference mode */
2000                                                 res = 0;
2001                                                 break;
2002                                         } else 
2003                                                 goto tackygoto;
2004                                 } else
2005                                 if ((who == c1)) {
2006                                         if (flags & AST_BRIDGE_DTMF_CHANNEL_1) {
2007                                                 *rc = c1;
2008                                                 *fo = f;
2009                                                 res =  0;
2010                                                 break;
2011                                         } else
2012                                                 goto tackygoto;
2013                                 }
2014                         } else {
2015 #if 0
2016                                 ast_log(LOG_DEBUG, "Read from %s\n", who->name);
2017                                 if (who == last) 
2018                                         ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
2019                                 last = who;
2020 #endif
2021 tackygoto:
2022                                 if (who == c0) 
2023                                         ast_write(c1, f);
2024                                 else 
2025                                         ast_write(c0, f);
2026                         }
2027                         ast_frfree(f);
2028                 } else
2029                         ast_frfree(f);
2030                 /* Swap who gets priority */
2031                 cs[2] = cs[0];
2032                 cs[0] = cs[1];
2033                 cs[1] = cs[2];
2034         }
2035         p0->bridgecallno = -1;
2036         p1->bridgecallno = -1;
2037         return res;
2038 }
2039
2040 static int iax_answer(struct ast_channel *c)
2041 {
2042         struct chan_iax_pvt *pvt = c->pvt->pvt;
2043         if (option_debug)
2044                 ast_log(LOG_DEBUG, "Answering\n");
2045         return send_command(pvt, AST_FRAME_CONTROL, AST_CONTROL_ANSWER, 0, NULL, 0, -1);
2046 }
2047
2048 static int iax_indicate(struct ast_channel *c, int condition)
2049 {
2050         struct chan_iax_pvt *pvt = c->pvt->pvt;
2051         if (option_debug)
2052                 ast_log(LOG_DEBUG, "Indicating condition %d\n", condition);
2053         return send_command(pvt, AST_FRAME_CONTROL, condition, 0, NULL, 0, -1);
2054 }
2055         
2056
2057 static int iax_write(struct ast_channel *c, struct ast_frame *f);
2058
2059 static int iax_getpeername(struct sockaddr_in sin, char *host, int len)
2060 {
2061         struct iax_peer *peer;
2062         int res = 0;
2063         ast_mutex_lock(&peerl.lock);
2064         peer = peerl.peers;
2065         while(peer) {
2066                 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
2067                                 (peer->addr.sin_port == sin.sin_port)) {
2068                                         strncpy(host, peer->name, len-1);
2069                                         res = 1;
2070                                         break;
2071                 }
2072                 peer = peer->next;
2073         }
2074         ast_mutex_unlock(&peerl.lock);
2075         return res;
2076 }
2077
2078 static struct ast_channel *ast_iax_new(struct chan_iax_pvt *i, int state, int capability)
2079 {
2080         char host[256];
2081         struct ast_channel *tmp;
2082         tmp = ast_channel_alloc(1);
2083         if (tmp) {
2084                 if (!iax_getpeername(i->addr, host, sizeof(host)))
2085                         snprintf(host, sizeof(host), "%s:%d", inet_ntoa(i->addr.sin_addr), ntohs(i->addr.sin_port));
2086                 if (strlen(i->username))
2087                         snprintf(tmp->name, sizeof(tmp->name), "IAX[%s@%s]/%d", i->username, host, i->callno);
2088                 else
2089                         snprintf(tmp->name, sizeof(tmp->name), "IAX[%s]/%d", host, i->callno);
2090                 tmp->type = type;
2091                 /* We can support any format by default, until we get restricted */
2092                 tmp->nativeformats = capability;
2093                 tmp->readformat = 0;
2094                 tmp->writeformat = 0;
2095                 tmp->pvt->pvt = i;
2096                 tmp->pvt->send_digit = iax_digit;
2097                 tmp->pvt->send_text = iax_sendtext;
2098                 tmp->pvt->send_image = iax_sendimage;
2099                 tmp->pvt->send_html = iax_sendhtml;
2100                 tmp->pvt->call = iax_call;
2101                 tmp->pvt->hangup = iax_hangup;
2102                 tmp->pvt->answer = iax_answer;
2103                 tmp->pvt->read = iax_read;
2104                 tmp->pvt->write = iax_write;
2105                 tmp->pvt->indicate = iax_indicate;
2106                 tmp->pvt->setoption = iax_setoption;
2107                 tmp->pvt->bridge = iax_bridge;
2108                 if (strlen(i->callerid))
2109                         tmp->callerid = strdup(i->callerid);
2110                 if (strlen(i->ani))
2111                         tmp->ani = strdup(i->ani);
2112                 if (strlen(i->language))
2113                         strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
2114                 if (strlen(i->dnid))
2115                         tmp->dnid = strdup(i->dnid);
2116                 if (strlen(i->accountcode))
2117                         strncpy(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode)-1);
2118                 if (i->amaflags)
2119                         tmp->amaflags = i->amaflags;
2120                 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
2121                 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
2122                 tmp->adsicpe = i->peeradsicpe;
2123                 tmp->pvt->fixup = iax_fixup;
2124                 i->owner = tmp;
2125                 i->capability = capability;
2126                 ast_setstate(tmp, state);
2127                 ast_mutex_lock(&usecnt_lock);
2128                 usecnt++;
2129                 ast_mutex_unlock(&usecnt_lock);
2130                 ast_update_use_count();
2131                 if (state != AST_STATE_DOWN) {
2132                         if (ast_pbx_start(tmp)) {
2133                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
2134                                 ast_hangup(tmp);
2135                                 tmp = NULL;
2136                         }
2137                 }
2138         }
2139         return tmp;
2140 }
2141
2142 static unsigned int calc_timestamp(struct chan_iax_pvt *p, unsigned int ts)
2143 {
2144         struct timeval tv;
2145         unsigned int ms;
2146         if (!p->offset.tv_sec && !p->offset.tv_usec)
2147                 gettimeofday(&p->offset, NULL);
2148         /* If the timestamp is specified, just send it as is */
2149         if (ts)
2150                 return ts;
2151         gettimeofday(&tv, NULL);
2152         ms = (tv.tv_sec - p->offset.tv_sec) * 1000 + (tv.tv_usec - p->offset.tv_usec) / 1000;
2153         /* We never send the same timestamp twice, so fudge a little if we must */
2154         if (ms <= p->lastsent)
2155                 ms = p->lastsent + 1;
2156         p->lastsent = ms;
2157         return ms;
2158 }
2159
2160 #ifdef BRIDGE_OPTIMIZATION
2161 static unsigned int calc_fakestamp(struct chan_iax_pvt *p1, struct chan_iax_pvt *p2, unsigned int fakets)
2162 {
2163         int ms;
2164         /* Receive from p1, send to p2 */
2165         
2166         /* Setup rxcore if necessary on outgoing channel */
2167         if (!p1->rxcore.tv_sec && !p1->rxcore.tv_usec)
2168                 gettimeofday(&p1->rxcore, NULL);
2169
2170         /* Setup txcore if necessary on outgoing channel */
2171         if (!p2->offset.tv_sec && !p2->offset.tv_usec)
2172                 gettimeofday(&p2->offset, NULL);
2173         
2174         /* Now, ts is the timestamp of the original packet in the orignal context.
2175            Adding rxcore to it gives us when we would want the packet to be delivered normally.
2176            Subtracting txcore of the outgoing channel gives us what we'd expect */
2177         
2178         ms = (p1->rxcore.tv_sec - p2->offset.tv_sec) * 1000 + (p1->rxcore.tv_usec - p1->offset.tv_usec) / 1000;
2179         fakets += ms;
2180         if (fakets <= p2->lastsent)
2181                 fakets = p2->lastsent + 1;
2182         p2->lastsent = fakets;
2183         return fakets;
2184 }
2185 #endif
2186
2187 static unsigned int calc_rxstamp(struct chan_iax_pvt *p)
2188 {
2189         /* Returns where in "receive time" we are */
2190         struct timeval tv;
2191         unsigned int ms;
2192         /* Setup rxcore if necessary */
2193         if (!p->rxcore.tv_sec && !p->rxcore.tv_usec)
2194                 gettimeofday(&p->rxcore, NULL);
2195
2196         gettimeofday(&tv, NULL);
2197         ms = (tv.tv_sec - p->rxcore.tv_sec) * 1000 + (tv.tv_usec - p->rxcore.tv_usec) / 1000;
2198         return ms;
2199 }
2200
2201 static int iax_send(struct chan_iax_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final)
2202 {
2203         /* Queue a packet for delivery on a given private structure.  Use "ts" for
2204            timestamp, or calculate if ts is 0.  Send immediately without retransmission
2205            or delayed, with retransmission */
2206         struct ast_iax_full_hdr *fh;
2207         struct ast_iax_mini_hdr *mh;
2208         struct ast_iax_frame *fr, fr2;
2209         int res;
2210         unsigned int lastsent;
2211         /* Allocate an ast_iax_frame */
2212         if (now)
2213                 fr = &fr2;
2214         else
2215                 fr = ast_iax_frame_new(DIRECTION_OUTGRESS);
2216         if (!fr) {
2217                 ast_log(LOG_WARNING, "Out of memory\n");
2218                 return -1;
2219         }
2220         if (!pvt) {
2221                 ast_log(LOG_WARNING, "No private structure for packet (%d)?\n", fr->callno);
2222                 if (!now)
2223                         ast_iax_frame_free(fr);
2224                 return -1;
2225         }
2226         /* Isolate our frame for transmission */
2227         fr->f = ast_frdup(f);
2228
2229         if (!fr->f) {
2230                 ast_log(LOG_WARNING, "Out of memory\n");
2231                 if (!now)
2232                         ast_iax_frame_free(fr);
2233                 return -1;
2234         }
2235         if (fr->f->offset < sizeof(struct ast_iax_full_hdr)) {
2236                 ast_log(LOG_WARNING, "Packet from '%s' not friendly\n", fr->f->src);
2237                 free(fr);
2238                 return -1;
2239         }
2240         lastsent = pvt->lastsent;
2241         fr->ts = calc_timestamp(pvt, ts);
2242         if (!fr->ts) {
2243                 ast_log(LOG_WARNING, "timestamp is 0?\n");
2244                 if (!now)
2245                         ast_iax_frame_free(fr);
2246                 return -1;
2247         }
2248         fr->callno = pvt->callno;
2249         fr->transfer = transfer;
2250         fr->final = final;
2251         if (((fr->ts & 0xFFFF0000L) != (lastsent & 0xFFFF0000L))
2252                 /* High two bits of timestamp differ */ ||
2253             (fr->f->frametype != AST_FRAME_VOICE) 
2254                 /* or not a voice frame */ || 
2255                 (fr->f->subclass != pvt->svoiceformat) 
2256                 /* or new voice format */ ) {
2257                 /* We need a full frame */
2258                 if (seqno > -1)
2259                         fr->seqno = seqno;
2260                 else
2261                         fr->seqno = pvt->oseqno++;
2262                 fh = (struct ast_iax_full_hdr *)(fr->f->data - sizeof(struct ast_iax_full_hdr));
2263                 fh->callno = htons(fr->callno | AST_FLAG_FULL);
2264                 fh->ts = htonl(fr->ts);
2265                 fh->seqno = htons(fr->seqno);
2266                 fh->type = fr->f->frametype & 0xFF;
2267                 fh->csub = compress_subclass(fr->f->subclass);
2268                 if (transfer) {
2269                         fh->dcallno = htons(pvt->transfercallno);
2270                 } else
2271                         fh->dcallno = htons(pvt->peercallno);
2272                 fr->datalen = fr->f->datalen + sizeof(struct ast_iax_full_hdr);
2273                 fr->data = fh;
2274                 fr->retries = 0;
2275                 /* Retry after 2x the ping time has passed */
2276                 fr->retrytime = pvt->pingtime * 2;
2277                 if (fr->retrytime < MIN_RETRY_TIME)
2278                         fr->retrytime = MIN_RETRY_TIME;
2279                 if (fr->retrytime > MAX_RETRY_TIME)
2280                         fr->retrytime = MAX_RETRY_TIME;
2281                 /* Acks' don't get retried */
2282                 if ((f->frametype == AST_FRAME_IAX) && (f->subclass == AST_IAX_COMMAND_ACK))
2283                         fr->retries = -1;
2284                 if (f->frametype == AST_FRAME_VOICE) {
2285                         pvt->svoiceformat = f->subclass;
2286                 }
2287                 if (now) {
2288                         res = send_packet(fr);
2289                         ast_frfree(fr->f);
2290                 } else
2291                         res = iax_transmit(fr);
2292         } else {
2293                 /* Mini-frames have no sequence number */
2294                 fr->seqno = -1;
2295                 /* Mini frame will do */
2296                 mh = (struct ast_iax_mini_hdr *)(fr->f->data - sizeof(struct ast_iax_mini_hdr));
2297                 mh->callno = htons(fr->callno);
2298                 mh->ts = htons(fr->ts & 0xFFFF);
2299                 fr->datalen = fr->f->datalen + sizeof(struct ast_iax_mini_hdr);
2300                 fr->data = mh;
2301                 fr->retries = -1;
2302                 if (now) {
2303                         res = send_packet(fr);
2304                         ast_frfree(fr->f);
2305                 } else
2306                         res = iax_transmit(fr);
2307         }
2308         return res;
2309 }
2310
2311
2312
2313 static int iax_show_users(int fd, int argc, char *argv[])
2314 {
2315 #define FORMAT "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-5.5s\n"
2316         struct iax_user *user;
2317         if (argc != 3) 
2318                 return RESULT_SHOWUSAGE;
2319         ast_mutex_lock(&userl.lock);
2320         ast_cli(fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C");
2321         for(user=userl.users;user;user=user->next) {
2322                 ast_cli(fd, FORMAT, user->name, user->secret, user->methods, 
2323                                 user->contexts ? user->contexts->context : context,
2324                                 user->ha ? "Yes" : "No");
2325         }
2326         ast_mutex_unlock(&userl.lock);
2327         return RESULT_SUCCESS;
2328 #undef FORMAT
2329 }
2330
2331 static int iax_show_peers(int fd, int argc, char *argv[])
2332 {
2333 #define FORMAT2 "%-15.15s  %-15.15s %s  %-15.15s  %-8s  %-10s\n"
2334 #define FORMAT "%-15.15s  %-15.15s %s  %-15.15s  %-8d  %-10s\n"
2335         struct iax_peer *peer;
2336         char name[256] = "";
2337         if (argc != 3)
2338                 return RESULT_SHOWUSAGE;
2339         ast_mutex_lock(&peerl.lock);
2340         ast_cli(fd, FORMAT2, "Name/Username", "Host", "   ", "Mask", "Port", "Status");
2341         for (peer = peerl.peers;peer;peer = peer->next) {
2342                 char nm[20];
2343                 char status[20];
2344                 if (strlen(peer->username))
2345                         snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
2346                 else
2347                         strncpy(name, peer->name, sizeof(name) - 1);
2348                 if (peer->maxms) {
2349                         if (peer->lastms < 0)
2350                                 strcpy(status, "UNREACHABLE");
2351                         else if (peer->lastms > peer->maxms) 
2352                                 snprintf(status, sizeof(status), "LAGGED (%d ms)", peer->lastms);
2353                         else if (peer->lastms) 
2354                                 snprintf(status, sizeof(status), "OK (%d ms)", peer->lastms);
2355                         else 
2356                                 strcpy(status, "UNKNOWN");
2357                 } else 
2358                         strcpy(status, "Unmonitored");
2359                 strncpy(nm, inet_ntoa(peer->mask), sizeof(nm)-1);
2360                 ast_cli(fd, FORMAT, name, 
2361                                         peer->addr.sin_addr.s_addr ? inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
2362                                         peer->dynamic ? "(D)" : "(S)",
2363                                         nm,
2364                                         ntohs(peer->addr.sin_port), status);
2365         }
2366         ast_mutex_unlock(&peerl.lock);
2367         return RESULT_SUCCESS;
2368 #undef FORMAT
2369 #undef FORMAT2
2370 }
2371
2372 /* JDG: callback to display iax peers in manager */
2373 static int manager_iax_show_peers( struct mansession *s, struct message *m )
2374 {
2375         char *a[] = { "iax", "show", "users" };
2376         int ret;
2377         ret = iax_show_peers( s->fd, 3, a );
2378         ast_cli( s->fd, "\r\n" );
2379         return ret;
2380 } /* /JDG */
2381
2382 static char *regstate2str(int regstate)
2383 {
2384         switch(regstate) {
2385         case REG_STATE_UNREGISTERED:
2386                 return "Unregistered";
2387         case REG_STATE_REGSENT:
2388                 return "Request Sent";
2389         case REG_STATE_AUTHSENT:
2390                 return "Auth. Sent";
2391         case REG_STATE_REGISTERED:
2392                 return "Registered";
2393         case REG_STATE_REJECTED:
2394                 return "Rejected";
2395         case REG_STATE_TIMEOUT:
2396                 return "Timeout";
2397         case REG_STATE_NOAUTH:
2398                 return "No Authentication";
2399         default:
2400                 return "Unknown";
2401         }
2402 }
2403
2404 static int iax_show_registry(int fd, int argc, char *argv[])
2405 {
2406 #define FORMAT2 "%-20.20s  %-10.10s  %-20.20s %8.8s  %s\n"
2407 #define FORMAT "%-20.20s  %-10.10s  %-20.20s %8d  %s\n"
2408         struct iax_registry *reg;
2409         char host[80];
2410         char perceived[80];
2411         if (argc != 3)
2412                 return RESULT_SHOWUSAGE;
2413         ast_mutex_lock(&peerl.lock);
2414         ast_cli(fd, FORMAT2, "Host", "Username", "Perceived", "Refresh", "State");
2415         for (reg = registrations;reg;reg = reg->next) {
2416                 snprintf(host, sizeof(host), "%s:%d", inet_ntoa(reg->addr.sin_addr), ntohs(reg->addr.sin_port));
2417                 if (reg->us.sin_addr.s_addr) 
2418                         snprintf(perceived, sizeof(perceived), "%s:%d", inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
2419                 else
2420                         strcpy(perceived, "<Unregistered>");
2421                 ast_cli(fd, FORMAT, host, 
2422                                         reg->username, perceived, reg->refresh, regstate2str(reg->regstate));
2423         }
2424         ast_mutex_unlock(&peerl.lock);
2425         return RESULT_SUCCESS;
2426 #undef FORMAT
2427 #undef FORMAT2
2428 }
2429
2430 static int iax_show_channels(int fd, int argc, char *argv[])
2431 {
2432 #define FORMAT2 "%-15.15s  %-10.10s  %-11.11s  %-11.11s  %-7.7s  %-6.6s  %s\n"
2433 #define FORMAT  "%-15.15s  %-10.10s  %5.5d/%5.5d  %5.5d/%5.5d  %-5.5dms  %-4.4dms  %-6.6s\n"
2434         int x;
2435         int numchans = 0;
2436         if (argc != 3)
2437                 return RESULT_SHOWUSAGE;
2438         ast_cli(fd, FORMAT2, "Peer", "Username", "ID (Lo/Rem)", "Seq (Tx/Rx)", "Lag", "Jitter", "Format");
2439         for (x=0;x<AST_IAX_MAX_CALLS;x++) {
2440                 ast_mutex_lock(&iaxsl[x]);
2441                 if (iaxs[x]) {
2442                         ast_cli(fd, FORMAT, inet_ntoa(iaxs[x]->addr.sin_addr), 
2443                                                 strlen(iaxs[x]->username) ? iaxs[x]->username : "(None)", 
2444                                                 iaxs[x]->callno, iaxs[x]->peercallno, 
2445                                                 iaxs[x]->oseqno, iaxs[x]->iseqno, 
2446                                                 iaxs[x]->lag,
2447                                                 iaxs[x]->jitter,
2448                                                 ast_getformatname(iaxs[x]->voiceformat) );
2449                         numchans++;
2450                 }
2451                 ast_mutex_unlock(&iaxsl[x]);
2452         }
2453         ast_cli(fd, "%d active IAX channel(s)\n", numchans);
2454         return RESULT_SUCCESS;
2455 #undef FORMAT
2456 #undef FORMAT2
2457 }
2458
2459 static int iax_do_debug(int fd, int argc, char *argv[])
2460 {
2461         if (argc != 2)
2462                 return RESULT_SHOWUSAGE;
2463         iaxdebug = 1;
2464         ast_cli(fd, "IAX Debugging Enabled\n");
2465         return RESULT_SUCCESS;
2466 }
2467
2468 static int iax_no_debug(int fd, int argc, char *argv[])
2469 {
2470         if (argc != 3)
2471                 return RESULT_SHOWUSAGE;
2472         iaxdebug = 0;
2473         ast_cli(fd, "IAX Debugging Disabled\n");
2474         return RESULT_SUCCESS;
2475 }
2476
2477
2478
2479 static char show_users_usage[] = 
2480 "Usage: iax1 show users\n"
2481 "       Lists all users known to the IAX (Inter-Asterisk eXchange) subsystem.\n";
2482
2483 static char show_channels_usage[] = 
2484 "Usage: iax1 show channels\n"
2485 "       Lists all currently active IAX channels.\n";
2486
2487 static char show_peers_usage[] = 
2488 "Usage: iax1 show peers\n"
2489 "       Lists all known IAX peers.\n";
2490
2491 static char show_reg_usage[] =
2492 "Usage: iax1 show registry\n"
2493 "       Lists all registration requests and status.\n";
2494
2495 #ifdef DEBUG_SUPPORT
2496
2497 static char debug_usage[] = 
2498 "Usage: iax1 debug\n"
2499 "       Enables dumping of IAX packets for debugging purposes\n";
2500
2501 static char no_debug_usage[] = 
2502 "Usage: iax1 no debug\n"
2503 "       Disables dumping of IAX packets for debugging purposes\n";
2504
2505 #endif
2506
2507 static struct ast_cli_entry  cli_show_users = 
2508         { { "iax1", "show", "users", NULL }, iax_show_users, "Show defined IAX users", show_users_usage };
2509 static struct ast_cli_entry  cli_show_channels =
2510         { { "iax1", "show", "channels", NULL }, iax_show_channels, "Show active IAX channels", show_channels_usage };
2511 static struct ast_cli_entry  cli_show_peers =
2512         { { "iax1", "show", "peers", NULL }, iax_show_peers, "Show defined IAX peers", show_peers_usage };
2513 static struct ast_cli_entry  cli_show_registry =
2514         { { "iax1", "show", "registry", NULL }, iax_show_registry, "Show IAX registration status", show_reg_usage };
2515 static struct ast_cli_entry  cli_debug =
2516         { { "iax1", "debug", NULL }, iax_do_debug, "Enable IAX debugging", debug_usage };
2517 static struct ast_cli_entry  cli_no_debug =
2518         { { "iax1", "no", "debug", NULL }, iax_no_debug, "Disable IAX debugging", no_debug_usage };
2519
2520 static int iax_write(struct ast_channel *c, struct ast_frame *f)
2521 {
2522         struct chan_iax_pvt *i = c->pvt->pvt;
2523         if (!i)
2524                 return -1;
2525         /* If there's an outstanding error, return failure now */
2526         if (i->error) {
2527                 ast_log(LOG_DEBUG, "Write error: %s\n", strerror(errno));
2528                 return -1;
2529         }
2530         /* If it's already gone, just return */
2531         if (i->alreadygone)
2532                 return 0;
2533         /* Don't waste bandwidth sending null frames */
2534         if (f->frametype == AST_FRAME_NULL)
2535                 return 0;
2536         /* If we're quelching voice, don't bother sending it */
2537         if ((f->frametype == AST_FRAME_VOICE) && i->quelch)
2538                 return 0;
2539         /* Simple, just queue for transmission */
2540         return iax_send(i, f, 0, -1, 0, 0, 0);
2541 }
2542
2543 static int __send_command(struct chan_iax_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno, 
2544                 int now, int transfer, int final)
2545 {
2546         struct ast_frame f;
2547         f.frametype = type;
2548         f.subclass = command;
2549         f.datalen = datalen;
2550         f.samples = 0;
2551         f.mallocd = 0;
2552         f.offset = 0;
2553         f.src = __FUNCTION__;
2554         f.data = data;
2555         return iax_send(i, &f, ts, seqno, now, transfer, final);
2556 }
2557
2558 static int send_command(struct chan_iax_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2559 {
2560         return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 0);
2561 }
2562
2563 #ifdef BRIDGE_OPTIMIZATION
2564 static int forward_command(struct chan_iax_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2565 {
2566         return __send_command(iaxs[i->bridgecallno], type, command, ts, data, datalen, seqno, 0, 0, 0);
2567 }
2568 #endif
2569
2570 static int send_command_final(struct chan_iax_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2571 {
2572         /* It is assumed that the callno has already been locked */
2573         iax_predestroy_nolock(i->callno);
2574         return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 1);
2575 }
2576
2577 static int send_command_immediate(struct chan_iax_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2578 {
2579         return __send_command(i, type, command, ts, data, datalen, seqno, 1, 0, 0);
2580 }
2581
2582 static int send_command_transfer(struct chan_iax_pvt *i, char type, int command, unsigned int ts, char *data, int datalen)
2583 {
2584         return __send_command(i, type, command, ts, data, datalen, 0, 0, 1, 0);
2585 }
2586
2587 static int apply_context(struct iax_context *con, char *context)
2588 {
2589         while(con) {
2590                 if (!strcmp(con->context, context))
2591                         return -1;
2592                 con = con->next;
2593         }
2594         return 0;
2595 }
2596
2597 static int iax_getformats(int callno, char *orequest)
2598 {
2599         char *var, *value;
2600         char request[256];
2601         char *stringp=NULL;
2602         strncpy(request, orequest, sizeof(request)-1);
2603         stringp=request;
2604         var = strsep(&stringp, ";");
2605         while(var) {
2606                 value = strchr(var, '=');
2607                 if (value) {
2608                         *value='\0';
2609                         value++;
2610                         if (!strcmp(var, "formats")) {
2611                                 iaxs[callno]->peerformat = atoi(value);
2612                         } else 
2613                                 ast_log(LOG_WARNING, "Unknown variable '%s' with value '%s'\n", var, value);
2614                 }
2615                 var = strsep(&stringp, ";");
2616         }
2617         return 0;
2618 }
2619
2620
2621 static int check_access(int callno, struct sockaddr_in *sin, char *orequest, int requestl)
2622 {
2623         /* Start pessimistic */
2624         int res = -1;
2625         int version = 1;
2626         char *var, *value;
2627         struct iax_user *user;
2628         char request[256];
2629         int gotcapability=0;
2630         char *stringp=NULL;
2631         strncpy(request, orequest, sizeof(request)-1);
2632         if (!iaxs[callno])
2633                 return res;
2634         stringp=request;
2635         var = strsep(&stringp, ";");
2636         while(var) {
2637                 value = strchr(var, '=');
2638                 if (value) { 
2639                         *value='\0';
2640                         value++;
2641                         if (!strcmp(var, "exten")) 
2642                                 strncpy(iaxs[callno]->exten, value, sizeof(iaxs[callno]->exten)-1);
2643                         else if (!strcmp(var, "callerid"))
2644                                 strncpy(iaxs[callno]->callerid, value, sizeof(iaxs[callno]->callerid)-1);
2645                         else if (!strcmp(var, "ani"))
2646                                 strncpy(iaxs[callno]->ani, value, sizeof(iaxs[callno]->ani) - 1);
2647                         else if (!strcmp(var, "dnid"))
2648                                 strncpy(iaxs[callno]->dnid, value, sizeof(iaxs[callno]->dnid)-1);
2649                         else if (!strcmp(var, "context"))
2650                                 strncpy(iaxs[callno]->context, value, sizeof(iaxs[callno]->context)-1);
2651                         else if (!strcmp(var, "language"))
2652                                 strncpy(iaxs[callno]->language, value, sizeof(iaxs[callno]->language)-1);
2653                         else if (!strcmp(var, "username"))
2654                                 strncpy(iaxs[callno]->username, value, sizeof(iaxs[callno]->username)-1);
2655                         else if (!strcmp(var, "formats")) 
2656                                 iaxs[callno]->peerformat = atoi(value);
2657                         else if (!strcmp(var, "adsicpe"))
2658                                 iaxs[callno]->peeradsicpe = atoi(value);
2659                         else if (!strcmp(var, "capability")) {
2660                                 gotcapability = 1;
2661                                 iaxs[callno]->peercapability = atoi(value);
2662                         } else if (!strcmp(var, "version"))
2663                                 version = atoi(value);
2664                         else 
2665                                 ast_log(LOG_WARNING, "Unknown variable '%s' with value '%s'\n", var, value);
2666                 }
2667                 var = strsep(&stringp, ";");
2668         }
2669         if (!gotcapability) 
2670                 iaxs[callno]->peercapability = iaxs[callno]->peerformat;
2671         if (version > AST_IAX_PROTO_VERSION) {
2672                 ast_log(LOG_WARNING, "Peer '%s' has too new a protocol version (%d) for me\n", 
2673                         inet_ntoa(sin->sin_addr), version);
2674                 return res;
2675         }
2676         ast_mutex_lock(&userl.lock);
2677         /* Search the userlist for a compatible entry, and fill in the rest */
2678         user = userl.users;
2679         while(user) {
2680                 if ((!strlen(iaxs[callno]->username) ||                         /* No username specified */
2681                         !strcmp(iaxs[callno]->username, user->name))    /* Or this username specified */
2682                         && ast_apply_ha(user->ha, sin)  /* Access is permitted from this IP */
2683                         && (!strlen(iaxs[callno]->context) ||                   /* No context specified */
2684                              apply_context(user->contexts, iaxs[callno]->context))) {                   /* Context is permitted */
2685                         break;
2686                 }
2687                 user = user->next;      
2688         }
2689 #ifdef MYSQL_FRIENDS
2690         if (!user && mysql && strlen(iaxs[callno]->username) && (strlen(iaxs[callno]->username) < 128)) {
2691                 user = mysql_user(iaxs[callno]->username);
2692                 if (user && strlen(iaxs[callno]->context) &&                    /* No context specified */
2693                              !apply_context(user->contexts, iaxs[callno]->context)) {                   /* Context is permitted */
2694                         if (user->contexts)
2695                                 free(user->contexts);
2696                         free(user);
2697                         user = NULL;
2698                 }
2699         }
2700 #endif  
2701         ast_mutex_unlock(&userl.lock);
2702         if (user) {
2703                 /* We found our match (use the first) */
2704                 
2705                 /* Store the requested username if not specified */
2706                 if (!strlen(iaxs[callno]->username))
2707                         strncpy(iaxs[callno]->username, user->name, sizeof(iaxs[callno]->username)-1);
2708                 /* And use the default context */
2709                 if (!strlen(iaxs[callno]->context)) {
2710                         if (user->contexts)
2711                                 strncpy(iaxs[callno]->context, user->contexts->context, sizeof(iaxs[callno]->context)-1);
2712                         else
2713                                 strncpy(iaxs[callno]->context, context, sizeof(iaxs[callno]->context)-1);
2714                 }
2715                 /* Copy the secret */
2716                 strncpy(iaxs[callno]->secret, user->secret, sizeof(iaxs[callno]->secret)-1);
2717                 /* And any input keys */
2718                 strncpy(iaxs[callno]->inkeys, user->inkeys, sizeof(iaxs[callno]->inkeys));
2719                 /* And the permitted authentication methods */
2720                 strncpy(iaxs[callno]->methods, user->methods, sizeof(iaxs[callno]->methods)-1);
2721                 /* If they have callerid, override the given caller id.  Always store the ANI */
2722                 if (strlen(iaxs[callno]->callerid)) {
2723                         if (user->hascallerid)
2724                                 strncpy(iaxs[callno]->callerid, user->callerid, sizeof(iaxs[callno]->callerid)-1);
2725                         strncpy(iaxs[callno]->ani, user->callerid, sizeof(iaxs[callno]->ani)-1);
2726                 }
2727                 if (strlen(user->accountcode))
2728                         strncpy(iaxs[callno]->accountcode, user->accountcode, sizeof(iaxs[callno]->accountcode)-1);
2729                 if (user->amaflags)
2730                         iaxs[callno]->amaflags = user->amaflags;
2731                 res = 0;
2732         }
2733         return res;
2734 }
2735
2736 static int raw_hangup(struct sockaddr_in *sin, short src, short dst)
2737 {
2738         struct ast_iax_full_hdr fh;
2739         fh.callno = htons(src | AST_FLAG_FULL);
2740         fh.dcallno = htons(dst);
2741         fh.ts = 0;
2742         fh.seqno = 0;
2743         fh.type = AST_FRAME_IAX;
2744         fh.csub = compress_subclass(AST_IAX_COMMAND_INVAL);
2745 #if 0
2746         if (option_debug)
2747 #endif  
2748                 ast_log(LOG_DEBUG, "Raw Hangup %s:%d, src=%d, dst=%d\n",
2749                         inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), src, dst);
2750         return sendto(netsocket, &fh, sizeof(fh), 0, (struct sockaddr *)sin, sizeof(*sin));
2751 }
2752
2753 static int authenticate_request(struct chan_iax_pvt *p)
2754 {
2755         char requeststr[256] = "";
2756         MYSNPRINTF "methods=%s;", p->methods);
2757         if (strstr(p->methods, "md5") || strstr(p->methods, "rsa")) {
2758                 /* Build the challenge */
2759                 snprintf(p->challenge, sizeof(p->challenge), "%d", rand());
2760                 MYSNPRINTF "challenge=%s;", p->challenge);
2761         }
2762         MYSNPRINTF "username=%s;", p->username);
2763         if (strlen(requeststr))
2764                 requeststr[strlen(requeststr) - 1] = '\0';
2765         return send_command(p, AST_FRAME_IAX, AST_IAX_COMMAND_AUTHREQ, 0, requeststr, strlen(requeststr) + 1, -1);
2766 }
2767
2768 static int authenticate_verify(struct chan_iax_pvt *p, char *orequest)
2769 {
2770         char requeststr[256] = "";
2771         char *var, *value, request[256];
2772         char md5secret[256] = "";
2773         char secret[256] = "";
2774         char rsasecret[256] = "";
2775         int res = -1; 
2776         int x;
2777         char *stringp=NULL;
2778         
2779         if (!(p->state & IAX_STATE_AUTHENTICATED))
2780                 return res;
2781         strncpy(request, orequest, sizeof(request)-1);
2782         stringp=request;
2783         var = strsep(&stringp, ";");
2784         while(var) {
2785                 value = strchr(var, '=');
2786                 if (value) { 
2787                         *value='\0';
2788                         value++;
2789                         if (!strcmp(var, "secret")) 
2790                                 strncpy(secret, value, sizeof(secret)-1);
2791                         else if (!strcmp(var, "md5secret"))
2792                                 strncpy(md5secret, value, sizeof(md5secret)-1);
2793                         else if (!strcmp(var, "rsasecret"))
2794                                 strncpy(rsasecret, value, sizeof(rsasecret)-1);
2795                         else
2796                                 ast_log(LOG_WARNING, "Unknown variable '%s' with value '%s'\n", var, value);
2797                 }
2798                 var = strsep(&stringp, ";");
2799         }
2800         if (strstr(p->methods, "rsa") && strlen(rsasecret) && strlen(p->inkeys)) {
2801                 struct ast_key *key;
2802                 char *keyn;
2803                 char tmpkey[256];
2804                 char *stringp=NULL;
2805                 strncpy(tmpkey, p->inkeys, sizeof(tmpkey));
2806                 stringp=tmpkey;
2807                 keyn = strsep(&stringp, ":");
2808                 while(keyn) {
2809                         key = ast_key_get(keyn, AST_KEY_PUBLIC);
2810                         if (key && !ast_check_signature(key, p->challenge, rsasecret)) {
2811                                 res = 0;
2812                                 break;
2813                         } else if (!key)
2814                                 ast_log(LOG_WARNING, "requested inkey '%s' for RSA authentication does not exist\n", keyn);
2815                         keyn = strsep(&stringp, ":");
2816                 }
2817         } else if (strstr(p->methods, "md5")) {
2818                 struct MD5Context md5;
2819                 unsigned char digest[16];
2820                 MD5Init(&md5);
2821                 MD5Update(&md5, p->challenge, strlen(p->challenge));
2822                 MD5Update(&md5, p->secret, strlen(p->secret));
2823                 MD5Final(digest, &md5);
2824                 /* If they support md5, authenticate with it.  */
2825                 for (x=0;x<16;x++)
2826                         MYSNPRINTF "%2.2x", digest[x]);
2827                 if (!strcasecmp(requeststr, md5secret))
2828                         res = 0;
2829         } else if (strstr(p->methods, "plaintext")) {
2830                 if (!strcmp(secret, p->secret))
2831                         res = 0;
2832         }
2833         return res;
2834 }
2835
2836 static int register_verify(int callno, struct sockaddr_in *sin, char *orequest)
2837 {
2838         char request[256];
2839         char requeststr[256] = "";
2840         char peer[256] = "";
2841         char md5secret[256] = "";
2842         char rsasecret[256] = "";
2843         char secret[256] = "";
2844         struct iax_peer *p;
2845         struct ast_key *key;
2846         char *var;
2847         char *value;
2848         char *keyn;
2849         int x;
2850         int expire = 0;
2851         char *stringp=NULL;
2852
2853         iaxs[callno]->state &= ~IAX_STATE_AUTHENTICATED;
2854         strcpy(iaxs[callno]->peer, "");
2855         if (!orequest)
2856                 return -1;
2857         strncpy(request, orequest, sizeof(request)-1);
2858         stringp=request;
2859         var = strsep(&stringp, ";");
2860         while(var) {
2861                 value = strchr(var, '=');
2862                 if (value) { 
2863                         *value='\0';
2864                         value++;
2865                         if (!strcmp(var, "peer")) 
2866                                 strncpy(peer, value, sizeof(peer)-1);
2867                         else if (!strcmp(var, "md5secret"))
2868                                 strncpy(md5secret, value, sizeof(md5secret)-1);
2869                         else if (!strcmp(var, "rsasecret"))
2870                                 strncpy(rsasecret, value, sizeof(rsasecret)-1);
2871                         else if (!strcmp(var, "secret"))
2872                                 strncpy(secret, value, sizeof(secret)-1);
2873                         else if (!strcmp(var, "refresh"))
2874                                 expire = atoi(value);
2875                         else 
2876                                 ast_log(LOG_WARNING, "Unknown variable '%s' with value '%s'\n", var, value);
2877                 }
2878                 var = strsep(&stringp, ";");
2879         }
2880
2881         if (!strlen(peer)) {
2882                 ast_log(LOG_NOTICE, "Empty registration from %s\n", inet_ntoa(sin->sin_addr));
2883                 return -1;
2884         }
2885
2886         for (p = peerl.peers; p ; p = p->next) 
2887                 if (!strcasecmp(p->name, peer))
2888                         break;
2889
2890 #ifdef MYSQL_FRIENDS
2891         if (!p) 
2892                 p = mysql_peer(peer);
2893 #endif
2894         if (!p) {
2895                 ast_log(LOG_NOTICE, "No registration for peer '%s' (from %s)\n", peer, inet_ntoa(sin->sin_addr));
2896                 return -1;
2897         }
2898
2899         if (!p->dynamic) {
2900                 ast_log(LOG_NOTICE, "Peer '%s' is not dynamic (from %s)\n", peer, inet_ntoa(sin->sin_addr));
2901                 if (p->delme)
2902                         free(p);
2903                 return -1;
2904         }
2905
2906         if (!ast_apply_ha(p->ha, sin)) {
2907                 ast_log(LOG_NOTICE, "Host %s denied access to register peer '%s'\n", inet_ntoa(sin->sin_addr), p->name);
2908                 if (p->delme)
2909                         free(p);
2910                 return -1;
2911         }
2912         strncpy(iaxs[callno]->secret, p->secret, sizeof(iaxs[callno]->secret)-1);
2913         strncpy(iaxs[callno]->inkeys, p->inkeys, sizeof(iaxs[callno]->inkeys)-1);
2914         /* Check secret against what we have on file */
2915         if (strlen(rsasecret) && strstr(p->methods, "rsa") && strlen(iaxs[callno]->challenge)) {
2916                 if (strlen(p->inkeys)) {
2917                         char tmpkeys[256];
2918                         char *stringp=NULL;
2919                         strncpy(tmpkeys, p->inkeys, sizeof(tmpkeys));
2920                         stringp=tmpkeys;
2921                         keyn = strsep(&stringp, ":");
2922                         while(keyn) {
2923                                 key = ast_key_get(keyn, AST_KEY_PUBLIC);
2924                                 if (key && !ast_check_signature(key, iaxs[callno]->challenge, rsasecret)) {
2925                                         iaxs[callno]->state |= IAX_STATE_AUTHENTICATED;
2926                                         break;
2927                                 } else if (!key) 
2928                                         ast_log(LOG_WARNING, "requested inkey '%s' does not exist\n", keyn);
2929                                 keyn = strsep(&stringp, ":");
2930                         }
2931                         if (!keyn) {
2932                                 ast_log(LOG_NOTICE, "Host %s failed RSA authentication with inkeys '%s'\n", peer, p->inkeys);
2933                                 if (p->delme)
2934                                         free(p);
2935                                 return -1;
2936                         }
2937                 } else {
2938                         ast_log(LOG_NOTICE, "Host '%s' trying to do RSA authentication, but we have no inkeys\n", peer);
2939                         if (p->delme)
2940                                 free(p);
2941                         return -1;
2942                 }
2943         } else if (strlen(secret) && strstr(p->methods, "plaintext")) {
2944                 /* They've provided a plain text password and we support that */
2945                 if (strcmp(secret, p->secret)) {
2946                         ast_log(LOG_NOTICE, "Host %s did not provide proper plaintext password for '%s'\n", inet_ntoa(sin->sin_addr), p->name);
2947                         if (p->delme)
2948                                 free(p);
2949                         return -1;
2950                 } else
2951                         iaxs[callno]->state |= IAX_STATE_AUTHENTICATED;
2952         } else if (strlen(md5secret) && strstr(p->methods, "md5") && strlen(iaxs[callno]->challenge)) {
2953                 struct MD5Context md5;
2954                 unsigned char digest[16];
2955                 MD5Init(&md5);
2956                 MD5Update(&md5, iaxs[callno]->challenge, strlen(iaxs[callno]->challenge));
2957                 MD5Update(&md5, p->secret, strlen(p->secret));
2958                 MD5Final(digest, &md5);
2959                 for (x=0;x<16;x++)
2960                         MYSNPRINTF "%2.2x", digest[x]);
2961                 if (strcasecmp(requeststr, md5secret)) {
2962                         ast_log(LOG_NOTICE, "Host %s failed MD5 authentication for '%s' (%s != %s)\n", inet_ntoa(sin->sin_addr), p->name, requeststr, md5secret);
2963                         if (p->delme)
2964                                 free(p);
2965                         return -1;
2966                 } else
2967                         iaxs[callno]->state |= IAX_STATE_AUTHENTICATED;
2968         } else if (strlen(md5secret) || strlen(secret)) {
2969                 ast_log(LOG_NOTICE, "Inappropriate authentication received\n");
2970                 if (p->delme)
2971                         free(p);
2972                 return -1;
2973         }
2974         strncpy(iaxs[callno]->peer, peer, sizeof(iaxs[callno]->peer)-1);
2975         /* Choose lowest expirey number */
2976         if (expire && (expire < iaxs[callno]->expirey)) 
2977                 iaxs[callno]->expirey = expire;
2978         if (p->delme)
2979                 free(p);
2980         return 0;
2981         
2982 }
2983
2984 static int authenticate(char *challenge, char *secret, char *keyn, char *methods, char *requeststr, int reqsize, struct sockaddr_in *sin)
2985 {
2986         int res = -1;
2987         int x;
2988         if (keyn && strlen(keyn)) {
2989                 if (!strstr(methods, "rsa")) {
2990                         if (!secret || !strlen(secret)) 
2991                                 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));
2992                 } else if (!strlen(challenge)) {
2993                         ast_log(LOG_NOTICE, "No challenge provided for RSA authentication to %s\n", inet_ntoa(sin->sin_addr));
2994                 } else {
2995                         char sig[256];
2996                         struct ast_key *key;
2997                         key = ast_key_get(keyn, AST_KEY_PRIVATE);
2998                         if (!key) {
2999                                 ast_log(LOG_NOTICE, "Unable to find private key '%s'\n", keyn);
3000                         } else {
3001                                 if (ast_sign(key, challenge, sig)) {
3002                                         ast_log(LOG_NOTICE, "Unable to sign challenge withy key\n");
3003                                         res = -1;
3004                                 } else {
3005                                         MYSNPRINTF2 "rsasecret=%s;", sig);
3006                                         res = 0;
3007                                 }
3008                         }
3009                 }
3010         } 
3011         /* Fall back */
3012         if (res && secret && strlen(secret)) {
3013                 if (strstr(methods, "md5") && strlen(challenge)) {
3014                         struct MD5Context md5;
3015                         unsigned char digest[16];
3016                         MD5Init(&md5);
3017                         MD5Update(&md5, challenge, strlen(challenge));
3018                         MD5Update(&md5, secret, strlen(secret));
3019                         MD5Final(digest, &md5);
3020                         /* If they support md5, authenticate with it.  */
3021                         MYSNPRINTF2 "md5secret=");
3022                         for (x=0;x<16;x++)
3023                                 MYSNPRINTF2 "%2.2x", digest[x]);
3024                         MYSNPRINTF2 ";");
3025                         res = 0;
3026                 } else if (strstr(methods, "plaintext")) {
3027                         MYSNPRINTF2 "secret=%s;", secret);
3028                         res = 0;
3029                 } else
3030                         ast_log(LOG_NOTICE, "No way to send secret to peer '%s' (their methods: %s)\n", inet_ntoa(sin->sin_addr), methods);
3031         }
3032         return res;
3033 }
3034
3035 static int authenticate_reply(struct chan_iax_pvt *p, struct sockaddr_in *sin, char *orequest, char *override, char *okey)
3036 {
3037         struct iax_peer *peer;
3038         /* Start pessimistic */
3039         int res = -1;
3040         char request[256];
3041         char methods[80] = "";
3042         char requeststr[256] = "";
3043         char *var, *value;
3044         char *stringp=NULL;
3045         
3046         strncpy(request, orequest, sizeof(request)-1);
3047         stringp=request;
3048         var = strsep(&stringp, ";");
3049         while(var) {
3050                 value = strchr(var, '=');
3051                 if (value) { 
3052                         *value='\0';
3053                         value++;
3054                         if (!strcmp(var, "username")) 
3055            &nb