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/channel_pvt.h>
18 #include <asterisk/logger.h>
19 #include <asterisk/module.h>
20 #include <asterisk/pbx.h>
21 #include <asterisk/sched.h>
22 #include <asterisk/io.h>
23 #include <asterisk/config.h>
24 #include <asterisk/options.h>
25 #include <asterisk/cli.h>
26 #include <asterisk/translate.h>
27 #include <asterisk/md5.h>
28 #include <asterisk/cdr.h>
29 #include <asterisk/crypto.h>
30 #include <asterisk/acl.h>
31 #include <asterisk/manager.h>
32 #include <asterisk/callerid.h>
33 #include <asterisk/app.h>
34 #include <asterisk/astdb.h>
35 #include <asterisk/musiconhold.h>
36 #include <asterisk/features.h>
37 #include <asterisk/utils.h>
38 #include <asterisk/causes.h>
39 #include <asterisk/localtime.h>
40 #include <asterisk/aes.h>
42 #include <arpa/inet.h>
44 #include <sys/socket.h>
45 #include <netinet/in.h>
46 #include <netinet/in_systm.h>
47 #include <netinet/ip.h>
49 #include <sys/signal.h>
58 #include <sys/types.h>
62 #include <sys/ioctl.h>
64 #include <linux/zaptel.h>
67 #endif /* __linux__ */
70 #include "iax2-parser.h"
71 #include "iax2-provision.h"
72 #include "../astconf.h"
75 #define IPTOS_MINCOST 0x02
79 * Uncomment to try experimental IAX bridge optimization,
80 * designed to reduce latency when IAX calls cannot
84 #define BRIDGE_OPTIMIZATION
86 #define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
87 #define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
89 #define DEFAULT_RETRY_TIME 1000
90 #define MEMORY_SIZE 100
91 #define DEFAULT_DROP 3
92 /* Flag to use with trunk calls, keeping these calls high up. It halves our effective use
93 but keeps the division between trunked and non-trunked better. */
94 #define TRUNK_CALL_START 0x4000
98 #define MIN_REUSE_TIME 60 /* Don't reuse a call number within 60 seconds */
100 /* Sample over last 100 units to determine historic jitter */
103 static struct ast_codec_pref prefs;
105 static char *desc = "Inter Asterisk eXchange (Ver 2)";
106 static char *tdesc = "Inter Asterisk eXchange Driver (Ver 2)";
107 static char *channeltype = "IAX2";
109 static char context[80] = "default";
111 static char language[MAX_LANGUAGE] = "";
112 static char regcontext[AST_MAX_EXTENSION] = "";
114 static int max_retries = 4;
115 static int ping_time = 20;
116 static int lagrq_time = 10;
117 static int maxtrunkcall = TRUNK_CALL_START;
118 static int maxnontrunkcall = 1;
119 static int maxjitterbuffer=1000;
120 static int jittershrinkrate=2;
121 static int trunkfreq = 20;
122 static int authdebug = 1;
123 static int autokill = 0;
124 static int iaxcompat = 0;
126 static int iaxdefaultdpcache=10 * 60; /* Cache dialplan entries for 10 minutes by default */
128 static int iaxdefaulttimeout = 5; /* Default to wait no more than 5 seconds for a reply to come back */
132 static int expirey = IAX_DEFAULT_REG_EXPIRE;
134 static int timingfd = -1; /* Timing file descriptor */
136 static struct ast_netsock_list netsock;
137 static int defaultsockfd = -1;
140 AST_MUTEX_DEFINE_STATIC(usecnt_lock);
142 int (*iax2_regfunk)(char *username, int onoff) = NULL;
145 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
147 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
148 ~AST_FORMAT_SLINEAR & \
152 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
156 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
160 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
161 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
162 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
164 static struct io_context *io;
165 static struct sched_context *sched;
167 static int iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
169 static int iax2_dropcount = DEFAULT_DROP;
171 static int iaxdebug = 0;
173 static int iaxtrunkdebug = 0;
175 static char accountcode[20];
176 static int amaflags = 0;
177 static int delayreject = 0;
178 static int iax2_encryption = 0;
180 static struct ast_flags globalflags = {0};
182 static pthread_t netthreadid = AST_PTHREADT_NULL;
184 #define IAX_STATE_STARTED (1 << 0)
185 #define IAX_STATE_AUTHENTICATED (1 << 1)
186 #define IAX_STATE_TBD (1 << 2)
188 struct iax2_context {
189 char context[AST_MAX_EXTENSION];
190 struct iax2_context *next;
193 #define IAX_HASCALLERID (1 << 0) /* CallerID has been specified */
194 #define IAX_DELME (1 << 1) /* Needs to be deleted */
195 #define IAX_TEMPONLY (1 << 2) /* Temporary (realtime) */
196 #define IAX_TRUNK (1 << 3) /* Treat as a trunk */
197 #define IAX_NOTRANSFER (1 << 4) /* Don't native bridge */
198 #define IAX_USEJITTERBUF (1 << 5) /* Use jitter buffer */
199 #define IAX_DYNAMIC (1 << 6) /* dynamic peer */
200 #define IAX_SENDANI (1 << 7) /* Send ANI along with CallerID */
201 #define IAX_MESSAGEDETAIL (1 << 8) /* Show exact numbers */
202 #define IAX_ALREADYGONE (1 << 9) /* Already disconnected */
203 #define IAX_PROVISION (1 << 10) /* This is a provisioning request */
204 #define IAX_QUELCH (1 << 11) /* Whether or not we quelch audio */
205 #define IAX_ENCRYPTED (1 << 12) /* Whether we should assume encrypted tx/rx */
206 #define IAX_KEYPOPULATED (1 << 13) /* Whether we have a key populated */
207 #define IAX_CODEC_USER_FIRST (1 << 14) /* are we willing to let the other guy choose the codec? */
208 #define IAX_CODEC_NOPREFS (1 << 15) /* Force old behaviour by turning off prefs */
209 #define IAX_CODEC_NOCAP (1 << 16) /* only consider requested format and ignore capabilities*/
210 #define IAX_RTCACHEFRIENDS (1 << 17) /* let realtime stay till your reload */
211 #define IAX_RTNOUPDATE (1 << 18) /* Don't send a realtime update */
212 #define IAX_RTAUTOCLEAR (1 << 19) /* erase me on expire */
214 static int global_rtautoclear = 120;
216 static struct iax2_peer *realtime_peer(const char *peername);
217 static int reload_config(void);
225 char accountcode[20];
226 char inkeys[80]; /* Key(s) this user can use to authenticate to us */
227 char language[MAX_LANGUAGE];
231 char cid_num[AST_MAX_EXTENSION];
232 char cid_name[AST_MAX_EXTENSION];
233 struct ast_codec_pref prefs;
235 struct iax2_context *contexts;
236 struct iax2_user *next;
237 struct ast_variable *vars;
245 char outkey[80]; /* What key we use to talk to this peer */
246 char context[AST_MAX_EXTENSION]; /* For transfers only */
247 char regexten[AST_MAX_EXTENSION]; /* Extension to register (if regcontext is used) */
248 char peercontext[AST_MAX_EXTENSION]; /* Context to pass to peer */
249 char mailbox[AST_MAX_EXTENSION]; /* Mailbox */
250 struct ast_codec_pref prefs;
251 struct sockaddr_in addr;
253 int sockfd; /* Socket to use for transmission */
257 /* Dynamic Registration fields */
258 struct sockaddr_in defaddr; /* Default address if there is one */
259 int authmethods; /* Authentication methods (IAX_AUTH_*) */
260 int encmethods; /* Encryption methods (IAX_ENCRYPT_*) */
261 char inkeys[80]; /* Key(s) this peer can use to authenticate to us */
263 /* Suggested caller id if registering */
264 char cid_num[AST_MAX_EXTENSION]; /* Default context (for transfer really) */
265 char cid_name[AST_MAX_EXTENSION]; /* Default context (for transfer really) */
267 int expire; /* Schedule entry for expirey */
268 int expirey; /* How soon to expire */
269 int capability; /* Capability */
270 char zonetag[80]; /* Time Zone */
273 int callno; /* Call number of POKE request */
274 int pokeexpire; /* When to expire poke */
275 int lastms; /* How long last response took (in ms), or -1 for no response */
276 int maxms; /* Max ms we will accept for the host to be up, 0 to not monitor */
279 struct iax2_peer *next;
282 #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
284 static struct iax2_trunk_peer {
287 struct sockaddr_in addr;
288 struct timeval txtrunktime; /* Transmit trunktime */
289 struct timeval rxtrunktime; /* Receive trunktime */
290 struct timeval lasttxtime; /* Last transmitted trunktime */
291 struct timeval trunkact; /* Last trunk activity */
292 unsigned int lastsent; /* Last sent time */
293 /* Trunk data and length */
294 unsigned char *trunkdata;
295 unsigned int trunkdatalen;
296 unsigned int trunkdataalloc;
297 struct iax2_trunk_peer *next;
302 AST_MUTEX_DEFINE_STATIC(tpeerlock);
304 struct iax_firmware {
305 struct iax_firmware *next;
309 struct ast_iax2_firmware_header *fwh;
313 #define REG_STATE_UNREGISTERED 0
314 #define REG_STATE_REGSENT 1
315 #define REG_STATE_AUTHSENT 2
316 #define REG_STATE_REGISTERED 3
317 #define REG_STATE_REJECTED 4
318 #define REG_STATE_TIMEOUT 5
319 #define REG_STATE_NOAUTH 6
321 #define TRANSFER_NONE 0
322 #define TRANSFER_BEGIN 1
323 #define TRANSFER_READY 2
324 #define TRANSFER_RELEASED 3
325 #define TRANSFER_PASSTHROUGH 4
327 struct iax2_registry {
328 struct sockaddr_in addr; /* Who we connect to for registration purposes */
330 char secret[80]; /* Password or key name in []'s */
332 int expire; /* Sched ID of expiration */
333 int refresh; /* How often to refresh */
335 int messages; /* Message count */
336 int callno; /* Associated call number if applicable */
337 struct sockaddr_in us; /* Who the server thinks we are */
338 struct iax2_registry *next;
341 static struct iax2_registry *registrations;
343 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
344 #define MIN_RETRY_TIME 100
345 #define MAX_RETRY_TIME 10000
347 #define MAX_JITTER_BUFFER 50
348 #define MIN_JITTER_BUFFER 10
350 #define DEFAULT_TRUNKDATA 640 * 10 /* 40ms, uncompressed linear * 10 channels */
351 #define MAX_TRUNKDATA 640 * 200 /* 40ms, uncompressed linear * 200 channels */
353 #define MAX_TIMESTAMP_SKEW 640
355 /* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
356 #define TS_GAP_FOR_JB_RESYNC 5000
358 /* If we have more than this much excess real jitter buffer, shrink it. */
359 static int max_jitter_buffer = MAX_JITTER_BUFFER;
360 /* If we have less than this much excess real jitter buffer, enlarge it. */
361 static int min_jitter_buffer = MIN_JITTER_BUFFER;
363 struct chan_iax2_pvt {
364 /* Socket to send/receive on for this call */
366 /* Last received voice format */
368 /* Last received voice format */
370 /* Last sent voice format */
372 /* Last sent video format */
374 /* What we are capable of sending */
376 /* Last received timestamp */
378 /* Last sent timestamp - never send the same timestamp twice in a single call */
379 unsigned int lastsent;
380 /* Next outgoing timestamp if everything is good */
381 unsigned int nextpred;
382 /* True if the last voice we transmitted was not silence/CNG */
385 unsigned int pingtime;
386 /* Max time for initial response */
389 struct sockaddr_in addr;
390 struct ast_codec_pref prefs;
391 /* Our call number */
392 unsigned short callno;
394 unsigned short peercallno;
395 /* Peer selected format */
397 /* Peer capability */
399 /* timeval that we base our transmission on */
400 struct timeval offset;
401 /* timeval that we base our delivery on */
402 struct timeval rxcore;
403 /* Historical delivery time */
404 int history[MEMORY_SIZE];
405 /* Current base jitterbuffer */
407 /* Current jitter measure */
409 /* Historic jitter value */
413 /* Error, as discovered by the manager */
415 /* Owner if we have one */
416 struct ast_channel *owner;
417 /* What's our state? */
419 /* Expirey (optional) */
421 /* Next outgoing sequence number */
422 unsigned char oseqno;
423 /* Next sequence number they have not yet acknowledged */
424 unsigned char rseqno;
425 /* Next incoming sequence number */
426 unsigned char iseqno;
427 /* Last incoming sequence number we have acknowledged */
428 unsigned char aseqno;
431 /* Default Context */
433 /* Caller ID if available */
436 /* Hidden Caller ID (i.e. ANI) if appropriate */
440 /* Requested Extension */
441 char exten[AST_MAX_EXTENSION];
442 /* Expected Username */
444 /* Expected Secret */
446 /* permitted authentication methods */
448 /* permitted encryption methods */
452 /* Public keys permitted keys for incoming authentication */
454 /* Private key for outgoing authentication */
456 /* Encryption AES-128 Key */
458 /* Decryption AES-128 Key */
460 /* 32 bytes of semi-random data */
462 /* Preferred language */
463 char language[MAX_LANGUAGE];
464 /* Hostname/peername for naming purposes */
466 /* Associated registry */
467 struct iax2_registry *reg;
468 /* Associated peer for poking */
469 struct iax2_peer *peerpoke;
473 /* Transferring status */
475 /* Transfer identifier */
477 /* Who we are IAX transfering to */
478 struct sockaddr_in transfer;
479 /* What's the new call number for the transfer */
480 unsigned short transfercallno;
481 /* Transfer decrypt AES-128 Key */
482 aes_encrypt_ctx tdcx;
484 /* Status of knowledge of peer ADSI capability */
487 /* Who we are bridged to */
488 unsigned short bridgecallno;
489 unsigned int bridgesfmt;
490 struct ast_trans_pvt *bridgetrans;
492 int pingid; /* Transmit PING request */
493 int lagid; /* Retransmit lag request */
494 int autoid; /* Auto hangup for Dialplan requestor */
495 int authid; /* Authentication rejection ID */
496 int authfail; /* Reason to report failure */
497 int initid; /* Initial peer auto-congest ID (based on qualified peers) */
501 char dproot[AST_MAX_EXTENSION];
502 char accountcode[20];
504 struct iax2_dpcache *dpentries;
505 struct ast_variable *vars;
508 static struct ast_iax2_queue {
509 struct iax_frame *head;
510 struct iax_frame *tail;
515 static struct ast_user_list {
516 struct iax2_user *users;
520 static struct ast_peer_list {
521 struct iax2_peer *peers;
525 static struct ast_firmware_list {
526 struct iax_firmware *wares;
530 /* Extension exists */
531 #define CACHE_FLAG_EXISTS (1 << 0)
532 /* Extension is non-existant */
533 #define CACHE_FLAG_NONEXISTANT (1 << 1)
534 /* Extension can exist */
535 #define CACHE_FLAG_CANEXIST (1 << 2)
536 /* Waiting to hear back response */
537 #define CACHE_FLAG_PENDING (1 << 3)
539 #define CACHE_FLAG_TIMEOUT (1 << 4)
540 /* Request transmitted */
541 #define CACHE_FLAG_TRANSMITTED (1 << 5)
543 #define CACHE_FLAG_UNKNOWN (1 << 6)
545 #define CACHE_FLAG_MATCHMORE (1 << 7)
547 static struct iax2_dpcache {
548 char peercontext[AST_MAX_EXTENSION];
549 char exten[AST_MAX_EXTENSION];
551 struct timeval expirey;
553 unsigned short callno;
555 struct iax2_dpcache *next;
556 struct iax2_dpcache *peer; /* For linking in peers */
559 AST_MUTEX_DEFINE_STATIC(dpcache_lock);
561 static void destroy_peer(struct iax2_peer *peer);
563 static void iax_debug_output(const char *data)
566 ast_verbose("%s", data);
569 static void iax_error_output(const char *data)
571 ast_log(LOG_WARNING, "%s", data);
574 /* XXX We probably should use a mutex when working with this XXX */
575 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS];
576 static ast_mutex_t iaxsl[IAX_MAX_CALLS];
577 static struct timeval lastused[IAX_MAX_CALLS];
580 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, char *, int, int);
581 static int send_command_locked(unsigned short callno, char, int, unsigned int, char *, int, int);
582 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, char *, int, int);
583 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, char *, int, int);
584 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, char *, int);
585 static struct iax2_user *build_user(const char *name, struct ast_variable *v, int temponly);
586 static void destroy_user(struct iax2_user *user);
587 static int expire_registry(void *data);
588 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
589 static int iax2_do_register(struct iax2_registry *reg);
590 static void prune_peers(void);
591 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
592 static int iax2_provision(struct sockaddr_in *end, char *dest, const char *template, int force);
595 static int send_ping(void *data)
597 int callno = (long)data;
598 /* Ping only if it's real, not if it's bridged */
600 #ifdef BRIDGE_OPTIMIZATION
601 if (!iaxs[callno]->bridgecallno)
603 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
609 static int get_encrypt_methods(const char *s)
612 if (!strcasecmp(s, "aes128"))
613 e = IAX_ENCRYPT_AES128;
614 else if (ast_true(s))
615 e = IAX_ENCRYPT_AES128;
621 static int send_lagrq(void *data)
623 int callno = (long)data;
624 /* Ping only if it's real not if it's bridged */
626 #ifdef BRIDGE_OPTIMIZATION
627 if (!iaxs[callno]->bridgecallno)
629 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
635 static unsigned char compress_subclass(int subclass)
639 /* If it's 128 or smaller, just return it */
640 if (subclass < IAX_FLAG_SC_LOG)
642 /* Otherwise find its power */
643 for (x = 0; x < IAX_MAX_SHIFT; x++) {
644 if (subclass & (1 << x)) {
646 ast_log(LOG_WARNING, "Can't compress subclass %d\n", subclass);
652 return power | IAX_FLAG_SC_LOG;
655 static int uncompress_subclass(unsigned char csub)
657 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
658 if (csub & IAX_FLAG_SC_LOG) {
659 /* special case for 'compressed' -1 */
663 return 1 << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
669 static struct iax2_peer *find_peer(const char *name, int realtime)
671 struct iax2_peer *peer;
672 ast_mutex_lock(&peerl.lock);
673 for(peer = peerl.peers; peer; peer = peer->next) {
674 if (!strcasecmp(peer->name, name)) {
678 ast_mutex_unlock(&peerl.lock);
679 if(!peer && realtime)
680 peer = realtime_peer(name);
684 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len, int lockpeer)
686 struct iax2_peer *peer;
689 ast_mutex_lock(&peerl.lock);
692 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
693 (peer->addr.sin_port == sin.sin_port)) {
694 strncpy(host, peer->name, len-1);
701 ast_mutex_unlock(&peerl.lock);
705 static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, int lockpeer, const char *host)
707 struct chan_iax2_pvt *tmp;
708 tmp = malloc(sizeof(struct chan_iax2_pvt));
710 memset(tmp, 0, sizeof(struct chan_iax2_pvt));
714 tmp->transfercallno = 0;
715 tmp->bridgecallno = 0;
721 /* strncpy(tmp->context, context, sizeof(tmp->context)-1); */
722 strncpy(tmp->exten, "s", sizeof(tmp->exten)-1);
723 strncpy(tmp->host, host, sizeof(tmp->host)-1);
728 static int get_samples(struct ast_frame *f)
731 switch(f->subclass) {
732 case AST_FORMAT_SPEEX:
733 samples = 160; /* XXX Not necessarily true XXX */
735 case AST_FORMAT_G723_1:
736 samples = 240 /* XXX Not necessarily true XXX */;
738 case AST_FORMAT_ILBC:
739 samples = 240 * (f->datalen / 50);
742 samples = 160 * (f->datalen / 33);
744 case AST_FORMAT_G729A:
745 samples = 160 * (f->datalen / 20);
747 case AST_FORMAT_SLINEAR:
748 samples = f->datalen / 2;
750 case AST_FORMAT_LPC10:
752 samples += (((char *)(f->data))[7] & 0x1) * 8;
754 case AST_FORMAT_ULAW:
755 samples = f->datalen;
757 case AST_FORMAT_ALAW:
758 samples = f->datalen;
760 case AST_FORMAT_ADPCM:
761 case AST_FORMAT_G726:
762 samples = f->datalen *2;
765 ast_log(LOG_WARNING, "Don't know how to calculate samples on %d packets\n", f->subclass);
770 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
772 /* Malloc() a copy of a frame */
773 struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen);
775 memcpy(new, fr, sizeof(struct iax_frame));
776 iax_frame_wrap(new, &fr->af);
779 new->direction = DIRECTION_INGRESS;
785 #define NEW_PREVENT 0
789 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, struct chan_iax2_pvt *cur)
791 if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
792 (cur->addr.sin_port == sin->sin_port)) {
793 /* This is the main host */
794 if ((cur->peercallno == callno) ||
795 ((dcallno == cur->callno) && !cur->peercallno)) {
796 /* That's us. Be sure we keep track of the peer call number */
800 if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
801 (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
802 /* We're transferring */
803 if (dcallno == cur->callno)
809 static void update_max_trunk(void)
811 int max = TRUNK_CALL_START;
813 /* XXX Prolly don't need locks here XXX */
814 for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
820 ast_log(LOG_DEBUG, "New max trunk callno is %d\n", max);
823 static void update_max_nontrunk(void)
827 /* XXX Prolly don't need locks here XXX */
828 for (x=1;x<TRUNK_CALL_START - 1; x++) {
832 maxnontrunkcall = max;
834 ast_log(LOG_DEBUG, "New max nontrunk callno is %d\n", max);
837 static int make_trunk(unsigned short callno, int locked)
842 if (iaxs[callno]->oseqno) {
843 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
846 if (callno & TRUNK_CALL_START) {
847 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
850 gettimeofday(&now, NULL);
851 for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
852 ast_mutex_lock(&iaxsl[x]);
853 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) {
854 iaxs[x] = iaxs[callno];
857 /* Update the two timers that should have been started */
858 if (iaxs[x]->pingid > -1)
859 ast_sched_del(sched, iaxs[x]->pingid);
860 if (iaxs[x]->lagid > -1)
861 ast_sched_del(sched, iaxs[x]->lagid);
862 iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
863 iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
865 ast_mutex_unlock(&iaxsl[callno]);
868 ast_mutex_unlock(&iaxsl[x]);
871 ast_mutex_unlock(&iaxsl[x]);
873 if (x >= IAX_MAX_CALLS - 1) {
874 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
877 ast_log(LOG_DEBUG, "Made call %d into trunk call %d\n", callno, x);
878 /* We move this call from a non-trunked to a trunked call */
880 update_max_nontrunk();
884 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int lockpeer, int sockfd)
889 char iabuf[INET_ADDRSTRLEN];
891 if (new <= NEW_ALLOW) {
892 /* Look for an existing connection first */
893 for (x=1;(res < 1) && (x<maxnontrunkcall);x++) {
894 ast_mutex_lock(&iaxsl[x]);
896 /* Look for an exact match */
897 if (match(sin, callno, dcallno, iaxs[x])) {
901 ast_mutex_unlock(&iaxsl[x]);
903 for (x=TRUNK_CALL_START;(res < 1) && (x<maxtrunkcall);x++) {
904 ast_mutex_lock(&iaxsl[x]);
906 /* Look for an exact match */
907 if (match(sin, callno, dcallno, iaxs[x])) {
911 ast_mutex_unlock(&iaxsl[x]);
914 if ((res < 1) && (new >= NEW_ALLOW)) {
915 if (!iax2_getpeername(*sin, host, sizeof(host), lockpeer))
916 snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr), ntohs(sin->sin_port));
917 gettimeofday(&now, NULL);
918 for (x=1;x<TRUNK_CALL_START;x++) {
919 /* Find first unused call number that hasn't been used in a while */
920 ast_mutex_lock(&iaxsl[x]);
921 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) break;
922 ast_mutex_unlock(&iaxsl[x]);
924 /* We've still got lock held if we found a spot */
925 if (x >= TRUNK_CALL_START) {
926 ast_log(LOG_WARNING, "No more space\n");
929 iaxs[x] = new_iax(sin, lockpeer, host);
930 update_max_nontrunk();
933 ast_log(LOG_DEBUG, "Creating new call structure %d\n", x);
934 iaxs[x]->sockfd = sockfd;
935 iaxs[x]->addr.sin_port = sin->sin_port;
936 iaxs[x]->addr.sin_family = sin->sin_family;
937 iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
938 iaxs[x]->peercallno = callno;
940 iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
941 iaxs[x]->expirey = expirey;
942 iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
943 iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
944 iaxs[x]->amaflags = amaflags;
945 ast_copy_flags(iaxs[x], (&globalflags), IAX_NOTRANSFER | IAX_USEJITTERBUF);
946 strncpy(iaxs[x]->accountcode, accountcode, sizeof(iaxs[x]->accountcode)-1);
948 ast_log(LOG_WARNING, "Out of resources\n");
949 ast_mutex_unlock(&iaxsl[x]);
952 ast_mutex_unlock(&iaxsl[x]);
958 static void iax2_frame_free(struct iax_frame *fr)
960 if (fr->retrans > -1)
961 ast_sched_del(sched, fr->retrans);
965 static int iax2_queue_frame(int callno, struct ast_frame *f)
967 /* Assumes lock for callno is already held... */
969 if (iaxs[callno] && iaxs[callno]->owner) {
970 if (ast_mutex_trylock(&iaxs[callno]->owner->lock)) {
971 /* Avoid deadlock by pausing and trying again */
972 ast_mutex_unlock(&iaxsl[callno]);
974 ast_mutex_lock(&iaxsl[callno]);
976 ast_queue_frame(iaxs[callno]->owner, f);
977 ast_mutex_unlock(&iaxs[callno]->owner->lock);
986 static void destroy_firmware(struct iax_firmware *cur)
990 munmap(cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh)));
996 static int try_firmware(char *s)
999 struct iax_firmware *cur;
1004 struct ast_iax2_firmware_header *fwh, fwh2;
1005 struct MD5Context md5;
1006 unsigned char sum[16];
1007 unsigned char buf[1024];
1011 s2 = alloca(strlen(s) + 100);
1013 ast_log(LOG_WARNING, "Alloca failed!\n");
1016 last = strrchr(s, '/');
1021 snprintf(s2, strlen(s) + 100, "/var/tmp/%s-%ld", last, (unsigned long)rand());
1022 res = stat(s, &stbuf);
1024 ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno));
1027 /* Make sure it's not a directory */
1028 if (S_ISDIR(stbuf.st_mode))
1030 ifd = open(s, O_RDONLY);
1032 ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
1035 fd = open(s2, O_RDWR | O_CREAT | O_EXCL);
1037 ast_log(LOG_WARNING, "Cannot open '%s' for writing: %s\n", s2, strerror(errno));
1041 /* Unlink our newly created file */
1044 /* Now copy the firmware into it */
1045 len = stbuf.st_size;
1048 if (chunk > sizeof(buf))
1049 chunk = sizeof(buf);
1050 res = read(ifd, buf, chunk);
1052 ast_log(LOG_WARNING, "Only read %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1057 res = write(fd, buf, chunk);
1059 ast_log(LOG_WARNING, "Only write %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1067 /* Return to the beginning */
1068 lseek(fd, 0, SEEK_SET);
1069 if ((res = read(fd, &fwh2, sizeof(fwh2))) != sizeof(fwh2)) {
1070 ast_log(LOG_WARNING, "Unable to read firmware header in '%s'\n", s);
1074 if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) {
1075 ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s);
1079 if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) {
1080 ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s);
1084 if (fwh2.devname[sizeof(fwh2.devname) - 1] || ast_strlen_zero(fwh2.devname)) {
1085 ast_log(LOG_WARNING, "No or invalid device type specified for '%s'\n", s);
1089 fwh = mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
1091 ast_log(LOG_WARNING, "mmap failed: %s\n", strerror(errno));
1096 MD5Update(&md5, fwh->data, ntohl(fwh->datalen));
1097 MD5Final(sum, &md5);
1098 if (memcmp(sum, fwh->chksum, sizeof(sum))) {
1099 ast_log(LOG_WARNING, "Firmware file '%s' fails checksum\n", s);
1100 munmap(fwh, stbuf.st_size);
1106 if (!strcmp(cur->fwh->devname, fwh->devname)) {
1107 /* Found a candidate */
1108 if (cur->dead || (ntohs(cur->fwh->version) < ntohs(fwh->version)))
1109 /* The version we have on loaded is older, load this one instead */
1111 /* This version is no newer than what we have. Don't worry about it.
1112 We'll consider it a proper load anyhow though */
1113 munmap(fwh, stbuf.st_size);
1120 /* Allocate a new one and link it */
1121 cur = malloc(sizeof(struct iax_firmware));
1123 memset(cur, 0, sizeof(struct iax_firmware));
1125 cur->next = waresl.wares;
1131 munmap(cur->fwh, cur->mmaplen);
1137 cur->mmaplen = stbuf.st_size;
1143 static int iax_check_version(char *dev)
1146 struct iax_firmware *cur;
1147 if (dev && !ast_strlen_zero(dev)) {
1148 ast_mutex_lock(&waresl.lock);
1151 if (!strcmp(dev, cur->fwh->devname)) {
1152 res = ntohs(cur->fwh->version);
1157 ast_mutex_unlock(&waresl.lock);
1162 static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
1165 unsigned int bs = desc & 0xff;
1166 unsigned int start = (desc >> 8) & 0xffffff;
1168 struct iax_firmware *cur;
1169 if (dev && !ast_strlen_zero(dev) && bs) {
1171 ast_mutex_lock(&waresl.lock);
1174 if (!strcmp(dev, cur->fwh->devname)) {
1175 iax_ie_append_int(ied, IAX_IE_FWBLOCKDESC, desc);
1176 if (start < ntohl(cur->fwh->datalen)) {
1177 bytes = ntohl(cur->fwh->datalen) - start;
1180 iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes);
1183 iax_ie_append(ied, IAX_IE_FWBLOCKDATA);
1193 ast_mutex_unlock(&waresl.lock);
1199 static void reload_firmware(void)
1201 struct iax_firmware *cur, *curl, *curp;
1206 /* Mark all as dead */
1207 ast_mutex_lock(&waresl.lock);
1213 /* Now that we've freed them, load the new ones */
1214 snprintf(dir, sizeof(dir), "%s/firmware/iax", (char *)ast_config_AST_VAR_DIR);
1217 while((de = readdir(fwd))) {
1218 if (de->d_name[0] != '.') {
1219 snprintf(fn, sizeof(fn), "%s/%s", dir, de->d_name);
1220 if (!try_firmware(fn)) {
1221 if (option_verbose > 1)
1222 ast_verbose(VERBOSE_PREFIX_2 "Loaded firmware '%s'\n", de->d_name);
1228 ast_log(LOG_WARNING, "Error opening firmware directory '%s': %s\n", dir, strerror(errno));
1230 /* Clean up leftovers */
1242 destroy_firmware(curl);
1247 ast_mutex_unlock(&waresl.lock);
1250 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
1252 static int __do_deliver(void *data)
1254 /* Just deliver the packet by using queueing. This is called by
1255 the IAX thread with the iaxsl lock held. */
1256 struct iax_frame *fr = data;
1258 if (iaxs[fr->callno] && !ast_test_flag(iaxs[fr->callno], IAX_ALREADYGONE))
1259 iax2_queue_frame(fr->callno, &fr->af);
1260 /* Free our iax frame */
1261 iax2_frame_free(fr);
1262 /* And don't run again */
1266 static int do_deliver(void *data)
1268 /* Locking version of __do_deliver */
1269 struct iax_frame *fr = data;
1270 int callno = fr->callno;
1272 ast_mutex_lock(&iaxsl[callno]);
1273 res = __do_deliver(data);
1274 ast_mutex_unlock(&iaxsl[callno]);
1278 static int handle_error(void)
1280 /* XXX Ideally we should figure out why an error occured and then abort those
1281 rather than continuing to try. Unfortunately, the published interface does
1282 not seem to work XXX */
1284 struct sockaddr_in *sin;
1287 struct sock_extended_err e;
1292 m.msg_controllen = sizeof(e);
1294 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
1296 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
1298 if (m.msg_controllen) {
1299 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
1301 ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr));
1303 ast_log(LOG_WARNING, "No address detected??\n");
1305 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
1312 static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin, int sockfd)
1315 res = sendto(sockfd, f->data, f->datalen, 0,(struct sockaddr *)sin,
1319 ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
1326 static int send_packet(struct iax_frame *f)
1329 char iabuf[INET_ADDRSTRLEN];
1330 /* Called with iaxsl held */
1332 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));
1333 /* Don't send if there was an error, but return error instead */
1335 ast_log(LOG_WARNING, "Call number = %d\n", f->callno);
1338 if (!iaxs[f->callno])
1340 if (iaxs[f->callno]->error)
1344 iax_showframe(f, NULL, 0, &iaxs[f->callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
1345 res = sendto(iaxs[f->callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[f->callno]->transfer,
1346 sizeof(iaxs[f->callno]->transfer));
1349 iax_showframe(f, NULL, 0, &iaxs[f->callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
1350 res = sendto(iaxs[f->callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[f->callno]->addr,
1351 sizeof(iaxs[f->callno]->addr));
1355 ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
1363 static int iax2_predestroy(int callno)
1365 struct ast_channel *c;
1366 struct chan_iax2_pvt *pvt;
1367 ast_mutex_lock(&iaxsl[callno]);
1370 ast_mutex_unlock(&iaxsl[callno]);
1373 if (!ast_test_flag(pvt, IAX_ALREADYGONE)) {
1374 /* No more pings or lagrq's */
1375 if (pvt->pingid > -1)
1376 ast_sched_del(sched, pvt->pingid);
1377 if (pvt->lagid > -1)
1378 ast_sched_del(sched, pvt->lagid);
1379 if (pvt->autoid > -1)
1380 ast_sched_del(sched, pvt->autoid);
1381 if (pvt->authid > -1)
1382 ast_sched_del(sched, pvt->authid);
1383 if (pvt->initid > -1)
1384 ast_sched_del(sched, pvt->initid);
1390 ast_set_flag(pvt, IAX_ALREADYGONE);
1394 c->_softhangup |= AST_SOFTHANGUP_DEV;
1396 ast_queue_hangup(c);
1398 ast_mutex_lock(&usecnt_lock);
1401 ast_log(LOG_WARNING, "Usecnt < 0???\n");
1402 ast_mutex_unlock(&usecnt_lock);
1404 ast_mutex_unlock(&iaxsl[callno]);
1405 ast_update_use_count();
1409 static int iax2_predestroy_nolock(int callno)
1412 ast_mutex_unlock(&iaxsl[callno]);
1413 res = iax2_predestroy(callno);
1414 ast_mutex_lock(&iaxsl[callno]);
1418 static void iax2_destroy(int callno)
1420 struct chan_iax2_pvt *pvt;
1421 struct iax_frame *cur;
1422 struct ast_channel *owner;
1425 ast_mutex_lock(&iaxsl[callno]);
1427 gettimeofday(&lastused[callno], NULL);
1434 if (ast_mutex_trylock(&owner->lock)) {
1435 ast_log(LOG_NOTICE, "Avoiding IAX destroy deadlock\n");
1436 ast_mutex_unlock(&iaxsl[callno]);
1442 iaxs[callno] = NULL;
1446 /* No more pings or lagrq's */
1447 if (pvt->pingid > -1)
1448 ast_sched_del(sched, pvt->pingid);
1449 if (pvt->lagid > -1)
1450 ast_sched_del(sched, pvt->lagid);
1451 if (pvt->autoid > -1)
1452 ast_sched_del(sched, pvt->autoid);
1453 if (pvt->authid > -1)
1454 ast_sched_del(sched, pvt->authid);
1455 if (pvt->initid > -1)
1456 ast_sched_del(sched, pvt->initid);
1462 if (pvt->bridgetrans)
1463 ast_translator_free_path(pvt->bridgetrans);
1464 pvt->bridgetrans = NULL;
1467 ast_set_flag(pvt, IAX_ALREADYGONE);
1470 /* If there's an owner, prod it to give up */
1471 owner->_softhangup |= AST_SOFTHANGUP_DEV;
1472 ast_queue_hangup(owner);
1475 for (cur = iaxq.head; cur ; cur = cur->next) {
1476 /* Cancel any pending transmissions */
1477 if (cur->callno == pvt->callno)
1481 pvt->reg->callno = 0;
1485 ast_variables_destroy(pvt->vars);
1492 ast_mutex_unlock(&owner->lock);
1494 ast_mutex_unlock(&iaxsl[callno]);
1495 if (callno & 0x4000)
1498 static void iax2_destroy_nolock(int callno)
1500 /* Actually it's easier to unlock, kill it, and relock */
1501 ast_mutex_unlock(&iaxsl[callno]);
1502 iax2_destroy(callno);
1503 ast_mutex_lock(&iaxsl[callno]);
1506 static int update_packet(struct iax_frame *f)
1508 /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
1509 struct ast_iax2_full_hdr *fh = f->data;
1510 /* Mark this as a retransmission */
1511 fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
1513 f->iseqno = iaxs[f->callno]->iseqno;
1514 fh->iseqno = f->iseqno;
1518 static int attempt_transmit(void *data)
1520 /* Attempt to transmit the frame to the remote peer...
1521 Called without iaxsl held. */
1522 struct iax_frame *f = data;
1524 int callno = f->callno;
1525 char iabuf[INET_ADDRSTRLEN];
1526 /* Make sure this call is still active */
1528 ast_mutex_lock(&iaxsl[callno]);
1529 if ((f->callno) && iaxs[f->callno]) {
1530 if ((f->retries < 0) /* Already ACK'd */ ||
1531 (f->retries >= max_retries) /* Too many attempts */) {
1532 /* Record an error if we've transmitted too many times */
1533 if (f->retries >= max_retries) {
1535 /* Transfer timeout */
1536 send_command(iaxs[f->callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
1537 } else if (f->final) {
1539 iax2_destroy_nolock(f->callno);
1541 if (iaxs[f->callno]->owner)
1542 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);
1543 iaxs[f->callno]->error = ETIMEDOUT;
1544 if (iaxs[f->callno]->owner) {
1545 struct ast_frame fr = { 0, };
1547 fr.frametype = AST_FRAME_CONTROL;
1548 fr.subclass = AST_CONTROL_HANGUP;
1549 iax2_queue_frame(f->callno, &fr);
1550 /* Remember, owner could disappear */
1551 if (iaxs[f->callno]->owner)
1552 iaxs[f->callno]->owner->hangupcause = AST_CAUSE_DESTINATION_OUT_OF_ORDER;
1554 if (iaxs[f->callno]->reg) {
1555 memset(&iaxs[f->callno]->reg->us, 0, sizeof(iaxs[f->callno]->reg->us));
1556 iaxs[f->callno]->reg->regstate = REG_STATE_TIMEOUT;
1557 iaxs[f->callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
1559 iax2_destroy_nolock(f->callno);
1566 /* Update it if it needs it */
1568 /* Attempt transmission */
1571 /* Try again later after 10 times as long */
1573 if (f->retrytime > MAX_RETRY_TIME)
1574 f->retrytime = MAX_RETRY_TIME;
1575 /* Transfer messages max out at one second */
1576 if (f->transfer && (f->retrytime > 1000))
1577 f->retrytime = 1000;
1578 f->retrans = ast_sched_add(sched, f->retrytime, attempt_transmit, f);
1581 /* Make sure it gets freed */
1586 ast_mutex_unlock(&iaxsl[callno]);
1587 /* Do not try again */
1589 /* Don't attempt delivery, just remove it from the queue */
1590 ast_mutex_lock(&iaxq.lock);
1592 f->prev->next = f->next;
1594 iaxq.head = f->next;
1596 f->next->prev = f->prev;
1598 iaxq.tail = f->prev;
1600 ast_mutex_unlock(&iaxq.lock);
1602 /* Free the IAX frame */
1608 static int iax2_set_jitter(int fd, int argc, char *argv[])
1610 if ((argc != 4) && (argc != 5))
1611 return RESULT_SHOWUSAGE;
1613 max_jitter_buffer = atoi(argv[3]);
1614 if (max_jitter_buffer < 0)
1615 max_jitter_buffer = 0;
1618 if ((atoi(argv[3]) >= 0) && (atoi(argv[3]) < IAX_MAX_CALLS)) {
1619 if (iaxs[atoi(argv[3])]) {
1620 iaxs[atoi(argv[3])]->jitterbuffer = atoi(argv[4]);
1621 if (iaxs[atoi(argv[3])]->jitterbuffer < 0)
1622 iaxs[atoi(argv[3])]->jitterbuffer = 0;
1624 ast_cli(fd, "No such call '%d'\n", atoi(argv[3]));
1626 ast_cli(fd, "%d is not a valid call number\n", atoi(argv[3]));
1629 return RESULT_SUCCESS;
1632 static char jitter_usage[] =
1633 "Usage: iax set jitter [callid] <value>\n"
1634 " If used with a callid, it sets the jitter buffer to the given static\n"
1635 "value (until its next calculation). If used without a callid, the value is used\n"
1636 "to establish the maximum excess jitter buffer that is permitted before the jitter\n"
1637 "buffer size is reduced.";
1639 static int iax2_prune_realtime(int fd, int argc, char *argv[])
1641 struct iax2_peer *peer;
1644 return RESULT_SHOWUSAGE;
1645 if (!strcmp(argv[3],"all")) {
1647 ast_cli(fd, "OK cache is flushed.\n");
1648 } else if ((peer = find_peer(argv[3], 0))) {
1649 if(ast_test_flag(peer, IAX_RTCACHEFRIENDS)) {
1650 ast_set_flag(peer, IAX_RTAUTOCLEAR);
1651 expire_registry(peer);
1652 ast_cli(fd, "OK peer %s was removed from the cache.\n", argv[3]);
1654 ast_cli(fd, "SORRY peer %s is not eligible for this operation.\n", argv[3]);
1657 ast_cli(fd, "SORRY peer %s was not found in the cache.\n", argv[3]);
1660 return RESULT_SUCCESS;
1663 /*--- iax2_show_peer: Show one peer in detail ---*/
1664 static int iax2_show_peer(int fd, int argc, char *argv[])
1666 char status[30] = "";
1668 char iabuf[INET_ADDRSTRLEN];
1669 struct iax2_peer *peer;
1670 char codec_buf[512];
1671 int x = 0, codec = 0, load_realtime = 0;
1674 return RESULT_SHOWUSAGE;
1676 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? 1 : 0;
1678 peer = find_peer(argv[3], load_realtime);
1681 ast_cli(fd, " * Name : %s\n", peer->name);
1682 ast_cli(fd, " Secret : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
1683 ast_cli(fd, " Context : %s\n", peer->context);
1684 ast_cli(fd, " Mailbox : %s\n", peer->mailbox);
1685 ast_cli(fd, " Dynamic : %s\n", ast_test_flag(peer, IAX_DYNAMIC) ? "Yes":"No");
1686 ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
1687 ast_cli(fd, " Expire : %d\n", peer->expire);
1688 ast_cli(fd, " ACL : %s\n", (peer->ha?"Yes":"No"));
1689 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));
1690 ast_cli(fd, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
1691 ast_cli(fd, " Username : %s\n", peer->username);
1692 ast_cli(fd, " Codecs : ");
1693 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
1694 ast_cli(fd, "%s\n", codec_buf);
1696 ast_cli(fd, " Codec Order : (");
1697 for(x = 0; x < 32 ; x++) {
1698 codec = ast_codec_pref_index(&peer->prefs,x);
1701 ast_cli(fd, "%s", ast_getformatname(codec));
1702 if(x < 31 && ast_codec_pref_index(&peer->prefs,x+1))
1707 ast_cli(fd, "none");
1711 ast_cli(fd, " Status : ");
1712 if (peer->lastms < 0)
1713 strncpy(status, "UNREACHABLE", sizeof(status) - 1);
1714 else if (peer->lastms > peer->maxms)
1715 snprintf(status, sizeof(status), "LAGGED (%d ms)", peer->lastms);
1716 else if (peer->lastms)
1717 snprintf(status, sizeof(status), "OK (%d ms)", peer->lastms);
1719 strncpy(status, "UNKNOWN", sizeof(status) - 1);
1720 ast_cli(fd, "%s\n",status);
1722 if (ast_test_flag(peer, IAX_TEMPONLY))
1725 ast_cli(fd,"Peer %s not found.\n", argv[3]);
1729 return RESULT_SUCCESS;
1732 static char *complete_iax2_show_peer(char *line, char *word, int pos, int state)
1735 struct iax2_peer *p;
1737 /* 0 - iax2; 1 - show; 2 - peer; 3 - <peername> */
1739 ast_mutex_lock(&peerl.lock);
1740 for(p = peerl.peers ; p ; p = p->next) {
1741 if(!strncasecmp(p->name, word, strlen(word))) {
1742 if(++which > state) {
1743 return strdup(p->name);
1747 ast_mutex_unlock(&peerl.lock);
1753 static int iax2_show_stats(int fd, int argc, char *argv[])
1755 struct iax_frame *cur;
1756 int cnt = 0, dead=0, final=0;
1758 return RESULT_SHOWUSAGE;
1759 for (cur = iaxq.head; cur ; cur = cur->next) {
1760 if (cur->retries < 0)
1766 ast_cli(fd, " IAX Statistics\n");
1767 ast_cli(fd, "---------------------\n");
1768 ast_cli(fd, "Outstanding frames: %d (%d ingress, %d outgress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
1769 ast_cli(fd, "Packets in transmit queue: %d dead, %d final, %d total\n", dead, final, cnt);
1770 return RESULT_SUCCESS;
1773 static int iax2_show_cache(int fd, int argc, char *argv[])
1775 struct iax2_dpcache *dp;
1776 char tmp[1024] = "", *pc;
1780 gettimeofday(&tv, NULL);
1781 ast_mutex_lock(&dpcache_lock);
1783 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
1785 s = dp->expirey.tv_sec - tv.tv_sec;
1787 if (dp->flags & CACHE_FLAG_EXISTS)
1788 strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
1789 if (dp->flags & CACHE_FLAG_NONEXISTANT)
1790 strncat(tmp, "NONEXISTANT|", sizeof(tmp) - strlen(tmp) - 1);
1791 if (dp->flags & CACHE_FLAG_CANEXIST)
1792 strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
1793 if (dp->flags & CACHE_FLAG_PENDING)
1794 strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
1795 if (dp->flags & CACHE_FLAG_TIMEOUT)
1796 strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
1797 if (dp->flags & CACHE_FLAG_TRANSMITTED)
1798 strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
1799 if (dp->flags & CACHE_FLAG_MATCHMORE)
1800 strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
1801 if (dp->flags & CACHE_FLAG_UNKNOWN)
1802 strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
1803 /* Trim trailing pipe */
1804 if (!ast_strlen_zero(tmp))
1805 tmp[strlen(tmp) - 1] = '\0';
1807 strncpy(tmp, "(none)", sizeof(tmp) - 1);
1809 pc = strchr(dp->peercontext, '@');
1811 pc = dp->peercontext;
1814 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
1815 if (dp->waiters[x] > -1)
1818 ast_cli(fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
1820 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
1823 ast_mutex_unlock(&dpcache_lock);
1824 return RESULT_SUCCESS;
1827 static char show_stats_usage[] =
1828 "Usage: iax show stats\n"
1829 " Display statistics on IAX channel driver.\n";
1832 static char show_cache_usage[] =
1833 "Usage: iax show cache\n"
1834 " Display currently cached IAX Dialplan results.\n";
1836 static char show_peer_usage[] =
1837 "Usage: iax show peer <name>\n"
1838 " Display details on specific IAX peer\n";
1840 static char prune_realtime_usage[] =
1841 "Usage: iax2 prune realtime [<peername>|all]\n"
1842 " Prunes object(s) from the cache\n";
1844 static struct ast_cli_entry cli_set_jitter =
1845 { { "iax2", "set", "jitter", NULL }, iax2_set_jitter, "Sets IAX jitter buffer", jitter_usage };
1847 static struct ast_cli_entry cli_show_stats =
1848 { { "iax2", "show", "stats", NULL }, iax2_show_stats, "Display IAX statistics", show_stats_usage };
1850 static struct ast_cli_entry cli_show_cache =
1851 { { "iax2", "show", "cache", NULL }, iax2_show_cache, "Display IAX cached dialplan", show_cache_usage };
1853 static struct ast_cli_entry cli_show_peer =
1854 { { "iax2", "show", "peer", NULL }, iax2_show_peer, "Show details on specific IAX peer", show_peer_usage, complete_iax2_show_peer };
1856 static struct ast_cli_entry cli_prune_realtime =
1857 { { "iax2", "prune", "realtime", NULL }, iax2_prune_realtime, "Prune a cached realtime lookup", prune_realtime_usage, complete_iax2_show_peer };
1859 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
1861 #ifdef BRIDGE_OPTIMIZATION
1862 static unsigned int calc_fakestamp(struct chan_iax2_pvt *from, struct chan_iax2_pvt *to, unsigned int ts);
1864 static int forward_delivery(struct iax_frame *fr)
1866 struct chan_iax2_pvt *p1, *p2;
1867 char iabuf[INET_ADDRSTRLEN];
1870 p1 = iaxs[fr->callno];
1871 p2 = iaxs[p1->bridgecallno];
1878 ast_log(LOG_DEBUG, "forward_delivery: Forwarding ts=%d on %d/%d to %d/%d on %s:%d\n",
1880 p1->callno, p1->peercallno,
1881 p2->callno, p2->peercallno,
1882 ast_inet_ntoa(iabuf, sizeof(iabuf), p2->addr.sin_addr),
1883 ntohs(p2->addr.sin_port));
1885 /* Undo wraparound - which can happen when full VOICE frame wasn't sent by our peer.
1886 This is necessary for when our peer is chan_iax2.c v1.1nn or earlier which didn't
1887 send full frame on timestamp wrap when doing optimized bridging
1888 (actually current code STILL doesn't)
1890 if (fr->ts + 50000 <= p1->last) {
1891 fr->ts = ( (p1->last & 0xFFFF0000) + 0x10000) | (fr->ts & 0xFFFF);
1893 ast_log(LOG_DEBUG, "forward_delivery: pushed forward timestamp to %u\n", fr->ts);
1896 /* Send with timestamp adjusted to the origin of the outbound leg */
1897 /* But don't destroy inbound timestamp still needed later to set "last" */
1899 fr->ts = calc_fakestamp(p1, p2, fr->ts);
1900 res = iax2_send(p2, &fr->af, fr->ts, -1, 0, 0, 0);
1906 static void unwrap_timestamp(struct iax_frame *fr)
1910 if ( (fr->ts & 0xFFFF0000) == (iaxs[fr->callno]->last & 0xFFFF0000) ) {
1911 x = fr->ts - iaxs[fr->callno]->last;
1913 /* Sudden big jump backwards in timestamp:
1914 What likely happened here is that miniframe timestamp has circled but we haven't
1915 gotten the update from the main packet. We'll just pretend that we did, and
1916 update the timestamp appropriately. */
1917 fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) + 0x10000) | (fr->ts & 0xFFFF);
1919 ast_log(LOG_DEBUG, "schedule_delivery: pushed forward timestamp\n");
1922 /* Sudden apparent big jump forwards in timestamp:
1923 What's likely happened is this is an old miniframe belonging to the previous
1924 top-16-bit timestamp that has turned up out of order.
1925 Adjust the timestamp appropriately. */
1926 fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) - 0x10000) | (fr->ts & 0xFFFF);
1928 ast_log(LOG_DEBUG, "schedule_delivery: pushed back timestamp\n");
1933 static int schedule_delivery(struct iax_frame *fr, int reallydeliver, int updatehistory, int fromtrunk)
1937 unsigned int orig_ts;
1938 int drops[MEMORY_SIZE];
1939 int min, max=0, prevjitterbuffer, maxone=0,y,z, match;
1941 /* Remember current jitterbuffer so we can log any change */
1942 prevjitterbuffer = iaxs[fr->callno]->jitterbuffer;
1943 /* Similarly for the frame timestamp */
1948 ast_log(LOG_DEBUG, "schedule_delivery: ts=%d, last=%d, really=%d, update=%d\n",
1949 fr->ts, iaxs[fr->callno]->last, reallydeliver, updatehistory);
1952 /* Attempt to recover wrapped timestamps */
1953 unwrap_timestamp(fr);
1955 if (updatehistory) {
1957 /* Attempt to spot a change of timebase on timestamps coming from the other side
1958 We detect by noticing a jump in consecutive timestamps that can't reasonably be explained
1959 by network jitter or reordering. Sometimes, also, the peer stops sending us frames
1960 for a while - in this case this code might also resync us. But that's not a bad thing.
1961 Be careful of non-voice frames which are timestamped differently (especially ACKS!)
1962 [that's why we only do this when updatehistory is true]
1964 x = fr->ts - iaxs[fr->callno]->last;
1965 if (x > TS_GAP_FOR_JB_RESYNC || x < -TS_GAP_FOR_JB_RESYNC) {
1967 ast_log(LOG_DEBUG, "schedule_delivery: call=%d: TS jumped. resyncing rxcore (ts=%d, last=%d)\n",
1968 fr->callno, fr->ts, iaxs[fr->callno]->last);
1969 /* zap rxcore - calc_rxstamp will make a new one based on this frame */
1970 iaxs[fr->callno]->rxcore.tv_sec = 0;
1971 iaxs[fr->callno]->rxcore.tv_usec = 0;
1972 /* wipe "last" if stamps have jumped backwards */
1974 iaxs[fr->callno]->last = 0;
1975 /* should we also empty history? */
1978 /* ms is a measure of the "lateness" of the frame relative to the "reference"
1979 frame we received. (initially the very first, but also see code just above here).
1980 Understand that "ms" can easily be -ve if lag improves since the reference frame.
1981 Called by IAX thread, with iaxsl lock held. */
1982 ms = calc_rxstamp(iaxs[fr->callno], fr->ts) - fr->ts;
1984 /* Rotate our history queue of "lateness". Don't worry about those initial
1985 zeros because the first entry will always be zero */
1986 for (x=0;x<MEMORY_SIZE - 1;x++)
1987 iaxs[fr->callno]->history[x] = iaxs[fr->callno]->history[x+1];
1988 /* Add a history entry for this one */
1989 iaxs[fr->callno]->history[x] = ms;
1995 /* delivery time is sender's sent timestamp converted back into absolute time according to our clock */
1996 if ( (!fromtrunk) && (iaxs[fr->callno]->rxcore.tv_sec || iaxs[fr->callno]->rxcore.tv_usec) ) {
1997 fr->af.delivery.tv_sec = iaxs[fr->callno]->rxcore.tv_sec;
1998 fr->af.delivery.tv_usec = iaxs[fr->callno]->rxcore.tv_usec;
1999 fr->af.delivery.tv_sec += fr->ts / 1000;
2000 fr->af.delivery.tv_usec += (fr->ts % 1000) * 1000;
2001 if (fr->af.delivery.tv_usec >= 1000000) {
2002 fr->af.delivery.tv_usec -= 1000000;
2003 fr->af.delivery.tv_sec += 1;
2009 ast_log(LOG_DEBUG, "schedule_delivery: set delivery to 0 as we don't have an rxcore yet, or frame is from trunk.\n");
2011 fr->af.delivery.tv_sec = 0;
2012 fr->af.delivery.tv_usec = 0;
2015 /* Initialize the minimum to reasonable values. It's too much
2016 work to do the same for the maximum, repeatedly */
2017 min=iaxs[fr->callno]->history[0];
2018 for (z=0;z < iax2_dropcount + 1;z++) {
2019 /* Start very optimistic ;-) */
2021 for (x=0;x<MEMORY_SIZE;x++) {
2022 if (max < iaxs[fr->callno]->history[x]) {
2023 /* We have a candidate new maximum value. Make
2024 sure it's not in our drop list */
2026 for (y=0;!match && (y<z);y++)
2027 match |= (drops[y] == x);
2029 /* It's not in our list, use it as the new maximum */
2030 max = iaxs[fr->callno]->history[x];
2036 /* On our first pass, find the minimum too */
2037 if (min > iaxs[fr->callno]->history[x])
2038 min = iaxs[fr->callno]->history[x];
2045 /* Just for reference, keep the "jitter" value, the difference between the
2046 earliest and the latest. */
2048 iaxs[fr->callno]->jitter = max - min;
2050 /* IIR filter for keeping track of historic jitter, but always increase
2051 historic jitter immediately for increase */
2053 if (iaxs[fr->callno]->jitter > iaxs[fr->callno]->historicjitter )
2054 iaxs[fr->callno]->historicjitter = iaxs[fr->callno]->jitter;
2056 iaxs[fr->callno]->historicjitter = GAMMA * (double)iaxs[fr->callno]->jitter + (1-GAMMA) *
2057 iaxs[fr->callno]->historicjitter;
2059 /* If our jitter buffer is too big (by a significant margin), then we slowly
2060 shrink it to avoid letting the change be perceived */
2061 if (max < iaxs[fr->callno]->jitterbuffer - max_jitter_buffer)
2062 iaxs[fr->callno]->jitterbuffer -= jittershrinkrate;
2064 /* If our jitter buffer headroom is too small (by a significant margin), then we slowly enlarge it */
2065 /* min_jitter_buffer should be SMALLER than max_jitter_buffer - leaving a "no mans land"
2066 in between - otherwise the jitterbuffer size will hunt up and down causing unnecessary
2067 disruption. Set maxexcessbuffer to say 150msec, minexcessbuffer to say 50 */
2068 if (max > iaxs[fr->callno]->jitterbuffer - min_jitter_buffer)
2069 iaxs[fr->callno]->jitterbuffer += jittershrinkrate;
2071 /* If our jitter buffer is smaller than our maximum delay, grow the jitter
2072 buffer immediately to accomodate it (and a little more). */
2073 if (max > iaxs[fr->callno]->jitterbuffer)
2074 iaxs[fr->callno]->jitterbuffer = max
2075 /* + ((float)iaxs[fr->callno]->jitter) * 0.1 */;
2077 /* If the caller just wanted us to update, return now */
2081 /* Subtract the lateness from our jitter buffer to know how long to wait
2082 before sending our packet. */
2083 delay = iaxs[fr->callno]->jitterbuffer - ms;
2085 /* Whatever happens, no frame waits longer than maxjitterbuffer */
2086 if (delay > maxjitterbuffer)
2087 delay = maxjitterbuffer;
2089 /* If jitter buffer is disabled then just pretend the frame is "right on time" */
2090 /* If frame came from trunk, also don't do any delay */
2091 if ( (!ast_test_flag(iaxs[fr->callno], IAX_USEJITTERBUF)) || fromtrunk )
2095 /* Log jitter stats for possible offline analysis */
2096 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",
2097 fr->callno, fr->ts, orig_ts, iaxs[fr->callno]->last,
2098 (fr->af.frametype == AST_FRAME_VOICE) ? "VOICE" : "CONTROL",
2099 min, max, iaxs[fr->callno]->jitterbuffer,
2100 iaxs[fr->callno]->jitterbuffer - prevjitterbuffer,
2102 iaxs[fr->callno]->jitter, iaxs[fr->callno]->historicjitter);
2106 /* Don't deliver it more than 4 ms late */
2107 if ((delay > -4) || (fr->af.frametype != AST_FRAME_VOICE)) {
2109 ast_log(LOG_DEBUG, "schedule_delivery: Delivering immediately (Calculated delay is %d)\n", delay);
2113 ast_log(LOG_DEBUG, "schedule_delivery: Dropping voice packet since %dms delay is too old\n", delay);
2114 /* Free our iax frame */
2115 iax2_frame_free(fr);
2119 ast_log(LOG_DEBUG, "schedule_delivery: Scheduling delivery in %d ms\n", delay);
2120 fr->retrans = ast_sched_add(sched, delay, do_deliver, fr);
2125 static int iax2_transmit(struct iax_frame *fr)
2127 /* Lock the queue and place this packet at the end */
2130 /* By setting this to 0, the network thread will send it for us, and
2131 queue retransmission if necessary */
2133 ast_mutex_lock(&iaxq.lock);
2140 iaxq.tail->next = fr;
2141 fr->prev = iaxq.tail;
2145 ast_mutex_unlock(&iaxq.lock);
2146 /* Wake up the network thread */
2147 pthread_kill(netthreadid, SIGURG);
2153 static int iax2_digit(struct ast_channel *c, char digit)
2155 return send_command_locked(PTR_TO_CALLNO(c->pvt->pvt), AST_FRAME_DTMF, digit, 0, NULL, 0, -1);
2158 static int iax2_sendtext(struct ast_channel *c, char *text)
2161 return send_command_locked(PTR_TO_CALLNO(c->pvt->pvt), AST_FRAME_TEXT,
2162 0, 0, text, strlen(text) + 1, -1);
2165 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
2167 return send_command_locked(PTR_TO_CALLNO(c->pvt->pvt), AST_FRAME_IMAGE, img->subclass, 0, img->data, img->datalen, -1);
2170 static int iax2_sendhtml(struct ast_channel *c, int subclass, char *data, int datalen)
2172 return send_command_locked(PTR_TO_CALLNO(c->pvt->pvt), AST_FRAME_HTML, subclass, 0, data, datalen, -1);
2175 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
2177 unsigned short callno = PTR_TO_CALLNO(newchan->pvt->pvt);
2178 ast_mutex_lock(&iaxsl[callno]);
2180 iaxs[callno]->owner = newchan;
2182 ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n");
2183 ast_mutex_unlock(&iaxsl[callno]);
2187 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, int temponly);
2188 static struct iax2_user *build_user(const char *name, struct ast_variable *v, int temponly);
2190 static void destroy_user(struct iax2_user *user);
2191 static int expire_registry(void *data);
2193 static struct iax2_peer *realtime_peer(const char *peername)
2195 struct ast_variable *var;
2196 struct ast_variable *tmp;
2197 struct iax2_peer *peer=NULL;
2198 time_t regseconds, nowtime;
2200 var = ast_load_realtime("iaxpeers", "name", peername, NULL);
2202 /* Make sure it's not a user only... */
2203 peer = build_peer(peername, var, ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS) ? 0 : 1);
2208 if (!strcasecmp(tmp->name, "type")) {
2209 if (strcasecmp(tmp->value, "friend") &&
2210 strcasecmp(tmp->value, "peer")) {
2211 /* Whoops, we weren't supposed to exist! */
2216 } else if (!strcasecmp(tmp->name, "regseconds")) {
2217 if (sscanf(tmp->value, "%li", ®seconds) != 1)
2219 } else if (!strcasecmp(tmp->name, "ipaddr")) {
2220 inet_aton(tmp->value, &(peer->addr.sin_addr));
2221 } else if (!strcasecmp(tmp->name, "port")) {
2222 peer->addr.sin_port = htons(atoi(tmp->value));
2223 } else if (!strcasecmp(tmp->name, "host")) {
2224 if (!strcasecmp(tmp->value, "dynamic"))
2230 /* Add some finishing touches, addresses, etc */
2231 if(ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
2232 ast_mutex_lock(&peerl.lock);
2233 peer->next = peerl.peers;
2235 ast_mutex_unlock(&peerl.lock);
2236 ast_copy_flags(peer, &globalflags, IAX_RTAUTOCLEAR|IAX_RTCACHEFRIENDS);
2237 if (ast_test_flag(peer, IAX_RTAUTOCLEAR))
2238 peer->expire = ast_sched_add(sched, (global_rtautoclear) * 1000, expire_registry, (void *)peer);
2240 ast_set_flag(peer, IAX_TEMPONLY);
2243 if (peer && dynamic) {
2245 if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE) {
2246 memset(&peer->addr, 0, sizeof(peer->addr));
2248 ast_log(LOG_DEBUG, "Bah, we're expired (%ld/%ld/%ld)!\n", nowtime - regseconds, regseconds, nowtime);
2252 ast_variables_destroy(var);
2257 static struct iax2_user *realtime_user(const char *username)
2259 struct ast_variable *var;
2260 struct ast_variable *tmp;
2261 struct iax2_user *user=NULL;
2262 var = ast_load_realtime("iaxusers", "name", username, NULL);
2264 /* Make sure it's not a user only... */
2265 user = build_user(username, var, !ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS));
2267 /* Add some finishing touches, addresses, etc */
2268 if(ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
2269 ast_mutex_lock(&userl.lock);
2270 user->next = userl.users;
2272 ast_mutex_unlock(&userl.lock);
2273 ast_set_flag(user, IAX_RTCACHEFRIENDS);
2275 ast_set_flag(user, IAX_TEMPONLY);
2279 if (!strcasecmp(tmp->name, "type")) {
2280 if (strcasecmp(tmp->value, "friend") &&
2281 strcasecmp(tmp->value, "user")) {
2282 /* Whoops, we weren't supposed to exist! */
2291 ast_variables_destroy(var);
2296 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin)
2300 char regseconds[20];
2304 snprintf(regseconds, sizeof(regseconds), "%ld", nowtime);
2305 ast_inet_ntoa(ipaddr, sizeof(ipaddr), sin->sin_addr);
2306 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
2307 ast_update_realtime("iaxpeers", "name", peername, "ipaddr", ipaddr, "port", port, "regseconds", regseconds, NULL);
2311 static int create_addr(struct sockaddr_in *sin, int *capability, int *sendani,
2312 int *maxtime, char *peer, char *context, int *trunk,
2313 int *notransfer, int *usejitterbuf, int *encmethods,
2314 char *username, int usernlen, char *secret, int seclen,
2315 int *ofound, char *peercontext, char *timezone, int tzlen, char *pref_str, size_t pref_size,
2318 struct ast_hostent ahp; struct hostent *hp;
2319 struct iax2_peer *p;
2328 *sockfd = defaultsockfd;
2329 sin->sin_family = AF_INET;
2330 p = find_peer(peer, 1);
2333 if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
2334 (!p->maxms || ((p->lastms > 0) && (p->lastms <= p->maxms)))) {
2337 ast_codec_pref_convert(&p->prefs, pref_str, pref_size, 1);
2340 *sendani = ast_test_flag(p, IAX_SENDANI); /* Whether we transmit ANI */
2342 *maxtime = p->maxms; /* Max time they should take */
2344 strncpy(context, p->context, AST_MAX_EXTENSION - 1);
2346 strncpy(peercontext, p->peercontext, AST_MAX_EXTENSION - 1);
2348 *trunk = ast_test_flag(p, IAX_TRUNK);
2350 *capability = p->capability;
2352 *encmethods = p->encmethods;
2354 strncpy(username, p->username, usernlen);
2355 if (p->addr.sin_addr.s_addr) {
2356 sin->sin_addr = p->addr.sin_addr;
2357 sin->sin_port = p->addr.sin_port;
2359 sin->sin_addr = p->defaddr.sin_addr;
2360 sin->sin_port = p->defaddr.sin_port;
2363 *sockfd = p->sockfd;
2365 *notransfer = ast_test_flag(p, IAX_NOTRANSFER);
2367 *usejitterbuf = ast_test_flag(p, IAX_USEJITTERBUF);
2369 if (!ast_strlen_zero(p->dbsecret)) {
2370 char *family, *key=NULL;
2371 family = ast_strdupa(p->dbsecret);
2373 key = strchr(family, '/');
2379 if (!family || !key || ast_db_get(family, key, secret, seclen)) {
2380 ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", p->dbsecret);
2381 if (ast_test_flag(p, IAX_TEMPONLY))
2386 strncpy(secret, p->secret, seclen); /* safe */
2389 snprintf(timezone, tzlen-1, "%s", p->zonetag);
2391 if (ast_test_flag(p, IAX_TEMPONLY))
2399 if(pref_str) { /* use global iax prefs for unknown peer/user */
2400 ast_codec_pref_convert(&prefs, pref_str, pref_size, 1);
2403 hp = ast_gethostbyname(peer, &ahp);
2405 memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
2406 sin->sin_port = htons(IAX_DEFAULT_PORTNO);
2409 ast_log(LOG_WARNING, "No such host: %s\n", peer);
2414 if (ast_test_flag(p, IAX_TEMPONLY))
2419 static int auto_congest(void *nothing)
2421 int callno = PTR_TO_CALLNO(nothing);
2422 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_CONGESTION };
2423 ast_mutex_lock(&iaxsl[callno]);
2425 iaxs[callno]->initid = -1;
2426 iax2_queue_frame(callno, &f);
2427 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
2429 ast_mutex_unlock(&iaxsl[callno]);
2433 static unsigned int iax2_datetime(char *tz)
2439 localtime_r(&t, &tm);
2440 if (!ast_strlen_zero(tz))
2441 ast_localtime(&t, &tm, tz);
2442 tmp = (tm.tm_sec >> 1) & 0x1f; /* 5 bits of seconds */
2443 tmp |= (tm.tm_min & 0x3f) << 5; /* 6 bits of minutes */
2444 tmp |= (tm.tm_hour & 0x1f) << 11; /* 5 bits of hours */
2445 tmp |= (tm.tm_mday & 0x1f) << 16; /* 5 bits of day of month */
2446 tmp |= ((tm.tm_mon + 1) & 0xf) << 21; /* 4 bits of month */
2447 tmp |= ((tm.tm_year - 100) & 0x7f) << 25; /* 7 bits of year */
2451 static int iax2_call(struct ast_channel *c, char *dest, int timeout)
2453 struct sockaddr_in sin;
2458 char *secret = NULL;
2460 char *l=NULL, *n=NULL;
2461 struct iax_ie_data ied;
2462 char myrdest [5] = "s";
2463 char context[AST_MAX_EXTENSION] ="";
2464 char peercontext[AST_MAX_EXTENSION] ="";
2465 char *portno = NULL;
2467 int encmethods=iax2_encryption;
2468 unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
2470 char storedusern[80], storedsecret[80];
2474 memset(out_prefs,0,32);
2476 if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
2477 ast_log(LOG_WARNING, "Line is already in use (%s)?\n", c->name);
2480 strncpy(host, dest, sizeof(host)-1);
2482 strsep(&stringp, "/");
2483 /* If no destination extension specified, use 's' */
2484 rdest = strsep(&stringp, "/");
2488 /* Check for trailing options */
2489 opts = strsep(&stringp, "/");
2494 strsep(&stringp, "@");
2495 rcontext = strsep(&stringp, "@");
2497 strsep(&stringp, "@");
2498 username = strsep(&stringp, "@");
2500 /* Really the second argument is the host, not the username */
2508 username = strsep(&stringp, ":");
2509 secret = strsep(&stringp, ":");
2512 if (strsep(&stringp, ":")) {
2514 strsep(&stringp, ":");
2515 portno = strsep(&stringp, ":");
2517 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)) {
2518 ast_log(LOG_WARNING, "No address associated with '%s'\n", hname);
2521 /* Keep track of the context for outgoing calls too */
2522 strncpy(c->context, context, sizeof(c->context) - 1);
2524 sin.sin_port = htons(atoi(portno));
2527 n = c->cid.cid_name;
2528 /* Now build request */
2529 memset(&ied, 0, sizeof(ied));
2530 /* On new call, first IE MUST be IAX version of caller */
2531 iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
2532 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, rdest);
2533 if (strchr(opts, 'a')) {
2534 /* Request auto answer */
2535 iax_ie_append(&ied, IAX_IE_AUTOANSWER);
2537 iax_ie_append_str(&ied, IAX_IE_CODEC_PREFS, out_prefs);
2540 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
2541 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
2543 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, AST_PRES_NUMBER_NOT_AVAILABLE);
2544 iax_ie_append_byte(&ied, IAX_IE_CALLINGTON, c->cid.cid_ton);
2545 iax_ie_append_short(&ied, IAX_IE_CALLINGTNS, c->cid.cid_tns);
2547 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n);
2548 if (ast_test_flag(iaxs[callno], IAX_SENDANI) && c->cid.cid_ani) {
2549 iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, c->cid.cid_ani);
2551 if (c->language && !ast_strlen_zero(c->language))
2552 iax_ie_append_str(&ied, IAX_IE_LANGUAGE, c->language);
2553 if (c->cid.cid_dnid && !ast_strlen_zero(c->cid.cid_dnid))
2554 iax_ie_append_str(&ied, IAX_IE_DNID, c->cid.cid_dnid);
2556 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, rcontext);
2557 else if (strlen(peercontext))
2558 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, peercontext);
2559 if (!username && !ast_strlen_zero(storedusern))
2560 username = storedusern;
2562 iax_ie_append_str(&ied, IAX_IE_USERNAME, username);
2564 iax_ie_append_short(&ied, IAX_IE_ENCRYPTION, encmethods);
2565 if (!secret && !ast_strlen_zero(storedsecret))
2566 secret = storedsecret;
2567 ast_mutex_lock(&iaxsl[callno]);
2568 if (!ast_strlen_zero(c->context))
2569 strncpy(iaxs[callno]->context, c->context, sizeof(iaxs[callno]->context) - 1);
2571 strncpy(iaxs[callno]->username, username, sizeof(iaxs[callno]->username)-1);
2572 iaxs[callno]->encmethods = encmethods;
2574 if (secret[0] == '[') {
2575 /* This is an RSA key, not a normal secret */
2576 strncpy(iaxs[callno]->outkey, secret + 1, sizeof(iaxs[callno]->secret)-1);
2577 if (!ast_strlen_zero(iaxs[callno]->outkey)) {
2578 iaxs[callno]->outkey[strlen(iaxs[callno]->outkey) - 1] = '\0';
2581 strncpy(iaxs[callno]->secret, secret, sizeof(iaxs[callno]->secret)-1);
2583 iax_ie_append_int(&ied, IAX_IE_FORMAT, c->nativeformats);
2584 iax_ie_append_int(&ied, IAX_IE_CAPABILITY, iaxs[callno]->capability);
2585 iax_ie_append_short(&ied, IAX_IE_ADSICPE, c->adsicpe);
2586 iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime(tz));
2587 /* Transmit the string in a "NEW" request */
2589 /* XXX We have no equivalent XXX */
2590 if (option_verbose > 2)
2591 ast_verbose(VERBOSE_PREFIX_3 "Calling using options '%s'\n", requeststr);
2593 if (iaxs[callno]->maxtime) {
2594 /* Initialize pingtime and auto-congest time */
2595 iaxs[callno]->pingtime = iaxs[callno]->maxtime / 2;
2596 iaxs[callno]->initid = ast_sched_add(sched, iaxs[callno]->maxtime * 2, auto_congest, CALLNO_TO_PTR(callno));
2597 } else if (autokill) {
2598 iaxs[callno]->pingtime = autokill / 2;
2599 iaxs[callno]->initid = ast_sched_add(sched, autokill * 2, auto_congest, CALLNO_TO_PTR(callno));
2601 send_command(iaxs[callno], AST_FRAME_IAX,
2602 IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
2603 ast_mutex_unlock(&iaxsl[callno]);
2604 ast_setstate(c, AST_STATE_RINGING);
2608 static int iax2_hangup(struct ast_channel *c)
2610 unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
2612 struct iax_ie_data ied;
2613 memset(&ied, 0, sizeof(ied));
2614 ast_mutex_lock(&iaxsl[callno]);
2615 if (callno && iaxs[callno]) {
2616 ast_log(LOG_DEBUG, "We're hanging up %s now...\n", c->name);
2617 alreadygone = ast_test_flag(iaxs[callno], IAX_ALREADYGONE);
2618 /* Send the hangup unless we have had a transmission error or are already gone */
2619 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, (unsigned char)c->hangupcause);
2620 if (!iaxs[callno]->error && !alreadygone)
2621 send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1);
2622 /* Explicitly predestroy it */
2623 iax2_predestroy_nolock(callno);
2624 /* If we were already gone to begin with, destroy us now */
2626 ast_log(LOG_DEBUG, "Really destroying %s now...\n", c->name);
2627 iax2_destroy_nolock(callno);
2630 ast_mutex_unlock(&iaxsl[callno]);
2631 if (option_verbose > 2)
2632 ast_verbose(VERBOSE_PREFIX_3 "Hungup '%s'\n", c->name);
2636 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
2638 struct ast_option_header *h;
2640 h = malloc(datalen + sizeof(struct ast_option_header));
2642 h->flag = AST_OPTION_FLAG_REQUEST;
2643 h->option = htons(option);
2644 memcpy(h->data, data, datalen);
2645 res = send_command_locked(PTR_TO_CALLNO(c->pvt->pvt), AST_FRAME_CONTROL,
2646 AST_CONTROL_OPTION, 0, (char *)h, datalen + sizeof(struct ast_option_header), -1);
2650 ast_log(LOG_WARNING, "Out of memory\n");
2654 static struct ast_frame *iax2_read(struct ast_channel *c)
2656 static struct ast_frame f = { AST_FRAME_NULL, };
2657 ast_log(LOG_NOTICE, "I should never be called!\n");
2661 static int iax2_start_transfer(unsigned short callno0, unsigned short callno1)
2664 struct iax_ie_data ied0;
2665 struct iax_ie_data ied1;
2666 unsigned int transferid = rand();
2667 memset(&ied0, 0, sizeof(ied0));
2668 iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &iaxs[callno1]->addr);
2669 iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[callno1]->peercallno);
2670 iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, transferid);
2672 memset(&ied1, 0, sizeof(ied1));
2673 iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &iaxs[callno0]->addr);
2674 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[callno0]->peercallno);
2675 iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, transferid);
2677 res = send_command(iaxs[callno0], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
2680 res = send_command(iaxs[callno1], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
2683 iaxs[callno0]->transferring = TRANSFER_BEGIN;
2684 iaxs[callno1]->transferring = TRANSFER_BEGIN;
2688 static void lock_both(unsigned short callno0, unsigned short callno1)
2690 ast_mutex_lock(&iaxsl[callno0]);
2691 while (ast_mutex_trylock(&iaxsl[callno1])) {
2692 ast_mutex_unlock(&iaxsl[callno0]);
2694 ast_mutex_lock(&iaxsl[callno0]);
2698 static void unlock_both(unsigned short callno0, unsigned short callno1)
2700 ast_mutex_unlock(&iaxsl[callno1]);
2701 ast_mutex_unlock(&iaxsl[callno0]);
2704 static int iax2_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
2706 struct ast_channel *cs[3];
2707 struct ast_channel *who;
2710 int transferstarted=0;
2711 struct ast_frame *f;
2712 unsigned short callno0 = PTR_TO_CALLNO(c0->pvt->pvt);
2713 unsigned short callno1 = PTR_TO_CALLNO(c1->pvt->pvt);
2714 struct timeval waittimer = {0, 0}, tv;
2716 lock_both(callno0, callno1);
2717 /* Put them in native bridge mode */
2718 iaxs[callno0]->bridgecallno = callno1;
2719 iaxs[callno1]->bridgecallno = callno0;
2720 unlock_both(callno0, callno1);
2722 /* If not, try to bridge until we can execute a transfer, if we can */
2725 for (/* ever */;;) {
2726 /* Check in case we got masqueraded into */
2727 if ((c0->type != channeltype) || (c1->type != channeltype)) {
2728 if (option_verbose > 2)
2729 ast_verbose(VERBOSE_PREFIX_3 "Can't masquerade, we're different...\n");
2730 /* Remove from native mode */
2731 if (c0->type == channeltype) {
2732 ast_mutex_lock(&iaxsl[callno0]);
2733 iaxs[callno0]->bridgecallno = 0;
2734 ast_mutex_unlock(&iaxsl[callno0]);
2736 if (c1->type == channeltype) {
2737 ast_mutex_lock(&iaxsl[callno1]);
2738 iaxs[callno1]->bridgecallno = 0;
2739 ast_mutex_unlock(&iaxsl[callno1]);
2743 if (c0->nativeformats != c1->nativeformats) {
2744 if (option_verbose > 2)
2745 ast_verbose(VERBOSE_PREFIX_3 "Operating with different codecs, can't native bridge...\n");
2746 /* Remove from native mode */
2747 lock_both(callno0, callno1);
2748 iaxs[callno0]->bridgecallno = 0;
2749 iaxs[callno1]->bridgecallno = 0;
2750 unlock_both(callno0, callno1);
2753 /* check if transfered and if we really want native bridging */
2754 if (!transferstarted && !ast_test_flag(iaxs[callno0], IAX_NOTRANSFER) && !ast_test_flag(iaxs[callno1], IAX_NOTRANSFER) &&
2755 !(flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
2756 /* Try the transfer */
2757 if (iax2_start_transfer(callno0, callno1))
2758 ast_log(LOG_WARNING, "Unable to start the transfer\n");
2759 transferstarted = 1;
2761 if ((iaxs[callno0]->transferring == TRANSFER_RELEASED) && (iaxs[callno1]->transferring == TRANSFER_RELEASED)) {
2762 /* Call has been transferred. We're no longer involved */
2763 gettimeofday(&tv, NULL);
2764 if (!waittimer.tv_sec && !waittimer.tv_usec) {
2765 waittimer.tv_sec = tv.tv_sec;
2766 waittimer.tv_usec = tv.tv_usec;
2767 } else if (tv.tv_sec - waittimer.tv_sec > IAX_LINGER_TIMEOUT) {
2768 c0->_softhangup |= AST_SOFTHANGUP_DEV;
2769 c1->_softhangup |= AST_SOFTHANGUP_DEV;
2777 who = ast_waitfor_n(cs, 2, &to);
2779 if (ast_check_hangup(c0) || ast_check_hangup(c1)) {
2792 if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
2798 if ((f->frametype == AST_FRAME_VOICE) ||
2799 (f->frametype == AST_FRAME_TEXT) ||
2800 (f->frametype == AST_FRAME_VIDEO) ||
2801 (f->frametype == AST_FRAME_IMAGE) ||
2802 (f->frametype == AST_FRAME_DTMF)) {
2803 if ((f->frametype == AST_FRAME_DTMF) &&
2804 (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
2806 if ((flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
2809 /* Take out of conference mode */
2811 /* Remove from native mode */
2817 if (flags & AST_BRIDGE_DTMF_CHANNEL_1) {
2821 /* Remove from native mode */
2828 ast_log(LOG_DEBUG, "Read from %s\n", who->name);
2830 ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
2842 /* Swap who gets priority */
2847 lock_both(callno0, callno1);
2849 iaxs[callno0]->bridgecallno = 0;
2851 iaxs[callno1]->bridgecallno = 0;
2852 unlock_both(callno0, callno1);
2856 static int iax2_answer(struct ast_channel *c)
2858 unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
2860 ast_log(LOG_DEBUG, "Answering\n");
2861 return send_command_locked(callno, AST_FRAME_CONTROL, AST_CONTROL_ANSWER, 0, NULL, 0, -1);
2864 static int iax2_indicate(struct ast_channel *c, int condition)
2866 unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
2868 ast_log(LOG_DEBUG, "Indicating condition %d\n", condition);
2869 return send_command_locked(callno, AST_FRAME_CONTROL, condition, 0, NULL, 0, -1);
2872 static int iax2_transfer(struct ast_channel *c, char *dest)
2874 unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
2875 struct iax_ie_data ied;
2876 char tmp[256] = "", *context;
2877 strncpy(tmp, dest, sizeof(tmp) - 1);
2878 context = strchr(tmp, '@');
2883 memset(&ied, 0, sizeof(ied));
2884 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, tmp);
2886 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, context);
2888 ast_log(LOG_DEBUG, "Transferring '%s' to '%s'\n", c->name, dest);
2889 return send_command_locked(callno, AST_FRAME_IAX, IAX_COMMAND_TRANSFER, 0, ied.buf, ied.pos, -1);
2893 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
2895 static int iax2_getpeertrunk(struct sockaddr_in sin)
2897 struct iax2_peer *peer;
2899 ast_mutex_lock(&peerl.lock);
2902 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
2903 (peer->addr.sin_port == sin.sin_port)) {
2904 res = ast_test_flag(peer, IAX_TRUNK);
2909 ast_mutex_unlock(&peerl.lock);
2913 static struct ast_channel *ast_iax2_new(int callno, int state, int capability)
2915 struct ast_channel *tmp;
2916 struct chan_iax2_pvt *i;
2917 struct ast_variable *v = NULL;
2919 /* Don't hold call lock */
2920 ast_mutex_unlock(&iaxsl[callno]);
2921 tmp = ast_channel_alloc(1);
2922 ast_mutex_lock(&iaxsl[callno]);
2925 if (!ast_strlen_zero(i->username))
2926 snprintf(tmp->name, sizeof(tmp->name), "IAX2/%s@%s/%d", i->username, i->host, i->callno);
2928 snprintf(tmp->name, sizeof(tmp->name), "IAX2/%s/%d", i->host, i->callno);
2929 tmp->type = channeltype;
2930 /* We can support any format by default, until we get restricted */
2931 tmp->nativeformats = capability;
2932 tmp->readformat = ast_best_codec(capability);
2933 tmp->writeformat = ast_best_codec(capability);
2934 tmp->pvt->pvt = CALLNO_TO_PTR(i->callno);
2935 tmp->pvt->send_digit = iax2_digit;
2936 tmp->pvt->send_text = iax2_sendtext;
2937 tmp->pvt->send_image = iax2_sendimage;
2938 tmp->pvt->send_html = iax2_sendhtml;
2939 tmp->pvt->call = iax2_call;
2940 tmp->pvt->hangup = iax2_hangup;
2941 tmp->pvt->answer = iax2_answer;
2942 tmp->pvt->read = iax2_read;
2943 tmp->pvt->write = iax2_write;
2944 tmp->pvt->write_video = iax2_write;
2945 tmp->pvt->indicate = iax2_indicate;
2946 tmp->pvt->setoption = iax2_setoption;
2947 tmp->pvt->bridge = iax2_bridge;
2948 tmp->pvt->transfer = iax2_transfer;
2949 if (!ast_strlen_zero(i->cid_num))
2950 tmp->cid.cid_num = strdup(i->cid_num);
2951 if (!ast_strlen_zero(i->cid_name))
2952 tmp->cid.cid_name = strdup(i->cid_name);
2953 if (!ast_strlen_zero(i->ani))
2954 tmp->cid.cid_ani = strdup(i->ani);
2955 if (!ast_strlen_zero(i->language))
2956 strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
2957 if (!ast_strlen_zero(i->dnid))
2958 tmp->cid.cid_dnid = strdup(i->dnid);
2959 tmp->cid.cid_pres = i->calling_pres;
2960 tmp->cid.cid_ton = i->calling_ton;
2961 tmp->cid.cid_tns = i->calling_tns;
2962 if (!ast_strlen_zero(i->accountcode))
2963 strncpy(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode)-1);
2965 tmp->amaflags = i->amaflags;
2966 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
2967 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
2968 tmp->adsicpe = i->peeradsicpe;
2969 tmp->pvt->fixup = iax2_fixup;
2971 i->capability = capability;
2972 ast_setstate(tmp, state);
2973 ast_mutex_lock(&usecnt_lock);
2975 ast_mutex_unlock(&usecnt_lock);
2976 ast_update_use_count();
2977 if (state != AST_STATE_DOWN) {
2978 if (ast_pbx_start(tmp)) {
2979 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
2984 for (v = i->vars ; v ; v = v->next)
2985 pbx_builtin_setvar_helper(tmp,v->name,v->value);
2991 static unsigned int calc_txpeerstamp(struct iax2_trunk_peer *tpeer, int sampms, struct timeval *tv)
2993 unsigned long int mssincetx; /* unsigned to handle overflows */
2996 tpeer->trunkact = *tv;
2997 mssincetx = (tv->tv_sec - tpeer->lasttxtime.tv_sec) * 1000 +
2998 (1000000 + tv->tv_usec - tpeer->lasttxtime.tv_usec) / 1000 - 1000;
2999 if (mssincetx > 5000 || (!tpeer->txtrunktime.tv_sec && !tpeer->txtrunktime.tv_usec)) {
3000 /* If it's been at least 5 seconds since the last time we transmitted on this trunk, reset our timers */
3001 tpeer->txtrunktime.tv_sec = tv->tv_sec;
3002 tpeer->txtrunktime.tv_usec = tv->tv_usec;
3003 tpeer->lastsent = 999999;
3005 /* Update last transmit time now */
3006 tpeer->lasttxtime.tv_sec = tv->tv_sec;
3007 tpeer->lasttxtime.tv_usec = tv->tv_usec;
3009 /* Calculate ms offset */
3010 ms = (tv->tv_sec - tpeer->txtrunktime.tv_sec) * 1000 +
3011 (1000000 + tv->tv_usec - tpeer->txtrunktime.tv_usec) / 1000 - 1000;
3012 /* Predict from last value */
3013 pred = tpeer->lastsent + sampms;
3014 if (abs(ms - pred) < MAX_TIMESTAMP_SKEW)
3017 /* We never send the same timestamp twice, so fudge a little if we must */
3018 if (ms == tpeer->lastsent)
3019 ms = tpeer->lastsent + 1;
3020 tpeer->lastsent = ms;
3024 static unsigned int fix_peerts(struct timeval *tv, int callno, unsigned int ts)
3026 long ms; /* NOT unsigned */
3027 if (!iaxs[callno]->rxcore.tv_sec && !iaxs[callno]->rxcore.tv_usec) {
3028 /* Initialize rxcore time if appropriate */
3029 gettimeofday(&iaxs[callno]->rxcore, NULL);
3030 /* Round to nearest 20ms so traces look pretty */
3031 iaxs[callno]->rxcore.tv_usec -= iaxs[callno]->rxcore.tv_usec % 20000;
3033 /* Calculate difference between trunk and channel */
3034 ms = (tv->tv_sec - iaxs[callno]->rxcore.tv_sec) * 1000 +
3035 (1000000 + tv->tv_usec - iaxs[callno]->rxcore.tv_usec) / 1000 - 1000;
3036 /* Return as the sum of trunk time and the difference between trunk and real time */
3040 static void add_ms(struct timeval *tv, int ms) {
3041 tv->tv_usec += ms * 1000;
3042 if(tv->tv_usec > 1000000) {
3043 tv->tv_usec -= 1000000;
3046 if(tv->tv_usec < 0) {
3047 tv->tv_usec += 1000000;
3052 static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts, struct ast_frame *f)
3058 struct timeval *delivery = NULL;
3060 /* What sort of frame do we have?: voice is self-explanatory
3061 "genuine" means an IAX frame - things like LAGRQ/RP, PING/PONG, ACK
3062 non-genuine frames are CONTROL frames [ringing etc], DTMF
3063 The "genuine" distinction is needed because genuine frames must get a clock-based timestamp,
3064 the others need a timestamp slaved to the voice frames so that they go in sequence
3067 if (f->frametype == AST_FRAME_VOICE) {
3069 delivery = &f->delivery;
3070 } else if (f->frametype == AST_FRAME_IAX) {
3072 } else if (f->frametype == AST_FRAME_CNG) {
3076 if (!p->offset.tv_sec && !p->offset.tv_usec) {
3077 gettimeofday(&p->offset, NULL);
3078 /* Round to nearest 20ms for nice looking traces */
3079 p->offset.tv_usec -= p->offset.tv_usec % 20000;
3081 /* If the timestamp is specified, just send it as is */
3084 /* If we have a time that the frame arrived, always use it to make our timestamp */
3085 if (delivery && (delivery->tv_sec || delivery->tv_usec)) {
3086 ms = (delivery->tv_sec - p->offset.tv_sec) * 1000 +
3087 (1000000 + delivery->tv_usec - p->offset.tv_usec) / 1000 - 1000;
3089 ast_log(LOG_DEBUG, "calc_timestamp: call %d/%d: Timestamp slaved to delivery time\n", p->callno, iaxs[p->callno]->peercallno);
3091 gettimeofday(&tv, NULL);
3092 ms = (tv.tv_sec - p->offset.tv_sec) * 1000 +
3093 (1000000 + tv.tv_usec - p->offset.tv_usec) / 1000 - 1000;
3097 /* On a voice frame, use predicted values if appropriate */
3098 if (p->notsilenttx && abs(ms - p->nextpred) <= MAX_TIMESTAMP_SKEW) {
3099 /* Adjust our txcore, keeping voice and
3100 non-voice synchronized */
3101 add_ms(&p->offset, (int)(ms - p->nextpred)/10);
3104 p->nextpred = ms; /*f->samples / 8;*/
3105 if (p->nextpred <= p->lastsent)
3106 p->nextpred = p->lastsent + 3;
3110 /* in this case, just use the actual
3111 * time, since we're either way off
3112 * (shouldn't happen), or we're ending a
3113 * silent period -- and seed the next
3114 * predicted time. Also, round ms to the
3115 * next multiple of frame size (so our
3116 * silent periods are multiples of
3117 * frame size too) */
3118 if (f->samples >= 8) /* check to make sure we dont core dump */
3120 int diff = ms % (f->samples / 8);
3122 ms += f->samples/8 - diff;
3129 /* On a dataframe, use last value + 3 (to accomodate jitter buffer shrinking) if appropriate unless
3130 it's a genuine frame */
3132 /* genuine (IAX LAGRQ etc) must keep their clock-based stamps */
3133 if (ms <= p->lastsent)
3134 ms = p->lastsent + 3;
3135 } else if (abs(ms - p->lastsent) <= MAX_TIMESTAMP_SKEW) {
3136 /* non-genuine frames (!?) (DTMF, CONTROL) should be pulled into the predicted stream stamps */
3137 ms = p->lastsent + 3;
3143 p->nextpred = p->nextpred + f->samples / 8;
3145 printf("TS: %s - %dms\n", voice ? "Audio" : "Control", ms);
3150 #ifdef BRIDGE_OPTIMIZATION
3151 static unsigned int calc_fakestamp(struct chan_iax2_pvt *p1, struct chan_iax2_pvt *p2, unsigned int fakets)
3154 /* Receive from p1, send to p2 */
3156 /* Setup rxcore if necessary on outgoing channel */
3157 if (!p1->rxcore.tv_sec && !p1->rxcore.tv_usec)
3158 gettimeofday(&p1->rxcore, NULL);
3160 /* Setup txcore if necessary on outgoing channel */
3161 if (!p2->offset.tv_sec && !p2->offset.tv_usec)
3162 gettimeofday(&p2->offset, NULL);
3164 /* Now, ts is the timestamp of the original packet in the orignal context.
3165 Adding rxcore to it gives us when we would want the packet to be delivered normally.
3166 Subtracting txcore of the outgoing channel gives us what we'd expect */
3168 ms = (p1->rxcore.tv_sec - p2->offset.tv_sec) * 1000 +
3169 (1000000 + p1->rxcore.tv_usec - p2->offset.tv_usec) / 1000 - 1000;
3172 /* FIXME? SLD would rather remove this and leave it to the end system to deal with */
3173 if (fakets <= p2->lastsent)
3174 fakets = p2->lastsent + 1;
3175 p2->lastsent = fakets;
3180 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset)
3182 /* Returns where in "receive time" we are. That is, how many ms
3183 since we received (or would have received) the frame with timestamp 0 */
3186 /* Setup rxcore if necessary */
3187 if (!p->rxcore.tv_sec && !p->rxcore.tv_usec) {
3188 gettimeofday(&p->rxcore, NULL);
3190 ast_log(LOG_DEBUG, "calc_rxstamp: call=%d: rxcore set to %d.%6.6d - %dms\n",
3191 p->callno, (int)(p->rxcore.tv_sec), (int)(p->rxcore.tv_usec), offset);
3192 p->rxcore.tv_sec -= offset / 1000;
3193 p->rxcore.tv_usec -= (offset % 1000) * 1000;
3194 if (p->rxcore.tv_usec < 0) {
3195 p->rxcore.tv_usec += 1000000;
3196 p->rxcore.tv_sec -= 1;
3200 ast_log(LOG_DEBUG, "calc_rxstamp: call=%d: works out as %d.%6.6d\n",
3201 p->callno, (int)(p->rxcore.tv_sec),(int)( p->rxcore.tv_usec));
3205 gettimeofday(&tv, NULL);
3206 ms = (tv.tv_sec - p->rxcore.tv_sec) * 1000 +
3207 (1000000 + tv.tv_usec - p->rxcore.tv_usec) / 1000 - 1000;
3211 static struct iax2_trunk_peer *find_tpeer(struct sockaddr_in *sin, int fd)
3213 struct iax2_trunk_peer *tpeer;
3214 char iabuf[INET_ADDRSTRLEN];
3215 /* Finds and locks trunk peer */
3216 ast_mutex_lock(&tpeerlock);
3219 /* We don't lock here because tpeer->addr *never* changes */
3220 if (!inaddrcmp(&tpeer->addr, sin)) {
3221 ast_mutex_lock(&tpeer->lock);
3224 tpeer = tpeer->next;
3227 tpeer = malloc(sizeof(struct iax2_trunk_peer));
3229 memset(tpeer, 0, sizeof(struct iax2_trunk_peer));
3230 ast_mutex_init(&tpeer->lock);
3231 tpeer->lastsent = 9999;
3232 memcpy(&tpeer->addr, sin, sizeof(tpeer->addr));
3233 gettimeofday(&tpeer->trunkact, NULL);
3234 ast_mutex_lock(&tpeer->lock);
3235 tpeer->next = tpeers;
3238 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));
3241 ast_mutex_unlock(&tpeerlock);
3245 static int iax2_trunk_queue(struct chan_iax2_pvt *pvt, struct ast_frame *f)
3247 struct iax2_trunk_peer *tpeer;
3249 struct ast_iax2_meta_trunk_entry *met;
3250 char iabuf[INET_ADDRSTRLEN];
3251 tpeer = find_tpeer(&pvt->addr, pvt->sockfd);
3253 if (tpeer->trunkdatalen + f->datalen + 4 >= tpeer->trunkdataalloc) {
3254 /* Need to reallocate space */
3255 if (tpeer->trunkdataalloc < MAX_TRUNKDATA) {
3256 tmp = realloc(tpeer->trunkdata, tpeer->trunkdataalloc + DEFAULT_TRUNKDATA + IAX2_TRUNK_PREFACE);
3258 tpeer->trunkdataalloc += DEFAULT_TRUNKDATA;
3259 tpeer->trunkdata = tmp;
3260 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);
3262 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));
3263 ast_mutex_unlock(&tpeer->lock);
3267 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));
3268 ast_mutex_unlock(&tpeer->lock);
3273 /* Append to meta frame */
3274 ptr = tpeer->trunkdata + IAX2_TRUNK_PREFACE + tpeer->trunkdatalen;
3275 met = (struct ast_iax2_meta_trunk_entry *)ptr;
3276 /* Store call number and length in meta header */
3277 met->callno = htons(pvt->callno);
3278 met->len = htons(f->datalen);
3279 /* Advance pointers/decrease length past trunk entry header */
3280 ptr += sizeof(struct ast_iax2_meta_trunk_entry);
3281 tpeer->trunkdatalen += sizeof(struct ast_iax2_meta_trunk_entry);
3282 /* Copy actual trunk data */
3283 memcpy(ptr, f->data, f->datalen);
3284 tpeer->trunkdatalen += f->datalen;
3286 ast_mutex_unlock(&tpeer->lock);
3291 static void build_enc_keys(const unsigned char *digest, aes_encrypt_ctx *ecx, aes_decrypt_ctx *dcx)
3293 aes_encrypt_key128(digest, ecx);
3294 aes_decrypt_key128(digest, dcx);
3297 static void memcpy_decrypt(unsigned char *dst, const unsigned char *src, int len, aes_decrypt_ctx *dcx)
3299 /* memcpy(dst, src, len); */
3300 unsigned char lastblock[16] = { 0 };
3303 aes_decrypt(src, dst, dcx);
3305 dst[x] ^= lastblock[x];
3306 memcpy(lastblock, src, sizeof(lastblock));
3313 static void memcpy_encrypt(unsigned char *dst, const unsigned char *src, int len, aes_encrypt_ctx *ecx)
3315 /* memcpy(dst, src, len); */
3316 unsigned char curblock[16] = { 0 };
3320 curblock[x] ^= src[x];
3321 aes_encrypt(curblock, dst, ecx);
3322 memcpy(curblock, dst, sizeof(curblock));
3329 static int decode_frame(aes_decrypt_ctx *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen)
3332 unsigned char *workspace;
3333 workspace = alloca(*datalen);
3336 if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
3337 struct ast_iax2_full_enc_hdr *efh = (struct ast_iax2_full_enc_hdr *)fh;
3339 ast_log(LOG_DEBUG, "Decoding full frame with length %d\n", *datalen);
3340 if (*datalen < 16 + sizeof(struct ast_iax2_full_hdr))
3342 padding = 16 + (efh->encdata[15] & 0xf);
3343 if (*datalen < padding + sizeof(struct ast_iax2_full_hdr))
3346 memcpy_decrypt(workspace, efh->encdata, *datalen, dcx);
3347 *datalen -= padding;
3348 memcpy(efh->encdata, workspace + padding, *datalen - sizeof(struct ast_iax2_full_enc_hdr));
3349 f->frametype = fh->type;
3350 if (f->frametype == AST_FRAME_VIDEO) {
3351 f->subclass = uncompress_subclass(fh->csub & ~0x40) | ((fh->csub >> 6) & 0x1);
3353 f->subclass = uncompress_subclass(fh->csub);
3356 struct ast_iax2_mini_enc_hdr *efh = (struct ast_iax2_mini_enc_hdr *)fh;
3358 ast_log(LOG_DEBUG, "Decoding mini with length %d\n", *datalen);
3359 if (*datalen < 16 + sizeof(struct ast_iax2_mini_hdr))
3361 padding = 16 + (efh->encdata[15] & 0x0f);
3362 if (*datalen < padding + sizeof(struct ast_iax2_mini_hdr))
3365 memcpy_decrypt(workspace, efh->encdata, *datalen, dcx);
3366 *datalen -= padding;
3367 memcpy(efh->encdata, workspace + padding, *datalen - sizeof(struct ast_iax2_mini_enc_hdr));
3372 static int encrypt_frame(aes_encrypt_ctx *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen)
3375 unsigned char *workspace;
3376 workspace = alloca(*datalen + 32);
3379 if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
3380 struct ast_iax2_full_enc_hdr *efh = (struct ast_iax2_full_enc_hdr *)fh;
3382 ast_log(LOG_DEBUG, "Encoding full frame with length %d\n", *datalen);
3383 padding = 16 - ((*datalen - sizeof(struct ast_iax2_full_enc_hdr)) % 16);
3384 padding = 16 + (padding & 0xf);
3385 memcpy(workspace, poo, padding);
3386 memcpy(workspace + padding, efh->encdata, *datalen - sizeof(struct ast_iax2_full_enc_hdr));
3387 *datalen += padding;
3388 workspace[15] &= 0xf0;
3389 workspace[15] |= (padding & 0xf);
3390 memcpy_encrypt(efh->encdata, workspace, *datalen, ecx);
3391 if (*datalen >= 32 + sizeof(struct ast_iax2_full_enc_hdr))
3392 memcpy(poo, workspace + *datalen - 32, 32);
3394 struct ast_iax2_mini_enc_hdr *efh = (struct ast_iax2_mini_enc_hdr *)fh;
3396 ast_log(LOG_DEBUG, "Encoding mini frame with length %d\n", *datalen);
3397 padding = 16 - ((*datalen - sizeof(struct ast_iax2_mini_enc_hdr)) % 16);
3398 padding = 16 + (padding & 0xf);
3399 memset(workspace, 0, padding);
3400 memcpy(workspace + padding, efh->encdata, *datalen - sizeof(struct ast_iax2_mini_enc_hdr));
3401 workspace[15] &= 0xf0;
3402 workspace[15] |= (padding & 0x0f);
3403 *datalen += padding;
3404 memcpy_encrypt(efh->encdata, workspace, *datalen, ecx);
3405 if (*datalen >= 32 + sizeof(struct ast_iax2_mini_enc_hdr))
3406 memcpy(poo, workspace + *datalen - 32, 32);
3411 static int decrypt_frame(int callno, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen)
3414 if (!ast_test_flag(iaxs[callno], IAX_KEYPOPULATED)) {
3415 /* Search for possible keys, given secrets */
3416 struct MD5Context md5;
3417 unsigned char digest[16];
3418 char *tmppw, *stringp;
3420 tmppw = ast_strdupa(iaxs[callno]->secret);
3422 while((tmppw = strsep(&stringp, ";"))) {
3424 MD5Update(&md5, iaxs[callno]->challenge, strlen(iaxs[callno]->challenge));
3425 MD5Update(&md5, tmppw, strlen(tmppw));
3426 MD5Final(digest, &md5);
3427 build_enc_keys(digest, &iaxs[callno]->ecx, &iaxs[callno]->dcx);
3428 res = decode_frame(&iaxs[callno]->dcx, fh, f, datalen);
3430 ast_set_flag(iaxs[callno], IAX_KEYPOPULATED);
3435 res = decode_frame(&iaxs[callno]->dcx, fh, f, datalen);
3439 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final)
3441 /* Queue a packet for delivery on a given private structure. Use "ts" for