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