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