4c51915289c4b72059c2c30a540de93055b1318b
[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         /* Undo wraparound - which can happen when full VOICE frame wasn't sent by our peer.
1676            This is necessary for when our peer is chan_iax2.c v1.175 or earlier which didn't
1677            send full frame on timestamp wrap when doing optimized bridging
1678         */
1679         if (fr->ts + 32767 <= p1->last) {
1680                 fr->ts = ( (p1->last & 0xFFFF0000) + 0x10000) | (fr->ts & 0xFFFF);
1681                 p1->last = fr->ts; /* necessary? */
1682                 if (option_debug)
1683                         ast_log(LOG_DEBUG, "forward_delivery: pushed forward timestamp to %u\n", fr->ts);
1684         }
1685
1686         /* Fix relative timestamp */
1687         fr->ts = calc_fakestamp(p1, p2, fr->ts);
1688         /* Now just send it send on the 2nd one 
1689            with adjusted timestamp */
1690         return iax2_send(p2, &fr->af, fr->ts, -1, 0, 0, 0);
1691 }
1692 #endif
1693
1694 static int schedule_delivery(struct iax_frame *fr, int reallydeliver, int updatehistory)
1695 {
1696         int ms,x;
1697         int drops[MEMORY_SIZE];
1698         int min, max=0, prevjitterbuffer, maxone=0,y,z, match;
1699
1700         /* Remember current jitterbuffer so we can log any change */
1701         prevjitterbuffer = iaxs[fr->callno]->jitterbuffer;
1702
1703         /* ms is a measure of the "lateness" of the packet relative to the first
1704            packet we received.  Understand that "ms" can easily be -ve if lag improves
1705            since call start.
1706            Called by IAX thread, with iaxsl lock held. */
1707         ms = calc_rxstamp(iaxs[fr->callno]) - fr->ts;
1708
1709         if (ms > 32767) {
1710                 /* What likely happened here is that our counter has circled but we haven't
1711                    gotten the update from the main packet.  We'll just pretend that we did, and
1712                    update the timestamp appropriately. */
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 forward timestamp\n");
1719         }
1720
1721         if (ms < -32768) {
1722                 /* We got this packet out of order.  Lets add 65536 to it to bring it into our new
1723                    time frame */
1724                 /*ms += 65536;  fr->ts -= 65536;*/
1725                 fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) - 0x10000) | (fr->ts & 0xFFFF);
1726                 iaxs[fr->callno]->last = fr->ts;
1727                 ms = calc_rxstamp(iaxs[fr->callno]) - fr->ts;
1728                 if (option_debug)
1729                         ast_log(LOG_DEBUG, "schedule_delivery: pushed back timestamp\n");
1730         }
1731
1732         /* delivery time is sender's sent timestamp converted back into absolute time according to our clock */
1733         fr->af.delivery.tv_sec = iaxs[fr->callno]->rxcore.tv_sec;
1734         fr->af.delivery.tv_usec = iaxs[fr->callno]->rxcore.tv_usec;
1735         fr->af.delivery.tv_sec += fr->ts / 1000;
1736         fr->af.delivery.tv_usec += (fr->ts % 1000) * 1000;
1737         if (fr->af.delivery.tv_usec >= 1000000) {
1738                 fr->af.delivery.tv_usec -= 1000000;
1739                 fr->af.delivery.tv_sec += 1;
1740         }
1741
1742         /* Rotate our history queue of "lateness".  Don't worry about those initial
1743            zeros because the first entry will always be zero */
1744         if (updatehistory) {
1745                 for (x=0;x<MEMORY_SIZE - 1;x++) 
1746                         iaxs[fr->callno]->history[x] = iaxs[fr->callno]->history[x+1];
1747                 /* Add a history entry for this one */
1748                 iaxs[fr->callno]->history[x] = ms;
1749         }
1750
1751         /* Initialize the minimum to reasonable values.  It's too much
1752            work to do the same for the maximum, repeatedly */
1753         min=iaxs[fr->callno]->history[0];
1754         for (z=0;z < iax2_dropcount + 1;z++) {
1755                 /* Start very optimistic ;-) */
1756                 max=-999999999;
1757                 for (x=0;x<MEMORY_SIZE;x++) {
1758                         if (max < iaxs[fr->callno]->history[x]) {
1759                                 /* We have a candidate new maximum value.  Make
1760                                    sure it's not in our drop list */
1761                                 match = 0;
1762                                 for (y=0;!match && (y<z);y++)
1763                                         match |= (drops[y] == x);
1764                                 if (!match) {
1765                                         /* It's not in our list, use it as the new maximum */
1766                                         max = iaxs[fr->callno]->history[x];
1767                                         maxone = x;
1768                                 }
1769                                 
1770                         }
1771                         if (!z) {
1772                                 /* On our first pass, find the minimum too */
1773                                 if (min > iaxs[fr->callno]->history[x])
1774                                         min = iaxs[fr->callno]->history[x];
1775                         }
1776                 }
1777 #if 1
1778                 drops[z] = maxone;
1779 #endif
1780         }
1781         /* Just for reference, keep the "jitter" value, the difference between the
1782            earliest and the latest. */
1783         iaxs[fr->callno]->jitter = max - min;   
1784         
1785         /* IIR filter for keeping track of historic jitter, but always increase
1786            historic jitter immediately for increase */
1787         
1788         if (iaxs[fr->callno]->jitter > iaxs[fr->callno]->historicjitter )
1789                 iaxs[fr->callno]->historicjitter = iaxs[fr->callno]->jitter;
1790         else
1791                 iaxs[fr->callno]->historicjitter = GAMMA * (double)iaxs[fr->callno]->jitter + (1-GAMMA) * 
1792                         iaxs[fr->callno]->historicjitter;
1793
1794         /* If our jitter buffer is too big (by a significant margin), then we slowly
1795            shrink it to avoid letting the change be perceived */
1796         if (max < iaxs[fr->callno]->jitterbuffer - max_jitter_buffer)
1797                 iaxs[fr->callno]->jitterbuffer -= jittershrinkrate;
1798
1799         /* If our jitter buffer headroom is too small (by a significant margin), then we slowly enlarge it */
1800         /* min_jitter_buffer should be SMALLER than max_jitter_buffer - leaving a "no mans land"
1801            in between - otherwise the jitterbuffer size will hunt up and down causing unnecessary
1802            disruption.  Set maxexcessbuffer to say 150msec, minexcessbuffer to say 50 */
1803         if (max > iaxs[fr->callno]->jitterbuffer - min_jitter_buffer)
1804                 iaxs[fr->callno]->jitterbuffer += jittershrinkrate;
1805
1806
1807 #if 1
1808         /* Constrain our maximum jitter buffer appropriately */
1809         if (max > min + maxjitterbuffer) {
1810                 if (option_debug)
1811                         ast_log(LOG_DEBUG, "Constraining buffer from %d to %d + %d\n", max, min , maxjitterbuffer);
1812                 max = min + maxjitterbuffer;
1813         }
1814 #endif
1815
1816         /* If our jitter buffer is smaller than our maximum delay, grow the jitter
1817            buffer immediately to accomodate it (and a little more).  */
1818         if (max > iaxs[fr->callno]->jitterbuffer)
1819                 iaxs[fr->callno]->jitterbuffer = max 
1820                         /* + ((float)iaxs[fr->callno]->jitter) * 0.1 */;
1821
1822         /* If the caller just wanted us to update, return now */
1823         if (!reallydeliver)
1824                 return 0;
1825
1826         if (option_debug)
1827                 /* Log jitter stats for possible offline analysis */
1828                 ast_log(LOG_DEBUG, "Jitter: call=%d ts=%d %s: min=%d max=%d jb=%d %+d; lateness=%d; jitter=%d historic=%d\n",
1829                                         fr->callno, fr->ts,
1830                                         (fr->af.frametype == AST_FRAME_VOICE) ? "VOICE" : "CONTROL",
1831                                         min, max, iaxs[fr->callno]->jitterbuffer,
1832                                         iaxs[fr->callno]->jitterbuffer - prevjitterbuffer,
1833                                         ms, iaxs[fr->callno]->jitter, iaxs[fr->callno]->historicjitter);
1834         
1835         /* Subtract the lateness from our jitter buffer to know how long to wait
1836            before sending our packet.  */
1837         ms = iaxs[fr->callno]->jitterbuffer - ms;
1838         
1839         if (!use_jitterbuffer)
1840                 ms = 0;
1841
1842         if (ms < 1) {
1843                 /* Don't deliver it more than 4 ms late */
1844                 if ((ms > -4) || (fr->af.frametype != AST_FRAME_VOICE)) {
1845                         if (option_debug)
1846                                 ast_log(LOG_DEBUG, "schedule_delivery: Delivering immediately (Calculated ms is %d)\n", ms);
1847                         __do_deliver(fr);
1848                 } else {
1849                         if (option_debug)
1850                                 ast_log(LOG_DEBUG, "schedule_delivery: Dropping voice packet since %d ms is too old\n", ms);
1851                         /* Free our iax frame */
1852                         iax2_frame_free(fr);
1853                 }
1854         } else {
1855                 if (option_debug)
1856                         ast_log(LOG_DEBUG, "schedule_delivery: Scheduling delivery in %d ms\n", ms);
1857                 fr->retrans = ast_sched_add(sched, ms, do_deliver, fr);
1858         }
1859         return 0;
1860 }
1861
1862 static int iax2_transmit(struct iax_frame *fr)
1863 {
1864         /* Lock the queue and place this packet at the end */
1865         fr->next = NULL;
1866         fr->prev = NULL;
1867         /* By setting this to 0, the network thread will send it for us, and
1868            queue retransmission if necessary */
1869         fr->sentyet = 0;
1870         ast_mutex_lock(&iaxq.lock);
1871         if (!iaxq.head) {
1872                 /* Empty queue */
1873                 iaxq.head = fr;
1874                 iaxq.tail = fr;
1875         } else {
1876                 /* Double link */
1877                 iaxq.tail->next = fr;
1878                 fr->prev = iaxq.tail;
1879                 iaxq.tail = fr;
1880         }
1881         iaxq.count++;
1882         ast_mutex_unlock(&iaxq.lock);
1883         /* Wake up the network thread */
1884         pthread_kill(netthreadid, SIGURG);
1885         return 0;
1886 }
1887
1888
1889
1890 static int iax2_digit(struct ast_channel *c, char digit)
1891 {
1892         return send_command_locked(PTR_TO_CALLNO(c->pvt->pvt), AST_FRAME_DTMF, digit, 0, NULL, 0, -1);
1893 }
1894
1895 static int iax2_sendtext(struct ast_channel *c, char *text)
1896 {
1897         
1898         return send_command_locked(PTR_TO_CALLNO(c->pvt->pvt), AST_FRAME_TEXT,
1899                 0, 0, text, strlen(text) + 1, -1);
1900 }
1901
1902 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
1903 {
1904         return send_command_locked(PTR_TO_CALLNO(c->pvt->pvt), AST_FRAME_IMAGE, img->subclass, 0, img->data, img->datalen, -1);
1905 }
1906
1907 static int iax2_sendhtml(struct ast_channel *c, int subclass, char *data, int datalen)
1908 {
1909         return send_command_locked(PTR_TO_CALLNO(c->pvt->pvt), AST_FRAME_HTML, subclass, 0, data, datalen, -1);
1910 }
1911
1912 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
1913 {
1914         unsigned short callno = PTR_TO_CALLNO(newchan->pvt->pvt);
1915         ast_mutex_lock(&iaxsl[callno]);
1916         if (iaxs[callno])
1917                 iaxs[callno]->owner = newchan;
1918         else
1919                 ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n");
1920         ast_mutex_unlock(&iaxsl[callno]);
1921         return 0;
1922 }
1923
1924 #ifdef MYSQL_FRIENDS
1925
1926 static void mysql_update_peer(char *peer, struct sockaddr_in *sin)
1927 {
1928         if (mysql && (strlen(peer) < 128)) {
1929                 char query[512];
1930                 char *name;
1931                 char iabuf[INET_ADDRSTRLEN];
1932                 time_t nowtime;
1933                 name = alloca(strlen(peer) * 2 + 1);
1934                 time(&nowtime);
1935                 mysql_real_escape_string(mysql, name, peer, strlen(peer));
1936                 snprintf(query, sizeof(query), "UPDATE iaxfriends SET ipaddr=\"%s\", port=\"%d\", regseconds=\"%ld\" WHERE name=\"%s\"", 
1937                         ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr), ntohs(sin->sin_port), nowtime, name);
1938                 ast_mutex_lock(&mysqllock);
1939                 if (mysql_real_query(mysql, query, strlen(query))) 
1940                         ast_log(LOG_WARNING, "Unable to update database\n");
1941                         
1942                 ast_mutex_unlock(&mysqllock);
1943         }
1944 }
1945
1946 static struct iax2_peer *mysql_peer(char *peer)
1947 {
1948         struct iax2_peer *p;
1949         int success = 0;
1950         
1951         p = malloc(sizeof(struct iax2_peer));
1952         memset(p, 0, sizeof(struct iax2_peer));
1953         if (mysql && (strlen(peer) < 128)) {
1954                 char query[512];
1955                 char *name;
1956                 int numfields, x;
1957                 int port;
1958                 time_t regseconds, nowtime;
1959                 MYSQL_RES *result;
1960                 MYSQL_FIELD *fields;
1961                 MYSQL_ROW rowval;
1962                 name = alloca(strlen(peer) * 2 + 1);
1963                 mysql_real_escape_string(mysql, name, peer, strlen(peer));
1964                 snprintf(query, sizeof(query), "SELECT name, secret, context, ipaddr, port, regseconds FROM iaxfriends WHERE name=\"%s\"", name);
1965                 ast_mutex_lock(&mysqllock);
1966                 mysql_query(mysql, query);
1967                 if ((result = mysql_store_result(mysql))) {
1968                         if ((rowval = mysql_fetch_row(result))) {
1969                                 numfields = mysql_num_fields(result);
1970                                 fields = mysql_fetch_fields(result);
1971                                 success = 1;
1972                                 for (x=0;x<numfields;x++) {
1973                                         if (rowval[x]) {
1974                                                 if (!strcasecmp(fields[x].name, "secret")) {
1975                                                         strncpy(p->secret, rowval[x], sizeof(p->secret) - 1);
1976                                                 } else if (!strcasecmp(fields[x].name, "context")) {
1977                                                         strncpy(p->context, rowval[x], sizeof(p->context) - 1);
1978                                                 } else if (!strcasecmp(fields[x].name, "ipaddr")) {
1979                                                         inet_aton(rowval[x], &p->addr.sin_addr);
1980                                                 } else if (!strcasecmp(fields[x].name, "port")) {
1981                                                         if (sscanf(rowval[x], "%i", &port) != 1)
1982                                                                 port = 0;
1983                                                         p->addr.sin_port = htons(port);
1984                                                 } else if (!strcasecmp(fields[x].name, "regseconds")) {
1985                                                         if (sscanf(rowval[x], "%li", &regseconds) != 1)
1986                                                                 regseconds = 0;
1987                                                 }
1988                                         }
1989                                 }
1990                                 time(&nowtime);
1991                                 if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE) 
1992                                         memset(&p->addr, 0, sizeof(p->addr));
1993                         }
1994                         mysql_free_result(result);
1995                         result = NULL;
1996                 }
1997                 ast_mutex_unlock(&mysqllock);
1998         }
1999         if (!success) {
2000                 free(p);
2001                 p = NULL;
2002         } else {
2003                 strncpy(p->name, peer, sizeof(p->name) - 1);
2004                 p->dynamic = 1;
2005                 p->temponly = 1;
2006                 p->expire = -1;
2007                 p->capability = iax2_capability;
2008                 p->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
2009         }
2010         return p;
2011 }
2012 static struct iax2_user *mysql_user(char *user)
2013 {
2014         struct iax2_user *p;
2015         struct iax2_context *con;
2016         int success = 0;
2017         
2018         p = malloc(sizeof(struct iax2_user));
2019         memset(p, 0, sizeof(struct iax2_user));
2020         con = malloc(sizeof(struct iax2_context));
2021         memset(con, 0, sizeof(struct iax2_context));
2022         strncpy(con->context, "default", sizeof(con->context) - 1);
2023         p->contexts = con;
2024         if (mysql && (strlen(user) < 128)) {
2025                 char query[512];
2026                 char *name;
2027                 int numfields, x;
2028                 MYSQL_RES *result;
2029                 MYSQL_FIELD *fields;
2030                 MYSQL_ROW rowval;
2031                 name = alloca(strlen(user) * 2 + 1);
2032                 mysql_real_escape_string(mysql, name, user, strlen(user));
2033                 snprintf(query, sizeof(query), "SELECT name, secret, context, ipaddr, port, regseconds, accountcode FROM iaxfriends WHERE name=\"%s\"", name);
2034                 ast_mutex_lock(&mysqllock);
2035                 mysql_query(mysql, query);
2036                 if ((result = mysql_store_result(mysql))) {
2037                         if ((rowval = mysql_fetch_row(result))) {
2038                                 numfields = mysql_num_fields(result);
2039                                 fields = mysql_fetch_fields(result);
2040                                 success = 1;
2041                                 for (x=0;x<numfields;x++) {
2042                                         if (rowval[x]) {
2043                                                 if (!strcasecmp(fields[x].name, "secret")) {
2044                                                         strncpy(p->secret, rowval[x], sizeof(p->secret) - 1);
2045                                                 } else if (!strcasecmp(fields[x].name, "context")) {
2046                                                         strncpy(p->contexts->context, rowval[x], sizeof(p->contexts->context) - 1);
2047                                                 } else if (!strcasecmp(fields[x].name, "accountcode")) {
2048                                                         strncpy(p->accountcode, rowval[x], sizeof(p->accountcode) - 1);
2049                                                 }
2050                                         }
2051                                 }
2052                         }
2053                         mysql_free_result(result);
2054                         result = NULL;
2055                 }
2056                 ast_mutex_unlock(&mysqllock);
2057         }
2058         if (!success) {
2059                 if (p->contexts)
2060                         free(p->contexts);
2061                 free(p);
2062                 p = NULL;
2063         } else {
2064                 strncpy(p->name, user, sizeof(p->name) - 1);
2065                 p->temponly = 1;
2066                 p->capability = iax2_capability;
2067                 p->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
2068         }
2069         return p;
2070 }
2071 #endif /* MYSQL_FRIENDS */
2072
2073 static int create_addr(struct sockaddr_in *sin, int *capability, int *sendani, int *maxtime, char *peer, char *context, int *trunk, int *notransfer, char *username, int usernlen, char *secret, int seclen, int *ofound, char *peercontext)
2074 {
2075         struct ast_hostent ahp; struct hostent *hp;
2076         struct iax2_peer *p;
2077         int found=0;
2078         if (sendani)
2079                 *sendani = 0;
2080         if (maxtime)
2081                 *maxtime = 0;
2082         if (trunk)
2083                 *trunk = 0;
2084         sin->sin_family = AF_INET;
2085         ast_mutex_lock(&peerl.lock);
2086         p = peerl.peers;
2087         while(p) {
2088                 if (!strcasecmp(p->name, peer)) {
2089                         break;
2090                 }
2091                 p = p->next;
2092         }
2093         ast_mutex_unlock(&peerl.lock);
2094 #ifdef MYSQL_FRIENDS
2095         if (!p)
2096                 p = mysql_peer(peer);
2097 #endif          
2098         if (p) {
2099                 found++;
2100                 if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
2101                         (!p->maxms || ((p->lastms > 0)  && (p->lastms <= p->maxms)))) {
2102                         if (sendani)
2103                                 *sendani = p->sendani;          /* Whether we transmit ANI */
2104                         if (maxtime)
2105                                 *maxtime = p->maxms;            /* Max time they should take */
2106                         if (context)
2107                                 strncpy(context, p->context, AST_MAX_EXTENSION - 1);
2108                         if (peercontext)
2109                                 strncpy(peercontext, p->peercontext, AST_MAX_EXTENSION - 1);
2110                         if (trunk)
2111                                 *trunk = p->trunk;
2112                         if (capability)
2113                                 *capability = p->capability;
2114                         if (username)
2115                                 strncpy(username, p->username, usernlen);
2116                         if (secret)
2117                                 strncpy(secret, p->secret, seclen); /* safe */
2118                         if (p->addr.sin_addr.s_addr) {
2119                                 sin->sin_addr = p->addr.sin_addr;
2120                                 sin->sin_port = p->addr.sin_port;
2121                         } else {
2122                                 sin->sin_addr = p->defaddr.sin_addr;
2123                                 sin->sin_port = p->defaddr.sin_port;
2124                         }
2125                         if (notransfer)
2126                                 *notransfer=p->notransfer;
2127                 } else {
2128                         if (p->temponly)
2129                                 free(p);
2130                         p = NULL;
2131                 }
2132         }
2133         if (ofound)
2134                 *ofound = found;
2135         if (!p && !found) {
2136                 hp = ast_gethostbyname(peer, &ahp);
2137                 if (hp) {
2138                         memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
2139                         sin->sin_port = htons(IAX_DEFAULT_PORTNO);
2140                         return 0;
2141                 } else {
2142                         ast_log(LOG_WARNING, "No such host: %s\n", peer);
2143                         return -1;
2144                 }
2145         } else if (!p)
2146                 return -1;
2147         if (p->temponly)
2148                 free(p);
2149         return 0;
2150 }
2151
2152 static int auto_congest(void *nothing)
2153 {
2154         int callno = PTR_TO_CALLNO(nothing);
2155         struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_CONGESTION };
2156         ast_mutex_lock(&iaxsl[callno]);
2157         if (iaxs[callno]) {
2158                 iaxs[callno]->initid = -1;
2159                 iax2_queue_frame(callno, &f);
2160                 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
2161         }
2162         ast_mutex_unlock(&iaxsl[callno]);
2163         return 0;
2164 }
2165
2166 static unsigned int iax2_datetime(void)
2167 {
2168         time_t t;
2169         struct tm tm;
2170         unsigned int tmp;
2171         time(&t);
2172         localtime_r(&t, &tm);
2173         tmp  = (tm.tm_sec >> 1) & 0x1f;   /* 5 bits of seconds */
2174         tmp |= (tm.tm_min & 0x3f) << 5;   /* 6 bits of minutes */
2175         tmp |= (tm.tm_hour & 0x1f) << 11;   /* 5 bits of hours */
2176         tmp |= (tm.tm_mday & 0x1f) << 16; /* 5 bits of day of month */
2177         tmp |= ((tm.tm_mon + 1) & 0xf) << 21; /* 4 bits of month */
2178         tmp |= ((tm.tm_year - 100) & 0x7f) << 25; /* 7 bits of year */
2179         return tmp;
2180 }
2181
2182 static int iax2_call(struct ast_channel *c, char *dest, int timeout)
2183 {
2184         struct sockaddr_in sin;
2185         char host[256];
2186         char *rdest;
2187         char *rcontext;
2188         char *username;
2189         char *secret = NULL;
2190         char *hname;
2191         char cid[256] = "";
2192         char *l=NULL, *n=NULL;
2193         struct iax_ie_data ied;
2194         char myrdest [5] = "s";
2195         char context[AST_MAX_EXTENSION] ="";
2196         char peercontext[AST_MAX_EXTENSION] ="";
2197         char *portno = NULL;
2198         char *opts = "";
2199         unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
2200         char *stringp=NULL;
2201         char storedusern[80], storedsecret[80];
2202         if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
2203                 ast_log(LOG_WARNING, "Line is already in use (%s)?\n", c->name);
2204                 return -1;
2205         }
2206         strncpy(host, dest, sizeof(host)-1);
2207         stringp=host;
2208         strsep(&stringp, "/");
2209         /* If no destination extension specified, use 's' */
2210         rdest = strsep(&stringp, "/");
2211         if (!rdest) 
2212                 rdest = myrdest;
2213         else {
2214                 /* Check for trailing options */
2215                 opts = strsep(&stringp, "/");
2216                 if (!opts)
2217                         opts = "";
2218         }
2219         stringp=rdest;
2220         strsep(&stringp, "@");
2221         rcontext = strsep(&stringp, "@");
2222         stringp=host;
2223         strsep(&stringp, "@");
2224         username = strsep(&stringp, "@");
2225         if (username) {
2226                 /* Really the second argument is the host, not the username */
2227                 hname = username;
2228                 username = host;
2229         } else {
2230                 hname = host;
2231         }
2232         if (username) {
2233                 stringp=username;
2234                 username = strsep(&stringp, ":");
2235                 secret = strsep(&stringp, ":");
2236         }
2237         stringp=hname;
2238         if (strsep(&stringp, ":")) {
2239                 stringp=hname;
2240                 strsep(&stringp, ":");
2241                 portno = strsep(&stringp, ":");
2242         }
2243         if (create_addr(&sin, NULL, NULL, NULL, hname, context, NULL, NULL, storedusern, sizeof(storedusern) - 1, storedsecret, sizeof(storedsecret) - 1, NULL, peercontext)) {
2244                 ast_log(LOG_WARNING, "No address associated with '%s'\n", hname);
2245                 return -1;
2246         }
2247         /* Keep track of the context for outgoing calls too */
2248         strncpy(c->context, context, sizeof(c->context) - 1);
2249         if (portno) {
2250                 sin.sin_port = htons(atoi(portno));
2251         }
2252         if (c->callerid) {
2253                 strncpy(cid, c->callerid, sizeof(cid) - 1);
2254                 ast_callerid_parse(cid, &n, &l);
2255                 if (l)
2256                         ast_shrink_phone_number(l);
2257         }
2258         /* Now build request */ 
2259         memset(&ied, 0, sizeof(ied));
2260         /* On new call, first IE MUST be IAX version of caller */
2261         iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
2262         iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, rdest);
2263         if (strchr(opts, 'a')) {
2264                 /* Request auto answer */
2265                 iax_ie_append(&ied, IAX_IE_AUTOANSWER);
2266         }
2267         if (l)
2268                 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
2269         if (n)
2270                 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n);
2271         if (iaxs[callno]->sendani && c->ani) {
2272                 l = n = NULL;
2273                 strncpy(cid, c->ani, sizeof(cid) - 1);
2274                 ast_callerid_parse(cid, &n, &l);
2275                 if (l) {
2276                         ast_shrink_phone_number(l);
2277                         iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, l);
2278                 }
2279         }
2280         if (c->language && !ast_strlen_zero(c->language))
2281                 iax_ie_append_str(&ied, IAX_IE_LANGUAGE, c->language);
2282         if (c->dnid && !ast_strlen_zero(c->dnid))
2283                 iax_ie_append_str(&ied, IAX_IE_DNID, c->dnid);
2284         if (rcontext)
2285                 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, rcontext);
2286         else if (strlen(peercontext))
2287                 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, peercontext);
2288         if (!username && !ast_strlen_zero(storedusern))
2289                 username = storedusern;
2290         if (username)
2291                 iax_ie_append_str(&ied, IAX_IE_USERNAME, username);
2292         if (!secret && !ast_strlen_zero(storedsecret))
2293                 secret = storedsecret;
2294         ast_mutex_lock(&iaxsl[callno]);
2295         if (!ast_strlen_zero(c->context))
2296                 strncpy(iaxs[callno]->context, c->context, sizeof(iaxs[callno]->context) - 1);
2297         if (secret) {
2298                 if (secret[0] == '[') {
2299                         /* This is an RSA key, not a normal secret */
2300                         strncpy(iaxs[callno]->outkey, secret + 1, sizeof(iaxs[callno]->secret)-1);
2301                         if (!ast_strlen_zero(iaxs[callno]->outkey)) {
2302                                 iaxs[callno]->outkey[strlen(iaxs[callno]->outkey) - 1] = '\0';
2303                         }
2304                 } else
2305                         strncpy(iaxs[callno]->secret, secret, sizeof(iaxs[callno]->secret)-1);
2306         }
2307         iax_ie_append_int(&ied, IAX_IE_FORMAT, c->nativeformats);
2308         iax_ie_append_int(&ied, IAX_IE_CAPABILITY, iaxs[callno]->capability);
2309         iax_ie_append_short(&ied, IAX_IE_ADSICPE, c->adsicpe);
2310         iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime());
2311         /* Transmit the string in a "NEW" request */
2312 #if 0
2313         /* XXX We have no equivalent XXX */
2314         if (option_verbose > 2)
2315                 ast_verbose(VERBOSE_PREFIX_3 "Calling using options '%s'\n", requeststr);
2316 #endif          
2317         if (iaxs[callno]->maxtime) {
2318                 /* Initialize pingtime and auto-congest time */
2319                 iaxs[callno]->pingtime = iaxs[callno]->maxtime / 2;
2320                 iaxs[callno]->initid = ast_sched_add(sched, iaxs[callno]->maxtime * 2, auto_congest, CALLNO_TO_PTR(callno));
2321         }
2322         send_command(iaxs[callno], AST_FRAME_IAX,
2323                 IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
2324         ast_mutex_unlock(&iaxsl[callno]);
2325         ast_setstate(c, AST_STATE_RINGING);
2326         return 0;
2327 }
2328
2329 static int iax2_hangup(struct ast_channel *c) 
2330 {
2331         unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
2332         int alreadygone;
2333         ast_mutex_lock(&iaxsl[callno]);
2334         if (callno && iaxs[callno]) {
2335                 ast_log(LOG_DEBUG, "We're hanging up %s now...\n", c->name);
2336                 alreadygone = iaxs[callno]->alreadygone;
2337                 /* Send the hangup unless we have had a transmission error or are already gone */
2338                 if (!iaxs[callno]->error && !alreadygone) 
2339                         send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, NULL, 0, -1);
2340                 /* Explicitly predestroy it */
2341                 iax2_predestroy_nolock(callno);
2342                 /* If we were already gone to begin with, destroy us now */
2343                 if (alreadygone) {
2344                         ast_log(LOG_DEBUG, "Really destroying %s now...\n", c->name);
2345                         iax2_destroy_nolock(callno);
2346                 }
2347         }
2348         ast_mutex_unlock(&iaxsl[callno]);
2349         if (option_verbose > 2) 
2350                 ast_verbose(VERBOSE_PREFIX_3 "Hungup '%s'\n", c->name);
2351         return 0;
2352 }
2353
2354 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
2355 {
2356         struct ast_option_header *h;
2357         int res;
2358         h = malloc(datalen + sizeof(struct ast_option_header));
2359         if (h) {
2360                 h->flag = AST_OPTION_FLAG_REQUEST;
2361                 h->option = htons(option);
2362                 memcpy(h->data, data, datalen);
2363                 res = send_command_locked(PTR_TO_CALLNO(c->pvt->pvt), AST_FRAME_CONTROL,
2364                         AST_CONTROL_OPTION, 0, (char *)h, datalen + sizeof(struct ast_option_header), -1);
2365                 free(h);
2366                 return res;
2367         } else 
2368                 ast_log(LOG_WARNING, "Out of memory\n");
2369         return -1;
2370 }
2371
2372 static struct ast_frame *iax2_read(struct ast_channel *c) 
2373 {
2374         static struct ast_frame f = { AST_FRAME_NULL, };
2375         ast_log(LOG_NOTICE, "I should never be called!\n");
2376         return &f;
2377 }
2378
2379 static int iax2_start_transfer(unsigned short callno0, unsigned short callno1)
2380 {
2381         int res;
2382         struct iax_ie_data ied0;
2383         struct iax_ie_data ied1;
2384         unsigned int transferid = rand();
2385         memset(&ied0, 0, sizeof(ied0));
2386         iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &iaxs[callno1]->addr);
2387         iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[callno1]->peercallno);
2388         iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, transferid);
2389
2390         memset(&ied1, 0, sizeof(ied1));
2391         iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &iaxs[callno0]->addr);
2392         iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[callno0]->peercallno);
2393         iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, transferid);
2394         
2395         res = send_command(iaxs[callno0], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
2396         if (res)
2397                 return -1;
2398         res = send_command(iaxs[callno1], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
2399         if (res)
2400                 return -1;
2401         iaxs[callno0]->transferring = TRANSFER_BEGIN;
2402         iaxs[callno1]->transferring = TRANSFER_BEGIN;
2403         return 0;
2404 }
2405
2406 static void lock_both(unsigned short callno0, unsigned short callno1)
2407 {
2408         ast_mutex_lock(&iaxsl[callno0]);
2409         while (ast_mutex_trylock(&iaxsl[callno1])) {
2410                 ast_mutex_unlock(&iaxsl[callno0]);
2411                 usleep(10);
2412                 ast_mutex_lock(&iaxsl[callno0]);
2413         }
2414 }
2415
2416 static void unlock_both(unsigned short callno0, unsigned short callno1)
2417 {
2418         ast_mutex_unlock(&iaxsl[callno1]);
2419         ast_mutex_unlock(&iaxsl[callno0]);
2420 }
2421
2422 static int iax2_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
2423 {
2424         struct ast_channel *cs[3];
2425         struct ast_channel *who;
2426         int to = -1;
2427         int res = -1;
2428         int transferstarted=0;
2429         struct ast_frame *f;
2430         unsigned short callno0 = PTR_TO_CALLNO(c0->pvt->pvt);
2431         unsigned short callno1 = PTR_TO_CALLNO(c1->pvt->pvt);
2432         struct timeval waittimer = {0, 0}, tv;
2433         
2434         lock_both(callno0, callno1);
2435         /* Put them in native bridge mode */
2436         iaxs[callno0]->bridgecallno = callno1;
2437         iaxs[callno1]->bridgecallno = callno0;
2438         unlock_both(callno0, callno1);
2439
2440         /* If not, try to bridge until we can execute a transfer, if we can */
2441         cs[0] = c0;
2442         cs[1] = c1;
2443         for (/* ever */;;) {
2444                 /* Check in case we got masqueraded into */
2445                 if ((c0->type != type) || (c1->type != type)) {
2446                         if (option_verbose > 2)
2447                                 ast_verbose(VERBOSE_PREFIX_3 "Can't masquerade, we're different...\n");
2448                         /* Remove from native mode */
2449                         if (c0->type == type) {
2450                                 ast_mutex_lock(&iaxsl[callno0]);
2451                                 iaxs[callno0]->bridgecallno = 0;
2452                                 ast_mutex_unlock(&iaxsl[callno0]);
2453                         }
2454                         if (c1->type == type) {
2455                                 ast_mutex_lock(&iaxsl[callno1]);
2456                                 iaxs[callno1]->bridgecallno = 0;
2457                                 ast_mutex_unlock(&iaxsl[callno1]);
2458                         }
2459                         return -2;
2460                 }
2461                 if (c0->nativeformats != c1->nativeformats) {
2462                         ast_verbose(VERBOSE_PREFIX_3 "Operating with different codecs, can't native bridge...\n");
2463                         /* Remove from native mode */
2464                         lock_both(callno0, callno1);
2465                         iaxs[callno0]->bridgecallno = 0;
2466                         iaxs[callno1]->bridgecallno = 0;
2467                         unlock_both(callno0, callno1);
2468                         return -2;
2469                 }
2470                 /* check if transfered and if we really want native bridging */
2471                 if (!transferstarted && !iaxs[callno0]->notransfer && !iaxs[callno1]->notransfer) {
2472                         /* Try the transfer */
2473                         if (iax2_start_transfer(callno0, callno1))
2474                                 ast_log(LOG_WARNING, "Unable to start the transfer\n");
2475                         transferstarted = 1;
2476                 }
2477                 if ((iaxs[callno0]->transferring == TRANSFER_RELEASED) && (iaxs[callno1]->transferring == TRANSFER_RELEASED)) {
2478                         /* Call has been transferred.  We're no longer involved */
2479                         gettimeofday(&tv, NULL);
2480                         if (!waittimer.tv_sec && !waittimer.tv_usec) {
2481                                 waittimer.tv_sec = tv.tv_sec;
2482                                 waittimer.tv_usec = tv.tv_usec;
2483                         } else if (tv.tv_sec - waittimer.tv_sec > IAX_LINGER_TIMEOUT) {
2484                                 c0->_softhangup |= AST_SOFTHANGUP_DEV;
2485                                 c1->_softhangup |= AST_SOFTHANGUP_DEV;
2486                                 *fo = NULL;
2487                                 *rc = c0;
2488                                 res = 0;
2489                                 break;
2490                         }
2491                 }
2492                 to = 1000;
2493                 who = ast_waitfor_n(cs, 2, &to);
2494                 if (!who) {
2495                         if (ast_check_hangup(c0) || ast_check_hangup(c1)) {
2496                                 res = -1;
2497                                 break;
2498                         }
2499                         continue;
2500                 }
2501                 f = ast_read(who);
2502                 if (!f) {
2503                         *fo = NULL;
2504                         *rc = who;
2505                         res = 0;
2506                         break;
2507                 }
2508                 if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
2509                         *fo = f;
2510                         *rc = who;
2511                         res =  0;
2512                         break;
2513                 }
2514                 if ((f->frametype == AST_FRAME_VOICE) ||
2515                         (f->frametype == AST_FRAME_TEXT) ||
2516                         (f->frametype == AST_FRAME_VIDEO) || 
2517                         (f->frametype == AST_FRAME_IMAGE) ||
2518                         (f->frametype == AST_FRAME_DTMF)) {
2519                         if ((f->frametype == AST_FRAME_DTMF) && 
2520                                 (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
2521                                 if ((who == c0)) {
2522                                         if  ((flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
2523                                                 *rc = c0;
2524                                                 *fo = f;
2525                                                 /* Take out of conference mode */
2526                                                 res = 0;
2527                                                 /* Remove from native mode */
2528                                                 break;
2529                                         } else 
2530                                                 goto tackygoto;
2531                                 } else
2532                                 if ((who == c1)) {
2533                                         if (flags & AST_BRIDGE_DTMF_CHANNEL_1) {
2534                                                 *rc = c1;
2535                                                 *fo = f;
2536                                                 res =  0;
2537                                                 /* Remove from native mode */
2538                                                 break;
2539                                         } else
2540                                                 goto tackygoto;
2541                                 }
2542                         } else {
2543 #if 0
2544                                 ast_log(LOG_DEBUG, "Read from %s\n", who->name);
2545                                 if (who == last) 
2546                                         ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
2547                                 last = who;
2548 #endif
2549 tackygoto:
2550                                 if (who == c0) 
2551                                         ast_write(c1, f);
2552                                 else 
2553                                         ast_write(c0, f);
2554                         }
2555                         ast_frfree(f);
2556                 } else
2557                         ast_frfree(f);
2558                 /* Swap who gets priority */
2559                 cs[2] = cs[0];
2560                 cs[0] = cs[1];
2561                 cs[1] = cs[2];
2562         }
2563         lock_both(callno0, callno1);
2564         iaxs[callno0]->bridgecallno = 0;
2565         iaxs[callno1]->bridgecallno = 0;
2566         unlock_both(callno0, callno1);
2567         return res;
2568 }
2569
2570 static int iax2_answer(struct ast_channel *c)
2571 {
2572         unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
2573         if (option_debug)
2574                 ast_log(LOG_DEBUG, "Answering\n");
2575         return send_command_locked(callno, AST_FRAME_CONTROL, AST_CONTROL_ANSWER, 0, NULL, 0, -1);
2576 }
2577
2578 static int iax2_indicate(struct ast_channel *c, int condition)
2579 {
2580         unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
2581         if (option_debug)
2582                 ast_log(LOG_DEBUG, "Indicating condition %d\n", condition);
2583         return send_command_locked(callno, AST_FRAME_CONTROL, condition, 0, NULL, 0, -1);
2584 }
2585         
2586 static int iax2_transfer(struct ast_channel *c, char *dest)
2587 {
2588         unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
2589         struct iax_ie_data ied;
2590         char tmp[256] = "", *context;
2591         strncpy(tmp, dest, sizeof(tmp) - 1);
2592         context = strchr(tmp, '@');
2593         if (context) {
2594                 *context = '\0';
2595                 context++;
2596         }
2597         memset(&ied, 0, sizeof(ied));
2598         iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, tmp);
2599         if (context)
2600                 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, context);
2601         if (option_debug)
2602                 ast_log(LOG_DEBUG, "Transferring '%s' to '%s'\n", c->name, dest);
2603         return send_command_locked(callno, AST_FRAME_IAX, IAX_COMMAND_TRANSFER, 0, ied.buf, ied.pos, -1);
2604 }
2605         
2606
2607 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
2608
2609 static int iax2_getpeertrunk(struct sockaddr_in sin)
2610 {
2611         struct iax2_peer *peer;
2612         int res = 0;
2613         ast_mutex_lock(&peerl.lock);
2614         peer = peerl.peers;
2615         while(peer) {
2616                 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
2617                                 (peer->addr.sin_port == sin.sin_port)) {
2618                                         res = peer->trunk;
2619                                         break;
2620                 }
2621                 peer = peer->next;
2622         }
2623         ast_mutex_unlock(&peerl.lock);
2624         return res;
2625 }
2626
2627 static struct ast_channel *ast_iax2_new(int callno, int state, int capability)
2628 {
2629         struct ast_channel *tmp;
2630         struct chan_iax2_pvt *i;
2631         /* Don't hold call lock */
2632         ast_mutex_unlock(&iaxsl[callno]);
2633         tmp = ast_channel_alloc(1);
2634         ast_mutex_lock(&iaxsl[callno]);
2635         i = iaxs[callno];
2636         if (i && tmp) {
2637                 if (!ast_strlen_zero(i->username))
2638                         snprintf(tmp->name, sizeof(tmp->name), "IAX2/%s@%s/%d", i->username, i->host, i->callno);
2639                 else
2640                         snprintf(tmp->name, sizeof(tmp->name), "IAX2/%s/%d", i->host, i->callno);
2641                 tmp->type = type;
2642                 /* We can support any format by default, until we get restricted */
2643                 tmp->nativeformats = capability;
2644                 tmp->readformat = 0;
2645                 tmp->writeformat = 0;
2646                 tmp->pvt->pvt = CALLNO_TO_PTR(i->callno);
2647                 tmp->pvt->send_digit = iax2_digit;
2648                 tmp->pvt->send_text = iax2_sendtext;
2649                 tmp->pvt->send_image = iax2_sendimage;
2650                 tmp->pvt->send_html = iax2_sendhtml;
2651                 tmp->pvt->call = iax2_call;
2652                 tmp->pvt->hangup = iax2_hangup;
2653                 tmp->pvt->answer = iax2_answer;
2654                 tmp->pvt->read = iax2_read;
2655                 tmp->pvt->write = iax2_write;
2656                 tmp->pvt->write_video = iax2_write;
2657                 tmp->pvt->indicate = iax2_indicate;
2658                 tmp->pvt->setoption = iax2_setoption;
2659                 tmp->pvt->bridge = iax2_bridge;
2660                 tmp->pvt->transfer = iax2_transfer;
2661                 if (!ast_strlen_zero(i->callerid))
2662                         tmp->callerid = strdup(i->callerid);
2663                 if (!ast_strlen_zero(i->ani))
2664                         tmp->ani = strdup(i->ani);
2665                 if (!ast_strlen_zero(i->language))
2666                         strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
2667                 if (!ast_strlen_zero(i->dnid))
2668                         tmp->dnid = strdup(i->dnid);
2669                 if (!ast_strlen_zero(i->accountcode))
2670                         strncpy(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode)-1);
2671                 if (i->amaflags)
2672                         tmp->amaflags = i->amaflags;
2673                 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
2674                 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
2675                 tmp->adsicpe = i->peeradsicpe;
2676                 tmp->pvt->fixup = iax2_fixup;
2677                 i->owner = tmp;
2678                 i->capability = capability;
2679                 ast_setstate(tmp, state);
2680                 ast_mutex_lock(&usecnt_lock);
2681                 usecnt++;
2682                 ast_mutex_unlock(&usecnt_lock);
2683                 ast_update_use_count();
2684                 if (state != AST_STATE_DOWN) {
2685                         if (ast_pbx_start(tmp)) {
2686                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
2687                                 ast_hangup(tmp);
2688                                 tmp = NULL;
2689                         }
2690                 }
2691         }
2692         return tmp;
2693 }
2694
2695 static unsigned int calc_txpeerstamp(struct iax2_trunk_peer *tpeer, int sampms, struct timeval *tv)
2696 {
2697         unsigned long int mssincetx; /* unsigned to handle overflows */
2698         long int ms, pred;
2699
2700         tpeer->trunkact = *tv;
2701         mssincetx = (tv->tv_sec - tpeer->lasttxtime.tv_sec) * 1000 +
2702                         (1000000 + tv->tv_usec - tpeer->lasttxtime.tv_usec) / 1000 - 1000;
2703         if (mssincetx > 5000 || (!tpeer->txtrunktime.tv_sec && !tpeer->txtrunktime.tv_usec)) {
2704                 /* If it's been at least 5 seconds since the last time we transmitted on this trunk, reset our timers */
2705                 tpeer->txtrunktime.tv_sec = tv->tv_sec;
2706                 tpeer->txtrunktime.tv_usec = tv->tv_usec;
2707                 tpeer->lastsent = 999999;
2708         }
2709         /* Update last transmit time now */
2710         tpeer->lasttxtime.tv_sec = tv->tv_sec;
2711         tpeer->lasttxtime.tv_usec = tv->tv_usec;
2712         
2713         /* Calculate ms offset */
2714         ms = (tv->tv_sec - tpeer->txtrunktime.tv_sec) * 1000 +
2715                 (1000000 + tv->tv_usec - tpeer->txtrunktime.tv_usec) / 1000 - 1000;
2716         /* Predict from last value */
2717         pred = tpeer->lastsent + sampms;
2718         if (abs(ms - pred) < MAX_TIMESTAMP_SKEW)
2719                 ms = pred;
2720         
2721         /* We never send the same timestamp twice, so fudge a little if we must */
2722         if (ms == tpeer->lastsent)
2723                 ms = tpeer->lastsent + 1;
2724         tpeer->lastsent = ms;
2725         return ms;
2726 }
2727
2728 static unsigned int fix_peerts(struct timeval *tv, int callno, unsigned int ts)
2729 {
2730         long ms;        /* NOT unsigned */
2731         if (!iaxs[callno]->rxcore.tv_sec && !iaxs[callno]->rxcore.tv_usec) {
2732                 /* Initialize rxcore time if appropriate */
2733                 gettimeofday(&iaxs[callno]->rxcore, NULL);
2734                 /* Round to nearest 20ms so traces look pretty */
2735                 iaxs[callno]->rxcore.tv_usec -= iaxs[callno]->rxcore.tv_usec % 20000;
2736         }
2737         /* Calculate difference between trunk and channel */
2738         ms = (tv->tv_sec - iaxs[callno]->rxcore.tv_sec) * 1000 + 
2739                 (1000000 + tv->tv_usec - iaxs[callno]->rxcore.tv_usec) / 1000 - 1000;
2740         /* Return as the sum of trunk time and the difference between trunk and real time */
2741         return ms + ts;
2742 }
2743
2744 static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts, struct ast_frame *f)
2745 {
2746         struct timeval tv;
2747         int ms;
2748         int voice = 0;
2749         int genuine = 0;
2750         struct timeval *delivery = NULL;
2751
2752         /* What sort of frame do we have?: voice is self-explanatory
2753            "genuine" means an IAX frame - things like LAGRQ/RP, PING/PONG, ACK
2754            non-genuine frames are CONTROL frames [ringing etc], DTMF
2755            The "genuine" distinction is needed because genuine frames must get a clock-based timestamp,
2756            the others need a timestamp slaved to the voice frames so that they go in sequence
2757         */
2758         if (f) {
2759                 if (f->frametype == AST_FRAME_VOICE) {
2760                         voice = 1;
2761                         delivery = &f->delivery;
2762                 } else if (f->frametype == AST_FRAME_IAX) {
2763                         genuine = 1;
2764                 }
2765         }
2766         if (!p->offset.tv_sec && !p->offset.tv_usec) {
2767                 gettimeofday(&p->offset, NULL);
2768                 /* Round to nearest 20ms for nice looking traces */
2769                 p->offset.tv_usec -= p->offset.tv_usec % 20000;
2770         }
2771         /* If the timestamp is specified, just send it as is */
2772         if (ts)
2773                 return ts;
2774         /* If we have a time that the frame arrived, always use it to make our timestamp */
2775         if (delivery && (delivery->tv_sec || delivery->tv_usec)) {
2776                 ms = (delivery->tv_sec - p->offset.tv_sec) * 1000 +
2777                         (1000000 + delivery->tv_usec - p->offset.tv_usec) / 1000 - 1000;
2778         } else {
2779                 gettimeofday(&tv, NULL);
2780                 ms = (tv.tv_sec - p->offset.tv_sec) * 1000 +
2781                         (1000000 + tv.tv_usec - p->offset.tv_usec) / 1000 - 1000;
2782                 if (ms < 0)
2783                         ms = 0;
2784                 if (voice) {
2785                         /* On a voice frame, use predicted values if appropriate */
2786                         if (abs(ms - p->nextpred) <= MAX_TIMESTAMP_SKEW) {
2787                                 if (!p->nextpred) {
2788                                         p->nextpred = ms; /*f->samples / 8;*/
2789                                         if (p->nextpred <= p->lastsent)
2790                                                 p->nextpred = p->lastsent + 3;
2791                                 }
2792                                 ms = p->nextpred;
2793                         } else
2794                                 p->nextpred = ms;
2795                 } else {
2796                         /* On a dataframe, use last value + 3 (to accomodate jitter buffer shrinking) if appropriate unless
2797                            it's a genuine frame */
2798                         if (genuine) {
2799                                 /* genuine (IAX LAGRQ etc) must keep their clock-based stamps */
2800                                 if (ms <= p->lastsent)
2801                                         ms = p->lastsent + 3;
2802                         } else if (abs(ms - p->lastsent) <= MAX_TIMESTAMP_SKEW) {
2803                                 /* non-genuine frames (!?) (DTMF, CONTROL) should be pulled into the predicted stream stamps */
2804                                 ms = p->lastsent + 3;
2805                         }
2806                 }
2807         }
2808         p->lastsent = ms;
2809         if (voice)
2810                 p->nextpred = p->nextpred + f->samples / 8;
2811 #if 0
2812         printf("TS: %s - %dms\n", voice ? "Audio" : "Control", ms);
2813 #endif  
2814         return ms;
2815 }
2816
2817 #ifdef BRIDGE_OPTIMIZATION
2818 static unsigned int calc_fakestamp(struct chan_iax2_pvt *p1, struct chan_iax2_pvt *p2, unsigned int fakets)
2819 {
2820         int ms;
2821         /* Receive from p1, send to p2 */
2822         
2823         /* Setup rxcore if necessary on outgoing channel */
2824         if (!p1->rxcore.tv_sec && !p1->rxcore.tv_usec)
2825                 gettimeofday(&p1->rxcore, NULL);
2826
2827         /* Setup txcore if necessary on outgoing channel */
2828         if (!p2->offset.tv_sec && !p2->offset.tv_usec)
2829                 gettimeofday(&p2->offset, NULL);
2830         
2831         /* Now, ts is the timestamp of the original packet in the orignal context.
2832            Adding rxcore to it gives us when we would want the packet to be delivered normally.
2833            Subtracting txcore of the outgoing channel gives us what we'd expect */
2834         
2835         ms = (p1->rxcore.tv_sec - p2->offset.tv_sec) * 1000 +
2836                 (1000000 + p1->rxcore.tv_usec - p2->offset.tv_usec) / 1000 - 1000;
2837         fakets += ms;
2838
2839         /* FIXME? SLD would rather remove this and leave it to the end system to deal with */
2840         if (fakets <= p2->lastsent)
2841                 fakets = p2->lastsent + 1;
2842         p2->lastsent = fakets;
2843         return fakets;
2844 }
2845 #endif
2846
2847 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p)
2848 {
2849         /* Returns where in "receive time" we are */
2850         struct timeval tv;
2851         int ms;
2852         /* Setup rxcore if necessary */
2853         if (!p->rxcore.tv_sec && !p->rxcore.tv_usec)
2854                 gettimeofday(&p->rxcore, NULL);
2855
2856         gettimeofday(&tv, NULL);
2857         ms = (tv.tv_sec - p->rxcore.tv_sec) * 1000 +
2858                 (1000000 + tv.tv_usec - p->rxcore.tv_usec) / 1000 - 1000;
2859         return ms;
2860 }
2861
2862 static struct iax2_trunk_peer *find_tpeer(struct sockaddr_in *sin)
2863 {
2864         struct iax2_trunk_peer *tpeer;
2865         char iabuf[INET_ADDRSTRLEN];
2866         /* Finds and locks trunk peer */
2867         ast_mutex_lock(&tpeerlock);
2868         tpeer = tpeers;
2869         while(tpeer) {
2870                 /* We don't lock here because tpeer->addr *never* changes */
2871                 if (!inaddrcmp(&tpeer->addr, sin)) {
2872                         ast_mutex_lock(&tpeer->lock);
2873                         break;
2874                 }
2875                 tpeer = tpeer->next;
2876         }
2877         if (!tpeer) {
2878                 tpeer = malloc(sizeof(struct iax2_trunk_peer));
2879                 if (tpeer) {
2880                         memset(tpeer, 0, sizeof(struct iax2_trunk_peer));
2881                         ast_mutex_init(&tpeer->lock);
2882                         tpeer->lastsent = 9999;
2883                         memcpy(&tpeer->addr, sin, sizeof(tpeer->addr));
2884                         gettimeofday(&tpeer->trunkact, NULL);
2885                         ast_mutex_lock(&tpeer->lock);
2886                         tpeer->next = tpeers;
2887                         tpeers = tpeer;
2888                         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));
2889                 }
2890         }
2891         ast_mutex_unlock(&tpeerlock);
2892         return tpeer;
2893 }
2894
2895 static int iax2_trunk_queue(struct chan_iax2_pvt *pvt, struct ast_frame *f)
2896 {
2897         struct iax2_trunk_peer *tpeer;
2898         void *tmp, *ptr;
2899         struct ast_iax2_meta_trunk_entry *met;
2900         char iabuf[INET_ADDRSTRLEN];
2901         tpeer = find_tpeer(&pvt->addr);
2902         if (tpeer) {
2903                 if (tpeer->trunkdatalen + f->datalen + 4 >= tpeer->trunkdataalloc) {
2904                         /* Need to reallocate space */
2905                         if (tpeer->trunkdataalloc < MAX_TRUNKDATA) {
2906                                 tmp = realloc(tpeer->trunkdata, tpeer->trunkdataalloc + DEFAULT_TRUNKDATA + IAX2_TRUNK_PREFACE);
2907                                 if (tmp) {
2908                                         tpeer->trunkdataalloc += DEFAULT_TRUNKDATA;
2909                                         tpeer->trunkdata = tmp;
2910                                         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);
2911                                 } else {
2912                                         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));
2913                                         ast_mutex_unlock(&tpeer->lock);
2914                                         return -1;
2915                                 }
2916                         } else {
2917                                 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));
2918                                 ast_mutex_unlock(&tpeer->lock);
2919                                 return -1;
2920                         }
2921                 }
2922                 
2923                 /* Append to meta frame */
2924                 ptr = tpeer->trunkdata + IAX2_TRUNK_PREFACE + tpeer->trunkdatalen;
2925                 met = (struct ast_iax2_meta_trunk_entry *)ptr;
2926                 /* Store call number and length in meta header */
2927                 met->callno = htons(pvt->callno);
2928                 met->len = htons(f->datalen);
2929                 /* Advance pointers/decrease length past trunk entry header */
2930                 ptr += sizeof(struct ast_iax2_meta_trunk_entry);
2931                 tpeer->trunkdatalen += sizeof(struct ast_iax2_meta_trunk_entry);
2932                 /* Copy actual trunk data */
2933                 memcpy(ptr, f->data, f->datalen);
2934                 tpeer->trunkdatalen += f->datalen;
2935                 tpeer->calls++;
2936                 ast_mutex_unlock(&tpeer->lock);
2937         }
2938         return 0;
2939 }
2940
2941 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final)
2942 {
2943         /* Queue a packet for delivery on a given private structure.  Use "ts" for
2944            timestamp, or calculate if ts is 0.  Send immediately without retransmission
2945            or delayed, with retransmission */
2946         struct ast_iax2_full_hdr *fh;
2947         struct ast_iax2_mini_hdr *mh;
2948         struct ast_iax2_video_hdr *vh;
2949         struct {
2950                 struct iax_frame fr2;
2951                 unsigned char buffer[4096];
2952         } frb;
2953         struct iax_frame *fr;
2954         int res;
2955         int sendmini=0;
2956         unsigned int lastsent;
2957         unsigned int fts;
2958                 
2959         if (!pvt) {
2960                 ast_log(LOG_WARNING, "No private structure for packet?\n");
2961                 return -1;
2962         }
2963         
2964         lastsent = pvt->lastsent;
2965
2966         /* Calculate actual timestamp */
2967         fts = calc_timestamp(pvt, ts, f);
2968
2969         if ((pvt->trunk || ((fts & 0xFFFF0000L) == (lastsent & 0xFFFF0000L)))
2970                 /* High two bytes are the same on timestamp, or sending on a trunk */ &&
2971             (f->frametype == AST_FRAME_VOICE) 
2972                 /* is a voice frame */ &&
2973                 (f->subclass == pvt->svoiceformat) 
2974                 /* is the same type */ ) {
2975                         /* Force immediate rather than delayed transmission */
2976                         now = 1;
2977                         /* Mark that mini-style frame is appropriate */
2978                         sendmini = 1;
2979         }
2980         if (((fts & 0xFFFF8000L) == (lastsent & 0xFFFF8000L)) && 
2981                 (f->frametype == AST_FRAME_VIDEO) &&
2982                 ((f->subclass & ~0x1) == pvt->svideoformat)) {
2983                         now = 1;
2984                         sendmini = 1;
2985         }
2986         /* Allocate an iax_frame */
2987         if (now) {
2988                 fr = &frb.fr2;
2989         } else
2990                 fr = iax_frame_new(DIRECTION_OUTGRESS, f->datalen);
2991         if (!fr) {
2992                 ast_log(LOG_WARNING, "Out of memory\n");
2993                 return -1;
2994         }
2995         /* Copy our prospective frame into our immediate or retransmitted wrapper */
2996         iax_frame_wrap(fr, f);
2997
2998         fr->ts = fts;
2999         fr->callno = pvt->callno;
3000         fr->transfer = transfer;
3001         fr->final = final;
3002         if (!sendmini) {
3003                 /* We need a full frame */
3004                 if (seqno > -1)
3005                         fr->oseqno = seqno;
3006                 else
3007                         fr->oseqno = pvt->oseqno++;
3008                 fr->iseqno = pvt->iseqno;
3009                 fh = (struct ast_iax2_full_hdr *)(fr->af.data - sizeof(struct ast_iax2_full_hdr));
3010                 fh->scallno = htons(fr->callno | IAX_FLAG_FULL);
3011                 fh->ts = htonl(fr->ts);
3012                 fh->oseqno = fr->oseqno;
3013                 if (transfer) {
3014                         fh->iseqno = 0;
3015                 } else
3016                         fh->iseqno = fr->iseqno;
3017                 /* Keep track of the last thing we've acknowledged */
3018                 if (!transfer)
3019                         pvt->aseqno = fr->iseqno;
3020                 fh->type = fr->af.frametype & 0xFF;
3021                 if (fr->af.frametype == AST_FRAME_VIDEO)
3022                         fh->csub = compress_subclass(fr->af.subclass & ~0x1) | ((fr->af.subclass & 0x1) << 6);
3023                 else
3024                         fh->csub = compress_subclass(fr->af.subclass);
3025                 if (transfer) {
3026                         fr->dcallno = pvt->transfercallno;
3027                 } else
3028                         fr->dcallno = pvt->peercallno;
3029                 fh->dcallno = htons(fr->dcallno);
3030                 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_full_hdr);
3031                 fr->data = fh;
3032                 fr->retries = 0;
3033                 /* Retry after 2x the ping time has passed */
3034                 fr->retrytime = pvt->pingtime * 2;
3035                 if (fr->retrytime < MIN_RETRY_TIME)
3036                         fr->retrytime = MIN_RETRY_TIME;
3037                 if (fr->retrytime > MAX_RETRY_TIME)
3038                         fr->retrytime = MAX_RETRY_TIME;
3039                 /* Acks' don't get retried */
3040                 if ((f->frametype == AST_FRAME_IAX) && (f->subclass == IAX_COMMAND_ACK))
3041                         fr->retries = -1;
3042                 else if (f->frametype == AST_FRAME_VOICE)
3043                         pvt->svoiceformat = f->subclass;
3044                 else if (f->frametype == AST_FRAME_VIDEO)
3045                         pvt->svideoformat = f->subclass & ~0x1;
3046                 if (now) {
3047                         res = send_packet(fr);
3048                 } else
3049                         res = iax2_transmit(fr);
3050         } else {
3051                 if (pvt->trunk) {
3052                         iax2_trunk_queue(pvt, &fr->af);
3053                         res = 0;
3054                 } else if (fr->af.frametype == AST_FRAME_VIDEO) {
3055                         /* Video frame have no sequence number */
3056                         fr->oseqno = -1;
3057                         fr->iseqno = -1;
3058                         vh = (struct ast_iax2_video_hdr *)(fr->af.data - sizeof(struct ast_iax2_video_hdr));
3059                         vh->zeros = 0;
3060                         vh->callno = htons(0x8000 | fr->callno);
3061                         vh->ts = htons((fr->ts & 0x7FFF) | (fr->af.subclass & 0x1 ? 0x8000 : 0));
3062                         fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_video_hdr);
3063                         fr->data = vh;
3064                         fr->retries = -1;
3065                         res = send_packet(fr);                  
3066                 } else {
3067                         /* Mini-frames have no sequence number */
3068                         fr->oseqno = -1;
3069                         fr->iseqno = -1;
3070                         /* Mini frame will do */
3071                         mh = (struct ast_iax2_mini_hdr *)(fr->af.data - sizeof(struct ast_iax2_mini_hdr));
3072                         mh->callno = htons(fr->callno);
3073                         mh->ts = htons(fr->ts & 0xFFFF);
3074                         fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_mini_hdr);
3075                         fr->data = mh;
3076                         fr->retries = -1;
3077                         res = send_packet(fr);
3078                 }
3079         }
3080         return res;
3081 }
3082
3083
3084
3085 static int iax2_show_users(int fd, int argc, char *argv[])
3086 {
3087 #define FORMAT "%-15.15s  %-20.20s  %-15.15s  %-15.15s  %-5.5s\n"
3088 #define FORMAT2 "%-15.15s  %-20.20s  %-15.15d  %-15.15s  %-5.5s\n"
3089         struct iax2_user *user;
3090         char auth[90] = "";
3091         if (argc != 3) 
3092                 return RESULT_SHOWUSAGE;
3093         ast_mutex_lock(&userl.lock);
3094         ast_cli(fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C");
3095         for(user=userl.users;user;user=user->next) {
3096                 if (!ast_strlen_zero(user->secret)) {
3097                         strncpy(auth,user->secret,sizeof(auth)-1);
3098                 } else if (!ast_strlen_zero(user->inkeys)) {
3099                         snprintf(auth, sizeof(auth), "Key: %-15.15s ", user->inkeys);
3100                 } else
3101                         strncpy(auth, "-no secret-", sizeof(auth) - 1);
3102                 ast_cli(fd, FORMAT2, user->name, auth, user->authmethods, 
3103                                 user->contexts ? user->contexts->context : context,
3104                                 user->ha ? "Yes" : "No");
3105         }
3106         ast_mutex_unlock(&userl.lock);
3107         return RESULT_SUCCESS;
3108 #undef FORMAT
3109 #undef FORMAT2
3110 }
3111
3112 static int iax2_show_peers(int fd, int argc, char *argv[])
3113 {
3114 #define FORMAT2 "%-15.15s  %-15.15s %s  %-15.15s  %-8s  %-10s\n"
3115 #define FORMAT "%-15.15s  %-15.15s %s  %-15.15s  %-5d%s  %-10s\n"
3116         struct iax2_peer *peer;
3117         char name[256] = "";
3118         char iabuf[INET_ADDRSTRLEN];
3119         int registeredonly=0;
3120         if ((argc != 3) && (argc != 4) && (argc != 5))
3121                 return RESULT_SHOWUSAGE;
3122         if ((argc == 4)) {
3123                 if (!strcasecmp(argv[3], "registered")) {
3124                         registeredonly = 1;
3125                 } else
3126                         return RESULT_SHOWUSAGE;
3127         }
3128         ast_mutex_lock(&peerl.lock);
3129         ast_cli(fd, FORMAT2, "Name/Username", "Host", "   ", "Mask", "Port", "Status");
3130         for (peer = peerl.peers;peer;peer = peer->next) {
3131                 char nm[20];
3132                 char status[20] = "";
3133                 int print_line = -1;
3134                 char srch[2000] = "";
3135                 if (registeredonly && !peer->addr.sin_addr.s_addr)
3136                         continue;
3137                 if (!ast_strlen_zero(peer->username))
3138                         snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
3139                 else
3140                         strncpy(name, peer->name, sizeof(name) - 1);
3141                 if (peer->maxms) {
3142                         if (peer->lastms < 0)
3143                                 strncpy(status, "UNREACHABLE", sizeof(status) - 1);
3144                         else if (peer->lastms > peer->maxms) 
3145                                 snprintf(status, sizeof(status), "LAGGED (%d ms)", peer->lastms);
3146                         else if (peer->lastms) 
3147                                 snprintf(status, sizeof(status), "OK (%d ms)", peer->lastms);
3148                         else 
3149                                 strncpy(status, "UNKNOWN", sizeof(status) - 1);
3150                 } else 
3151                         strncpy(status, "Unmonitored", sizeof(status) - 1);
3152                 strncpy(nm, ast_inet_ntoa(iabuf, sizeof(iabuf), peer->mask), sizeof(nm)-1);
3153
3154                 snprintf(srch, sizeof(srch), FORMAT, name, 
3155                                         peer->addr.sin_addr.s_addr ? ast_inet_ntoa(iabuf, sizeof(iabuf), peer->addr.sin_addr) : "(Unspecified)",
3156                                         peer->dynamic ? "(D)" : "(S)",
3157                                         nm,
3158                                         ntohs(peer->addr.sin_port), peer->trunk ? "(T)" : "   ", status);
3159
3160                 if (argc == 5) {
3161                   if (!strcasecmp(argv[3],"include") && strstr(srch,argv[4])) {
3162                         print_line = -1;
3163                    } else if (!strcasecmp(argv[3],"exclude") && !strstr(srch,argv[4])) {
3164                         print_line = 1;
3165                    } else if (!strcasecmp(argv[3],"begin") && !strncasecmp(srch,argv[4],strlen(argv[4]))) {
3166                         print_line = -1;
3167                    } else {
3168                         print_line = 0;
3169                   }
3170                 }
3171                 
3172                 if (print_line) {
3173                 ast_cli(fd, FORMAT, name, 
3174                                         peer->addr.sin_addr.s_addr ? ast_inet_ntoa(iabuf, sizeof(iabuf), peer->addr.sin_addr) : "(Unspecified)",
3175                                         peer->dynamic ? "(D)" : "(S)",
3176                                         nm,
3177                                         ntohs(peer->addr.sin_port), peer->trunk ? "(T)" : "   ", status);
3178                 }
3179         }
3180         ast_mutex_unlock(&peerl.lock);
3181         return RESULT_SUCCESS;
3182 #undef FORMAT
3183 #undef FORMAT2
3184 }
3185
3186 static int iax2_show_firmware(int fd, int argc, char *argv[])
3187 {
3188 #define FORMAT2 "%-15.15s  %-15.15s %-15.15s\n"
3189 #define FORMAT "%-15.15s  %-15d %-15d\n"
3190         struct iax_firmware *cur;
3191         if ((argc != 3) && (argc != 4))
3192                 return RESULT_SHOWUSAGE;
3193         ast_mutex_lock(&waresl.lock);
3194         
3195         ast_cli(fd, FORMAT2, "Device", "Version", "Size");
3196         for (cur = waresl.wares;cur;cur = cur->next) {
3197                 if ((argc == 3) || (!strcasecmp(argv[3], cur->fwh->devname))) 
3198                         ast_cli(fd, FORMAT, cur->fwh->devname, ntohs(cur->fwh->version),
3199                                                 ntohl(cur->fwh->datalen));
3200         }
3201         ast_mutex_unlock(&waresl.lock);
3202         return RESULT_SUCCESS;
3203 #undef FORMAT
3204 #undef FORMAT2
3205 }
3206
3207 /* JDG: callback to display iax peers in manager */
3208 static int manager_iax2_show_peers( struct mansession *s, struct message *m )
3209 {
3210         char *a[] = { "iax2", "show", "users" };
3211         int ret;
3212         ret = iax2_show_peers( s->fd, 3, a );
3213         ast_cli( s->fd, "\r\n" );
3214         return ret;
3215 } /* /JDG */
3216
3217 static char *regstate2str(int regstate)
3218 {
3219         switch(regstate) {
3220         case REG_STATE_UNREGISTERED:
3221                 return "Unregistered";
3222         case REG_STATE_REGSENT:
3223                 return "Request Sent";
3224         case REG_STATE_AUTHSENT:
3225                 return "Auth. Sent";
3226         case REG_STATE_REGISTERED:
3227                 return "Registered";
3228         case REG_STATE_REJECTED:
3229                 return "Rejected";
3230         case REG_STATE_TIMEOUT:
3231                 return "Timeout";
3232         case REG_STATE_NOAUTH:
3233                 return "No Authentication";
3234         default:
3235                 return "Unknown";
3236         }
3237 }
3238
3239 static int iax2_show_registry(int fd, int argc, char *argv[])
3240 {
3241 #define FORMAT2 "%-20.20s  %-10.10s  %-20.20s %8.8s  %s\n"
3242 #define FORMAT "%-20.20s  %-10.10s  %-20.20s %8d  %s\n"
3243         struct iax2_registry *reg;
3244         char host[80];
3245         char perceived[80] = "";
3246         char iabuf[INET_ADDRSTRLEN];
3247         if (argc != 3)
3248                 return RESULT_SHOWUSAGE;
3249         ast_mutex_lock(&peerl.lock);
3250         ast_cli(fd, FORMAT2, "Host", "Username", "Perceived", "Refresh", "State");
3251         for (reg = registrations;reg;reg = reg->next) {
3252                 snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(iabuf, sizeof(iabuf), reg->addr.sin_addr), ntohs(reg->addr.sin_port));
3253                 if (reg->us.sin_addr.s_addr) 
3254                         snprintf(perceived, sizeof(perceived), "%s:%d", ast_inet_ntoa(iabuf, sizeof(iabuf), reg->us.sin_addr), ntohs(reg->us.sin_port));
3255                 else
3256                         strncpy(perceived, "<Unregistered>", sizeof(perceived) - 1);
3257                 ast_cli(fd, FORMAT, host, 
3258                                         reg->username, perceived, reg->refresh, regstate2str(reg->regstate));
3259         }
3260         ast_mutex_unlock(&peerl.lock);
3261         return RESULT_SUCCESS;
3262 #undef FORMAT
3263 #undef FORMAT2
3264 }
3265
3266 static int jitterbufsize(struct chan_iax2_pvt *pvt) {
3267         int min, i;
3268         min = 99999999;
3269         for (i=0; i<MEMORY_SIZE; i++) {
3270                 if (pvt->history[i] < min)
3271                         min = pvt->history[i];
3272         }
3273         return pvt->jitterbuffer - min;
3274 }
3275
3276 static int iax2_show_channels(int fd, int argc, char *argv[])
3277 {
3278 #define FORMAT2 "%-15.15s  %-10.10s  %-11.11s  %-11.11s  %-7.7s  %-6.6s  %-6.6s  %s\n"
3279 #define FORMAT  "%-15.15s  %-10.10s  %5.5d/%5.5d  %5.5d/%5.5d  %-5.5dms  %-4.4dms  %-4.4dms  %-6.6s\n"
3280         int x;
3281         int numchans = 0;
3282         char iabuf[INET_ADDRSTRLEN];
3283         if (argc != 3)
3284                 return RESULT_SHOWUSAGE;
3285         ast_cli(fd, FORMAT2, "Peer", "Username", "ID (Lo/Rem)", "Seq (Tx/Rx)", "Lag", "Jitter", "JitBuf", "Format");
3286         for (x=0;x<IAX_MAX_CALLS;x++) {
3287                 ast_mutex_lock(&iaxsl[x]);
3288                 if (iaxs[x]) {
3289                         ast_cli(fd, FORMAT, ast_inet_ntoa(iabuf, sizeof(iabuf), iaxs[x]->addr.sin_addr), 
3290                                                 !ast_strlen_zero(iaxs[x]->username) ? iaxs[x]->username : "(None)", 
3291                                                 iaxs[x]->callno, iaxs[x]->peercallno, 
3292                                                 iaxs[x]->oseqno, iaxs[x]->iseqno, 
3293                                                 iaxs[x]->lag,
3294                                                 iaxs[x]->jitter,
3295                                                 use_jitterbuffer ? jitterbufsize(iaxs[x]) : 0,
3296                                                 ast_getformatname(iaxs[x]->voiceformat) );
3297                         numchans++;
3298                 }
3299                 ast_mutex_unlock(&iaxsl[x]);
3300         }
3301         ast_cli(fd, "%d active IAX channel(s)\n", numchans);
3302         return RESULT_SUCCESS;
3303 #undef FORMAT
3304 #undef FORMAT2
3305 }
3306
3307 static int iax2_do_trunk_debug(int fd, int argc, char *argv[])
3308 {
3309         if (argc != 3)
3310                 return RESULT_SHOWUSAGE;
3311         iaxtrunkdebug = 1;
3312         ast_cli(fd, "IAX2 Trunk Debug Requested\n");
3313         return RESULT_SUCCESS;
3314 }
3315
3316 static int iax2_do_debug(int fd, int argc, char *argv[])
3317 {
3318         if (argc != 2)
3319                 return RESULT_SHOWUSAGE;
3320         iaxdebug = 1;
3321         ast_cli(fd, "IAX2 Debugging Enabled\n");
3322         return RESULT_SUCCESS;
3323 }
3324
3325 static int iax2_no_debug(int fd, int argc, char *argv[])
3326 {
3327         if (argc != 3)
3328                 return RESULT_SHOWUSAGE;
3329         iaxdebug = 0;
3330         ast_cli(fd, "IAX2 Debugging Disabled\n");
3331         return RESULT_SUCCESS;
3332 }
3333
3334
3335
3336 static char show_users_usage[] = 
3337 "Usage: iax2 show users\n"
3338 "       Lists all users known to the IAX (Inter-Asterisk eXchange rev 2) subsystem.\n";
3339
3340 static char show_channels_usage[] = 
3341 "Usage: iax2 show channels\n"
3342 "       Lists all currently active IAX channels.\n";
3343
3344 static char show_peers_usage[] = 
3345 "Usage: iax2 show peers\n"
3346 "       Lists all known IAX peers.\n";
3347
3348 static char show_firmware_usage[] = 
3349 "Usage: iax2 show firmware\n"
3350 "       Lists all known IAX firmware images.\n";
3351
3352 static char show_reg_usage[] =
3353 "Usage: iax2 show registry\n"
3354 "       Lists all registration requests and status.\n";
3355
3356 static char debug_usage[] = 
3357 "Usage: iax2 debug\n"
3358 "       Enables dumping of IAX packets for debugging purposes\n";
3359
3360 static char no_debug_usage[] = 
3361 "Usage: iax2 no debug\n"
3362 "       Disables dumping of IAX packets for debugging purposes\n";
3363
3364 static char debug_trunk_usage[] =
3365 "Usage: iax2 trunk debug\n"
3366 "       Requests current status of IAX trunking\n";
3367
3368 static struct ast_cli_entry  cli_show_users = 
3369         { { "iax2", "show", "users", NULL }, iax2_show_users, "Show defined IAX users", show_users_usage };
3370 static struct ast_cli_entry  cli_show_firmware = 
3371         { { "iax2", "show", "firmware", NULL }, iax2_show_firmware, "Show available IAX firmwares", show_firmware_usage };
3372 static struct ast_cli_entry  cli_show_channels =
3373         { { "iax2", "show", "channels", NULL }, iax2_show_channels, "Show active IAX channels", show_channels_usage };
3374 static struct ast_cli_entry  cli_show_peers =
3375         { { "iax2", "show", "peers", NULL }, iax2_show_peers, "Show defined IAX peers", show_peers_usage };
3376 static struct ast_cli_entry  cli_show_peers_include =
3377         { { "iax2", "show", "peers", "include", NULL }, iax2_show_peers, "Show defined IAX peers", show_peers_usage };
3378 static struct ast_cli_entry  cli_show_peers_exclude =
3379         { { "iax2", "show", "peers", "exclude", NULL }, iax2_show_peers, "Show defined IAX peers", show_peers_usage };
3380 static struct ast_cli_entry  cli_show_peers_begin =
3381         { { "iax2", "show", "peers", "begin", NULL }, iax2_show_peers, "Show defined IAX peers", show_peers_usage };
3382 static struct ast_cli_entry  cli_show_registry =
3383         { { "iax2", "show", "registry", NULL }, iax2_show_registry, "Show IAX registration status", show_reg_usage };
3384 static struct ast_cli_entry  cli_debug =
3385         { { "iax2", "debug", NULL }, iax2_do_debug, "Enable IAX debugging", debug_usage };
3386 static struct ast_cli_entry  cli_trunk_debug =
3387         { { "iax2", "trunk", "debug", NULL }, iax2_do_trunk_debug, "Request IAX trunk debug", debug_trunk_usage };
3388 static struct ast_cli_entry  cli_no_debug =
3389         { { "iax2", "no", "debug", NULL }, iax2_no_debug, "Disable IAX debugging", no_debug_usage };
3390
3391 static int iax2_write(struct ast_channel *c, struct ast_frame *f)
3392 {
3393         unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
3394         int res = -1;
3395         ast_mutex_lock(&iaxsl[callno]);
3396         if (iaxs[callno]) {
3397         /* If there's an outstanding error, return failure now */
3398                 if (!iaxs[callno]->error) {
3399                         if (iaxs[callno]->alreadygone)
3400                                 res = 0;
3401                                 /* Don't waste bandwidth sending null frames */
3402                         else if (f->frametype == AST_FRAME_NULL)
3403                                 res = 0;
3404                         else if ((f->frametype == AST_FRAME_VOICE) && iaxs[callno]->quelch)
3405                                 res = 0;
3406                         else if (!(iaxs[callno]->state & IAX_STATE_STARTED))
3407                                 res = 0;
3408                         else
3409                         /* Simple, just queue for transmission */
3410                                 res = iax2_send(iaxs[callno], f, 0, -1, 0, 0, 0);
3411                 } else {
3412                         ast_log(LOG_DEBUG, "Write error: %s\n", strerror(errno));
3413                 }
3414         }
3415         /* If it's already gone, just return */
3416         ast_mutex_unlock(&iaxsl[callno]);
3417         return res;
3418 }
3419
3420 static int __send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno, 
3421                 int now, int transfer, int final)
3422 {
3423         struct ast_frame f;
3424         f.frametype = type;
3425         f.subclass = command;
3426         f.datalen = datalen;
3427         f.samples = 0;
3428         f.mallocd = 0;
3429         f.offset = 0;
3430         f.src = __FUNCTION__;
3431         f.data = data;
3432         return iax2_send(i, &f, ts, seqno, now, transfer, final);
3433 }
3434
3435 static int send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
3436 {
3437         return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 0);
3438 }
3439
3440 static int send_command_locked(unsigned short callno, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
3441 {
3442         int res;
3443         ast_mutex_lock(&iaxsl[callno]);
3444         res = send_command(iaxs[callno], type, command, ts, data, datalen, seqno);
3445         ast_mutex_unlock(&iaxsl[callno]);
3446         return res;
3447 }
3448
3449 #ifdef BRIDGE_OPTIMIZATION
3450 static int forward_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
3451 {
3452         return __send_command(iaxs[i->bridgecallno], type, command, ts, data, datalen, seqno, 0, 0, 0);
3453 }
3454 #endif
3455
3456 static int send_command_final(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
3457 {
3458         /* It is assumed that the callno has already been locked */
3459         iax2_predestroy_nolock(i->callno);
3460         return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 1);
3461 }
3462
3463 static int send_command_immediate(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
3464 {
3465         return __send_command(i, type, command, ts, data, datalen, seqno, 1, 0, 0);
3466 }
3467
3468 static int send_command_transfer(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen)
3469 {
3470         return __send_command(i, type, command, ts, data, datalen, 0, 0, 1, 0);
3471 }
3472
3473 static int apply_context(struct iax2_context *con, char *context)
3474 {
3475         while(con) {
3476                 if (!strcmp(con->context, context))
3477                         return -1;
3478                 con = con->next;
3479         }
3480         return 0;
3481 }
3482
3483
3484 static int check_access(int callno, struct sockaddr_in *sin, struct iax_ies *ies)
3485 {
3486 &