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