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