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