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