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