2 * Asterisk -- A telephony toolkit for Linux.
4 * Implementation of Inter-Asterisk eXchange Version 2
6 * Copyright (C) 2003 - 2005, Digium, Inc.
8 * Mark Spencer <markster@digium.com>
10 * This program is free software, distributed under the terms of
11 * the GNU General Public License
14 #include <asterisk/lock.h>
15 #include <asterisk/frame.h>
16 #include <asterisk/channel.h>
17 #include <asterisk/logger.h>
18 #include <asterisk/module.h>
19 #include <asterisk/pbx.h>
20 #include <asterisk/sched.h>
21 #include <asterisk/io.h>
22 #include <asterisk/config.h>
23 #include <asterisk/options.h>
24 #include <asterisk/cli.h>
25 #include <asterisk/translate.h>
26 #include <asterisk/md5.h>
27 #include <asterisk/cdr.h>
28 #include <asterisk/crypto.h>
29 #include <asterisk/acl.h>
30 #include <asterisk/manager.h>
31 #include <asterisk/callerid.h>
32 #include <asterisk/app.h>
33 #include <asterisk/astdb.h>
34 #include <asterisk/musiconhold.h>
35 #include <asterisk/features.h>
36 #include <asterisk/utils.h>
37 #include <asterisk/causes.h>
38 #include <asterisk/localtime.h>
39 #include <asterisk/aes.h>
41 #include <arpa/inet.h>
43 #include <sys/socket.h>
44 #include <netinet/in.h>
45 #include <netinet/in_systm.h>
46 #include <netinet/ip.h>
48 #include <sys/signal.h>
57 #include <sys/types.h>
61 #include <sys/ioctl.h>
63 #include <linux/zaptel.h>
66 #endif /* __linux__ */
69 #include "iax2-parser.h"
70 #include "iax2-provision.h"
71 #include "../astconf.h"
74 #define IPTOS_MINCOST 0x02
78 * Uncomment to try experimental IAX bridge optimization,
79 * designed to reduce latency when IAX calls cannot
83 #define BRIDGE_OPTIMIZATION
85 #define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
86 #define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
88 #define DEFAULT_RETRY_TIME 1000
89 #define MEMORY_SIZE 100
90 #define DEFAULT_DROP 3
91 /* Flag to use with trunk calls, keeping these calls high up. It halves our effective use
92 but keeps the division between trunked and non-trunked better. */
93 #define TRUNK_CALL_START 0x4000
97 #define MIN_REUSE_TIME 60 /* Don't reuse a call number within 60 seconds */
99 /* Sample over last 100 units to determine historic jitter */
102 static struct ast_codec_pref prefs;
104 static const char desc[] = "Inter Asterisk eXchange (Ver 2)";
105 static const char tdesc[] = "Inter Asterisk eXchange Driver (Ver 2)";
106 static const char channeltype[] = "IAX2";
108 static char context[80] = "default";
110 static char language[MAX_LANGUAGE] = "";
111 static char regcontext[AST_MAX_EXTENSION] = "";
113 static int max_retries = 4;
114 static int ping_time = 20;
115 static int lagrq_time = 10;
116 static int maxtrunkcall = TRUNK_CALL_START;
117 static int maxnontrunkcall = 1;
118 static int maxjitterbuffer=1000;
119 static int jittershrinkrate=2;
120 static int trunkfreq = 20;
121 static int authdebug = 1;
122 static int autokill = 0;
123 static int iaxcompat = 0;
125 static int iaxdefaultdpcache=10 * 60; /* Cache dialplan entries for 10 minutes by default */
127 static int iaxdefaulttimeout = 5; /* Default to wait no more than 5 seconds for a reply to come back */
131 static int expirey = IAX_DEFAULT_REG_EXPIRE;
133 static int timingfd = -1; /* Timing file descriptor */
135 static struct ast_netsock_list netsock;
136 static int defaultsockfd = -1;
139 AST_MUTEX_DEFINE_STATIC(usecnt_lock);
141 int (*iax2_regfunk)(char *username, int onoff) = NULL;
144 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
146 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
147 ~AST_FORMAT_SLINEAR & \
151 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
155 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
159 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
160 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
161 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
163 static struct io_context *io;
164 static struct sched_context *sched;
166 static int iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
168 static int iax2_dropcount = DEFAULT_DROP;
170 static int iaxdebug = 0;
172 static int iaxtrunkdebug = 0;
174 static char accountcode[20];
175 static int amaflags = 0;
176 static int delayreject = 0;
177 static int iax2_encryption = 0;
179 static struct ast_flags globalflags = {0};
181 static pthread_t netthreadid = AST_PTHREADT_NULL;
183 #define IAX_STATE_STARTED (1 << 0)
184 #define IAX_STATE_AUTHENTICATED (1 << 1)
185 #define IAX_STATE_TBD (1 << 2)
187 struct iax2_context {
188 char context[AST_MAX_EXTENSION];
189 struct iax2_context *next;
192 #define IAX_HASCALLERID (1 << 0) /* CallerID has been specified */
193 #define IAX_DELME (1 << 1) /* Needs to be deleted */
194 #define IAX_TEMPONLY (1 << 2) /* Temporary (realtime) */
195 #define IAX_TRUNK (1 << 3) /* Treat as a trunk */
196 #define IAX_NOTRANSFER (1 << 4) /* Don't native bridge */
197 #define IAX_USEJITTERBUF (1 << 5) /* Use jitter buffer */
198 #define IAX_DYNAMIC (1 << 6) /* dynamic peer */
199 #define IAX_SENDANI (1 << 7) /* Send ANI along with CallerID */
200 #define IAX_MESSAGEDETAIL (1 << 8) /* Show exact numbers */
201 #define IAX_ALREADYGONE (1 << 9) /* Already disconnected */
202 #define IAX_PROVISION (1 << 10) /* This is a provisioning request */
203 #define IAX_QUELCH (1 << 11) /* Whether or not we quelch audio */
204 #define IAX_ENCRYPTED (1 << 12) /* Whether we should assume encrypted tx/rx */
205 #define IAX_KEYPOPULATED (1 << 13) /* Whether we have a key populated */
206 #define IAX_CODEC_USER_FIRST (1 << 14) /* are we willing to let the other guy choose the codec? */
207 #define IAX_CODEC_NOPREFS (1 << 15) /* Force old behaviour by turning off prefs */
208 #define IAX_CODEC_NOCAP (1 << 16) /* only consider requested format and ignore capabilities*/
209 #define IAX_RTCACHEFRIENDS (1 << 17) /* let realtime stay till your reload */
210 #define IAX_RTNOUPDATE (1 << 18) /* Don't send a realtime update */
211 #define IAX_RTAUTOCLEAR (1 << 19) /* erase me on expire */
213 static int global_rtautoclear = 120;
215 static struct iax2_peer *realtime_peer(const char *peername);
216 static int reload_config(void);
224 char accountcode[20];
225 char inkeys[80]; /* Key(s) this user can use to authenticate to us */
226 char language[MAX_LANGUAGE];
230 char cid_num[AST_MAX_EXTENSION];
231 char cid_name[AST_MAX_EXTENSION];
232 struct ast_codec_pref prefs;
234 struct iax2_context *contexts;
235 struct iax2_user *next;
236 struct ast_variable *vars;
244 char outkey[80]; /* What key we use to talk to this peer */
245 char context[AST_MAX_EXTENSION]; /* For transfers only */
246 char regexten[AST_MAX_EXTENSION]; /* Extension to register (if regcontext is used) */
247 char peercontext[AST_MAX_EXTENSION]; /* Context to pass to peer */
248 char mailbox[AST_MAX_EXTENSION]; /* Mailbox */
249 struct ast_codec_pref prefs;
250 struct sockaddr_in addr;
252 int sockfd; /* Socket to use for transmission */
256 /* Dynamic Registration fields */
257 struct sockaddr_in defaddr; /* Default address if there is one */
258 int authmethods; /* Authentication methods (IAX_AUTH_*) */
259 int encmethods; /* Encryption methods (IAX_ENCRYPT_*) */
260 char inkeys[80]; /* Key(s) this peer can use to authenticate to us */
262 /* Suggested caller id if registering */
263 char cid_num[AST_MAX_EXTENSION]; /* Default context (for transfer really) */
264 char cid_name[AST_MAX_EXTENSION]; /* Default context (for transfer really) */
266 int expire; /* Schedule entry for expirey */
267 int expirey; /* How soon to expire */
268 int capability; /* Capability */
269 char zonetag[80]; /* Time Zone */
272 int callno; /* Call number of POKE request */
273 int pokeexpire; /* When to expire poke */
274 int lastms; /* How long last response took (in ms), or -1 for no response */
275 int maxms; /* Max ms we will accept for the host to be up, 0 to not monitor */
278 struct iax2_peer *next;
281 #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
283 static struct iax2_trunk_peer {
286 struct sockaddr_in addr;
287 struct timeval txtrunktime; /* Transmit trunktime */
288 struct timeval rxtrunktime; /* Receive trunktime */
289 struct timeval lasttxtime; /* Last transmitted trunktime */
290 struct timeval trunkact; /* Last trunk activity */
291 unsigned int lastsent; /* Last sent time */
292 /* Trunk data and length */
293 unsigned char *trunkdata;
294 unsigned int trunkdatalen;
295 unsigned int trunkdataalloc;
296 struct iax2_trunk_peer *next;
301 AST_MUTEX_DEFINE_STATIC(tpeerlock);
303 struct iax_firmware {
304 struct iax_firmware *next;
308 struct ast_iax2_firmware_header *fwh;
312 #define REG_STATE_UNREGISTERED 0
313 #define REG_STATE_REGSENT 1
314 #define REG_STATE_AUTHSENT 2
315 #define REG_STATE_REGISTERED 3
316 #define REG_STATE_REJECTED 4
317 #define REG_STATE_TIMEOUT 5
318 #define REG_STATE_NOAUTH 6
320 #define TRANSFER_NONE 0
321 #define TRANSFER_BEGIN 1
322 #define TRANSFER_READY 2
323 #define TRANSFER_RELEASED 3
324 #define TRANSFER_PASSTHROUGH 4
326 struct iax2_registry {
327 struct sockaddr_in addr; /* Who we connect to for registration purposes */
329 char secret[80]; /* Password or key name in []'s */
331 int expire; /* Sched ID of expiration */
332 int refresh; /* How often to refresh */
334 int messages; /* Message count */
335 int callno; /* Associated call number if applicable */
336 struct sockaddr_in us; /* Who the server thinks we are */
337 struct iax2_registry *next;
340 static struct iax2_registry *registrations;
342 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
343 #define MIN_RETRY_TIME 100
344 #define MAX_RETRY_TIME 10000
346 #define MAX_JITTER_BUFFER 50
347 #define MIN_JITTER_BUFFER 10
349 #define DEFAULT_TRUNKDATA 640 * 10 /* 40ms, uncompressed linear * 10 channels */
350 #define MAX_TRUNKDATA 640 * 200 /* 40ms, uncompressed linear * 200 channels */
352 #define MAX_TIMESTAMP_SKEW 640
354 /* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
355 #define TS_GAP_FOR_JB_RESYNC 5000
357 /* If we have more than this much excess real jitter buffer, shrink it. */
358 static int max_jitter_buffer = MAX_JITTER_BUFFER;
359 /* If we have less than this much excess real jitter buffer, enlarge it. */
360 static int min_jitter_buffer = MIN_JITTER_BUFFER;
372 struct chan_iax2_pvt {
373 /* Socket to send/receive on for this call */
375 /* Last received voice format */
377 /* Last received voice format */
379 /* Last sent voice format */
381 /* Last sent video format */
383 /* What we are capable of sending */
385 /* Last received timestamp */
387 /* Last sent timestamp - never send the same timestamp twice in a single call */
388 unsigned int lastsent;
389 /* Next outgoing timestamp if everything is good */
390 unsigned int nextpred;
391 /* True if the last voice we transmitted was not silence/CNG */
394 unsigned int pingtime;
395 /* Max time for initial response */
398 struct sockaddr_in addr;
399 struct ast_codec_pref prefs;
400 /* Our call number */
401 unsigned short callno;
403 unsigned short peercallno;
404 /* Peer selected format */
406 /* Peer capability */
408 /* timeval that we base our transmission on */
409 struct timeval offset;
410 /* timeval that we base our delivery on */
411 struct timeval rxcore;
412 /* Historical delivery time */
413 int history[MEMORY_SIZE];
414 /* Current base jitterbuffer */
416 /* Current jitter measure */
418 /* Historic jitter value */
422 /* Error, as discovered by the manager */
424 /* Owner if we have one */
425 struct ast_channel *owner;
426 /* What's our state? */
428 /* Expirey (optional) */
430 /* Next outgoing sequence number */
431 unsigned char oseqno;
432 /* Next sequence number they have not yet acknowledged */
433 unsigned char rseqno;
434 /* Next incoming sequence number */
435 unsigned char iseqno;
436 /* Last incoming sequence number we have acknowledged */
437 unsigned char aseqno;
440 /* Default Context */
442 /* Caller ID if available */
445 /* Hidden Caller ID (i.e. ANI) if appropriate */
449 /* Requested Extension */
450 char exten[AST_MAX_EXTENSION];
451 /* Expected Username */
453 /* Expected Secret */
455 /* permitted authentication methods */
457 /* permitted encryption methods */
461 /* Public keys permitted keys for incoming authentication */
463 /* Private key for outgoing authentication */
465 /* Encryption AES-128 Key */
467 /* Decryption AES-128 Key */
469 /* 32 bytes of semi-random data */
471 /* Preferred language */
472 char language[MAX_LANGUAGE];
473 /* Hostname/peername for naming purposes */
475 /* Associated registry */
476 struct iax2_registry *reg;
477 /* Associated peer for poking */
478 struct iax2_peer *peerpoke;
482 /* Transferring status */
484 /* Transfer identifier */
486 /* Who we are IAX transfering to */
487 struct sockaddr_in transfer;
488 /* What's the new call number for the transfer */
489 unsigned short transfercallno;
490 /* Transfer decrypt AES-128 Key */
491 aes_encrypt_ctx tdcx;
493 /* Status of knowledge of peer ADSI capability */
496 /* Who we are bridged to */
497 unsigned short bridgecallno;
498 unsigned int bridgesfmt;
499 struct ast_trans_pvt *bridgetrans;
501 int pingid; /* Transmit PING request */
502 int lagid; /* Retransmit lag request */
503 int autoid; /* Auto hangup for Dialplan requestor */
504 int authid; /* Authentication rejection ID */
505 int authfail; /* Reason to report failure */
506 int initid; /* Initial peer auto-congest ID (based on qualified peers) */
510 char dproot[AST_MAX_EXTENSION];
511 char accountcode[20];
513 struct iax2_dpcache *dpentries;
514 struct ast_variable *vars;
515 /* last received remote rr */
516 struct iax_rr remote_rr;
517 /* Current base time: (just for stats) */
519 /* Dropped frame count: (just for stats) */
521 /* received frame count: (just for stats) */
525 static struct ast_iax2_queue {
526 struct iax_frame *head;
527 struct iax_frame *tail;
532 static struct ast_user_list {
533 struct iax2_user *users;
537 static struct ast_peer_list {
538 struct iax2_peer *peers;
542 static struct ast_firmware_list {
543 struct iax_firmware *wares;
547 /* Extension exists */
548 #define CACHE_FLAG_EXISTS (1 << 0)
549 /* Extension is non-existant */
550 #define CACHE_FLAG_NONEXISTANT (1 << 1)
551 /* Extension can exist */
552 #define CACHE_FLAG_CANEXIST (1 << 2)
553 /* Waiting to hear back response */
554 #define CACHE_FLAG_PENDING (1 << 3)
556 #define CACHE_FLAG_TIMEOUT (1 << 4)
557 /* Request transmitted */
558 #define CACHE_FLAG_TRANSMITTED (1 << 5)
560 #define CACHE_FLAG_UNKNOWN (1 << 6)
562 #define CACHE_FLAG_MATCHMORE (1 << 7)
564 static struct iax2_dpcache {
565 char peercontext[AST_MAX_EXTENSION];
566 char exten[AST_MAX_EXTENSION];
568 struct timeval expirey;
570 unsigned short callno;
572 struct iax2_dpcache *next;
573 struct iax2_dpcache *peer; /* For linking in peers */
576 AST_MUTEX_DEFINE_STATIC(dpcache_lock);
578 static void destroy_peer(struct iax2_peer *peer);
580 static void iax_debug_output(const char *data)
583 ast_verbose("%s", data);
586 static void iax_error_output(const char *data)
588 ast_log(LOG_WARNING, "%s", data);
591 /* XXX We probably should use a mutex when working with this XXX */
592 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS];
593 static ast_mutex_t iaxsl[IAX_MAX_CALLS];
594 static struct timeval lastused[IAX_MAX_CALLS];
597 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, char *, int, int);
598 static int send_command_locked(unsigned short callno, char, int, unsigned int, char *, int, int);
599 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, char *, int, int);
600 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, char *, int, int);
601 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, char *, int);
602 static struct iax2_user *build_user(const char *name, struct ast_variable *v, int temponly);
603 static void destroy_user(struct iax2_user *user);
604 static int expire_registry(void *data);
605 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
606 static int iax2_do_register(struct iax2_registry *reg);
607 static void prune_peers(void);
608 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
609 static int iax2_provision(struct sockaddr_in *end, char *dest, const char *template, int force);
611 static struct ast_channel *iax2_request(const char *type, int format, void *data, int *cause);
612 static int iax2_devicestate(void *data);
613 static int iax2_digit(struct ast_channel *c, char digit);
614 static int iax2_sendtext(struct ast_channel *c, char *text);
615 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
616 static int iax2_sendhtml(struct ast_channel *c, int subclass, char *data, int datalen);
617 static int iax2_call(struct ast_channel *c, char *dest, int timeout);
618 static int iax2_hangup(struct ast_channel *c);
619 static int iax2_answer(struct ast_channel *c);
620 static struct ast_frame *iax2_read(struct ast_channel *c);
621 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
622 static int iax2_indicate(struct ast_channel *c, int condition);
623 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
624 static int iax2_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc);
625 static int iax2_transfer(struct ast_channel *c, char *dest);
626 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
628 static const struct ast_channel_tech iax2_tech = {
630 .description = tdesc,
631 .capabilities = IAX_CAPABILITY_FULLBANDWIDTH,
632 .requester = iax2_request,
633 .devicestate = iax2_devicestate,
634 .send_digit = iax2_digit,
635 .send_text = iax2_sendtext,
636 .send_image = iax2_sendimage,
637 .send_html = iax2_sendhtml,
639 .hangup = iax2_hangup,
640 .answer = iax2_answer,
643 .write_video = iax2_write,
644 .indicate = iax2_indicate,
645 .setoption = iax2_setoption,
646 .bridge = iax2_bridge,
647 .transfer = iax2_transfer,
651 static int send_ping(void *data)
653 int callno = (long)data;
654 /* Ping only if it's real, not if it's bridged */
656 #ifdef BRIDGE_OPTIMIZATION
657 if (!iaxs[callno]->bridgecallno)
659 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
665 static int get_encrypt_methods(const char *s)
668 if (!strcasecmp(s, "aes128"))
669 e = IAX_ENCRYPT_AES128;
670 else if (ast_true(s))
671 e = IAX_ENCRYPT_AES128;
677 static int send_lagrq(void *data)
679 int callno = (long)data;
680 /* Ping only if it's real not if it's bridged */
682 #ifdef BRIDGE_OPTIMIZATION
683 if (!iaxs[callno]->bridgecallno)
685 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
691 static unsigned char compress_subclass(int subclass)
695 /* If it's 128 or smaller, just return it */
696 if (subclass < IAX_FLAG_SC_LOG)
698 /* Otherwise find its power */
699 for (x = 0; x < IAX_MAX_SHIFT; x++) {
700 if (subclass & (1 << x)) {
702 ast_log(LOG_WARNING, "Can't compress subclass %d\n", subclass);
708 return power | IAX_FLAG_SC_LOG;
711 static int uncompress_subclass(unsigned char csub)
713 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
714 if (csub & IAX_FLAG_SC_LOG) {
715 /* special case for 'compressed' -1 */
719 return 1 << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
725 static struct iax2_peer *find_peer(const char *name, int realtime)
727 struct iax2_peer *peer;
728 ast_mutex_lock(&peerl.lock);
729 for(peer = peerl.peers; peer; peer = peer->next) {
730 if (!strcasecmp(peer->name, name)) {
734 ast_mutex_unlock(&peerl.lock);
735 if(!peer && realtime)
736 peer = realtime_peer(name);
740 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len, int lockpeer)
742 struct iax2_peer *peer;
745 ast_mutex_lock(&peerl.lock);
748 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
749 (peer->addr.sin_port == sin.sin_port)) {
750 strncpy(host, peer->name, len-1);
757 ast_mutex_unlock(&peerl.lock);
761 static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, int lockpeer, const char *host)
763 struct chan_iax2_pvt *tmp;
764 tmp = malloc(sizeof(struct chan_iax2_pvt));
766 memset(tmp, 0, sizeof(struct chan_iax2_pvt));
770 tmp->transfercallno = 0;
771 tmp->bridgecallno = 0;
777 /* strncpy(tmp->context, context, sizeof(tmp->context)-1); */
778 strncpy(tmp->exten, "s", sizeof(tmp->exten)-1);
779 strncpy(tmp->host, host, sizeof(tmp->host)-1);
784 static int get_samples(struct ast_frame *f)
787 switch(f->subclass) {
788 case AST_FORMAT_SPEEX:
789 samples = 160; /* XXX Not necessarily true XXX */
791 case AST_FORMAT_G723_1:
792 samples = 240 /* XXX Not necessarily true XXX */;
794 case AST_FORMAT_ILBC:
795 samples = 240 * (f->datalen / 50);
798 samples = 160 * (f->datalen / 33);
800 case AST_FORMAT_G729A:
801 samples = 160 * (f->datalen / 20);
803 case AST_FORMAT_SLINEAR:
804 samples = f->datalen / 2;
806 case AST_FORMAT_LPC10:
808 samples += (((char *)(f->data))[7] & 0x1) * 8;
810 case AST_FORMAT_ULAW:
811 samples = f->datalen;
813 case AST_FORMAT_ALAW:
814 samples = f->datalen;
816 case AST_FORMAT_ADPCM:
817 case AST_FORMAT_G726:
818 samples = f->datalen *2;
821 ast_log(LOG_WARNING, "Don't know how to calculate samples on %d packets\n", f->subclass);
826 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
828 /* Malloc() a copy of a frame */
829 struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen);
831 memcpy(new, fr, sizeof(struct iax_frame));
832 iax_frame_wrap(new, &fr->af);
835 new->direction = DIRECTION_INGRESS;
841 #define NEW_PREVENT 0
845 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, struct chan_iax2_pvt *cur)
847 if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
848 (cur->addr.sin_port == sin->sin_port)) {
849 /* This is the main host */
850 if ((cur->peercallno == callno) ||
851 ((dcallno == cur->callno) && !cur->peercallno)) {
852 /* That's us. Be sure we keep track of the peer call number */
856 if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
857 (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
858 /* We're transferring */
859 if (dcallno == cur->callno)
865 static void update_max_trunk(void)
867 int max = TRUNK_CALL_START;
869 /* XXX Prolly don't need locks here XXX */
870 for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
876 ast_log(LOG_DEBUG, "New max trunk callno is %d\n", max);
879 static void update_max_nontrunk(void)
883 /* XXX Prolly don't need locks here XXX */
884 for (x=1;x<TRUNK_CALL_START - 1; x++) {
888 maxnontrunkcall = max;
890 ast_log(LOG_DEBUG, "New max nontrunk callno is %d\n", max);
893 static int make_trunk(unsigned short callno, int locked)
898 if (iaxs[callno]->oseqno) {
899 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
902 if (callno & TRUNK_CALL_START) {
903 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
906 gettimeofday(&now, NULL);
907 for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
908 ast_mutex_lock(&iaxsl[x]);
909 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) {
910 iaxs[x] = iaxs[callno];
913 /* Update the two timers that should have been started */
914 if (iaxs[x]->pingid > -1)
915 ast_sched_del(sched, iaxs[x]->pingid);
916 if (iaxs[x]->lagid > -1)
917 ast_sched_del(sched, iaxs[x]->lagid);
918 iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
919 iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
921 ast_mutex_unlock(&iaxsl[callno]);
924 ast_mutex_unlock(&iaxsl[x]);
927 ast_mutex_unlock(&iaxsl[x]);
929 if (x >= IAX_MAX_CALLS - 1) {
930 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
933 ast_log(LOG_DEBUG, "Made call %d into trunk call %d\n", callno, x);
934 /* We move this call from a non-trunked to a trunked call */
936 update_max_nontrunk();
940 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int lockpeer, int sockfd)
945 char iabuf[INET_ADDRSTRLEN];
947 if (new <= NEW_ALLOW) {
948 /* Look for an existing connection first */
949 for (x=1;(res < 1) && (x<maxnontrunkcall);x++) {
950 ast_mutex_lock(&iaxsl[x]);
952 /* Look for an exact match */
953 if (match(sin, callno, dcallno, iaxs[x])) {
957 ast_mutex_unlock(&iaxsl[x]);
959 for (x=TRUNK_CALL_START;(res < 1) && (x<maxtrunkcall);x++) {
960 ast_mutex_lock(&iaxsl[x]);
962 /* Look for an exact match */
963 if (match(sin, callno, dcallno, iaxs[x])) {
967 ast_mutex_unlock(&iaxsl[x]);
970 if ((res < 1) && (new >= NEW_ALLOW)) {
971 if (!iax2_getpeername(*sin, host, sizeof(host), lockpeer))
972 snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr), ntohs(sin->sin_port));
973 gettimeofday(&now, NULL);
974 for (x=1;x<TRUNK_CALL_START;x++) {
975 /* Find first unused call number that hasn't been used in a while */
976 ast_mutex_lock(&iaxsl[x]);
977 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) break;
978 ast_mutex_unlock(&iaxsl[x]);
980 /* We've still got lock held if we found a spot */
981 if (x >= TRUNK_CALL_START) {
982 ast_log(LOG_WARNING, "No more space\n");
985 iaxs[x] = new_iax(sin, lockpeer, host);
986 update_max_nontrunk();
989 ast_log(LOG_DEBUG, "Creating new call structure %d\n", x);
990 iaxs[x]->sockfd = sockfd;
991 iaxs[x]->addr.sin_port = sin->sin_port;
992 iaxs[x]->addr.sin_family = sin->sin_family;
993 iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
994 iaxs[x]->peercallno = callno;
996 iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
997 iaxs[x]->expirey = expirey;
998 iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
999 iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
1000 iaxs[x]->amaflags = amaflags;
1001 ast_copy_flags(iaxs[x], (&globalflags), IAX_NOTRANSFER | IAX_USEJITTERBUF);
1002 strncpy(iaxs[x]->accountcode, accountcode, sizeof(iaxs[x]->accountcode)-1);
1004 ast_log(LOG_WARNING, "Out of resources\n");
1005 ast_mutex_unlock(&iaxsl[x]);
1008 ast_mutex_unlock(&iaxsl[x]);
1014 static void iax2_frame_free(struct iax_frame *fr)
1016 if (fr->retrans > -1)
1017 ast_sched_del(sched, fr->retrans);
1021 static int iax2_queue_frame(int callno, struct ast_frame *f)
1023 /* Assumes lock for callno is already held... */
1025 if (iaxs[callno] && iaxs[callno]->owner) {
1026 if (ast_mutex_trylock(&iaxs[callno]->owner->lock)) {
1027 /* Avoid deadlock by pausing and trying again */
1028 ast_mutex_unlock(&iaxsl[callno]);
1030 ast_mutex_lock(&iaxsl[callno]);
1032 ast_queue_frame(iaxs[callno]->owner, f);
1033 ast_mutex_unlock(&iaxs[callno]->owner->lock);
1042 static void destroy_firmware(struct iax_firmware *cur)
1044 /* Close firmware */
1046 munmap(cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh)));
1052 static int try_firmware(char *s)
1055 struct iax_firmware *cur;
1060 struct ast_iax2_firmware_header *fwh, fwh2;
1061 struct MD5Context md5;
1062 unsigned char sum[16];
1063 unsigned char buf[1024];
1067 s2 = alloca(strlen(s) + 100);
1069 ast_log(LOG_WARNING, "Alloca failed!\n");
1072 last = strrchr(s, '/');
1077 snprintf(s2, strlen(s) + 100, "/var/tmp/%s-%ld", last, (unsigned long)rand());
1078 res = stat(s, &stbuf);
1080 ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno));
1083 /* Make sure it's not a directory */
1084 if (S_ISDIR(stbuf.st_mode))
1086 ifd = open(s, O_RDONLY);
1088 ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
1091 fd = open(s2, O_RDWR | O_CREAT | O_EXCL);
1093 ast_log(LOG_WARNING, "Cannot open '%s' for writing: %s\n", s2, strerror(errno));
1097 /* Unlink our newly created file */
1100 /* Now copy the firmware into it */
1101 len = stbuf.st_size;
1104 if (chunk > sizeof(buf))
1105 chunk = sizeof(buf);
1106 res = read(ifd, buf, chunk);
1108 ast_log(LOG_WARNING, "Only read %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1113 res = write(fd, buf, chunk);
1115 ast_log(LOG_WARNING, "Only write %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1123 /* Return to the beginning */
1124 lseek(fd, 0, SEEK_SET);
1125 if ((res = read(fd, &fwh2, sizeof(fwh2))) != sizeof(fwh2)) {
1126 ast_log(LOG_WARNING, "Unable to read firmware header in '%s'\n", s);
1130 if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) {
1131 ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s);
1135 if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) {
1136 ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s);
1140 if (fwh2.devname[sizeof(fwh2.devname) - 1] || ast_strlen_zero(fwh2.devname)) {
1141 ast_log(LOG_WARNING, "No or invalid device type specified for '%s'\n", s);
1145 fwh = mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
1147 ast_log(LOG_WARNING, "mmap failed: %s\n", strerror(errno));
1152 MD5Update(&md5, fwh->data, ntohl(fwh->datalen));
1153 MD5Final(sum, &md5);
1154 if (memcmp(sum, fwh->chksum, sizeof(sum))) {
1155 ast_log(LOG_WARNING, "Firmware file '%s' fails checksum\n", s);
1156 munmap(fwh, stbuf.st_size);
1162 if (!strcmp(cur->fwh->devname, fwh->devname)) {
1163 /* Found a candidate */
1164 if (cur->dead || (ntohs(cur->fwh->version) < ntohs(fwh->version)))
1165 /* The version we have on loaded is older, load this one instead */
1167 /* This version is no newer than what we have. Don't worry about it.
1168 We'll consider it a proper load anyhow though */
1169 munmap(fwh, stbuf.st_size);
1176 /* Allocate a new one and link it */
1177 cur = malloc(sizeof(struct iax_firmware));
1179 memset(cur, 0, sizeof(struct iax_firmware));
1181 cur->next = waresl.wares;
1187 munmap(cur->fwh, cur->mmaplen);
1193 cur->mmaplen = stbuf.st_size;
1199 static int iax_check_version(char *dev)
1202 struct iax_firmware *cur;
1203 if (dev && !ast_strlen_zero(dev)) {
1204 ast_mutex_lock(&waresl.lock);
1207 if (!strcmp(dev, cur->fwh->devname)) {
1208 res = ntohs(cur->fwh->version);
1213 ast_mutex_unlock(&waresl.lock);
1218 static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
1221 unsigned int bs = desc & 0xff;
1222 unsigned int start = (desc >> 8) & 0xffffff;
1224 struct iax_firmware *cur;
1225 if (dev && !ast_strlen_zero(dev) && bs) {
1227 ast_mutex_lock(&waresl.lock);
1230 if (!strcmp(dev, cur->fwh->devname)) {
1231 iax_ie_append_int(ied, IAX_IE_FWBLOCKDESC, desc);
1232 if (start < ntohl(cur->fwh->datalen)) {
1233 bytes = ntohl(cur->fwh->datalen) - start;
1236 iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes);
1239 iax_ie_append(ied, IAX_IE_FWBLOCKDATA);
1249 ast_mutex_unlock(&waresl.lock);
1255 static void reload_firmware(void)
1257 struct iax_firmware *cur, *curl, *curp;
1262 /* Mark all as dead */
1263 ast_mutex_lock(&waresl.lock);
1269 /* Now that we've freed them, load the new ones */
1270 snprintf(dir, sizeof(dir), "%s/firmware/iax", (char *)ast_config_AST_VAR_DIR);
1273 while((de = readdir(fwd))) {
1274 if (de->d_name[0] != '.') {
1275 snprintf(fn, sizeof(fn), "%s/%s", dir, de->d_name);
1276 if (!try_firmware(fn)) {
1277 if (option_verbose > 1)
1278 ast_verbose(VERBOSE_PREFIX_2 "Loaded firmware '%s'\n", de->d_name);
1284 ast_log(LOG_WARNING, "Error opening firmware directory '%s': %s\n", dir, strerror(errno));
1286 /* Clean up leftovers */
1298 destroy_firmware(curl);
1303 ast_mutex_unlock(&waresl.lock);
1306 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
1308 static int __do_deliver(void *data)
1310 /* Just deliver the packet by using queueing. This is called by
1311 the IAX thread with the iaxsl lock held. */
1312 struct iax_frame *fr = data;
1314 if (iaxs[fr->callno] && !ast_test_flag(iaxs[fr->callno], IAX_ALREADYGONE))
1315 iax2_queue_frame(fr->callno, &fr->af);
1316 /* Free our iax frame */
1317 iax2_frame_free(fr);
1318 /* And don't run again */
1322 static int do_deliver(void *data)
1324 /* Locking version of __do_deliver */
1325 struct iax_frame *fr = data;
1326 int callno = fr->callno;
1328 ast_mutex_lock(&iaxsl[callno]);
1329 res = __do_deliver(data);
1330 ast_mutex_unlock(&iaxsl[callno]);
1334 static int handle_error(void)
1336 /* XXX Ideally we should figure out why an error occured and then abort those
1337 rather than continuing to try. Unfortunately, the published interface does
1338 not seem to work XXX */
1340 struct sockaddr_in *sin;
1343 struct sock_extended_err e;
1348 m.msg_controllen = sizeof(e);
1350 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
1352 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
1354 if (m.msg_controllen) {
1355 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
1357 ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr));
1359 ast_log(LOG_WARNING, "No address detected??\n");
1361 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
1368 static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin, int sockfd)
1371 res = sendto(sockfd, f->data, f->datalen, 0,(struct sockaddr *)sin,
1375 ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
1382 static int send_packet(struct iax_frame *f)
1385 char iabuf[INET_ADDRSTRLEN];
1386 /* Called with iaxsl held */
1388 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));
1389 /* Don't send if there was an error, but return error instead */
1391 ast_log(LOG_WARNING, "Call number = %d\n", f->callno);
1394 if (!iaxs[f->callno])
1396 if (iaxs[f->callno]->error)
1400 iax_showframe(f, NULL, 0, &iaxs[f->callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
1401 res = sendto(iaxs[f->callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[f->callno]->transfer,
1402 sizeof(iaxs[f->callno]->transfer));
1405 iax_showframe(f, NULL, 0, &iaxs[f->callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
1406 res = sendto(iaxs[f->callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[f->callno]->addr,
1407 sizeof(iaxs[f->callno]->addr));
1411 ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
1419 static int iax2_predestroy(int callno)
1421 struct ast_channel *c;
1422 struct chan_iax2_pvt *pvt;
1423 ast_mutex_lock(&iaxsl[callno]);
1426 ast_mutex_unlock(&iaxsl[callno]);
1429 if (!ast_test_flag(pvt, IAX_ALREADYGONE)) {
1430 /* No more pings or lagrq's */
1431 if (pvt->pingid > -1)
1432 ast_sched_del(sched, pvt->pingid);
1433 if (pvt->lagid > -1)
1434 ast_sched_del(sched, pvt->lagid);
1435 if (pvt->autoid > -1)
1436 ast_sched_del(sched, pvt->autoid);
1437 if (pvt->authid > -1)
1438 ast_sched_del(sched, pvt->authid);
1439 if (pvt->initid > -1)
1440 ast_sched_del(sched, pvt->initid);
1446 ast_set_flag(pvt, IAX_ALREADYGONE);
1450 c->_softhangup |= AST_SOFTHANGUP_DEV;
1452 ast_queue_hangup(c);
1454 ast_mutex_lock(&usecnt_lock);
1457 ast_log(LOG_WARNING, "Usecnt < 0???\n");
1458 ast_mutex_unlock(&usecnt_lock);
1460 ast_mutex_unlock(&iaxsl[callno]);
1461 ast_update_use_count();
1465 static int iax2_predestroy_nolock(int callno)
1468 ast_mutex_unlock(&iaxsl[callno]);
1469 res = iax2_predestroy(callno);
1470 ast_mutex_lock(&iaxsl[callno]);
1474 static void iax2_destroy(int callno)
1476 struct chan_iax2_pvt *pvt;
1477 struct iax_frame *cur;
1478 struct ast_channel *owner;
1481 ast_mutex_lock(&iaxsl[callno]);
1483 gettimeofday(&lastused[callno], NULL);
1490 if (ast_mutex_trylock(&owner->lock)) {
1491 ast_log(LOG_NOTICE, "Avoiding IAX destroy deadlock\n");
1492 ast_mutex_unlock(&iaxsl[callno]);
1498 iaxs[callno] = NULL;
1502 /* No more pings or lagrq's */
1503 if (pvt->pingid > -1)
1504 ast_sched_del(sched, pvt->pingid);
1505 if (pvt->lagid > -1)
1506 ast_sched_del(sched, pvt->lagid);
1507 if (pvt->autoid > -1)
1508 ast_sched_del(sched, pvt->autoid);
1509 if (pvt->authid > -1)
1510 ast_sched_del(sched, pvt->authid);
1511 if (pvt->initid > -1)
1512 ast_sched_del(sched, pvt->initid);
1518 if (pvt->bridgetrans)
1519 ast_translator_free_path(pvt->bridgetrans);
1520 pvt->bridgetrans = NULL;
1523 ast_set_flag(pvt, IAX_ALREADYGONE);
1526 /* If there's an owner, prod it to give up */
1527 owner->_softhangup |= AST_SOFTHANGUP_DEV;
1528 ast_queue_hangup(owner);
1531 for (cur = iaxq.head; cur ; cur = cur->next) {
1532 /* Cancel any pending transmissions */
1533 if (cur->callno == pvt->callno)
1537 pvt->reg->callno = 0;
1541 ast_variables_destroy(pvt->vars);
1548 ast_mutex_unlock(&owner->lock);
1550 ast_mutex_unlock(&iaxsl[callno]);
1551 if (callno & 0x4000)
1554 static void iax2_destroy_nolock(int callno)
1556 /* Actually it's easier to unlock, kill it, and relock */
1557 ast_mutex_unlock(&iaxsl[callno]);
1558 iax2_destroy(callno);
1559 ast_mutex_lock(&iaxsl[callno]);
1562 static int update_packet(struct iax_frame *f)
1564 /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
1565 struct ast_iax2_full_hdr *fh = f->data;
1566 /* Mark this as a retransmission */
1567 fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
1569 f->iseqno = iaxs[f->callno]->iseqno;
1570 fh->iseqno = f->iseqno;
1574 static int attempt_transmit(void *data)
1576 /* Attempt to transmit the frame to the remote peer...
1577 Called without iaxsl held. */
1578 struct iax_frame *f = data;
1580 int callno = f->callno;
1581 char iabuf[INET_ADDRSTRLEN];
1582 /* Make sure this call is still active */
1584 ast_mutex_lock(&iaxsl[callno]);
1585 if ((f->callno) && iaxs[f->callno]) {
1586 if ((f->retries < 0) /* Already ACK'd */ ||
1587 (f->retries >= max_retries) /* Too many attempts */) {
1588 /* Record an error if we've transmitted too many times */
1589 if (f->retries >= max_retries) {
1591 /* Transfer timeout */
1592 send_command(iaxs[f->callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
1593 } else if (f->final) {
1595 iax2_destroy_nolock(f->callno);
1597 if (iaxs[f->callno]->owner)
1598 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);
1599 iaxs[f->callno]->error = ETIMEDOUT;
1600 if (iaxs[f->callno]->owner) {
1601 struct ast_frame fr = { 0, };
1603 fr.frametype = AST_FRAME_CONTROL;
1604 fr.subclass = AST_CONTROL_HANGUP;
1605 iax2_queue_frame(f->callno, &fr);
1606 /* Remember, owner could disappear */
1607 if (iaxs[f->callno]->owner)
1608 iaxs[f->callno]->owner->hangupcause = AST_CAUSE_DESTINATION_OUT_OF_ORDER;
1610 if (iaxs[f->callno]->reg) {
1611 memset(&iaxs[f->callno]->reg->us, 0, sizeof(iaxs[f->callno]->reg->us));
1612 iaxs[f->callno]->reg->regstate = REG_STATE_TIMEOUT;
1613 iaxs[f->callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
1615 iax2_destroy_nolock(f->callno);
1622 /* Update it if it needs it */
1624 /* Attempt transmission */
1627 /* Try again later after 10 times as long */
1629 if (f->retrytime > MAX_RETRY_TIME)
1630 f->retrytime = MAX_RETRY_TIME;
1631 /* Transfer messages max out at one second */
1632 if (f->transfer && (f->retrytime > 1000))
1633 f->retrytime = 1000;
1634 f->retrans = ast_sched_add(sched, f->retrytime, attempt_transmit, f);
1637 /* Make sure it gets freed */
1642 ast_mutex_unlock(&iaxsl[callno]);
1643 /* Do not try again */
1645 /* Don't attempt delivery, just remove it from the queue */
1646 ast_mutex_lock(&iaxq.lock);
1648 f->prev->next = f->next;
1650 iaxq.head = f->next;
1652 f->next->prev = f->prev;
1654 iaxq.tail = f->prev;
1656 ast_mutex_unlock(&iaxq.lock);
1658 /* Free the IAX frame */
1664 static int iax2_set_jitter(int fd, int argc, char *argv[])
1666 if ((argc != 4) && (argc != 5))
1667 return RESULT_SHOWUSAGE;
1669 max_jitter_buffer = atoi(argv[3]);
1670 if (max_jitter_buffer < 0)
1671 max_jitter_buffer = 0;
1674 if ((atoi(argv[3]) >= 0) && (atoi(argv[3]) < IAX_MAX_CALLS)) {
1675 if (iaxs[atoi(argv[3])]) {
1676 iaxs[atoi(argv[3])]->jitterbuffer = atoi(argv[4]);
1677 if (iaxs[atoi(argv[3])]->jitterbuffer < 0)
1678 iaxs[atoi(argv[3])]->jitterbuffer = 0;
1680 ast_cli(fd, "No such call '%d'\n", atoi(argv[3]));
1682 ast_cli(fd, "%d is not a valid call number\n", atoi(argv[3]));
1685 return RESULT_SUCCESS;
1688 static char jitter_usage[] =
1689 "Usage: iax set jitter [callid] <value>\n"
1690 " If used with a callid, it sets the jitter buffer to the given static\n"
1691 "value (until its next calculation). If used without a callid, the value is used\n"
1692 "to establish the maximum excess jitter buffer that is permitted before the jitter\n"
1693 "buffer size is reduced.";
1695 static int iax2_prune_realtime(int fd, int argc, char *argv[])
1697 struct iax2_peer *peer;
1700 return RESULT_SHOWUSAGE;
1701 if (!strcmp(argv[3],"all")) {
1703 ast_cli(fd, "OK cache is flushed.\n");
1704 } else if ((peer = find_peer(argv[3], 0))) {
1705 if(ast_test_flag(peer, IAX_RTCACHEFRIENDS)) {
1706 ast_set_flag(peer, IAX_RTAUTOCLEAR);
1707 expire_registry(peer);
1708 ast_cli(fd, "OK peer %s was removed from the cache.\n", argv[3]);
1710 ast_cli(fd, "SORRY peer %s is not eligible for this operation.\n", argv[3]);
1713 ast_cli(fd, "SORRY peer %s was not found in the cache.\n", argv[3]);
1716 return RESULT_SUCCESS;
1719 /*--- iax2_show_peer: Show one peer in detail ---*/
1720 static int iax2_show_peer(int fd, int argc, char *argv[])
1722 char status[30] = "";
1724 char iabuf[INET_ADDRSTRLEN];
1725 struct iax2_peer *peer;
1726 char codec_buf[512];
1727 int x = 0, codec = 0, load_realtime = 0;
1730 return RESULT_SHOWUSAGE;
1732 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? 1 : 0;
1734 peer = find_peer(argv[3], load_realtime);
1737 ast_cli(fd, " * Name : %s\n", peer->name);
1738 ast_cli(fd, " Secret : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
1739 ast_cli(fd, " Context : %s\n", peer->context);
1740 ast_cli(fd, " Mailbox : %s\n", peer->mailbox);
1741 ast_cli(fd, " Dynamic : %s\n", ast_test_flag(peer, IAX_DYNAMIC) ? "Yes":"No");
1742 ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
1743 ast_cli(fd, " Expire : %d\n", peer->expire);
1744 ast_cli(fd, " ACL : %s\n", (peer->ha?"Yes":"No"));
1745 ast_cli(fd, " Addr->IP : %s Port %d\n", peer->addr.sin_addr.s_addr ? ast_inet_ntoa(iabuf, sizeof(iabuf), peer->addr.sin_addr) : "(Unspecified)", ntohs(peer->addr.sin_port));
1746 ast_cli(fd, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
1747 ast_cli(fd, " Username : %s\n", peer->username);
1748 ast_cli(fd, " Codecs : ");
1749 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
1750 ast_cli(fd, "%s\n", codec_buf);
1752 ast_cli(fd, " Codec Order : (");
1753 for(x = 0; x < 32 ; x++) {
1754 codec = ast_codec_pref_index(&peer->prefs,x);
1757 ast_cli(fd, "%s", ast_getformatname(codec));
1758 if(x < 31 && ast_codec_pref_index(&peer->prefs,x+1))
1763 ast_cli(fd, "none");
1767 ast_cli(fd, " Status : ");
1768 if (peer->lastms < 0)
1769 strncpy(status, "UNREACHABLE", sizeof(status) - 1);
1770 else if (peer->lastms > peer->maxms)
1771 snprintf(status, sizeof(status), "LAGGED (%d ms)", peer->lastms);
1772 else if (peer->lastms)
1773 snprintf(status, sizeof(status), "OK (%d ms)", peer->lastms);
1775 strncpy(status, "UNKNOWN", sizeof(status) - 1);
1776 ast_cli(fd, "%s\n",status);
1778 if (ast_test_flag(peer, IAX_TEMPONLY))
1781 ast_cli(fd,"Peer %s not found.\n", argv[3]);
1785 return RESULT_SUCCESS;
1788 static char *complete_iax2_show_peer(char *line, char *word, int pos, int state)
1791 struct iax2_peer *p;
1793 /* 0 - iax2; 1 - show; 2 - peer; 3 - <peername> */
1795 ast_mutex_lock(&peerl.lock);
1796 for(p = peerl.peers ; p ; p = p->next) {
1797 if(!strncasecmp(p->name, word, strlen(word))) {
1798 if(++which > state) {
1799 return strdup(p->name);
1803 ast_mutex_unlock(&peerl.lock);
1809 static int iax2_show_stats(int fd, int argc, char *argv[])
1811 struct iax_frame *cur;
1812 int cnt = 0, dead=0, final=0;
1814 return RESULT_SHOWUSAGE;
1815 for (cur = iaxq.head; cur ; cur = cur->next) {
1816 if (cur->retries < 0)
1822 ast_cli(fd, " IAX Statistics\n");
1823 ast_cli(fd, "---------------------\n");
1824 ast_cli(fd, "Outstanding frames: %d (%d ingress, %d outgress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
1825 ast_cli(fd, "Packets in transmit queue: %d dead, %d final, %d total\n", dead, final, cnt);
1826 return RESULT_SUCCESS;
1829 static int iax2_show_cache(int fd, int argc, char *argv[])
1831 struct iax2_dpcache *dp;
1832 char tmp[1024] = "", *pc;
1836 gettimeofday(&tv, NULL);
1837 ast_mutex_lock(&dpcache_lock);
1839 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
1841 s = dp->expirey.tv_sec - tv.tv_sec;
1843 if (dp->flags & CACHE_FLAG_EXISTS)
1844 strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
1845 if (dp->flags & CACHE_FLAG_NONEXISTANT)
1846 strncat(tmp, "NONEXISTANT|", sizeof(tmp) - strlen(tmp) - 1);
1847 if (dp->flags & CACHE_FLAG_CANEXIST)
1848 strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
1849 if (dp->flags & CACHE_FLAG_PENDING)
1850 strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
1851 if (dp->flags & CACHE_FLAG_TIMEOUT)
1852 strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
1853 if (dp->flags & CACHE_FLAG_TRANSMITTED)
1854 strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
1855 if (dp->flags & CACHE_FLAG_MATCHMORE)
1856 strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
1857 if (dp->flags & CACHE_FLAG_UNKNOWN)
1858 strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
1859 /* Trim trailing pipe */
1860 if (!ast_strlen_zero(tmp))
1861 tmp[strlen(tmp) - 1] = '\0';
1863 strncpy(tmp, "(none)", sizeof(tmp) - 1);
1865 pc = strchr(dp->peercontext, '@');
1867 pc = dp->peercontext;
1870 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
1871 if (dp->waiters[x] > -1)
1874 ast_cli(fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
1876 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
1879 ast_mutex_unlock(&dpcache_lock);
1880 return RESULT_SUCCESS;
1883 static char show_stats_usage[] =
1884 "Usage: iax show stats\n"
1885 " Display statistics on IAX channel driver.\n";
1888 static char show_cache_usage[] =
1889 "Usage: iax show cache\n"
1890 " Display currently cached IAX Dialplan results.\n";
1892 static char show_peer_usage[] =
1893 "Usage: iax show peer <name>\n"
1894 " Display details on specific IAX peer\n";
1896 static char prune_realtime_usage[] =
1897 "Usage: iax2 prune realtime [<peername>|all]\n"
1898 " Prunes object(s) from the cache\n";
1900 static struct ast_cli_entry cli_set_jitter =
1901 { { "iax2", "set", "jitter", NULL }, iax2_set_jitter, "Sets IAX jitter buffer", jitter_usage };
1903 static struct ast_cli_entry cli_show_stats =
1904 { { "iax2", "show", "stats", NULL }, iax2_show_stats, "Display IAX statistics", show_stats_usage };
1906 static struct ast_cli_entry cli_show_cache =
1907 { { "iax2", "show", "cache", NULL }, iax2_show_cache, "Display IAX cached dialplan", show_cache_usage };
1909 static struct ast_cli_entry cli_show_peer =
1910 { { "iax2", "show", "peer", NULL }, iax2_show_peer, "Show details on specific IAX peer", show_peer_usage, complete_iax2_show_peer };
1912 static struct ast_cli_entry cli_prune_realtime =
1913 { { "iax2", "prune", "realtime", NULL }, iax2_prune_realtime, "Prune a cached realtime lookup", prune_realtime_usage, complete_iax2_show_peer };
1915 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
1917 #ifdef BRIDGE_OPTIMIZATION
1918 static unsigned int calc_fakestamp(struct chan_iax2_pvt *from, struct chan_iax2_pvt *to, unsigned int ts);
1920 static int forward_delivery(struct iax_frame *fr)
1922 struct chan_iax2_pvt *p1, *p2;
1923 char iabuf[INET_ADDRSTRLEN];
1926 p1 = iaxs[fr->callno];
1927 p2 = iaxs[p1->bridgecallno];
1934 ast_log(LOG_DEBUG, "forward_delivery: Forwarding ts=%d on %d/%d to %d/%d on %s:%d\n",
1936 p1->callno, p1->peercallno,
1937 p2->callno, p2->peercallno,
1938 ast_inet_ntoa(iabuf, sizeof(iabuf), p2->addr.sin_addr),
1939 ntohs(p2->addr.sin_port));
1941 /* Undo wraparound - which can happen when full VOICE frame wasn't sent by our peer.
1942 This is necessary for when our peer is chan_iax2.c v1.1nn or earlier which didn't
1943 send full frame on timestamp wrap when doing optimized bridging
1944 (actually current code STILL doesn't)
1946 if (fr->ts + 50000 <= p1->last) {
1947 fr->ts = ( (p1->last & 0xFFFF0000) + 0x10000) | (fr->ts & 0xFFFF);
1949 ast_log(LOG_DEBUG, "forward_delivery: pushed forward timestamp to %u\n", fr->ts);
1952 /* Send with timestamp adjusted to the origin of the outbound leg */
1953 /* But don't destroy inbound timestamp still needed later to set "last" */
1955 fr->ts = calc_fakestamp(p1, p2, fr->ts);
1956 res = iax2_send(p2, &fr->af, fr->ts, -1, 0, 0, 0);
1962 static void unwrap_timestamp(struct iax_frame *fr)
1966 if ( (fr->ts & 0xFFFF0000) == (iaxs[fr->callno]->last & 0xFFFF0000) ) {
1967 x = fr->ts - iaxs[fr->callno]->last;
1969 /* Sudden big jump backwards in timestamp:
1970 What likely happened here is that miniframe timestamp has circled but we haven't
1971 gotten the update from the main packet. We'll just pretend that we did, and
1972 update the timestamp appropriately. */
1973 fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) + 0x10000) | (fr->ts & 0xFFFF);
1975 ast_log(LOG_DEBUG, "schedule_delivery: pushed forward timestamp\n");
1978 /* Sudden apparent big jump forwards in timestamp:
1979 What's likely happened is this is an old miniframe belonging to the previous
1980 top-16-bit timestamp that has turned up out of order.
1981 Adjust the timestamp appropriately. */
1982 fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) - 0x10000) | (fr->ts & 0xFFFF);
1984 ast_log(LOG_DEBUG, "schedule_delivery: pushed back timestamp\n");
1989 static int schedule_delivery(struct iax_frame *fr, int reallydeliver, int updatehistory, int fromtrunk)
1993 unsigned int orig_ts;
1994 int drops[MEMORY_SIZE];
1995 int min, max=0, prevjitterbuffer, maxone=0,y,z, match;
1997 /* Remember current jitterbuffer so we can log any change */
1998 prevjitterbuffer = iaxs[fr->callno]->jitterbuffer;
1999 /* Similarly for the frame timestamp */
2004 ast_log(LOG_DEBUG, "schedule_delivery: ts=%d, last=%d, really=%d, update=%d\n",
2005 fr->ts, iaxs[fr->callno]->last, reallydeliver, updatehistory);
2008 /* Attempt to recover wrapped timestamps */
2009 unwrap_timestamp(fr);
2011 if (updatehistory) {
2013 /* Attempt to spot a change of timebase on timestamps coming from the other side
2014 We detect by noticing a jump in consecutive timestamps that can't reasonably be explained
2015 by network jitter or reordering. Sometimes, also, the peer stops sending us frames
2016 for a while - in this case this code might also resync us. But that's not a bad thing.
2017 Be careful of non-voice frames which are timestamped differently (especially ACKS!)
2018 [that's why we only do this when updatehistory is true]
2020 x = fr->ts - iaxs[fr->callno]->last;
2021 if (x > TS_GAP_FOR_JB_RESYNC || x < -TS_GAP_FOR_JB_RESYNC) {
2023 ast_log(LOG_DEBUG, "schedule_delivery: call=%d: TS jumped. resyncing rxcore (ts=%d, last=%d)\n",
2024 fr->callno, fr->ts, iaxs[fr->callno]->last);
2025 /* zap rxcore - calc_rxstamp will make a new one based on this frame */
2026 iaxs[fr->callno]->rxcore.tv_sec = 0;
2027 iaxs[fr->callno]->rxcore.tv_usec = 0;
2028 /* wipe "last" if stamps have jumped backwards */
2030 iaxs[fr->callno]->last = 0;
2031 /* should we also empty history? */
2034 /* ms is a measure of the "lateness" of the frame relative to the "reference"
2035 frame we received. (initially the very first, but also see code just above here).
2036 Understand that "ms" can easily be -ve if lag improves since the reference frame.
2037 Called by IAX thread, with iaxsl lock held. */
2038 ms = calc_rxstamp(iaxs[fr->callno], fr->ts) - fr->ts;
2040 /* Rotate our history queue of "lateness". Don't worry about those initial
2041 zeros because the first entry will always be zero */
2042 for (x=0;x<MEMORY_SIZE - 1;x++)
2043 iaxs[fr->callno]->history[x] = iaxs[fr->callno]->history[x+1];
2044 /* Add a history entry for this one */
2045 iaxs[fr->callno]->history[x] = ms;
2051 /* delivery time is sender's sent timestamp converted back into absolute time according to our clock */
2052 if ( (!fromtrunk) && (iaxs[fr->callno]->rxcore.tv_sec || iaxs[fr->callno]->rxcore.tv_usec) ) {
2053 fr->af.delivery.tv_sec = iaxs[fr->callno]->rxcore.tv_sec;
2054 fr->af.delivery.tv_usec = iaxs[fr->callno]->rxcore.tv_usec;
2055 fr->af.delivery.tv_sec += fr->ts / 1000;
2056 fr->af.delivery.tv_usec += (fr->ts % 1000) * 1000;
2057 if (fr->af.delivery.tv_usec >= 1000000) {
2058 fr->af.delivery.tv_usec -= 1000000;
2059 fr->af.delivery.tv_sec += 1;
2065 ast_log(LOG_DEBUG, "schedule_delivery: set delivery to 0 as we don't have an rxcore yet, or frame is from trunk.\n");
2067 fr->af.delivery.tv_sec = 0;
2068 fr->af.delivery.tv_usec = 0;
2071 /* Initialize the minimum to reasonable values. It's too much
2072 work to do the same for the maximum, repeatedly */
2073 min=iaxs[fr->callno]->history[0];
2074 for (z=0;z < iax2_dropcount + 1;z++) {
2075 /* Start very optimistic ;-) */
2077 for (x=0;x<MEMORY_SIZE;x++) {
2078 if (max < iaxs[fr->callno]->history[x]) {
2079 /* We have a candidate new maximum value. Make
2080 sure it's not in our drop list */
2082 for (y=0;!match && (y<z);y++)
2083 match |= (drops[y] == x);
2085 /* It's not in our list, use it as the new maximum */
2086 max = iaxs[fr->callno]->history[x];
2092 /* On our first pass, find the minimum too */
2093 if (min > iaxs[fr->callno]->history[x])
2094 min = iaxs[fr->callno]->history[x];
2101 /* Just for reference, keep the "jitter" value, the difference between the
2102 earliest and the latest. */
2104 iaxs[fr->callno]->jitter = max - min;
2106 /* IIR filter for keeping track of historic jitter, but always increase
2107 historic jitter immediately for increase */
2109 if (iaxs[fr->callno]->jitter > iaxs[fr->callno]->historicjitter )
2110 iaxs[fr->callno]->historicjitter = iaxs[fr->callno]->jitter;
2112 iaxs[fr->callno]->historicjitter = GAMMA * (double)iaxs[fr->callno]->jitter + (1-GAMMA) *
2113 iaxs[fr->callno]->historicjitter;
2115 /* If our jitter buffer is too big (by a significant margin), then we slowly
2116 shrink it to avoid letting the change be perceived */
2117 if (max < iaxs[fr->callno]->jitterbuffer - max_jitter_buffer)
2118 iaxs[fr->callno]->jitterbuffer -= jittershrinkrate;
2120 /* If our jitter buffer headroom is too small (by a significant margin), then we slowly enlarge it */
2121 /* min_jitter_buffer should be SMALLER than max_jitter_buffer - leaving a "no mans land"
2122 in between - otherwise the jitterbuffer size will hunt up and down causing unnecessary
2123 disruption. Set maxexcessbuffer to say 150msec, minexcessbuffer to say 50 */
2124 if (max > iaxs[fr->callno]->jitterbuffer - min_jitter_buffer)
2125 iaxs[fr->callno]->jitterbuffer += jittershrinkrate;
2127 /* If our jitter buffer is smaller than our maximum delay, grow the jitter
2128 buffer immediately to accomodate it (and a little more). */
2129 if (max > iaxs[fr->callno]->jitterbuffer)
2130 iaxs[fr->callno]->jitterbuffer = max
2131 /* + ((float)iaxs[fr->callno]->jitter) * 0.1 */;
2133 /* update "min", just for RRs and stats */
2134 iaxs[fr->callno]->min = min;
2136 /* If the caller just wanted us to update, return now */
2140 /* Subtract the lateness from our jitter buffer to know how long to wait
2141 before sending our packet. */
2142 delay = iaxs[fr->callno]->jitterbuffer - ms;
2144 /* Whatever happens, no frame waits longer than maxjitterbuffer */
2145 if (delay > maxjitterbuffer)
2146 delay = maxjitterbuffer;
2148 /* If jitter buffer is disabled then just pretend the frame is "right on time" */
2149 /* If frame came from trunk, also don't do any delay */
2150 if ( (!ast_test_flag(iaxs[fr->callno], IAX_USEJITTERBUF)) || fromtrunk )
2154 /* Log jitter stats for possible offline analysis */
2155 ast_log(LOG_DEBUG, "Jitter: call=%d ts=%d orig=%d last=%d %s: min=%d max=%d jb=%d %+d lateness=%d jbdelay=%d jitter=%d historic=%d\n",
2156 fr->callno, fr->ts, orig_ts, iaxs[fr->callno]->last,
2157 (fr->af.frametype == AST_FRAME_VOICE) ? "VOICE" : "CONTROL",
2158 min, max, iaxs[fr->callno]->jitterbuffer,
2159 iaxs[fr->callno]->jitterbuffer - prevjitterbuffer,
2161 iaxs[fr->callno]->jitter, iaxs[fr->callno]->historicjitter);
2165 /* Don't deliver it more than 4 ms late */
2166 if ((delay > -4) || (fr->af.frametype != AST_FRAME_VOICE)) {
2168 ast_log(LOG_DEBUG, "schedule_delivery: Delivering immediately (Calculated delay is %d)\n", delay);
2172 ast_log(LOG_DEBUG, "schedule_delivery: Dropping voice packet since %dms delay is too old\n", delay);
2173 iaxs[fr->callno]->frames_dropped++;
2174 /* Free our iax frame */
2175 iax2_frame_free(fr);
2179 ast_log(LOG_DEBUG, "schedule_delivery: Scheduling delivery in %d ms\n", delay);
2180 fr->retrans = ast_sched_add(sched, delay, do_deliver, fr);
2185 static int iax2_transmit(struct iax_frame *fr)
2187 /* Lock the queue and place this packet at the end */
2190 /* By setting this to 0, the network thread will send it for us, and
2191 queue retransmission if necessary */
2193 ast_mutex_lock(&iaxq.lock);
2200 iaxq.tail->next = fr;
2201 fr->prev = iaxq.tail;
2205 ast_mutex_unlock(&iaxq.lock);
2206 /* Wake up the network thread */
2207 pthread_kill(netthreadid, SIGURG);
2213 static int iax2_digit(struct ast_channel *c, char digit)
2215 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF, digit, 0, NULL, 0, -1);
2218 static int iax2_sendtext(struct ast_channel *c, char *text)
2221 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_TEXT,
2222 0, 0, text, strlen(text) + 1, -1);
2225 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
2227 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_IMAGE, img->subclass, 0, img->data, img->datalen, -1);
2230 static int iax2_sendhtml(struct ast_channel *c, int subclass, char *data, int datalen)
2232 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_HTML, subclass, 0, data, datalen, -1);
2235 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
2237 unsigned short callno = PTR_TO_CALLNO(newchan->tech_pvt);
2238 ast_mutex_lock(&iaxsl[callno]);
2240 iaxs[callno]->owner = newchan;
2242 ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n");
2243 ast_mutex_unlock(&iaxsl[callno]);
2247 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, int temponly);
2248 static struct iax2_user *build_user(const char *name, struct ast_variable *v, int temponly);
2250 static void destroy_user(struct iax2_user *user);
2251 static int expire_registry(void *data);
2253 static struct iax2_peer *realtime_peer(const char *peername)
2255 struct ast_variable *var;
2256 struct ast_variable *tmp;
2257 struct iax2_peer *peer=NULL;
2258 time_t regseconds, nowtime;
2260 var = ast_load_realtime("iaxpeers", "name", peername, NULL);
2262 /* Make sure it's not a user only... */
2263 peer = build_peer(peername, var, ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS) ? 0 : 1);
2268 if (!strcasecmp(tmp->name, "type")) {
2269 if (strcasecmp(tmp->value, "friend") &&
2270 strcasecmp(tmp->value, "peer")) {
2271 /* Whoops, we weren't supposed to exist! */
2276 } else if (!strcasecmp(tmp->name, "regseconds")) {
2277 if (sscanf(tmp->value, "%li", ®seconds) != 1)
2279 } else if (!strcasecmp(tmp->name, "ipaddr")) {
2280 inet_aton(tmp->value, &(peer->addr.sin_addr));
2281 } else if (!strcasecmp(tmp->name, "port")) {
2282 peer->addr.sin_port = htons(atoi(tmp->value));
2283 } else if (!strcasecmp(tmp->name, "host")) {
2284 if (!strcasecmp(tmp->value, "dynamic"))
2290 /* Add some finishing touches, addresses, etc */
2291 if(ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
2292 ast_mutex_lock(&peerl.lock);
2293 peer->next = peerl.peers;
2295 ast_mutex_unlock(&peerl.lock);
2296 ast_copy_flags(peer, &globalflags, IAX_RTAUTOCLEAR|IAX_RTCACHEFRIENDS);
2297 if (ast_test_flag(peer, IAX_RTAUTOCLEAR))
2298 peer->expire = ast_sched_add(sched, (global_rtautoclear) * 1000, expire_registry, (void *)peer);
2300 ast_set_flag(peer, IAX_TEMPONLY);
2303 if (peer && dynamic) {
2305 if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE) {
2306 memset(&peer->addr, 0, sizeof(peer->addr));
2308 ast_log(LOG_DEBUG, "Bah, we're expired (%ld/%ld/%ld)!\n", nowtime - regseconds, regseconds, nowtime);
2312 ast_variables_destroy(var);
2317 static struct iax2_user *realtime_user(const char *username)
2319 struct ast_variable *var;
2320 struct ast_variable *tmp;
2321 struct iax2_user *user=NULL;
2322 var = ast_load_realtime("iaxusers", "name", username, NULL);
2324 /* Make sure it's not a user only... */
2325 user = build_user(username, var, !ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS));
2327 /* Add some finishing touches, addresses, etc */
2328 if(ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
2329 ast_mutex_lock(&userl.lock);
2330 user->next = userl.users;
2332 ast_mutex_unlock(&userl.lock);
2333 ast_set_flag(user, IAX_RTCACHEFRIENDS);
2335 ast_set_flag(user, IAX_TEMPONLY);
2339 if (!strcasecmp(tmp->name, "type")) {
2340 if (strcasecmp(tmp->value, "friend") &&
2341 strcasecmp(tmp->value, "user")) {
2342 /* Whoops, we weren't supposed to exist! */
2351 ast_variables_destroy(var);
2356 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin)
2360 char regseconds[20];
2364 snprintf(regseconds, sizeof(regseconds), "%ld", nowtime);
2365 ast_inet_ntoa(ipaddr, sizeof(ipaddr), sin->sin_addr);
2366 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
2367 ast_update_realtime("iaxpeers", "name", peername, "ipaddr", ipaddr, "port", port, "regseconds", regseconds, NULL);
2371 static int create_addr(struct sockaddr_in *sin, int *capability, int *sendani,
2372 int *maxtime, char *peer, char *context, int *trunk,
2373 int *notransfer, int *usejitterbuf, int *encmethods,
2374 char *username, int usernlen, char *secret, int seclen,
2375 int *ofound, char *peercontext, char *timezone, int tzlen, char *pref_str, size_t pref_size,
2378 struct ast_hostent ahp; struct hostent *hp;
2379 struct iax2_peer *p;
2388 *sockfd = defaultsockfd;
2389 sin->sin_family = AF_INET;
2390 p = find_peer(peer, 1);
2393 if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
2394 (!p->maxms || ((p->lastms > 0) && (p->lastms <= p->maxms)))) {
2397 ast_codec_pref_convert(&p->prefs, pref_str, pref_size, 1);
2400 *sendani = ast_test_flag(p, IAX_SENDANI); /* Whether we transmit ANI */
2402 *maxtime = p->maxms; /* Max time they should take */
2404 strncpy(context, p->context, AST_MAX_EXTENSION - 1);
2406 strncpy(peercontext, p->peercontext, AST_MAX_EXTENSION - 1);
2408 *trunk = ast_test_flag(p, IAX_TRUNK);
2410 *capability = p->capability;
2412 *encmethods = p->encmethods;
2414 strncpy(username, p->username, usernlen);
2415 if (p->addr.sin_addr.s_addr) {
2416 sin->sin_addr = p->addr.sin_addr;
2417 sin->sin_port = p->addr.sin_port;
2419 sin->sin_addr = p->defaddr.sin_addr;
2420 sin->sin_port = p->defaddr.sin_port;
2423 *sockfd = p->sockfd;
2425 *notransfer = ast_test_flag(p, IAX_NOTRANSFER);
2427 *usejitterbuf = ast_test_flag(p, IAX_USEJITTERBUF);
2429 if (!ast_strlen_zero(p->dbsecret)) {
2430 char *family, *key=NULL;
2431 family = ast_strdupa(p->dbsecret);
2433 key = strchr(family, '/');
2439 if (!family || !key || ast_db_get(family, key, secret, seclen)) {
2440 ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", p->dbsecret);
2441 if (ast_test_flag(p, IAX_TEMPONLY))
2446 strncpy(secret, p->secret, seclen); /* safe */
2449 snprintf(timezone, tzlen-1, "%s", p->zonetag);
2451 if (ast_test_flag(p, IAX_TEMPONLY))
2459 if(pref_str) { /* use global iax prefs for unknown peer/user */
2460 ast_codec_pref_convert(&prefs, pref_str, pref_size, 1);
2463 hp = ast_gethostbyname(peer, &ahp);
2465 memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
2466 sin->sin_port = htons(IAX_DEFAULT_PORTNO);
2469 ast_log(LOG_WARNING, "No such host: %s\n", peer);
2474 if (ast_test_flag(p, IAX_TEMPONLY))
2479 static int auto_congest(void *nothing)
2481 int callno = PTR_TO_CALLNO(nothing);
2482 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_CONGESTION };
2483 ast_mutex_lock(&iaxsl[callno]);
2485 iaxs[callno]->initid = -1;
2486 iax2_queue_frame(callno, &f);
2487 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
2489 ast_mutex_unlock(&iaxsl[callno]);
2493 static unsigned int iax2_datetime(char *tz)
2499 localtime_r(&t, &tm);
2500 if (!ast_strlen_zero(tz))
2501 ast_localtime(&t, &tm, tz);
2502 tmp = (tm.tm_sec >> 1) & 0x1f; /* 5 bits of seconds */
2503 tmp |= (tm.tm_min & 0x3f) << 5; /* 6 bits of minutes */
2504 tmp |= (tm.tm_hour & 0x1f) << 11; /* 5 bits of hours */
2505 tmp |= (tm.tm_mday & 0x1f) << 16; /* 5 bits of day of month */
2506 tmp |= ((tm.tm_mon + 1) & 0xf) << 21; /* 4 bits of month */
2507 tmp |= ((tm.tm_year - 100) & 0x7f) << 25; /* 7 bits of year */
2511 static int iax2_call(struct ast_channel *c, char *dest, int timeout)
2513 struct sockaddr_in sin;
2518 char *secret = NULL;
2520 char *l=NULL, *n=NULL;
2521 struct iax_ie_data ied;
2522 char myrdest [5] = "s";
2523 char context[AST_MAX_EXTENSION] ="";
2524 char peercontext[AST_MAX_EXTENSION] ="";
2525 char *portno = NULL;
2527 int encmethods=iax2_encryption;
2528 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
2530 char storedusern[80], storedsecret[80];
2534 memset(out_prefs,0,32);
2536 if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
2537 ast_log(LOG_WARNING, "Line is already in use (%s)?\n", c->name);
2540 strncpy(host, dest, sizeof(host)-1);
2542 strsep(&stringp, "/");
2543 /* If no destination extension specified, use 's' */
2544 rdest = strsep(&stringp, "/");
2548 /* Check for trailing options */
2549 opts = strsep(&stringp, "/");
2554 strsep(&stringp, "@");
2555 rcontext = strsep(&stringp, "@");
2557 strsep(&stringp, "@");
2558 username = strsep(&stringp, "@");
2560 /* Really the second argument is the host, not the username */
2568 username = strsep(&stringp, ":");
2569 secret = strsep(&stringp, ":");
2572 if (strsep(&stringp, ":")) {
2574 strsep(&stringp, ":");
2575 portno = strsep(&stringp, ":");
2577 if (create_addr(&sin, NULL, NULL, NULL, hname, context, NULL, NULL, NULL, &encmethods, storedusern, sizeof(storedusern) - 1, storedsecret, sizeof(storedsecret) - 1, NULL, peercontext, tz, sizeof(tz), out_prefs, sizeof(out_prefs), NULL)) {
2578 ast_log(LOG_WARNING, "No address associated with '%s'\n", hname);
2581 /* Keep track of the context for outgoing calls too */
2582 strncpy(c->context, context, sizeof(c->context) - 1);
2584 sin.sin_port = htons(atoi(portno));
2587 n = c->cid.cid_name;
2588 /* Now build request */
2589 memset(&ied, 0, sizeof(ied));
2590 /* On new call, first IE MUST be IAX version of caller */
2591 iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
2592 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, rdest);
2593 if (strchr(opts, 'a')) {
2594 /* Request auto answer */
2595 iax_ie_append(&ied, IAX_IE_AUTOANSWER);
2597 iax_ie_append_str(&ied, IAX_IE_CODEC_PREFS, out_prefs);
2600 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
2601 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
2603 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, AST_PRES_NUMBER_NOT_AVAILABLE);
2604 iax_ie_append_byte(&ied, IAX_IE_CALLINGTON, c->cid.cid_ton);
2605 iax_ie_append_short(&ied, IAX_IE_CALLINGTNS, c->cid.cid_tns);
2607 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n);
2608 if (ast_test_flag(iaxs[callno], IAX_SENDANI) && c->cid.cid_ani) {
2609 iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, c->cid.cid_ani);
2611 if (c->language && !ast_strlen_zero(c->language))
2612 iax_ie_append_str(&ied, IAX_IE_LANGUAGE, c->language);
2613 if (c->cid.cid_dnid && !ast_strlen_zero(c->cid.cid_dnid))
2614 iax_ie_append_str(&ied, IAX_IE_DNID, c->cid.cid_dnid);
2616 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, rcontext);
2617 else if (strlen(peercontext))
2618 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, peercontext);
2619 if (!username && !ast_strlen_zero(storedusern))
2620 username = storedusern;
2622 iax_ie_append_str(&ied, IAX_IE_USERNAME, username);
2624 iax_ie_append_short(&ied, IAX_IE_ENCRYPTION, encmethods);
2625 if (!secret && !ast_strlen_zero(storedsecret))
2626 secret = storedsecret;
2627 ast_mutex_lock(&iaxsl[callno]);
2628 if (!ast_strlen_zero(c->context))
2629 strncpy(iaxs[callno]->context, c->context, sizeof(iaxs[callno]->context) - 1);
2631 strncpy(iaxs[callno]->username, username, sizeof(iaxs[callno]->username)-1);
2632 iaxs[callno]->encmethods = encmethods;
2634 if (secret[0] == '[') {
2635 /* This is an RSA key, not a normal secret */
2636 strncpy(iaxs[callno]->outkey, secret + 1, sizeof(iaxs[callno]->secret)-1);
2637 if (!ast_strlen_zero(iaxs[callno]->outkey)) {
2638 iaxs[callno]->outkey[strlen(iaxs[callno]->outkey) - 1] = '\0';
2641 strncpy(iaxs[callno]->secret, secret, sizeof(iaxs[callno]->secret)-1);
2643 iax_ie_append_int(&ied, IAX_IE_FORMAT, c->nativeformats);
2644 iax_ie_append_int(&ied, IAX_IE_CAPABILITY, iaxs[callno]->capability);
2645 iax_ie_append_short(&ied, IAX_IE_ADSICPE, c->adsicpe);
2646 iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime(tz));
2647 /* Transmit the string in a "NEW" request */
2649 /* XXX We have no equivalent XXX */
2650 if (option_verbose > 2)
2651 ast_verbose(VERBOSE_PREFIX_3 "Calling using options '%s'\n", requeststr);
2653 if (iaxs[callno]->maxtime) {
2654 /* Initialize pingtime and auto-congest time */
2655 iaxs[callno]->pingtime = iaxs[callno]->maxtime / 2;
2656 iaxs[callno]->initid = ast_sched_add(sched, iaxs[callno]->maxtime * 2, auto_congest, CALLNO_TO_PTR(callno));
2657 } else if (autokill) {
2658 iaxs[callno]->pingtime = autokill / 2;
2659 iaxs[callno]->initid = ast_sched_add(sched, autokill * 2, auto_congest, CALLNO_TO_PTR(callno));
2661 send_command(iaxs[callno], AST_FRAME_IAX,
2662 IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
2663 ast_mutex_unlock(&iaxsl[callno]);
2664 ast_setstate(c, AST_STATE_RINGING);
2668 static int iax2_hangup(struct ast_channel *c)
2670 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
2672 struct iax_ie_data ied;
2673 memset(&ied, 0, sizeof(ied));
2674 ast_mutex_lock(&iaxsl[callno]);
2675 if (callno && iaxs[callno]) {
2676 ast_log(LOG_DEBUG, "We're hanging up %s now...\n", c->name);
2677 alreadygone = ast_test_flag(iaxs[callno], IAX_ALREADYGONE);
2678 /* Send the hangup unless we have had a transmission error or are already gone */
2679 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, (unsigned char)c->hangupcause);
2680 if (!iaxs[callno]->error && !alreadygone)
2681 send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1);
2682 /* Explicitly predestroy it */
2683 iax2_predestroy_nolock(callno);
2684 /* If we were already gone to begin with, destroy us now */
2686 ast_log(LOG_DEBUG, "Really destroying %s now...\n", c->name);
2687 iax2_destroy_nolock(callno);
2690 ast_mutex_unlock(&iaxsl[callno]);
2691 if (option_verbose > 2)
2692 ast_verbose(VERBOSE_PREFIX_3 "Hungup '%s'\n", c->name);
2696 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
2698 struct ast_option_header *h;
2700 h = malloc(datalen + sizeof(struct ast_option_header));
2702 h->flag = AST_OPTION_FLAG_REQUEST;
2703 h->option = htons(option);
2704 memcpy(h->data, data, datalen);
2705 res = send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_CONTROL,
2706 AST_CONTROL_OPTION, 0, (char *)h, datalen + sizeof(struct ast_option_header), -1);
2710 ast_log(LOG_WARNING, "Out of memory\n");
2714 static struct ast_frame *iax2_read(struct ast_channel *c)
2716 static struct ast_frame f = { AST_FRAME_NULL, };
2717 ast_log(LOG_NOTICE, "I should never be called!\n");
2721 static int iax2_start_transfer(unsigned short callno0, unsigned short callno1)
2724 struct iax_ie_data ied0;
2725 struct iax_ie_data ied1;
2726 unsigned int transferid = rand();
2727 memset(&ied0, 0, sizeof(ied0));
2728 iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &iaxs[callno1]->addr);
2729 iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[callno1]->peercallno);
2730 iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, transferid);
2732 memset(&ied1, 0, sizeof(ied1));
2733 iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &iaxs[callno0]->addr);
2734 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[callno0]->peercallno);
2735 iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, transferid);
2737 res = send_command(iaxs[callno0], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
2740 res = send_command(iaxs[callno1], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
2743 iaxs[callno0]->transferring = TRANSFER_BEGIN;
2744 iaxs[callno1]->transferring = TRANSFER_BEGIN;
2748 static void lock_both(unsigned short callno0, unsigned short callno1)
2750 ast_mutex_lock(&iaxsl[callno0]);
2751 while (ast_mutex_trylock(&iaxsl[callno1])) {
2752 ast_mutex_unlock(&iaxsl[callno0]);
2754 ast_mutex_lock(&iaxsl[callno0]);
2758 static void unlock_both(unsigned short callno0, unsigned short callno1)
2760 ast_mutex_unlock(&iaxsl[callno1]);
2761 ast_mutex_unlock(&iaxsl[callno0]);
2764 static int iax2_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
2766 struct ast_channel *cs[3];
2767 struct ast_channel *who;
2770 int transferstarted=0;
2771 struct ast_frame *f;
2772 unsigned short callno0 = PTR_TO_CALLNO(c0->tech_pvt);
2773 unsigned short callno1 = PTR_TO_CALLNO(c1->tech_pvt);
2774 struct timeval waittimer = {0, 0}, tv;
2776 lock_both(callno0, callno1);
2777 /* Put them in native bridge mode */
2778 if (!flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1)) {
2779 iaxs[callno0]->bridgecallno = callno1;
2780 iaxs[callno1]->bridgecallno = callno0;
2782 unlock_both(callno0, callno1);
2784 /* If not, try to bridge until we can execute a transfer, if we can */
2787 for (/* ever */;;) {
2788 /* Check in case we got masqueraded into */
2789 if ((c0->type != channeltype) || (c1->type != channeltype)) {
2790 if (option_verbose > 2)
2791 ast_verbose(VERBOSE_PREFIX_3 "Can't masquerade, we're different...\n");
2792 /* Remove from native mode */
2793 if (c0->type == channeltype) {
2794 ast_mutex_lock(&iaxsl[callno0]);
2795 iaxs[callno0]->bridgecallno = 0;
2796 ast_mutex_unlock(&iaxsl[callno0]);
2798 if (c1->type == channeltype) {
2799 ast_mutex_lock(&iaxsl[callno1]);
2800 iaxs[callno1]->bridgecallno = 0;
2801 ast_mutex_unlock(&iaxsl[callno1]);
2805 if (c0->nativeformats != c1->nativeformats) {
2806 if (option_verbose > 2) {
2809 ast_getformatname_multiple(buf0, sizeof(buf0) -1, c0->nativeformats);
2810 ast_getformatname_multiple(buf1, sizeof(buf1) -1, c1->nativeformats);
2811 ast_verbose(VERBOSE_PREFIX_3 "Operating with different codecs %d[%s] %d[%s] , can't native bridge...\n", c0->nativeformats, buf0, c1->nativeformats, buf1);
2813 /* Remove from native mode */
2814 lock_both(callno0, callno1);
2815 iaxs[callno0]->bridgecallno = 0;
2816 iaxs[callno1]->bridgecallno = 0;
2817 unlock_both(callno0, callno1);
2820 /* check if transfered and if we really want native bridging */
2821 if (!transferstarted && !ast_test_flag(iaxs[callno0], IAX_NOTRANSFER) && !ast_test_flag(iaxs[callno1], IAX_NOTRANSFER) &&
2822 !(flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
2823 /* Try the transfer */
2824 if (iax2_start_transfer(callno0, callno1))
2825 ast_log(LOG_WARNING, "Unable to start the transfer\n");
2826 transferstarted = 1;
2828 if ((iaxs[callno0]->transferring == TRANSFER_RELEASED) && (iaxs[callno1]->transferring == TRANSFER_RELEASED)) {
2829 /* Call has been transferred. We're no longer involved */
2830 gettimeofday(&tv, NULL);
2831 if (!waittimer.tv_sec && !waittimer.tv_usec) {
2832 waittimer.tv_sec = tv.tv_sec;
2833 waittimer.tv_usec = tv.tv_usec;
2834 } else if (tv.tv_sec - waittimer.tv_sec > IAX_LINGER_TIMEOUT) {
2835 c0->_softhangup |= AST_SOFTHANGUP_DEV;
2836 c1->_softhangup |= AST_SOFTHANGUP_DEV;
2844 who = ast_waitfor_n(cs, 2, &to);
2846 if (ast_check_hangup(c0) || ast_check_hangup(c1)) {
2859 if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
2865 if ((f->frametype == AST_FRAME_VOICE) ||
2866 (f->frametype == AST_FRAME_TEXT) ||
2867 (f->frametype == AST_FRAME_VIDEO) ||
2868 (f->frametype == AST_FRAME_IMAGE) ||
2869 (f->frametype == AST_FRAME_DTMF)) {
2870 if ((f->frametype == AST_FRAME_DTMF) &&
2871 (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
2873 if ((flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
2876 /* Take out of conference mode */
2878 /* Remove from native mode */
2884 if (flags & AST_BRIDGE_DTMF_CHANNEL_1) {
2888 /* Remove from native mode */
2895 ast_log(LOG_DEBUG, "Read from %s\n", who->name);
2897 ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
2909 /* Swap who gets priority */
2914 lock_both(callno0, callno1);
2916 iaxs[callno0]->bridgecallno = 0;
2918 iaxs[callno1]->bridgecallno = 0;
2919 unlock_both(callno0, callno1);
2923 static int iax2_answer(struct ast_channel *c)
2925 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
2927 ast_log(LOG_DEBUG, "Answering\n");
2928 return send_command_locked(callno, AST_FRAME_CONTROL, AST_CONTROL_ANSWER, 0, NULL, 0, -1);
2931 static int iax2_indicate(struct ast_channel *c, int condition)
2933 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
2935 ast_log(LOG_DEBUG, "Indicating condition %d\n", condition);
2936 return send_command_locked(callno, AST_FRAME_CONTROL, condition, 0, NULL, 0, -1);
2939 static int iax2_transfer(struct ast_channel *c, char *dest)
2941 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
2942 struct iax_ie_data ied;
2943 char tmp[256] = "", *context;
2944 strncpy(tmp, dest, sizeof(tmp) - 1);
2945 context = strchr(tmp, '@');
2950 memset(&ied, 0, sizeof(ied));
2951 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, tmp);
2953 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, context);
2955 ast_log(LOG_DEBUG, "Transferring '%s' to '%s'\n", c->name, dest);
2956 return send_command_locked(callno, AST_FRAME_IAX, IAX_COMMAND_TRANSFER, 0, ied.buf, ied.pos, -1);
2960 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
2962 static int iax2_getpeertrunk(struct sockaddr_in sin)
2964 struct iax2_peer *peer;
2966 ast_mutex_lock(&peerl.lock);
2969 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
2970 (peer->addr.sin_port == sin.sin_port)) {
2971 res = ast_test_flag(peer, IAX_TRUNK);
2976 ast_mutex_unlock(&peerl.lock);
2980 /*--- ast_iax2_new: Create new call, interface with the PBX core */
2981 static struct ast_channel *ast_iax2_new(int callno, int state, int capability)
2983 struct ast_channel *tmp;
2984 struct chan_iax2_pvt *i;
2985 struct ast_variable *v = NULL;
2987 /* Don't hold call lock */
2988 ast_mutex_unlock(&iaxsl[callno]);
2989 tmp = ast_channel_alloc(1);
2990 ast_mutex_lock(&iaxsl[callno]);
2993 tmp->tech = &iax2_tech;
2994 if (!ast_strlen_zero(i->username))
2995 snprintf(tmp->name, sizeof(tmp->name), "IAX2/%s@%s-%d", i->username, i->host, i->callno);
2997 snprintf(tmp->name, sizeof(tmp->name), "IAX2/%s-%d", i->host, i->callno);
2998 tmp->type = channeltype;
2999 /* We can support any format by default, until we get restricted */
3000 tmp->nativeformats = capability;
3001 tmp->readformat = ast_best_codec(capability);
3002 tmp->writeformat = ast_best_codec(capability);
3003 tmp->tech_pvt = CALLNO_TO_PTR(i->callno);
3005 if (!ast_strlen_zero(i->cid_num))
3006 tmp->cid.cid_num = strdup(i->cid_num);
3007 if (!ast_strlen_zero(i->cid_name))
3008 tmp->cid.cid_name = strdup(i->cid_name);
3009 if (!ast_strlen_zero(i->ani))
3010 tmp->cid.cid_ani = strdup(i->ani);
3011 if (!ast_strlen_zero(i->language))
3012 strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
3013 if (!ast_strlen_zero(i->dnid))
3014 tmp->cid.cid_dnid = strdup(i->dnid);
3015 tmp->cid.cid_pres = i->calling_pres;
3016 tmp->cid.cid_ton = i->calling_ton;
3017 tmp->cid.cid_tns = i->calling_tns;
3018 if (!ast_strlen_zero(i->accountcode))
3019 strncpy(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode)-1);
3021 tmp->amaflags = i->amaflags;
3022 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
3023 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
3024 tmp->adsicpe = i->peeradsicpe;
3026 i->capability = capability;
3027 ast_setstate(tmp, state);
3028 ast_mutex_lock(&usecnt_lock);
3030 ast_mutex_unlock(&usecnt_lock);
3031 ast_update_use_count();
3032 if (state != AST_STATE_DOWN) {
3033 if (ast_pbx_start(tmp)) {
3034 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
3039 for (v = i->vars ; v ; v = v->next)
3040 pbx_builtin_setvar_helper(tmp,v->name,v->value);
3046 static unsigned int calc_txpeerstamp(struct iax2_trunk_peer *tpeer, int sampms, struct timeval *tv)
3048 unsigned long int mssincetx; /* unsigned to handle overflows */
3051 tpeer->trunkact = *tv;
3052 mssincetx = (tv->tv_sec - tpeer->lasttxtime.tv_sec) * 1000 +
3053 (1000000 + tv->tv_usec - tpeer->lasttxtime.tv_usec) / 1000 - 1000;
3054 if (mssincetx > 5000 || (!tpeer->txtrunktime.tv_sec && !tpeer->txtrunktime.tv_usec)) {
3055 /* If it's been at least 5 seconds since the last time we transmitted on this trunk, reset our timers */
3056 tpeer->txtrunktime.tv_sec = tv->tv_sec;
3057 tpeer->txtrunktime.tv_usec = tv->tv_usec;
3058 tpeer->lastsent = 999999;
3060 /* Update last transmit time now */
3061 tpeer->lasttxtime.tv_sec = tv->tv_sec;
3062 tpeer->lasttxtime.tv_usec = tv->tv_usec;
3064 /* Calculate ms offset */
3065 ms = (tv->tv_sec - tpeer->txtrunktime.tv_sec) * 1000 +
3066 (1000000 + tv->tv_usec - tpeer->txtrunktime.tv_usec) / 1000 - 1000;
3067 /* Predict from last value */
3068 pred = tpeer->lastsent + sampms;
3069 if (abs(ms - pred) < MAX_TIMESTAMP_SKEW)
3072 /* We never send the same timestamp twice, so fudge a little if we must */
3073 if (ms == tpeer->lastsent)
3074 ms = tpeer->lastsent + 1;
3075 tpeer->lastsent = ms;
3079 static unsigned int fix_peerts(struct timeval *tv, int callno, unsigned int ts)
3081 long ms; /* NOT unsigned */
3082 if (!iaxs[callno]->rxcore.tv_sec && !iaxs[callno]->rxcore.tv_usec) {
3083 /* Initialize rxcore time if appropriate */
3084 gettimeofday(&iaxs[callno]->rxcore, NULL);
3085 /* Round to nearest 20ms so traces look pretty */
3086 iaxs[callno]->rxcore.tv_usec -= iaxs[callno]->rxcore.tv_usec % 20000;
3088 /* Calculate difference between trunk and channel */
3089 ms = (tv->tv_sec - iaxs[callno]->rxcore.tv_sec) * 1000 +
3090 (1000000 + tv->tv_usec - iaxs[callno]->rxcore.tv_usec) / 1000 - 1000;
3091 /* Return as the sum of trunk time and the difference between trunk and real time */
3095 static void add_ms(struct timeval *tv, int ms) {
3096 tv->tv_usec += ms * 1000;
3097 if(tv->tv_usec > 1000000) {
3098 tv->tv_usec -= 1000000;
3101 if(tv->tv_usec < 0) {
3102 tv->tv_usec += 1000000;
3107 static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts, struct ast_frame *f)
3113 struct timeval *delivery = NULL;
3115 /* What sort of frame do we have?: voice is self-explanatory
3116 "genuine" means an IAX frame - things like LAGRQ/RP, PING/PONG, ACK
3117 non-genuine frames are CONTROL frames [ringing etc], DTMF
3118 The "genuine" distinction is needed because genuine frames must get a clock-based timestamp,
3119 the others need a timestamp slaved to the voice frames so that they go in sequence
3122 if (f->frametype == AST_FRAME_VOICE) {
3124 delivery = &f->delivery;
3125 } else if (f->frametype == AST_FRAME_IAX) {
3127 } else if (f->frametype == AST_FRAME_CNG) {
3131 if (!p->offset.tv_sec && !p->offset.tv_usec) {
3132 gettimeofday(&p->offset, NULL);
3133 /* Round to nearest 20ms for nice looking traces */
3134 p->offset.tv_usec -= p->offset.tv_usec % 20000;
3136 /* If the timestamp is specified, just send it as is */
3139 /* If we have a time that the frame arrived, always use it to make our timestamp */
3140 if (delivery && (delivery->tv_sec || delivery->tv_usec)) {
3141 ms = (delivery->tv_sec - p->offset.tv_sec) * 1000 +
3142 (1000000 + delivery->tv_usec - p->offset.tv_usec) / 1000 - 1000;
3144 ast_log(LOG_DEBUG, "calc_timestamp: call %d/%d: Timestamp slaved to delivery time\n", p->callno, iaxs[p->callno]->peercallno);
3146 gettimeofday(&tv, NULL);
3147 ms = (tv.tv_sec - p->offset.tv_sec) * 1000 +
3148 (1000000 + tv.tv_usec - p->offset.tv_usec) / 1000 - 1000;
3152 /* On a voice frame, use predicted values if appropriate */
3153 if (p->notsilenttx && abs(ms - p->nextpred) <= MAX_TIMESTAMP_SKEW) {
3154 /* Adjust our txcore, keeping voice and
3155 non-voice synchronized */
3156 add_ms(&p->offset, (int)(ms - p->nextpred)/10);
3159 p->nextpred = ms; /*f->samples / 8;*/
3160 if (p->nextpred <= p->lastsent)
3161 p->nextpred = p->lastsent + 3;
3165 /* in this case, just use the actual
3166 * time, since we're either way off
3167 * (shouldn't happen), or we're ending a
3168 * silent period -- and seed the next
3169 * predicted time. Also, round ms to the
3170 * next multiple of frame size (so our
3171 * silent periods are multiples of
3172 * frame size too) */
3173 if (f->samples >= 8) /* check to make sure we dont core dump */
3175 int diff = ms % (f->samples / 8);
3177 ms += f->samples/8 - diff;
3184 /* On a dataframe, use last value + 3 (to accomodate jitter buffer shrinking) if appropriate unless
3185 it's a genuine frame */
3187 /* genuine (IAX LAGRQ etc) must keep their clock-based stamps */
3188 if (ms <= p->lastsent)
3189 ms = p->lastsent + 3;
3190 } else if (abs(ms - p->lastsent) <= MAX_TIMESTAMP_SKEW) {
3191 /* non-genuine frames (!?) (DTMF, CONTROL) should be pulled into the predicted stream stamps */
3192 ms = p->lastsent + 3;
3198 p->nextpred = p->nextpred + f->samples / 8;
3200 printf("TS: %s - %dms\n", voice ? "Audio" : "Control", ms);
3205 #ifdef BRIDGE_OPTIMIZATION
3206 static unsigned int calc_fakestamp(struct chan_iax2_pvt *p1, struct chan_iax2_pvt *p2, unsigned int fakets)
3209 /* Receive from p1, send to p2 */
3211 /* Setup rxcore if necessary on outgoing channel */
3212 if (!p1->rxcore.tv_sec && !p1->rxcore.tv_usec)
3213 gettimeofday(&p1->rxcore, NULL);
3215 /* Setup txcore if necessary on outgoing channel */
3216 if (!p2->offset.tv_sec && !p2->offset.tv_usec)
3217 gettimeofday(&p2->offset, NULL);
3219 /* Now, ts is the timestamp of the original packet in the orignal context.
3220 Adding rxcore to it gives us when we would want the packet to be delivered normally.
3221 Subtracting txcore of the outgoing channel gives us what we'd expect */
3223 ms = (p1->rxcore.tv_sec - p2->offset.tv_sec) * 1000 +
3224 (1000000 + p1->rxcore.tv_usec - p2->offset.tv_usec) / 1000 - 1000;
3227 /* FIXME? SLD would rather remove this and leave it to the end system to deal with */
3228 if (fakets <= p2->lastsent)
3229 fakets = p2->lastsent + 1;
3230 p2->lastsent = fakets;
3235 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset)
3237 /* Returns where in "receive time" we are. That is, how many ms
3238 since we received (or would have received) the frame with timestamp 0 */
3241 /* Setup rxcore if necessary */
3242 if (!p->rxcore.tv_sec && !p->rxcore.tv_usec) {
3243 gettimeofday(&p->rxcore, NULL);
3245 ast_log(LOG_DEBUG, "calc_rxstamp: call=%d: rxcore set to %d.%6.6d - %dms\n",
3246 p->callno, (int)(p->rxcore.tv_sec), (int)(p->rxcore.tv_usec), offset);
3247 p->rxcore.tv_sec -= offset / 1000;
3248 p->rxcore.tv_usec -= (offset % 1000) * 1000;
3249 if (p->rxcore.tv_usec < 0) {
3250 p->rxcore.tv_usec += 1000000;
3251 p->rxcore.tv_sec -= 1;
3255 ast_log(LOG_DEBUG, "calc_rxstamp: call=%d: works out as %d.%6.6d\n",
3256 p->callno, (int)(p->rxcore.tv_sec),(int)( p->rxcore.tv_usec));
3260 gettimeofday(&tv, NULL);
3261 ms = (tv.tv_sec - p->rxcore.tv_sec) * 1000 +
3262 (1000000 + tv.tv_usec - p->rxcore.tv_usec) / 1000 - 1000;
3266 static struct iax2_trunk_peer *find_tpeer(struct sockaddr_in *sin, int fd)
3268 struct iax2_trunk_peer *tpeer;
3269 char iabuf[INET_ADDRSTRLEN];
3270 /* Finds and locks trunk peer */
3271 ast_mutex_lock(&tpeerlock);
3274 /* We don't lock here because tpeer->addr *never* changes */
3275 if (!inaddrcmp(&tpeer->addr, sin)) {
3276 ast_mutex_lock(&tpeer->lock);
3279 tpeer = tpeer->next;
3282 tpeer = malloc(sizeof(struct iax2_trunk_peer));
3284 memset(tpeer, 0, sizeof(struct iax2_trunk_peer));
3285 ast_mutex_init(&tpeer->lock);
3286 tpeer->lastsent = 9999;
3287 memcpy(&tpeer->addr, sin, sizeof(tpeer->addr));
3288 gettimeofday(&tpeer->trunkact, NULL);
3289 ast_mutex_lock(&tpeer->lock);
3290 tpeer->next = tpeers;
3293 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));
3296 ast_mutex_unlock(&tpeerlock);
3300 static int iax2_trunk_queue(struct chan_iax2_pvt *pvt, struct ast_frame *f)
3302 struct iax2_trunk_peer *tpeer;
3304 struct ast_iax2_meta_trunk_entry *met;
3305 char iabuf[INET_ADDRSTRLEN];
3306 tpeer = find_tpeer(&pvt->addr, pvt->sockfd);
3308 if (tpeer->trunkdatalen + f->datalen + 4 >= tpeer->trunkdataalloc) {
3309 /* Need to reallocate space */
3310 if (tpeer->trunkdataalloc < MAX_TRUNKDATA) {
3311 tmp = realloc(tpeer->trunkdata, tpeer->trunkdataalloc + DEFAULT_TRUNKDATA + IAX2_TRUNK_PREFACE);
3313 tpeer->trunkdataalloc += DEFAULT_TRUNKDATA;
3314 tpeer->trunkdata = tmp;
3315 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);
3317 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));
3318 ast_mutex_unlock(&tpeer->lock);
3322 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));
3323 ast_mutex_unlock(&tpeer->lock);
3328 /* Append to meta frame */
3329 ptr = tpeer->trunkdata + IAX2_TRUNK_PREFACE + tpeer->trunkdatalen;
3330 met = (struct ast_iax2_meta_trunk_entry *)ptr;
3331 /* Store call number and length in meta header */
3332 met->callno = htons(pvt->callno);
3333 met->len = htons(f->datalen);
3334 /* Advance pointers/decrease length past trunk entry header */
3335 ptr += sizeof(struct ast_iax2_meta_trunk_entry);
3336 tpeer->trunkdatalen += sizeof(struct ast_iax2_meta_trunk_entry);
3337 /* Copy actual trunk data */
3338 memcpy(ptr, f->data, f->datalen);
3339 tpeer->trunkdatalen += f->datalen;
3341 ast_mutex_unlock(&tpeer->lock);
3346 static void build_enc_keys(const unsigned char *digest, aes_encrypt_ctx *ecx, aes_decrypt_ctx *dcx)
3348 aes_encrypt_key128(digest, ecx);
3349 aes_decrypt_key128(digest, dcx);
3352 static void memcpy_decrypt(unsigned char *dst, const unsigned char *src, int len, aes_decrypt_ctx *dcx)
3354 /* memcpy(dst, src, len); */
3355 unsigned char lastblock[16] = { 0 };
3358 aes_decrypt(src, dst, dcx);
3360 dst[x] ^= lastblock[x];
3361 memcpy(lastblock, src, sizeof(lastblock));
3368 static void memcpy_encrypt(unsigned char *dst, const unsigned char *src, int len, aes_encrypt_ctx *ecx)
3370 /* memcpy(dst, src, len); */
3371 unsigned char curblock[16] = { 0 };
3375 curblock[x] ^= src[x];
3376 aes_encrypt(curblock, dst, ecx);
3377 memcpy(curblock, dst, sizeof(curblock));
3384 static int decode_frame(aes_decrypt_ctx *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen)
3387 unsigned char *workspace;
3388 workspace = alloca(*datalen);
3391 if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
3392 struct ast_iax2_full_enc_hdr *efh = (struct ast_iax2_full_enc_hdr *)fh;
3394 ast_log(LOG_DEBUG, "Decoding full frame with length %d\n", *datalen);
3395 if (*datalen < 16 + sizeof(struct ast_iax2_full_hdr))
3397 padding = 16 + (efh->encdata[15] & 0xf);
3398 if (*datalen < padding + sizeof(struct ast_iax2_full_hdr))
3401 memcpy_decrypt(workspace, efh->encdata, *datalen, dcx);
3402 *datalen -= padding;
3403 memcpy(efh->encdata, workspace + padding, *datalen - sizeof(struct ast_iax2_full_enc_hdr));
3404 f->frametype = fh->type;
3405 if (f->frametype == AST_FRAME_VIDEO) {
3406 f->subclass = uncompress_subclass(fh->csub & ~0x40) | ((fh->csub >> 6) & 0x1);
3408 f->subclass = uncompress_subclass(fh->csub);
3411 struct ast_iax2_mini_enc_hdr *efh = (struct ast_iax2_mini_enc_hdr *)fh;
3413 ast_log(LOG_DEBUG, "Decoding mini with length %d\n", *datalen);
3414 if (*datalen < 16 + sizeof(struct ast_iax2_mini_hdr))
3416 padding = 16 + (efh->encdata[15] & 0x0f);
3417 if (*datalen < padding + sizeof(struct ast_iax2_mini_hdr))
3420 memcpy_decrypt(workspace, efh->encdata, *datalen, dcx);
3421 *datalen -= padding;
3422 memcpy(efh->encdata, workspace + padding, *datalen - sizeof(struct ast_iax2_mini_enc_hdr));
3427 static int encrypt_frame(aes_encrypt_ctx *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen)
3430 unsigned char *workspace;
3431 workspace = alloca(*datalen + 32);
3434 if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
3435 struct ast_iax2_full_enc_hdr *efh = (struct ast_iax2_full_enc_hdr *)fh;
3437 ast_log(LOG_DEBUG, "Encoding full frame with length %d\n", *datalen);
3438 padding = 16 - ((*datalen - sizeof(struct ast_iax2_full_enc_hdr)) % 16);
3439 padding = 16 + (padding & 0xf);
3440 memcpy(workspace, poo, padding);
3441 memcpy(workspace + padding, efh->encdata, *datalen - sizeof(struct ast_iax2_full_enc_hdr));
3442 *datalen += padding;
3443 workspace[15] &= 0xf0;
3444 workspace[15] |= (padding & 0xf);
3445 memcpy_encrypt(efh->encdata, workspace, *datalen, ecx);
3446 if (*datalen >= 32 + sizeof(struct ast_iax2_full_enc_hdr))
3447 memcpy(poo, workspace + *datalen - 32, 32);
3449 struct ast_iax2_mini_enc_hdr *efh = (struct ast_iax2_mini_enc_hdr *)fh;