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