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