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