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