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