Thu Mar 13 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 char oseqno;
281         /* Next sequence number they have not yet acknowledged */
282         unsigned char rseqno;
283         /* Next incoming sequence number */
284         unsigned char iseqno;
285         /* Last incoming sequence number we have acknowledged */
286         unsigned char 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: %3.3d ISeqno: %3.3d Type: %s Subclass: %s\n",
610         (rx ? "Rx" : "Tx"),
611         retries, fh->oseqno, 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 = 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, int updatehistory)
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         if (updatehistory) {
1427                 for (x=0;x<MEMORY_SIZE - 1;x++) 
1428                         iaxs[fr->callno]->history[x] = iaxs[fr->callno]->history[x+1];
1429                 /* Add a history entry for this one */
1430                 iaxs[fr->callno]->history[x] = ms;
1431         }
1432
1433         /* Initialize the minimum to reasonable values.  It's too much
1434            work to do the same for the maximum, repeatedly */
1435         min=iaxs[fr->callno]->history[0];
1436         for (z=0;z < iax2_dropcount + 1;z++) {
1437                 /* Start very optimistic ;-) */
1438                 max=-999999999;
1439                 for (x=0;x<MEMORY_SIZE;x++) {
1440                         if (max < iaxs[fr->callno]->history[x]) {
1441                                 /* We have a candidate new maximum value.  Make
1442                                    sure it's not in our drop list */
1443                                 match = 0;
1444                                 for (y=0;!match && (y<z);y++)
1445                                         match |= (drops[y] == x);
1446                                 if (!match) {
1447                                         /* It's not in our list, use it as the new maximum */
1448                                         max = iaxs[fr->callno]->history[x];
1449                                         maxone = x;
1450                                 }
1451                                 
1452                         }
1453                         if (!z) {
1454                                 /* On our first pass, find the minimum too */
1455                                 if (min > iaxs[fr->callno]->history[x])
1456                                         min = iaxs[fr->callno]->history[x];
1457                         }
1458                 }
1459 #if 1
1460                 drops[z] = maxone;
1461 #endif
1462         }
1463         /* Just for reference, keep the "jitter" value, the difference between the
1464            earliest and the latest. */
1465         iaxs[fr->callno]->jitter = max - min;   
1466         
1467         /* IIR filter for keeping track of historic jitter, but always increase
1468            historic jitter immediately for increase */
1469         
1470         if (iaxs[fr->callno]->jitter > iaxs[fr->callno]->historicjitter )
1471                 iaxs[fr->callno]->historicjitter = iaxs[fr->callno]->jitter;
1472         else
1473                 iaxs[fr->callno]->historicjitter = GAMMA * (double)iaxs[fr->callno]->jitter + (1-GAMMA) * 
1474                         iaxs[fr->callno]->historicjitter;
1475
1476         /* If our jitter buffer is too big (by a significant margin), then we slowly
1477            shrink it by about 1 ms each time to avoid letting the change be perceived */
1478         if (max < iaxs[fr->callno]->jitterbuffer - max_jitter_buffer)
1479                 iaxs[fr->callno]->jitterbuffer -= 2;
1480
1481
1482 #if 1
1483         /* Constrain our maximum jitter buffer appropriately */
1484         if (max > min + maxjitterbuffer) {
1485                 if (option_debug)
1486                         ast_log(LOG_DEBUG, "Constraining buffer from %d to %d + %d\n", max, min , maxjitterbuffer);
1487                 max = min + maxjitterbuffer;
1488         }
1489 #endif
1490
1491         /* If our jitter buffer is smaller than our maximum delay, grow the jitter
1492            buffer immediately to accomodate it (and a little more).  */
1493         if (max > iaxs[fr->callno]->jitterbuffer)
1494                 iaxs[fr->callno]->jitterbuffer = max 
1495                         /* + ((float)iaxs[fr->callno]->jitter) * 0.1 */;
1496                 
1497
1498         if (option_debug)
1499                 ast_log(LOG_DEBUG, "min = %d, max = %d, jb = %d, lateness = %d\n", min, max, iaxs[fr->callno]->jitterbuffer, ms);
1500         
1501         /* Subtract the lateness from our jitter buffer to know how long to wait
1502            before sending our packet.  */
1503         ms = iaxs[fr->callno]->jitterbuffer - ms;
1504         
1505         if (!use_jitterbuffer)
1506                 ms = 0;
1507
1508         /* If the caller just wanted us to update, return now */
1509         if (!reallydeliver)
1510                 return 0;
1511                 
1512         if (ms < 1) {
1513                 if (option_debug)
1514                         ast_log(LOG_DEBUG, "Calculated ms is %d\n", ms);
1515                 /* Don't deliver it more than 4 ms late */
1516                 if ((ms > -4) || (fr->af.frametype != AST_FRAME_VOICE)) {
1517                         __do_deliver(fr);
1518                 } else {
1519                         if (option_debug)
1520                                 ast_log(LOG_DEBUG, "Dropping voice packet since %d ms is, too old\n", ms);
1521                         /* Free our iax frame */
1522                         ast_iax2_frame_free(fr);
1523                 }
1524         } else {
1525                 if (option_debug)
1526                         ast_log(LOG_DEBUG, "Scheduling delivery in %d ms\n", ms);
1527                 fr->retrans = ast_sched_add(sched, ms, do_deliver, fr);
1528         }
1529         return 0;
1530 }
1531
1532 static int iax2_transmit(struct ast_iax2_frame *fr)
1533 {
1534         /* Lock the queue and place this packet at the end */
1535         fr->next = NULL;
1536         fr->prev = NULL;
1537         /* By setting this to 0, the network thread will send it for us, and
1538            queue retransmission if necessary */
1539         fr->sentyet = 0;
1540         ast_pthread_mutex_lock(&iaxq.lock);
1541         if (!iaxq.head) {
1542                 /* Empty queue */
1543                 iaxq.head = fr;
1544                 iaxq.tail = fr;
1545         } else {
1546                 /* Double link */
1547                 iaxq.tail->next = fr;
1548                 fr->prev = iaxq.tail;
1549                 iaxq.tail = fr;
1550         }
1551         iaxq.count++;
1552         ast_pthread_mutex_unlock(&iaxq.lock);
1553         /* Wake up the network thread */
1554         pthread_kill(netthreadid, SIGURG);
1555         return 0;
1556 }
1557
1558
1559
1560 static int iax2_digit(struct ast_channel *c, char digit)
1561 {
1562         return send_command(c->pvt->pvt, AST_FRAME_DTMF, digit, 0, NULL, 0, -1);
1563 }
1564
1565 static int iax2_sendtext(struct ast_channel *c, char *text)
1566 {
1567         
1568         return send_command(c->pvt->pvt, AST_FRAME_TEXT,
1569                 0, 0, text, strlen(text) + 1, -1);
1570 }
1571
1572 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
1573 {
1574         return send_command(c->pvt->pvt, AST_FRAME_IMAGE, img->subclass, 0, img->data, img->datalen, -1);
1575 }
1576
1577 static int iax2_sendhtml(struct ast_channel *c, int subclass, char *data, int datalen)
1578 {
1579         return send_command(c->pvt->pvt, AST_FRAME_HTML, subclass, 0, data, datalen, -1);
1580 }
1581
1582 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
1583 {
1584         struct chan_iax2_pvt *pvt = newchan->pvt->pvt;
1585         pvt->owner = newchan;
1586         return 0;
1587 }
1588
1589 static int create_addr(struct sockaddr_in *sin, int *capability, int *sendani, int *maxtime, char *peer, char *context)
1590 {
1591         struct hostent *hp;
1592         struct iax2_peer *p;
1593         int found=0;
1594         if (sendani)
1595                 *sendani = 0;
1596         if (maxtime)
1597                 *maxtime = 0;
1598         sin->sin_family = AF_INET;
1599         ast_pthread_mutex_lock(&peerl.lock);
1600         p = peerl.peers;
1601         while(p) {
1602                 if (!strcasecmp(p->name, peer)) {
1603                         found++;
1604                         if (capability)
1605                                 *capability = p->capability;
1606                         if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
1607                                 (!p->maxms || ((p->lastms > 0)  && (p->lastms <= p->maxms)))) {
1608                                 if (sendani)
1609                                         *sendani = p->sendani;          /* Whether we transmit ANI */
1610                                 if (maxtime)
1611                                         *maxtime = p->maxms;            /* Max time they should take */
1612                                 if (context)
1613                                         strncpy(context, p->context, AST_MAX_EXTENSION - 1);
1614                                 if (p->addr.sin_addr.s_addr) {
1615                                         sin->sin_addr = p->addr.sin_addr;
1616                                         sin->sin_port = p->addr.sin_port;
1617                                 } else {
1618                                         sin->sin_addr = p->defaddr.sin_addr;
1619                                         sin->sin_port = p->defaddr.sin_port;
1620                                 }
1621                                 break;
1622                         }
1623                 }
1624                 p = p->next;
1625         }
1626         ast_pthread_mutex_unlock(&peerl.lock);
1627         if (!p && !found) {
1628                 hp = gethostbyname(peer);
1629                 if (hp) {
1630                         memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
1631                         sin->sin_port = htons(AST_DEFAULT_IAX_PORTNO);
1632                         return 0;
1633                 } else {
1634                         ast_log(LOG_WARNING, "No such host: %s\n", peer);
1635                         return -1;
1636                 }
1637         } else if (!p)
1638                 return -1;
1639         else
1640                 return 0;
1641 }
1642
1643 static int auto_congest(void *nothing)
1644 {
1645         int callno = (int)(long)(nothing);
1646         struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_CONGESTION };
1647         ast_pthread_mutex_lock(&iaxsl[callno]);
1648         if (iaxs[callno]) {
1649                 iaxs[callno]->initid = -1;
1650                 iax2_queue_frame(callno, &f);
1651                 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
1652         }
1653         ast_pthread_mutex_unlock(&iaxsl[callno]);
1654         return 0;
1655 }
1656
1657 static int iax_ie_append_raw(struct iax_ie_data *ied, unsigned char ie, void *data, int datalen)
1658 {
1659         if (datalen > (sizeof(ied->buf) - ied->pos)) {
1660                 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);
1661                 return -1;
1662         }
1663         ied->buf[ied->pos++] = ie;
1664         ied->buf[ied->pos++] = datalen;
1665         memcpy(ied->buf + ied->pos, data, datalen);
1666         ied->pos += datalen;
1667         return 0;
1668 }
1669
1670 static int iax_ie_append_addr(struct iax_ie_data *ied, unsigned char ie, struct sockaddr_in *sin)
1671 {
1672         return iax_ie_append_raw(ied, ie, sin, sizeof(struct sockaddr_in));
1673 }
1674
1675 static int iax_ie_append_int(struct iax_ie_data *ied, unsigned char ie, unsigned int value) 
1676 {
1677         unsigned int newval;
1678         newval = htonl(value);
1679         return iax_ie_append_raw(ied, ie, &newval, sizeof(newval));
1680 }
1681
1682 static int iax_ie_append_short(struct iax_ie_data *ied, unsigned char ie, unsigned short value) 
1683 {
1684         unsigned short newval;
1685         newval = htons(value);
1686         return iax_ie_append_raw(ied, ie, &newval, sizeof(newval));
1687 }
1688
1689 static int iax_ie_append_str(struct iax_ie_data *ied, unsigned char ie, unsigned char *str)
1690 {
1691         return iax_ie_append_raw(ied, ie, str, strlen(str));
1692 }
1693
1694 static int iax2_call(struct ast_channel *c, char *dest, int timeout)
1695 {
1696         struct sockaddr_in sin;
1697         char host[256];
1698         char *rdest;
1699         char *rcontext;
1700         char *username;
1701         char *secret = NULL;
1702         char *hname;
1703         char cid[256] = "";
1704         char *l=NULL, *n=NULL;
1705         struct iax_ie_data ied;
1706         char myrdest [5] = "s";
1707         char context[AST_MAX_EXTENSION] ="";
1708         char *portno = NULL;
1709         struct chan_iax2_pvt *p = c->pvt->pvt;
1710         char *stringp=NULL;
1711         if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
1712                 ast_log(LOG_WARNING, "Line is already in use (%s)?\n", c->name);
1713                 return -1;
1714         }
1715         strncpy(host, dest, sizeof(host)-1);
1716         stringp=host;
1717         strsep(&stringp, "/");
1718         /* If no destination extension specified, use 's' */
1719         rdest = strsep(&stringp, "/");
1720         if (!rdest) 
1721                 rdest = myrdest;
1722         stringp=rdest;
1723         strsep(&stringp, "@");
1724         rcontext = strsep(&stringp, "@");
1725         stringp=host;
1726         strsep(&stringp, "@");
1727         username = strsep(&stringp, "@");
1728         if (username) {
1729                 /* Really the second argument is the host, not the username */
1730                 hname = username;
1731                 username = host;
1732         } else {
1733                 hname = host;
1734         }
1735         if (username) {
1736                 stringp=username;
1737                 username = strsep(&stringp, ":");
1738                 secret = strsep(&stringp, ":");
1739         }
1740         stringp=hname;
1741         if (strsep(&stringp, ":")) {
1742                 stringp=hname;
1743                 strsep(&stringp, ":");
1744                 portno = strsep(&stringp, ":");
1745         }
1746         if (create_addr(&sin, NULL, NULL, NULL, hname, context)) {
1747                 ast_log(LOG_WARNING, "No address associated with '%s'\n", hname);
1748                 return -1;
1749         }
1750         /* Keep track of the context for outgoing calls too */
1751         strncpy(c->context, context, sizeof(c->context) - 1);
1752         if (portno) {
1753                 sin.sin_port = htons(atoi(portno));
1754         }
1755         if (c->callerid) {
1756                 strncpy(cid, c->callerid, sizeof(cid) - 1);
1757                 ast_callerid_parse(cid, &n, &l);
1758                 if (l)
1759                         ast_shrink_phone_number(l);
1760         }
1761         /* Now build request */ 
1762         memset(&ied, 0, sizeof(ied));
1763         /* On new call, first IE MUST be IAX version of caller */
1764         iax_ie_append_short(&ied, IAX_IE_VERSION, AST_IAX2_PROTO_VERSION);
1765         iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, rdest);
1766         if (l)
1767                 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
1768         if (n)
1769                 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n);
1770         if (p->sendani && c->ani) {
1771                 l = n = NULL;
1772                 strncpy(cid, c->ani, sizeof(cid) - 1);
1773                 ast_callerid_parse(cid, &n, &l);
1774                 if (l) {
1775                         ast_shrink_phone_number(l);
1776                         iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, l);
1777                 }
1778         }
1779         if (c->language && strlen(c->language))
1780                 iax_ie_append_str(&ied, IAX_IE_LANGUAGE, c->language);
1781         if (c->dnid && strlen(c->dnid))
1782                 iax_ie_append_str(&ied, IAX_IE_DNID, c->dnid);
1783         if (rcontext)
1784                 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, rcontext);
1785         if (username)
1786                 iax_ie_append_str(&ied, IAX_IE_USERNAME, username);
1787         if (secret) {
1788                 if (secret[0] == '[') {
1789                         /* This is an RSA key, not a normal secret */
1790                         strncpy(p->outkey, secret + 1, sizeof(p->secret)-1);
1791                         if (strlen(p->outkey)) {
1792                                 p->outkey[strlen(p->outkey) - 1] = '\0';
1793                         }
1794                 } else
1795                         strncpy(p->secret, secret, sizeof(p->secret)-1);
1796         }
1797         iax_ie_append_int(&ied, IAX_IE_FORMAT, c->nativeformats);
1798         iax_ie_append_int(&ied, IAX_IE_CAPABILITY, p->capability);
1799         iax_ie_append_int(&ied, IAX_IE_ADSICPE, c->adsicpe);
1800         /* Transmit the string in a "NEW" request */
1801 #if 0
1802         /* XXX We have no equivalent XXX */
1803         if (option_verbose > 2)
1804                 ast_verbose(VERBOSE_PREFIX_3 "Calling using options '%s'\n", requeststr);
1805 #endif          
1806         if (p->maxtime) {
1807                 /* Initialize pingtime and auto-congest time */
1808                 p->pingtime = p->maxtime / 2;
1809                 p->initid = ast_sched_add(sched, p->maxtime * 2, auto_congest, (void *)(long)p->callno);
1810         }
1811         send_command(p, AST_FRAME_IAX,
1812                 AST_IAX2_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
1813         ast_setstate(c, AST_STATE_RINGING);
1814         return 0;
1815 }
1816
1817 static int iax2_hangup(struct ast_channel *c) 
1818 {
1819         struct chan_iax2_pvt *pvt = c->pvt->pvt;
1820         int alreadygone;
1821         int callno;
1822         if (pvt) {
1823                 callno = pvt->callno;
1824                 ast_pthread_mutex_lock(&iaxsl[callno]);
1825                 ast_log(LOG_DEBUG, "We're hanging up %s now...\n", c->name);
1826                 alreadygone = pvt->alreadygone;
1827                 /* Send the hangup unless we have had a transmission error or are already gone */
1828                 if (!pvt->error && !alreadygone) 
1829                         send_command_final(pvt, AST_FRAME_IAX, AST_IAX2_COMMAND_HANGUP, 0, NULL, 0, -1);
1830                 /* Explicitly predestroy it */
1831                 iax2_predestroy_nolock(callno);
1832                 /* If we were already gone to begin with, destroy us now */
1833                 if (alreadygone) {
1834                         ast_log(LOG_DEBUG, "Really destroying %s now...\n", c->name);
1835                         iax2_destroy_nolock(callno);
1836                 }
1837                 ast_pthread_mutex_unlock(&iaxsl[callno]);
1838         }
1839         if (option_verbose > 2) 
1840                 ast_verbose(VERBOSE_PREFIX_3 "Hungup '%s'\n", c->name);
1841         return 0;
1842 }
1843
1844 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
1845 {
1846         struct ast_option_header *h;
1847         int res;
1848         h = malloc(datalen + sizeof(struct ast_option_header));
1849         if (h) {
1850                 h->flag = AST_OPTION_FLAG_REQUEST;
1851                 h->option = htons(option);
1852                 memcpy(h->data, data, datalen);
1853                 res = send_command((struct chan_iax2_pvt *)c->pvt->pvt, AST_FRAME_CONTROL,
1854                         AST_CONTROL_OPTION, 0, (char *)h, datalen + sizeof(struct ast_option_header), -1);
1855                 free(h);
1856                 return res;
1857         } else 
1858                 ast_log(LOG_WARNING, "Out of memory\n");
1859         return -1;
1860 }
1861 static struct ast_frame *iax2_read(struct ast_channel *c) 
1862 {
1863         static struct ast_frame f = { AST_FRAME_NULL, };
1864         ast_log(LOG_NOTICE, "I should never be called!\n");
1865         return &f;
1866 }
1867
1868 static int iax2_start_transfer(struct ast_channel *c0, struct ast_channel *c1)
1869 {
1870         int res;
1871         struct iax_ie_data ied0;
1872         struct iax_ie_data ied1;
1873         struct chan_iax2_pvt *p0 = c0->pvt->pvt;
1874         struct chan_iax2_pvt *p1 = c1->pvt->pvt;
1875         memset(&ied0, 0, sizeof(ied0));
1876         iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &p1->addr);
1877         iax_ie_append_short(&ied0, IAX_IE_CALLNO, p1->peercallno);
1878
1879         memset(&ied1, 0, sizeof(ied1));
1880         iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &p0->addr);
1881         iax_ie_append_short(&ied1, IAX_IE_CALLNO, p0->peercallno);
1882         
1883         res = send_command(p0, AST_FRAME_IAX, AST_IAX2_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
1884         if (res)
1885                 return -1;
1886         res = send_command(p1, AST_FRAME_IAX, AST_IAX2_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
1887         if (res)
1888                 return -1;
1889         p0->transferring = TRANSFER_BEGIN;
1890         p1->transferring = TRANSFER_BEGIN;
1891         return 0;
1892 }
1893
1894 static int iax2_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
1895 {
1896         struct ast_channel *cs[3];
1897         struct ast_channel *who;
1898         int to = -1;
1899         int res;
1900         int transferstarted=0;
1901         struct ast_frame *f;
1902         struct chan_iax2_pvt *p0 = c0->pvt->pvt;
1903         struct chan_iax2_pvt *p1 = c1->pvt->pvt;
1904
1905         /* Put them in native bridge mode */
1906         p0->bridgecallno = p1->callno;
1907         p1->bridgecallno = p0->callno;
1908
1909         /* If not, try to bridge until we can execute a transfer, if we can */
1910         cs[0] = c0;
1911         cs[1] = c1;
1912         for (/* ever */;;) {
1913                 /* Check in case we got masqueraded into */
1914                 if ((c0->type != type) || (c1->type != type)) {
1915                         if (option_verbose > 2)
1916                                 ast_verbose(VERBOSE_PREFIX_3 "Can't masquerade, we're different...\n");
1917                         return -2;
1918                 }
1919                 if (c0->nativeformats != c1->nativeformats) {
1920                         ast_verbose(VERBOSE_PREFIX_3 "Operating with different codecs, can't native bridge...\n");
1921                         return -2;
1922                 }
1923                 if (!transferstarted) {
1924                         /* Try the transfer */
1925                         if (iax2_start_transfer(c0, c1))
1926                                 ast_log(LOG_WARNING, "Unable to start the transfer\n");
1927                         transferstarted = 1;
1928                 }
1929                 
1930                 if ((p0->transferring == TRANSFER_RELEASED) && (p1->transferring == TRANSFER_RELEASED)) {
1931                         /* Call has been transferred.  We're no longer involved */
1932                         sleep(1);
1933                         c0->_softhangup |= AST_SOFTHANGUP_DEV;
1934                         c1->_softhangup |= AST_SOFTHANGUP_DEV;
1935                         *fo = NULL;
1936                         *rc = c0;
1937                         res = 0;
1938                         break;
1939                 }
1940                 to = 1000;
1941                 who = ast_waitfor_n(cs, 2, &to);
1942                 if (!who) {
1943                         continue;
1944                 }
1945                 f = ast_read(who);
1946                 if (!f) {
1947                         *fo = NULL;
1948                         *rc = who;
1949                         res = 0;
1950                         break;
1951                 }
1952                 if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
1953                         *fo = f;
1954                         *rc = who;
1955                         res =  0;
1956                         break;
1957                 }
1958                 if ((f->frametype == AST_FRAME_VOICE) ||
1959                         (f->frametype == AST_FRAME_TEXT) ||
1960                         (f->frametype == AST_FRAME_VIDEO) || 
1961                         (f->frametype == AST_FRAME_IMAGE) ||
1962                         (f->frametype == AST_FRAME_DTMF)) {
1963                         if ((f->frametype == AST_FRAME_DTMF) && 
1964                                 (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
1965                                 if ((who == c0)) {
1966                                         if  ((flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
1967                                                 *rc = c0;
1968                                                 *fo = f;
1969                                                 /* Take out of conference mode */
1970                                                 res = 0;
1971                                                 break;
1972                                         } else 
1973                                                 goto tackygoto;
1974                                 } else
1975                                 if ((who == c1)) {
1976                                         if (flags & AST_BRIDGE_DTMF_CHANNEL_1) {
1977                                                 *rc = c1;
1978                                                 *fo = f;
1979                                                 res =  0;
1980                                                 break;
1981                                         } else
1982                                                 goto tackygoto;
1983                                 }
1984                         } else {
1985 #if 0
1986                                 ast_log(LOG_DEBUG, "Read from %s\n", who->name);
1987                                 if (who == last) 
1988                                         ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
1989                                 last = who;
1990 #endif
1991 tackygoto:
1992                                 if (who == c0) 
1993                                         ast_write(c1, f);
1994                                 else 
1995                                         ast_write(c0, f);
1996                         }
1997                         ast_frfree(f);
1998                 } else
1999                         ast_frfree(f);
2000                 /* Swap who gets priority */
2001                 cs[2] = cs[0];
2002                 cs[0] = cs[1];
2003                 cs[1] = cs[2];
2004         }
2005         p0->bridgecallno = 0;
2006         p1->bridgecallno = 0;
2007         return res;
2008 }
2009
2010 static int iax2_answer(struct ast_channel *c)
2011 {
2012         struct chan_iax2_pvt *pvt = c->pvt->pvt;
2013         if (option_debug)
2014                 ast_log(LOG_DEBUG, "Answering\n");
2015         return send_command(pvt, AST_FRAME_CONTROL, AST_CONTROL_ANSWER, 0, NULL, 0, -1);
2016 }
2017
2018 static int iax2_indicate(struct ast_channel *c, int condition)
2019 {
2020         struct chan_iax2_pvt *pvt = c->pvt->pvt;
2021         if (option_debug)
2022                 ast_log(LOG_DEBUG, "Indicating condition %d\n", condition);
2023         return send_command(pvt, AST_FRAME_CONTROL, condition, 0, NULL, 0, -1);
2024 }
2025         
2026
2027 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
2028
2029 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len)
2030 {
2031         struct iax2_peer *peer;
2032         int res = 0;
2033         ast_pthread_mutex_lock(&peerl.lock);
2034         peer = peerl.peers;
2035         while(peer) {
2036                 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
2037                                 (peer->addr.sin_port == sin.sin_port)) {
2038                                         strncpy(host, peer->name, len-1);
2039                                         res = 1;
2040                                         break;
2041                 }
2042                 peer = peer->next;
2043         }
2044         ast_pthread_mutex_unlock(&peerl.lock);
2045         return res;
2046 }
2047
2048 static struct ast_channel *ast_iax2_new(struct chan_iax2_pvt *i, int state, int capability)
2049 {
2050         char host[256];
2051         struct ast_channel *tmp;
2052         tmp = ast_channel_alloc(1);
2053         if (tmp) {
2054                 if (!iax2_getpeername(i->addr, host, sizeof(host)))
2055                         snprintf(host, sizeof(host), "%s:%d", inet_ntoa(i->addr.sin_addr), ntohs(i->addr.sin_port));
2056                 if (strlen(i->username))
2057                         snprintf(tmp->name, sizeof(tmp->name), "IAX2[%s@%s]/%d", i->username, host, i->callno);
2058                 else
2059                         snprintf(tmp->name, sizeof(tmp->name), "IAX2[%s]/%d", host, i->callno);
2060                 tmp->type = type;
2061                 /* We can support any format by default, until we get restricted */
2062                 tmp->nativeformats = capability;
2063                 tmp->readformat = 0;
2064                 tmp->writeformat = 0;
2065                 tmp->pvt->pvt = i;
2066                 tmp->pvt->send_digit = iax2_digit;
2067                 tmp->pvt->send_text = iax2_sendtext;
2068                 tmp->pvt->send_image = iax2_sendimage;
2069                 tmp->pvt->send_html = iax2_sendhtml;
2070                 tmp->pvt->call = iax2_call;
2071                 tmp->pvt->hangup = iax2_hangup;
2072                 tmp->pvt->answer = iax2_answer;
2073                 tmp->pvt->read = iax2_read;
2074                 tmp->pvt->write = iax2_write;
2075                 tmp->pvt->indicate = iax2_indicate;
2076                 tmp->pvt->setoption = iax2_setoption;
2077                 tmp->pvt->bridge = iax2_bridge;
2078                 if (strlen(i->callerid))
2079                         tmp->callerid = strdup(i->callerid);
2080                 if (strlen(i->ani))
2081                         tmp->ani = strdup(i->ani);
2082                 if (strlen(i->language))
2083                         strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
2084                 if (strlen(i->dnid))
2085                         tmp->dnid = strdup(i->dnid);
2086                 if (strlen(i->accountcode))
2087                         strncpy(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode)-1);
2088                 if (i->amaflags)
2089                         tmp->amaflags = i->amaflags;
2090                 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
2091                 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
2092                 tmp->adsicpe = i->peeradsicpe;
2093                 tmp->pvt->fixup = iax2_fixup;
2094                 i->owner = tmp;
2095                 i->capability = capability;
2096                 ast_setstate(tmp, state);
2097                 ast_pthread_mutex_lock(&usecnt_lock);
2098                 usecnt++;
2099                 ast_pthread_mutex_unlock(&usecnt_lock);
2100                 ast_update_use_count();
2101                 if (state != AST_STATE_DOWN) {
2102                         if (ast_pbx_start(tmp)) {
2103                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
2104                                 ast_hangup(tmp);
2105                                 tmp = NULL;
2106                         }
2107                 }
2108         }
2109         return tmp;
2110 }
2111
2112 static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts)
2113 {
2114         struct timeval tv;
2115         unsigned int ms;
2116         if (!p->offset.tv_sec && !p->offset.tv_usec)
2117                 gettimeofday(&p->offset, NULL);
2118         /* If the timestamp is specified, just send it as is */
2119         if (ts)
2120                 return ts;
2121         gettimeofday(&tv, NULL);
2122         ms = (tv.tv_sec - p->offset.tv_sec) * 1000 + (tv.tv_usec - p->offset.tv_usec) / 1000;
2123         /* We never send the same timestamp twice, so fudge a little if we must */
2124         if (ms <= p->lastsent)
2125                 ms = p->lastsent + 1;
2126         p->lastsent = ms;
2127         return ms;
2128 }
2129
2130 #ifdef BRIDGE_OPTIMIZATION
2131 static unsigned int calc_fakestamp(struct chan_iax2_pvt *p1, struct chan_iax2_pvt *p2, unsigned int fakets)
2132 {
2133         int ms;
2134         /* Receive from p1, send to p2 */
2135         
2136         /* Setup rxcore if necessary on outgoing channel */
2137         if (!p1->rxcore.tv_sec && !p1->rxcore.tv_usec)
2138                 gettimeofday(&p1->rxcore, NULL);
2139
2140         /* Setup txcore if necessary on outgoing channel */
2141         if (!p2->offset.tv_sec && !p2->offset.tv_usec)
2142                 gettimeofday(&p2->offset, NULL);
2143         
2144         /* Now, ts is the timestamp of the original packet in the orignal context.
2145            Adding rxcore to it gives us when we would want the packet to be delivered normally.
2146            Subtracting txcore of the outgoing channel gives us what we'd expect */
2147         
2148         ms = (p1->rxcore.tv_sec - p2->offset.tv_sec) * 1000 + (p1->rxcore.tv_usec - p1->offset.tv_usec) / 1000;
2149         fakets += ms;
2150         if (fakets <= p2->lastsent)
2151                 fakets = p2->lastsent + 1;
2152         p2->lastsent = fakets;
2153         return fakets;
2154 }
2155 #endif
2156
2157 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p)
2158 {
2159         /* Returns where in "receive time" we are */
2160         struct timeval tv;
2161         unsigned int ms;
2162         /* Setup rxcore if necessary */
2163         if (!p->rxcore.tv_sec && !p->rxcore.tv_usec)
2164                 gettimeofday(&p->rxcore, NULL);
2165
2166         gettimeofday(&tv, NULL);
2167         ms = (tv.tv_sec - p->rxcore.tv_sec) * 1000 + (tv.tv_usec - p->rxcore.tv_usec) / 1000;
2168         return ms;
2169 }
2170
2171 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final)
2172 {
2173         /* Queue a packet for delivery on a given private structure.  Use "ts" for
2174            timestamp, or calculate if ts is 0.  Send immediately without retransmission
2175            or delayed, with retransmission */
2176         struct ast_iax2_full_hdr *fh;
2177         struct ast_iax2_mini_hdr *mh;
2178         struct ast_iax2_frame *fr, fr2;
2179         int res;
2180         unsigned int lastsent;
2181         /* Allocate an ast_iax2_frame */
2182         if (now) {
2183                 fr = &fr2;
2184         } else
2185                 fr = ast_iax2_frame_new(DIRECTION_OUTGRESS, f->datalen);
2186         if (!fr) {
2187                 ast_log(LOG_WARNING, "Out of memory\n");
2188                 return -1;
2189         }
2190         if (!pvt) {
2191                 ast_log(LOG_WARNING, "No private structure for packet (%d)?\n", fr->callno);
2192                 if (!now)
2193                         ast_iax2_frame_free(fr);
2194                 return -1;
2195         }
2196         /* Copy our prospective frame into our immediate or retransmitted wrapper */
2197         ast_iax2_frame_wrap(fr, f);
2198
2199         lastsent = pvt->lastsent;
2200         fr->ts = calc_timestamp(pvt, ts);
2201         if (!fr->ts) {
2202                 ast_log(LOG_WARNING, "timestamp is 0?\n");
2203                 if (!now)
2204                         ast_iax2_frame_free(fr);
2205                 return -1;
2206         }
2207         fr->callno = pvt->callno;
2208         fr->transfer = transfer;
2209         fr->final = final;
2210         if (((fr->ts & 0xFFFF0000L) != (lastsent & 0xFFFF0000L))
2211                 /* High two bits of timestamp differ */ ||
2212             (fr->af.frametype != AST_FRAME_VOICE) 
2213                 /* or not a voice frame */ || 
2214                 (fr->af.subclass != pvt->svoiceformat) 
2215                 /* or new voice format */ ) {
2216                 /* We need a full frame */
2217                 if (seqno > -1)
2218                         fr->oseqno = seqno;
2219                 else
2220                         fr->oseqno = pvt->oseqno++;
2221                 fr->iseqno = pvt->iseqno;
2222                 fh = (struct ast_iax2_full_hdr *)(fr->af.data - sizeof(struct ast_iax2_full_hdr));
2223                 fh->scallno = htons(fr->callno | AST_FLAG_FULL);
2224                 fh->ts = htonl(fr->ts);
2225                 fh->oseqno = fr->oseqno;
2226                 fh->iseqno = fr->iseqno;
2227                 /* Keep track of the last thing we've acknowledged */
2228                 pvt->aseqno = fr->iseqno;
2229                 fh->type = fr->af.frametype & 0xFF;
2230                 fh->csub = compress_subclass(fr->af.subclass);
2231                 if (transfer) {
2232                         fr->dcallno = pvt->transfercallno;
2233                 } else
2234                         fr->dcallno = pvt->peercallno;
2235                 fh->dcallno = htons(fr->dcallno);
2236                 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_full_hdr);
2237                 fr->data = fh;
2238                 fr->retries = 0;
2239                 /* Retry after 2x the ping time has passed */
2240                 fr->retrytime = pvt->pingtime * 2;
2241                 if (fr->retrytime < MIN_RETRY_TIME)
2242                         fr->retrytime = MIN_RETRY_TIME;
2243                 if (fr->retrytime > MAX_RETRY_TIME)
2244                         fr->retrytime = MAX_RETRY_TIME;
2245                 /* Acks' don't get retried */
2246                 if ((f->frametype == AST_FRAME_IAX) && (f->subclass == AST_IAX2_COMMAND_ACK))
2247                         fr->retries = -1;
2248                 if (f->frametype == AST_FRAME_VOICE) {
2249                         pvt->svoiceformat = f->subclass;
2250                 }
2251                 if (now) {
2252                         res = send_packet(fr);
2253                 } else
2254                         res = iax2_transmit(fr);
2255         } else {
2256                 /* Mini-frames have no sequence number */
2257                 fr->oseqno = -1;
2258                 fr->iseqno = -1;
2259                 /* Mini frame will do */
2260                 mh = (struct ast_iax2_mini_hdr *)(fr->af.data - sizeof(struct ast_iax2_mini_hdr));
2261                 mh->callno = htons(fr->callno);
2262                 mh->ts = htons(fr->ts & 0xFFFF);
2263                 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_mini_hdr);
2264                 fr->data = mh;
2265                 fr->retries = -1;
2266                 if (now) {
2267                         res = send_packet(fr);
2268                 } else
2269                         res = iax2_transmit(fr);
2270         }
2271         return res;
2272 }
2273
2274
2275
2276 static int iax2_show_users(int fd, int argc, char *argv[])
2277 {
2278 #define FORMAT "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-5.5s\n"
2279 #define FORMAT2 "%-15.15s  %-15.15s  %-15.15d  %-15.15s  %-5.5s\n"
2280         struct iax2_user *user;
2281         if (argc != 3) 
2282                 return RESULT_SHOWUSAGE;
2283         ast_pthread_mutex_lock(&userl.lock);
2284         ast_cli(fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C");
2285         for(user=userl.users;user;user=user->next) {
2286                 ast_cli(fd, FORMAT2, user->name, user->secret, user->authmethods, 
2287                                 user->contexts ? user->contexts->context : context,
2288                                 user->ha ? "Yes" : "No");
2289         }
2290         ast_pthread_mutex_unlock(&userl.lock);
2291         return RESULT_SUCCESS;
2292 #undef FORMAT
2293 #undef FORMAT2
2294 }
2295
2296 static int iax2_show_peers(int fd, int argc, char *argv[])
2297 {
2298 #define FORMAT2 "%-15.15s  %-15.15s %s  %-15.15s  %-8s  %-10s\n"
2299 #define FORMAT "%-15.15s  %-15.15s %s  %-15.15s  %-8d  %-10s\n"
2300         struct iax2_peer *peer;
2301         char name[256] = "";
2302         if (argc != 3)
2303                 return RESULT_SHOWUSAGE;
2304         ast_pthread_mutex_lock(&peerl.lock);
2305         ast_cli(fd, FORMAT2, "Name/Username", "Host", "   ", "Mask", "Port", "Status");
2306         for (peer = peerl.peers;peer;peer = peer->next) {
2307                 char nm[20];
2308                 char status[20];
2309                 if (strlen(peer->username))
2310                         snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
2311                 else
2312                         strncpy(name, peer->name, sizeof(name) - 1);
2313                 if (peer->maxms) {
2314                         if (peer->lastms < 0)
2315                                 strcpy(status, "UNREACHABLE");
2316                         else if (peer->lastms > peer->maxms) 
2317                                 snprintf(status, sizeof(status), "LAGGED (%d ms)", peer->lastms);
2318                         else if (peer->lastms) 
2319                                 snprintf(status, sizeof(status), "OK (%d ms)", peer->lastms);
2320                         else 
2321                                 strcpy(status, "UNKNOWN");
2322                 } else 
2323                         strcpy(status, "Unmonitored");
2324                 strncpy(nm, inet_ntoa(peer->mask), sizeof(nm)-1);
2325                 ast_cli(fd, FORMAT, name, 
2326                                         peer->addr.sin_addr.s_addr ? inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
2327                                         peer->dynamic ? "(D)" : "(S)",
2328                                         nm,
2329                                         ntohs(peer->addr.sin_port), status);
2330         }
2331         ast_pthread_mutex_unlock(&peerl.lock);
2332         return RESULT_SUCCESS;
2333 #undef FORMAT
2334 #undef FORMAT2
2335 }
2336
2337 /* JDG: callback to display iax peers in manager */
2338 static int manager_iax2_show_peers( struct mansession *s, struct message *m )
2339 {
2340         char *a[] = { "iax2", "show", "users" };
2341         int ret;
2342         ret = iax2_show_peers( s->fd, 3, a );
2343         ast_cli( s->fd, "\r\n" );
2344         return ret;
2345 } /* /JDG */
2346
2347 static char *regstate2str(int regstate)
2348 {
2349         switch(regstate) {
2350         case REG_STATE_UNREGISTERED:
2351                 return "Unregistered";
2352         case REG_STATE_REGSENT:
2353                 return "Request Sent";
2354         case REG_STATE_AUTHSENT:
2355                 return "Auth. Sent";
2356         case REG_STATE_REGISTERED:
2357                 return "Registered";
2358         case REG_STATE_REJECTED:
2359                 return "Rejected";
2360         case REG_STATE_TIMEOUT:
2361                 return "Timeout";
2362         case REG_STATE_NOAUTH:
2363                 return "No Authentication";
2364         default:
2365                 return "Unknown";
2366         }
2367 }
2368
2369 static int iax2_show_registry(int fd, int argc, char *argv[])
2370 {
2371 #define FORMAT2 "%-20.20s  %-10.10s  %-20.20s %8.8s  %s\n"
2372 #define FORMAT "%-20.20s  %-10.10s  %-20.20s %8d  %s\n"
2373         struct iax2_registry *reg;
2374         char host[80];
2375         char perceived[80];
2376         if (argc != 3)
2377                 return RESULT_SHOWUSAGE;
2378         ast_pthread_mutex_lock(&peerl.lock);
2379         ast_cli(fd, FORMAT2, "Host", "Username", "Perceived", "Refresh", "State");
2380         for (reg = registrations;reg;reg = reg->next) {
2381                 snprintf(host, sizeof(host), "%s:%d", inet_ntoa(reg->addr.sin_addr), ntohs(reg->addr.sin_port));
2382                 if (reg->us.sin_addr.s_addr) 
2383                         snprintf(perceived, sizeof(perceived), "%s:%d", inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
2384                 else
2385                         strcpy(perceived, "<Unregistered>");
2386                 ast_cli(fd, FORMAT, host, 
2387                                         reg->username, perceived, reg->refresh, regstate2str(reg->regstate));
2388         }
2389         ast_pthread_mutex_unlock(&peerl.lock);
2390         return RESULT_SUCCESS;
2391 #undef FORMAT
2392 #undef FORMAT2
2393 }
2394
2395 static int iax2_show_channels(int fd, int argc, char *argv[])
2396 {
2397 #define FORMAT2 "%-15.15s  %-10.10s  %-11.11s  %-11.11s  %-7.7s  %-6.6s  %s\n"
2398 #define FORMAT  "%-15.15s  %-10.10s  %5.5d/%5.5d  %5.5d/%5.5d  %-5.5dms  %-4.4dms  %d\n"
2399         int x;
2400         int numchans = 0;
2401         if (argc != 3)
2402                 return RESULT_SHOWUSAGE;
2403         ast_cli(fd, FORMAT2, "Peer", "Username", "ID (Lo/Rem)", "Seq (Tx/Rx)", "Lag", "Jitter", "Format");
2404         for (x=0;x<AST_IAX2_MAX_CALLS;x++) {
2405                 ast_pthread_mutex_lock(&iaxsl[x]);
2406                 if (iaxs[x]) {
2407                         ast_cli(fd, FORMAT, inet_ntoa(iaxs[x]->addr.sin_addr), 
2408                                                 strlen(iaxs[x]->username) ? iaxs[x]->username : "(None)", 
2409                                                 iaxs[x]->callno, iaxs[x]->peercallno, 
2410                                                 iaxs[x]->oseqno, iaxs[x]->iseqno, 
2411                                                 iaxs[x]->lag,
2412                                                 iaxs[x]->jitter,
2413                                                 iaxs[x]->voiceformat);
2414                         numchans++;
2415                 }
2416                 ast_pthread_mutex_unlock(&iaxsl[x]);
2417         }
2418         ast_cli(fd, "%d active IAX channel(s)\n", numchans);
2419         return RESULT_SUCCESS;
2420 #undef FORMAT
2421 #undef FORMAT2
2422 }
2423
2424 static int iax2_do_debug(int fd, int argc, char *argv[])
2425 {
2426         if (argc != 2)
2427                 return RESULT_SHOWUSAGE;
2428         iaxdebug = 1;
2429         ast_cli(fd, "IAX2 Debugging Enabled\n");
2430         return RESULT_SUCCESS;
2431 }
2432
2433 static int iax2_no_debug(int fd, int argc, char *argv[])
2434 {
2435         if (argc != 3)
2436                 return RESULT_SHOWUSAGE;
2437         iaxdebug = 0;
2438         ast_cli(fd, "IAX2 Debugging Disabled\n");
2439         return RESULT_SUCCESS;
2440 }
2441
2442
2443
2444 static char show_users_usage[] = 
2445 "Usage: iax2 show users\n"
2446 "       Lists all users known to the IAX2 (Inter-Asterisk eXchange rev 2) subsystem.\n";
2447
2448 static char show_channels_usage[] = 
2449 "Usage: iax2 show channels\n"
2450 "       Lists all currently active IAX2 channels.\n";
2451
2452 static char show_peers_usage[] = 
2453 "Usage: iax2 show peers\n"
2454 "       Lists all known IAX peers.\n";
2455
2456 static char show_reg_usage[] =
2457 "Usage: iax2 show registry\n"
2458 "       Lists all registration requests and status.\n";
2459
2460 #ifdef DEBUG_SUPPORT
2461
2462 static char debug_usage[] = 
2463 "Usage: iax2 debug\n"
2464 "       Enables dumping of IAX2 packets for debugging purposes\n";
2465
2466 static char no_debug_usage[] = 
2467 "Usage: iax2 no debug\n"
2468 "       Disables dumping of IAX2 packets for debugging purposes\n";
2469
2470 #endif
2471
2472 static struct ast_cli_entry  cli_show_users = 
2473         { { "iax2", "show", "users", NULL }, iax2_show_users, "Show defined IAX2 users", show_users_usage };
2474 static struct ast_cli_entry  cli_show_channels =
2475         { { "iax2", "show", "channels", NULL }, iax2_show_channels, "Show active IAX2 channels", show_channels_usage };
2476 static struct ast_cli_entry  cli_show_peers =
2477         { { "iax2", "show", "peers", NULL }, iax2_show_peers, "Show defined IAX2 peers", show_peers_usage };
2478 static struct ast_cli_entry  cli_show_registry =
2479         { { "iax2", "show", "registry", NULL }, iax2_show_registry, "Show IAX2 registration status", show_reg_usage };
2480 static struct ast_cli_entry  cli_debug =
2481         { { "iax2", "debug", NULL }, iax2_do_debug, "Enable IAX2 debugging", debug_usage };
2482 static struct ast_cli_entry  cli_no_debug =
2483         { { "iax2", "no", "debug", NULL }, iax2_no_debug, "Disable IAX2 debugging", no_debug_usage };
2484
2485 static int iax2_write(struct ast_channel *c, struct ast_frame *f)
2486 {
2487         struct chan_iax2_pvt *i = c->pvt->pvt;
2488         if (!i)
2489                 return -1;
2490         /* If there's an outstanding error, return failure now */
2491         if (i->error) {
2492                 ast_log(LOG_DEBUG, "Write error: %s\n", strerror(errno));
2493                 return -1;
2494         }
2495         /* If it's already gone, just return */
2496         if (i->alreadygone)
2497                 return 0;
2498         /* Don't waste bandwidth sending null frames */
2499         if (f->frametype == AST_FRAME_NULL)
2500                 return 0;
2501         /* If we're quelching voice, don't bother sending it */
2502         if ((f->frametype == AST_FRAME_VOICE) && i->quelch)
2503                 return 0;
2504         /* Simple, just queue for transmission */
2505         return iax2_send(i, f, 0, -1, 0, 0, 0);
2506 }
2507
2508 static int __send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno, 
2509                 int now, int transfer, int final)
2510 {
2511         struct ast_frame f;
2512         f.frametype = type;
2513         f.subclass = command;
2514         f.datalen = datalen;
2515         f.samples = 0;
2516         f.mallocd = 0;
2517         f.offset = 0;
2518         f.src = __FUNCTION__;
2519         f.data = data;
2520         return iax2_send(i, &f, ts, seqno, now, transfer, final);
2521 }
2522
2523 static int send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2524 {
2525         return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 0);
2526 }
2527
2528 #ifdef BRIDGE_OPTIMIZATION
2529 static int forward_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2530 {
2531         return __send_command(iaxs[i->bridgecallno], type, command, ts, data, datalen, seqno, 0, 0, 0);
2532 }
2533 #endif
2534
2535 static int send_command_final(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2536 {
2537         /* It is assumed that the callno has already been locked */
2538         iax2_predestroy_nolock(i->callno);
2539         return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 1);
2540 }
2541
2542 static int send_command_immediate(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2543 {
2544         return __send_command(i, type, command, ts, data, datalen, seqno, 1, 0, 0);
2545 }
2546
2547 static int send_command_transfer(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen)
2548 {
2549         return __send_command(i, type, command, ts, data, datalen, 0, 0, 1, 0);
2550 }
2551
2552 static int apply_context(struct iax2_context *con, char *context)
2553 {
2554         while(con) {
2555                 if (!strcmp(con->context, context))
2556                         return -1;
2557                 con = con->next;
2558         }
2559         return 0;
2560 }
2561
2562
2563 static int check_access(int callno, struct sockaddr_in *sin, struct iax_ies *ies)
2564 {
2565         /* Start pessimistic */
2566         int res = -1;
2567         int version = 2;
2568         struct iax2_user *user;
2569         int gotcapability=0;
2570         if (!iaxs[callno])
2571                 return res;
2572         if (ies->called_number)
2573                 strncpy(iaxs[callno]->exten, ies->called_number, sizeof(iaxs[callno]->exten) - 1);
2574         if (ies->calling_number) {
2575                 if (ies->calling_name)
2576                         snprintf(iaxs[callno]->callerid, sizeof(iaxs[callno]->callerid), "\"%s\" <%s>", ies->calling_name, ies->calling_number);
2577                 else
2578                         strncpy(iaxs[callno]->callerid, ies->calling_number, sizeof(iaxs[callno]->callerid) - 1);
2579         } else if (ies->calling_name)
2580                 strncpy(iaxs[callno]->callerid, ies->calling_name, sizeof(iaxs[callno]->callerid) - 1);
2581         if (ies->calling_ani)
2582                 strncpy(iaxs[callno]->ani, ies->calling_ani, sizeof(iaxs[callno]->ani) - 1);
2583         if (ies->dnid)
2584                 strncpy(iaxs[callno]->dnid, ies->dnid, sizeof(iaxs[callno]->dnid)-1);
2585         if (ies->called_context)
2586                 strncpy(iaxs[callno]->context, ies->called_context, sizeof(iaxs[callno]->context)-1);
2587         if (ies->language)
2588                 strncpy(iaxs[callno]->language, ies->language, sizeof(iaxs[callno]->language)-1);
2589         if (ies->username)
2590                 strncpy(iaxs[callno]->username, ies->username, sizeof(iaxs[callno]->username)-1);
2591         if (ies->format)
2592                 iaxs[callno]->peerformat = ies->format;
2593         if (ies->adsicpe)
2594                 iaxs[callno]->peeradsicpe = ies->adsicpe;
2595         if (ies->capability) {
2596                 gotcapability = 1;
2597                 iaxs[callno]->peercapability = ies->capability;
2598         } 
2599         if (ies->version)
2600                 version = ies->version;
2601         if (!gotcapability) 
2602                 iaxs[callno]->peercapability = iaxs[callno]->peerformat;
2603         if (version > AST_IAX2_PROTO_VERSION) {
2604                 ast_log(LOG_WARNING, "Peer '%s' has too new a protocol version (%d) for me\n", 
2605                         inet_ntoa(sin->sin_addr), version);
2606                 return res;
2607         }
2608         ast_pthread_mutex_lock(&userl.lock);
2609         /* Search the userlist for a compatible entry, and fill in the rest */
2610         user = userl.users;
2611         while(user) {
2612                 if ((!strlen(iaxs[callno]->username) ||                         /* No username specified */
2613                         !strcmp(iaxs[callno]->username, user->name))    /* Or this username specified */
2614                         && ast_apply_ha(user->ha, sin)  /* Access is permitted from this IP */
2615                         && (!strlen(iaxs[callno]->context) ||                   /* No context specified */
2616                              apply_context(user->contexts, iaxs[callno]->context))) {                   /* Context is permitted */
2617                         /* We found our match (use the first) */
2618                         
2619                         /* Store the requested username if not specified */
2620                         if (!strlen(iaxs[callno]->username))
2621                                 strncpy(iaxs[callno]->username, user->name, sizeof(iaxs[callno]->username)-1);
2622                         /* And use the default context */
2623                         if (!strlen(iaxs[callno]->context)) {
2624                                 if (user->contexts)
2625                                         strncpy(iaxs[callno]->context, user->contexts->context, sizeof(iaxs[callno]->context)-1);
2626                                 else
2627                                         strncpy(iaxs[callno]->context, context, sizeof(iaxs[callno]->context)-1);
2628                         }
2629                         /* Copy the secret */
2630                         strncpy(iaxs[callno]->secret, user->secret, sizeof(iaxs[callno]->secret)-1);
2631                         /* And any input keys */
2632                         strncpy(iaxs[callno]->inkeys, user->inkeys, sizeof(iaxs[callno]->inkeys));
2633                         /* And the permitted authentication methods */
2634                         iaxs[callno]->authmethods = user->authmethods;
2635                         /* If they have callerid, override the given caller id.  Always store the ANI */
2636                         if (strlen(iaxs[callno]->callerid)) {
2637                                 if (user->hascallerid)
2638                                         strncpy(iaxs[callno]->callerid, user->callerid, sizeof(iaxs[callno]->callerid)-1);
2639                                 strncpy(iaxs[callno]->ani, user->callerid, sizeof(iaxs[callno]->ani)-1);
2640                         }
2641                         if (strlen(user->accountcode))
2642                                 strncpy(iaxs[callno]->accountcode, user->accountcode, sizeof(iaxs[callno]->accountcode)-1);
2643                         if (user->amaflags)
2644                                 iaxs[callno]->amaflags = user->amaflags;
2645                         res = 0;
2646                         break;
2647                 }
2648                 user = user->next;      
2649         }
2650         ast_pthread_mutex_unlock(&userl.lock);
2651         return res;
2652 }
2653
2654 static int raw_hangup(struct sockaddr_in *sin, unsigned short src, unsigned short dst)
2655 {
2656         struct ast_iax2_full_hdr fh;
2657         fh.scallno = htons(src | AST_FLAG_FULL);
2658         fh.dcallno = htons(dst);
2659         fh.ts = 0;
2660         fh.oseqno = 0;
2661         fh.iseqno = 0;
2662         fh.type = AST_FRAME_IAX;
2663         fh.csub = compress_subclass(AST_IAX2_COMMAND_INVAL);
2664 #if 0
2665         if (option_debug)
2666 #endif  
2667                 ast_log(LOG_DEBUG, "Raw Hangup %s:%d, src=%d, dst=%d\n",
2668                         inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), src, dst);
2669         return sendto(netsocket, &fh, sizeof(fh), 0, (struct sockaddr *)sin, sizeof(*sin));
2670 }
2671
2672 static int authenticate_request(struct chan_iax2_pvt *p)
2673 {
2674         struct iax_ie_data ied;
2675         memset(&ied, 0, sizeof(ied));
2676         iax_ie_append_short(&ied, IAX_IE_AUTHMETHODS, p->authmethods);
2677         if (p->authmethods & (IAX_AUTH_MD5 | IAX_AUTH_RSA)) {
2678                 snprintf(p->challenge, sizeof(p->challenge), "%d", rand());
2679                 iax_ie_append_str(&ied, IAX_IE_CHALLENGE, p->challenge);
2680         }
2681         iax_ie_append_str(&ied,IAX_IE_USERNAME, p->username);
2682         return send_command(p, AST_FRAME_IAX, AST_IAX2_COMMAND_AUTHREQ, 0, ied.buf, ied.pos, -1);
2683 }
2684
2685 static int authenticate_verify(struct chan_iax2_pvt *p, struct iax_ies *ies)
2686 {
2687         char requeststr[256] = "";
2688         char md5secret[256] = "";
2689         char secret[256] = "";
2690         char rsasecret[256] = "";
2691         int res = -1; 
2692         int x;
2693         
2694         if (!(p->state & IAX_STATE_AUTHENTICATED))
2695                 return res;
2696         if (ies->password)
2697                 strncpy(secret, ies->password, sizeof(secret) - 1);
2698         if (ies->md5_result)
2699                 strncpy(md5secret, ies->md5_result, sizeof(md5secret)-1);
2700         if (ies->rsa_result)
2701                 strncpy(rsasecret, ies->rsa_result, sizeof(rsasecret)-1);
2702         if ((p->authmethods & IAX_AUTH_RSA) && strlen(rsasecret) && strlen(p->inkeys)) {
2703                 struct ast_key *key;
2704                 char *keyn;
2705                 char tmpkey[256];
2706                 char *stringp=NULL;
2707                 strncpy(tmpkey, p->inkeys, sizeof(tmpkey));
2708                 stringp=tmpkey;
2709                 keyn = strsep(&stringp, ":");
2710                 while(keyn) {
2711                         key = ast_key_get(keyn, AST_KEY_PUBLIC);
2712                         if (key && !ast_check_signature(key, p->challenge, rsasecret)) {
2713                                 res = 0;
2714                                 break;
2715                         } else if (!key)
2716                                 ast_log(LOG_WARNING, "requested inkey '%s' for RSA authentication does not exist\n", keyn);
2717                         keyn = strsep(&stringp, ":");
2718                 }
2719         } else if (p->authmethods & IAX_AUTH_MD5) {
2720                 struct MD5Context md5;
2721                 unsigned char digest[16];
2722                 MD5Init(&md5);
2723                 MD5Update(&md5, p->challenge, strlen(p->challenge));
2724                 MD5Update(&md5, p->secret, strlen(p->secret));
2725                 MD5Final(digest, &md5);
2726                 /* If they support md5, authenticate with it.  */
2727                 for (x=0;x<16;x++)
2728                         sprintf(requeststr + (x << 1), "%2.2x", digest[x]);
2729                 if (!strcasecmp(requeststr, md5secret))
2730                         res = 0;
2731         } else if (p->authmethods & IAX_AUTH_PLAINTEXT) {
2732                 if (!strcmp(secret, p->secret))
2733                         res = 0;
2734         }
2735         return res;
2736 }
2737
2738 static int register_verify(int callno, struct sockaddr_in *sin, struct iax_ies *ies)
2739 {
2740         char requeststr[256] = "";
2741         char peer[256] = "";
2742         char md5secret[256] = "";
2743         char rsasecret[256] = "";
2744         char secret[256] = "";
2745         struct iax2_peer *p;
2746         struct ast_key *key;
2747         char *keyn;
2748         int x;
2749         int expire = 0;
2750
2751         iaxs[callno]->state &= ~IAX_STATE_AUTHENTICATED;
2752         strcpy(iaxs[callno]->peer, "");
2753         if (ies->username)
2754                 strncpy(peer, ies->username, sizeof(peer) - 1);
2755         if (ies->password)
2756                 strncpy(secret, ies->password, sizeof(secret) - 1);
2757         if (ies->md5_result)
2758                 strncpy(md5secret, ies->md5_result, sizeof(md5secret)-1);
2759         if (ies->rsa_result)
2760                 strncpy(rsasecret, ies->rsa_result, sizeof(rsasecret)-1);
2761         if (ies->refresh)
2762                 expire = ies->refresh;
2763
2764         if (!strlen(peer)) {
2765                 ast_log(LOG_NOTICE, "Empty registration from %s\n", inet_ntoa(sin->sin_addr));
2766                 return -1;
2767         }
2768
2769         for (p = peerl.peers; p ; p = p->next) 
2770                 if (!strcasecmp(p->name, peer))
2771                         break;
2772
2773         if (!p) {
2774                 ast_log(LOG_NOTICE, "No registration for peer '%s' (from %s)\n", peer, inet_ntoa(sin->sin_addr));
2775                 return -1;
2776         }
2777
2778         if (!p->dynamic) {
2779                 ast_log(LOG_NOTICE, "Peer '%s' is not dynamic (from %s)\n", peer, inet_ntoa(sin->sin_addr));
2780                 return -1;
2781         }
2782
2783         if (!ast_apply_ha(p->ha, sin)) {
2784                 ast_log(LOG_NOTICE, "Host %s denied access to register peer '%s'\n", inet_ntoa(sin->sin_addr), p->name);
2785                 return -1;
2786         }
2787         strncpy(iaxs[callno]->secret, p->secret, sizeof(iaxs[callno]->secret)-1);
2788         strncpy(iaxs[callno]->inkeys, p->inkeys, sizeof(iaxs[callno]->inkeys)-1);
2789         /* Check secret against what we have on file */
2790         if (strlen(rsasecret) && (p->authmethods & IAX_AUTH_RSA) && strlen(p->challenge)) {
2791                 if (strlen(p->inkeys)) {
2792                         char tmpkeys[256];
2793                         char *stringp=NULL;
2794                         strncpy(tmpkeys, p->inkeys, sizeof(tmpkeys));
2795                         stringp=tmpkeys;
2796                         keyn = strsep(&stringp, ":");
2797                         while(keyn) {
2798                                 key = ast_key_get(keyn, AST_KEY_PUBLIC);
2799                                 if (key && !ast_check_signature(key, p->challenge, rsasecret)) {
2800                                         iaxs[callno]->state |= IAX_STATE_AUTHENTICATED;
2801                                         break;
2802                                 } else if (!key) 
2803                                         ast_log(LOG_WARNING, "requested inkey '%s' does not exist\n", keyn);
2804                                 keyn = strsep(&stringp, ":");
2805                         }
2806                         if (!keyn) {
2807                                 ast_log(LOG_NOTICE, "Host %s failed RSA authentication with inkeys '%s'\n", peer, p->inkeys);
2808                                 return -1;
2809                         }
2810                 } else {
2811                         ast_log(LOG_NOTICE, "Host '%s' trying to do RSA authentication, but we have no inkeys\n", peer);
2812                         return -1;
2813                 }
2814         } else if (strlen(secret) && (p->authmethods & IAX_AUTH_PLAINTEXT)) {
2815                 /* They've provided a plain text password and we support that */
2816                 if (strcmp(secret, p->secret)) {
2817                         ast_log(LOG_NOTICE, "Host %s did not provide proper plaintext password for '%s'\n", inet_ntoa(sin->sin_addr), p->name);
2818                         return -1;
2819                 } else
2820                         iaxs[callno]->state |= IAX_STATE_AUTHENTICATED;
2821         } else if (strlen(md5secret) && (p->authmethods & IAX_AUTH_MD5) && strlen(p->challenge)) {
2822                 struct MD5Context md5;
2823                 unsigned char digest[16];
2824                 MD5Init(&md5);
2825                 MD5Update(&md5, p->challenge, strlen(p->challenge));
2826                 MD5Update(&md5, p->secret, strlen(p->secret));
2827                 MD5Final(digest, &md5);
2828                 for (x=0;x<16;x++)
2829                         sprintf(requeststr + (x << 1), "%2.2x", digest[x]);
2830                 if (strcasecmp(requeststr, md5secret)) {
2831                         ast_log(LOG_NOTICE, "Host %s failed MD5 authentication for '%s' (%s != %s)\n", inet_ntoa(sin->sin_addr), p->name, requeststr, md5secret);
2832                         return -1;
2833                 } else
2834                         iaxs[callno]->state |= IAX_STATE_AUTHENTICATED;
2835         } else if (strlen(md5secret) || strlen(secret)) {
2836                 ast_log(LOG_NOTICE, "Inappropriate authentication received\n");
2837                 return -1;
2838         }
2839         strncpy(iaxs[callno]->peer, peer, sizeof(iaxs[callno]->peer)-1);
2840         /* Choose lowest expirey number */
2841         if (expire && (expire < iaxs[callno]->expirey)) 
2842                 iaxs[callno]->expirey = expire;
2843         return 0;
2844         
2845 }
2846
2847 static int authenticate(char *challenge, char *secret, char *keyn, int authmethods, struct iax_ie_data *ied, struct sockaddr_in *sin)
2848 {
2849         int res = -1;
2850         int x;
2851         if (keyn && strlen(keyn)) {
2852                 if (!(authmethods & IAX_AUTH_RSA)) {
2853                         if (!secret || !strlen(secret)) 
2854                                 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));
2855                 } else if (!strlen(challenge)) {
2856                         ast_log(LOG_NOTICE, "No challenge provided for RSA authentication to %s\n", inet_ntoa(sin->sin_addr));
2857                 } else {
2858                         char sig[256];
2859                         struct ast_key *key;
2860                         key = ast_key_get(keyn, AST_KEY_PRIVATE);
2861                         if (!key) {
2862                                 ast_log(LOG_NOTICE, "Unable to find private key '%s'\n", keyn);
2863                         } else {
2864                                 if (ast_sign(key, challenge, sig)) {
2865                                         ast_log(LOG_NOTICE, "Unable to sign challenge withy key\n");
2866                                         res = -1;
2867                                 } else {
2868                                         iax_ie_append_str(ied, IAX_IE_RSA_RESULT, sig);
2869                                         res = 0;
2870                                 }
2871                         }
2872                 }
2873         } 
2874         /* Fall back */
2875         if (res && secret && strlen(secret)) {
2876                 if ((authmethods & IAX_AUTH_MD5) && strlen(challenge)) {
2877                         struct MD5Context md5;
2878                         unsigned char digest[16];
2879                         char digres[128] = "";
2880                         MD5Init(&md5);
2881                         MD5Update(&md5, challenge, strlen(challenge));
2882                         MD5Update(&md5, secret, strlen(secret));
2883                         MD5Final(digest, &md5);
2884                         /* If they support md5, authenticate with it.  */
2885                         for (x=0;x<16;x++)
2886                                 sprintf(digres + (x << 1),  "%2.2x", digest[x]);
2887                         iax_ie_append_str(ied, IAX_IE_MD5_RESULT, digres);
2888                         res = 0;
2889                 } else if (authmethods & IAX_AUTH_PLAINTEXT) {
2890                         iax_ie_append_str(ied, IAX_IE_PASSWORD, secret);
2891                         res = 0;
2892                 } else
2893                         ast_log(LOG_NOTICE, "No way to send secret to peer '%s' (their methods: %d)\n", inet_ntoa(sin->sin_addr), authmethods);
2894         }
2895         return res;
2896 }
2897
2898 static int authenticate_reply(struct chan_iax2_pvt *p, struct sockaddr_in *sin, struct iax_ies *ies, char *override, char *okey)
2899 {
2900         struct iax2_peer *peer;
2901         /* Start pessimistic */
2902         int res = -1;
2903         int authmethods = 0;
2904         struct iax_ie_data ied;
2905         
2906         memset(&ied, 0, sizeof(ied));
2907         
2908         if (ies->username)
2909                 strncpy(p->username, ies->username, sizeof(p->username) - 1);
2910         if (ies->challenge)
2911                 strncpy(p->challenge, ies->challenge, sizeof(p->challenge)-1);
2912         if (ies->authmethods)
2913                 authmethods = ies->authmethods;
2914
2915         /* Check for override RSA authentication first */
2916         if ((override && strlen(override)) || (okey && strlen(okey))) {
2917                 /* Normal password authentication */
2918                 res = authenticate(p->challenge, override, okey, authmethods, &ied, sin);
2919         } else {
2920                 ast_pthread_mutex_lock(&peerl.lock);
2921                 peer = peerl.peers;
2922                 while(peer) {
2923                         if ((!strlen(p->peer) || !strcmp(p->peer, peer->name)) 
2924                                                                 /* No peer specified at our end, or this is the peer */
2925                          && (!strlen(peer->username) || (!strcmp(peer->username, p->username)))
2926                                                                 /* No username specified in peer rule, or this is the right username */
2927                          && (!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)))
2928                                                                 /* No specified host, or this is our host */
2929                         ) {
2930                                 res = authenticate(p->challenge, peer->secret, peer->outkey, authmethods, &ied, sin);
2931                                 if (!res)
2932                                         break;  
2933                         }
2934                         peer = peer->next;
2935                 }
2936                 ast_pthread_mutex_unlock(&peerl.lock);
2937         }
2938         if (!res)
2939                 res = send_command(p, AST_FRAME_IAX, AST_IAX2_COMMAND_AUTHREP, 0, ied.buf, ied.pos, -1);
2940         return res;
2941 }
2942
2943 static int iax2_do_register(struct iax2_registry *reg);
2944
2945 static int iax2_do_register_s(void *data)
2946 {
2947         struct iax2_registry *reg = data;
2948         reg->expire = -1;
2949         iax2_do_register(reg);
2950         return 0;
2951 }
2952
2953 static int try_transfer(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
2954 {
2955         int newcall = 0;
2956         char newip[256] = "";
2957         
2958         struct sockaddr_in new;
2959         
2960         if (ies->apparent_addr)
2961                 memcpy(&new, ies->apparent_addr, sizeof(new));
2962         if (ies->callno)
2963                 newcall = ies->callno;
2964         if (!newcall || !new.sin_addr.s_addr || !new.sin_port) {
2965                 ast_log(LOG_WARNING, "Invalid transfer request\n");
2966                 return -1;
2967         }
2968         pvt->transfercallno = newcall;
2969         memcpy(&pvt->transfer, &new, sizeof(pvt->transfer));
2970         inet_aton(newip, &pvt->transfer.sin_addr);
2971         pvt->transfer.sin_family = AF_INET;
2972         pvt->transferring = TRANSFER_BEGIN;
2973         send_command_transfer(pvt, AST_FRAME_IAX, AST_IAX2_COMMAND_TXCNT, 0, NULL, 0);
2974         return 0; 
2975 }
2976
2977 static int complete_dpreply(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
2978 {
2979         char exten[256] = "";
2980         int status = CACHE_FLAG_UNKNOWN;
2981         int expirey = iaxdefaultdpcache;
2982         int x;
2983         int matchmore = 0;
2984         struct iax2_dpcache *dp, *prev;
2985         
2986         if (ies->called_number)
2987                 strncpy(exten, ies->called_number, sizeof(exten)-1);
2988
2989         if (ies->dpstatus & IAX_DPSTATUS_EXISTS)
2990                 status = CACHE_FLAG_EXISTS;
2991         else if (ies->dpstatus & IAX_DPSTATUS_CANEXIST)
2992                 status = CACHE_FLAG_CANEXIST;
2993         else if (ies->dpstatus & IAX_DPSTATUS_NONEXISTANT)
2994                 status = CACHE_FLAG_NONEXISTANT;
2995
2996         if (ies->dpstatus & IAX_DPSTATUS_IGNOREPAT) {
2997                 /* Don't really do anything with this */
2998         }
2999         if (ies->refresh)
3000                 expirey = ies->refresh;
3001         if (ies->dpstatus & IAX_DPSTATUS_MATCHMORE)
3002                 matchmore = CACHE_FLAG_MATCHMORE;
3003         ast_pthread_mutex_lock(&dpcache_lock);
3004         prev = NULL;
3005         dp = pvt->dpentries;
3006         while(dp) {
3007                 if (!strcmp(dp->exten, exten)) {
3008                         /* Let them go */
3009                         if (prev)
3010                                 prev->peer = dp->peer;
3011                         else
3012                                 pvt->dpentries = dp->peer;
3013                         dp->peer = NULL;
3014                         dp->callno = 0;
3015                         dp->expirey.tv_sec = dp->orig.tv_sec + expirey;
3016                         if (dp->flags & CACHE_FLAG_PENDING) {
3017                                 dp->flags &= ~CACHE_FLAG_PENDING;
3018                                 dp->flags |= status;
3019                                 dp->flags |= CACHE_FLAG_MATCHMORE;
3020                         }
3021                         /* Wake up waiters */
3022                         for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
3023                                 if (dp->waiters[x] > -1)
3024                                         write(dp->waiters[x], "asdf", 4);
3025                 }
3026                 prev = dp;
3027                 dp = dp->peer;
3028         }
3029         ast_pthread_mutex_unlock(&dpcache_lock);
3030         return 0;
3031 }
3032
3033 static int complete_transfer(int callno, struct iax_ies *ies)
3034 {
3035         int peercallno = 0;
3036         struct chan_iax2_pvt *pvt = iaxs[callno];
3037         struct ast_iax2_frame *cur;
3038
3039         if (ies->callno)
3040                 peercallno = ies->callno;
3041
3042         if (peercallno < 1) {
3043                 ast_log(LOG_WARNING, "Invalid transfer request\n");
3044                 return -1;
3045         }
3046         memcpy(&pvt->addr, &pvt->transfer, sizeof(pvt->addr));
3047         memset(&pvt->transfer, 0, sizeof(pvt->transfer));
3048         /* Reset sequence numbers */
3049         pvt->oseqno = 0;
3050         pvt->iseqno = 0;
3051         pvt->peercallno = peercallno;
3052         pvt->transferring = TRANSFER_NONE;
3053         pvt->svoiceformat = -1;
3054         pvt->voiceformat = 0;
3055         pvt->transfercallno = -1;
3056         memset(&pvt->rxcore, 0, sizeof(pvt->rxcore));
3057         memset(&pvt->offset, 0, sizeof(pvt->offset));
3058         memset(&pvt->history, 0, sizeof(pvt->history));
3059         pvt->jitterbuffer = 0;
3060         pvt->jitter = 0;
3061         pvt->historicjitter = 0;
3062         pvt->lag = 0;
3063         pvt->last = 0;
3064         pvt->lastsent = 0;
3065         pvt->pingtime = DEFAULT_RETRY_TIME;
3066         ast_pthread_mutex_lock(&iaxq.lock);
3067         for (cur = iaxq.head; cur ; cur = cur->next) {
3068                 /* We must cancel any packets that would have been transmitted
3069                    because now we're talking to someone new.  It's okay, they
3070                    were transmitted to someone that didn't care anyway. */
3071                 if (callno == cur->callno) 
3072                         cur->retries = -1;
3073         }
3074         ast_pthread_mutex_unlock(&iaxq.lock);
3075         return 0; 
3076 }
3077
3078 static int iax2_ack_registry(struct iax_ies