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