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