Merge IAX2 peer completion patch (bug #3462)
[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 static char *complete_iax2_show_peer(char *line, char *word, int pos, int state)
1694 {
1695         int which = 0;
1696         struct iax2_peer *p;
1697
1698         /* 0 - iax2; 1 - show; 2 - peer; 3 - <peername> */
1699         if(pos == 3) {
1700                 ast_mutex_lock(&peerl.lock);
1701                 for(p = peerl.peers ; p ; p = p->next) {
1702                         if(!strncasecmp(p->name, word, strlen(word))) {
1703                                 if(++which > state) {
1704                                         return strdup(p->name);
1705                                 }
1706                         }
1707                 }
1708                 ast_mutex_unlock(&peerl.lock);
1709         }
1710
1711         return NULL;
1712 }
1713
1714 static int iax2_show_stats(int fd, int argc, char *argv[])
1715 {
1716         struct iax_frame *cur;
1717         int cnt = 0, dead=0, final=0;
1718         if (argc != 3)
1719                 return RESULT_SHOWUSAGE;
1720         for (cur = iaxq.head; cur ; cur = cur->next) {
1721                 if (cur->retries < 0)
1722                         dead++;
1723                 if (cur->final)
1724                         final++;
1725                 cnt++;
1726         }
1727         ast_cli(fd, "    IAX Statistics\n");
1728         ast_cli(fd, "---------------------\n");
1729         ast_cli(fd, "Outstanding frames: %d (%d ingress, %d outgress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
1730         ast_cli(fd, "Packets in transmit queue: %d dead, %d final, %d total\n", dead, final, cnt);
1731         return RESULT_SUCCESS;
1732 }
1733
1734 static int iax2_show_cache(int fd, int argc, char *argv[])
1735 {
1736         struct iax2_dpcache *dp;
1737         char tmp[1024] = "", *pc;
1738         int s;
1739         int x,y;
1740         struct timeval tv;
1741         gettimeofday(&tv, NULL);
1742         ast_mutex_lock(&dpcache_lock);
1743         dp = dpcache;
1744         ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
1745         while(dp) {
1746                 s = dp->expirey.tv_sec - tv.tv_sec;
1747                 tmp[0] = '\0';
1748                 if (dp->flags & CACHE_FLAG_EXISTS)
1749                         strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
1750                 if (dp->flags & CACHE_FLAG_NONEXISTANT)
1751                         strncat(tmp, "NONEXISTANT|", sizeof(tmp) - strlen(tmp) - 1);
1752                 if (dp->flags & CACHE_FLAG_CANEXIST)
1753                         strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
1754                 if (dp->flags & CACHE_FLAG_PENDING)
1755                         strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
1756                 if (dp->flags & CACHE_FLAG_TIMEOUT)
1757                         strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
1758                 if (dp->flags & CACHE_FLAG_TRANSMITTED)
1759                         strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
1760                 if (dp->flags & CACHE_FLAG_MATCHMORE)
1761                         strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
1762                 if (dp->flags & CACHE_FLAG_UNKNOWN)
1763                         strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
1764                 /* Trim trailing pipe */
1765                 if (!ast_strlen_zero(tmp))
1766                         tmp[strlen(tmp) - 1] = '\0';
1767                 else
1768                         strncpy(tmp, "(none)", sizeof(tmp) - 1);
1769                 y=0;
1770                 pc = strchr(dp->peercontext, '@');
1771                 if (!pc)
1772                         pc = dp->peercontext;
1773                 else
1774                         pc++;
1775                 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
1776                         if (dp->waiters[x] > -1)
1777                                 y++;
1778                 if (s > 0)
1779                         ast_cli(fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
1780                 else
1781                         ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
1782                 dp = dp->next;
1783         }
1784         ast_mutex_unlock(&dpcache_lock);
1785         return RESULT_SUCCESS;
1786 }
1787
1788 static char show_stats_usage[] =
1789 "Usage: iax show stats\n"
1790 "       Display statistics on IAX channel driver.\n";
1791
1792
1793 static char show_cache_usage[] =
1794 "Usage: iax show cache\n"
1795 "       Display currently cached IAX Dialplan results.\n";
1796
1797 static char show_peer_usage[] =
1798 "Usage: iax show peer <name>\n"
1799 "       Display details on specific IAX peer\n";
1800
1801 static struct ast_cli_entry cli_set_jitter = 
1802 { { "iax2", "set", "jitter", NULL }, iax2_set_jitter, "Sets IAX jitter buffer", jitter_usage };
1803
1804 static struct ast_cli_entry cli_show_stats =
1805 { { "iax2", "show", "stats", NULL }, iax2_show_stats, "Display IAX statistics", show_stats_usage };
1806
1807 static struct ast_cli_entry cli_show_cache =
1808 { { "iax2", "show", "cache", NULL }, iax2_show_cache, "Display IAX cached dialplan", show_cache_usage };
1809
1810 static struct ast_cli_entry  cli_show_peer =
1811         { { "iax2", "show", "peer", NULL }, iax2_show_peer, "Show details on specific IAX peer", show_peer_usage, complete_iax2_show_peer };
1812
1813 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
1814
1815 #ifdef BRIDGE_OPTIMIZATION
1816 static unsigned int calc_fakestamp(struct chan_iax2_pvt *from, struct chan_iax2_pvt *to, unsigned int ts);
1817
1818 static int forward_delivery(struct iax_frame *fr)
1819 {
1820         struct chan_iax2_pvt *p1, *p2;
1821         char iabuf[INET_ADDRSTRLEN];
1822         int res, orig_ts;
1823
1824         p1 = iaxs[fr->callno];
1825         p2 = iaxs[p1->bridgecallno];
1826         if (!p1)
1827                 return -1;
1828         if (!p2)
1829                 return -1;
1830
1831         if (option_debug)
1832                 ast_log(LOG_DEBUG, "forward_delivery: Forwarding ts=%d on %d/%d to %d/%d on %s:%d\n",
1833                                 fr->ts,
1834                                 p1->callno, p1->peercallno,
1835                                 p2->callno, p2->peercallno,
1836                                 ast_inet_ntoa(iabuf, sizeof(iabuf), p2->addr.sin_addr),
1837                                 ntohs(p2->addr.sin_port));
1838
1839         /* Undo wraparound - which can happen when full VOICE frame wasn't sent by our peer.
1840            This is necessary for when our peer is chan_iax2.c v1.1nn or earlier which didn't
1841            send full frame on timestamp wrap when doing optimized bridging
1842            (actually current code STILL doesn't)
1843         */
1844         if (fr->ts + 50000 <= p1->last) {
1845                 fr->ts = ( (p1->last & 0xFFFF0000) + 0x10000) | (fr->ts & 0xFFFF);
1846                 if (option_debug)
1847                         ast_log(LOG_DEBUG, "forward_delivery: pushed forward timestamp to %u\n", fr->ts);
1848         }
1849
1850         /* Send with timestamp adjusted to the origin of the outbound leg */
1851         /* But don't destroy inbound timestamp still needed later to set "last" */
1852         orig_ts = fr->ts;
1853         fr->ts = calc_fakestamp(p1, p2, fr->ts);
1854         res = iax2_send(p2, &fr->af, fr->ts, -1, 0, 0, 0);
1855         fr->ts = orig_ts;
1856         return res;
1857 }
1858 #endif
1859
1860 static void unwrap_timestamp(struct iax_frame *fr)
1861 {
1862         int x;
1863
1864         if ( (fr->ts & 0xFFFF0000) == (iaxs[fr->callno]->last & 0xFFFF0000) ) {
1865                 x = fr->ts - iaxs[fr->callno]->last;
1866                 if (x < -50000) {
1867                         /* Sudden big jump backwards in timestamp:
1868                            What likely happened here is that miniframe timestamp has circled but we haven't
1869                            gotten the update from the main packet.  We'll just pretend that we did, and
1870                            update the timestamp appropriately. */
1871                         fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) + 0x10000) | (fr->ts & 0xFFFF);
1872                         if (option_debug)
1873                                 ast_log(LOG_DEBUG, "schedule_delivery: pushed forward timestamp\n");
1874                 }
1875                 if (x > 50000) {
1876                         /* Sudden apparent big jump forwards in timestamp:
1877                            What's likely happened is this is an old miniframe belonging to the previous
1878                            top-16-bit timestamp that has turned up out of order.
1879                            Adjust the timestamp appropriately. */
1880                         fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) - 0x10000) | (fr->ts & 0xFFFF);
1881                         if (option_debug)
1882                                 ast_log(LOG_DEBUG, "schedule_delivery: pushed back timestamp\n");
1883                 }
1884         }
1885 }
1886
1887 static int schedule_delivery(struct iax_frame *fr, int reallydeliver, int updatehistory, int fromtrunk)
1888 {
1889         int ms,x;
1890         int delay;
1891         unsigned int orig_ts;
1892         int drops[MEMORY_SIZE];
1893         int min, max=0, prevjitterbuffer, maxone=0,y,z, match;
1894
1895         /* Remember current jitterbuffer so we can log any change */
1896         prevjitterbuffer = iaxs[fr->callno]->jitterbuffer;
1897         /* Similarly for the frame timestamp */
1898         orig_ts = fr->ts;
1899
1900 #if 0
1901         if (option_debug)
1902                 ast_log(LOG_DEBUG, "schedule_delivery: ts=%d, last=%d, really=%d, update=%d\n",
1903                                 fr->ts, iaxs[fr->callno]->last, reallydeliver, updatehistory);
1904 #endif
1905
1906         /* Attempt to recover wrapped timestamps */
1907         unwrap_timestamp(fr);
1908
1909         if (updatehistory) {
1910
1911                 /* Attempt to spot a change of timebase on timestamps coming from the other side
1912                    We detect by noticing a jump in consecutive timestamps that can't reasonably be explained
1913                    by network jitter or reordering.  Sometimes, also, the peer stops sending us frames
1914                    for a while - in this case this code might also resync us.  But that's not a bad thing.
1915                    Be careful of non-voice frames which are timestamped differently (especially ACKS!)
1916                    [that's why we only do this when updatehistory is true]
1917                 */
1918                 x = fr->ts - iaxs[fr->callno]->last;
1919                 if (x > TS_GAP_FOR_JB_RESYNC || x < -TS_GAP_FOR_JB_RESYNC) {
1920                         if (option_debug)
1921                                 ast_log(LOG_DEBUG, "schedule_delivery: call=%d: TS jumped.  resyncing rxcore (ts=%d, last=%d)\n",
1922                                                         fr->callno, fr->ts, iaxs[fr->callno]->last);
1923                         /* zap rxcore - calc_rxstamp will make a new one based on this frame */
1924                         iaxs[fr->callno]->rxcore.tv_sec = 0;
1925                         iaxs[fr->callno]->rxcore.tv_usec = 0;
1926                         /* wipe "last" if stamps have jumped backwards */
1927                         if (x<0)
1928                                 iaxs[fr->callno]->last = 0;
1929                         /* should we also empty history? */
1930                 }
1931
1932                 /* ms is a measure of the "lateness" of the frame relative to the "reference"
1933                    frame we received.  (initially the very first, but also see code just above here).
1934                    Understand that "ms" can easily be -ve if lag improves since the reference frame.
1935                    Called by IAX thread, with iaxsl lock held. */
1936                 ms = calc_rxstamp(iaxs[fr->callno], fr->ts) - fr->ts;
1937         
1938                 /* Rotate our history queue of "lateness".  Don't worry about those initial
1939                    zeros because the first entry will always be zero */
1940                 for (x=0;x<MEMORY_SIZE - 1;x++) 
1941                         iaxs[fr->callno]->history[x] = iaxs[fr->callno]->history[x+1];
1942                 /* Add a history entry for this one */
1943                 iaxs[fr->callno]->history[x] = ms;
1944
1945         }
1946         else
1947                 ms = 0;
1948
1949         /* delivery time is sender's sent timestamp converted back into absolute time according to our clock */
1950         if ( (!fromtrunk) && (iaxs[fr->callno]->rxcore.tv_sec || iaxs[fr->callno]->rxcore.tv_usec) ) {
1951                 fr->af.delivery.tv_sec = iaxs[fr->callno]->rxcore.tv_sec;
1952                 fr->af.delivery.tv_usec = iaxs[fr->callno]->rxcore.tv_usec;
1953                 fr->af.delivery.tv_sec += fr->ts / 1000;
1954                 fr->af.delivery.tv_usec += (fr->ts % 1000) * 1000;
1955                 if (fr->af.delivery.tv_usec >= 1000000) {
1956                         fr->af.delivery.tv_usec -= 1000000;
1957                         fr->af.delivery.tv_sec += 1;
1958                 }
1959         }
1960         else {
1961 #if 0
1962                 if (reallydeliver)
1963                         ast_log(LOG_DEBUG, "schedule_delivery: set delivery to 0 as we don't have an rxcore yet, or frame is from trunk.\n");
1964 #endif
1965                 fr->af.delivery.tv_sec = 0;
1966                 fr->af.delivery.tv_usec = 0;
1967         }
1968
1969         /* Initialize the minimum to reasonable values.  It's too much
1970            work to do the same for the maximum, repeatedly */
1971         min=iaxs[fr->callno]->history[0];
1972         for (z=0;z < iax2_dropcount + 1;z++) {
1973                 /* Start very optimistic ;-) */
1974                 max=-999999999;
1975                 for (x=0;x<MEMORY_SIZE;x++) {
1976                         if (max < iaxs[fr->callno]->history[x]) {
1977                                 /* We have a candidate new maximum value.  Make
1978                                    sure it's not in our drop list */
1979                                 match = 0;
1980                                 for (y=0;!match && (y<z);y++)
1981                                         match |= (drops[y] == x);
1982                                 if (!match) {
1983                                         /* It's not in our list, use it as the new maximum */
1984                                         max = iaxs[fr->callno]->history[x];
1985                                         maxone = x;
1986                                 }
1987                                 
1988                         }
1989                         if (!z) {
1990                                 /* On our first pass, find the minimum too */
1991                                 if (min > iaxs[fr->callno]->history[x])
1992                                         min = iaxs[fr->callno]->history[x];
1993                         }
1994                 }
1995 #if 1
1996                 drops[z] = maxone;
1997 #endif
1998         }
1999         /* Just for reference, keep the "jitter" value, the difference between the
2000            earliest and the latest. */
2001         if (max >= min)
2002                 iaxs[fr->callno]->jitter = max - min;   
2003         
2004         /* IIR filter for keeping track of historic jitter, but always increase
2005            historic jitter immediately for increase */
2006         
2007         if (iaxs[fr->callno]->jitter > iaxs[fr->callno]->historicjitter )
2008                 iaxs[fr->callno]->historicjitter = iaxs[fr->callno]->jitter;
2009         else
2010                 iaxs[fr->callno]->historicjitter = GAMMA * (double)iaxs[fr->callno]->jitter + (1-GAMMA) * 
2011                         iaxs[fr->callno]->historicjitter;
2012
2013         /* If our jitter buffer is too big (by a significant margin), then we slowly
2014            shrink it to avoid letting the change be perceived */
2015         if (max < iaxs[fr->callno]->jitterbuffer - max_jitter_buffer)
2016                 iaxs[fr->callno]->jitterbuffer -= jittershrinkrate;
2017
2018         /* If our jitter buffer headroom is too small (by a significant margin), then we slowly enlarge it */
2019         /* min_jitter_buffer should be SMALLER than max_jitter_buffer - leaving a "no mans land"
2020            in between - otherwise the jitterbuffer size will hunt up and down causing unnecessary
2021            disruption.  Set maxexcessbuffer to say 150msec, minexcessbuffer to say 50 */
2022         if (max > iaxs[fr->callno]->jitterbuffer - min_jitter_buffer)
2023                 iaxs[fr->callno]->jitterbuffer += jittershrinkrate;
2024
2025         /* If our jitter buffer is smaller than our maximum delay, grow the jitter
2026            buffer immediately to accomodate it (and a little more).  */
2027         if (max > iaxs[fr->callno]->jitterbuffer)
2028                 iaxs[fr->callno]->jitterbuffer = max 
2029                         /* + ((float)iaxs[fr->callno]->jitter) * 0.1 */;
2030
2031         /* If the caller just wanted us to update, return now */
2032         if (!reallydeliver)
2033                 return 0;
2034
2035         /* Subtract the lateness from our jitter buffer to know how long to wait
2036            before sending our packet.  */
2037         delay = iaxs[fr->callno]->jitterbuffer - ms;
2038
2039         /* Whatever happens, no frame waits longer than maxjitterbuffer */
2040         if (delay > maxjitterbuffer)
2041                 delay = maxjitterbuffer;
2042         
2043         /* If jitter buffer is disabled then just pretend the frame is "right on time" */
2044         /* If frame came from trunk, also don't do any delay */
2045         if ( (!ast_test_flag(iaxs[fr->callno], IAX_USEJITTERBUF)) || fromtrunk )
2046                 delay = 0;
2047
2048         if (option_debug) {
2049                 /* Log jitter stats for possible offline analysis */
2050                 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",
2051                                         fr->callno, fr->ts, orig_ts, iaxs[fr->callno]->last,
2052                                         (fr->af.frametype == AST_FRAME_VOICE) ? "VOICE" : "CONTROL",
2053                                         min, max, iaxs[fr->callno]->jitterbuffer,
2054                                         iaxs[fr->callno]->jitterbuffer - prevjitterbuffer,
2055                                         ms, delay,
2056                                         iaxs[fr->callno]->jitter, iaxs[fr->callno]->historicjitter);
2057         }
2058
2059         if (delay < 1) {
2060                 /* Don't deliver it more than 4 ms late */
2061                 if ((delay > -4) || (fr->af.frametype != AST_FRAME_VOICE)) {
2062                         if (option_debug)
2063                                 ast_log(LOG_DEBUG, "schedule_delivery: Delivering immediately (Calculated delay is %d)\n", delay);
2064                         __do_deliver(fr);
2065                 } else {
2066                         if (option_debug)
2067                                 ast_log(LOG_DEBUG, "schedule_delivery: Dropping voice packet since %dms delay is too old\n", delay);
2068                         /* Free our iax frame */
2069                         iax2_frame_free(fr);
2070                 }
2071         } else {
2072                 if (option_debug)
2073                         ast_log(LOG_DEBUG, "schedule_delivery: Scheduling delivery in %d ms\n", delay);
2074                 fr->retrans = ast_sched_add(sched, delay, do_deliver, fr);
2075         }
2076         return 0;
2077 }
2078
2079 static int iax2_transmit(struct iax_frame *fr)
2080 {
2081         /* Lock the queue and place this packet at the end */
2082         fr->next = NULL;
2083         fr->prev = NULL;
2084         /* By setting this to 0, the network thread will send it for us, and
2085            queue retransmission if necessary */
2086         fr->sentyet = 0;
2087         ast_mutex_lock(&iaxq.lock);
2088         if (!iaxq.head) {
2089                 /* Empty queue */
2090                 iaxq.head = fr;
2091                 iaxq.tail = fr;
2092         } else {
2093                 /* Double link */
2094                 iaxq.tail->next = fr;
2095                 fr->prev = iaxq.tail;
2096                 iaxq.tail = fr;
2097         }
2098         iaxq.count++;
2099         ast_mutex_unlock(&iaxq.lock);
2100         /* Wake up the network thread */
2101         pthread_kill(netthreadid, SIGURG);
2102         return 0;
2103 }
2104
2105
2106
2107 static int iax2_digit(struct ast_channel *c, char digit)
2108 {
2109         return send_command_locked(PTR_TO_CALLNO(c->pvt->pvt), AST_FRAME_DTMF, digit, 0, NULL, 0, -1);
2110 }
2111
2112 static int iax2_sendtext(struct ast_channel *c, char *text)
2113 {
2114         
2115         return send_command_locked(PTR_TO_CALLNO(c->pvt->pvt), AST_FRAME_TEXT,
2116                 0, 0, text, strlen(text) + 1, -1);
2117 }
2118
2119 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
2120 {
2121         return send_command_locked(PTR_TO_CALLNO(c->pvt->pvt), AST_FRAME_IMAGE, img->subclass, 0, img->data, img->datalen, -1);
2122 }
2123
2124 static int iax2_sendhtml(struct ast_channel *c, int subclass, char *data, int datalen)
2125 {
2126         return send_command_locked(PTR_TO_CALLNO(c->pvt->pvt), AST_FRAME_HTML, subclass, 0, data, datalen, -1);
2127 }
2128
2129 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
2130 {
2131         unsigned short callno = PTR_TO_CALLNO(newchan->pvt->pvt);
2132         ast_mutex_lock(&iaxsl[callno]);
2133         if (iaxs[callno])
2134                 iaxs[callno]->owner = newchan;
2135         else
2136                 ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n");
2137         ast_mutex_unlock(&iaxsl[callno]);
2138         return 0;
2139 }
2140
2141 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, int temponly);
2142 static struct iax2_user *build_user(const char *name, struct ast_variable *v, int temponly);
2143
2144 static void destroy_user(struct iax2_user *user);
2145
2146 static struct iax2_peer *realtime_peer(const char *peername)
2147 {
2148         struct ast_variable *var;
2149         struct ast_variable *tmp;
2150         struct iax2_peer *peer=NULL;
2151         time_t regseconds, nowtime;
2152         int dynamic=0;
2153         var = ast_load_realtime("iaxfriends", "name", peername, NULL);
2154         if (var) {
2155                 /* Make sure it's not a user only... */
2156                 peer = build_peer(peername, var, 1);
2157                 if (peer) {
2158                         /* Add some finishing touches, addresses, etc */
2159                         ast_set_flag(peer, IAX_TEMPONLY);       
2160                         tmp = var;
2161                         while(tmp) {
2162                                 if (!strcasecmp(tmp->name, "type")) {
2163                                         if (strcasecmp(tmp->value, "friend") &&
2164                                                 strcasecmp(tmp->value, "peer")) {
2165                                                 /* Whoops, we weren't supposed to exist! */
2166                                                 destroy_peer(peer);
2167                                                 peer = NULL;
2168                                                 break;
2169                                         } 
2170                                 } else if (!strcasecmp(tmp->name, "regseconds")) {
2171                                         if (sscanf(tmp->value, "%li", &regseconds) != 1)
2172                                                 regseconds = 0;
2173                                 } else if (!strcasecmp(tmp->name, "ipaddr")) {
2174                                         inet_aton(tmp->value, &(peer->addr.sin_addr));
2175                                 } else if (!strcasecmp(tmp->name, "port")) {
2176                                         peer->addr.sin_port = htons(atoi(tmp->value));
2177                                 } else if (!strcasecmp(tmp->name, "host")) {
2178                                         if (!strcasecmp(tmp->value, "dynamic"))
2179                                                 dynamic = 1;
2180                                 }
2181                                 tmp = tmp->next;
2182                         }
2183                         if (peer && dynamic) {
2184                                 time(&nowtime);
2185                                 if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE) {
2186                                         memset(&peer->addr, 0, sizeof(peer->addr));
2187                                         if (option_debug)
2188                                                 ast_log(LOG_DEBUG, "Bah, we're expired (%ld/%ld/%ld)!\n", nowtime - regseconds, regseconds, nowtime);
2189                                 }
2190                         }
2191                 }
2192                 ast_variables_destroy(var);
2193         }
2194         return peer;
2195 }
2196
2197 static struct iax2_user *realtime_user(const char *username)
2198 {
2199         struct ast_variable *var;
2200         struct ast_variable *tmp;
2201         struct iax2_user *user=NULL;
2202         var = ast_load_realtime("iaxfriends", "name", username, NULL);
2203         if (var) {
2204                 /* Make sure it's not a user only... */
2205                 user = build_user(username, var, 1);
2206                 if (user) {
2207                         /* Add some finishing touches, addresses, etc */
2208                         ast_set_flag(user, IAX_TEMPONLY);       
2209                         tmp = var;
2210                         while(tmp) {
2211                                 if (!strcasecmp(tmp->name, "type")) {
2212                                         if (strcasecmp(tmp->value, "friend") &&
2213                                                 strcasecmp(tmp->value, "user")) {
2214                                                 /* Whoops, we weren't supposed to exist! */
2215                                                 destroy_user(user);
2216                                                 user = NULL;
2217                                                 break;
2218                                         } 
2219                                 }
2220                                 tmp = tmp->next;
2221                         }
2222                 }
2223                 ast_variables_destroy(var);
2224         }
2225         return user;
2226 }
2227
2228 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin)
2229 {
2230         char port[10];
2231         char ipaddr[20];
2232         char regseconds[20];
2233         time_t nowtime;
2234         
2235         time(&nowtime);
2236         snprintf(regseconds, sizeof(regseconds), "%ld", nowtime);
2237         ast_inet_ntoa(ipaddr, sizeof(ipaddr), sin->sin_addr);
2238         snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
2239         ast_update_realtime("iaxfriends", "name", peername, "ipaddr", ipaddr, "port", port, "regseconds", regseconds, NULL);
2240 }
2241
2242
2243 static int create_addr(struct sockaddr_in *sin, int *capability, int *sendani, 
2244                                            int *maxtime, char *peer, char *context, int *trunk, 
2245                                            int *notransfer, int *usejitterbuf, int *encmethods, 
2246                                            char *username, int usernlen, char *secret, int seclen, 
2247                                            int *ofound, char *peercontext, char *timezone, int tzlen, char *pref_str, size_t pref_size,
2248                                            int *sockfd)
2249 {
2250         struct ast_hostent ahp; struct hostent *hp;
2251         struct iax2_peer *p;
2252         int found=0;
2253         if (sendani)
2254                 *sendani = 0;
2255         if (maxtime)
2256                 *maxtime = 0;
2257         if (trunk)
2258                 *trunk = 0;
2259         if (sockfd)
2260                 *sockfd = defaultsockfd;
2261         sin->sin_family = AF_INET;
2262         p = find_peer(peer);
2263         if (p) {
2264                 found++;
2265                 if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
2266                         (!p->maxms || ((p->lastms > 0)  && (p->lastms <= p->maxms)))) {
2267
2268                         if(pref_str) {
2269                                 ast_codec_pref_convert(&p->prefs, pref_str, pref_size, 1);
2270                         }
2271                         if (sendani)
2272                                 *sendani = ast_test_flag(p, IAX_SENDANI);               /* Whether we transmit ANI */
2273                         if (maxtime)
2274                                 *maxtime = p->maxms;            /* Max time they should take */
2275                         if (context)
2276                                 strncpy(context, p->context, AST_MAX_EXTENSION - 1);
2277                         if (peercontext)
2278                                 strncpy(peercontext, p->peercontext, AST_MAX_EXTENSION - 1);
2279                         if (trunk)
2280                                 *trunk = ast_test_flag(p, IAX_TRUNK);
2281                         if (capability)
2282                                 *capability = p->capability;
2283                         if (encmethods)
2284                                 *encmethods = p->encmethods;
2285                         if (username)
2286                                 strncpy(username, p->username, usernlen);
2287                         if (p->addr.sin_addr.s_addr) {
2288                                 sin->sin_addr = p->addr.sin_addr;
2289                                 sin->sin_port = p->addr.sin_port;
2290                         } else {
2291                                 sin->sin_addr = p->defaddr.sin_addr;
2292                                 sin->sin_port = p->defaddr.sin_port;
2293                         }
2294                         if (sockfd)
2295                                 *sockfd = p->sockfd;
2296                         if (notransfer)
2297                                 *notransfer = ast_test_flag(p, IAX_NOTRANSFER);
2298                         if (usejitterbuf)
2299                                 *usejitterbuf = ast_test_flag(p, IAX_USEJITTERBUF);
2300                         if (secret) {
2301                                 if (!ast_strlen_zero(p->dbsecret)) {
2302                                         char *family, *key=NULL;
2303                                         family = ast_strdupa(p->dbsecret);
2304                                         if (family) {
2305                                                 key = strchr(family, '/');
2306                                                 if (key) {
2307                                                         *key = '\0';
2308                                                         key++;
2309                                                 }
2310                                         }
2311                                         if (!family || !key || ast_db_get(family, key, secret, seclen)) {
2312                                                 ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", p->dbsecret);
2313                                                 if (ast_test_flag(p, IAX_TEMPONLY))
2314                                                         destroy_peer(p);
2315                                                 p = NULL;
2316                                         }
2317                                 } else
2318                                         strncpy(secret, p->secret, seclen); /* safe */
2319                         }
2320                         if (timezone)
2321                                 snprintf(timezone, tzlen-1, "%s", p->zonetag);
2322                 } else {
2323                         if (ast_test_flag(p, IAX_TEMPONLY))
2324                                 destroy_peer(p);
2325                         p = NULL;
2326                 }
2327         }
2328         if (ofound)
2329                 *ofound = found;
2330         if (!p && !found) {
2331                 if(pref_str) { /* use global iax prefs for unknown peer/user */
2332                         ast_codec_pref_convert(&prefs, pref_str, pref_size, 1);
2333                 }
2334
2335                 hp = ast_gethostbyname(peer, &ahp);
2336                 if (hp) {
2337                         memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
2338                         sin->sin_port = htons(IAX_DEFAULT_PORTNO);
2339                         return 0;
2340                 } else {
2341                         ast_log(LOG_WARNING, "No such host: %s\n", peer);
2342                         return -1;
2343                 }
2344         } else if (!p)
2345                 return -1;
2346         if (ast_test_flag(p, IAX_TEMPONLY))
2347                 destroy_peer(p);
2348         return 0;
2349 }
2350
2351 static int auto_congest(void *nothing)
2352 {
2353         int callno = PTR_TO_CALLNO(nothing);
2354         struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_CONGESTION };
2355         ast_mutex_lock(&iaxsl[callno]);
2356         if (iaxs[callno]) {
2357                 iaxs[callno]->initid = -1;
2358                 iax2_queue_frame(callno, &f);
2359                 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
2360         }
2361         ast_mutex_unlock(&iaxsl[callno]);
2362         return 0;
2363 }
2364
2365 static unsigned int iax2_datetime(char *tz)
2366 {
2367         time_t t;
2368         struct tm tm;
2369         unsigned int tmp;
2370         time(&t);
2371         localtime_r(&t, &tm);
2372         if (!ast_strlen_zero(tz))
2373                 ast_localtime(&t, &tm, tz);
2374         tmp  = (tm.tm_sec >> 1) & 0x1f;   /* 5 bits of seconds */
2375         tmp |= (tm.tm_min & 0x3f) << 5;   /* 6 bits of minutes */
2376         tmp |= (tm.tm_hour & 0x1f) << 11;   /* 5 bits of hours */
2377         tmp |= (tm.tm_mday & 0x1f) << 16; /* 5 bits of day of month */
2378         tmp |= ((tm.tm_mon + 1) & 0xf) << 21; /* 4 bits of month */
2379         tmp |= ((tm.tm_year - 100) & 0x7f) << 25; /* 7 bits of year */
2380         return tmp;
2381 }
2382
2383 static int iax2_call(struct ast_channel *c, char *dest, int timeout)
2384 {
2385         struct sockaddr_in sin;
2386         char host[256];
2387         char *rdest;
2388         char *rcontext;
2389         char *username;
2390         char *secret = NULL;
2391         char *hname;
2392         char *l=NULL, *n=NULL;
2393         struct iax_ie_data ied;
2394         char myrdest [5] = "s";
2395         char context[AST_MAX_EXTENSION] ="";
2396         char peercontext[AST_MAX_EXTENSION] ="";
2397         char *portno = NULL;
2398         char *opts = "";
2399         int encmethods=iax2_encryption;
2400         unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
2401         char *stringp=NULL;
2402         char storedusern[80], storedsecret[80];
2403         char tz[80] = "";       
2404         char out_prefs[32];
2405
2406         memset(out_prefs,0,32);
2407
2408         if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
2409                 ast_log(LOG_WARNING, "Line is already in use (%s)?\n", c->name);
2410                 return -1;
2411         }
2412         strncpy(host, dest, sizeof(host)-1);
2413         stringp=host;
2414         strsep(&stringp, "/");
2415         /* If no destination extension specified, use 's' */
2416         rdest = strsep(&stringp, "/");
2417         if (!rdest) 
2418                 rdest = myrdest;
2419         else {
2420                 /* Check for trailing options */
2421                 opts = strsep(&stringp, "/");
2422                 if (!opts)
2423                         opts = "";
2424         }
2425         stringp=rdest;
2426         strsep(&stringp, "@");
2427         rcontext = strsep(&stringp, "@");
2428         stringp=host;
2429         strsep(&stringp, "@");
2430         username = strsep(&stringp, "@");
2431         if (username) {
2432                 /* Really the second argument is the host, not the username */
2433                 hname = username;
2434                 username = host;
2435         } else {
2436                 hname = host;
2437         }
2438         if (username) {
2439                 stringp=username;
2440                 username = strsep(&stringp, ":");
2441                 secret = strsep(&stringp, ":");
2442         }
2443         stringp=hname;
2444         if (strsep(&stringp, ":")) {
2445                 stringp=hname;
2446                 strsep(&stringp, ":");
2447                 portno = strsep(&stringp, ":");
2448         }
2449         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)) {
2450                 ast_log(LOG_WARNING, "No address associated with '%s'\n", hname);
2451                 return -1;
2452         }
2453         /* Keep track of the context for outgoing calls too */
2454         strncpy(c->context, context, sizeof(c->context) - 1);
2455         if (portno) {
2456                 sin.sin_port = htons(atoi(portno));
2457         }
2458         l = c->cid.cid_num;
2459         n = c->cid.cid_name;
2460         /* Now build request */ 
2461         memset(&ied, 0, sizeof(ied));
2462         /* On new call, first IE MUST be IAX version of caller */
2463         iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
2464         iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, rdest);
2465         if (strchr(opts, 'a')) {
2466                 /* Request auto answer */
2467                 iax_ie_append(&ied, IAX_IE_AUTOANSWER);
2468         }
2469         iax_ie_append_str(&ied, IAX_IE_CODEC_PREFS, out_prefs);
2470
2471         if (l) {
2472                 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
2473                 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
2474         } else
2475                 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, AST_PRES_NUMBER_NOT_AVAILABLE);
2476         iax_ie_append_byte(&ied, IAX_IE_CALLINGTON, c->cid.cid_ton);
2477         iax_ie_append_short(&ied, IAX_IE_CALLINGTNS, c->cid.cid_tns);
2478         if (n)
2479                 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n);
2480         if (ast_test_flag(iaxs[callno], IAX_SENDANI) && c->cid.cid_ani) {
2481                 iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, c->cid.cid_ani);
2482         }
2483         if (c->language && !ast_strlen_zero(c->language))
2484                 iax_ie_append_str(&ied, IAX_IE_LANGUAGE, c->language);
2485         if (c->cid.cid_dnid && !ast_strlen_zero(c->cid.cid_dnid))
2486                 iax_ie_append_str(&ied, IAX_IE_DNID, c->cid.cid_dnid);
2487         if (rcontext)
2488                 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, rcontext);
2489         else if (strlen(peercontext))
2490                 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, peercontext);
2491         if (!username && !ast_strlen_zero(storedusern))
2492                 username = storedusern;
2493         if (username)
2494                 iax_ie_append_str(&ied, IAX_IE_USERNAME, username);
2495         if (encmethods)
2496                 iax_ie_append_short(&ied, IAX_IE_ENCRYPTION, encmethods);
2497         if (!secret && !ast_strlen_zero(storedsecret))
2498                 secret = storedsecret;
2499         ast_mutex_lock(&iaxsl[callno]);
2500         if (!ast_strlen_zero(c->context))
2501                 strncpy(iaxs[callno]->context, c->context, sizeof(iaxs[callno]->context) - 1);
2502         if (username)
2503                 strncpy(iaxs[callno]->username, username, sizeof(iaxs[callno]->username)-1);
2504         iaxs[callno]->encmethods = encmethods;
2505         if (secret) {
2506                 if (secret[0] == '[') {
2507                         /* This is an RSA key, not a normal secret */
2508                         strncpy(iaxs[callno]->outkey, secret + 1, sizeof(iaxs[callno]->secret)-1);
2509                         if (!ast_strlen_zero(iaxs[callno]->outkey)) {
2510                                 iaxs[callno]->outkey[strlen(iaxs[callno]->outkey) - 1] = '\0';
2511                         }
2512                 } else
2513                         strncpy(iaxs[callno]->secret, secret, sizeof(iaxs[callno]->secret)-1);
2514         }
2515         iax_ie_append_int(&ied, IAX_IE_FORMAT, c->nativeformats);
2516         iax_ie_append_int(&ied, IAX_IE_CAPABILITY, iaxs[callno]->capability);
2517         iax_ie_append_short(&ied, IAX_IE_ADSICPE, c->adsicpe);
2518         iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime(tz));
2519         /* Transmit the string in a "NEW" request */
2520 #if 0
2521         /* XXX We have no equivalent XXX */
2522         if (option_verbose > 2)
2523                 ast_verbose(VERBOSE_PREFIX_3 "Calling using options '%s'\n", requeststr);
2524 #endif          
2525         if (iaxs[callno]->maxtime) {
2526                 /* Initialize pingtime and auto-congest time */
2527                 iaxs[callno]->pingtime = iaxs[callno]->maxtime / 2;
2528                 iaxs[callno]->initid = ast_sched_add(sched, iaxs[callno]->maxtime * 2, auto_congest, CALLNO_TO_PTR(callno));
2529         } else if (autokill) {
2530                 iaxs[callno]->pingtime = autokill / 2;
2531                 iaxs[callno]->initid = ast_sched_add(sched, autokill * 2, auto_congest, CALLNO_TO_PTR(callno));
2532         }
2533         send_command(iaxs[callno], AST_FRAME_IAX,
2534                 IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
2535         ast_mutex_unlock(&iaxsl[callno]);
2536         ast_setstate(c, AST_STATE_RINGING);
2537         return 0;
2538 }
2539
2540 static int iax2_hangup(struct ast_channel *c) 
2541 {
2542         unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
2543         int alreadygone;
2544         struct iax_ie_data ied;
2545         memset(&ied, 0, sizeof(ied));
2546         ast_mutex_lock(&iaxsl[callno]);
2547         if (callno && iaxs[callno]) {
2548                 ast_log(LOG_DEBUG, "We're hanging up %s now...\n", c->name);
2549                 alreadygone = ast_test_flag(iaxs[callno], IAX_ALREADYGONE);
2550                 /* Send the hangup unless we have had a transmission error or are already gone */
2551                 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, (unsigned char)c->hangupcause);
2552                 if (!iaxs[callno]->error && !alreadygone) 
2553                         send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1);
2554                 /* Explicitly predestroy it */
2555                 iax2_predestroy_nolock(callno);
2556                 /* If we were already gone to begin with, destroy us now */
2557                 if (alreadygone) {
2558                         ast_log(LOG_DEBUG, "Really destroying %s now...\n", c->name);
2559                         iax2_destroy_nolock(callno);
2560                 }
2561         }
2562         ast_mutex_unlock(&iaxsl[callno]);
2563         if (option_verbose > 2) 
2564                 ast_verbose(VERBOSE_PREFIX_3 "Hungup '%s'\n", c->name);
2565         return 0;
2566 }
2567
2568 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
2569 {
2570         struct ast_option_header *h;
2571         int res;
2572         h = malloc(datalen + sizeof(struct ast_option_header));
2573         if (h) {
2574                 h->flag = AST_OPTION_FLAG_REQUEST;
2575                 h->option = htons(option);
2576                 memcpy(h->data, data, datalen);
2577                 res = send_command_locked(PTR_TO_CALLNO(c->pvt->pvt), AST_FRAME_CONTROL,
2578                         AST_CONTROL_OPTION, 0, (char *)h, datalen + sizeof(struct ast_option_header), -1);
2579                 free(h);
2580                 return res;
2581         } else 
2582                 ast_log(LOG_WARNING, "Out of memory\n");
2583         return -1;
2584 }
2585
2586 static struct ast_frame *iax2_read(struct ast_channel *c) 
2587 {
2588         static struct ast_frame f = { AST_FRAME_NULL, };
2589         ast_log(LOG_NOTICE, "I should never be called!\n");
2590         return &f;
2591 }
2592
2593 static int iax2_start_transfer(unsigned short callno0, unsigned short callno1)
2594 {
2595         int res;
2596         struct iax_ie_data ied0;
2597         struct iax_ie_data ied1;
2598         unsigned int transferid = rand();
2599         memset(&ied0, 0, sizeof(ied0));
2600         iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &iaxs[callno1]->addr);
2601         iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[callno1]->peercallno);
2602         iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, transferid);
2603
2604         memset(&ied1, 0, sizeof(ied1));
2605         iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &iaxs[callno0]->addr);
2606         iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[callno0]->peercallno);
2607         iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, transferid);
2608         
2609         res = send_command(iaxs[callno0], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
2610         if (res)
2611                 return -1;
2612         res = send_command(iaxs[callno1], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
2613         if (res)
2614                 return -1;
2615         iaxs[callno0]->transferring = TRANSFER_BEGIN;
2616         iaxs[callno1]->transferring = TRANSFER_BEGIN;
2617         return 0;
2618 }
2619
2620 static void lock_both(unsigned short callno0, unsigned short callno1)
2621 {
2622         ast_mutex_lock(&iaxsl[callno0]);
2623         while (ast_mutex_trylock(&iaxsl[callno1])) {
2624                 ast_mutex_unlock(&iaxsl[callno0]);
2625                 usleep(10);
2626                 ast_mutex_lock(&iaxsl[callno0]);
2627         }
2628 }
2629
2630 static void unlock_both(unsigned short callno0, unsigned short callno1)
2631 {
2632         ast_mutex_unlock(&iaxsl[callno1]);
2633         ast_mutex_unlock(&iaxsl[callno0]);
2634 }
2635
2636 static int iax2_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
2637 {
2638         struct ast_channel *cs[3];
2639         struct ast_channel *who;
2640         int to = -1;
2641         int res = -1;
2642         int transferstarted=0;
2643         struct ast_frame *f;
2644         unsigned short callno0 = PTR_TO_CALLNO(c0->pvt->pvt);
2645         unsigned short callno1 = PTR_TO_CALLNO(c1->pvt->pvt);
2646         struct timeval waittimer = {0, 0}, tv;
2647         
2648         lock_both(callno0, callno1);
2649         /* Put them in native bridge mode */
2650         iaxs[callno0]->bridgecallno = callno1;
2651         iaxs[callno1]->bridgecallno = callno0;
2652         unlock_both(callno0, callno1);
2653
2654         /* If not, try to bridge until we can execute a transfer, if we can */
2655         cs[0] = c0;
2656         cs[1] = c1;
2657         for (/* ever */;;) {
2658                 /* Check in case we got masqueraded into */
2659                 if ((c0->type != channeltype) || (c1->type != channeltype)) {
2660                         if (option_verbose > 2)
2661                                 ast_verbose(VERBOSE_PREFIX_3 "Can't masquerade, we're different...\n");
2662                         /* Remove from native mode */
2663                         if (c0->type == channeltype) {
2664                                 ast_mutex_lock(&iaxsl[callno0]);
2665                                 iaxs[callno0]->bridgecallno = 0;
2666                                 ast_mutex_unlock(&iaxsl[callno0]);
2667                         }
2668                         if (c1->type == channeltype) {
2669                                 ast_mutex_lock(&iaxsl[callno1]);
2670                                 iaxs[callno1]->bridgecallno = 0;
2671                                 ast_mutex_unlock(&iaxsl[callno1]);
2672                         }
2673                         return -2;
2674                 }
2675                 if (c0->nativeformats != c1->nativeformats) {
2676                         if (option_verbose > 2)
2677                                 ast_verbose(VERBOSE_PREFIX_3 "Operating with different codecs, can't native bridge...\n");
2678                         /* Remove from native mode */
2679                         lock_both(callno0, callno1);
2680                         iaxs[callno0]->bridgecallno = 0;
2681                         iaxs[callno1]->bridgecallno = 0;
2682                         unlock_both(callno0, callno1);
2683                         return -2;
2684                 }
2685                 /* check if transfered and if we really want native bridging */
2686                 if (!transferstarted && !ast_test_flag(iaxs[callno0], IAX_NOTRANSFER) && !ast_test_flag(iaxs[callno1], IAX_NOTRANSFER) && 
2687                 !(flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
2688                         /* Try the transfer */
2689                         if (iax2_start_transfer(callno0, callno1))
2690                                 ast_log(LOG_WARNING, "Unable to start the transfer\n");
2691                         transferstarted = 1;
2692                 }
2693                 if ((iaxs[callno0]->transferring == TRANSFER_RELEASED) && (iaxs[callno1]->transferring == TRANSFER_RELEASED)) {
2694                         /* Call has been transferred.  We're no longer involved */
2695                         gettimeofday(&tv, NULL);
2696                         if (!waittimer.tv_sec && !waittimer.tv_usec) {
2697                                 waittimer.tv_sec = tv.tv_sec;
2698                                 waittimer.tv_usec = tv.tv_usec;
2699                         } else if (tv.tv_sec - waittimer.tv_sec > IAX_LINGER_TIMEOUT) {
2700                                 c0->_softhangup |= AST_SOFTHANGUP_DEV;
2701                                 c1->_softhangup |= AST_SOFTHANGUP_DEV;
2702                                 *fo = NULL;
2703                                 *rc = c0;
2704                                 res = 0;
2705                                 break;
2706                         }
2707                 }
2708                 to = 1000;
2709                 who = ast_waitfor_n(cs, 2, &to);
2710                 if (!who) {
2711                         if (ast_check_hangup(c0) || ast_check_hangup(c1)) {
2712                                 res = -1;
2713                                 break;
2714                         }
2715                         continue;
2716                 }
2717                 f = ast_read(who);
2718                 if (!f) {
2719                         *fo = NULL;
2720                         *rc = who;
2721                         res = 0;
2722                         break;
2723                 }
2724                 if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
2725                         *fo = f;
2726                         *rc = who;
2727                         res =  0;
2728                         break;
2729                 }
2730                 if ((f->frametype == AST_FRAME_VOICE) ||
2731                         (f->frametype == AST_FRAME_TEXT) ||
2732                         (f->frametype == AST_FRAME_VIDEO) || 
2733                         (f->frametype == AST_FRAME_IMAGE) ||
2734                         (f->frametype == AST_FRAME_DTMF)) {
2735                         if ((f->frametype == AST_FRAME_DTMF) && 
2736                                 (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
2737                                 if ((who == c0)) {
2738                                         if  ((flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
2739                                                 *rc = c0;
2740                                                 *fo = f;
2741                                                 /* Take out of conference mode */
2742                                                 res = 0;
2743                                                 /* Remove from native mode */
2744                                                 break;
2745                                         } else 
2746                                                 goto tackygoto;
2747                                 } else
2748                                 if ((who == c1)) {
2749                                         if (flags & AST_BRIDGE_DTMF_CHANNEL_1) {
2750                                                 *rc = c1;
2751                                                 *fo = f;
2752                                                 res =  0;
2753                                                 /* Remove from native mode */
2754                                                 break;
2755                                         } else
2756                                                 goto tackygoto;
2757                                 }
2758                         } else {
2759 #if 0
2760                                 ast_log(LOG_DEBUG, "Read from %s\n", who->name);
2761                                 if (who == last) 
2762                                         ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
2763                                 last = who;
2764 #endif
2765 tackygoto:
2766                                 if (who == c0) 
2767                                         ast_write(c1, f);
2768                                 else 
2769                                         ast_write(c0, f);
2770                         }
2771                         ast_frfree(f);
2772                 } else
2773                         ast_frfree(f);
2774                 /* Swap who gets priority */
2775                 cs[2] = cs[0];
2776                 cs[0] = cs[1];
2777                 cs[1] = cs[2];
2778         }
2779         lock_both(callno0, callno1);
2780         if(iaxs[callno0])
2781                 iaxs[callno0]->bridgecallno = 0;
2782         if(iaxs[callno1])
2783                 iaxs[callno1]->bridgecallno = 0;
2784         unlock_both(callno0, callno1);
2785         return res;
2786 }
2787
2788 static int iax2_answer(struct ast_channel *c)
2789 {
2790         unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
2791         if (option_debug)
2792                 ast_log(LOG_DEBUG, "Answering\n");
2793         return send_command_locked(callno, AST_FRAME_CONTROL, AST_CONTROL_ANSWER, 0, NULL, 0, -1);
2794 }
2795
2796 static int iax2_indicate(struct ast_channel *c, int condition)
2797 {
2798         unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
2799         if (option_debug)
2800                 ast_log(LOG_DEBUG, "Indicating condition %d\n", condition);
2801         return send_command_locked(callno, AST_FRAME_CONTROL, condition, 0, NULL, 0, -1);
2802 }
2803         
2804 static int iax2_transfer(struct ast_channel *c, char *dest)
2805 {
2806         unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
2807         struct iax_ie_data ied;
2808         char tmp[256] = "", *context;
2809         strncpy(tmp, dest, sizeof(tmp) - 1);
2810         context = strchr(tmp, '@');
2811         if (context) {
2812                 *context = '\0';
2813                 context++;
2814         }
2815         memset(&ied, 0, sizeof(ied));
2816         iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, tmp);
2817         if (context)
2818                 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, context);
2819         if (option_debug)
2820                 ast_log(LOG_DEBUG, "Transferring '%s' to '%s'\n", c->name, dest);
2821         return send_command_locked(callno, AST_FRAME_IAX, IAX_COMMAND_TRANSFER, 0, ied.buf, ied.pos, -1);
2822 }
2823         
2824
2825 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
2826
2827 static int iax2_getpeertrunk(struct sockaddr_in sin)
2828 {
2829         struct iax2_peer *peer;
2830         int res = 0;
2831         ast_mutex_lock(&peerl.lock);
2832         peer = peerl.peers;
2833         while(peer) {
2834                 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
2835                                 (peer->addr.sin_port == sin.sin_port)) {
2836                                         res = ast_test_flag(peer, IAX_TRUNK);
2837                                         break;
2838                 }
2839                 peer = peer->next;
2840         }
2841         ast_mutex_unlock(&peerl.lock);
2842         return res;
2843 }
2844
2845 static struct ast_channel *ast_iax2_new(int callno, int state, int capability)
2846 {
2847         struct ast_channel *tmp;
2848         struct chan_iax2_pvt *i;
2849         struct ast_variable *v = NULL;
2850
2851         /* Don't hold call lock */
2852         ast_mutex_unlock(&iaxsl[callno]);
2853         tmp = ast_channel_alloc(1);
2854         ast_mutex_lock(&iaxsl[callno]);
2855         i = iaxs[callno];
2856         if (i && tmp) {
2857                 if (!ast_strlen_zero(i->username))
2858                         snprintf(tmp->name, sizeof(tmp->name), "IAX2/%s@%s/%d", i->username, i->host, i->callno);
2859                 else
2860                         snprintf(tmp->name, sizeof(tmp->name), "IAX2/%s/%d", i->host, i->callno);
2861                 tmp->type = channeltype;
2862                 /* We can support any format by default, until we get restricted */
2863                 tmp->nativeformats = capability;
2864                 tmp->readformat = ast_best_codec(capability);
2865                 tmp->writeformat = ast_best_codec(capability);
2866                 tmp->pvt->pvt = CALLNO_TO_PTR(i->callno);
2867                 tmp->pvt->send_digit = iax2_digit;
2868                 tmp->pvt->send_text = iax2_sendtext;
2869                 tmp->pvt->send_image = iax2_sendimage;
2870                 tmp->pvt->send_html = iax2_sendhtml;
2871                 tmp->pvt->call = iax2_call;
2872                 tmp->pvt->hangup = iax2_hangup;
2873                 tmp->pvt->answer = iax2_answer;
2874                 tmp->pvt->read = iax2_read;
2875                 tmp->pvt->write = iax2_write;
2876                 tmp->pvt->write_video = iax2_write;
2877                 tmp->pvt->indicate = iax2_indicate;
2878                 tmp->pvt->setoption = iax2_setoption;
2879                 tmp->pvt->bridge = iax2_bridge;
2880                 tmp->pvt->transfer = iax2_transfer;
2881                 if (!ast_strlen_zero(i->cid_num))
2882                         tmp->cid.cid_num = strdup(i->cid_num);
2883                 if (!ast_strlen_zero(i->cid_name))
2884                         tmp->cid.cid_name = strdup(i->cid_name);
2885                 if (!ast_strlen_zero(i->ani))
2886                         tmp->cid.cid_ani = strdup(i->ani);
2887                 if (!ast_strlen_zero(i->language))
2888                         strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
2889                 if (!ast_strlen_zero(i->dnid))
2890                         tmp->cid.cid_dnid = strdup(i->dnid);
2891                 tmp->cid.cid_pres = i->calling_pres;
2892                 tmp->cid.cid_ton = i->calling_ton;
2893                 tmp->cid.cid_tns = i->calling_tns;
2894                 if (!ast_strlen_zero(i->accountcode))
2895                         strncpy(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode)-1);
2896                 if (i->amaflags)
2897                         tmp->amaflags = i->amaflags;
2898                 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
2899                 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
2900                 tmp->adsicpe = i->peeradsicpe;
2901                 tmp->pvt->fixup = iax2_fixup;
2902                 i->owner = tmp;
2903                 i->capability = capability;
2904                 ast_setstate(tmp, state);
2905                 ast_mutex_lock(&usecnt_lock);
2906                 usecnt++;
2907                 ast_mutex_unlock(&usecnt_lock);
2908                 ast_update_use_count();
2909                 if (state != AST_STATE_DOWN) {
2910                         if (ast_pbx_start(tmp)) {
2911                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
2912                                 ast_hangup(tmp);
2913                                 tmp = NULL;
2914                         }
2915                 }
2916                 for (v = i->vars ; v ; v = v->next)
2917                         pbx_builtin_setvar_helper(tmp,v->name,v->value);
2918                 
2919         }
2920         return tmp;
2921 }
2922
2923 static unsigned int calc_txpeerstamp(struct iax2_trunk_peer *tpeer, int sampms, struct timeval *tv)
2924 {
2925         unsigned long int mssincetx; /* unsigned to handle overflows */
2926         long int ms, pred;
2927
2928         tpeer->trunkact = *tv;
2929         mssincetx = (tv->tv_sec - tpeer->lasttxtime.tv_sec) * 1000 +
2930                         (1000000 + tv->tv_usec - tpeer->lasttxtime.tv_usec) / 1000 - 1000;
2931         if (mssincetx > 5000 || (!tpeer->txtrunktime.tv_sec && !tpeer->txtrunktime.tv_usec)) {
2932                 /* If it's been at least 5 seconds since the last time we transmitted on this trunk, reset our timers */
2933                 tpeer->txtrunktime.tv_sec = tv->tv_sec;
2934                 tpeer->txtrunktime.tv_usec = tv->tv_usec;
2935                 tpeer->lastsent = 999999;
2936         }
2937         /* Update last transmit time now */
2938         tpeer->lasttxtime.tv_sec = tv->tv_sec;
2939         tpeer->lasttxtime.tv_usec = tv->tv_usec;
2940         
2941         /* Calculate ms offset */
2942         ms = (tv->tv_sec - tpeer->txtrunktime.tv_sec) * 1000 +
2943                 (1000000 + tv->tv_usec - tpeer->txtrunktime.tv_usec) / 1000 - 1000;
2944         /* Predict from last value */
2945         pred = tpeer->lastsent + sampms;
2946         if (abs(ms - pred) < MAX_TIMESTAMP_SKEW)
2947                 ms = pred;
2948         
2949         /* We never send the same timestamp twice, so fudge a little if we must */
2950         if (ms == tpeer->lastsent)
2951                 ms = tpeer->lastsent + 1;
2952         tpeer->lastsent = ms;
2953         return ms;
2954 }
2955
2956 static unsigned int fix_peerts(struct timeval *tv, int callno, unsigned int ts)
2957 {
2958         long ms;        /* NOT unsigned */
2959         if (!iaxs[callno]->rxcore.tv_sec && !iaxs[callno]->rxcore.tv_usec) {
2960                 /* Initialize rxcore time if appropriate */
2961                 gettimeofday(&iaxs[callno]->rxcore, NULL);
2962                 /* Round to nearest 20ms so traces look pretty */
2963                 iaxs[callno]->rxcore.tv_usec -= iaxs[callno]->rxcore.tv_usec % 20000;
2964         }
2965         /* Calculate difference between trunk and channel */
2966         ms = (tv->tv_sec - iaxs[callno]->rxcore.tv_sec) * 1000 + 
2967                 (1000000 + tv->tv_usec - iaxs[callno]->rxcore.tv_usec) / 1000 - 1000;
2968         /* Return as the sum of trunk time and the difference between trunk and real time */
2969         return ms + ts;
2970 }
2971
2972 static void add_ms(struct timeval *tv, int ms) {
2973   tv->tv_usec += ms * 1000;
2974   if(tv->tv_usec > 1000000) {
2975       tv->tv_usec -= 1000000;
2976       tv->tv_sec++;
2977   }
2978   if(tv->tv_usec < 0) {
2979       tv->tv_usec += 1000000;
2980       tv->tv_sec--;
2981   }
2982 }
2983
2984 static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts, struct ast_frame *f)
2985 {
2986         struct timeval tv;
2987         int ms;
2988         int voice = 0;
2989         int genuine = 0;
2990         struct timeval *delivery = NULL;
2991
2992         /* What sort of frame do we have?: voice is self-explanatory
2993            "genuine" means an IAX frame - things like LAGRQ/RP, PING/PONG, ACK
2994            non-genuine frames are CONTROL frames [ringing etc], DTMF
2995            The "genuine" distinction is needed because genuine frames must get a clock-based timestamp,
2996            the others need a timestamp slaved to the voice frames so that they go in sequence
2997         */
2998         if (f) {
2999                 if (f->frametype == AST_FRAME_VOICE) {
3000                         voice = 1;
3001                         delivery = &f->delivery;
3002                 } else if (f->frametype == AST_FRAME_IAX) {
3003                         genuine = 1;
3004                 } else if (f->frametype == AST_FRAME_CNG) {
3005                         p->notsilenttx = 0;     
3006                 }
3007         }
3008         if (!p->offset.tv_sec && !p->offset.tv_usec) {
3009                 gettimeofday(&p->offset, NULL);
3010                 /* Round to nearest 20ms for nice looking traces */
3011                 p->offset.tv_usec -= p->offset.tv_usec % 20000;
3012         }
3013         /* If the timestamp is specified, just send it as is */
3014         if (ts)
3015                 return ts;
3016         /* If we have a time that the frame arrived, always use it to make our timestamp */
3017         if (delivery && (delivery->tv_sec || delivery->tv_usec)) {
3018                 ms = (delivery->tv_sec - p->offset.tv_sec) * 1000 +
3019                         (1000000 + delivery->tv_usec - p->offset.tv_usec) / 1000 - 1000;
3020                 if (option_debug)
3021                         ast_log(LOG_DEBUG, "calc_timestamp: call %d/%d: Timestamp slaved to delivery time\n", p->callno, iaxs[p->callno]->peercallno);
3022         } else {
3023