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