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