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