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