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