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