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