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