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