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