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