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