77982305c0d0a08660fb6720b8d492493a71e6df
[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                 time_t nowtime;
1840                 name = alloca(strlen(peer) * 2 + 1);
1841                 time(&nowtime);
1842                 mysql_real_escape_string(mysql, name, peer, strlen(peer));
1843                 snprintf(query, sizeof(query), "UPDATE iaxfriends SET ipaddr=\"%s\", port=\"%d\", regseconds=\"%ld\" WHERE name=\"%s\"", 
1844                         ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr), ntohs(sin->sin_port), nowtime, name);
1845                 ast_mutex_lock(&mysqllock);
1846                 if (mysql_real_query(mysql, query, strlen(query))) 
1847                         ast_log(LOG_WARNING, "Unable to update database\n");
1848                         
1849                 ast_mutex_unlock(&mysqllock);
1850         }
1851 }
1852
1853 static struct iax2_peer *mysql_peer(char *peer)
1854 {
1855         struct iax2_peer *p;
1856         int success = 0;
1857         
1858         p = malloc(sizeof(struct iax2_peer));
1859         memset(p, 0, sizeof(struct iax2_peer));
1860         if (mysql && (strlen(peer) < 128)) {
1861                 char query[512];
1862                 char *name;
1863                 int numfields, x;
1864                 int port;
1865                 time_t regseconds, nowtime;
1866                 MYSQL_RES *result;
1867                 MYSQL_FIELD *fields;
1868                 MYSQL_ROW rowval;
1869                 name = alloca(strlen(peer) * 2 + 1);
1870                 mysql_real_escape_string(mysql, name, peer, strlen(peer));
1871                 snprintf(query, sizeof(query), "SELECT name, secret, context, ipaddr, port, regseconds FROM iaxfriends WHERE name=\"%s\"", name);
1872                 ast_mutex_lock(&mysqllock);
1873                 mysql_query(mysql, query);
1874                 if ((result = mysql_store_result(mysql))) {
1875                         if ((rowval = mysql_fetch_row(result))) {
1876                                 numfields = mysql_num_fields(result);
1877                                 fields = mysql_fetch_fields(result);
1878                                 success = 1;
1879                                 for (x=0;x<numfields;x++) {
1880                                         if (rowval[x]) {
1881                                                 if (!strcasecmp(fields[x].name, "secret")) {
1882                                                         strncpy(p->secret, rowval[x], sizeof(p->secret));
1883                                                 } else if (!strcasecmp(fields[x].name, "context")) {
1884                                                         strncpy(p->context, rowval[x], sizeof(p->context) - 1);
1885                                                 } else if (!strcasecmp(fields[x].name, "ipaddr")) {
1886                                                         inet_aton(rowval[x], &p->addr.sin_addr);
1887                                                 } else if (!strcasecmp(fields[x].name, "port")) {
1888                                                         if (sscanf(rowval[x], "%i", &port) != 1)
1889                                                                 port = 0;
1890                                                         p->addr.sin_port = htons(port);
1891                                                 } else if (!strcasecmp(fields[x].name, "regseconds")) {
1892                                                         if (sscanf(rowval[x], "%li", &regseconds) != 1)
1893                                                                 regseconds = 0;
1894                                                 }
1895                                         }
1896                                 }
1897                                 time(&nowtime);
1898                                 if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE) 
1899                                         memset(&p->addr, 0, sizeof(p->addr));
1900                         }
1901                         mysql_free_result(result);
1902                         result = NULL;
1903                 }
1904                 ast_mutex_unlock(&mysqllock);
1905         }
1906         if (!success) {
1907                 free(p);
1908                 p = NULL;
1909         } else {
1910                 strncpy(p->name, peer, sizeof(p->name) - 1);
1911                 p->dynamic = 1;
1912                 p->temponly = 1;
1913                 p->expire = -1;
1914                 p->capability = iax2_capability;
1915                 p->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
1916         }
1917         return p;
1918 }
1919 static struct iax2_user *mysql_user(char *user)
1920 {
1921         struct iax2_user *p;
1922         struct iax2_context *con;
1923         int success = 0;
1924         
1925         p = malloc(sizeof(struct iax2_user));
1926         memset(p, 0, sizeof(struct iax2_user));
1927         con = malloc(sizeof(struct iax2_context));
1928         memset(con, 0, sizeof(struct iax2_context));
1929         strcpy(con->context, "default");
1930         p->contexts = con;
1931         if (mysql && (strlen(user) < 128)) {
1932                 char query[512];
1933                 char *name;
1934                 int numfields, x;
1935                 MYSQL_RES *result;
1936                 MYSQL_FIELD *fields;
1937                 MYSQL_ROW rowval;
1938                 name = alloca(strlen(user) * 2 + 1);
1939                 mysql_real_escape_string(mysql, name, user, strlen(user));
1940                 snprintf(query, sizeof(query), "SELECT name, secret, context, ipaddr, port, regseconds, accountcode FROM iaxfriends WHERE name=\"%s\"", name);
1941                 ast_mutex_lock(&mysqllock);
1942                 mysql_query(mysql, query);
1943                 if ((result = mysql_store_result(mysql))) {
1944                         if ((rowval = mysql_fetch_row(result))) {
1945                                 numfields = mysql_num_fields(result);
1946                                 fields = mysql_fetch_fields(result);
1947                                 success = 1;
1948                                 for (x=0;x<numfields;x++) {
1949                                         if (rowval[x]) {
1950                                                 if (!strcasecmp(fields[x].name, "secret")) {
1951                                                         strncpy(p->secret, rowval[x], sizeof(p->secret));
1952                                                 } else if (!strcasecmp(fields[x].name, "context")) {
1953                                                         strncpy(p->contexts->context, rowval[x], sizeof(p->contexts->context) - 1);
1954                                                 } else if (!strcasecmp(fields[x].name, "accountcode")) {
1955                                                         strncpy(p->accountcode, rowval[x], sizeof(p->accountcode));
1956                                                 }
1957                                         }
1958                                 }
1959                         }
1960                         mysql_free_result(result);
1961                         result = NULL;
1962                 }
1963                 ast_mutex_unlock(&mysqllock);
1964         }
1965         if (!success) {
1966                 if (p->contexts)
1967                         free(p->contexts);
1968                 free(p);
1969                 p = NULL;
1970         } else {
1971                 strncpy(p->name, user, sizeof(p->name) - 1);
1972                 p->temponly = 1;
1973                 p->capability = iax2_capability;
1974                 p->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
1975         }
1976         return p;
1977 }
1978 #endif /* MYSQL_FRIENDS */
1979
1980 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)
1981 {
1982         struct ast_hostent ahp; struct hostent *hp;
1983         struct iax2_peer *p;
1984         int found=0;
1985         if (sendani)
1986                 *sendani = 0;
1987         if (maxtime)
1988                 *maxtime = 0;
1989         if (trunk)
1990                 *trunk = 0;
1991         sin->sin_family = AF_INET;
1992         ast_mutex_lock(&peerl.lock);
1993         p = peerl.peers;
1994         while(p) {
1995                 if (!strcasecmp(p->name, peer)) {
1996                         break;
1997                 }
1998                 p = p->next;
1999         }
2000         ast_mutex_unlock(&peerl.lock);
2001 #ifdef MYSQL_FRIENDS
2002         if (!p)
2003                 p = mysql_peer(peer);
2004 #endif          
2005         if (p) {
2006                 found++;
2007                 if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
2008                         (!p->maxms || ((p->lastms > 0)  && (p->lastms <= p->maxms)))) {
2009                         if (sendani)
2010                                 *sendani = p->sendani;          /* Whether we transmit ANI */
2011                         if (maxtime)
2012                                 *maxtime = p->maxms;            /* Max time they should take */
2013                         if (context)
2014                                 strncpy(context, p->context, AST_MAX_EXTENSION - 1);
2015                         if (peercontext)
2016                                 strncpy(peercontext, p->peercontext, AST_MAX_EXTENSION - 1);
2017                         if (trunk)
2018                                 *trunk = p->trunk;
2019                         if (capability)
2020                                 *capability = p->capability;
2021                         if (secret)
2022                                 strncpy(secret, p->secret, seclen);
2023                         if (p->addr.sin_addr.s_addr) {
2024                                 sin->sin_addr = p->addr.sin_addr;
2025                                 sin->sin_port = p->addr.sin_port;
2026                         } else {
2027                                 sin->sin_addr = p->defaddr.sin_addr;
2028                                 sin->sin_port = p->defaddr.sin_port;
2029                         }
2030                         if (notransfer)
2031                                 *notransfer=p->notransfer;
2032                 } else {
2033                         if (p->temponly)
2034                                 free(p);
2035                         p = NULL;
2036                 }
2037         }
2038         if (ofound)
2039                 *ofound = found;
2040         if (!p && !found) {
2041                 hp = ast_gethostbyname(peer, &ahp);
2042                 if (hp) {
2043                         memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
2044                         sin->sin_port = htons(IAX_DEFAULT_PORTNO);
2045                         return 0;
2046                 } else {
2047                         ast_log(LOG_WARNING, "No such host: %s\n", peer);
2048                         return -1;
2049                 }
2050         } else if (!p)
2051                 return -1;
2052         if (p->temponly)
2053                 free(p);
2054         return 0;
2055 }
2056
2057 static int auto_congest(void *nothing)
2058 {
2059         int callno = PTR_TO_CALLNO(nothing);
2060         struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_CONGESTION };
2061         ast_mutex_lock(&iaxsl[callno]);
2062         if (iaxs[callno]) {
2063                 iaxs[callno]->initid = -1;
2064                 iax2_queue_frame(callno, &f);
2065                 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
2066         }
2067         ast_mutex_unlock(&iaxsl[callno]);
2068         return 0;
2069 }
2070
2071 static unsigned int iax2_datetime(void)
2072 {
2073         time_t t;
2074         struct tm tm;
2075         unsigned int tmp;
2076         time(&t);
2077         localtime_r(&t, &tm);
2078         tmp  = (tm.tm_sec >> 1) & 0x1f;   /* 5 bits of seconds */
2079         tmp |= (tm.tm_min & 0x3f) << 5;   /* 6 bits of minutes */
2080         tmp |= (tm.tm_hour & 0x1f) << 11;   /* 5 bits of hours */
2081         tmp |= (tm.tm_mday & 0x1f) << 16; /* 5 bits of day of month */
2082         tmp |= ((tm.tm_mon + 1) & 0xf) << 21; /* 4 bits of month */
2083         tmp |= ((tm.tm_year - 100) & 0x7f) << 25; /* 7 bits of year */
2084         return tmp;
2085 }
2086
2087 static int iax2_call(struct ast_channel *c, char *dest, int timeout)
2088 {
2089         struct sockaddr_in sin;
2090         char host[256];
2091         char *rdest;
2092         char *rcontext;
2093         char *username;
2094         char *secret = NULL;
2095         char *hname;
2096         char cid[256] = "";
2097         char *l=NULL, *n=NULL;
2098         struct iax_ie_data ied;
2099         char myrdest [5] = "s";
2100         char context[AST_MAX_EXTENSION] ="";
2101         char peercontext[AST_MAX_EXTENSION] ="";
2102         char *portno = NULL;
2103         char *opts = "";
2104         unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
2105         char *stringp=NULL;
2106         char storedsecret[80];
2107         if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
2108                 ast_log(LOG_WARNING, "Line is already in use (%s)?\n", c->name);
2109                 return -1;
2110         }
2111         strncpy(host, dest, sizeof(host)-1);
2112         stringp=host;
2113         strsep(&stringp, "/");
2114         /* If no destination extension specified, use 's' */
2115         rdest = strsep(&stringp, "/");
2116         if (!rdest) 
2117                 rdest = myrdest;
2118         else {
2119                 /* Check for trailing options */
2120                 opts = strsep(&stringp, "/");
2121                 if (!opts)
2122                         opts = "";
2123         }
2124         stringp=rdest;
2125         strsep(&stringp, "@");
2126         rcontext = strsep(&stringp, "@");
2127         stringp=host;
2128         strsep(&stringp, "@");
2129         username = strsep(&stringp, "@");
2130         if (username) {
2131                 /* Really the second argument is the host, not the username */
2132                 hname = username;
2133                 username = host;
2134         } else {
2135                 hname = host;
2136         }
2137         if (username) {
2138                 stringp=username;
2139                 username = strsep(&stringp, ":");
2140                 secret = strsep(&stringp, ":");
2141         }
2142         stringp=hname;
2143         if (strsep(&stringp, ":")) {
2144                 stringp=hname;
2145                 strsep(&stringp, ":");
2146                 portno = strsep(&stringp, ":");
2147         }
2148         if (create_addr(&sin, NULL, NULL, NULL, hname, context, NULL, NULL, storedsecret, sizeof(storedsecret) - 1, NULL, peercontext)) {
2149                 ast_log(LOG_WARNING, "No address associated with '%s'\n", hname);
2150                 return -1;
2151         }
2152         /* Keep track of the context for outgoing calls too */
2153         strncpy(c->context, context, sizeof(c->context) - 1);
2154         if (portno) {
2155                 sin.sin_port = htons(atoi(portno));
2156         }
2157         if (c->callerid) {
2158                 strncpy(cid, c->callerid, sizeof(cid) - 1);
2159                 ast_callerid_parse(cid, &n, &l);
2160                 if (l)
2161                         ast_shrink_phone_number(l);
2162         }
2163         /* Now build request */ 
2164         memset(&ied, 0, sizeof(ied));
2165         /* On new call, first IE MUST be IAX version of caller */
2166         iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
2167         iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, rdest);
2168         if (strchr(opts, 'a')) {
2169                 /* Request auto answer */
2170                 iax_ie_append(&ied, IAX_IE_AUTOANSWER);
2171         }
2172         if (l)
2173                 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
2174         if (n)
2175                 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n);
2176         if (iaxs[callno]->sendani && c->ani) {
2177                 l = n = NULL;
2178                 strncpy(cid, c->ani, sizeof(cid) - 1);
2179                 ast_callerid_parse(cid, &n, &l);
2180                 if (l) {
2181                         ast_shrink_phone_number(l);
2182                         iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, l);
2183                 }
2184         }
2185         if (c->language && !ast_strlen_zero(c->language))
2186                 iax_ie_append_str(&ied, IAX_IE_LANGUAGE, c->language);
2187         if (c->dnid && !ast_strlen_zero(c->dnid))
2188                 iax_ie_append_str(&ied, IAX_IE_DNID, c->dnid);
2189         if (rcontext)
2190                 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, rcontext);
2191         else if (strlen(peercontext))
2192                 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, peercontext);
2193         if (username)
2194                 iax_ie_append_str(&ied, IAX_IE_USERNAME, username);
2195         if (!secret && !ast_strlen_zero(storedsecret))
2196                 secret = storedsecret;
2197         ast_mutex_lock(&iaxsl[callno]);
2198         if (!ast_strlen_zero(c->context))
2199                 strncpy(iaxs[callno]->context, c->context, sizeof(iaxs[callno]->context));
2200         if (secret) {
2201                 if (secret[0] == '[') {
2202                         /* This is an RSA key, not a normal secret */
2203                         strncpy(iaxs[callno]->outkey, secret + 1, sizeof(iaxs[callno]->secret)-1);
2204                         if (!ast_strlen_zero(iaxs[callno]->outkey)) {
2205                                 iaxs[callno]->outkey[strlen(iaxs[callno]->outkey) - 1] = '\0';
2206                         }
2207                 } else
2208                         strncpy(iaxs[callno]->secret, secret, sizeof(iaxs[callno]->secret)-1);
2209         }
2210         iax_ie_append_int(&ied, IAX_IE_FORMAT, c->nativeformats);
2211         iax_ie_append_int(&ied, IAX_IE_CAPABILITY, iaxs[callno]->capability);
2212         iax_ie_append_short(&ied, IAX_IE_ADSICPE, c->adsicpe);
2213         iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime());
2214         /* Transmit the string in a "NEW" request */
2215 #if 0
2216         /* XXX We have no equivalent XXX */
2217         if (option_verbose > 2)
2218                 ast_verbose(VERBOSE_PREFIX_3 "Calling using options '%s'\n", requeststr);
2219 #endif          
2220         if (iaxs[callno]->maxtime) {
2221                 /* Initialize pingtime and auto-congest time */
2222                 iaxs[callno]->pingtime = iaxs[callno]->maxtime / 2;
2223                 iaxs[callno]->initid = ast_sched_add(sched, iaxs[callno]->maxtime * 2, auto_congest, CALLNO_TO_PTR(callno));
2224         }
2225         send_command(iaxs[callno], AST_FRAME_IAX,
2226                 IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
2227         ast_mutex_unlock(&iaxsl[callno]);
2228         ast_setstate(c, AST_STATE_RINGING);
2229         return 0;
2230 }
2231
2232 static int iax2_hangup(struct ast_channel *c) 
2233 {
2234         unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
2235         int alreadygone;
2236         ast_mutex_lock(&iaxsl[callno]);
2237         if (callno && iaxs[callno]) {
2238                 ast_log(LOG_DEBUG, "We're hanging up %s now...\n", c->name);
2239                 alreadygone = iaxs[callno]->alreadygone;
2240                 /* Send the hangup unless we have had a transmission error or are already gone */
2241                 if (!iaxs[callno]->error && !alreadygone) 
2242                         send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, NULL, 0, -1);
2243                 /* Explicitly predestroy it */
2244                 iax2_predestroy_nolock(callno);
2245                 /* If we were already gone to begin with, destroy us now */
2246                 if (alreadygone) {
2247                         ast_log(LOG_DEBUG, "Really destroying %s now...\n", c->name);
2248                         iax2_destroy_nolock(callno);
2249                 }
2250         }
2251         ast_mutex_unlock(&iaxsl[callno]);
2252         if (option_verbose > 2) 
2253                 ast_verbose(VERBOSE_PREFIX_3 "Hungup '%s'\n", c->name);
2254         return 0;
2255 }
2256
2257 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
2258 {
2259         struct ast_option_header *h;
2260         int res;
2261         h = malloc(datalen + sizeof(struct ast_option_header));
2262         if (h) {
2263                 h->flag = AST_OPTION_FLAG_REQUEST;
2264                 h->option = htons(option);
2265                 memcpy(h->data, data, datalen);
2266                 res = send_command_locked(PTR_TO_CALLNO(c->pvt->pvt), AST_FRAME_CONTROL,
2267                         AST_CONTROL_OPTION, 0, (char *)h, datalen + sizeof(struct ast_option_header), -1);
2268                 free(h);
2269                 return res;
2270         } else 
2271                 ast_log(LOG_WARNING, "Out of memory\n");
2272         return -1;
2273 }
2274
2275 static struct ast_frame *iax2_read(struct ast_channel *c) 
2276 {
2277         static struct ast_frame f = { AST_FRAME_NULL, };
2278         ast_log(LOG_NOTICE, "I should never be called!\n");
2279         return &f;
2280 }
2281
2282 static int iax2_start_transfer(unsigned short callno0, unsigned short callno1)
2283 {
2284         int res;
2285         struct iax_ie_data ied0;
2286         struct iax_ie_data ied1;
2287         unsigned int transferid = rand();
2288         memset(&ied0, 0, sizeof(ied0));
2289         iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &iaxs[callno1]->addr);
2290         iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[callno1]->peercallno);
2291         iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, transferid);
2292
2293         memset(&ied1, 0, sizeof(ied1));
2294         iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &iaxs[callno0]->addr);
2295         iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[callno0]->peercallno);
2296         iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, transferid);
2297         
2298         res = send_command(iaxs[callno0], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
2299         if (res)
2300                 return -1;
2301         res = send_command(iaxs[callno1], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
2302         if (res)
2303                 return -1;
2304         iaxs[callno0]->transferring = TRANSFER_BEGIN;
2305         iaxs[callno1]->transferring = TRANSFER_BEGIN;
2306         return 0;
2307 }
2308
2309 static void lock_both(unsigned short callno0, unsigned short callno1)
2310 {
2311         ast_mutex_lock(&iaxsl[callno0]);
2312         while (ast_mutex_trylock(&iaxsl[callno1])) {
2313                 ast_mutex_unlock(&iaxsl[callno0]);
2314                 usleep(10);
2315                 ast_mutex_lock(&iaxsl[callno0]);
2316         }
2317 }
2318
2319 static void unlock_both(unsigned short callno0, unsigned short callno1)
2320 {
2321         ast_mutex_unlock(&iaxsl[callno1]);
2322         ast_mutex_unlock(&iaxsl[callno0]);
2323 }
2324
2325 static int iax2_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
2326 {
2327         struct ast_channel *cs[3];
2328         struct ast_channel *who;
2329         int to = -1;
2330         int res = -1;
2331         int transferstarted=0;
2332         struct ast_frame *f;
2333         unsigned short callno0 = PTR_TO_CALLNO(c0->pvt->pvt);
2334         unsigned short callno1 = PTR_TO_CALLNO(c1->pvt->pvt);
2335         struct timeval waittimer = {0, 0}, tv;
2336         
2337         lock_both(callno0, callno1);
2338         /* Put them in native bridge mode */
2339         iaxs[callno0]->bridgecallno = callno1;
2340         iaxs[callno1]->bridgecallno = callno0;
2341         unlock_both(callno0, callno1);
2342
2343         /* If not, try to bridge until we can execute a transfer, if we can */
2344         cs[0] = c0;
2345         cs[1] = c1;
2346         for (/* ever */;;) {
2347                 /* Check in case we got masqueraded into */
2348                 if ((c0->type != type) || (c1->type != type)) {
2349                         if (option_verbose > 2)
2350                                 ast_verbose(VERBOSE_PREFIX_3 "Can't masquerade, we're different...\n");
2351                         /* Remove from native mode */
2352                         if (c0->type == type) {
2353                                 ast_mutex_lock(&iaxsl[callno0]);
2354                                 iaxs[callno0]->bridgecallno = 0;
2355                                 ast_mutex_unlock(&iaxsl[callno0]);
2356                         }
2357                         if (c1->type == type) {
2358                                 ast_mutex_lock(&iaxsl[callno1]);
2359                                 iaxs[callno1]->bridgecallno = 0;
2360                                 ast_mutex_unlock(&iaxsl[callno1]);
2361                         }
2362                         return -2;
2363                 }
2364                 if (c0->nativeformats != c1->nativeformats) {
2365                         ast_verbose(VERBOSE_PREFIX_3 "Operating with different codecs, can't native bridge...\n");
2366                         /* Remove from native mode */
2367                         lock_both(callno0, callno1);
2368                         iaxs[callno0]->bridgecallno = 0;
2369                         iaxs[callno1]->bridgecallno = 0;
2370                         unlock_both(callno0, callno1);
2371                         return -2;
2372                 }
2373                 /* check if transfered and if we really want native bridging */
2374                 if (!transferstarted && !iaxs[callno0]->notransfer && !iaxs[callno1]->notransfer) {
2375                         /* Try the transfer */
2376                         if (iax2_start_transfer(callno0, callno1))
2377                                 ast_log(LOG_WARNING, "Unable to start the transfer\n");
2378                         transferstarted = 1;
2379                 }
2380                 if ((iaxs[callno0]->transferring == TRANSFER_RELEASED) && (iaxs[callno1]->transferring == TRANSFER_RELEASED)) {
2381                         /* Call has been transferred.  We're no longer involved */
2382                         gettimeofday(&tv, NULL);
2383                         if (!waittimer.tv_sec && !waittimer.tv_usec) {
2384                                 waittimer.tv_sec = tv.tv_sec;
2385                                 waittimer.tv_usec = tv.tv_usec;
2386                         } else if (tv.tv_sec - waittimer.tv_sec > IAX_LINGER_TIMEOUT) {
2387                                 c0->_softhangup |= AST_SOFTHANGUP_DEV;
2388                                 c1->_softhangup |= AST_SOFTHANGUP_DEV;
2389                                 *fo = NULL;
2390                                 *rc = c0;
2391                                 res = 0;
2392                                 break;
2393                         }
2394                 }
2395                 to = 1000;
2396                 who = ast_waitfor_n(cs, 2, &to);
2397                 if (!who) {
2398                         if (ast_check_hangup(c0) || ast_check_hangup(c1)) {
2399                                 res = -1;
2400                                 break;
2401                         }
2402                         continue;
2403                 }
2404                 f = ast_read(who);
2405                 if (!f) {
2406                         *fo = NULL;
2407                         *rc = who;
2408                         res = 0;
2409                         break;
2410                 }
2411                 if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
2412                         *fo = f;
2413                         *rc = who;
2414                         res =  0;
2415                         break;
2416                 }
2417                 if ((f->frametype == AST_FRAME_VOICE) ||
2418                         (f->frametype == AST_FRAME_TEXT) ||
2419                         (f->frametype == AST_FRAME_VIDEO) || 
2420                         (f->frametype == AST_FRAME_IMAGE) ||
2421                         (f->frametype == AST_FRAME_DTMF)) {
2422                         if ((f->frametype == AST_FRAME_DTMF) && 
2423                                 (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
2424                                 if ((who == c0)) {
2425                                         if  ((flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
2426                                                 *rc = c0;
2427                                                 *fo = f;
2428                                                 /* Take out of conference mode */
2429                                                 res = 0;
2430                                                 /* Remove from native mode */
2431                                                 break;
2432                                         } else 
2433                                                 goto tackygoto;
2434                                 } else
2435                                 if ((who == c1)) {
2436                                         if (flags & AST_BRIDGE_DTMF_CHANNEL_1) {
2437                                                 *rc = c1;
2438                                                 *fo = f;
2439                                                 res =  0;
2440                                                 /* Remove from native mode */
2441                                                 break;
2442                                         } else
2443                                                 goto tackygoto;
2444                                 }
2445                         } else {
2446 #if 0
2447                                 ast_log(LOG_DEBUG, "Read from %s\n", who->name);
2448                                 if (who == last) 
2449                                         ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
2450                                 last = who;
2451 #endif
2452 tackygoto:
2453                                 if (who == c0) 
2454                                         ast_write(c1, f);
2455                                 else 
2456                                         ast_write(c0, f);
2457                         }
2458                         ast_frfree(f);
2459                 } else
2460                         ast_frfree(f);
2461                 /* Swap who gets priority */
2462                 cs[2] = cs[0];
2463                 cs[0] = cs[1];
2464                 cs[1] = cs[2];
2465         }
2466         lock_both(callno0, callno1);
2467         iaxs[callno0]->bridgecallno = 0;
2468         iaxs[callno1]->bridgecallno = 0;
2469         unlock_both(callno0, callno1);
2470         return res;
2471 }
2472
2473 static int iax2_answer(struct ast_channel *c)
2474 {
2475         unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
2476         if (option_debug)
2477                 ast_log(LOG_DEBUG, "Answering\n");
2478         return send_command_locked(callno, AST_FRAME_CONTROL, AST_CONTROL_ANSWER, 0, NULL, 0, -1);
2479 }
2480
2481 static int iax2_indicate(struct ast_channel *c, int condition)
2482 {
2483         unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
2484         if (option_debug)
2485                 ast_log(LOG_DEBUG, "Indicating condition %d\n", condition);
2486         return send_command_locked(callno, AST_FRAME_CONTROL, condition, 0, NULL, 0, -1);
2487 }
2488         
2489 static int iax2_transfer(struct ast_channel *c, char *dest)
2490 {
2491         unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
2492         struct iax_ie_data ied;
2493         char tmp[256] = "", *context;
2494         strncpy(tmp, dest, sizeof(tmp) - 1);
2495         context = strchr(tmp, '@');
2496         if (context) {
2497                 *context = '\0';
2498                 context++;
2499         }
2500         memset(&ied, 0, sizeof(ied));
2501         iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, tmp);
2502         if (context)
2503                 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, context);
2504         if (option_debug)
2505                 ast_log(LOG_DEBUG, "Transferring '%s' to '%s'\n", c->name, dest);
2506         return send_command_locked(callno, AST_FRAME_IAX, IAX_COMMAND_TRANSFER, 0, ied.buf, ied.pos, -1);
2507 }
2508         
2509
2510 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
2511
2512 static int iax2_getpeertrunk(struct sockaddr_in sin)
2513 {
2514         struct iax2_peer *peer;
2515         int res = 0;
2516         ast_mutex_lock(&peerl.lock);
2517         peer = peerl.peers;
2518         while(peer) {
2519                 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
2520                                 (peer->addr.sin_port == sin.sin_port)) {
2521                                         res = peer->trunk;
2522                                         break;
2523                 }
2524                 peer = peer->next;
2525         }
2526         ast_mutex_unlock(&peerl.lock);
2527         return res;
2528 }
2529
2530 static struct ast_channel *ast_iax2_new(int callno, int state, int capability)
2531 {
2532         struct ast_channel *tmp;
2533         struct chan_iax2_pvt *i;
2534         /* Don't hold call lock */
2535         ast_mutex_unlock(&iaxsl[callno]);
2536         tmp = ast_channel_alloc(1);
2537         ast_mutex_lock(&iaxsl[callno]);
2538         i = iaxs[callno];
2539         if (i && tmp) {
2540                 if (!ast_strlen_zero(i->username))
2541                         snprintf(tmp->name, sizeof(tmp->name), "IAX2[%s@%s]/%d", i->username, i->host, i->callno);
2542                 else
2543                         snprintf(tmp->name, sizeof(tmp->name), "IAX2[%s]/%d", i->host, i->callno);
2544                 tmp->type = type;
2545                 /* We can support any format by default, until we get restricted */
2546                 tmp->nativeformats = capability;
2547                 tmp->readformat = 0;
2548                 tmp->writeformat = 0;
2549                 tmp->pvt->pvt = CALLNO_TO_PTR(i->callno);
2550                 tmp->pvt->send_digit = iax2_digit;
2551                 tmp->pvt->send_text = iax2_sendtext;
2552                 tmp->pvt->send_image = iax2_sendimage;
2553                 tmp->pvt->send_html = iax2_sendhtml;
2554                 tmp->pvt->call = iax2_call;
2555                 tmp->pvt->hangup = iax2_hangup;
2556                 tmp->pvt->answer = iax2_answer;
2557                 tmp->pvt->read = iax2_read;
2558                 tmp->pvt->write = iax2_write;
2559                 tmp->pvt->write_video = iax2_write;
2560                 tmp->pvt->indicate = iax2_indicate;
2561                 tmp->pvt->setoption = iax2_setoption;
2562                 tmp->pvt->bridge = iax2_bridge;
2563                 tmp->pvt->transfer = iax2_transfer;
2564                 if (!ast_strlen_zero(i->callerid))
2565                         tmp->callerid = strdup(i->callerid);
2566                 if (!ast_strlen_zero(i->ani))
2567                         tmp->ani = strdup(i->ani);
2568                 if (!ast_strlen_zero(i->language))
2569                         strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
2570                 if (!ast_strlen_zero(i->dnid))
2571                         tmp->dnid = strdup(i->dnid);
2572                 if (!ast_strlen_zero(i->accountcode))
2573                         strncpy(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode)-1);
2574                 if (i->amaflags)
2575                         tmp->amaflags = i->amaflags;
2576                 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
2577                 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
2578                 tmp->adsicpe = i->peeradsicpe;
2579                 tmp->pvt->fixup = iax2_fixup;
2580                 i->owner = tmp;
2581                 i->capability = capability;
2582                 ast_setstate(tmp, state);
2583                 ast_mutex_lock(&usecnt_lock);
2584                 usecnt++;
2585                 ast_mutex_unlock(&usecnt_lock);
2586                 ast_update_use_count();
2587                 if (state != AST_STATE_DOWN) {
2588                         if (ast_pbx_start(tmp)) {
2589                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
2590                                 ast_hangup(tmp);
2591                                 tmp = NULL;
2592                         }
2593                 }
2594         }
2595         return tmp;
2596 }
2597
2598 static unsigned int calc_txpeerstamp(struct iax2_trunk_peer *tpeer, int sampms, struct timeval *tv)
2599 {
2600         unsigned long int mssincetx; /* unsigned to handle overflows */
2601         long int ms, pred;
2602
2603         tpeer->trunkact = *tv;
2604         mssincetx = (tv->tv_sec - tpeer->lasttxtime.tv_sec) * 1000 +
2605                         (1000000 + tv->tv_usec - tpeer->lasttxtime.tv_usec) / 1000 - 1000;
2606         if (mssincetx > 5000 || (!tpeer->txtrunktime.tv_sec && !tpeer->txtrunktime.tv_usec)) {
2607                 /* If it's been at least 5 seconds since the last time we transmitted on this trunk, reset our timers */
2608                 tpeer->txtrunktime.tv_sec = tv->tv_sec;
2609                 tpeer->txtrunktime.tv_usec = tv->tv_usec;
2610                 tpeer->lastsent = 999999;
2611         }
2612         /* Update last transmit time now */
2613         tpeer->lasttxtime.tv_sec = tv->tv_sec;
2614         tpeer->lasttxtime.tv_usec = tv->tv_usec;
2615         
2616         /* Calculate ms offset */
2617         ms = (tv->tv_sec - tpeer->txtrunktime.tv_sec) * 1000 +
2618                 (1000000 + tv->tv_usec - tpeer->txtrunktime.tv_usec) / 1000 - 1000;
2619         /* Predict from last value */
2620         pred = tpeer->lastsent + sampms;
2621         if (abs(ms - pred) < MAX_TIMESTAMP_SKEW)
2622                 ms = pred;
2623         
2624         /* We never send the same timestamp twice, so fudge a little if we must */
2625         if (ms == tpeer->lastsent)
2626                 ms = tpeer->lastsent + 1;
2627         tpeer->lastsent = ms;
2628         return ms;
2629 }
2630
2631 static unsigned int fix_peerts(struct timeval *tv, int callno, unsigned int ts)
2632 {
2633         long ms;        /* NOT unsigned */
2634         if (!iaxs[callno]->rxcore.tv_sec && !iaxs[callno]->rxcore.tv_usec) {
2635                 /* Initialize rxcore time if appropriate */
2636                 gettimeofday(&iaxs[callno]->rxcore, NULL);
2637                 /* Round to nearest 20ms so traces look pretty */
2638                 iaxs[callno]->rxcore.tv_usec -= iaxs[callno]->rxcore.tv_usec % 20000;
2639         }
2640         /* Calculate difference between trunk and channel */
2641         ms = (tv->tv_sec - iaxs[callno]->rxcore.tv_sec) * 1000 + 
2642                 (1000000 + tv->tv_usec - iaxs[callno]->rxcore.tv_usec) / 1000 - 1000;
2643         /* Return as the sum of trunk time and the difference between trunk and real time */
2644         return ms + ts;
2645 }
2646
2647 static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts, struct ast_frame *f)
2648 {
2649         struct timeval tv;
2650         int ms;
2651         int voice = 0;
2652         int genuine = 0;
2653         struct timeval *delivery = NULL;
2654
2655         /* What sort of frame do we have?: voice is self-explanatory
2656            "genuine" means an IAX frame - things like LAGRQ/RP, PING/PONG, ACK
2657            non-genuine frames are CONTROL frames [ringing etc], DTMF
2658            The "genuine" distinction is needed because genuine frames must get a clock-based timestamp,
2659            the others need a timestamp slaved to the voice frames so that they go in sequence
2660         */
2661         if (f) {
2662                 if (f->frametype == AST_FRAME_VOICE) {
2663                         voice = 1;
2664                         delivery = &f->delivery;
2665                 } else if (f->frametype == AST_FRAME_IAX) {
2666                         genuine = 1;
2667                 }
2668         }
2669         if (!p->offset.tv_sec && !p->offset.tv_usec) {
2670                 gettimeofday(&p->offset, NULL);
2671                 /* Round to nearest 20ms for nice looking traces */
2672                 p->offset.tv_usec -= p->offset.tv_usec % 20000;
2673         }
2674         /* If the timestamp is specified, just send it as is */
2675         if (ts)
2676                 return ts;
2677         /* If we have a time that the frame arrived, always use it to make our timestamp */
2678         if (delivery && (delivery->tv_sec || delivery->tv_usec)) {
2679                 ms = (delivery->tv_sec - p->offset.tv_sec) * 1000 +
2680                         (1000000 + delivery->tv_usec - p->offset.tv_usec) / 1000 - 1000;
2681         } else {
2682                 gettimeofday(&tv, NULL);
2683                 ms = (tv.tv_sec - p->offset.tv_sec) * 1000 +
2684                         (1000000 + tv.tv_usec - p->offset.tv_usec) / 1000 - 1000;
2685                 if (ms < 0)
2686                         ms = 0;
2687                 if (voice) {
2688                         /* On a voice frame, use predicted values if appropriate */
2689                         if (abs(ms - p->nextpred) <= MAX_TIMESTAMP_SKEW) {
2690                                 if (!p->nextpred) {
2691                                         p->nextpred = ms; /*f->samples / 8;*/
2692                                         if (p->nextpred <= p->lastsent)
2693                                                 p->nextpred = p->lastsent + 3;
2694                                 }
2695                                 ms = p->nextpred;
2696                         } else
2697                                 p->nextpred = ms;
2698                 } else {
2699                         /* On a dataframe, use last value + 3 (to accomodate jitter buffer shrinking) if appropriate unless
2700                            it's a genuine frame */
2701                         if (genuine) {
2702                                 /* genuine (IAX LAGRQ etc) must keep their clock-based stamps */
2703                                 if (ms <= p->lastsent)
2704                                         ms = p->lastsent + 3;
2705                         } else if (abs(ms - p->lastsent) <= MAX_TIMESTAMP_SKEW) {
2706                                 /* non-genuine frames (!?) (DTMF, CONTROL) should be pulled into the predicted stream stamps */
2707                                 ms = p->lastsent + 3;
2708                         }
2709                 }
2710         }
2711         p->lastsent = ms;
2712         if (voice)
2713                 p->nextpred = p->nextpred + f->samples / 8;
2714 #if 0
2715         printf("TS: %s - %dms\n", voice ? "Audio" : "Control", ms);
2716 #endif  
2717         return ms;
2718 }
2719
2720 #ifdef BRIDGE_OPTIMIZATION
2721 static unsigned int calc_fakestamp(struct chan_iax2_pvt *p1, struct chan_iax2_pvt *p2, unsigned int fakets)
2722 {
2723         int ms;
2724         /* Receive from p1, send to p2 */
2725         
2726         /* Setup rxcore if necessary on outgoing channel */
2727         if (!p1->rxcore.tv_sec && !p1->rxcore.tv_usec)
2728                 gettimeofday(&p1->rxcore, NULL);
2729
2730         /* Setup txcore if necessary on outgoing channel */
2731         if (!p2->offset.tv_sec && !p2->offset.tv_usec)
2732                 gettimeofday(&p2->offset, NULL);
2733         
2734         /* Now, ts is the timestamp of the original packet in the orignal context.
2735            Adding rxcore to it gives us when we would want the packet to be delivered normally.
2736            Subtracting txcore of the outgoing channel gives us what we'd expect */
2737         
2738         ms = (p1->rxcore.tv_sec - p2->offset.tv_sec) * 1000 +
2739                 (1000000 + p1->rxcore.tv_usec - p2->offset.tv_usec) / 1000 - 1000;
2740         fakets += ms;
2741         if (fakets <= p2->lastsent)
2742                 fakets = p2->lastsent + 1;
2743         p2->lastsent = fakets;
2744         return fakets;
2745 }
2746 #endif
2747
2748 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p)
2749 {
2750         /* Returns where in "receive time" we are */
2751         struct timeval tv;
2752         int ms;
2753         /* Setup rxcore if necessary */
2754         if (!p->rxcore.tv_sec && !p->rxcore.tv_usec)
2755                 gettimeofday(&p->rxcore, NULL);
2756
2757         gettimeofday(&tv, NULL);
2758         ms = (tv.tv_sec - p->rxcore.tv_sec) * 1000 +
2759                 (1000000 + tv.tv_usec - p->rxcore.tv_usec) / 1000 - 1000;
2760         return ms;
2761 }
2762
2763 static struct iax2_trunk_peer *find_tpeer(struct sockaddr_in *sin)
2764 {
2765         struct iax2_trunk_peer *tpeer;
2766         char iabuf[80];
2767         /* Finds and locks trunk peer */
2768         ast_mutex_lock(&tpeerlock);
2769         tpeer = tpeers;
2770         while(tpeer) {
2771                 /* We don't lock here because tpeer->addr *never* changes */
2772                 if (!inaddrcmp(&tpeer->addr, sin)) {
2773                         ast_mutex_lock(&tpeer->lock);
2774                         break;
2775                 }
2776                 tpeer = tpeer->next;
2777         }
2778         if (!tpeer) {
2779                 tpeer = malloc(sizeof(struct iax2_trunk_peer));
2780                 if (tpeer) {
2781                         memset(tpeer, 0, sizeof(struct iax2_trunk_peer));
2782                         ast_mutex_init(&tpeer->lock);
2783                         tpeer->lastsent = 9999;
2784                         memcpy(&tpeer->addr, sin, sizeof(tpeer->addr));
2785                         gettimeofday(&tpeer->trunkact, NULL);
2786                         ast_mutex_lock(&tpeer->lock);
2787                         tpeer->next = tpeers;
2788                         tpeers = tpeer;
2789                         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));
2790                 }
2791         }
2792         ast_mutex_unlock(&tpeerlock);
2793         return tpeer;
2794 }
2795
2796 static int iax2_trunk_queue(struct chan_iax2_pvt *pvt, struct ast_frame *f)
2797 {
2798         struct iax2_trunk_peer *tpeer;
2799         void *tmp, *ptr;
2800         struct ast_iax2_meta_trunk_entry *met;
2801         char iabuf[80];
2802         tpeer = find_tpeer(&pvt->addr);
2803         if (tpeer) {
2804                 if (tpeer->trunkdatalen + f->datalen + 4 >= tpeer->trunkdataalloc) {
2805                         /* Need to reallocate space */
2806                         if (tpeer->trunkdataalloc < MAX_TRUNKDATA) {
2807                                 tmp = realloc(tpeer->trunkdata, tpeer->trunkdataalloc + DEFAULT_TRUNKDATA + IAX2_TRUNK_PREFACE);
2808                                 if (tmp) {
2809                                         tpeer->trunkdataalloc += DEFAULT_TRUNKDATA;
2810                                         tpeer->trunkdata = tmp;
2811                                         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);
2812                                 } else {
2813                                         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));
2814                                         ast_mutex_unlock(&tpeer->lock);
2815                                         return -1;
2816                                 }
2817                         } else {
2818                                 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));
2819                                 ast_mutex_unlock(&tpeer->lock);
2820                                 return -1;
2821                         }
2822                 }
2823                 
2824                 /* Append to meta frame */
2825                 ptr = tpeer->trunkdata + IAX2_TRUNK_PREFACE + tpeer->trunkdatalen;
2826                 met = (struct ast_iax2_meta_trunk_entry *)ptr;
2827                 /* Store call number and length in meta header */
2828                 met->callno = htons(pvt->callno);
2829                 met->len = htons(f->datalen);
2830                 /* Advance pointers/decrease length past trunk entry header */
2831                 ptr += sizeof(struct ast_iax2_meta_trunk_entry);
2832                 tpeer->trunkdatalen += sizeof(struct ast_iax2_meta_trunk_entry);
2833                 /* Copy actual trunk data */
2834                 memcpy(ptr, f->data, f->datalen);
2835                 tpeer->trunkdatalen += f->datalen;
2836                 tpeer->calls++;
2837                 ast_mutex_unlock(&tpeer->lock);
2838         }
2839         return 0;
2840 }
2841
2842 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final)
2843 {
2844         /* Queue a packet for delivery on a given private structure.  Use "ts" for
2845            timestamp, or calculate if ts is 0.  Send immediately without retransmission
2846            or delayed, with retransmission */
2847         struct ast_iax2_full_hdr *fh;
2848         struct ast_iax2_mini_hdr *mh;
2849         struct ast_iax2_video_hdr *vh;
2850         struct {
2851                 struct iax_frame fr2;
2852                 unsigned char buffer[4096];
2853         } frb;
2854         struct iax_frame *fr;
2855         int res;
2856         int sendmini=0;
2857         unsigned int lastsent;
2858         unsigned int fts;
2859                 
2860         if (!pvt) {
2861                 ast_log(LOG_WARNING, "No private structure for packet?\n");
2862                 return -1;
2863         }
2864         
2865         lastsent = pvt->lastsent;
2866
2867         /* Calculate actual timestamp */
2868         fts = calc_timestamp(pvt, ts, f);
2869
2870         if ((pvt->trunk || ((fts & 0xFFFF0000L) == (lastsent & 0xFFFF0000L)))
2871                 /* High two bits are the same on timestamp, or sending on a trunk */ &&
2872             (f->frametype == AST_FRAME_VOICE) 
2873                 /* is a voice frame */ &&
2874                 (f->subclass == pvt->svoiceformat) 
2875                 /* is the same type */ ) {
2876                         /* Force immediate rather than delayed transmission */
2877                         now = 1;
2878                         /* Mark that mini-style frame is appropriate */
2879                         sendmini = 1;
2880         }
2881         if (((fts & 0xFFFF8000L) == (lastsent & 0xFFFF8000L)) && 
2882                 (f->frametype == AST_FRAME_VIDEO) &&
2883                 ((f->subclass & ~0x1) == pvt->svideoformat)) {
2884                         now = 1;
2885                         sendmini = 1;
2886         }
2887         /* Allocate an iax_frame */
2888         if (now) {
2889                 fr = &frb.fr2;
2890         } else
2891                 fr = iax_frame_new(DIRECTION_OUTGRESS, f->datalen);
2892         if (!fr) {
2893                 ast_log(LOG_WARNING, "Out of memory\n");
2894                 return -1;
2895         }
2896         /* Copy our prospective frame into our immediate or retransmitted wrapper */
2897         iax_frame_wrap(fr, f);
2898
2899         fr->ts = fts;
2900         fr->callno = pvt->callno;
2901         fr->transfer = transfer;
2902         fr->final = final;
2903         if (!sendmini) {
2904                 /* We need a full frame */
2905                 if (seqno > -1)
2906                         fr->oseqno = seqno;
2907                 else
2908                         fr->oseqno = pvt->oseqno++;
2909                 fr->iseqno = pvt->iseqno;
2910                 fh = (struct ast_iax2_full_hdr *)(fr->af.data - sizeof(struct ast_iax2_full_hdr));
2911                 fh->scallno = htons(fr->callno | IAX_FLAG_FULL);
2912                 fh->ts = htonl(fr->ts);
2913                 fh->oseqno = fr->oseqno;
2914                 if (transfer) {
2915                         fh->iseqno = 0;
2916                 } else
2917                         fh->iseqno = fr->iseqno;
2918                 /* Keep track of the last thing we've acknowledged */
2919                 if (!transfer)
2920                         pvt->aseqno = fr->iseqno;
2921                 fh->type = fr->af.frametype & 0xFF;
2922                 if (fr->af.frametype == AST_FRAME_VIDEO)
2923                         fh->csub = compress_subclass(fr->af.subclass & ~0x1) | ((fr->af.subclass & 0x1) << 6);
2924                 else
2925                         fh->csub = compress_subclass(fr->af.subclass);
2926                 if (transfer) {
2927                         fr->dcallno = pvt->transfercallno;
2928                 } else
2929                         fr->dcallno = pvt->peercallno;
2930                 fh->dcallno = htons(fr->dcallno);
2931                 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_full_hdr);
2932                 fr->data = fh;
2933                 fr->retries = 0;
2934                 /* Retry after 2x the ping time has passed */
2935                 fr->retrytime = pvt->pingtime * 2;
2936                 if (fr->retrytime < MIN_RETRY_TIME)
2937                         fr->retrytime = MIN_RETRY_TIME;
2938                 if (fr->retrytime > MAX_RETRY_TIME)
2939                         fr->retrytime = MAX_RETRY_TIME;
2940                 /* Acks' don't get retried */
2941                 if ((f->frametype == AST_FRAME_IAX) && (f->subclass == IAX_COMMAND_ACK))
2942                         fr->retries = -1;
2943                 else if (f->frametype == AST_FRAME_VOICE)
2944                         pvt->svoiceformat = f->subclass;
2945                 else if (f->frametype == AST_FRAME_VIDEO)
2946                         pvt->svideoformat = f->subclass & ~0x1;
2947                 if (now) {
2948                         res = send_packet(fr);
2949                 } else
2950                         res = iax2_transmit(fr);
2951         } else {
2952                 if (pvt->trunk) {
2953                         iax2_trunk_queue(pvt, &fr->af);
2954                         res = 0;
2955                 } else if (fr->af.frametype == AST_FRAME_VIDEO) {
2956                         /* Video frame have no sequence number */
2957                         fr->oseqno = -1;
2958                         fr->iseqno = -1;
2959                         vh = (struct ast_iax2_video_hdr *)(fr->af.data - sizeof(struct ast_iax2_video_hdr));
2960                         vh->zeros = 0;
2961                         vh->callno = htons(0x8000 | fr->callno);
2962                         vh->ts = htons((fr->ts & 0x7FFF) | (fr->af.subclass & 0x1 ? 0x8000 : 0));
2963                         fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_video_hdr);
2964                         fr->data = vh;
2965                         fr->retries = -1;
2966                         res = send_packet(fr);                  
2967                 } else {
2968                         /* Mini-frames have no sequence number */
2969                         fr->oseqno = -1;
2970                         fr->iseqno = -1;
2971                         /* Mini frame will do */
2972                         mh = (struct ast_iax2_mini_hdr *)(fr->af.data - sizeof(struct ast_iax2_mini_hdr));
2973                         mh->callno = htons(fr->callno);
2974                         mh->ts = htons(fr->ts & 0xFFFF);
2975                         fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_mini_hdr);
2976                         fr->data = mh;
2977                         fr->retries = -1;
2978                         res = send_packet(fr);
2979                 }
2980         }
2981         return res;
2982 }
2983
2984
2985
2986 static int iax2_show_users(int fd, int argc, char *argv[])
2987 {
2988 #define FORMAT "%-15.15s  %-20.20s  %-15.15s  %-15.15s  %-5.5s\n"
2989 #define FORMAT2 "%-15.15s  %-20.20s  %-15.15d  %-15.15s  %-5.5s\n"
2990         struct iax2_user *user;
2991         char auth[90];
2992         if (argc != 3) 
2993                 return RESULT_SHOWUSAGE;
2994         ast_mutex_lock(&userl.lock);
2995         ast_cli(fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C");
2996         for(user=userl.users;user;user=user->next) {
2997                 if (!ast_strlen_zero(user->secret)) {
2998                         strncpy(auth,user->secret,sizeof(auth)-1);
2999                 } else if (!ast_strlen_zero(user->inkeys)) {
3000                         sprintf(auth,"Key: %-15.15s ",user->inkeys);
3001                 } else
3002                         strcpy(auth,"-no secret-");
3003                 ast_cli(fd, FORMAT2, user->name, auth, user->authmethods, 
3004                                 user->contexts ? user->contexts->context : context,
3005                                 user->ha ? "Yes" : "No");
3006         }
3007         ast_mutex_unlock(&userl.lock);
3008         return RESULT_SUCCESS;
3009 #undef FORMAT
3010 #undef FORMAT2
3011 }
3012
3013 static int iax2_show_peers(int fd, int argc, char *argv[])
3014 {
3015 #define FORMAT2 "%-15.15s  %-15.15s %s  %-15.15s  %-8s  %-10s\n"
3016 #define FORMAT "%-15.15s  %-15.15s %s  %-15.15s  %-5d%s  %-10s\n"
3017         struct iax2_peer *peer;
3018         char name[256] = "";
3019         char iabuf[80];
3020         int registeredonly=0;
3021         if ((argc != 3) && (argc != 4) && (argc != 5))
3022                 return RESULT_SHOWUSAGE;
3023         if ((argc == 4)) {
3024                 if (!strcasecmp(argv[3], "registered")) {
3025                         registeredonly = 1;
3026                 } else
3027                         return RESULT_SHOWUSAGE;
3028         }
3029         ast_mutex_lock(&peerl.lock);
3030         ast_cli(fd, FORMAT2, "Name/Username", "Host", "   ", "Mask", "Port", "Status");
3031         for (peer = peerl.peers;peer;peer = peer->next) {
3032                 char nm[20];
3033                 char status[20];
3034                 int print_line = -1;
3035                 char srch[2000];
3036                 if (registeredonly && !peer->addr.sin_addr.s_addr)
3037                         continue;
3038                 if (!ast_strlen_zero(peer->username))
3039                         snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
3040                 else
3041                         strncpy(name, peer->name, sizeof(name) - 1);
3042                 if (peer->maxms) {
3043                         if (peer->lastms < 0)
3044                                 strcpy(status, "UNREACHABLE");
3045                         else if (peer->lastms > peer->maxms) 
3046                                 snprintf(status, sizeof(status), "LAGGED (%d ms)", peer->lastms);
3047                         else if (peer->lastms) 
3048                                 snprintf(status, sizeof(status), "OK (%d ms)", peer->lastms);
3049                         else 
3050                                 strcpy(status, "UNKNOWN");
3051                 } else 
3052                         strcpy(status, "Unmonitored");
3053                 strncpy(nm, ast_inet_ntoa(iabuf, sizeof(iabuf), peer->mask), sizeof(nm)-1);
3054
3055                 sprintf(srch, FORMAT, name, 
3056                                         peer->addr.sin_addr.s_addr ? ast_inet_ntoa(iabuf, sizeof(iabuf), peer->addr.sin_addr) : "(Unspecified)",
3057                                         peer->dynamic ? "(D)" : "(S)",
3058                                         nm,
3059                                         ntohs(peer->addr.sin_port), peer->trunk ? "(T)" : "   ", status);
3060
3061                 if (argc == 5) {
3062                   if (!strcasecmp(argv[3],"include") && strstr(srch,argv[4])) {
3063                         print_line = -1;
3064                    } else if (!strcasecmp(argv[3],"exclude") && !strstr(srch,argv[4])) {
3065                         print_line = 1;
3066                    } else if (!strcasecmp(argv[3],"begin") && !strncasecmp(srch,argv[4],strlen(argv[4]))) {
3067                         print_line = -1;
3068                    } else {
3069                         print_line = 0;
3070                   }
3071                 }
3072                 
3073                 if (print_line) {
3074                 ast_cli(fd, FORMAT, name, 
3075                                         peer->addr.sin_addr.s_addr ? ast_inet_ntoa(iabuf, sizeof(iabuf), peer->addr.sin_addr) : "(Unspecified)",
3076                                         peer->dynamic ? "(D)" : "(S)",
3077                                         nm,
3078                                         ntohs(peer->addr.sin_port), peer->trunk ? "(T)" : "   ", status);
3079                 }
3080         }
3081         ast_mutex_unlock(&peerl.lock);
3082         return RESULT_SUCCESS;
3083 #undef FORMAT
3084 #undef FORMAT2
3085 }
3086
3087 static int iax2_show_firmware(int fd, int argc, char *argv[])
3088 {
3089 #define FORMAT2 "%-15.15s  %-15.15s %-15.15s\n"
3090 #define FORMAT "%-15.15s  %-15d %-15d\n"
3091         struct iax_firmware *cur;
3092         if ((argc != 3) && (argc != 4))
3093                 return RESULT_SHOWUSAGE;
3094         ast_mutex_lock(&waresl.lock);
3095         
3096         ast_cli(fd, FORMAT2, "Device", "Version", "Size");
3097         for (cur = waresl.wares;cur;cur = cur->next) {
3098                 if ((argc == 3) || (!strcasecmp(argv[3], cur->fwh->devname))) 
3099                         ast_cli(fd, FORMAT, cur->fwh->devname, ntohs(cur->fwh->version),
3100                                                 ntohl(cur->fwh->datalen));
3101         }
3102         ast_mutex_unlock(&waresl.lock);
3103         return RESULT_SUCCESS;
3104 #undef FORMAT
3105 #undef FORMAT2
3106 }
3107
3108 /* JDG: callback to display iax peers in manager */
3109 static int manager_iax2_show_peers( struct mansession *s, struct message *m )
3110 {
3111         char *a[] = { "iax2", "show", "users" };
3112         int ret;
3113         ret = iax2_show_peers( s->fd, 3, a );
3114         ast_cli( s->fd, "\r\n" );
3115         return ret;
3116 } /* /JDG */
3117
3118 static char *regstate2str(int regstate)
3119 {
3120         switch(regstate) {
3121         case REG_STATE_UNREGISTERED:
3122                 return "Unregistered";
3123         case REG_STATE_REGSENT:
3124                 return "Request Sent";
3125         case REG_STATE_AUTHSENT:
3126                 return "Auth. Sent";
3127         case REG_STATE_REGISTERED:
3128                 return "Registered";
3129         case REG_STATE_REJECTED:
3130                 return "Rejected";
3131         case REG_STATE_TIMEOUT:
3132                 return "Timeout";
3133         case REG_STATE_NOAUTH:
3134                 return "No Authentication";
3135         default:
3136                 return "Unknown";
3137         }
3138 }
3139
3140 static int iax2_show_registry(int fd, int argc, char *argv[])
3141 {
3142 #define FORMAT2 "%-20.20s  %-10.10s  %-20.20s %8.8s  %s\n"
3143 #define FORMAT "%-20.20s  %-10.10s  %-20.20s %8d  %s\n"
3144         struct iax2_registry *reg;
3145         char host[80];
3146         char perceived[80];
3147         char iabuf[80];
3148         if (argc != 3)
3149                 return RESULT_SHOWUSAGE;
3150         ast_mutex_lock(&peerl.lock);
3151         ast_cli(fd, FORMAT2, "Host", "Username", "Perceived", "Refresh", "State");
3152         for (reg = registrations;reg;reg = reg->next) {
3153                 snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(iabuf, sizeof(iabuf), reg->addr.sin_addr), ntohs(reg->addr.sin_port));
3154                 if (reg->us.sin_addr.s_addr) 
3155                         snprintf(perceived, sizeof(perceived), "%s:%d", ast_inet_ntoa(iabuf, sizeof(iabuf), reg->us.sin_addr), ntohs(reg->us.sin_port));
3156                 else
3157                         strcpy(perceived, "<Unregistered>");
3158                 ast_cli(fd, FORMAT, host, 
3159                                         reg->username, perceived, reg->refresh, regstate2str(reg->regstate));
3160         }
3161         ast_mutex_unlock(&peerl.lock);
3162         return RESULT_SUCCESS;
3163 #undef FORMAT
3164 #undef FORMAT2
3165 }
3166
3167 static int jitterbufsize(struct chan_iax2_pvt *pvt) {
3168         int min, i;
3169         min = 99999999;
3170         for (i=0; i<MEMORY_SIZE; i++) {
3171                 if (pvt->history[i] < min)
3172                         min = pvt->history[i];
3173         }
3174         return pvt->jitterbuffer - min;
3175 }
3176
3177 static int iax2_show_channels(int fd, int argc, char *argv[])
3178 {
3179 #define FORMAT2 "%-15.15s  %-10.10s  %-11.11s  %-11.11s  %-7.7s  %-6.6s  %-6.6s  %s\n"
3180 #define FORMAT  "%-15.15s  %-10.10s  %5.5d/%5.5d  %5.5d/%5.5d  %-5.5dms  %-4.4dms  %-4.4dms  %-6.6s\n"
3181         int x;
3182         int numchans = 0;
3183         char iabuf[80];
3184         if (argc != 3)
3185                 return RESULT_SHOWUSAGE;
3186         ast_cli(fd, FORMAT2, "Peer", "Username", "ID (Lo/Rem)", "Seq (Tx/Rx)", "Lag", "Jitter", "JitBuf", "Format");
3187         for (x=0;x<IAX_MAX_CALLS;x++) {
3188                 ast_mutex_lock(&iaxsl[x]);
3189                 if (iaxs[x]) {
3190                         ast_cli(fd, FORMAT, ast_inet_ntoa(iabuf, sizeof(iabuf), iaxs[x]->addr.sin_addr), 
3191                                                 !ast_strlen_zero(iaxs[x]->username) ? iaxs[x]->username : "(None)", 
3192                                                 iaxs[x]->callno, iaxs[x]->peercallno, 
3193                                                 iaxs[x]->oseqno, iaxs[x]->iseqno, 
3194                                                 iaxs[x]->lag,
3195                                                 iaxs[x]->jitter,
3196                                                 jitterbufsize(iaxs[x]),
3197                                                 ast_getformatname(iaxs[x]->voiceformat) );
3198                         numchans++;
3199                 }
3200                 ast_mutex_unlock(&iaxsl[x]);
3201         }
3202         ast_cli(fd, "%d active IAX channel(s)\n", numchans);
3203         return RESULT_SUCCESS;
3204 #undef FORMAT
3205 #undef FORMAT2
3206 }
3207
3208 static int iax2_do_trunk_debug(int fd, int argc, char *argv[])
3209 {
3210         if (argc != 3)
3211                 return RESULT_SHOWUSAGE;
3212         iaxtrunkdebug = 1;
3213         ast_cli(fd, "IAX2 Trunk Debug Requested\n");
3214         return RESULT_SUCCESS;
3215 }
3216
3217 static int iax2_do_debug(int fd, int argc, char *argv[])
3218 {
3219         if (argc != 2)
3220                 return RESULT_SHOWUSAGE;
3221         iaxdebug = 1;
3222         ast_cli(fd, "IAX2 Debugging Enabled\n");
3223         return RESULT_SUCCESS;
3224 }
3225
3226 static int iax2_no_debug(int fd, int argc, char *argv[])
3227 {
3228         if (argc != 3)
3229                 return RESULT_SHOWUSAGE;
3230         iaxdebug = 0;
3231         ast_cli(fd, "IAX2 Debugging Disabled\n");
3232         return RESULT_SUCCESS;
3233 }
3234
3235
3236
3237 static char show_users_usage[] = 
3238 "Usage: iax2 show users\n"
3239 "       Lists all users known to the IAX (Inter-Asterisk eXchange rev 2) subsystem.\n";
3240
3241 static char show_channels_usage[] = 
3242 "Usage: iax2 show channels\n"
3243 "       Lists all currently active IAX channels.\n";
3244
3245 static char show_peers_usage[] = 
3246 "Usage: iax2 show peers\n"
3247 "       Lists all known IAX peers.\n";
3248
3249 static char show_firmware_usage[] = 
3250 "Usage: iax2 show firmware\n"
3251 "       Lists all known IAX firmware images.\n";
3252
3253 static char show_reg_usage[] =
3254 "Usage: iax2 show registry\n"
3255 "       Lists all registration requests and status.\n";
3256
3257 static char debug_usage[] = 
3258 "Usage: iax2 debug\n"
3259 "       Enables dumping of IAX packets for debugging purposes\n";
3260
3261 static char no_debug_usage[] = 
3262 "Usage: iax2 no debug\n"
3263 "       Disables dumping of IAX packets for debugging purposes\n";
3264
3265 static char debug_trunk_usage[] =
3266 "Usage: iax2 trunk debug\n"
3267 "       Requests current status of IAX trunking\n";
3268
3269 static struct ast_cli_entry  cli_show_users = 
3270         { { "iax2", "show", "users", NULL }, iax2_show_users, "Show defined IAX users", show_users_usage };
3271 static struct ast_cli_entry  cli_show_firmware = 
3272         { { "iax2", "show", "firmware", NULL }, iax2_show_firmware, "Show available IAX firmwares", show_firmware_usage };
3273 static struct ast_cli_entry  cli_show_channels =
3274         { { "iax2", "show", "channels", NULL }, iax2_show_channels, "Show active IAX channels", show_channels_usage };
3275 static struct ast_cli_entry  cli_show_peers =
3276         { { "iax2", "show", "peers", NULL }, iax2_show_peers, "Show defined IAX peers", show_peers_usage };
3277 static struct ast_cli_entry  cli_show_peers_include =
3278         { { "iax2", "show", "peers", "include", NULL }, iax2_show_peers, "Show defined IAX peers", show_peers_usage };
3279 static struct ast_cli_entry  cli_show_peers_exclude =
3280         { { "iax2", "show", "peers", "exclude", NULL }, iax2_show_peers, "Show defined IAX peers", show_peers_usage };
3281 static struct ast_cli_entry  cli_show_peers_begin =
3282         { { "iax2", "show", "peers", "begin", NULL }, iax2_show_peers, "Show defined IAX peers", show_peers_usage };
3283 static struct ast_cli_entry  cli_show_registry =
3284         { { "iax2", "show", "registry", NULL }, iax2_show_registry, "Show IAX registration status", show_reg_usage };
3285 static struct ast_cli_entry  cli_debug =
3286         { { "iax2", "debug", NULL }, iax2_do_debug, "Enable IAX debugging", debug_usage };
3287 static struct ast_cli_entry  cli_trunk_debug =
3288         { { "iax2", "trunk", "debug", NULL }, iax2_do_trunk_debug, "Request IAX trunk debug", debug_trunk_usage };
3289 static struct ast_cli_entry  cli_no_debug =
3290         { { "iax2", "no", "debug", NULL }, iax2_no_debug, "Disable IAX debugging", no_debug_usage };
3291
3292 static int iax2_write(struct ast_channel *c, struct ast_frame *f)
3293 {
3294         unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
3295         int res = -1;
3296         ast_mutex_lock(&iaxsl[callno]);
3297         if (iaxs[callno]) {
3298         /* If there's an outstanding error, return failure now */
3299                 if (!iaxs[callno]->error) {
3300                         if (iaxs[callno]->alreadygone)
3301                                 res = 0;
3302                                 /* Don't waste bandwidth sending null frames */
3303                         else if (f->frametype == AST_FRAME_NULL)
3304                                 res = 0;
3305                         else if ((f->frametype == AST_FRAME_VOICE) && iaxs[callno]->quelch)
3306                                 res = 0;
3307                         else if (!(iaxs[callno]->state & IAX_STATE_STARTED))
3308                                 res = 0;
3309                         else
3310                         /* Simple, just queue for transmission */
3311                                 res = iax2_send(iaxs[callno], f, 0, -1, 0, 0, 0);
3312                 } else {
3313                         ast_log(LOG_DEBUG, "Write error: %s\n", strerror(errno));
3314                 }
3315         }
3316         /* If it's already gone, just return */
3317         ast_mutex_unlock(&iaxsl[callno]);
3318         return res;
3319 }
3320
3321 static int __send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno, 
3322                 int now, int transfer, int final)
3323 {
3324         struct ast_frame f;
3325         f.frametype = type;
3326         f.subclass = command;
3327         f.datalen = datalen;
3328         f.samples = 0;
3329         f.mallocd = 0;
3330         f.offset = 0;
3331         f.src = __FUNCTION__;
3332         f.data = data;
3333         return iax2_send(i, &f, ts, seqno, now, transfer, final);
3334 }
3335
3336 static int send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
3337 {
3338         return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 0);
3339 }
3340
3341 static int send_command_locked(unsigned short callno, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
3342 {
3343         int res;
3344         ast_mutex_lock(&iaxsl[callno]);
3345         res = send_command(iaxs[callno], type, command, ts, data, datalen, seqno);
3346         ast_mutex_unlock(&iaxsl[callno]);
3347         return res;
3348 }
3349
3350 #ifdef BRIDGE_OPTIMIZATION
3351 static int forward_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
3352 {
3353         return __send_command(iaxs[i->bridgecallno], type, command, ts, data, datalen, seqno, 0, 0, 0);
3354 }
3355 #endif
3356
3357 static int send_command_final(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
3358 {
3359         /* It is assumed that the callno has already been locked */
3360         iax2_predestroy_nolock(i->callno);
3361         return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 1);
3362 }
3363
3364 static int send_command_immediate(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
3365 {
3366         return __send_command(i, type, command, ts, data, datalen, seqno, 1, 0, 0);
3367 }
3368
3369 static int send_command_transfer(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen)
3370 {
3371         return __send_command(i, type, command, ts, data, datalen, 0, 0, 1, 0);
3372 }
3373
3374 static int apply_context(struct iax2_context *con, char *context)
3375 {
3376         while(con) {
3377                 if (!strcmp(con->context, context))
3378                         return -1;
3379                 con = con->next;
3380         }
3381         return 0;
3382 }
3383
3384
3385 static int check_access(int callno, struct sockaddr_in *sin, struct iax_ies *ies)
3386 {
3387         /* Start pessimistic */
3388         int res = -1;
3389         int version = 2;
3390         struct iax2_user *user, *best = NULL;
3391         int bestscore = 0;
3392         int gotcapability=0;
3393         char iabuf[80];
3394         
3395         if (!iaxs[callno])
3396                 return res;
3397         if (ies->called_number)
3398                 strncpy(iaxs[callno]->exten, ies->called_number, sizeof(iaxs[callno]->exten) - 1);
3399         if (ies->calling_number) {
3400                 if (ies->calling_name)
3401                         snprintf(iaxs[callno]->callerid, sizeof(iaxs[callno]->callerid), "\"%s\" <%s>", ies->calling_name, ies->calling_number);
3402                 else
3403                         strncpy(iaxs[callno]->callerid, ies->calling_number, sizeof(iaxs[callno]->callerid) - 1);
3404         } else if (ies->calling_name)
3405                 strncpy(iaxs[callno]->callerid, ies->calling_name, sizeof(iaxs[callno]->callerid) - 1);
3406         if (ies->calling_ani)
3407                 strncpy(iaxs[callno]->ani, ies->calling_ani, sizeof(iaxs[callno]->ani) - 1);
3408         if (ies->dnid)
3409                 strncpy(iaxs[callno]->dnid, ies->dnid, sizeof(iaxs[callno]->dnid)-1);
3410         if (ies->called_context)
3411                 strncpy(iaxs[callno]->context, ies->called_context, sizeof(iaxs[callno]->context)-1);
3412         if (ies->language)
3413                 strncpy(iaxs[callno]->language, ies->language, sizeof(iaxs[callno]->language)-1);
3414         if (ies->username)
3415                 strncpy(iaxs[callno]->username, ies->username, sizeof(iaxs[callno]->username)-1);
3416         if (ies->format)
3417                 iaxs[callno]->peerformat = ies->format;
3418         if (ies->adsicpe)
3419                 iaxs[callno]->peeradsicpe = ies->adsicpe;
3420         if (ies->capability) {
3421                 gotcapability = 1;
3422                 iaxs[callno]->peercapability = ies->capability;
3423         } 
3424         if (ies->version)
3425                 version = ies->version;
3426         if (!gotcapability) 
3427                 iaxs[callno]->peercapability = iaxs[callno]->peerformat;
3428         if (version > IAX_PROTO_VERSION) {
3429                 ast_log(LOG_WARNING, "Peer '%s' has too new a protocol version (%d) for me\n", 
3430                         ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr), version);
3431                 return res;
3432         }
3433         ast_mutex_lock(&userl.lock);
3434         /* Search the userlist for a compatible entry, and fill in the rest */
3435         user = userl.users;
3436         while(user) {
3437                 if ((ast_strlen_zero(iaxs[callno]->username) ||                         /* No username specified */
3438                         !strcmp(iaxs[callno]->username, user->name))    /* Or this username specified */
3439                         && ast_apply_ha(user->ha, sin)  /* Access is permitted from this IP */
3440                         && (ast_strlen_zero(iaxs[callno]->context) ||                   /* No context specified */
3441                              apply_context(user->contexts, iaxs[callno]->context))) {                   /* Context is permitted */
3442                         if (!ast_strlen_zero(iaxs[callno]->username)) {
3443                                 /* Exact match, stop right now. */
3444                                 best = user;
3445                                 break;
3446                         } else if (ast_strlen_zero(user->secret) && ast_strlen_zero(user->inkeys)) {
3447                                 /* No required authentication */
3448                                 if (user->ha) {
3449                                         /* There was host authentication and we passed, bonus! */
3450                                         if (bestscore < 4) {
3451                                                 bestscore = 4;
3452                                                 best = user;
3453                                         }
3454                                 } else {
3455                                         /* No host access, but no secret, either, not bad */
3456                                         if (bestscore < 3) {
3457                                                 bestscore = 3;
3458                                                 best = user;
3459                                         }
3460                                 }
3461                         } else {
3462                                 if (user->ha) {
3463                                         /* Authentication, but host access too, eh, it's something.. */
3464                                         if (bestscore < 2) {
3465                                                 bestscore = 2;
3466                                                 best = user;
3467                                         }
3468                                 } else {
3469                                         /* Authentication and no host access...  This is our baseline */
3470                                         if (bestscore < 1) {
3471                                                 bestscore = 1;
3472                                                 best = user;
3473                                         }
3474