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