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