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