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