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