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