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