2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2006, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
21 * \brief Implementation of Inter-Asterisk eXchange Version 2
23 * \author Mark Spencer <markster@digium.com>
26 * \arg \ref Config_iax
28 * \ingroup channel_drivers
38 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
42 #include <sys/types.h>
45 #include <sys/socket.h>
46 #include <netinet/in.h>
47 #include <arpa/inet.h>
48 #include <netinet/in_systm.h>
49 #include <netinet/ip.h>
51 #include <sys/signal.h>
62 #include "asterisk/zapata.h"
64 #include "asterisk/lock.h"
65 #include "asterisk/frame.h"
66 #include "asterisk/channel.h"
67 #include "asterisk/logger.h"
68 #include "asterisk/module.h"
69 #include "asterisk/pbx.h"
70 #include "asterisk/sched.h"
71 #include "asterisk/io.h"
72 #include "asterisk/config.h"
73 #include "asterisk/options.h"
74 #include "asterisk/cli.h"
75 #include "asterisk/translate.h"
76 #include "asterisk/md5.h"
77 #include "asterisk/cdr.h"
78 #include "asterisk/crypto.h"
79 #include "asterisk/acl.h"
80 #include "asterisk/manager.h"
81 #include "asterisk/callerid.h"
82 #include "asterisk/app.h"
83 #include "asterisk/astdb.h"
84 #include "asterisk/musiconhold.h"
85 #include "asterisk/features.h"
86 #include "asterisk/utils.h"
87 #include "asterisk/causes.h"
88 #include "asterisk/localtime.h"
89 #include "asterisk/aes.h"
90 #include "asterisk/dnsmgr.h"
91 #include "asterisk/devicestate.h"
92 #include "asterisk/netsock.h"
93 #include "asterisk/stringfields.h"
94 #include "asterisk/linkedlists.h"
95 #include "asterisk/event.h"
98 #include "iax2-parser.h"
99 #include "iax2-provision.h"
100 #include "jitterbuf.h"
102 /* Define SCHED_MULTITHREADED to run the scheduler in a special
103 multithreaded mode. */
104 #define SCHED_MULTITHREADED
106 /* Define DEBUG_SCHED_MULTITHREADED to keep track of where each
107 thread is actually doing. */
108 #define DEBUG_SCHED_MULTITHREAD
110 #ifndef IPTOS_MINCOST
111 #define IPTOS_MINCOST 0x02
115 static int nochecksums = 0;
119 #define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
120 #define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
122 #define DEFAULT_THREAD_COUNT 10
123 #define DEFAULT_MAX_THREAD_COUNT 100
124 #define DEFAULT_RETRY_TIME 1000
125 #define MEMORY_SIZE 100
126 #define DEFAULT_DROP 3
127 /* Flag to use with trunk calls, keeping these calls high up. It halves our effective use
128 but keeps the division between trunked and non-trunked better. */
129 #define TRUNK_CALL_START 0x4000
131 #define DEBUG_SUPPORT
133 #define MIN_REUSE_TIME 60 /* Don't reuse a call number within 60 seconds */
135 /* Sample over last 100 units to determine historic jitter */
138 static struct ast_codec_pref prefs;
140 static const char tdesc[] = "Inter Asterisk eXchange Driver (Ver 2)";
143 /*! \brief Maximum transmission unit for the UDP packet in the trunk not to be
144 fragmented. This is based on 1516 - ethernet - ip - udp - iax minus one g711 frame = 1240 */
145 #define MAX_TRUNK_MTU 1240
147 static int global_max_trunk_mtu; /*!< Maximum MTU, 0 if not used */
148 static int trunk_timed, trunk_untimed, trunk_maxmtu, trunk_nmaxmtu ; /*!< Trunk MTU statistics */
151 static char context[80] = "default";
153 static char language[MAX_LANGUAGE] = "";
154 static char regcontext[AST_MAX_CONTEXT] = "";
156 static int maxauthreq = 3;
157 static int max_retries = 4;
158 static int ping_time = 21;
159 static int lagrq_time = 10;
160 static int maxtrunkcall = TRUNK_CALL_START;
161 static int maxnontrunkcall = 1;
162 static int maxjitterbuffer=1000;
163 static int resyncthreshold=1000;
164 static int maxjitterinterps=10;
165 static int jittertargetextra = 40; /* number of milliseconds the new jitter buffer adds on to its size */
167 #define MAX_TRUNKDATA 640 * 200 /*!< 40ms, uncompressed linear * 200 channels */
169 static int trunkfreq = 20;
170 static int trunkmaxsize = MAX_TRUNKDATA;
172 static int authdebug = 1;
173 static int autokill = 0;
174 static int iaxcompat = 0;
176 static int iaxdefaultdpcache=10 * 60; /* Cache dialplan entries for 10 minutes by default */
178 static int iaxdefaulttimeout = 5; /* Default to wait no more than 5 seconds for a reply to come back */
180 static unsigned int tos = 0;
182 static unsigned int cos = 0;
184 static int min_reg_expire;
185 static int max_reg_expire;
187 static int srvlookup = 0;
189 static int timingfd = -1; /* Timing file descriptor */
191 static struct ast_netsock_list *netsock;
192 static struct ast_netsock_list *outsock; /*!< used if sourceaddress specified and bindaddr == INADDR_ANY */
193 static int defaultsockfd = -1;
195 int (*iax2_regfunk)(const char *username, int onoff) = NULL;
198 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
200 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
201 ~AST_FORMAT_SLINEAR & \
206 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
208 ~AST_FORMAT_G726_AAL2 & \
211 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
215 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
216 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
217 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
219 static struct io_context *io;
220 static struct sched_context *sched;
222 static int iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
224 static int iaxdebug = 0;
226 static int iaxtrunkdebug = 0;
228 static int test_losspct = 0;
230 static int test_late = 0;
231 static int test_resync = 0;
232 static int test_jit = 0;
233 static int test_jitpct = 0;
234 #endif /* IAXTESTS */
236 static char accountcode[AST_MAX_ACCOUNT_CODE];
237 static char mohinterpret[MAX_MUSICCLASS];
238 static char mohsuggest[MAX_MUSICCLASS];
239 static int amaflags = 0;
241 static int delayreject = 0;
242 static int iax2_encryption = 0;
244 static struct ast_flags globalflags = { 0 };
246 static pthread_t netthreadid = AST_PTHREADT_NULL;
247 static pthread_t schedthreadid = AST_PTHREADT_NULL;
248 AST_MUTEX_DEFINE_STATIC(sched_lock);
249 static ast_cond_t sched_cond;
252 IAX_STATE_STARTED = (1 << 0),
253 IAX_STATE_AUTHENTICATED = (1 << 1),
254 IAX_STATE_TBD = (1 << 2),
255 IAX_STATE_UNCHANGED = (1 << 3),
258 struct iax2_context {
259 char context[AST_MAX_CONTEXT];
260 struct iax2_context *next;
264 IAX_HASCALLERID = (1 << 0), /*!< CallerID has been specified */
265 IAX_DELME = (1 << 1), /*!< Needs to be deleted */
266 IAX_TEMPONLY = (1 << 2), /*!< Temporary (realtime) */
267 IAX_TRUNK = (1 << 3), /*!< Treat as a trunk */
268 IAX_NOTRANSFER = (1 << 4), /*!< Don't native bridge */
269 IAX_USEJITTERBUF = (1 << 5), /*!< Use jitter buffer */
270 IAX_DYNAMIC = (1 << 6), /*!< dynamic peer */
271 IAX_SENDANI = (1 << 7), /*!< Send ANI along with CallerID */
272 /* (1 << 8) is currently unused due to the deprecation of an old option. Go ahead, take it! */
273 IAX_ALREADYGONE = (1 << 9), /*!< Already disconnected */
274 IAX_PROVISION = (1 << 10), /*!< This is a provisioning request */
275 IAX_QUELCH = (1 << 11), /*!< Whether or not we quelch audio */
276 IAX_ENCRYPTED = (1 << 12), /*!< Whether we should assume encrypted tx/rx */
277 IAX_KEYPOPULATED = (1 << 13), /*!< Whether we have a key populated */
278 IAX_CODEC_USER_FIRST = (1 << 14), /*!< are we willing to let the other guy choose the codec? */
279 IAX_CODEC_NOPREFS = (1 << 15), /*!< Force old behaviour by turning off prefs */
280 IAX_CODEC_NOCAP = (1 << 16), /*!< only consider requested format and ignore capabilities*/
281 IAX_RTCACHEFRIENDS = (1 << 17), /*!< let realtime stay till your reload */
282 IAX_RTUPDATE = (1 << 18), /*!< Send a realtime update */
283 IAX_RTAUTOCLEAR = (1 << 19), /*!< erase me on expire */
284 IAX_FORCEJITTERBUF = (1 << 20), /*!< Force jitterbuffer, even when bridged to a channel that can take jitter */
285 IAX_RTIGNOREREGEXPIRE = (1 << 21), /*!< When using realtime, ignore registration expiration */
286 IAX_TRUNKTIMESTAMPS = (1 << 22), /*!< Send trunk timestamps */
287 IAX_TRANSFERMEDIA = (1 << 23), /*!< When doing IAX2 transfers, transfer media only */
288 IAX_MAXAUTHREQ = (1 << 24), /*!< Maximum outstanding AUTHREQ restriction is in place */
289 IAX_DELAYPBXSTART = (1 << 25), /*!< Don't start a PBX on the channel until the peer sends us a
290 response, so that we've achieved a three-way handshake with
291 them before sending voice or anything else*/
294 static int global_rtautoclear = 120;
296 static int reload_config(void);
297 static int iax2_reload(int fd, int argc, char *argv[]);
301 AST_DECLARE_STRING_FIELDS(
302 AST_STRING_FIELD(name);
303 AST_STRING_FIELD(secret);
304 AST_STRING_FIELD(dbsecret);
305 AST_STRING_FIELD(accountcode);
306 AST_STRING_FIELD(mohinterpret);
307 AST_STRING_FIELD(mohsuggest);
308 AST_STRING_FIELD(inkeys); /*!< Key(s) this user can use to authenticate to us */
309 AST_STRING_FIELD(language);
310 AST_STRING_FIELD(cid_num);
311 AST_STRING_FIELD(cid_name);
320 int maxauthreq; /*!< Maximum allowed outstanding AUTHREQs */
321 int curauthreq; /*!< Current number of outstanding AUTHREQs */
322 struct ast_codec_pref prefs;
324 struct iax2_context *contexts;
325 struct ast_variable *vars;
326 AST_LIST_ENTRY(iax2_user) entry;
330 AST_DECLARE_STRING_FIELDS(
331 AST_STRING_FIELD(name);
332 AST_STRING_FIELD(username);
333 AST_STRING_FIELD(secret);
334 AST_STRING_FIELD(dbsecret);
335 AST_STRING_FIELD(outkey); /*!< What key we use to talk to this peer */
337 AST_STRING_FIELD(regexten); /*!< Extension to register (if regcontext is used) */
338 AST_STRING_FIELD(context); /*!< For transfers only */
339 AST_STRING_FIELD(peercontext); /*!< Context to pass to peer */
340 AST_STRING_FIELD(mailbox); /*!< Mailbox */
341 AST_STRING_FIELD(mohinterpret);
342 AST_STRING_FIELD(mohsuggest);
343 AST_STRING_FIELD(inkeys); /*!< Key(s) this peer can use to authenticate to us */
344 /* Suggested caller id if registering */
345 AST_STRING_FIELD(cid_num); /*!< Default context (for transfer really) */
346 AST_STRING_FIELD(cid_name); /*!< Default context (for transfer really) */
347 AST_STRING_FIELD(zonetag); /*!< Time Zone */
349 struct ast_codec_pref prefs;
350 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
351 struct sockaddr_in addr;
353 int sockfd; /*!< Socket to use for transmission */
358 /* Dynamic Registration fields */
359 struct sockaddr_in defaddr; /*!< Default address if there is one */
360 int authmethods; /*!< Authentication methods (IAX_AUTH_*) */
361 int encmethods; /*!< Encryption methods (IAX_ENCRYPT_*) */
363 int expire; /*!< Schedule entry for expiry */
364 int expiry; /*!< How soon to expire */
365 int capability; /*!< Capability */
368 int callno; /*!< Call number of POKE request */
369 int pokeexpire; /*!< Scheduled qualification-related task (ie iax2_poke_peer_s or iax2_poke_noanswer) */
370 int lastms; /*!< How long last response took (in ms), or -1 for no response */
371 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
373 int pokefreqok; /*!< How often to check if the host is up */
374 int pokefreqnotok; /*!< How often to check when the host has been determined to be down */
375 int historicms; /*!< How long recent average responses took */
376 int smoothing; /*!< Sample over how many units to determine historic ms */
378 struct ast_event_sub *mwi_event_sub;
381 AST_LIST_ENTRY(iax2_peer) entry;
384 #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
386 struct iax2_trunk_peer {
389 struct sockaddr_in addr;
390 struct timeval txtrunktime; /*!< Transmit trunktime */
391 struct timeval rxtrunktime; /*!< Receive trunktime */
392 struct timeval lasttxtime; /*!< Last transmitted trunktime */
393 struct timeval trunkact; /*!< Last trunk activity */
394 unsigned int lastsent; /*!< Last sent time */
395 /* Trunk data and length */
396 unsigned char *trunkdata;
397 unsigned int trunkdatalen;
398 unsigned int trunkdataalloc;
402 AST_LIST_ENTRY(iax2_trunk_peer) list;
405 static AST_LIST_HEAD_STATIC(tpeers, iax2_trunk_peer);
407 struct iax_firmware {
408 AST_LIST_ENTRY(iax_firmware) list;
412 struct ast_iax2_firmware_header *fwh;
417 REG_STATE_UNREGISTERED = 0,
420 REG_STATE_REGISTERED,
426 enum iax_transfer_state {
431 TRANSFER_PASSTHROUGH,
435 TRANSFER_MPASSTHROUGH,
440 struct iax2_registry {
441 struct sockaddr_in addr; /*!< Who we connect to for registration purposes */
443 char secret[80]; /*!< Password or key name in []'s */
444 int expire; /*!< Sched ID of expiration */
445 int refresh; /*!< How often to refresh */
446 enum iax_reg_state regstate;
447 int messages; /*!< Message count, low 8 bits = new, high 8 bits = old */
448 int callno; /*!< Associated call number if applicable */
449 struct sockaddr_in us; /*!< Who the server thinks we are */
450 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
451 AST_LIST_ENTRY(iax2_registry) entry;
454 static AST_LIST_HEAD_STATIC(registrations, iax2_registry);
456 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
457 #define MIN_RETRY_TIME 100
458 #define MAX_RETRY_TIME 10000
460 #define MAX_JITTER_BUFFER 50
461 #define MIN_JITTER_BUFFER 10
463 #define DEFAULT_TRUNKDATA 640 * 10 /*!< 40ms, uncompressed linear * 10 channels */
465 #define MAX_TIMESTAMP_SKEW 160 /*!< maximum difference between actual and predicted ts for sending */
467 /* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
468 #define TS_GAP_FOR_JB_RESYNC 5000
470 static int iaxthreadcount = DEFAULT_THREAD_COUNT;
471 static int iaxmaxthreadcount = DEFAULT_MAX_THREAD_COUNT;
472 static int iaxdynamicthreadcount = 0;
473 static int iaxactivethreadcount = 0;
487 struct chan_iax2_pvt {
488 /*! Socket to send/receive on for this call */
490 /*! Last received voice format */
492 /*! Last received video format */
494 /*! Last sent voice format */
496 /*! Last sent video format */
498 /*! What we are capable of sending */
500 /*! Last received timestamp */
502 /*! Last sent timestamp - never send the same timestamp twice in a single call */
503 unsigned int lastsent;
504 /*! Next outgoing timestamp if everything is good */
505 unsigned int nextpred;
506 /*! True if the last voice we transmitted was not silence/CNG */
507 unsigned int notsilenttx:1;
509 unsigned int pingtime;
510 /*! Max time for initial response */
513 struct sockaddr_in addr;
514 /*! Actual used codec preferences */
515 struct ast_codec_pref prefs;
516 /*! Requested codec preferences */
517 struct ast_codec_pref rprefs;
518 /*! Our call number */
519 unsigned short callno;
521 unsigned short peercallno;
522 /*! Negotiated format, this is only used to remember what format was
523 chosen for an unauthenticated call so that the channel can get
524 created later using the right format */
526 /*! Peer selected format */
528 /*! Peer capability */
530 /*! timeval that we base our transmission on */
531 struct timeval offset;
532 /*! timeval that we base our delivery on */
533 struct timeval rxcore;
534 /*! The jitterbuffer */
536 /*! active jb read scheduler id */
540 /*! Error, as discovered by the manager */
542 /*! Owner if we have one */
543 struct ast_channel *owner;
544 /*! What's our state? */
545 struct ast_flags state;
546 /*! Expiry (optional) */
548 /*! Next outgoing sequence number */
549 unsigned char oseqno;
550 /*! Next sequence number they have not yet acknowledged */
551 unsigned char rseqno;
552 /*! Next incoming sequence number */
553 unsigned char iseqno;
554 /*! Last incoming sequence number we have acknowledged */
555 unsigned char aseqno;
557 AST_DECLARE_STRING_FIELDS(
559 AST_STRING_FIELD(peer);
560 /*! Default Context */
561 AST_STRING_FIELD(context);
562 /*! Caller ID if available */
563 AST_STRING_FIELD(cid_num);
564 AST_STRING_FIELD(cid_name);
565 /*! Hidden Caller ID (i.e. ANI) if appropriate */
566 AST_STRING_FIELD(ani);
568 AST_STRING_FIELD(dnid);
570 AST_STRING_FIELD(rdnis);
571 /*! Requested Extension */
572 AST_STRING_FIELD(exten);
573 /*! Expected Username */
574 AST_STRING_FIELD(username);
575 /*! Expected Secret */
576 AST_STRING_FIELD(secret);
578 AST_STRING_FIELD(challenge);
579 /*! Public keys permitted keys for incoming authentication */
580 AST_STRING_FIELD(inkeys);
581 /*! Private key for outgoing authentication */
582 AST_STRING_FIELD(outkey);
583 /*! Preferred language */
584 AST_STRING_FIELD(language);
585 /*! Hostname/peername for naming purposes */
586 AST_STRING_FIELD(host);
588 AST_STRING_FIELD(dproot);
589 AST_STRING_FIELD(accountcode);
590 AST_STRING_FIELD(mohinterpret);
591 AST_STRING_FIELD(mohsuggest);
592 /*! received OSP token */
593 AST_STRING_FIELD(osptoken);
596 /*! permitted authentication methods */
598 /*! permitted encryption methods */
600 /*! Encryption AES-128 Key */
601 ast_aes_encrypt_key ecx;
602 /*! Decryption AES-128 Key */
603 ast_aes_decrypt_key dcx;
604 /*! 32 bytes of semi-random data */
605 unsigned char semirand[32];
606 /*! Associated registry */
607 struct iax2_registry *reg;
608 /*! Associated peer for poking */
609 struct iax2_peer *peerpoke;
614 /*! Transferring status */
615 enum iax_transfer_state transferring;
616 /*! Transfer identifier */
618 /*! Who we are IAX transferring to */
619 struct sockaddr_in transfer;
620 /*! What's the new call number for the transfer */
621 unsigned short transfercallno;
622 /*! Transfer encrypt AES-128 Key */
623 ast_aes_encrypt_key tdcx;
625 /*! Status of knowledge of peer ADSI capability */
628 /*! Who we are bridged to */
629 unsigned short bridgecallno;
631 int pingid; /*!< Transmit PING request */
632 int lagid; /*!< Retransmit lag request */
633 int autoid; /*!< Auto hangup for Dialplan requestor */
634 int authid; /*!< Authentication rejection ID */
635 int authfail; /*!< Reason to report failure */
636 int initid; /*!< Initial peer auto-congest ID (based on qualified peers) */
641 AST_LIST_HEAD_NOLOCK(, iax2_dpcache) dpentries;
642 struct ast_variable *vars;
643 /*! last received remote rr */
644 struct iax_rr remote_rr;
645 /*! Current base time: (just for stats) */
647 /*! Dropped frame count: (just for stats) */
649 /*! received frame count: (just for stats) */
654 * \brief a list of frames that may need to be retransmitted
656 * \note The contents of this list do not need to be explicitly destroyed
657 * on module unload. This is because all active calls are destroyed, and
658 * all frames in this queue will get destroyed as a part of that process.
660 static AST_LIST_HEAD_STATIC(frame_queue, iax_frame);
662 static AST_LIST_HEAD_STATIC(users, iax2_user);
664 static AST_LIST_HEAD_STATIC(peers, iax2_peer);
666 static AST_LIST_HEAD_STATIC(firmwares, iax_firmware);
669 /*! Extension exists */
670 CACHE_FLAG_EXISTS = (1 << 0),
671 /*! Extension is nonexistent */
672 CACHE_FLAG_NONEXISTENT = (1 << 1),
673 /*! Extension can exist */
674 CACHE_FLAG_CANEXIST = (1 << 2),
675 /*! Waiting to hear back response */
676 CACHE_FLAG_PENDING = (1 << 3),
678 CACHE_FLAG_TIMEOUT = (1 << 4),
679 /*! Request transmitted */
680 CACHE_FLAG_TRANSMITTED = (1 << 5),
682 CACHE_FLAG_UNKNOWN = (1 << 6),
684 CACHE_FLAG_MATCHMORE = (1 << 7),
687 struct iax2_dpcache {
688 char peercontext[AST_MAX_CONTEXT];
689 char exten[AST_MAX_EXTENSION];
691 struct timeval expiry;
693 unsigned short callno;
695 AST_LIST_ENTRY(iax2_dpcache) cache_list;
696 AST_LIST_ENTRY(iax2_dpcache) peer_list;
699 static AST_LIST_HEAD_STATIC(dpcache, iax2_dpcache);
701 static void reg_source_db(struct iax2_peer *p);
702 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
704 static void destroy_peer(struct iax2_peer *peer);
705 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt);
707 enum iax2_thread_iostate {
710 IAX_IOSTATE_PROCESSING,
711 IAX_IOSTATE_SCHEDREADY,
714 enum iax2_thread_type {
715 IAX_THREAD_TYPE_POOL,
716 IAX_THREAD_TYPE_DYNAMIC,
719 struct iax2_pkt_buf {
720 AST_LIST_ENTRY(iax2_pkt_buf) entry;
722 unsigned char buf[1];
726 AST_LIST_ENTRY(iax2_thread) list;
727 enum iax2_thread_type type;
728 enum iax2_thread_iostate iostate;
729 #ifdef SCHED_MULTITHREADED
730 void (*schedfunc)(void *);
733 #ifdef DEBUG_SCHED_MULTITHREAD
739 struct sockaddr_in iosin;
740 unsigned char readbuf[4096];
748 unsigned int ready_for_signal:1;
749 /*! if this thread is processing a full frame,
750 some information about that frame will be stored
751 here, so we can avoid dispatching any more full
752 frames for that callno to other threads */
754 unsigned short callno;
755 struct sockaddr_in sin;
759 /*! Queued up full frames for processing. If more full frames arrive for
760 * a call which this thread is already processing a full frame for, they
761 * are queued up here. */
762 AST_LIST_HEAD_NOLOCK(, iax2_pkt_buf) full_frames;
766 static AST_LIST_HEAD_STATIC(idle_list, iax2_thread);
767 static AST_LIST_HEAD_STATIC(active_list, iax2_thread);
768 static AST_LIST_HEAD_STATIC(dynamic_list, iax2_thread);
770 static void *iax2_process_thread(void *data);
772 static void signal_condition(ast_mutex_t *lock, ast_cond_t *cond)
774 ast_mutex_lock(lock);
775 ast_cond_signal(cond);
776 ast_mutex_unlock(lock);
779 static void iax_debug_output(const char *data)
782 ast_verbose("%s", data);
785 static void iax_error_output(const char *data)
787 ast_log(LOG_WARNING, "%s", data);
790 static void jb_error_output(const char *fmt, ...)
796 vsnprintf(buf, sizeof(buf), fmt, args);
799 ast_log(LOG_ERROR, buf);
802 static void jb_warning_output(const char *fmt, ...)
808 vsnprintf(buf, sizeof(buf), fmt, args);
811 ast_log(LOG_WARNING, buf);
814 static void jb_debug_output(const char *fmt, ...)
820 vsnprintf(buf, sizeof(buf), fmt, args);
827 * \brief an array of iax2 pvt structures
829 * The container for active chan_iax2_pvt structures is implemented as an
830 * array for extremely quick direct access to the correct pvt structure
831 * based on the local call number. The local call number is used as the
832 * index into the array where the associated pvt structure is stored.
834 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS];
836 * \brief chan_iax2_pvt structure locks
838 * These locks are used when accessing a pvt structure in the iaxs array.
839 * The index used here is the same as used in the iaxs array. It is the
840 * local call number for the associated pvt struct.
842 static ast_mutex_t iaxsl[IAX_MAX_CALLS];
844 * \brief The last time a call number was used
846 * It is important to know the last time that a call number was used locally so
847 * that it is not used again too soon. The reason for this is the same as the
848 * reason that the TCP protocol state machine requires a "TIME WAIT" state.
850 * For example, say that a call is up. Then, the remote side sends a HANGUP,
851 * which we respond to with an ACK. However, there is no way to know whether
852 * the ACK made it there successfully. If it were to get lost, the remote
853 * side may retransmit the HANGUP. If in the meantime, this call number has
854 * been reused locally, given the right set of circumstances, this retransmitted
855 * HANGUP could potentially improperly hang up the new session. So, to avoid
856 * this potential issue, we must wait a specified timeout period before reusing
857 * a local call number.
859 * The specified time that we must wait before reusing a local call number is
860 * defined as MIN_REUSE_TIME, with a default of 60 seconds.
862 static struct timeval lastused[IAX_MAX_CALLS];
864 static enum ast_bridge_result iax2_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc, int timeoutms);
865 static int expire_registry(void *data);
866 static int iax2_answer(struct ast_channel *c);
867 static int iax2_call(struct ast_channel *c, char *dest, int timeout);
868 static int iax2_devicestate(void *data);
869 static int iax2_digit_begin(struct ast_channel *c, char digit);
870 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration);
871 static int iax2_do_register(struct iax2_registry *reg);
872 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
873 static int iax2_hangup(struct ast_channel *c);
874 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen);
875 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
876 static int iax2_provision(struct sockaddr_in *end, int sockfd, char *dest, const char *template, int force);
877 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
878 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
879 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
880 static int iax2_sendtext(struct ast_channel *c, const char *text);
881 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
882 static int iax2_transfer(struct ast_channel *c, const char *dest);
883 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
884 static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now);
885 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
886 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
887 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
888 static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int);
889 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
890 static struct ast_channel *iax2_request(const char *type, int format, void *data, int *cause);
891 static struct ast_frame *iax2_read(struct ast_channel *c);
892 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
893 static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
894 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, time_t regtime);
895 static void destroy_user(struct iax2_user *user);
896 static void prune_peers(void);
897 static void *iax2_dup_variable_datastore(void *);
898 static void iax2_free_variable_datastore(void *);
900 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
901 static int acf_channel_write(struct ast_channel *chan, const char *function, char *data, const char *value);
903 static const struct ast_channel_tech iax2_tech = {
905 .description = tdesc,
906 .capabilities = IAX_CAPABILITY_FULLBANDWIDTH,
907 .properties = AST_CHAN_TP_WANTSJITTER,
908 .requester = iax2_request,
909 .devicestate = iax2_devicestate,
910 .send_digit_begin = iax2_digit_begin,
911 .send_digit_end = iax2_digit_end,
912 .send_text = iax2_sendtext,
913 .send_image = iax2_sendimage,
914 .send_html = iax2_sendhtml,
916 .hangup = iax2_hangup,
917 .answer = iax2_answer,
920 .write_video = iax2_write,
921 .indicate = iax2_indicate,
922 .setoption = iax2_setoption,
923 .bridge = iax2_bridge,
924 .transfer = iax2_transfer,
926 .func_channel_read = acf_channel_read,
927 .func_channel_write = acf_channel_write,
930 static void mwi_event_cb(const struct ast_event *event, void *userdata)
932 /* The MWI subscriptions exist just so the core knows we care about those
933 * mailboxes. However, we just grab the events out of the cache when it
934 * is time to send MWI, since it is only sent with a REGACK. */
937 /*! \brief Send manager event at call setup to link between Asterisk channel name
938 and IAX2 call identifiers */
939 static void iax2_ami_channelupdate(struct chan_iax2_pvt *pvt)
941 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
942 "Channel: %s\r\nChanneltype: IAX2\r\nIAX2-callno-local: %d\r\nIAX2-callno-remote: %d\r\nIAX2-peer: %s\r\n",
943 pvt->owner ? pvt->owner->name : "",
944 pvt->callno, pvt->peercallno, pvt->peer ? pvt->peer : "");
948 static struct ast_datastore_info iax2_variable_datastore_info = {
949 .type = "IAX2_VARIABLE",
950 .duplicate = iax2_dup_variable_datastore,
951 .destroy = iax2_free_variable_datastore,
954 static void *iax2_dup_variable_datastore(void *old)
956 AST_LIST_HEAD(, ast_var_t) *oldlist = old, *newlist;
957 struct ast_var_t *oldvar, *newvar;
959 newlist = ast_calloc(sizeof(*newlist), 1);
961 ast_log(LOG_ERROR, "Unable to duplicate iax2 variables\n");
965 AST_LIST_HEAD_INIT(newlist);
966 AST_LIST_LOCK(oldlist);
967 AST_LIST_TRAVERSE(oldlist, oldvar, entries) {
968 newvar = ast_var_assign(ast_var_name(oldvar), ast_var_value(oldvar));
970 AST_LIST_INSERT_TAIL(newlist, newvar, entries);
972 ast_log(LOG_ERROR, "Unable to duplicate iax2 variable '%s'\n", ast_var_name(oldvar));
974 AST_LIST_UNLOCK(oldlist);
978 static void iax2_free_variable_datastore(void *old)
980 AST_LIST_HEAD(, ast_var_t) *oldlist = old;
981 struct ast_var_t *oldvar;
983 AST_LIST_LOCK(oldlist);
984 while ((oldvar = AST_LIST_REMOVE_HEAD(oldlist, entries))) {
987 AST_LIST_UNLOCK(oldlist);
988 AST_LIST_HEAD_DESTROY(oldlist);
992 /* WARNING: insert_idle_thread should only ever be called within the
993 * context of an iax2_process_thread() thread.
995 static void insert_idle_thread(struct iax2_thread *thread)
997 if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
998 AST_LIST_LOCK(&dynamic_list);
999 AST_LIST_INSERT_TAIL(&dynamic_list, thread, list);
1000 AST_LIST_UNLOCK(&dynamic_list);
1002 AST_LIST_LOCK(&idle_list);
1003 AST_LIST_INSERT_TAIL(&idle_list, thread, list);
1004 AST_LIST_UNLOCK(&idle_list);
1010 static struct iax2_thread *find_idle_thread(void)
1012 struct iax2_thread *thread = NULL;
1014 /* Pop the head of the idle list off */
1015 AST_LIST_LOCK(&idle_list);
1016 thread = AST_LIST_REMOVE_HEAD(&idle_list, list);
1017 AST_LIST_UNLOCK(&idle_list);
1019 /* If we popped a thread off the idle list, just return it */
1021 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1025 /* Pop the head of the dynamic list off */
1026 AST_LIST_LOCK(&dynamic_list);
1027 thread = AST_LIST_REMOVE_HEAD(&dynamic_list, list);
1028 AST_LIST_UNLOCK(&dynamic_list);
1030 /* If we popped a thread off the dynamic list, just return it */
1032 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1036 /* If we can't create a new dynamic thread for any reason, return no thread at all */
1037 if (iaxdynamicthreadcount >= iaxmaxthreadcount || !(thread = ast_calloc(1, sizeof(*thread))))
1040 /* Set default values */
1041 thread->threadnum = ast_atomic_fetchadd_int(&iaxdynamicthreadcount, 1);
1042 thread->type = IAX_THREAD_TYPE_DYNAMIC;
1044 /* Initialize lock and condition */
1045 ast_mutex_init(&thread->lock);
1046 ast_cond_init(&thread->cond, NULL);
1048 /* Create thread and send it on it's way */
1049 if (ast_pthread_create_detached_background(&thread->threadid, NULL, iax2_process_thread, thread)) {
1050 ast_cond_destroy(&thread->cond);
1051 ast_mutex_destroy(&thread->lock);
1056 /* this thread is not processing a full frame (since it is idle),
1057 so ensure that the field for the full frame call number is empty */
1058 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1060 /* Wait for the thread to be ready before returning it to the caller */
1061 while (!thread->ready_for_signal)
1067 #ifdef SCHED_MULTITHREADED
1068 static int __schedule_action(void (*func)(void *data), void *data, const char *funcname)
1070 struct iax2_thread *thread = NULL;
1071 static time_t lasterror;
1074 thread = find_idle_thread();
1076 if (thread != NULL) {
1077 thread->schedfunc = func;
1078 thread->scheddata = data;
1079 thread->iostate = IAX_IOSTATE_SCHEDREADY;
1080 #ifdef DEBUG_SCHED_MULTITHREAD
1081 ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc));
1083 signal_condition(&thread->lock, &thread->cond);
1088 ast_log(LOG_NOTICE, "Out of idle IAX2 threads for scheduling!\n");
1093 #define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
1096 static int send_ping(void *data);
1098 static void __send_ping(void *data)
1100 int callno = (long)data;
1101 ast_mutex_lock(&iaxsl[callno]);
1102 if (iaxs[callno] && iaxs[callno]->pingid != -1) {
1103 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
1104 iaxs[callno]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, data);
1106 ast_mutex_unlock(&iaxsl[callno]);
1109 static int send_ping(void *data)
1111 #ifdef SCHED_MULTITHREADED
1112 if (schedule_action(__send_ping, data))
1118 static int get_encrypt_methods(const char *s)
1121 if (!strcasecmp(s, "aes128"))
1122 e = IAX_ENCRYPT_AES128;
1123 else if (ast_true(s))
1124 e = IAX_ENCRYPT_AES128;
1130 static int send_lagrq(void *data);
1132 static void __send_lagrq(void *data)
1134 int callno = (long)data;
1135 /* Ping only if it's real not if it's bridged */
1136 ast_mutex_lock(&iaxsl[callno]);
1137 if (iaxs[callno] && iaxs[callno]->lagid != -1) {
1138 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
1139 iaxs[callno]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, data);
1141 ast_mutex_unlock(&iaxsl[callno]);
1144 static int send_lagrq(void *data)
1146 #ifdef SCHED_MULTITHREADED
1147 if (schedule_action(__send_lagrq, data))
1153 static unsigned char compress_subclass(int subclass)
1157 /* If it's 128 or smaller, just return it */
1158 if (subclass < IAX_FLAG_SC_LOG)
1160 /* Otherwise find its power */
1161 for (x = 0; x < IAX_MAX_SHIFT; x++) {
1162 if (subclass & (1 << x)) {
1164 ast_log(LOG_WARNING, "Can't compress subclass %d\n", subclass);
1170 return power | IAX_FLAG_SC_LOG;
1173 static int uncompress_subclass(unsigned char csub)
1175 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
1176 if (csub & IAX_FLAG_SC_LOG) {
1177 /* special case for 'compressed' -1 */
1181 return 1 << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
1188 * \note This funtion calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
1189 * so do not call it with a pvt lock held.
1191 static struct iax2_peer *find_peer(const char *name, int realtime)
1193 struct iax2_peer *peer = NULL;
1195 /* Grab peer from linked list */
1196 AST_LIST_LOCK(&peers);
1197 AST_LIST_TRAVERSE(&peers, peer, entry) {
1198 if (!strcasecmp(peer->name, name)) {
1202 AST_LIST_UNLOCK(&peers);
1204 /* Now go for realtime if applicable */
1205 if(!peer && realtime)
1206 peer = realtime_peer(name, NULL);
1210 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len, int lockpeer)
1212 struct iax2_peer *peer = NULL;
1216 AST_LIST_LOCK(&peers);
1217 AST_LIST_TRAVERSE(&peers, peer, entry) {
1218 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
1219 (peer->addr.sin_port == sin.sin_port)) {
1220 ast_copy_string(host, peer->name, len);
1226 AST_LIST_UNLOCK(&peers);
1228 peer = realtime_peer(NULL, &sin);
1230 ast_copy_string(host, peer->name, len);
1231 if (ast_test_flag(peer, IAX_TEMPONLY))
1240 static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, int lockpeer, const char *host)
1242 struct chan_iax2_pvt *tmp;
1245 if (!(tmp = ast_calloc(1, sizeof(*tmp))))
1248 if (ast_string_field_init(tmp, 32)) {
1261 ast_string_field_set(tmp,exten, "s");
1262 ast_string_field_set(tmp,host, host);
1266 jbconf.max_jitterbuf = maxjitterbuffer;
1267 jbconf.resync_threshold = resyncthreshold;
1268 jbconf.max_contig_interp = maxjitterinterps;
1269 jbconf.target_extra = jittertargetextra;
1270 jb_setconf(tmp->jb,&jbconf);
1272 AST_LIST_HEAD_INIT_NOLOCK(&tmp->dpentries);
1277 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
1279 struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen, fr->cacheable);
1281 size_t afdatalen = new->afdatalen;
1282 memcpy(new, fr, sizeof(*new));
1283 iax_frame_wrap(new, &fr->af);
1284 new->afdatalen = afdatalen;
1287 new->direction = DIRECTION_INGRESS;
1293 #define NEW_PREVENT 0
1297 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, const struct chan_iax2_pvt *cur)
1299 if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
1300 (cur->addr.sin_port == sin->sin_port)) {
1301 /* This is the main host */
1302 if ((cur->peercallno == callno) ||
1303 ((dcallno == cur->callno) && !cur->peercallno)) {
1304 /* That's us. Be sure we keep track of the peer call number */
1308 if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
1309 (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
1310 /* We're transferring */
1311 if ((dcallno == cur->callno) || (cur->transferring == TRANSFER_MEDIAPASS && cur->transfercallno == callno))
1317 static void update_max_trunk(void)
1319 int max = TRUNK_CALL_START;
1321 /* XXX Prolly don't need locks here XXX */
1322 for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
1328 ast_debug(1, "New max trunk callno is %d\n", max);
1331 static void update_max_nontrunk(void)
1335 /* XXX Prolly don't need locks here XXX */
1336 for (x=1;x<TRUNK_CALL_START - 1; x++) {
1340 maxnontrunkcall = max;
1342 ast_debug(1, "New max nontrunk callno is %d\n", max);
1345 static int make_trunk(unsigned short callno, int locked)
1349 struct timeval now = ast_tvnow();
1350 if (iaxs[callno]->oseqno) {
1351 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
1354 if (callno & TRUNK_CALL_START) {
1355 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
1358 for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
1359 ast_mutex_lock(&iaxsl[x]);
1360 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) {
1361 iaxs[x] = iaxs[callno];
1362 iaxs[x]->callno = x;
1363 iaxs[callno] = NULL;
1364 /* Update the two timers that should have been started */
1365 if (iaxs[x]->pingid > -1)
1366 ast_sched_del(sched, iaxs[x]->pingid);
1367 if (iaxs[x]->lagid > -1)
1368 ast_sched_del(sched, iaxs[x]->lagid);
1369 iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
1370 iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
1372 ast_mutex_unlock(&iaxsl[callno]);
1375 ast_mutex_unlock(&iaxsl[x]);
1378 ast_mutex_unlock(&iaxsl[x]);
1380 if (x >= IAX_MAX_CALLS - 1) {
1381 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
1384 ast_debug(1, "Made call %d into trunk call %d\n", callno, x);
1385 /* We move this call from a non-trunked to a trunked call */
1387 update_max_nontrunk();
1392 * \todo XXX Note that this function contains a very expensive operation that
1393 * happens for *every* incoming media frame. It iterates through every
1394 * possible call number, locking and unlocking each one, to try to match the
1395 * incoming frame to an active call. Call numbers can be up to 2^15, 32768.
1396 * So, for an call with a local call number of 20000, every incoming audio
1397 * frame would require 20000 mutex lock and unlock operations. Ouch.
1399 * It's a shame that IAX2 media frames carry the source call number instead of
1400 * the destination call number. If they did, this lookup wouldn't be needed.
1401 * However, it's too late to change that now. Instead, we need to come up with
1402 * a better way of indexing active calls so that these frequent lookups are not
1405 * \note Calling this function while holding another pvt lock can cause a deadlock.
1407 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int lockpeer, int sockfd)
1414 if (new <= NEW_ALLOW) {
1415 for (x=1;(res < 1) && (x<maxnontrunkcall);x++) {
1416 ast_mutex_lock(&iaxsl[x]);
1418 /* Look for an exact match */
1419 if (match(sin, callno, dcallno, iaxs[x])) {
1423 ast_mutex_unlock(&iaxsl[x]);
1425 for (x=TRUNK_CALL_START;(res < 1) && (x<maxtrunkcall);x++) {
1426 ast_mutex_lock(&iaxsl[x]);
1428 /* Look for an exact match */
1429 if (match(sin, callno, dcallno, iaxs[x])) {
1433 ast_mutex_unlock(&iaxsl[x]);
1436 if ((res < 1) && (new >= NEW_ALLOW)) {
1437 /* It may seem odd that we look through the peer list for a name for
1438 * this *incoming* call. Well, it is weird. However, users don't
1439 * have an IP address/port number that we can match against. So,
1440 * this is just checking for a peer that has that IP/port and
1441 * assuming that we have a user of the same name. This isn't always
1442 * correct, but it will be changed if needed after authentication. */
1443 if (!iax2_getpeername(*sin, host, sizeof(host), lockpeer))
1444 snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
1446 for (x=1;x<TRUNK_CALL_START;x++) {
1447 /* Find first unused call number that hasn't been used in a while */
1448 ast_mutex_lock(&iaxsl[x]);
1449 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) break;
1450 ast_mutex_unlock(&iaxsl[x]);
1452 /* We've still got lock held if we found a spot */
1453 if (x >= TRUNK_CALL_START) {
1454 ast_log(LOG_WARNING, "No more space\n");
1457 iaxs[x] = new_iax(sin, lockpeer, host);
1458 update_max_nontrunk();
1461 ast_debug(1, "Creating new call structure %d\n", x);
1462 iaxs[x]->sockfd = sockfd;
1463 iaxs[x]->addr.sin_port = sin->sin_port;
1464 iaxs[x]->addr.sin_family = sin->sin_family;
1465 iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
1466 iaxs[x]->peercallno = callno;
1467 iaxs[x]->callno = x;
1468 iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
1469 iaxs[x]->expiry = min_reg_expire;
1470 iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
1471 iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
1472 iaxs[x]->amaflags = amaflags;
1473 ast_copy_flags(iaxs[x], (&globalflags), IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
1475 ast_string_field_set(iaxs[x], accountcode, accountcode);
1476 ast_string_field_set(iaxs[x], mohinterpret, mohinterpret);
1477 ast_string_field_set(iaxs[x], mohsuggest, mohsuggest);
1479 ast_log(LOG_WARNING, "Out of resources\n");
1480 ast_mutex_unlock(&iaxsl[x]);
1483 ast_mutex_unlock(&iaxsl[x]);
1489 static void iax2_frame_free(struct iax_frame *fr)
1491 if (fr->retrans > -1)
1492 ast_sched_del(sched, fr->retrans);
1497 * \brief Queue a frame to a call's owning asterisk channel
1499 * \note This function assumes that iaxsl[callno] is locked when called.
1501 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
1502 * was valid before calling it, it may no longer be valid after calling it.
1503 * This function may unlock and lock the mutex associated with this callno,
1504 * meaning that another thread may grab it and destroy the call.
1506 static int iax2_queue_frame(int callno, struct ast_frame *f)
1508 /* Assumes lock for callno is already held... */
1510 if (iaxs[callno] && iaxs[callno]->owner) {
1511 if (ast_mutex_trylock(&iaxs[callno]->owner->lock)) {
1512 /* Avoid deadlock by pausing and trying again */
1513 ast_mutex_unlock(&iaxsl[callno]);
1515 ast_mutex_lock(&iaxsl[callno]);
1517 ast_queue_frame(iaxs[callno]->owner, f);
1518 ast_mutex_unlock(&iaxs[callno]->owner->lock);
1527 static void destroy_firmware(struct iax_firmware *cur)
1529 /* Close firmware */
1531 munmap((void*)cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh)));
1537 static int try_firmware(char *s)
1540 struct iax_firmware *cur = NULL;
1541 int ifd, fd, res, len, chunk;
1542 struct ast_iax2_firmware_header *fwh, fwh2;
1543 struct MD5Context md5;
1544 unsigned char sum[16], buf[1024];
1547 if (!(s2 = alloca(strlen(s) + 100))) {
1548 ast_log(LOG_WARNING, "Alloca failed!\n");
1552 last = strrchr(s, '/');
1558 snprintf(s2, strlen(s) + 100, "/var/tmp/%s-%ld", last, (unsigned long)ast_random());
1560 if ((res = stat(s, &stbuf) < 0)) {
1561 ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno));
1565 /* Make sure it's not a directory */
1566 if (S_ISDIR(stbuf.st_mode))
1568 ifd = open(s, O_RDONLY);
1570 ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
1573 fd = open(s2, O_RDWR | O_CREAT | O_EXCL, AST_FILE_MODE);
1575 ast_log(LOG_WARNING, "Cannot open '%s' for writing: %s\n", s2, strerror(errno));
1579 /* Unlink our newly created file */
1582 /* Now copy the firmware into it */
1583 len = stbuf.st_size;
1586 if (chunk > sizeof(buf))
1587 chunk = sizeof(buf);
1588 res = read(ifd, buf, chunk);
1590 ast_log(LOG_WARNING, "Only read %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1595 res = write(fd, buf, chunk);
1597 ast_log(LOG_WARNING, "Only write %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1605 /* Return to the beginning */
1606 lseek(fd, 0, SEEK_SET);
1607 if ((res = read(fd, &fwh2, sizeof(fwh2))) != sizeof(fwh2)) {
1608 ast_log(LOG_WARNING, "Unable to read firmware header in '%s'\n", s);
1612 if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) {
1613 ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s);
1617 if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) {
1618 ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s);
1622 if (fwh2.devname[sizeof(fwh2.devname) - 1] || ast_strlen_zero((char *)fwh2.devname)) {
1623 ast_log(LOG_WARNING, "No or invalid device type specified for '%s'\n", s);
1627 fwh = (struct ast_iax2_firmware_header*)mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
1628 if (fwh == (void *) -1) {
1629 ast_log(LOG_WARNING, "mmap failed: %s\n", strerror(errno));
1634 MD5Update(&md5, fwh->data, ntohl(fwh->datalen));
1635 MD5Final(sum, &md5);
1636 if (memcmp(sum, fwh->chksum, sizeof(sum))) {
1637 ast_log(LOG_WARNING, "Firmware file '%s' fails checksum\n", s);
1638 munmap((void*)fwh, stbuf.st_size);
1643 AST_LIST_TRAVERSE(&firmwares, cur, list) {
1644 if (!strcmp((char *)cur->fwh->devname, (char *)fwh->devname)) {
1645 /* Found a candidate */
1646 if (cur->dead || (ntohs(cur->fwh->version) < ntohs(fwh->version)))
1647 /* The version we have on loaded is older, load this one instead */
1649 /* This version is no newer than what we have. Don't worry about it.
1650 We'll consider it a proper load anyhow though */
1651 munmap((void*)fwh, stbuf.st_size);
1657 if (!cur && ((cur = ast_calloc(1, sizeof(*cur))))) {
1659 AST_LIST_INSERT_TAIL(&firmwares, cur, list);
1664 munmap((void*)cur->fwh, cur->mmaplen);
1669 cur->mmaplen = stbuf.st_size;
1676 static int iax_check_version(char *dev)
1679 struct iax_firmware *cur = NULL;
1681 if (ast_strlen_zero(dev))
1684 AST_LIST_LOCK(&firmwares);
1685 AST_LIST_TRAVERSE(&firmwares, cur, list) {
1686 if (!strcmp(dev, (char *)cur->fwh->devname)) {
1687 res = ntohs(cur->fwh->version);
1691 AST_LIST_UNLOCK(&firmwares);
1696 static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
1699 unsigned int bs = desc & 0xff;
1700 unsigned int start = (desc >> 8) & 0xffffff;
1702 struct iax_firmware *cur;
1704 if (ast_strlen_zero((char *)dev) || !bs)
1709 AST_LIST_LOCK(&firmwares);
1710 AST_LIST_TRAVERSE(&firmwares, cur, list) {
1711 if (strcmp((char *)dev, (char *)cur->fwh->devname))
1713 iax_ie_append_int(ied, IAX_IE_FWBLOCKDESC, desc);
1714 if (start < ntohl(cur->fwh->datalen)) {
1715 bytes = ntohl(cur->fwh->datalen) - start;
1718 iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes);
1721 iax_ie_append(ied, IAX_IE_FWBLOCKDATA);
1729 AST_LIST_UNLOCK(&firmwares);
1735 static void reload_firmware(void)
1737 struct iax_firmware *cur = NULL;
1740 char dir[256], fn[256];
1742 AST_LIST_LOCK(&firmwares);
1744 /* Mark all as dead */
1745 AST_LIST_TRAVERSE(&firmwares, cur, list)
1748 /* Now that we have marked them dead... load new ones */
1749 snprintf(dir, sizeof(dir), "%s/firmware/iax", (char *)ast_config_AST_DATA_DIR);
1752 while((de = readdir(fwd))) {
1753 if (de->d_name[0] != '.') {
1754 snprintf(fn, sizeof(fn), "%s/%s", dir, de->d_name);
1755 if (!try_firmware(fn)) {
1756 ast_verb(2, "Loaded firmware '%s'\n", de->d_name);
1762 ast_log(LOG_WARNING, "Error opening firmware directory '%s': %s\n", dir, strerror(errno));
1764 /* Clean up leftovers */
1765 AST_LIST_TRAVERSE_SAFE_BEGIN(&firmwares, cur, list) {
1768 AST_LIST_REMOVE_CURRENT(&firmwares, list);
1769 destroy_firmware(cur);
1771 AST_LIST_TRAVERSE_SAFE_END
1773 AST_LIST_UNLOCK(&firmwares);
1777 * \note This function assumes that iaxsl[callno] is locked when called.
1779 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
1780 * was valid before calling it, it may no longer be valid after calling it.
1781 * This function calls iax2_queue_frame(), which may unlock and lock the mutex
1782 * associated with this callno, meaning that another thread may grab it and destroy the call.
1784 static int __do_deliver(void *data)
1786 /* Just deliver the packet by using queueing. This is called by
1787 the IAX thread with the iaxsl lock held. */
1788 struct iax_frame *fr = data;
1790 fr->af.has_timing_info = 0;
1791 if (iaxs[fr->callno] && !ast_test_flag(iaxs[fr->callno], IAX_ALREADYGONE))
1792 iax2_queue_frame(fr->callno, &fr->af);
1793 /* Free our iax frame */
1794 iax2_frame_free(fr);
1795 /* And don't run again */
1799 static int handle_error(void)
1801 /* XXX Ideally we should figure out why an error occurred and then abort those
1802 rather than continuing to try. Unfortunately, the published interface does
1803 not seem to work XXX */
1805 struct sockaddr_in *sin;
1808 struct sock_extended_err e;
1813 m.msg_controllen = sizeof(e);
1815 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
1817 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
1819 if (m.msg_controllen) {
1820 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
1822 ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(sin->sin_addr));
1824 ast_log(LOG_WARNING, "No address detected??\n");
1826 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
1833 static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin, int sockfd)
1836 res = sendto(sockfd, f->data, f->datalen, 0,(struct sockaddr *)sin,
1839 ast_debug(1, "Received error: %s\n", strerror(errno));
1846 static int send_packet(struct iax_frame *f)
1849 int callno = f->callno;
1851 /* Don't send if there was an error, but return error instead */
1852 if (!callno || !iaxs[callno] || iaxs[callno]->error)
1855 /* Called with iaxsl held */
1857 ast_debug(3, "Sending %d on %d/%d to %s:%d\n", f->ts, callno, iaxs[callno]->peercallno, ast_inet_ntoa(iaxs[callno]->addr.sin_addr), ntohs(iaxs[callno]->addr.sin_port));
1860 iax_showframe(f, NULL, 0, &iaxs[callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
1861 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->transfer,
1862 sizeof(iaxs[callno]->transfer));
1865 iax_showframe(f, NULL, 0, &iaxs[callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
1866 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->addr,
1867 sizeof(iaxs[callno]->addr));
1871 ast_debug(1, "Received error: %s\n", strerror(errno));
1878 static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
1880 struct iax2_user *user = NULL;
1882 /* Decrement AUTHREQ count if needed */
1883 if (ast_test_flag(pvt, IAX_MAXAUTHREQ)) {
1884 AST_LIST_LOCK(&users);
1885 AST_LIST_TRAVERSE(&users, user, entry) {
1886 if (!strcmp(user->name, pvt->username)) {
1891 AST_LIST_UNLOCK(&users);
1892 ast_clear_flag(pvt, IAX_MAXAUTHREQ);
1894 /* No more pings or lagrq's */
1895 if (pvt->pingid > -1)
1896 ast_sched_del(sched, pvt->pingid);
1898 if (pvt->lagid > -1)
1899 ast_sched_del(sched, pvt->lagid);
1901 if (pvt->autoid > -1)
1902 ast_sched_del(sched, pvt->autoid);
1904 if (pvt->authid > -1)
1905 ast_sched_del(sched, pvt->authid);
1907 if (pvt->initid > -1)
1908 ast_sched_del(sched, pvt->initid);
1911 ast_sched_del(sched, pvt->jbid);
1915 static int iax2_predestroy(int callno)
1917 struct ast_channel *c = NULL;
1918 struct chan_iax2_pvt *pvt = iaxs[callno];
1923 if (!ast_test_flag(pvt, IAX_ALREADYGONE)) {
1924 iax2_destroy_helper(pvt);
1925 ast_set_flag(pvt, IAX_ALREADYGONE);
1928 if ((c = pvt->owner)) {
1929 c->_softhangup |= AST_SOFTHANGUP_DEV;
1931 ast_queue_hangup(c);
1933 ast_module_unref(ast_module_info->self);
1939 static void iax2_destroy(int callno)
1941 struct chan_iax2_pvt *pvt = NULL;
1942 struct iax_frame *cur = NULL;
1943 struct ast_channel *owner = NULL;
1947 lastused[callno] = ast_tvnow();
1949 owner = pvt ? pvt->owner : NULL;
1952 if (ast_mutex_trylock(&owner->lock)) {
1953 ast_log(LOG_NOTICE, "Avoiding IAX destroy deadlock\n");
1954 ast_mutex_unlock(&iaxsl[callno]);
1956 ast_mutex_lock(&iaxsl[callno]);
1961 iaxs[callno] = NULL;
1965 iax2_destroy_helper(pvt);
1968 ast_set_flag(pvt, IAX_ALREADYGONE);
1971 /* If there's an owner, prod it to give up */
1972 owner->_softhangup |= AST_SOFTHANGUP_DEV;
1973 ast_queue_hangup(owner);
1976 AST_LIST_LOCK(&frame_queue);
1977 AST_LIST_TRAVERSE(&frame_queue, cur, list) {
1978 /* Cancel any pending transmissions */
1979 if (cur->callno == pvt->callno)
1982 AST_LIST_UNLOCK(&frame_queue);
1985 pvt->reg->callno = 0;
1989 ast_variables_destroy(pvt->vars);
1993 while (jb_getall(pvt->jb, &frame) == JB_OK)
1994 iax2_frame_free(frame.data);
1995 jb_destroy(pvt->jb);
1996 /* gotta free up the stringfields */
1997 ast_string_field_free_pools(pvt);
2002 ast_mutex_unlock(&owner->lock);
2004 if (callno & 0x4000)
2008 static int update_packet(struct iax_frame *f)
2010 /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
2011 struct ast_iax2_full_hdr *fh = f->data;
2012 /* Mark this as a retransmission */
2013 fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
2015 f->iseqno = iaxs[f->callno]->iseqno;
2016 fh->iseqno = f->iseqno;
2020 static int attempt_transmit(void *data);
2021 static void __attempt_transmit(void *data)
2023 /* Attempt to transmit the frame to the remote peer...
2024 Called without iaxsl held. */
2025 struct iax_frame *f = data;
2027 int callno = f->callno;
2028 /* Make sure this call is still active */
2030 ast_mutex_lock(&iaxsl[callno]);
2031 if (callno && iaxs[callno]) {
2032 if ((f->retries < 0) /* Already ACK'd */ ||
2033 (f->retries >= max_retries) /* Too many attempts */) {
2034 /* Record an error if we've transmitted too many times */
2035 if (f->retries >= max_retries) {
2037 /* Transfer timeout */
2038 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
2039 } else if (f->final) {
2041 iax2_destroy(callno);
2043 if (iaxs[callno]->owner)
2044 ast_log(LOG_WARNING, "Max retries exceeded to host %s on %s (type = %d, subclass = %d, ts=%d, seqno=%d)\n", ast_inet_ntoa(iaxs[f->callno]->addr.sin_addr),iaxs[f->callno]->owner->name , f->af.frametype, f->af.subclass, f->ts, f->oseqno);
2045 iaxs[callno]->error = ETIMEDOUT;
2046 if (iaxs[callno]->owner) {
2047 struct ast_frame fr = { 0, };
2049 fr.frametype = AST_FRAME_CONTROL;
2050 fr.subclass = AST_CONTROL_HANGUP;
2051 iax2_queue_frame(callno, &fr); // XXX
2052 /* Remember, owner could disappear */
2053 if (iaxs[callno] && iaxs[callno]->owner)
2054 iaxs[callno]->owner->hangupcause = AST_CAUSE_DESTINATION_OUT_OF_ORDER;
2056 if (iaxs[callno]->reg) {
2057 memset(&iaxs[callno]->reg->us, 0, sizeof(iaxs[callno]->reg->us));
2058 iaxs[callno]->reg->regstate = REG_STATE_TIMEOUT;
2059 iaxs[callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
2061 iax2_destroy(callno);
2068 /* Update it if it needs it */
2070 /* Attempt transmission */
2073 /* Try again later after 10 times as long */
2075 if (f->retrytime > MAX_RETRY_TIME)
2076 f->retrytime = MAX_RETRY_TIME;
2077 /* Transfer messages max out at one second */
2078 if (f->transfer && (f->retrytime > 1000))
2079 f->retrytime = 1000;
2080 f->retrans = ast_sched_add(sched, f->retrytime, attempt_transmit, f);
2083 /* Make sure it gets freed */
2088 ast_mutex_unlock(&iaxsl[callno]);
2089 /* Do not try again */
2091 /* Don't attempt delivery, just remove it from the queue */
2092 AST_LIST_LOCK(&frame_queue);
2093 AST_LIST_REMOVE(&frame_queue, f, list);
2094 AST_LIST_UNLOCK(&frame_queue);
2096 /* Free the IAX frame */
2101 static int attempt_transmit(void *data)
2103 #ifdef SCHED_MULTITHREADED
2104 if (schedule_action(__attempt_transmit, data))
2106 __attempt_transmit(data);
2110 static int iax2_prune_realtime(int fd, int argc, char *argv[])
2112 struct iax2_peer *peer;
2115 return RESULT_SHOWUSAGE;
2116 if (!strcmp(argv[3],"all")) {
2118 ast_cli(fd, "OK cache is flushed.\n");
2119 } else if ((peer = find_peer(argv[3], 0))) {
2120 if(ast_test_flag(peer, IAX_RTCACHEFRIENDS)) {
2121 ast_set_flag(peer, IAX_RTAUTOCLEAR);
2122 expire_registry((void *)peer->name);
2123 ast_cli(fd, "OK peer %s was removed from the cache.\n", argv[3]);
2125 ast_cli(fd, "SORRY peer %s is not eligible for this operation.\n", argv[3]);
2128 ast_cli(fd, "SORRY peer %s was not found in the cache.\n", argv[3]);
2131 return RESULT_SUCCESS;
2134 static int iax2_test_losspct(int fd, int argc, char *argv[])
2137 return RESULT_SHOWUSAGE;
2139 test_losspct = atoi(argv[3]);
2141 return RESULT_SUCCESS;
2145 static int iax2_test_late(int fd, int argc, char *argv[])
2148 return RESULT_SHOWUSAGE;
2150 test_late = atoi(argv[3]);
2152 return RESULT_SUCCESS;
2155 static int iax2_test_resync(int fd, int argc, char *argv[])
2158 return RESULT_SHOWUSAGE;
2160 test_resync = atoi(argv[3]);
2162 return RESULT_SUCCESS;
2165 static int iax2_test_jitter(int fd, int argc, char *argv[])
2167 if (argc < 4 || argc > 5)
2168 return RESULT_SHOWUSAGE;
2170 test_jit = atoi(argv[3]);
2172 test_jitpct = atoi(argv[4]);
2174 return RESULT_SUCCESS;
2176 #endif /* IAXTESTS */
2178 /*! \brief peer_status: Report Peer status in character string */
2179 /* returns 1 if peer is online, -1 if unmonitored */
2180 static int peer_status(struct iax2_peer *peer, char *status, int statuslen)
2184 if (peer->lastms < 0) {
2185 ast_copy_string(status, "UNREACHABLE", statuslen);
2186 } else if (peer->lastms > peer->maxms) {
2187 snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
2189 } else if (peer->lastms) {
2190 snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
2193 ast_copy_string(status, "UNKNOWN", statuslen);
2196 ast_copy_string(status, "Unmonitored", statuslen);
2202 /*! \brief Show one peer in detail */
2203 static int iax2_show_peer(int fd, int argc, char *argv[])
2207 struct iax2_peer *peer;
2208 char codec_buf[512];
2209 int x = 0, codec = 0, load_realtime = 0;
2212 return RESULT_SHOWUSAGE;
2214 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? 1 : 0;
2216 peer = find_peer(argv[3], load_realtime);
2219 ast_cli(fd, " * Name : %s\n", peer->name);
2220 ast_cli(fd, " Secret : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
2221 ast_cli(fd, " Context : %s\n", peer->context);
2222 ast_cli(fd, " Mailbox : %s\n", peer->mailbox);
2223 ast_cli(fd, " Dynamic : %s\n", ast_test_flag(peer, IAX_DYNAMIC) ? "Yes":"No");
2224 ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
2225 ast_cli(fd, " Expire : %d\n", peer->expire);
2226 ast_cli(fd, " ACL : %s\n", (peer->ha?"Yes":"No"));
2227 ast_cli(fd, " Addr->IP : %s Port %d\n", peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)", ntohs(peer->addr.sin_port));
2228 ast_cli(fd, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
2229 ast_cli(fd, " Username : %s\n", peer->username);
2230 ast_cli(fd, " Codecs : ");
2231 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
2232 ast_cli(fd, "%s\n", codec_buf);
2234 ast_cli(fd, " Codec Order : (");
2235 for(x = 0; x < 32 ; x++) {
2236 codec = ast_codec_pref_index(&peer->prefs,x);
2239 ast_cli(fd, "%s", ast_getformatname(codec));
2240 if(x < 31 && ast_codec_pref_index(&peer->prefs,x+1))
2245 ast_cli(fd, "none");
2248 ast_cli(fd, " Status : ");
2249 peer_status(peer, status, sizeof(status));
2250 ast_cli(fd, "%s\n",status);
2251 ast_cli(fd, " Qualify : every %dms when OK, every %dms when UNREACHABLE (sample smoothing %s)\n", peer->pokefreqok, peer->pokefreqnotok, peer->smoothing ? "On" : "Off");
2253 if (ast_test_flag(peer, IAX_TEMPONLY))
2256 ast_cli(fd,"Peer %s not found.\n", argv[3]);
2260 return RESULT_SUCCESS;
2263 static char *complete_iax2_show_peer(const char *line, const char *word, int pos, int state)
2266 struct iax2_peer *p = NULL;
2268 int wordlen = strlen(word);
2270 /* 0 - iax2; 1 - show; 2 - peer; 3 - <peername> */
2272 AST_LIST_LOCK(&peers);
2273 AST_LIST_TRAVERSE(&peers, p, entry) {
2274 if (!strncasecmp(p->name, word, wordlen) && ++which > state) {
2275 res = ast_strdup(p->name);
2279 AST_LIST_UNLOCK(&peers);
2285 static int iax2_show_stats(int fd, int argc, char *argv[])
2287 struct iax_frame *cur;
2288 int cnt = 0, dead=0, final=0;
2291 return RESULT_SHOWUSAGE;
2293 AST_LIST_LOCK(&frame_queue);
2294 AST_LIST_TRAVERSE(&frame_queue, cur, list) {
2295 if (cur->retries < 0)
2301 AST_LIST_UNLOCK(&frame_queue);
2303 ast_cli(fd, " IAX Statistics\n");
2304 ast_cli(fd, "---------------------\n");
2305 ast_cli(fd, "Outstanding frames: %d (%d ingress, %d egress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
2306 ast_cli(fd, "%d timed and %d untimed transmits; MTU %d/%d/%d\n", trunk_timed, trunk_untimed,
2307 trunk_maxmtu, trunk_nmaxmtu, global_max_trunk_mtu);
2309 ast_cli(fd, "Packets in transmit queue: %d dead, %d final, %d total\n\n", dead, final, cnt);
2311 trunk_timed = trunk_untimed = 0;
2312 if (trunk_maxmtu > trunk_nmaxmtu)
2313 trunk_nmaxmtu = trunk_maxmtu;
2315 return RESULT_SUCCESS;
2318 /*! \brief Set trunk MTU from CLI */
2319 static int iax2_set_mtu(int fd, int argc, char *argv[])
2324 return RESULT_SHOWUSAGE;
2325 if (strncasecmp(argv[3], "default", strlen(argv[3])) == 0)
2326 mtuv = MAX_TRUNK_MTU;
2328 mtuv = atoi(argv[3]);
2331 ast_cli(fd, "Trunk MTU control disabled (mtu was %d)\n", global_max_trunk_mtu);
2332 global_max_trunk_mtu = 0;
2333 return RESULT_SUCCESS;
2335 if (mtuv < 172 || mtuv > 4000) {
2336 ast_cli(fd, "Trunk MTU must be between 172 and 4000\n");
2337 return RESULT_SHOWUSAGE;
2339 ast_cli(fd, "Trunk MTU changed from %d to %d\n", global_max_trunk_mtu, mtuv);
2340 global_max_trunk_mtu = mtuv;
2341 return RESULT_SUCCESS;
2344 static int iax2_show_cache(int fd, int argc, char *argv[])
2346 struct iax2_dpcache *dp = NULL;
2347 char tmp[1024], *pc = NULL;
2349 struct timeval tv = ast_tvnow();
2351 AST_LIST_LOCK(&dpcache);
2353 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
2355 AST_LIST_TRAVERSE(&dpcache, dp, cache_list) {
2356 s = dp->expiry.tv_sec - tv.tv_sec;
2358 if (dp->flags & CACHE_FLAG_EXISTS)
2359 strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
2360 if (dp->flags & CACHE_FLAG_NONEXISTENT)
2361 strncat(tmp, "NONEXISTENT|", sizeof(tmp) - strlen(tmp) - 1);
2362 if (dp->flags & CACHE_FLAG_CANEXIST)
2363 strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
2364 if (dp->flags & CACHE_FLAG_PENDING)
2365 strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
2366 if (dp->flags & CACHE_FLAG_TIMEOUT)
2367 strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
2368 if (dp->flags & CACHE_FLAG_TRANSMITTED)
2369 strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
2370 if (dp->flags & CACHE_FLAG_MATCHMORE)
2371 strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
2372 if (dp->flags & CACHE_FLAG_UNKNOWN)
2373 strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
2374 /* Trim trailing pipe */
2375 if (!ast_strlen_zero(tmp))
2376 tmp[strlen(tmp) - 1] = '\0';
2378 ast_copy_string(tmp, "(none)", sizeof(tmp));
2380 pc = strchr(dp->peercontext, '@');
2382 pc = dp->peercontext;
2385 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
2386 if (dp->waiters[x] > -1)
2389 ast_cli(fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
2391 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
2394 AST_LIST_LOCK(&dpcache);
2396 return RESULT_SUCCESS;
2399 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
2401 static void unwrap_timestamp(struct iax_frame *fr)
2405 if ( (fr->ts & 0xFFFF0000) == (iaxs[fr->callno]->last & 0xFFFF0000) ) {
2406 x = fr->ts - iaxs[fr->callno]->last;
2408 /* Sudden big jump backwards in timestamp:
2409 What likely happened here is that miniframe timestamp has circled but we haven't
2410 gotten the update from the main packet. We'll just pretend that we did, and
2411 update the timestamp appropriately. */
2412 fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) + 0x10000) | (fr->ts & 0xFFFF);
2414 ast_debug(1, "schedule_delivery: pushed forward timestamp\n");
2417 /* Sudden apparent big jump forwards in timestamp:
2418 What's likely happened is this is an old miniframe belonging to the previous
2419 top-16-bit timestamp that has turned up out of order.
2420 Adjust the timestamp appropriately. */
2421 fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) - 0x10000) | (fr->ts & 0xFFFF);
2423 ast_debug(1, "schedule_delivery: pushed back timestamp\n");
2428 static int get_from_jb(void *p);
2430 static void update_jbsched(struct chan_iax2_pvt *pvt)
2434 when = ast_tvdiff_ms(ast_tvnow(), pvt->rxcore);
2436 when = jb_next(pvt->jb) - when;
2438 if(pvt->jbid > -1) ast_sched_del(sched, pvt->jbid);
2441 /* XXX should really just empty until when > 0.. */
2445 pvt->jbid = ast_sched_add(sched, when, get_from_jb, CALLNO_TO_PTR(pvt->callno));
2447 /* Signal scheduler thread */
2448 signal_condition(&sched_lock, &sched_cond);
2451 static void __get_from_jb(void *p)
2453 int callno = PTR_TO_CALLNO(p);
2454 struct chan_iax2_pvt *pvt = NULL;
2455 struct iax_frame *fr;
2460 struct timeval tv = ast_tvnow();
2462 /* Make sure we have a valid private structure before going on */
2463 ast_mutex_lock(&iaxsl[callno]);
2467 ast_mutex_unlock(&iaxsl[callno]);
2473 /* round up a millisecond since ast_sched_runq does; */
2474 /* prevents us from spinning while waiting for our now */
2475 /* to catch up with runq's now */
2478 now = ast_tvdiff_ms(tv, pvt->rxcore);
2480 if(now >= (next = jb_next(pvt->jb))) {
2481 ret = jb_get(pvt->jb,&frame,now,ast_codec_interp_len(pvt->voiceformat));
2486 /* __do_deliver() can cause the call to disappear */
2491 struct ast_frame af = { 0, };
2493 /* create an interpolation frame */
2494 af.frametype = AST_FRAME_VOICE;
2495 af.subclass = pvt->voiceformat;
2496 af.samples = frame.ms * 8;
2497 af.src = "IAX2 JB interpolation";
2498 af.delivery = ast_tvadd(pvt->rxcore, ast_samp2tv(next, 1000));
2499 af.offset = AST_FRIENDLY_OFFSET;
2501 /* queue the frame: For consistency, we would call __do_deliver here, but __do_deliver wants an iax_frame,
2502 * which we'd need to malloc, and then it would free it. That seems like a drag */
2503 if (!ast_test_flag(iaxs[callno], IAX_ALREADYGONE)) {
2504 iax2_queue_frame(callno, &af);
2505 /* iax2_queue_frame() could cause the call to disappear */
2511 iax2_frame_free(frame.data);
2518 /* shouldn't happen */
2523 update_jbsched(pvt);
2524 ast_mutex_unlock(&iaxsl[callno]);
2527 static int get_from_jb(void *data)
2529 #ifdef SCHED_MULTITHREADED
2530 if (schedule_action(__get_from_jb, data))
2532 __get_from_jb(data);
2537 * \note This function assumes fr->callno is locked
2539 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
2540 * was valid before calling it, it may no longer be valid after calling it.
2542 static int schedule_delivery(struct iax_frame *fr, int updatehistory, int fromtrunk, unsigned int *tsout)
2548 /* Attempt to recover wrapped timestamps */
2549 unwrap_timestamp(fr);
2551 /* delivery time is sender's sent timestamp converted back into absolute time according to our clock */
2552 if ( !fromtrunk && !ast_tvzero(iaxs[fr->callno]->rxcore))
2553 fr->af.delivery = ast_tvadd(iaxs[fr->callno]->rxcore, ast_samp2tv(fr->ts, 1000));
2556 ast_debug(1, "schedule_delivery: set delivery to 0 as we don't have an rxcore yet, or frame is from trunk.\n");
2558 fr->af.delivery = ast_tv(0,0);
2561 type = JB_TYPE_CONTROL;
2564 if(fr->af.frametype == AST_FRAME_VOICE) {
2565 type = JB_TYPE_VOICE;
2566 len = ast_codec_get_samples(&fr->af) / 8;
2567 } else if(fr->af.frametype == AST_FRAME_CNG) {
2568 type = JB_TYPE_SILENCE;
2571 if ( (!ast_test_flag(iaxs[fr->callno], IAX_USEJITTERBUF)) ) {
2578 /* if the user hasn't requested we force the use of the jitterbuffer, and we're bridged to
2579 * a channel that can accept jitter, then flush and suspend the jb, and send this frame straight through */
2580 if( (!ast_test_flag(iaxs[fr->callno], IAX_FORCEJITTERBUF)) &&
2581 iaxs[fr->callno]->owner && ast_bridged_channel(iaxs[fr->callno]->owner) &&
2582 (ast_bridged_channel(iaxs[fr->callno]->owner)->tech->properties & AST_CHAN_TP_WANTSJITTER)) {
2585 /* deliver any frames in the jb */
2586 while (jb_getall(iaxs[fr->callno]->jb, &frame) == JB_OK) {
2587 __do_deliver(frame.data);
2588 /* __do_deliver() can make the call disappear */
2589 if (!iaxs[fr->callno])
2593 jb_reset(iaxs[fr->callno]->jb);
2595 if (iaxs[fr->callno]->jbid > -1)
2596 ast_sched_del(sched, iaxs[fr->callno]->jbid);
2598 iaxs[fr->callno]->jbid = -1;
2600 /* deliver this frame now */
2607 /* insert into jitterbuffer */
2608 /* TODO: Perhaps we could act immediately if it's not droppable and late */
2609 ret = jb_put(iaxs[fr->callno]->jb, fr, type, len, fr->ts,
2610 calc_rxstamp(iaxs[fr->callno],fr->ts));
2611 if (ret == JB_DROP) {
2613 } else if (ret == JB_SCHED) {
2614 update_jbsched(iaxs[fr->callno]);
2619 /* Free our iax frame */
2620 iax2_frame_free(fr);
2626 static int iax2_transmit(struct iax_frame *fr)
2628 /* Lock the queue and place this packet at the end */
2629 /* By setting this to 0, the network thread will send it for us, and
2630 queue retransmission if necessary */
2632 AST_LIST_LOCK(&frame_queue);
2633 AST_LIST_INSERT_TAIL(&frame_queue, fr, list);
2634 AST_LIST_UNLOCK(&frame_queue);
2635 /* Wake up the network and scheduler thread */
2636 if (netthreadid != AST_PTHREADT_NULL)
2637 pthread_kill(netthreadid, SIGURG);
2638 signal_condition(&sched_lock, &sched_cond);
2644 static int iax2_digit_begin(struct ast_channel *c, char digit)
2646 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF_BEGIN, digit, 0, NULL, 0, -1);
2649 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration)
2651 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF_END, digit, 0, NULL, 0, -1);
2654 static int iax2_sendtext(struct ast_channel *c, const char *text)
2657 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_TEXT,
2658 0, 0, (unsigned char *)text, strlen(text) + 1, -1);
2661 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
2663 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_IMAGE, img->subclass, 0, img->data, img->datalen, -1);
2666 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen)
2668 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_HTML, subclass, 0, (unsigned char *)data, datalen, -1);
2671 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
2673 unsigned short callno = PTR_TO_CALLNO(newchan->tech_pvt);
2674 ast_mutex_lock(&iaxsl[callno]);
2676 iaxs[callno]->owner = newchan;
2678 ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n");
2679 ast_mutex_unlock(&iaxsl[callno]);
2684 * \note This function calls reg_source_db -> iax2_poke_peer -> find_callno,
2685 * so do not call this with a pvt lock held.
2687 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin)
2689 struct ast_variable *var;
2690 struct ast_variable *tmp;
2691 struct iax2_peer *peer=NULL;
2692 time_t regseconds = 0, nowtime;
2696 var = ast_load_realtime("iaxpeers", "name", peername, NULL);
2699 sprintf(porta, "%d", ntohs(sin->sin_port));
2700 var = ast_load_realtime("iaxpeers", "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, NULL);
2702 /* We'll need the peer name in order to build the structure! */
2703 for (tmp = var; tmp; tmp = tmp->next) {
2704 if (!strcasecmp(tmp->name, "name"))
2705 peername = tmp->value;
2712 peer = build_peer(peername, var, NULL, ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS) ? 0 : 1);
2715 ast_variables_destroy(var);
2719 for (tmp = var; tmp; tmp = tmp->next) {
2720 /* Make sure it's not a user only... */
2721 if (!strcasecmp(tmp->name, "type")) {
2722 if (strcasecmp(tmp->value, "friend") &&
2723 strcasecmp(tmp->value, "peer")) {
2724 /* Whoops, we weren't supposed to exist! */
2729 } else if (!strcasecmp(tmp->name, "regseconds")) {
2730 ast_get_time_t(tmp->value, ®seconds, 0, NULL);
2731 } else if (!strcasecmp(tmp->name, "ipaddr")) {
2732 inet_aton(tmp->value, &(peer->addr.sin_addr));
2733 } else if (!strcasecmp(tmp->name, "port")) {
2734 peer->addr.sin_port = htons(atoi(tmp->value));
2735 } else if (!strcasecmp(tmp->name, "host")) {
2736 if (!strcasecmp(tmp->value, "dynamic"))
2741 ast_variables_destroy(var);
2746 if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
2747 ast_copy_flags(peer, &globalflags, IAX_RTAUTOCLEAR|IAX_RTCACHEFRIENDS);
2748 if (ast_test_flag(peer, IAX_RTAUTOCLEAR)) {
2749 if (peer->expire > -1)
2750 ast_sched_del(sched, peer->expire);
2751 peer->expire = ast_sched_add(sched, (global_rtautoclear) * 1000, expire_registry, (void*)peer->name);
2753 AST_LIST_LOCK(&peers);
2754 AST_LIST_INSERT_HEAD(&peers, peer, entry);
2755 AST_LIST_UNLOCK(&peers);
2756 if (ast_test_flag(peer, IAX_DYNAMIC))
2757 reg_source_db(peer);
2759 ast_set_flag(peer, IAX_TEMPONLY);
2762 if (!ast_test_flag(&globalflags, IAX_RTIGNOREREGEXPIRE) && dynamic) {
2764 if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE) {
2765 memset(&peer->addr, 0, sizeof(peer->addr));
2766 realtime_update_peer(peer->name, &peer->addr, 0);
2767 ast_debug(1, "realtime_peer: Bah, '%s' is expired (%d/%d/%d)!\n",
2768 peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
2771 ast_debug(1, "realtime_peer: Registration for '%s' still active (%d/%d/%d)!\n",
2772 peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
2779 static struct iax2_user *realtime_user(const char *username)
2781 struct ast_variable *var;
2782 struct ast_variable *tmp;
2783 struct iax2_user *user=NULL;
2785 var = ast_load_realtime("iaxusers", "name", username, NULL);
2791 /* Make sure it's not a peer only... */
2792 if (!strcasecmp(tmp->name, "type")) {
2793 if (strcasecmp(tmp->value, "friend") &&
2794 strcasecmp(tmp->value, "user")) {
2801 user = build_user(username, var, NULL, !ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS));
2803 ast_variables_destroy(var);
2808 if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
2809 ast_set_flag(user, IAX_RTCACHEFRIENDS);
2810 AST_LIST_LOCK(&users);
2811 AST_LIST_INSERT_HEAD(&users, user, entry);
2812 AST_LIST_UNLOCK(&users);
2814 ast_set_flag(user, IAX_TEMPONLY);
2820 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, time_t regtime)
2823 char regseconds[20];
2825 snprintf(regseconds, sizeof(regseconds), "%d", (int)regtime);
2826 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
2827 ast_update_realtime("iaxpeers", "name", peername,
2828 "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", port,
2829 "regseconds", regseconds, NULL);
2832 struct create_addr_info {
2845 char context[AST_MAX_CONTEXT];
2846 char peercontext[AST_MAX_CONTEXT];
2847 char mohinterpret[MAX_MUSICCLASS];
2848 char mohsuggest[MAX_MUSICCLASS];
2851 static int create_addr(const char *peername, struct sockaddr_in *sin, struct create_addr_info *cai)
2853 struct iax2_peer *peer;
2855 ast_clear_flag(cai, IAX_SENDANI | IAX_TRUNK);
2856 cai->sockfd = defaultsockfd;
2858 sin->sin_family = AF_INET;
2860 if (!(peer = find_peer(peername, 1))) {
2862 if (ast_get_ip_or_srv(sin, peername, srvlookup ? "_iax._udp" : NULL)) {
2863 ast_log(LOG_WARNING, "No such host: %s\n", peername);
2866 sin->sin_port = htons(IAX_DEFAULT_PORTNO);
2867 /* use global iax prefs for unknown peer/user */
2868 ast_codec_pref_convert(&prefs, cai->prefs, sizeof(cai->prefs), 1);
2874 /* if the peer has no address (current or default), return failure */
2875 if (!(peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr)) {
2876 if (ast_test_flag(peer, IAX_TEMPONLY))
2881 /* if the peer is being monitored and is currently unreachable, return failure */
2882 if (peer->maxms && ((peer->lastms > peer->maxms) || (peer->lastms < 0))) {
2883 if (ast_test_flag(peer, IAX_TEMPONLY))
2888 ast_copy_flags(cai, peer, IAX_SENDANI | IAX_TRUNK | IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
2889 cai->maxtime = peer->maxms;
2890 cai->capability = peer->capability;
2891 cai->encmethods = peer->encmethods;
2892 cai->sockfd = peer->sockfd;
2893 cai->adsi = peer->adsi;
2894 ast_codec_pref_convert(&peer->prefs, cai->prefs, sizeof(cai->prefs), 1);
2895 ast_copy_string(cai->context, peer->context, sizeof(cai->context));
2896 ast_copy_string(cai->peercontext, peer->peercontext, sizeof(cai->peercontext));
2897 ast_copy_string(cai->username, peer->username, sizeof(cai->username));
2898 ast_copy_string(cai->timezone, peer->zonetag, sizeof(cai->timezone));
2899 ast_copy_string(cai->outkey, peer->outkey, sizeof(cai->outkey));
2900 ast_copy_string(cai->mohinterpret, peer->mohinterpret, sizeof(cai->mohinterpret));
2901 ast_copy_string(cai->mohsuggest, peer->mohsuggest, sizeof(cai->mohsuggest));
2902 if (ast_strlen_zero(peer->dbsecret)) {
2903 ast_copy_string(cai->secret, peer->secret, sizeof(cai->secret));
2908 family = ast_strdupa(peer->dbsecret);
2909 key = strchr(family, '/');
2912 if (!key || ast_db_get(family, key, cai->secret, sizeof(cai->secret))) {
2913 ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", peer->dbsecret);
2914 if (ast_test_flag(peer, IAX_TEMPONLY))
2920 if (peer->addr.sin_addr.s_addr) {
2921 sin->sin_addr = peer->addr.sin_addr;
2922 sin->sin_port = peer->addr.sin_port;
2924 sin->sin_addr = peer->defaddr.sin_addr;
2925 sin->sin_port = peer->defaddr.sin_port;
2928 if (ast_test_flag(peer, IAX_TEMPONLY))
2934 static void __auto_congest(void *nothing)
2936 int callno = PTR_TO_CALLNO(nothing);
2937 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_CONGESTION };
2938 ast_mutex_lock(&iaxsl[callno]);
2940 iaxs[callno]->initid = -1;
2941 iax2_queue_frame(callno, &f);
2942 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
2944 ast_mutex_unlock(&iaxsl[callno]);
2947 static int auto_congest(void *data)
2949 #ifdef SCHED_MULTITHREADED
2950 if (schedule_action(__auto_congest, data))
2952 __auto_congest(data);
2956 static unsigned int iax2_datetime(const char *tz)
2958 struct timeval t = ast_tvnow();
2961 ast_localtime(&t, &tm, ast_strlen_zero(tz) ? NULL : tz);
2962 tmp = (tm.tm_sec >> 1) & 0x1f; /* 5 bits of seconds */
2963 tmp |= (tm.tm_min & 0x3f) << 5; /* 6 bits of minutes */
2964 tmp |= (tm.tm_hour & 0x1f) << 11; /* 5 bits of hours */
2965 tmp |= (tm.tm_mday & 0x1f) << 16; /* 5 bits of day of month */
2966 tmp |= ((tm.tm_mon + 1) & 0xf) << 21; /* 4 bits of month */
2967 tmp |= ((tm.tm_year - 100) & 0x7f) << 25; /* 7 bits of year */
2971 struct parsed_dial_string {
2983 * \brief Parses an IAX dial string into its component parts.
2984 * \param data the string to be parsed
2985 * \param pds pointer to a \c struct \c parsed_dial_string to be filled in
2988 * This function parses the string and fills the structure
2989 * with pointers to its component parts. The input string
2992 * \note This function supports both plaintext passwords and RSA
2993 * key names; if the password string is formatted as '[keyname]',
2994 * then the keyname will be placed into the key field, and the
2995 * password field will be set to NULL.
2997 * \note The dial string format is:
2998 * [username[:password]@]peer[:port][/exten[@@context]][/options]
3000 static void parse_dial_string(char *data, struct parsed_dial_string *pds)
3002 if (ast_strlen_zero(data))
3005 pds->peer = strsep(&data, "/");
3006 pds->exten = strsep(&data, "/");
3007 pds->options = data;
3011 pds->exten = strsep(&data, "@");
3012 pds->context = data;
3015 if (strchr(pds->peer, '@')) {
3017 pds->username = strsep(&data, "@");
3021 if (pds->username) {
3022 data = pds->username;
3023 pds->username = strsep(&data, ":");
3024 pds->password = data;
3028 pds->peer = strsep(&data, ":");
3031 /* check for a key name wrapped in [] in the secret position, if found,
3032 move it to the key field instead
3034 if (pds->password && (pds->password[0] == '[')) {
3035 pds->key = ast_strip_quoted(pds->password, "[", "]");
3036 pds->password = NULL;
3040 static int iax2_call(struct ast_channel *c, char *dest, int timeout)
3042 struct sockaddr_in sin;
3043 char *l=NULL, *n=NULL, *tmpstr;
3044 struct iax_ie_data ied;
3045 char *defaultrdest = "s";
3046 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
3047 struct parsed_dial_string pds;
3048 struct create_addr_info cai;
3049 struct ast_var_t *var;
3050 struct ast_datastore *variablestore = ast_channel_datastore_find(c, &iax2_variable_datastore_info, NULL);
3051 const char* osp_token_ptr;
3052 unsigned int osp_token_length;
3053 unsigned char osp_block_index;
3054 unsigned int osp_block_length;
3055 unsigned char osp_buffer[256];
3057 if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
3058 ast_log(LOG_WARNING, "Channel is already in use (%s)?\n", c->name);
3062 memset(&cai, 0, sizeof(cai));
3063 cai.encmethods = iax2_encryption;
3065 memset(&pds, 0, sizeof(pds));
3066 tmpstr = ast_strdupa(dest);
3067 parse_dial_string(tmpstr, &pds);
3070 pds.exten = defaultrdest;
3072 if (create_addr(pds.peer, &sin, &cai)) {
3073 ast_log(LOG_WARNING, "No address associated with '%s'\n", pds.peer);
3077 if (!pds.username && !ast_strlen_zero(cai.username))
3078 pds.username = cai.username;
3079 if (!pds.password && !ast_strlen_zero(cai.secret))
3080 pds.password = cai.secret;
3081 if (!pds.key && !ast_strlen_zero(cai.outkey))
3082 pds.key = cai.outkey;
3083 if (!pds.context && !ast_strlen_zero(cai.peercontext))
3084 pds.context = cai.peercontext;
3086 /* Keep track of the context for outgoing calls too */
3087 ast_copy_string(c->context, cai.context, sizeof(c->context));
3090 sin.sin_port = htons(atoi(pds.port));
3093 n = c->cid.cid_name;
3095 /* Now build request */
3096 memset(&ied, 0, sizeof(ied));
3098 /* On new call, first IE MUST be IAX version of caller */
3099 iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
3100 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, pds.exten);
3101 if (pds.options && strchr(pds.options, 'a')) {
3102 /* Request auto answer */
3103 iax_ie_append(&ied, IAX_IE_AUTOANSWER);
3106 iax_ie_append_str(&ied, IAX_IE_CODEC_PREFS, cai.prefs);
3109 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
3110 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
3113 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
3115 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, AST_PRES_NUMBER_NOT_AVAILABLE);
3118 iax_ie_append_byte(&ied, IAX_IE_CALLINGTON, c->cid.cid_ton);
3119 iax_ie_append_short(&ied, IAX_IE_CALLINGTNS, c->cid.cid_tns);
3122 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n);
3123 if (ast_test_flag(iaxs[callno], IAX_SENDANI) && c->cid.cid_ani)
3124 iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, c->cid.cid_ani);
3126 if (!ast_strlen_zero(c->language))
3127 iax_ie_append_str(&ied, IAX_IE_LANGUAGE, c->language);
3128 if (!ast_strlen_zero(c->cid.cid_dnid))
3129 iax_ie_append_str(&ied, IAX_IE_DNID, c->cid.cid_dnid);
3130 if (!ast_strlen_zero(c->cid.cid_rdnis))
3131 iax_ie_append_str(&ied, IAX_IE_RDNIS, c->cid.cid_rdnis);
3134 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, pds.context);
3137 iax_ie_append_str(&ied, IAX_IE_USERNAME, pds.username);
3140 iax_ie_append_short(&ied, IAX_IE_ENCRYPTION, cai.encmethods);
3142 ast_mutex_lock(&iaxsl[callno]);
3144 if (!ast_strlen_zero(c->context))
3145 ast_string_field_set(iaxs[callno], context, c->context);
3148 ast_string_field_set(iaxs[callno], username, pds.username);
3150 iaxs[callno]->encmethods = cai.encmethods;
3152 iaxs[callno]->adsi = cai.adsi;
3154 ast_string_field_set(iaxs[callno], mohinterpret, cai.mohinterpret);
3155 ast_string_field_set(iaxs[callno], mohsuggest, cai.mohsuggest);
3158 ast_string_field_set(iaxs[callno], outkey, pds.key);
3160 ast_string_field_set(iaxs[callno], secret, pds.password);
3162 iax_ie_append_int(&ied, IAX_IE_FORMAT, c->nativeformats);
3163 iax_ie_append_int(&ied, IAX_IE_CAPABILITY, iaxs[callno]->capability);
3164 iax_ie_append_short(&ied, IAX_IE_ADSICPE, c->adsicpe);
3165 iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime(cai.timezone));
3167 if (iaxs[callno]->maxtime) {
3168 /* Initialize pingtime and auto-congest time */
3169 iaxs[callno]->pingtime = iaxs[callno]->maxtime / 2;
3170 iaxs[callno]->initid = ast_sched_add(sched, iaxs[callno]->maxtime * 2, auto_congest, CALLNO_TO_PTR(callno));
3171 } else if (autokill) {
3172 iaxs[callno]->pingtime = autokill / 2;
3173 iaxs[callno]->initid = ast_sched_add(sched, autokill * 2, auto_congest, CALLNO_TO_PTR(callno));
3176 /* Check if there is an OSP token set by IAXCHANINFO function */
3177 osp_token_ptr = iaxs[callno]->osptoken;
3178 if (!ast_strlen_zero(osp_token_ptr)) {
3179 if ((osp_token_length = strlen(osp_token_ptr)) <= IAX_MAX_OSPTOKEN_SIZE) {
3180 osp_block_index = 0;
3181 while (osp_token_length > 0) {
3182 osp_block_length = IAX_MAX_OSPBLOCK_SIZE < osp_token_length ? IAX_MAX_OSPBLOCK_SIZE : osp_token_length;
3183 osp_buffer[0] = osp_block_index;
3184 memcpy(osp_buffer + 1, osp_token_ptr, osp_block_length);
3185 iax_ie_append_raw(&ied, IAX_IE_OSPTOKEN, osp_buffer, osp_block_length + 1);
3187 osp_token_ptr += osp_block_length;
3188 osp_token_length -= osp_block_length;
3191 ast_log(LOG_WARNING, "OSP token is too long\n");
3192 } else if (iaxdebug)
3193 ast_debug(1, "OSP token is undefined\n");
3195 /* send the command using the appropriate socket for this peer */
3196 iaxs[callno]->sockfd = cai.sockfd;
3198 /* Add remote vars */