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