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