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