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