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