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