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