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