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