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