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