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