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