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