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