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