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