Use INET_ADDRLEN (bug #1956) (from airport!)
[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[INET_ADDRSTRLEN];
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[INET_ADDRSTRLEN];
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[INET_ADDRSTRLEN];
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 iabuf[INET_ADDRSTRLEN];
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(iabuf, sizeof(iabuf), p2->addr.sin_addr),
1614                                 ntohs(p2->addr.sin_port));
1615
1616         /* Fix relative timestamp */
1617         fr->ts = calc_fakestamp(p1, p2, fr->ts);
1618         /* Now just send it send on the 2nd one 
1619            with adjusted timestamp */
1620         return iax2_send(p2, &fr->af, fr->ts, -1, 0, 0, 0);
1621 }
1622 #endif
1623
1624 static int schedule_delivery(struct iax_frame *fr, int reallydeliver, int updatehistory)
1625 {
1626         int ms,x;
1627         int drops[MEMORY_SIZE];
1628         int min, max=0, maxone=0,y,z, match;
1629
1630         /* ms is a measure of the "lateness" of the packet relative to the first
1631            packet we received.  Understand that "ms" can easily be -ve if lag improves
1632            since call start.
1633            Called by IAX thread, with iaxsl lock held. */
1634         ms = calc_rxstamp(iaxs[fr->callno]) - fr->ts;
1635
1636         if (ms > 32767) {
1637                 /* What likely happened here is that our counter has circled but we haven't
1638                    gotten the update from the main packet.  We'll just pretend that we did, and
1639                    update the timestamp appropriately. */
1640                 ms -= 65536;
1641                 fr->ts += 65536;
1642         }
1643
1644         if (ms < -32768) {
1645                 /* We got this packet out of order.  Lets add 65536 to it to bring it into our new
1646                    time frame */
1647                 ms += 65536;
1648                 fr->ts -= 65536;
1649         }
1650
1651         /* delivery time is sender's sent timestamp converted back into absolute time according to our clock */
1652         fr->af.delivery.tv_sec = iaxs[fr->callno]->rxcore.tv_sec;
1653         fr->af.delivery.tv_usec = iaxs[fr->callno]->rxcore.tv_usec;
1654         fr->af.delivery.tv_sec += fr->ts / 1000;
1655         fr->af.delivery.tv_usec += (fr->ts % 1000) * 1000;
1656         if (fr->af.delivery.tv_usec >= 1000000) {
1657                 fr->af.delivery.tv_usec -= 1000000;
1658                 fr->af.delivery.tv_sec += 1;
1659         }
1660
1661         /* Rotate our history queue of "lateness".  Don't worry about those initial
1662            zeros because the first entry will always be zero */
1663         if (updatehistory) {
1664                 for (x=0;x<MEMORY_SIZE - 1;x++) 
1665                         iaxs[fr->callno]->history[x] = iaxs[fr->callno]->history[x+1];
1666                 /* Add a history entry for this one */
1667                 iaxs[fr->callno]->history[x] = ms;
1668         }
1669
1670         /* Initialize the minimum to reasonable values.  It's too much
1671            work to do the same for the maximum, repeatedly */
1672         min=iaxs[fr->callno]->history[0];
1673         for (z=0;z < iax2_dropcount + 1;z++) {
1674                 /* Start very optimistic ;-) */
1675                 max=-999999999;
1676                 for (x=0;x<MEMORY_SIZE;x++) {
1677                         if (max < iaxs[fr->callno]->history[x]) {
1678                                 /* We have a candidate new maximum value.  Make
1679                                    sure it's not in our drop list */
1680                                 match = 0;
1681                                 for (y=0;!match && (y<z);y++)
1682                                         match |= (drops[y] == x);
1683                                 if (!match) {
1684                                         /* It's not in our list, use it as the new maximum */
1685                                         max = iaxs[fr->callno]->history[x];
1686                                         maxone = x;
1687                                 }
1688                                 
1689                         }
1690                         if (!z) {
1691                                 /* On our first pass, find the minimum too */
1692                                 if (min > iaxs[fr->callno]->history[x])
1693                                         min = iaxs[fr->callno]->history[x];
1694                         }
1695                 }
1696 #if 1
1697                 drops[z] = maxone;
1698 #endif
1699         }
1700         /* Just for reference, keep the "jitter" value, the difference between the
1701            earliest and the latest. */
1702         iaxs[fr->callno]->jitter = max - min;   
1703         
1704         /* IIR filter for keeping track of historic jitter, but always increase
1705            historic jitter immediately for increase */
1706         
1707         if (iaxs[fr->callno]->jitter > iaxs[fr->callno]->historicjitter )
1708                 iaxs[fr->callno]->historicjitter = iaxs[fr->callno]->jitter;
1709         else
1710                 iaxs[fr->callno]->historicjitter = GAMMA * (double)iaxs[fr->callno]->jitter + (1-GAMMA) * 
1711                         iaxs[fr->callno]->historicjitter;
1712
1713         /* If our jitter buffer is too big (by a significant margin), then we slowly
1714            shrink it by about 1 ms each time to avoid letting the change be perceived */
1715         if (max < iaxs[fr->callno]->jitterbuffer - max_jitter_buffer)
1716                 iaxs[fr->callno]->jitterbuffer -= jittershrinkrate;
1717
1718
1719 #if 1
1720         /* Constrain our maximum jitter buffer appropriately */
1721         if (max > min + maxjitterbuffer) {
1722                 if (option_debug)
1723                         ast_log(LOG_DEBUG, "Constraining buffer from %d to %d + %d\n", max, min , maxjitterbuffer);
1724                 max = min + maxjitterbuffer;
1725         }
1726 #endif
1727
1728         /* If our jitter buffer is smaller than our maximum delay, grow the jitter
1729            buffer immediately to accomodate it (and a little more).  */
1730         if (max > iaxs[fr->callno]->jitterbuffer)
1731                 iaxs[fr->callno]->jitterbuffer = max 
1732                         /* + ((float)iaxs[fr->callno]->jitter) * 0.1 */;
1733
1734         /* If the caller just wanted us to update, return now */
1735         if (!reallydeliver)
1736                 return 0;
1737
1738         if (option_debug)
1739                 /* Log jitter stats for possible offline analysis */
1740                 ast_log(LOG_DEBUG, "Jitter: call=%d ts=%d: min=%d max=%d jb=%d; lateness=%d; jitter=%d historic=%d\n",
1741                                         fr->callno, fr->ts, min, max, iaxs[fr->callno]->jitterbuffer, ms,
1742                                         iaxs[fr->callno]->jitter, iaxs[fr->callno]->historicjitter);
1743         
1744         /* Subtract the lateness from our jitter buffer to know how long to wait
1745            before sending our packet.  */
1746         ms = iaxs[fr->callno]->jitterbuffer - ms;
1747         
1748         if (!use_jitterbuffer)
1749                 ms = 0;
1750
1751         if (ms < 1) {
1752                 /* Don't deliver it more than 4 ms late */
1753                 if ((ms > -4) || (fr->af.frametype != AST_FRAME_VOICE)) {
1754                         if (option_debug)
1755                                 ast_log(LOG_DEBUG, "schedule_delivery: Delivering immediately (Calculated ms is %d)\n", ms);
1756                         __do_deliver(fr);
1757                 } else {
1758                         if (option_debug)
1759                                 ast_log(LOG_DEBUG, "schedule_delivery: Dropping voice packet since %d ms is too old\n", ms);
1760                         /* Free our iax frame */
1761                         iax2_frame_free(fr);
1762                 }
1763         } else {
1764                 if (option_debug)
1765                         ast_log(LOG_DEBUG, "schedule_delivery: Scheduling delivery in %d ms\n", ms);
1766                 fr->retrans = ast_sched_add(sched, ms, do_deliver, fr);
1767         }
1768         return 0;
1769 }
1770
1771 static int iax2_transmit(struct iax_frame *fr)
1772 {
1773         /* Lock the queue and place this packet at the end */
1774         fr->next = NULL;
1775         fr->prev = NULL;
1776         /* By setting this to 0, the network thread will send it for us, and
1777            queue retransmission if necessary */
1778         fr->sentyet = 0;
1779         ast_mutex_lock(&iaxq.lock);
1780         if (!iaxq.head) {
1781                 /* Empty queue */
1782                 iaxq.head = fr;
1783                 iaxq.tail = fr;
1784         } else {
1785                 /* Double link */
1786                 iaxq.tail->next = fr;
1787                 fr->prev = iaxq.tail;
1788                 iaxq.tail = fr;
1789         }
1790         iaxq.count++;
1791         ast_mutex_unlock(&iaxq.lock);
1792         /* Wake up the network thread */
1793         pthread_kill(netthreadid, SIGURG);
1794         return 0;
1795 }
1796
1797
1798
1799 static int iax2_digit(struct ast_channel *c, char digit)
1800 {
1801         return send_command_locked(PTR_TO_CALLNO(c->pvt->pvt), AST_FRAME_DTMF, digit, 0, NULL, 0, -1);
1802 }
1803
1804 static int iax2_sendtext(struct ast_channel *c, char *text)
1805 {
1806         
1807         return send_command_locked(PTR_TO_CALLNO(c->pvt->pvt), AST_FRAME_TEXT,
1808                 0, 0, text, strlen(text) + 1, -1);
1809 }
1810
1811 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
1812 {
1813         return send_command_locked(PTR_TO_CALLNO(c->pvt->pvt), AST_FRAME_IMAGE, img->subclass, 0, img->data, img->datalen, -1);
1814 }
1815
1816 static int iax2_sendhtml(struct ast_channel *c, int subclass, char *data, int datalen)
1817 {
1818         return send_command_locked(PTR_TO_CALLNO(c->pvt->pvt), AST_FRAME_HTML, subclass, 0, data, datalen, -1);
1819 }
1820
1821 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
1822 {
1823         unsigned short callno = PTR_TO_CALLNO(newchan->pvt->pvt);
1824         ast_mutex_lock(&iaxsl[callno]);
1825         if (iaxs[callno])
1826                 iaxs[callno]->owner = newchan;
1827         else
1828                 ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n");
1829         ast_mutex_unlock(&iaxsl[callno]);
1830         return 0;
1831 }
1832
1833 #ifdef MYSQL_FRIENDS
1834
1835 static void mysql_update_peer(char *peer, struct sockaddr_in *sin)
1836 {
1837         if (mysql && (strlen(peer) < 128)) {
1838                 char query[512];
1839                 char *name;
1840                 char iabuf[INET_ADDRSTRLEN];
1841                 time_t nowtime;
1842                 name = alloca(strlen(peer) * 2 + 1);
1843                 time(&nowtime);
1844                 mysql_real_escape_string(mysql, name, peer, strlen(peer));
1845                 snprintf(query, sizeof(query), "UPDATE iaxfriends SET ipaddr=\"%s\", port=\"%d\", regseconds=\"%ld\" WHERE name=\"%s\"", 
1846                         ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr), ntohs(sin->sin_port), nowtime, name);
1847                 ast_mutex_lock(&mysqllock);
1848                 if (mysql_real_query(mysql, query, strlen(query))) 
1849                         ast_log(LOG_WARNING, "Unable to update database\n");
1850                         
1851                 ast_mutex_unlock(&mysqllock);
1852         }
1853 }
1854
1855 static struct iax2_peer *mysql_peer(char *peer)
1856 {
1857         struct iax2_peer *p;
1858         int success = 0;
1859         
1860         p = malloc(sizeof(struct iax2_peer));
1861         memset(p, 0, sizeof(struct iax2_peer));
1862         if (mysql && (strlen(peer) < 128)) {
1863                 char query[512];
1864                 char *name;
1865                 int numfields, x;
1866                 int port;
1867                 time_t regseconds, nowtime;
1868                 MYSQL_RES *result;
1869                 MYSQL_FIELD *fields;
1870                 MYSQL_ROW rowval;
1871                 name = alloca(strlen(peer) * 2 + 1);
1872                 mysql_real_escape_string(mysql, name, peer, strlen(peer));
1873                 snprintf(query, sizeof(query), "SELECT name, secret, context, ipaddr, port, regseconds FROM iaxfriends WHERE name=\"%s\"", name);
1874                 ast_mutex_lock(&mysqllock);
1875                 mysql_query(mysql, query);
1876                 if ((result = mysql_store_result(mysql))) {
1877                         if ((rowval = mysql_fetch_row(result))) {
1878                                 numfields = mysql_num_fields(result);
1879                                 fields = mysql_fetch_fields(result);
1880                                 success = 1;
1881                                 for (x=0;x<numfields;x++) {
1882                                         if (rowval[x]) {
1883                                                 if (!strcasecmp(fields[x].name, "secret")) {
1884                                                         strncpy(p->secret, rowval[x], sizeof(p->secret));
1885                                                 } else if (!strcasecmp(fields[x].name, "context")) {
1886                                                         strncpy(p->context, rowval[x], sizeof(p->context) - 1);
1887                                                 } else if (!strcasecmp(fields[x].name, "ipaddr")) {
1888                                                         inet_aton(rowval[x], &p->addr.sin_addr);
1889                                                 } else if (!strcasecmp(fields[x].name, "port")) {
1890                                                         if (sscanf(rowval[x], "%i", &port) != 1)
1891                                                                 port = 0;
1892                                                         p->addr.sin_port = htons(port);
1893                                                 } else if (!strcasecmp(fields[x].name, "regseconds")) {
1894                                                         if (sscanf(rowval[x], "%li", &regseconds) != 1)
1895                                                                 regseconds = 0;
1896                                                 }
1897                                         }
1898                                 }
1899                                 time(&nowtime);
1900                                 if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE) 
1901                                         memset(&p->addr, 0, sizeof(p->addr));
1902                         }
1903                         mysql_free_result(result);
1904                         result = NULL;
1905                 }
1906                 ast_mutex_unlock(&mysqllock);
1907         }
1908         if (!success) {
1909                 free(p);
1910                 p = NULL;
1911         } else {
1912                 strncpy(p->name, peer, sizeof(p->name) - 1);
1913                 p->dynamic = 1;
1914                 p->temponly = 1;
1915                 p->expire = -1;
1916                 p->capability = iax2_capability;
1917                 p->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
1918         }
1919         return p;
1920 }
1921 static struct iax2_user *mysql_user(char *user)
1922 {
1923         struct iax2_user *p;
1924         struct iax2_context *con;
1925         int success = 0;
1926         
1927         p = malloc(sizeof(struct iax2_user));
1928         memset(p, 0, sizeof(struct iax2_user));
1929         con = malloc(sizeof(struct iax2_context));
1930         memset(con, 0, sizeof(struct iax2_context));
1931         strcpy(con->context, "default");
1932         p->contexts = con;
1933         if (mysql && (strlen(user) < 128)) {
1934                 char query[512];
1935                 char *name;
1936                 int numfields, x;
1937                 MYSQL_RES *result;
1938                 MYSQL_FIELD *fields;
1939                 MYSQL_ROW rowval;
1940                 name = alloca(strlen(user) * 2 + 1);
1941                 mysql_real_escape_string(mysql, name, user, strlen(user));
1942                 snprintf(query, sizeof(query), "SELECT name, secret, context, ipaddr, port, regseconds, accountcode FROM iaxfriends WHERE name=\"%s\"", name);
1943                 ast_mutex_lock(&mysqllock);
1944                 mysql_query(mysql, query);
1945                 if ((result = mysql_store_result(mysql))) {
1946                         if ((rowval = mysql_fetch_row(result))) {
1947                                 numfields = mysql_num_fields(result);
1948                                 fields = mysql_fetch_fields(result);
1949                                 success = 1;
1950                                 for (x=0;x<numfields;x++) {
1951                                         if (rowval[x]) {
1952                                                 if (!strcasecmp(fields[x].name, "secret")) {
1953                                                         strncpy(p->secret, rowval[x], sizeof(p->secret));
1954                                                 } else if (!strcasecmp(fields[x].name, "context")) {
1955                                                         strncpy(p->contexts->context, rowval[x], sizeof(p->contexts->context) - 1);
1956                                                 } else if (!strcasecmp(fields[x].name, "accountcode")) {
1957                                                         strncpy(p->accountcode, rowval[x], sizeof(p->accountcode));
1958                                                 }
1959                                         }
1960                                 }
1961                         }
1962                         mysql_free_result(result);
1963                         result = NULL;
1964                 }
1965                 ast_mutex_unlock(&mysqllock);
1966         }
1967         if (!success) {
1968                 if (p->contexts)
1969                         free(p->contexts);
1970                 free(p);
1971                 p = NULL;
1972         } else {
1973                 strncpy(p->name, user, sizeof(p->name) - 1);
1974                 p->temponly = 1;
1975                 p->capability = iax2_capability;
1976                 p->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
1977         }
1978         return p;
1979 }
1980 #endif /* MYSQL_FRIENDS */
1981
1982 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)
1983 {
1984         struct ast_hostent ahp; struct hostent *hp;
1985         struct iax2_peer *p;
1986         int found=0;
1987         if (sendani)
1988                 *sendani = 0;
1989         if (maxtime)
1990                 *maxtime = 0;
1991         if (trunk)
1992                 *trunk = 0;
1993         sin->sin_family = AF_INET;
1994         ast_mutex_lock(&peerl.lock);
1995         p = peerl.peers;
1996         while(p) {
1997                 if (!strcasecmp(p->name, peer)) {
1998                         break;
1999                 }
2000                 p = p->next;
2001         }
2002         ast_mutex_unlock(&peerl.lock);
2003 #ifdef MYSQL_FRIENDS
2004         if (!p)
2005                 p = mysql_peer(peer);
2006 #endif          
2007         if (p) {
2008                 found++;
2009                 if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
2010                         (!p->maxms || ((p->lastms > 0)  && (p->lastms <= p->maxms)))) {
2011                         if (sendani)
2012                                 *sendani = p->sendani;          /* Whether we transmit ANI */
2013                         if (maxtime)
2014                                 *maxtime = p->maxms;            /* Max time they should take */
2015                         if (context)
2016                                 strncpy(context, p->context, AST_MAX_EXTENSION - 1);
2017                         if (peercontext)
2018                                 strncpy(peercontext, p->peercontext, AST_MAX_EXTENSION - 1);
2019                         if (trunk)
2020                                 *trunk = p->trunk;
2021                         if (capability)
2022                                 *capability = p->capability;
2023                         if (secret)
2024                                 strncpy(secret, p->secret, seclen);
2025                         if (p->addr.sin_addr.s_addr) {
2026                                 sin->sin_addr = p->addr.sin_addr;
2027                                 sin->sin_port = p->addr.sin_port;
2028                         } else {
2029                                 sin->sin_addr = p->defaddr.sin_addr;
2030                                 sin->sin_port = p->defaddr.sin_port;
2031                         }
2032                         if (notransfer)
2033                                 *notransfer=p->notransfer;
2034                 } else {
2035                         if (p->temponly)
2036                                 free(p);
2037                         p = NULL;
2038                 }
2039         }
2040         if (ofound)
2041                 *ofound = found;
2042         if (!p && !found) {
2043                 hp = ast_gethostbyname(peer, &ahp);
2044                 if (hp) {
2045                         memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
2046                         sin->sin_port = htons(IAX_DEFAULT_PORTNO);
2047                         return 0;
2048                 } else {
2049                         ast_log(LOG_WARNING, "No such host: %s\n", peer);
2050                         return -1;
2051                 }
2052         } else if (!p)
2053                 return -1;
2054         if (p->temponly)
2055                 free(p);
2056         return 0;
2057 }
2058
2059 static int auto_congest(void *nothing)
2060 {
2061         int callno = PTR_TO_CALLNO(nothing);
2062         struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_CONGESTION };
2063         ast_mutex_lock(&iaxsl[callno]);
2064         if (iaxs[callno]) {
2065                 iaxs[callno]->initid = -1;
2066                 iax2_queue_frame(callno, &f);
2067                 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
2068         }
2069         ast_mutex_unlock(&iaxsl[callno]);
2070         return 0;
2071 }
2072
2073 static unsigned int iax2_datetime(void)
2074 {
2075         time_t t;
2076         struct tm tm;
2077         unsigned int tmp;
2078         time(&t);
2079         localtime_r(&t, &tm);
2080         tmp  = (tm.tm_sec >> 1) & 0x1f;   /* 5 bits of seconds */
2081         tmp |= (tm.tm_min & 0x3f) << 5;   /* 6 bits of minutes */
2082         tmp |= (tm.tm_hour & 0x1f) << 11;   /* 5 bits of hours */
2083         tmp |= (tm.tm_mday & 0x1f) << 16; /* 5 bits of day of month */
2084         tmp |= ((tm.tm_mon + 1) & 0xf) << 21; /* 4 bits of month */
2085         tmp |= ((tm.tm_year - 100) & 0x7f) << 25; /* 7 bits of year */
2086         return tmp;
2087 }
2088
2089 static int iax2_call(struct ast_channel *c, char *dest, int timeout)
2090 {
2091         struct sockaddr_in sin;
2092         char host[256];
2093         char *rdest;
2094         char *rcontext;
2095         char *username;
2096         char *secret = NULL;
2097         char *hname;
2098         char cid[256] = "";
2099         char *l=NULL, *n=NULL;
2100         struct iax_ie_data ied;
2101         char myrdest [5] = "s";
2102         char context[AST_MAX_EXTENSION] ="";
2103         char peercontext[AST_MAX_EXTENSION] ="";
2104         char *portno = NULL;
2105         char *opts = "";
2106         unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
2107         char *stringp=NULL;
2108         char storedsecret[80];
2109         if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
2110                 ast_log(LOG_WARNING, "Line is already in use (%s)?\n", c->name);
2111                 return -1;
2112         }
2113         strncpy(host, dest, sizeof(host)-1);
2114         stringp=host;
2115         strsep(&stringp, "/");
2116         /* If no destination extension specified, use 's' */
2117         rdest = strsep(&stringp, "/");
2118         if (!rdest) 
2119                 rdest = myrdest;
2120         else {
2121                 /* Check for trailing options */
2122                 opts = strsep(&stringp, "/");
2123                 if (!opts)
2124                         opts = "";
2125         }
2126         stringp=rdest;
2127         strsep(&stringp, "@");
2128         rcontext = strsep(&stringp, "@");
2129         stringp=host;
2130         strsep(&stringp, "@");
2131         username = strsep(&stringp, "@");
2132         if (username) {
2133                 /* Really the second argument is the host, not the username */
2134                 hname = username;
2135                 username = host;
2136         } else {
2137                 hname = host;
2138         }
2139         if (username) {
2140                 stringp=username;
2141                 username = strsep(&stringp, ":");
2142                 secret = strsep(&stringp, ":");
2143         }
2144         stringp=hname;
2145         if (strsep(&stringp, ":")) {
2146                 stringp=hname;
2147                 strsep(&stringp, ":");
2148                 portno = strsep(&stringp, ":");
2149         }
2150         if (create_addr(&sin, NULL, NULL, NULL, hname, context, NULL, NULL, storedsecret, sizeof(storedsecret) - 1, NULL, peercontext)) {
2151                 ast_log(LOG_WARNING, "No address associated with '%s'\n", hname);
2152                 return -1;
2153         }
2154         /* Keep track of the context for outgoing calls too */
2155         strncpy(c->context, context, sizeof(c->context) - 1);
2156         if (portno) {
2157                 sin.sin_port = htons(atoi(portno));
2158         }
2159         if (c->callerid) {
2160                 strncpy(cid, c->callerid, sizeof(cid) - 1);
2161                 ast_callerid_parse(cid, &n, &l);
2162                 if (l)
2163                         ast_shrink_phone_number(l);
2164         }
2165         /* Now build request */ 
2166         memset(&ied, 0, sizeof(ied));
2167         /* On new call, first IE MUST be IAX version of caller */
2168         iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
2169         iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, rdest);
2170         if (strchr(opts, 'a')) {
2171                 /* Request auto answer */
2172                 iax_ie_append(&ied, IAX_IE_AUTOANSWER);
2173         }
2174         if (l)
2175                 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
2176         if (n)
2177                 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n);
2178         if (iaxs[callno]->sendani && c->ani) {
2179                 l = n = NULL;
2180                 strncpy(cid, c->ani, sizeof(cid) - 1);
2181                 ast_callerid_parse(cid, &n, &l);
2182                 if (l) {
2183                         ast_shrink_phone_number(l);
2184                         iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, l);
2185                 }
2186         }
2187         if (c->language && !ast_strlen_zero(c->language))
2188                 iax_ie_append_str(&ied, IAX_IE_LANGUAGE, c->language);
2189         if (c->dnid && !ast_strlen_zero(c->dnid))
2190                 iax_ie_append_str(&ied, IAX_IE_DNID, c->dnid);
2191         if (rcontext)
2192                 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, rcontext);
2193         else if (strlen(peercontext))
2194                 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, peercontext);
2195         if (username)
2196                 iax_ie_append_str(&ied, IAX_IE_USERNAME, username);
2197         if (!secret && !ast_strlen_zero(storedsecret))
2198                 secret = storedsecret;
2199         ast_mutex_lock(&iaxsl[callno]);
2200         if (!ast_strlen_zero(c->context))
2201                 strncpy(iaxs[callno]->context, c->context, sizeof(iaxs[callno]->context));
2202         if (secret) {
2203                 if (secret[0] == '[') {
2204                         /* This is an RSA key, not a normal secret */
2205                         strncpy(iaxs[callno]->outkey, secret + 1, sizeof(iaxs[callno]->secret)-1);
2206                         if (!ast_strlen_zero(iaxs[callno]->outkey)) {
2207                                 iaxs[callno]->outkey[strlen(iaxs[callno]->outkey) - 1] = '\0';
2208                         }
2209                 } else
2210                         strncpy(iaxs[callno]->secret, secret, sizeof(iaxs[callno]->secret)-1);
2211         }
2212         iax_ie_append_int(&ied, IAX_IE_FORMAT, c->nativeformats);
2213         iax_ie_append_int(&ied, IAX_IE_CAPABILITY, iaxs[callno]->capability);
2214         iax_ie_append_short(&ied, IAX_IE_ADSICPE, c->adsicpe);
2215         iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime());
2216         /* Transmit the string in a "NEW" request */
2217 #if 0
2218         /* XXX We have no equivalent XXX */
2219         if (option_verbose > 2)
2220                 ast_verbose(VERBOSE_PREFIX_3 "Calling using options '%s'\n", requeststr);
2221 #endif          
2222         if (iaxs[callno]->maxtime) {
2223                 /* Initialize pingtime and auto-congest time */
2224                 iaxs[callno]->pingtime = iaxs[callno]->maxtime / 2;
2225                 iaxs[callno]->initid = ast_sched_add(sched, iaxs[callno]->maxtime * 2, auto_congest, CALLNO_TO_PTR(callno));
2226         }
2227         send_command(iaxs[callno], AST_FRAME_IAX,
2228                 IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
2229         ast_mutex_unlock(&iaxsl[callno]);
2230         ast_setstate(c, AST_STATE_RINGING);
2231         return 0;
2232 }
2233
2234 static int iax2_hangup(struct ast_channel *c) 
2235 {
2236         unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
2237         int alreadygone;
2238         ast_mutex_lock(&iaxsl[callno]);
2239         if (callno && iaxs[callno]) {
2240                 ast_log(LOG_DEBUG, "We're hanging up %s now...\n", c->name);
2241                 alreadygone = iaxs[callno]->alreadygone;
2242                 /* Send the hangup unless we have had a transmission error or are already gone */
2243                 if (!iaxs[callno]->error && !alreadygone) 
2244                         send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, NULL, 0, -1);
2245                 /* Explicitly predestroy it */
2246                 iax2_predestroy_nolock(callno);
2247                 /* If we were already gone to begin with, destroy us now */
2248                 if (alreadygone) {
2249                         ast_log(LOG_DEBUG, "Really destroying %s now...\n", c->name);
2250                         iax2_destroy_nolock(callno);
2251                 }
2252         }
2253         ast_mutex_unlock(&iaxsl[callno]);
2254         if (option_verbose > 2) 
2255                 ast_verbose(VERBOSE_PREFIX_3 "Hungup '%s'\n", c->name);
2256         return 0;
2257 }
2258
2259 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
2260 {
2261         struct ast_option_header *h;
2262         int res;
2263         h = malloc(datalen + sizeof(struct ast_option_header));
2264         if (h) {
2265                 h->flag = AST_OPTION_FLAG_REQUEST;
2266                 h->option = htons(option);
2267                 memcpy(h->data, data, datalen);
2268                 res = send_command_locked(PTR_TO_CALLNO(c->pvt->pvt), AST_FRAME_CONTROL,
2269                         AST_CONTROL_OPTION, 0, (char *)h, datalen + sizeof(struct ast_option_header), -1);
2270                 free(h);
2271                 return res;
2272         } else 
2273                 ast_log(LOG_WARNING, "Out of memory\n");
2274         return -1;
2275 }
2276
2277 static struct ast_frame *iax2_read(struct ast_channel *c) 
2278 {
2279         static struct ast_frame f = { AST_FRAME_NULL, };
2280         ast_log(LOG_NOTICE, "I should never be called!\n");
2281         return &f;
2282 }
2283
2284 static int iax2_start_transfer(unsigned short callno0, unsigned short callno1)
2285 {
2286         int res;
2287         struct iax_ie_data ied0;
2288         struct iax_ie_data ied1;
2289         unsigned int transferid = rand();
2290         memset(&ied0, 0, sizeof(ied0));
2291         iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &iaxs[callno1]->addr);
2292         iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[callno1]->peercallno);
2293         iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, transferid);
2294
2295         memset(&ied1, 0, sizeof(ied1));
2296         iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &iaxs[callno0]->addr);
2297         iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[callno0]->peercallno);
2298         iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, transferid);
2299         
2300         res = send_command(iaxs[callno0], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
2301         if (res)
2302                 return -1;
2303         res = send_command(iaxs[callno1], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
2304         if (res)
2305                 return -1;
2306         iaxs[callno0]->transferring = TRANSFER_BEGIN;
2307         iaxs[callno1]->transferring = TRANSFER_BEGIN;
2308         return 0;
2309 }
2310
2311 static void lock_both(unsigned short callno0, unsigned short callno1)
2312 {
2313         ast_mutex_lock(&iaxsl[callno0]);
2314         while (ast_mutex_trylock(&iaxsl[callno1])) {
2315                 ast_mutex_unlock(&iaxsl[callno0]);
2316                 usleep(10);
2317                 ast_mutex_lock(&iaxsl[callno0]);
2318         }
2319 }
2320
2321 static void unlock_both(unsigned short callno0, unsigned short callno1)
2322 {
2323         ast_mutex_unlock(&iaxsl[callno1]);
2324         ast_mutex_unlock(&iaxsl[callno0]);
2325 }
2326
2327 static int iax2_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
2328 {
2329         struct ast_channel *cs[3];
2330         struct ast_channel *who;
2331         int to = -1;
2332         int res = -1;
2333         int transferstarted=0;
2334         struct ast_frame *f;
2335         unsigned short callno0 = PTR_TO_CALLNO(c0->pvt->pvt);
2336         unsigned short callno1 = PTR_TO_CALLNO(c1->pvt->pvt);
2337         struct timeval waittimer = {0, 0}, tv;
2338         
2339         lock_both(callno0, callno1);
2340         /* Put them in native bridge mode */
2341         iaxs[callno0]->bridgecallno = callno1;
2342         iaxs[callno1]->bridgecallno = callno0;
2343         unlock_both(callno0, callno1);
2344
2345         /* If not, try to bridge until we can execute a transfer, if we can */
2346         cs[0] = c0;
2347         cs[1] = c1;
2348         for (/* ever */;;) {
2349                 /* Check in case we got masqueraded into */
2350                 if ((c0->type != type) || (c1->type != type)) {
2351                         if (option_verbose > 2)
2352                                 ast_verbose(VERBOSE_PREFIX_3 "Can't masquerade, we're different...\n");
2353                         /* Remove from native mode */
2354                         if (c0->type == type) {
2355                                 ast_mutex_lock(&iaxsl[callno0]);
2356                                 iaxs[callno0]->bridgecallno = 0;
2357                                 ast_mutex_unlock(&iaxsl[callno0]);
2358                         }
2359                         if (c1->type == type) {
2360                                 ast_mutex_lock(&iaxsl[callno1]);
2361                                 iaxs[callno1]->bridgecallno = 0;
2362                                 ast_mutex_unlock(&iaxsl[callno1]);
2363                         }
2364                         return -2;
2365                 }
2366                 if (c0->nativeformats != c1->nativeformats) {
2367                         ast_verbose(VERBOSE_PREFIX_3 "Operating with different codecs, can't native bridge...\n");
2368                         /* Remove from native mode */
2369                         lock_both(callno0, callno1);
2370                         iaxs[callno0]->bridgecallno = 0;
2371                         iaxs[callno1]->bridgecallno = 0;
2372                         unlock_both(callno0, callno1);
2373                         return -2;
2374                 }
2375                 /* check if transfered and if we really want native bridging */
2376                 if (!transferstarted && !iaxs[callno0]->notransfer && !iaxs[callno1]->notransfer) {
2377                         /* Try the transfer */
2378                         if (iax2_start_transfer(callno0, callno1))
2379                                 ast_log(LOG_WARNING, "Unable to start the transfer\n");
2380                         transferstarted = 1;
2381                 }
2382                 if ((iaxs[callno0]->transferring == TRANSFER_RELEASED) && (iaxs[callno1]->transferring == TRANSFER_RELEASED)) {
2383                         /* Call has been transferred.  We're no longer involved */
2384                         gettimeofday(&tv, NULL);
2385                         if (!waittimer.tv_sec && !waittimer.tv_usec) {
2386                                 waittimer.tv_sec = tv.tv_sec;
2387                                 waittimer.tv_usec = tv.tv_usec;
2388                         } else if (tv.tv_sec - waittimer.tv_sec > IAX_LINGER_TIMEOUT) {
2389                                 c0->_softhangup |= AST_SOFTHANGUP_DEV;
2390                                 c1->_softhangup |= AST_SOFTHANGUP_DEV;
2391                                 *fo = NULL;
2392                                 *rc = c0;
2393                                 res = 0;
2394                                 break;
2395                         }
2396                 }
2397                 to = 1000;
2398                 who = ast_waitfor_n(cs, 2, &to);
2399                 if (!who) {
2400                         if (ast_check_hangup(c0) || ast_check_hangup(c1)) {
2401                                 res = -1;
2402                                 break;
2403                         }
2404                         continue;
2405                 }
2406                 f = ast_read(who);
2407                 if (!f) {
2408                         *fo = NULL;
2409                         *rc = who;
2410                         res = 0;
2411                         break;
2412                 }
2413                 if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
2414                         *fo = f;
2415                         *rc = who;
2416                         res =  0;
2417                         break;
2418                 }
2419                 if ((f->frametype == AST_FRAME_VOICE) ||
2420                         (f->frametype == AST_FRAME_TEXT) ||
2421                         (f->frametype == AST_FRAME_VIDEO) || 
2422                         (f->frametype == AST_FRAME_IMAGE) ||
2423                         (f->frametype == AST_FRAME_DTMF)) {
2424                         if ((f->frametype == AST_FRAME_DTMF) && 
2425                                 (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
2426                                 if ((who == c0)) {
2427                                         if  ((flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
2428                                                 *rc = c0;
2429                                                 *fo = f;
2430                                                 /* Take out of conference mode */
2431                                                 res = 0;
2432                                                 /* Remove from native mode */
2433                                                 break;
2434                                         } else 
2435                                                 goto tackygoto;
2436                                 } else
2437                                 if ((who == c1)) {
2438                                         if (flags & AST_BRIDGE_DTMF_CHANNEL_1) {
2439                                                 *rc = c1;
2440                                                 *fo = f;
2441                                                 res =  0;
2442                                                 /* Remove from native mode */
2443                                                 break;
2444                                         } else
2445                                                 goto tackygoto;
2446                                 }
2447                         } else {
2448 #if 0
2449                                 ast_log(LOG_DEBUG, "Read from %s\n", who->name);
2450                                 if (who == last) 
2451                                         ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
2452                                 last = who;
2453 #endif
2454 tackygoto:
2455                                 if (who == c0) 
2456                                         ast_write(c1, f);
2457                                 else 
2458                                         ast_write(c0, f);
2459                         }
2460                         ast_frfree(f);
2461                 } else
2462                         ast_frfree(f);
2463                 /* Swap who gets priority */
2464                 cs[2] = cs[0];
2465                 cs[0] = cs[1];
2466                 cs[1] = cs[2];
2467         }
2468         lock_both(callno0, callno1);
2469         iaxs[callno0]->bridgecallno = 0;
2470         iaxs[callno1]->bridgecallno = 0;
2471         unlock_both(callno0, callno1);
2472         return res;
2473 }
2474
2475 static int iax2_answer(struct ast_channel *c)
2476 {
2477         unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
2478         if (option_debug)
2479                 ast_log(LOG_DEBUG, "Answering\n");
2480         return send_command_locked(callno, AST_FRAME_CONTROL, AST_CONTROL_ANSWER, 0, NULL, 0, -1);
2481 }
2482
2483 static int iax2_indicate(struct ast_channel *c, int condition)
2484 {
2485         unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
2486         if (option_debug)
2487                 ast_log(LOG_DEBUG, "Indicating condition %d\n", condition);
2488         return send_command_locked(callno, AST_FRAME_CONTROL, condition, 0, NULL, 0, -1);
2489 }
2490         
2491 static int iax2_transfer(struct ast_channel *c, char *dest)
2492 {
2493         unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
2494         struct iax_ie_data ied;
2495         char tmp[256] = "", *context;
2496         strncpy(tmp, dest, sizeof(tmp) - 1);
2497         context = strchr(tmp, '@');
2498         if (context) {
2499                 *context = '\0';
2500                 context++;
2501         }
2502         memset(&ied, 0, sizeof(ied));
2503         iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, tmp);
2504         if (context)
2505                 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, context);
2506         if (option_debug)
2507                 ast_log(LOG_DEBUG, "Transferring '%s' to '%s'\n", c->name, dest);
2508         return send_command_locked(callno, AST_FRAME_IAX, IAX_COMMAND_TRANSFER, 0, ied.buf, ied.pos, -1);
2509 }
2510         
2511
2512 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
2513
2514 static int iax2_getpeertrunk(struct sockaddr_in sin)
2515 {
2516         struct iax2_peer *peer;
2517         int res = 0;
2518         ast_mutex_lock(&peerl.lock);
2519         peer = peerl.peers;
2520         while(peer) {
2521                 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
2522                                 (peer->addr.sin_port == sin.sin_port)) {
2523                                         res = peer->trunk;
2524                                         break;
2525                 }
2526                 peer = peer->next;
2527         }
2528         ast_mutex_unlock(&peerl.lock);
2529         return res;
2530 }
2531
2532 static struct ast_channel *ast_iax2_new(int callno, int state, int capability)
2533 {
2534         struct ast_channel *tmp;
2535         struct chan_iax2_pvt *i;
2536         /* Don't hold call lock */
2537         ast_mutex_unlock(&iaxsl[callno]);
2538         tmp = ast_channel_alloc(1);
2539         ast_mutex_lock(&iaxsl[callno]);
2540         i = iaxs[callno];
2541         if (i && tmp) {
2542                 if (!ast_strlen_zero(i->username))
2543                         snprintf(tmp->name, sizeof(tmp->name), "IAX2[%s@%s]/%d", i->username, i->host, i->callno);
2544                 else
2545                         snprintf(tmp->name, sizeof(tmp->name), "IAX2[%s]/%d", i->host, i->callno);
2546                 tmp->type = type;
2547                 /* We can support any format by default, until we get restricted */
2548                 tmp->nativeformats = capability;
2549                 tmp->readformat = 0;
2550                 tmp->writeformat = 0;
2551                 tmp->pvt->pvt = CALLNO_TO_PTR(i->callno);
2552                 tmp->pvt->send_digit = iax2_digit;
2553                 tmp->pvt->send_text = iax2_sendtext;
2554                 tmp->pvt->send_image = iax2_sendimage;
2555                 tmp->pvt->send_html = iax2_sendhtml;
2556                 tmp->pvt->call = iax2_call;
2557                 tmp->pvt->hangup = iax2_hangup;
2558                 tmp->pvt->answer = iax2_answer;
2559                 tmp->pvt->read = iax2_read;
2560                 tmp->pvt->write = iax2_write;
2561                 tmp->pvt->write_video = iax2_write;
2562                 tmp->pvt->indicate = iax2_indicate;
2563                 tmp->pvt->setoption = iax2_setoption;
2564                 tmp->pvt->bridge = iax2_bridge;
2565                 tmp->pvt->transfer = iax2_transfer;
2566                 if (!ast_strlen_zero(i->callerid))
2567                         tmp->callerid = strdup(i->callerid);
2568                 if (!ast_strlen_zero(i->ani))
2569                         tmp->ani = strdup(i->ani);
2570                 if (!ast_strlen_zero(i->language))
2571                         strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
2572                 if (!ast_strlen_zero(i->dnid))
2573                         tmp->dnid = strdup(i->dnid);
2574                 if (!ast_strlen_zero(i->accountcode))
2575                         strncpy(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode)-1);
2576                 if (i->amaflags)
2577                         tmp->amaflags = i->amaflags;
2578                 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
2579                 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
2580                 tmp->adsicpe = i->peeradsicpe;
2581                 tmp->pvt->fixup = iax2_fixup;
2582                 i->owner = tmp;
2583                 i->capability = capability;
2584                 ast_setstate(tmp, state);
2585                 ast_mutex_lock(&usecnt_lock);
2586                 usecnt++;
2587                 ast_mutex_unlock(&usecnt_lock);
2588                 ast_update_use_count();
2589                 if (state != AST_STATE_DOWN) {
2590                         if (ast_pbx_start(tmp)) {
2591                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
2592                                 ast_hangup(tmp);
2593                                 tmp = NULL;
2594                         }
2595                 }
2596         }
2597         return tmp;
2598 }
2599
2600 static unsigned int calc_txpeerstamp(struct iax2_trunk_peer *tpeer, int sampms, struct timeval *tv)
2601 {
2602         unsigned long int mssincetx; /* unsigned to handle overflows */
2603         long int ms, pred;
2604
2605         tpeer->trunkact = *tv;
2606         mssincetx = (tv->tv_sec - tpeer->lasttxtime.tv_sec) * 1000 +
2607                         (1000000 + tv->tv_usec - tpeer->lasttxtime.tv_usec) / 1000 - 1000;
2608         if (mssincetx > 5000 || (!tpeer->txtrunktime.tv_sec && !tpeer->txtrunktime.tv_usec)) {
2609                 /* If it's been at least 5 seconds since the last time we transmitted on this trunk, reset our timers */
2610                 tpeer->txtrunktime.tv_sec = tv->tv_sec;
2611                 tpeer->txtrunktime.tv_usec = tv->tv_usec;
2612                 tpeer->lastsent = 999999;
2613         }
2614         /* Update last transmit time now */
2615         tpeer->lasttxtime.tv_sec = tv->tv_sec;
2616         tpeer->lasttxtime.tv_usec = tv->tv_usec;
2617         
2618         /* Calculate ms offset */
2619         ms = (tv->tv_sec - tpeer->txtrunktime.tv_sec) * 1000 +
2620                 (1000000 + tv->tv_usec - tpeer->txtrunktime.tv_usec) / 1000 - 1000;
2621         /* Predict from last value */
2622         pred = tpeer->lastsent + sampms;
2623         if (abs(ms - pred) < MAX_TIMESTAMP_SKEW)
2624                 ms = pred;
2625         
2626         /* We never send the same timestamp twice, so fudge a little if we must */
2627         if (ms == tpeer->lastsent)
2628                 ms = tpeer->lastsent + 1;
2629         tpeer->lastsent = ms;
2630         return ms;
2631 }
2632
2633 static unsigned int fix_peerts(struct timeval *tv, int callno, unsigned int ts)
2634 {
2635         long ms;        /* NOT unsigned */
2636         if (!iaxs[callno]->rxcore.tv_sec && !iaxs[callno]->rxcore.tv_usec) {
2637                 /* Initialize rxcore time if appropriate */
2638                 gettimeofday(&iaxs[callno]->rxcore, NULL);
2639                 /* Round to nearest 20ms so traces look pretty */
2640                 iaxs[callno]->rxcore.tv_usec -= iaxs[callno]->rxcore.tv_usec % 20000;
2641         }
2642         /* Calculate difference between trunk and channel */
2643         ms = (tv->tv_sec - iaxs[callno]->rxcore.tv_sec) * 1000 + 
2644                 (1000000 + tv->tv_usec - iaxs[callno]->rxcore.tv_usec) / 1000 - 1000;
2645         /* Return as the sum of trunk time and the difference between trunk and real time */
2646         return ms + ts;
2647 }
2648
2649 static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts, struct ast_frame *f)
2650 {
2651         struct timeval tv;
2652         int ms;
2653         int voice = 0;
2654         int genuine = 0;
2655         struct timeval *delivery = NULL;
2656
2657         /* What sort of frame do we have?: voice is self-explanatory
2658            "genuine" means an IAX frame - things like LAGRQ/RP, PING/PONG, ACK
2659            non-genuine frames are CONTROL frames [ringing etc], DTMF
2660            The "genuine" distinction is needed because genuine frames must get a clock-based timestamp,
2661            the others need a timestamp slaved to the voice frames so that they go in sequence
2662         */
2663         if (f) {
2664                 if (f->frametype == AST_FRAME_VOICE) {
2665                         voice = 1;
2666                         delivery = &f->delivery;
2667                 } else if (f->frametype == AST_FRAME_IAX) {
2668                         genuine = 1;
2669                 }
2670         }
2671         if (!p->offset.tv_sec && !p->offset.tv_usec) {
2672                 gettimeofday(&p->offset, NULL);
2673                 /* Round to nearest 20ms for nice looking traces */
2674                 p->offset.tv_usec -= p->offset.tv_usec % 20000;
2675         }
2676         /* If the timestamp is specified, just send it as is */
2677         if (ts)
2678                 return ts;
2679         /* If we have a time that the frame arrived, always use it to make our timestamp */
2680         if (delivery && (delivery->tv_sec || delivery->tv_usec)) {
2681                 ms = (delivery->tv_sec - p->offset.tv_sec) * 1000 +
2682                         (1000000 + delivery->tv_usec - p->offset.tv_usec) / 1000 - 1000;
2683         } else {
2684                 gettimeofday(&tv, NULL);
2685                 ms = (tv.tv_sec - p->offset.tv_sec) * 1000 +
2686                         (1000000 + tv.tv_usec - p->offset.tv_usec) / 1000 - 1000;
2687                 if (ms < 0)
2688                         ms = 0;
2689                 if (voice) {
2690                         /* On a voice frame, use predicted values if appropriate */
2691                         if (abs(ms - p->nextpred) <= MAX_TIMESTAMP_SKEW) {
2692                                 if (!p->nextpred) {
2693                                         p->nextpred = ms; /*f->samples / 8;*/
2694                                         if (p->nextpred <= p->lastsent)
2695                                                 p->nextpred = p->lastsent + 3;
2696                                 }
2697                                 ms = p->nextpred;
2698                         } else
2699                                 p->nextpred = ms;
2700                 } else {
2701                         /* On a dataframe, use last value + 3 (to accomodate jitter buffer shrinking) if appropriate unless
2702                            it's a genuine frame */
2703                         if (genuine) {
2704                                 /* genuine (IAX LAGRQ etc) must keep their clock-based stamps */
2705                                 if (ms <= p->lastsent)
2706                                         ms = p->lastsent + 3;
2707                         } else if (abs(ms - p->lastsent) <= MAX_TIMESTAMP_SKEW) {
2708                                 /* non-genuine frames (!?) (DTMF, CONTROL) should be pulled into the predicted stream stamps */
2709                                 ms = p->lastsent + 3;
2710                         }
2711                 }
2712         }
2713         p->lastsent = ms;
2714         if (voice)
2715                 p->nextpred = p->nextpred + f->samples / 8;
2716 #if 0
2717         printf("TS: %s - %dms\n", voice ? "Audio" : "Control", ms);
2718 #endif  
2719         return ms;
2720 }
2721
2722 #ifdef BRIDGE_OPTIMIZATION
2723 static unsigned int calc_fakestamp(struct chan_iax2_pvt *p1, struct chan_iax2_pvt *p2, unsigned int fakets)
2724 {
2725         int ms;
2726         /* Receive from p1, send to p2 */
2727         
2728         /* Setup rxcore if necessary on outgoing channel */
2729         if (!p1->rxcore.tv_sec && !p1->rxcore.tv_usec)
2730                 gettimeofday(&p1->rxcore, NULL);
2731
2732         /* Setup txcore if necessary on outgoing channel */
2733         if (!p2->offset.tv_sec && !p2->offset.tv_usec)
2734                 gettimeofday(&p2->offset, NULL);
2735         
2736         /* Now, ts is the timestamp of the original packet in the orignal context.
2737            Adding rxcore to it gives us when we would want the packet to be delivered normally.
2738            Subtracting txcore of the outgoing channel gives us what we'd expect */
2739         
2740         ms = (p1->rxcore.tv_sec - p2->offset.tv_sec) * 1000 +
2741                 (1000000 + p1->rxcore.tv_usec - p2->offset.tv_usec) / 1000 - 1000;
2742         fakets += ms;
2743         if (fakets <= p2->lastsent)
2744                 fakets = p2->lastsent + 1;
2745         p2->lastsent = fakets;
2746         return fakets;
2747 }
2748 #endif
2749
2750 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p)
2751 {
2752         /* Returns where in "receive time" we are */
2753         struct timeval tv;
2754         int ms;
2755         /* Setup rxcore if necessary */
2756         if (!p->rxcore.tv_sec && !p->rxcore.tv_usec)
2757                 gettimeofday(&p->rxcore, NULL);
2758
2759         gettimeofday(&tv, NULL);
2760         ms = (tv.tv_sec - p->rxcore.tv_sec) * 1000 +
2761                 (1000000 + tv.tv_usec - p->rxcore.tv_usec) / 1000 - 1000;
2762         return ms;
2763 }
2764
2765 static struct iax2_trunk_peer *find_tpeer(struct sockaddr_in *sin)
2766 {
2767         struct iax2_trunk_peer *tpeer;
2768         char iabuf[INET_ADDRSTRLEN];
2769         /* Finds and locks trunk peer */
2770         ast_mutex_lock(&tpeerlock);
2771         tpeer = tpeers;
2772         while(tpeer) {
2773                 /* We don't lock here because tpeer->addr *never* changes */
2774                 if (!inaddrcmp(&tpeer->addr, sin)) {
2775                         ast_mutex_lock(&tpeer->lock);
2776                         break;
2777                 }
2778                 tpeer = tpeer->next;
2779         }
2780         if (!tpeer) {
2781                 tpeer = malloc(sizeof(struct iax2_trunk_peer));
2782                 if (tpeer) {
2783                         memset(tpeer, 0, sizeof(struct iax2_trunk_peer));
2784                         ast_mutex_init(&tpeer->lock);
2785                         tpeer->lastsent = 9999;
2786                         memcpy(&tpeer->addr, sin, sizeof(tpeer->addr));
2787                         gettimeofday(&tpeer->trunkact, NULL);
2788                         ast_mutex_lock(&tpeer->lock);
2789                         tpeer->next = tpeers;
2790                         tpeers = tpeer;
2791                         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));
2792                 }
2793         }
2794         ast_mutex_unlock(&tpeerlock);
2795         return tpeer;
2796 }
2797
2798 static int iax2_trunk_queue(struct chan_iax2_pvt *pvt, struct ast_frame *f)
2799 {
2800         struct iax2_trunk_peer *tpeer;
2801         void *tmp, *ptr;
2802         struct ast_iax2_meta_trunk_entry *met;
2803         char iabuf[INET_ADDRSTRLEN];
2804         tpeer = find_tpeer(&pvt->addr);
2805         if (tpeer) {
2806                 if (tpeer->trunkdatalen + f->datalen + 4 >= tpeer->trunkdataalloc) {
2807                         /* Need to reallocate space */
2808                         if (tpeer->trunkdataalloc < MAX_TRUNKDATA) {
2809                                 tmp = realloc(tpeer->trunkdata, tpeer->trunkdataalloc + DEFAULT_TRUNKDATA + IAX2_TRUNK_PREFACE);
2810                                 if (tmp) {
2811                                         tpeer->trunkdataalloc += DEFAULT_TRUNKDATA;
2812                                         tpeer->trunkdata = tmp;
2813                                         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);
2814                                 } else {
2815                                         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));
2816                                         ast_mutex_unlock(&tpeer->lock);
2817                                         return -1;
2818                                 }
2819                         } else {
2820                                 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));
2821                                 ast_mutex_unlock(&tpeer->lock);
2822                                 return -1;
2823                         }
2824                 }
2825                 
2826                 /* Append to meta frame */
2827                 ptr = tpeer->trunkdata + IAX2_TRUNK_PREFACE + tpeer->trunkdatalen;
2828                 met = (struct ast_iax2_meta_trunk_entry *)ptr;
2829                 /* Store call number and length in meta header */
2830                 met->callno = htons(pvt->callno);
2831                 met->len = htons(f->datalen);
2832                 /* Advance pointers/decrease length past trunk entry header */
2833                 ptr += sizeof(struct ast_iax2_meta_trunk_entry);
2834                 tpeer->trunkdatalen += sizeof(struct ast_iax2_meta_trunk_entry);
2835                 /* Copy actual trunk data */
2836                 memcpy(ptr, f->data, f->datalen);
2837                 tpeer->trunkdatalen += f->datalen;
2838                 tpeer->calls++;
2839                 ast_mutex_unlock(&tpeer->lock);
2840         }
2841         return 0;
2842 }
2843
2844 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final)
2845 {
2846         /* Queue a packet for delivery on a given private structure.  Use "ts" for
2847            timestamp, or calculate if ts is 0.  Send immediately without retransmission
2848            or delayed, with retransmission */
2849         struct ast_iax2_full_hdr *fh;
2850         struct ast_iax2_mini_hdr *mh;
2851         struct ast_iax2_video_hdr *vh;
2852         struct {
2853                 struct iax_frame fr2;
2854                 unsigned char buffer[4096];
2855         } frb;
2856         struct iax_frame *fr;
2857         int res;
2858         int sendmini=0;
2859         unsigned int lastsent;
2860         unsigned int fts;
2861                 
2862         if (!pvt) {
2863                 ast_log(LOG_WARNING, "No private structure for packet?\n");
2864                 return -1;
2865         }
2866         
2867         lastsent = pvt->lastsent;
2868
2869         /* Calculate actual timestamp */
2870         fts = calc_timestamp(pvt, ts, f);
2871
2872         if ((pvt->trunk || ((fts & 0xFFFF0000L) == (lastsent & 0xFFFF0000L)))
2873                 /* High two bits are the same on timestamp, or sending on a trunk */ &&
2874             (f->frametype == AST_FRAME_VOICE) 
2875                 /* is a voice frame */ &&
2876                 (f->subclass == pvt->svoiceformat) 
2877                 /* is the same type */ ) {
2878                         /* Force immediate rather than delayed transmission */
2879                         now = 1;
2880                         /* Mark that mini-style frame is appropriate */
2881                         sendmini = 1;
2882         }
2883         if (((fts & 0xFFFF8000L) == (lastsent & 0xFFFF8000L)) && 
2884                 (f->frametype == AST_FRAME_VIDEO) &&
2885                 ((f->subclass & ~0x1) == pvt->svideoformat)) {
2886                         now = 1;
2887                         sendmini = 1;
2888         }
2889         /* Allocate an iax_frame */
2890         if (now) {
2891                 fr = &frb.fr2;
2892         } else
2893                 fr = iax_frame_new(DIRECTION_OUTGRESS, f->datalen);
2894         if (!fr) {
2895                 ast_log(LOG_WARNING, "Out of memory\n");
2896                 return -1;
2897         }
2898         /* Copy our prospective frame into our immediate or retransmitted wrapper */
2899         iax_frame_wrap(fr, f);
2900
2901         fr->ts = fts;
2902         fr->callno = pvt->callno;
2903         fr->transfer = transfer;
2904         fr->final = final;
2905         if (!sendmini) {
2906                 /* We need a full frame */
2907                 if (seqno > -1)
2908                         fr->oseqno = seqno;
2909                 else
2910                         fr->oseqno = pvt->oseqno++;
2911                 fr->iseqno = pvt->iseqno;
2912                 fh = (struct ast_iax2_full_hdr *)(fr->af.data - sizeof(struct ast_iax2_full_hdr));
2913                 fh->scallno = htons(fr->callno | IAX_FLAG_FULL);
2914                 fh->ts = htonl(fr->ts);
2915                 fh->oseqno = fr->oseqno;
2916                 if (transfer) {
2917                         fh->iseqno = 0;
2918                 } else
2919                         fh->iseqno = fr->iseqno;
2920                 /* Keep track of the last thing we've acknowledged */
2921                 if (!transfer)
2922                         pvt->aseqno = fr->iseqno;
2923                 fh->type = fr->af.frametype & 0xFF;
2924                 if (fr->af.frametype == AST_FRAME_VIDEO)
2925                         fh->csub = compress_subclass(fr->af.subclass & ~0x1) | ((fr->af.subclass & 0x1) << 6);
2926                 else
2927                         fh->csub = compress_subclass(fr->af.subclass);
2928                 if (transfer) {
2929                         fr->dcallno = pvt->transfercallno;
2930                 } else
2931                         fr->dcallno = pvt->peercallno;
2932                 fh->dcallno = htons(fr->dcallno);
2933                 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_full_hdr);
2934                 fr->data = fh;
2935                 fr->retries = 0;
2936                 /* Retry after 2x the ping time has passed */
2937                 fr->retrytime = pvt->pingtime * 2;
2938                 if (fr->retrytime < MIN_RETRY_TIME)
2939                         fr->retrytime = MIN_RETRY_TIME;
2940                 if (fr->retrytime > MAX_RETRY_TIME)
2941                         fr->retrytime = MAX_RETRY_TIME;
2942                 /* Acks' don't get retried */
2943                 if ((f->frametype == AST_FRAME_IAX) && (f->subclass == IAX_COMMAND_ACK))
2944                         fr->retries = -1;
2945                 else if (f->frametype == AST_FRAME_VOICE)
2946                         pvt->svoiceformat = f->subclass;
2947                 else if (f->frametype == AST_FRAME_VIDEO)
2948                         pvt->svideoformat = f->subclass & ~0x1;
2949                 if (now) {
2950                         res = send_packet(fr);
2951                 } else
2952                         res = iax2_transmit(fr);
2953         } else {
2954                 if (pvt->trunk) {
2955                         iax2_trunk_queue(pvt, &fr->af);
2956                         res = 0;
2957                 } else if (fr->af.frametype == AST_FRAME_VIDEO) {
2958                         /* Video frame have no sequence number */
2959                         fr->oseqno = -1;
2960                         fr->iseqno = -1;
2961                         vh = (struct ast_iax2_video_hdr *)(fr->af.data - sizeof(struct ast_iax2_video_hdr));
2962                         vh->zeros = 0;
2963                         vh->callno = htons(0x8000 | fr->callno);
2964                         vh->ts = htons((fr->ts & 0x7FFF) | (fr->af.subclass & 0x1 ? 0x8000 : 0));
2965                         fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_video_hdr);
2966                         fr->data = vh;
2967                         fr->retries = -1;
2968                         res = send_packet(fr);                  
2969                 } else {
2970                         /* Mini-frames have no sequence number */
2971                         fr->oseqno = -1;
2972                         fr->iseqno = -1;
2973                         /* Mini frame will do */
2974                         mh = (struct ast_iax2_mini_hdr *)(fr->af.data - sizeof(struct ast_iax2_mini_hdr));
2975                         mh->callno = htons(fr->callno);
2976                         mh->ts = htons(fr->ts & 0xFFFF);
2977                         fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_mini_hdr);
2978                         fr->data = mh;
2979                         fr->retries = -1;
2980                         res = send_packet(fr);
2981                 }
2982         }
2983         return res;
2984 }
2985
2986
2987
2988 static int iax2_show_users(int fd, int argc, char *argv[])
2989 {
2990 #define FORMAT "%-15.15s  %-20.20s  %-15.15s  %-15.15s  %-5.5s\n"
2991 #define FORMAT2 "%-15.15s  %-20.20s  %-15.15d  %-15.15s  %-5.5s\n"
2992         struct iax2_user *user;
2993         char auth[90];
2994         if (argc != 3) 
2995                 return RESULT_SHOWUSAGE;
2996         ast_mutex_lock(&userl.lock);
2997         ast_cli(fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C");
2998         for(user=userl.users;user;user=user->next) {
2999                 if (!ast_strlen_zero(user->secret)) {
3000                         strncpy(auth,user->secret,sizeof(auth)-1);
3001                 } else if (!ast_strlen_zero(user->inkeys)) {
3002                         sprintf(auth,"Key: %-15.15s ",user->inkeys);
3003                 } else
3004                         strcpy(auth,"-no secret-");
3005                 ast_cli(fd, FORMAT2, user->name, auth, user->authmethods, 
3006                                 user->contexts ? user->contexts->context : context,
3007                                 user->ha ? "Yes" : "No");
3008         }
3009         ast_mutex_unlock(&userl.lock);
3010         return RESULT_SUCCESS;
3011 #undef FORMAT
3012 #undef FORMAT2
3013 }
3014
3015 static int iax2_show_peers(int fd, int argc, char *argv[])
3016 {
3017 #define FORMAT2 "%-15.15s  %-15.15s %s  %-15.15s  %-8s  %-10s\n"
3018 #define FORMAT "%-15.15s  %-15.15s %s  %-15.15s  %-5d%s  %-10s\n"
3019         struct iax2_peer *peer;
3020         char name[256] = "";
3021         char iabuf[INET_ADDRSTRLEN];
3022         int registeredonly=0;
3023         if ((argc != 3) && (argc != 4) && (argc != 5))
3024                 return RESULT_SHOWUSAGE;
3025         if ((argc == 4)) {
3026                 if (!strcasecmp(argv[3], "registered")) {
3027                         registeredonly = 1;
3028                 } else
3029                         return RESULT_SHOWUSAGE;
3030         }
3031         ast_mutex_lock(&peerl.lock);
3032         ast_cli(fd, FORMAT2, "Name/Username", "Host", "   ", "Mask", "Port", "Status");