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