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
30 * \todo Implement musicclass settings for IAX2 devices
39 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
43 #include <sys/socket.h>
44 #include <netinet/in.h>
45 #include <arpa/inet.h>
46 #include <netinet/in_systm.h>
47 #include <netinet/ip.h>
49 #include <sys/signal.h>
57 #include "asterisk/paths.h" /* need ast_config_AST_DATA_DIR for firmware */
59 #include "asterisk/lock.h"
60 #include "asterisk/frame.h"
61 #include "asterisk/channel.h"
62 #include "asterisk/module.h"
63 #include "asterisk/pbx.h"
64 #include "asterisk/sched.h"
65 #include "asterisk/io.h"
66 #include "asterisk/config.h"
67 #include "asterisk/cli.h"
68 #include "asterisk/translate.h"
69 #include "asterisk/md5.h"
70 #include "asterisk/cdr.h"
71 #include "asterisk/crypto.h"
72 #include "asterisk/acl.h"
73 #include "asterisk/manager.h"
74 #include "asterisk/callerid.h"
75 #include "asterisk/app.h"
76 #include "asterisk/astdb.h"
77 #include "asterisk/musiconhold.h"
78 #include "asterisk/features.h"
79 #include "asterisk/utils.h"
80 #include "asterisk/causes.h"
81 #include "asterisk/localtime.h"
82 #include "asterisk/aes.h"
83 #include "asterisk/dnsmgr.h"
84 #include "asterisk/devicestate.h"
85 #include "asterisk/netsock.h"
86 #include "asterisk/stringfields.h"
87 #include "asterisk/linkedlists.h"
88 #include "asterisk/event.h"
89 #include "asterisk/astobj2.h"
90 #include "asterisk/timing.h"
91 #include "asterisk/taskprocessor.h"
94 #include "iax2-parser.h"
95 #include "iax2-provision.h"
96 #include "jitterbuf.h"
99 <application name="IAX2Provision" language="en_US">
101 Provision a calling IAXy with a given template.
104 <parameter name="template">
105 <para>If not specified, defaults to <literal>default</literal>.</para>
109 <para>Provisions the calling IAXy (assuming the calling entity is in fact an IAXy) with the
110 given <replaceable>template</replaceable>. Returns <literal>-1</literal> on error
111 or <literal>0</literal> on success.</para>
114 <function name="IAXPEER" language="en_US">
116 Gets IAX peer information.
119 <parameter name="peername" required="true">
121 <enum name="CURRENTCHANNEL">
122 <para>If <replaceable>peername</replaceable> is specified to this value, return the IP address of the
123 endpoint of the current channel</para>
127 <parameter name="item">
128 <para>If <replaceable>peername</replaceable> is specified, valid items are:</para>
131 <para>(default) The IP address.</para>
134 <para>The peer's status (if <literal>qualify=yes</literal>)</para>
136 <enum name="mailbox">
137 <para>The configured mailbox.</para>
139 <enum name="context">
140 <para>The configured context.</para>
143 <para>The epoch time of the next expire.</para>
145 <enum name="dynamic">
146 <para>Is it dynamic? (yes/no).</para>
148 <enum name="callerid_name">
149 <para>The configured Caller ID name.</para>
151 <enum name="callerid_num">
152 <para>The configured Caller ID number.</para>
155 <para>The configured codecs.</para>
157 <enum name="codec[x]">
158 <para>Preferred codec index number <replaceable>x</replaceable> (beginning
159 with <literal>0</literal>)</para>
166 <ref type="function">SIPPEER</ref>
169 <function name="IAXVAR" language="en_US">
171 Sets or retrieves a remote variable.
174 <parameter name="varname" required="true" />
178 <manager name="IAXpeers" language="en_US">
183 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
188 <manager name="IAXpeerlist" language="en_US">
193 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
196 <para>List all the IAX peers.</para>
199 <manager name="IAXnetstats" language="en_US">
205 <para>Show IAX channels network statistics.</para>
208 <manager name="IAXregistry" language="en_US">
210 Show IAX registrations.
213 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
216 <para>Show IAX registrations.</para>
221 /* Define SCHED_MULTITHREADED to run the scheduler in a special
222 multithreaded mode. */
223 #define SCHED_MULTITHREADED
225 /* Define DEBUG_SCHED_MULTITHREADED to keep track of where each
226 thread is actually doing. */
227 #define DEBUG_SCHED_MULTITHREAD
231 static int nochecksums = 0;
234 #define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
235 #define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
237 #define DEFAULT_THREAD_COUNT 10
238 #define DEFAULT_MAX_THREAD_COUNT 100
239 #define DEFAULT_RETRY_TIME 1000
240 #define MEMORY_SIZE 100
241 #define DEFAULT_DROP 3
243 #define DEBUG_SUPPORT
245 #define MIN_REUSE_TIME 60 /* Don't reuse a call number within 60 seconds */
247 /* Sample over last 100 units to determine historic jitter */
250 static struct ast_codec_pref prefs;
252 static const char tdesc[] = "Inter Asterisk eXchange Driver (Ver 2)";
255 /*! \brief Maximum transmission unit for the UDP packet in the trunk not to be
256 fragmented. This is based on 1516 - ethernet - ip - udp - iax minus one g711 frame = 1240 */
257 #define MAX_TRUNK_MTU 1240
259 static int global_max_trunk_mtu; /*!< Maximum MTU, 0 if not used */
260 static int trunk_timed, trunk_untimed, trunk_maxmtu, trunk_nmaxmtu ; /*!< Trunk MTU statistics */
262 #define DEFAULT_CONTEXT "default"
264 static char default_parkinglot[AST_MAX_CONTEXT];
266 static char language[MAX_LANGUAGE] = "";
267 static char regcontext[AST_MAX_CONTEXT] = "";
269 static int maxauthreq = 3;
270 static int max_retries = 4;
271 static int ping_time = 21;
272 static int lagrq_time = 10;
273 static int maxjitterbuffer=1000;
274 static int resyncthreshold=1000;
275 static int maxjitterinterps=10;
276 static int jittertargetextra = 40; /* number of milliseconds the new jitter buffer adds on to its size */
278 #define MAX_TRUNKDATA 640 * 200 /*!< 40ms, uncompressed linear * 200 channels */
280 static int trunkfreq = 20;
281 static int trunkmaxsize = MAX_TRUNKDATA;
283 static int authdebug = 1;
284 static int autokill = 0;
285 static int iaxcompat = 0;
286 static int last_authmethod = 0;
288 static int iaxdefaultdpcache=10 * 60; /* Cache dialplan entries for 10 minutes by default */
290 static int iaxdefaulttimeout = 5; /* Default to wait no more than 5 seconds for a reply to come back */
297 static int min_reg_expire;
298 static int max_reg_expire;
300 static int srvlookup = 0;
302 static struct ast_timer *timer; /* Timer for trunking */
304 static struct ast_netsock_list *netsock;
305 static struct ast_netsock_list *outsock; /*!< used if sourceaddress specified and bindaddr == INADDR_ANY */
306 static int defaultsockfd = -1;
308 static int (*iax2_regfunk)(const char *username, int onoff) = NULL;
311 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
313 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
314 ~AST_FORMAT_SLINEAR & \
315 ~AST_FORMAT_SLINEAR16 & \
316 ~AST_FORMAT_SIREN7 & \
317 ~AST_FORMAT_SIREN14 & \
322 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
324 ~AST_FORMAT_G726_AAL2 & \
327 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
331 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
332 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
333 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
335 /* if a pvt has encryption setup done and is running on the call */
336 #define IAX_CALLENCRYPTED(pvt) \
337 (ast_test_flag64(pvt, IAX_ENCRYPTED) && ast_test_flag64(pvt, IAX_KEYPOPULATED))
339 #define IAX_DEBUGDIGEST(msg, key) do { \
341 char digest[33] = ""; \
346 for (idx = 0; idx < 16; idx++) \
347 sprintf(digest + (idx << 1), "%2.2x", (unsigned char) key[idx]); \
349 ast_log(LOG_NOTICE, msg " IAX_COMMAND_RTKEY to rotate key to '%s'\n", digest); \
352 static struct io_context *io;
353 static struct ast_sched_thread *sched;
355 static format_t iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
357 static int iaxdebug = 0;
359 static int iaxtrunkdebug = 0;
361 static int test_losspct = 0;
363 static int test_late = 0;
364 static int test_resync = 0;
365 static int test_jit = 0;
366 static int test_jitpct = 0;
367 #endif /* IAXTESTS */
369 static char accountcode[AST_MAX_ACCOUNT_CODE];
370 static char mohinterpret[MAX_MUSICCLASS];
371 static char mohsuggest[MAX_MUSICCLASS];
372 static int amaflags = 0;
374 static int delayreject = 0;
375 static int iax2_encryption = 0;
377 static struct ast_flags64 globalflags = { 0 };
379 static pthread_t netthreadid = AST_PTHREADT_NULL;
382 IAX_STATE_STARTED = (1 << 0),
383 IAX_STATE_AUTHENTICATED = (1 << 1),
384 IAX_STATE_TBD = (1 << 2),
387 struct iax2_context {
388 char context[AST_MAX_CONTEXT];
389 struct iax2_context *next;
393 #define IAX_HASCALLERID (uint64_t)(1 << 0) /*!< CallerID has been specified */
394 #define IAX_DELME (uint64_t)(1 << 1) /*!< Needs to be deleted */
395 #define IAX_TEMPONLY (uint64_t)(1 << 2) /*!< Temporary (realtime) */
396 #define IAX_TRUNK (uint64_t)(1 << 3) /*!< Treat as a trunk */
397 #define IAX_NOTRANSFER (uint64_t)(1 << 4) /*!< Don't native bridge */
398 #define IAX_USEJITTERBUF (uint64_t)(1 << 5) /*!< Use jitter buffer */
399 #define IAX_DYNAMIC (uint64_t)(1 << 6) /*!< dynamic peer */
400 #define IAX_SENDANI (uint64_t)(1 << 7) /*!< Send ANI along with CallerID */
401 #define IAX_RTSAVE_SYSNAME (uint64_t)(1 << 8) /*!< Save Systname on Realtime Updates */
402 #define IAX_ALREADYGONE (uint64_t)(1 << 9) /*!< Already disconnected */
403 #define IAX_PROVISION (uint64_t)(1 << 10) /*!< This is a provisioning request */
404 #define IAX_QUELCH (uint64_t)(1 << 11) /*!< Whether or not we quelch audio */
405 #define IAX_ENCRYPTED (uint64_t)(1 << 12) /*!< Whether we should assume encrypted tx/rx */
406 #define IAX_KEYPOPULATED (uint64_t)(1 << 13) /*!< Whether we have a key populated */
407 #define IAX_CODEC_USER_FIRST (uint64_t)(1 << 14) /*!< are we willing to let the other guy choose the codec? */
408 #define IAX_CODEC_NOPREFS (uint64_t)(1 << 15) /*!< Force old behaviour by turning off prefs */
409 #define IAX_CODEC_NOCAP (uint64_t)(1 << 16) /*!< only consider requested format and ignore capabilities*/
410 #define IAX_RTCACHEFRIENDS (uint64_t)(1 << 17) /*!< let realtime stay till your reload */
411 #define IAX_RTUPDATE (uint64_t)(1 << 18) /*!< Send a realtime update */
412 #define IAX_RTAUTOCLEAR (uint64_t)(1 << 19) /*!< erase me on expire */
413 #define IAX_FORCEJITTERBUF (uint64_t)(1 << 20) /*!< Force jitterbuffer, even when bridged to a channel that can take jitter */
414 #define IAX_RTIGNOREREGEXPIRE (uint64_t)(1 << 21) /*!< When using realtime, ignore registration expiration */
415 #define IAX_TRUNKTIMESTAMPS (uint64_t)(1 << 22) /*!< Send trunk timestamps */
416 #define IAX_TRANSFERMEDIA (uint64_t)(1 << 23) /*!< When doing IAX2 transfers, transfer media only */
417 #define IAX_MAXAUTHREQ (uint64_t)(1 << 24) /*!< Maximum outstanding AUTHREQ restriction is in place */
418 #define IAX_DELAYPBXSTART (uint64_t)(1 << 25) /*!< Don't start a PBX on the channel until the peer sends us a response, so that we've achieved a three-way handshake with them before sending voice or anything else */
419 #define IAX_ALLOWFWDOWNLOAD (uint64_t)(1 << 26) /*!< Allow the FWDOWNL command? */
420 #define IAX_IMMEDIATE (uint64_t)(1 << 27) /*!< Allow immediate off-hook to extension s */
421 #define IAX_SENDCONNECTEDLINE (uint64_t)(1 << 28) /*!< Allow sending of connected line updates */
422 #define IAX_RECVCONNECTEDLINE (uint64_t)(1 << 29) /*!< Allow receiving of connected line updates */
423 #define IAX_FORCE_ENCRYPT (uint64_t)(1 << 30) /*!< Forces call encryption, if encryption not possible hangup */
424 #define IAX_SHRINKCALLERID (uint64_t)(1 << 31) /*!< Turn on and off caller id shrinking */
425 static int global_rtautoclear = 120;
427 static int reload_config(void);
430 * \brief Call token validation settings.
432 enum calltoken_peer_enum {
433 /*! \brief Default calltoken required unless the ip is in the ignorelist */
434 CALLTOKEN_DEFAULT = 0,
435 /*! \brief Require call token validation. */
437 /*! \brief Require call token validation after a successful registration
438 * using call token validation occurs. */
440 /*! \brief Do not require call token validation. */
445 AST_DECLARE_STRING_FIELDS(
446 AST_STRING_FIELD(name);
447 AST_STRING_FIELD(secret);
448 AST_STRING_FIELD(dbsecret);
449 AST_STRING_FIELD(accountcode);
450 AST_STRING_FIELD(mohinterpret);
451 AST_STRING_FIELD(mohsuggest);
452 AST_STRING_FIELD(inkeys); /*!< Key(s) this user can use to authenticate to us */
453 AST_STRING_FIELD(language);
454 AST_STRING_FIELD(cid_num);
455 AST_STRING_FIELD(cid_name);
456 AST_STRING_FIELD(parkinglot); /*!< Default parkinglot for device */
465 int maxauthreq; /*!< Maximum allowed outstanding AUTHREQs */
466 int curauthreq; /*!< Current number of outstanding AUTHREQs */
467 struct ast_codec_pref prefs;
469 struct iax2_context *contexts;
470 struct ast_variable *vars;
471 enum calltoken_peer_enum calltoken_required; /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
475 AST_DECLARE_STRING_FIELDS(
476 AST_STRING_FIELD(name);
477 AST_STRING_FIELD(username);
478 AST_STRING_FIELD(secret);
479 AST_STRING_FIELD(dbsecret);
480 AST_STRING_FIELD(outkey); /*!< What key we use to talk to this peer */
482 AST_STRING_FIELD(regexten); /*!< Extension to register (if regcontext is used) */
483 AST_STRING_FIELD(context); /*!< For transfers only */
484 AST_STRING_FIELD(peercontext); /*!< Context to pass to peer */
485 AST_STRING_FIELD(mailbox); /*!< Mailbox */
486 AST_STRING_FIELD(mohinterpret);
487 AST_STRING_FIELD(mohsuggest);
488 AST_STRING_FIELD(inkeys); /*!< Key(s) this peer can use to authenticate to us */
489 /* Suggested caller id if registering */
490 AST_STRING_FIELD(cid_num); /*!< Default context (for transfer really) */
491 AST_STRING_FIELD(cid_name); /*!< Default context (for transfer really) */
492 AST_STRING_FIELD(zonetag); /*!< Time Zone */
493 AST_STRING_FIELD(parkinglot); /*!< Default parkinglot for device */
495 struct ast_codec_pref prefs;
496 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
497 struct sockaddr_in addr;
499 int sockfd; /*!< Socket to use for transmission */
504 /* Dynamic Registration fields */
505 struct sockaddr_in defaddr; /*!< Default address if there is one */
506 int authmethods; /*!< Authentication methods (IAX_AUTH_*) */
507 int encmethods; /*!< Encryption methods (IAX_ENCRYPT_*) */
509 int expire; /*!< Schedule entry for expiry */
510 int expiry; /*!< How soon to expire */
511 format_t capability; /*!< Capability */
514 int callno; /*!< Call number of POKE request */
515 int pokeexpire; /*!< Scheduled qualification-related task (ie iax2_poke_peer_s or iax2_poke_noanswer) */
516 int lastms; /*!< How long last response took (in ms), or -1 for no response */
517 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
519 int pokefreqok; /*!< How often to check if the host is up */
520 int pokefreqnotok; /*!< How often to check when the host has been determined to be down */
521 int historicms; /*!< How long recent average responses took */
522 int smoothing; /*!< Sample over how many units to determine historic ms */
523 uint16_t maxcallno; /*!< Max call number limit for this peer. Set on registration */
525 struct ast_event_sub *mwi_event_sub;
528 enum calltoken_peer_enum calltoken_required; /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
531 #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
533 struct iax2_trunk_peer {
536 struct sockaddr_in addr;
537 struct timeval txtrunktime; /*!< Transmit trunktime */
538 struct timeval rxtrunktime; /*!< Receive trunktime */
539 struct timeval lasttxtime; /*!< Last transmitted trunktime */
540 struct timeval trunkact; /*!< Last trunk activity */
541 unsigned int lastsent; /*!< Last sent time */
542 /* Trunk data and length */
543 unsigned char *trunkdata;
544 unsigned int trunkdatalen;
545 unsigned int trunkdataalloc;
549 AST_LIST_ENTRY(iax2_trunk_peer) list;
552 static AST_LIST_HEAD_STATIC(tpeers, iax2_trunk_peer);
554 struct iax_firmware {
555 AST_LIST_ENTRY(iax_firmware) list;
559 struct ast_iax2_firmware_header *fwh;
564 REG_STATE_UNREGISTERED = 0,
567 REG_STATE_REGISTERED,
573 enum iax_transfer_state {
578 TRANSFER_PASSTHROUGH,
582 TRANSFER_MPASSTHROUGH,
587 struct iax2_registry {
588 struct sockaddr_in addr; /*!< Who we connect to for registration purposes */
590 char secret[80]; /*!< Password or key name in []'s */
591 int expire; /*!< Sched ID of expiration */
592 int refresh; /*!< How often to refresh */
593 enum iax_reg_state regstate;
594 int messages; /*!< Message count, low 8 bits = new, high 8 bits = old */
595 int callno; /*!< Associated call number if applicable */
596 struct sockaddr_in us; /*!< Who the server thinks we are */
597 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
598 AST_LIST_ENTRY(iax2_registry) entry;
601 static AST_LIST_HEAD_STATIC(registrations, iax2_registry);
603 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
604 #define MIN_RETRY_TIME 100
605 #define MAX_RETRY_TIME 10000
607 #define MAX_JITTER_BUFFER 50
608 #define MIN_JITTER_BUFFER 10
610 #define DEFAULT_TRUNKDATA 640 * 10 /*!< 40ms, uncompressed linear * 10 channels */
612 #define MAX_TIMESTAMP_SKEW 160 /*!< maximum difference between actual and predicted ts for sending */
614 /* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
615 #define TS_GAP_FOR_JB_RESYNC 5000
617 /* used for first_iax_message and last_iax_message. If this bit is set it was TX, else RX */
618 #define MARK_IAX_SUBCLASS_TX 0x8000
620 static int iaxthreadcount = DEFAULT_THREAD_COUNT;
621 static int iaxmaxthreadcount = DEFAULT_MAX_THREAD_COUNT;
622 static int iaxdynamicthreadcount = 0;
623 static int iaxdynamicthreadnum = 0;
624 static int iaxactivethreadcount = 0;
638 struct chan_iax2_pvt {
639 /*! Socket to send/receive on for this call */
641 /*! Last received voice format */
642 format_t voiceformat;
643 /*! Last received video format */
644 format_t videoformat;
645 /*! Last sent voice format */
646 format_t svoiceformat;
647 /*! Last sent video format */
648 format_t svideoformat;
649 /*! What we are capable of sending */
651 /*! Last received timestamp */
653 /*! Last sent timestamp - never send the same timestamp twice in a single call */
654 unsigned int lastsent;
655 /*! Timestamp of the last video frame sent */
656 unsigned int lastvsent;
657 /*! Next outgoing timestamp if everything is good */
658 unsigned int nextpred;
659 /*! iax frame subclass that began iax2_pvt entry. 0x8000 bit is set on TX */
660 int first_iax_message;
661 /*! Last iax frame subclass sent or received for a iax2_pvt. 0x8000 bit is set on TX */
662 int last_iax_message;
663 /*! True if the last voice we transmitted was not silence/CNG */
664 unsigned int notsilenttx:1;
666 unsigned int pingtime;
667 /*! Max time for initial response */
670 struct sockaddr_in addr;
671 /*! Actual used codec preferences */
672 struct ast_codec_pref prefs;
673 /*! Requested codec preferences */
674 struct ast_codec_pref rprefs;
675 /*! Our call number */
676 unsigned short callno;
677 /*! Our callno_entry entry */
678 struct callno_entry *callno_entry;
680 unsigned short peercallno;
681 /*! Negotiated format, this is only used to remember what format was
682 chosen for an unauthenticated call so that the channel can get
683 created later using the right format */
684 format_t chosenformat;
685 /*! Peer selected format */
687 /*! Peer capability */
688 format_t peercapability;
689 /*! timeval that we base our transmission on */
690 struct timeval offset;
691 /*! timeval that we base our delivery on */
692 struct timeval rxcore;
693 /*! The jitterbuffer */
695 /*! active jb read scheduler id */
699 /*! Error, as discovered by the manager */
701 /*! Owner if we have one */
702 struct ast_channel *owner;
703 /*! What's our state? */
704 struct ast_flags state;
705 /*! Expiry (optional) */
707 /*! Next outgoing sequence number */
708 unsigned char oseqno;
709 /*! Next sequence number they have not yet acknowledged */
710 unsigned char rseqno;
711 /*! Next incoming sequence number */
712 unsigned char iseqno;
713 /*! Last incoming sequence number we have acknowledged */
714 unsigned char aseqno;
716 AST_DECLARE_STRING_FIELDS(
718 AST_STRING_FIELD(peer);
719 /*! Default Context */
720 AST_STRING_FIELD(context);
721 /*! Caller ID if available */
722 AST_STRING_FIELD(cid_num);
723 AST_STRING_FIELD(cid_name);
724 /*! Hidden Caller ID (i.e. ANI) if appropriate */
725 AST_STRING_FIELD(ani);
727 AST_STRING_FIELD(dnid);
729 AST_STRING_FIELD(rdnis);
730 /*! Requested Extension */
731 AST_STRING_FIELD(exten);
732 /*! Expected Username */
733 AST_STRING_FIELD(username);
734 /*! Expected Secret */
735 AST_STRING_FIELD(secret);
737 AST_STRING_FIELD(challenge);
738 /*! Public keys permitted keys for incoming authentication */
739 AST_STRING_FIELD(inkeys);
740 /*! Private key for outgoing authentication */
741 AST_STRING_FIELD(outkey);
742 /*! Preferred language */
743 AST_STRING_FIELD(language);
744 /*! Hostname/peername for naming purposes */
745 AST_STRING_FIELD(host);
747 AST_STRING_FIELD(dproot);
748 AST_STRING_FIELD(accountcode);
749 AST_STRING_FIELD(mohinterpret);
750 AST_STRING_FIELD(mohsuggest);
751 /*! received OSP token */
752 AST_STRING_FIELD(osptoken);
753 /*! Default parkinglot */
754 AST_STRING_FIELD(parkinglot);
756 /*! AUTHREJ all AUTHREP frames */
758 /*! permitted authentication methods */
760 /*! permitted encryption methods */
762 /*! Encryption AES-128 Key */
763 ast_aes_encrypt_key ecx;
764 /*! Decryption AES-128 Key corresponding to ecx */
765 ast_aes_decrypt_key mydcx;
766 /*! Decryption AES-128 Key used to decrypt peer frames */
767 ast_aes_decrypt_key dcx;
768 /*! scheduler id associated with iax_key_rotate
769 * for encrypted calls*/
771 /*! 32 bytes of semi-random data */
772 unsigned char semirand[32];
773 /*! Associated registry */
774 struct iax2_registry *reg;
775 /*! Associated peer for poking */
776 struct iax2_peer *peerpoke;
781 /*! Transferring status */
782 enum iax_transfer_state transferring;
783 /*! Transfer identifier */
785 /*! Who we are IAX transferring to */
786 struct sockaddr_in transfer;
787 /*! What's the new call number for the transfer */
788 unsigned short transfercallno;
789 /*! Transfer encrypt AES-128 Key */
790 ast_aes_encrypt_key tdcx;
792 /*! Status of knowledge of peer ADSI capability */
795 /*! Who we are bridged to */
796 unsigned short bridgecallno;
798 int pingid; /*!< Transmit PING request */
799 int lagid; /*!< Retransmit lag request */
800 int autoid; /*!< Auto hangup for Dialplan requestor */
801 int authid; /*!< Authentication rejection ID */
802 int authfail; /*!< Reason to report failure */
803 int initid; /*!< Initial peer auto-congest ID (based on qualified peers) */
808 AST_LIST_HEAD_NOLOCK(, iax2_dpcache) dpentries;
809 /*! variables inherited from the user definition */
810 struct ast_variable *vars;
811 /*! variables transmitted in a NEW packet */
812 struct ast_variable *iaxvars;
813 /*! last received remote rr */
814 struct iax_rr remote_rr;
815 /*! Current base time: (just for stats) */
817 /*! Dropped frame count: (just for stats) */
819 /*! received frame count: (just for stats) */
821 /*! num bytes used for calltoken ie, even an empty ie should contain 2 */
822 unsigned char calltoken_ie_len;
823 /*! hold all signaling frames from the pbx thread until we have a destination callno */
825 /*! frame queue for signaling frames from pbx thread waiting for destination callno */
826 AST_LIST_HEAD_NOLOCK(signaling_queue, signaling_queue_entry) signaling_queue;
829 struct signaling_queue_entry {
831 AST_LIST_ENTRY(signaling_queue_entry) next;
834 /*! table of available call numbers */
835 static struct ao2_container *callno_pool;
837 /*! table of available trunk call numbers */
838 static struct ao2_container *callno_pool_trunk;
840 static const unsigned int CALLNO_POOL_BUCKETS = 2699;
843 * \brief a list of frames that may need to be retransmitted
845 * \note The contents of this list do not need to be explicitly destroyed
846 * on module unload. This is because all active calls are destroyed, and
847 * all frames in this queue will get destroyed as a part of that process.
849 * \note Contents protected by the iaxsl[] locks
851 static AST_LIST_HEAD_NOLOCK(, iax_frame) frame_queue[IAX_MAX_CALLS];
853 static struct ast_taskprocessor *transmit_processor;
855 static int randomcalltokendata;
857 static const time_t MAX_CALLTOKEN_DELAY = 10;
860 * This module will get much higher performance when doing a lot of
861 * user and peer lookups if the number of buckets is increased from 1.
862 * However, to maintain old behavior for Asterisk 1.4, these are set to
863 * 1 by default. When using multiple buckets, search order through these
864 * containers is considered random, so you will not be able to depend on
865 * the order the entires are specified in iax.conf for matching order. */
867 #define MAX_PEER_BUCKETS 17
869 #define MAX_PEER_BUCKETS 563
871 static struct ao2_container *peers;
873 #define MAX_USER_BUCKETS MAX_PEER_BUCKETS
874 static struct ao2_container *users;
876 /*! Table containing peercnt objects for every ip address consuming a callno */
877 static struct ao2_container *peercnts;
879 /*! Table containing custom callno limit rules for a range of ip addresses. */
880 static struct ao2_container *callno_limits;
882 /*! Table containing ip addresses not requiring calltoken validation */
883 static struct ao2_container *calltoken_ignores;
885 static uint16_t DEFAULT_MAXCALLNO_LIMIT = 2048;
887 static uint16_t DEFAULT_MAXCALLNO_LIMIT_NONVAL = 8192;
889 static uint16_t global_maxcallno;
891 /*! Total num of call numbers allowed to be allocated without calltoken validation */
892 static uint16_t global_maxcallno_nonval;
894 static uint16_t total_nonval_callno_used = 0;
896 /*! peer connection private, keeps track of all the call numbers
897 * consumed by a single ip address */
899 /*! ip address consuming call numbers */
901 /*! Number of call numbers currently used by this ip address */
903 /*! Max call numbers allowed for this ip address */
905 /*! Specifies whether limit is set by a registration or not, if so normal
906 * limit setting rules do not apply to this address. */
910 /*! used by both callno_limits and calltoken_ignores containers */
912 /*! ip address range for custom callno limit rule */
914 /*! callno limit for this ip address range, only used in callno_limits container */
916 /*! delete me marker for reloads */
920 struct callno_entry {
921 /*! callno used for this entry */
923 /*! was this callno calltoken validated or not */
924 unsigned char validated;
927 static AST_LIST_HEAD_STATIC(firmwares, iax_firmware);
930 /*! Extension exists */
931 CACHE_FLAG_EXISTS = (1 << 0),
932 /*! Extension is nonexistent */
933 CACHE_FLAG_NONEXISTENT = (1 << 1),
934 /*! Extension can exist */
935 CACHE_FLAG_CANEXIST = (1 << 2),
936 /*! Waiting to hear back response */
937 CACHE_FLAG_PENDING = (1 << 3),
939 CACHE_FLAG_TIMEOUT = (1 << 4),
940 /*! Request transmitted */
941 CACHE_FLAG_TRANSMITTED = (1 << 5),
943 CACHE_FLAG_UNKNOWN = (1 << 6),
945 CACHE_FLAG_MATCHMORE = (1 << 7),
948 struct iax2_dpcache {
949 char peercontext[AST_MAX_CONTEXT];
950 char exten[AST_MAX_EXTENSION];
952 struct timeval expiry;
954 unsigned short callno;
956 AST_LIST_ENTRY(iax2_dpcache) cache_list;
957 AST_LIST_ENTRY(iax2_dpcache) peer_list;
960 static AST_LIST_HEAD_STATIC(dpcache, iax2_dpcache);
962 static void reg_source_db(struct iax2_peer *p);
963 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
964 static struct iax2_user *realtime_user(const char *username, struct sockaddr_in *sin);
966 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt);
967 static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags);
968 static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state);
970 enum iax2_thread_iostate {
973 IAX_IOSTATE_PROCESSING,
974 IAX_IOSTATE_SCHEDREADY,
977 enum iax2_thread_type {
978 IAX_THREAD_TYPE_POOL,
979 IAX_THREAD_TYPE_DYNAMIC,
982 struct iax2_pkt_buf {
983 AST_LIST_ENTRY(iax2_pkt_buf) entry;
985 unsigned char buf[1];
989 AST_LIST_ENTRY(iax2_thread) list;
990 enum iax2_thread_type type;
991 enum iax2_thread_iostate iostate;
992 #ifdef SCHED_MULTITHREADED
993 void (*schedfunc)(const void *);
994 const void *scheddata;
996 #ifdef DEBUG_SCHED_MULTITHREAD
1002 struct sockaddr_in iosin;
1003 unsigned char readbuf[4096];
1011 ast_mutex_t init_lock;
1012 ast_cond_t init_cond;
1013 /*! if this thread is processing a full frame,
1014 some information about that frame will be stored
1015 here, so we can avoid dispatching any more full
1016 frames for that callno to other threads */
1018 unsigned short callno;
1019 struct sockaddr_in sin;
1023 /*! Queued up full frames for processing. If more full frames arrive for
1024 * a call which this thread is already processing a full frame for, they
1025 * are queued up here. */
1026 AST_LIST_HEAD_NOLOCK(, iax2_pkt_buf) full_frames;
1030 static AST_LIST_HEAD_STATIC(idle_list, iax2_thread);
1031 static AST_LIST_HEAD_STATIC(active_list, iax2_thread);
1032 static AST_LIST_HEAD_STATIC(dynamic_list, iax2_thread);
1034 static void *iax2_process_thread(void *data);
1035 static void iax2_destroy(int callno);
1037 static void signal_condition(ast_mutex_t *lock, ast_cond_t *cond)
1039 ast_mutex_lock(lock);
1040 ast_cond_signal(cond);
1041 ast_mutex_unlock(lock);
1045 * \brief an array of iax2 pvt structures
1047 * The container for active chan_iax2_pvt structures is implemented as an
1048 * array for extremely quick direct access to the correct pvt structure
1049 * based on the local call number. The local call number is used as the
1050 * index into the array where the associated pvt structure is stored.
1052 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS];
1055 * \brief Another container of iax2_pvt structures
1057 * Active IAX2 pvt structs are also stored in this container, if they are a part
1058 * of an active call where we know the remote side's call number. The reason
1059 * for this is that incoming media frames do not contain our call number. So,
1060 * instead of having to iterate the entire iaxs array, we use this container to
1061 * look up calls where the remote side is using a given call number.
1063 static struct ao2_container *iax_peercallno_pvts;
1066 * \brief chan_iax2_pvt structure locks
1068 * These locks are used when accessing a pvt structure in the iaxs array.
1069 * The index used here is the same as used in the iaxs array. It is the
1070 * local call number for the associated pvt struct.
1072 static ast_mutex_t iaxsl[ARRAY_LEN(iaxs)];
1075 * * \brief Another container of iax2_pvt structures
1077 * Active IAX2 pvt stucts used during transfering a call are stored here.
1079 static struct ao2_container *iax_transfercallno_pvts;
1081 /* Flag to use with trunk calls, keeping these calls high up. It halves our effective use
1082 but keeps the division between trunked and non-trunked better. */
1083 #define TRUNK_CALL_START ARRAY_LEN(iaxs) / 2
1085 /* Debug routines... */
1086 static struct sockaddr_in debugaddr;
1088 static void iax_outputframe(struct iax_frame *f, struct ast_iax2_full_hdr *fhi, int rx, struct sockaddr_in *sin, int datalen)
1091 (sin && debugaddr.sin_addr.s_addr &&
1092 (!ntohs(debugaddr.sin_port) ||
1093 debugaddr.sin_port == sin->sin_port) &&
1094 debugaddr.sin_addr.s_addr == sin->sin_addr.s_addr)) {
1096 iax_showframe(f, fhi, rx, sin, datalen);
1099 iax_showframe(f, fhi, rx, sin, datalen);
1105 static void iax_debug_output(const char *data)
1108 ast_verbose("%s", data);
1111 static void iax_error_output(const char *data)
1113 ast_log(LOG_WARNING, "%s", data);
1116 static void __attribute__((format(printf, 1, 2))) jb_error_output(const char *fmt, ...)
1121 va_start(args, fmt);
1122 vsnprintf(buf, sizeof(buf), fmt, args);
1125 ast_log(LOG_ERROR, "%s", buf);
1128 static void __attribute__((format(printf, 1, 2))) jb_warning_output(const char *fmt, ...)
1133 va_start(args, fmt);
1134 vsnprintf(buf, sizeof(buf), fmt, args);
1137 ast_log(LOG_WARNING, "%s", buf);
1140 static void __attribute__((format(printf, 1, 2))) jb_debug_output(const char *fmt, ...)
1145 va_start(args, fmt);
1146 vsnprintf(buf, sizeof(buf), fmt, args);
1149 ast_verbose("%s", buf);
1152 static int maxtrunkcall = TRUNK_CALL_START;
1153 static int maxnontrunkcall = 1;
1155 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);
1156 static int expire_registry(const void *data);
1157 static int iax2_answer(struct ast_channel *c);
1158 static int iax2_call(struct ast_channel *c, char *dest, int timeout);
1159 static int iax2_devicestate(void *data);
1160 static int iax2_digit_begin(struct ast_channel *c, char digit);
1161 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration);
1162 static int iax2_do_register(struct iax2_registry *reg);
1163 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
1164 static int iax2_hangup(struct ast_channel *c);
1165 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen);
1166 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
1167 static int iax2_provision(struct sockaddr_in *end, int sockfd, const char *dest, const char *template, int force);
1168 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
1169 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
1170 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
1171 static int iax2_sendtext(struct ast_channel *c, const char *text);
1172 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
1173 static int iax2_transfer(struct ast_channel *c, const char *dest);
1174 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
1175 static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now);
1176 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1177 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1178 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1179 static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int);
1180 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
1181 static struct ast_channel *iax2_request(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause);
1182 static struct ast_frame *iax2_read(struct ast_channel *c);
1183 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
1184 static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
1185 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, time_t regtime);
1186 static void *iax2_dup_variable_datastore(void *);
1187 static void prune_peers(void);
1188 static void prune_users(void);
1189 static void iax2_free_variable_datastore(void *);
1191 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
1192 static int acf_channel_write(struct ast_channel *chan, const char *function, char *data, const char *value);
1193 static int decode_frame(ast_aes_decrypt_key *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen);
1194 static int encrypt_frame(ast_aes_encrypt_key *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen);
1195 static void build_ecx_key(const unsigned char *digest, struct chan_iax2_pvt *pvt);
1196 static void build_rand_pad(unsigned char *buf, ssize_t len);
1197 static struct callno_entry *get_unused_callno(int trunk, int validated);
1198 static int replace_callno(const void *obj);
1199 static void sched_delay_remove(struct sockaddr_in *sin, struct callno_entry *callno_entry);
1201 static const struct ast_channel_tech iax2_tech = {
1203 .description = tdesc,
1204 .capabilities = IAX_CAPABILITY_FULLBANDWIDTH,
1205 .properties = AST_CHAN_TP_WANTSJITTER,
1206 .requester = iax2_request,
1207 .devicestate = iax2_devicestate,
1208 .send_digit_begin = iax2_digit_begin,
1209 .send_digit_end = iax2_digit_end,
1210 .send_text = iax2_sendtext,
1211 .send_image = iax2_sendimage,
1212 .send_html = iax2_sendhtml,
1214 .hangup = iax2_hangup,
1215 .answer = iax2_answer,
1217 .write = iax2_write,
1218 .write_video = iax2_write,
1219 .indicate = iax2_indicate,
1220 .setoption = iax2_setoption,
1221 .bridge = iax2_bridge,
1222 .transfer = iax2_transfer,
1223 .fixup = iax2_fixup,
1224 .func_channel_read = acf_channel_read,
1225 .func_channel_write = acf_channel_write,
1228 static void mwi_event_cb(const struct ast_event *event, void *userdata)
1230 /* The MWI subscriptions exist just so the core knows we care about those
1231 * mailboxes. However, we just grab the events out of the cache when it
1232 * is time to send MWI, since it is only sent with a REGACK. */
1235 /*! \brief Send manager event at call setup to link between Asterisk channel name
1236 and IAX2 call identifiers */
1237 static void iax2_ami_channelupdate(struct chan_iax2_pvt *pvt)
1239 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
1240 "Channel: %s\r\nChanneltype: IAX2\r\nIAX2-callno-local: %d\r\nIAX2-callno-remote: %d\r\nIAX2-peer: %s\r\n",
1241 pvt->owner ? pvt->owner->name : "",
1242 pvt->callno, pvt->peercallno, pvt->peer ? pvt->peer : "");
1246 static struct ast_datastore_info iax2_variable_datastore_info = {
1247 .type = "IAX2_VARIABLE",
1248 .duplicate = iax2_dup_variable_datastore,
1249 .destroy = iax2_free_variable_datastore,
1252 static void *iax2_dup_variable_datastore(void *old)
1254 AST_LIST_HEAD(, ast_var_t) *oldlist = old, *newlist;
1255 struct ast_var_t *oldvar, *newvar;
1257 newlist = ast_calloc(sizeof(*newlist), 1);
1259 ast_log(LOG_ERROR, "Unable to duplicate iax2 variables\n");
1263 AST_LIST_HEAD_INIT(newlist);
1264 AST_LIST_LOCK(oldlist);
1265 AST_LIST_TRAVERSE(oldlist, oldvar, entries) {
1266 newvar = ast_var_assign(ast_var_name(oldvar), ast_var_value(oldvar));
1268 AST_LIST_INSERT_TAIL(newlist, newvar, entries);
1270 ast_log(LOG_ERROR, "Unable to duplicate iax2 variable '%s'\n", ast_var_name(oldvar));
1272 AST_LIST_UNLOCK(oldlist);
1276 static void iax2_free_variable_datastore(void *old)
1278 AST_LIST_HEAD(, ast_var_t) *oldlist = old;
1279 struct ast_var_t *oldvar;
1281 AST_LIST_LOCK(oldlist);
1282 while ((oldvar = AST_LIST_REMOVE_HEAD(oldlist, entries))) {
1285 AST_LIST_UNLOCK(oldlist);
1286 AST_LIST_HEAD_DESTROY(oldlist);
1291 /* WARNING: insert_idle_thread should only ever be called within the
1292 * context of an iax2_process_thread() thread.
1294 static void insert_idle_thread(struct iax2_thread *thread)
1296 if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
1297 AST_LIST_LOCK(&dynamic_list);
1298 AST_LIST_INSERT_TAIL(&dynamic_list, thread, list);
1299 AST_LIST_UNLOCK(&dynamic_list);
1301 AST_LIST_LOCK(&idle_list);
1302 AST_LIST_INSERT_TAIL(&idle_list, thread, list);
1303 AST_LIST_UNLOCK(&idle_list);
1309 static struct iax2_thread *find_idle_thread(void)
1311 struct iax2_thread *thread = NULL;
1313 /* Pop the head of the idle list off */
1314 AST_LIST_LOCK(&idle_list);
1315 thread = AST_LIST_REMOVE_HEAD(&idle_list, list);
1316 AST_LIST_UNLOCK(&idle_list);
1318 /* If we popped a thread off the idle list, just return it */
1320 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1324 /* Pop the head of the dynamic list off */
1325 AST_LIST_LOCK(&dynamic_list);
1326 thread = AST_LIST_REMOVE_HEAD(&dynamic_list, list);
1327 AST_LIST_UNLOCK(&dynamic_list);
1329 /* If we popped a thread off the dynamic list, just return it */
1331 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1335 /* If we can't create a new dynamic thread for any reason, return no thread at all */
1336 if (iaxdynamicthreadcount >= iaxmaxthreadcount || !(thread = ast_calloc(1, sizeof(*thread))))
1339 /* Set default values */
1340 ast_atomic_fetchadd_int(&iaxdynamicthreadcount, 1);
1341 thread->threadnum = ast_atomic_fetchadd_int(&iaxdynamicthreadnum, 1);
1342 thread->type = IAX_THREAD_TYPE_DYNAMIC;
1344 /* Initialize lock and condition */
1345 ast_mutex_init(&thread->lock);
1346 ast_cond_init(&thread->cond, NULL);
1347 ast_mutex_init(&thread->init_lock);
1348 ast_cond_init(&thread->init_cond, NULL);
1349 ast_mutex_lock(&thread->init_lock);
1351 /* Create thread and send it on it's way */
1352 if (ast_pthread_create_detached_background(&thread->threadid, NULL, iax2_process_thread, thread)) {
1353 ast_cond_destroy(&thread->cond);
1354 ast_mutex_destroy(&thread->lock);
1359 /* this thread is not processing a full frame (since it is idle),
1360 so ensure that the field for the full frame call number is empty */
1361 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1363 /* Wait for the thread to be ready before returning it to the caller */
1364 ast_cond_wait(&thread->init_cond, &thread->init_lock);
1366 /* Done with init_lock */
1367 ast_mutex_unlock(&thread->init_lock);
1372 #ifdef SCHED_MULTITHREADED
1373 static int __schedule_action(void (*func)(const void *data), const void *data, const char *funcname)
1375 struct iax2_thread *thread = NULL;
1376 static time_t lasterror;
1379 thread = find_idle_thread();
1381 if (thread != NULL) {
1382 thread->schedfunc = func;
1383 thread->scheddata = data;
1384 thread->iostate = IAX_IOSTATE_SCHEDREADY;
1385 #ifdef DEBUG_SCHED_MULTITHREAD
1386 ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc));
1388 signal_condition(&thread->lock, &thread->cond);
1393 ast_debug(1, "Out of idle IAX2 threads for scheduling!\n");
1398 #define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
1401 static int iax2_sched_replace(int id, struct ast_sched_thread *st, int when,
1402 ast_sched_cb callback, const void *data)
1404 ast_sched_thread_del(st, id);
1406 return ast_sched_thread_add(st, when, callback, data);
1409 static int iax2_sched_add(struct ast_sched_thread *st, int when,
1410 ast_sched_cb callback, const void *data)
1412 return ast_sched_thread_add(st, when, callback, data);
1415 static int send_ping(const void *data);
1417 static void __send_ping(const void *data)
1419 int callno = (long) data;
1421 ast_mutex_lock(&iaxsl[callno]);
1424 if (iaxs[callno]->peercallno) {
1425 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
1426 iaxs[callno]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, data);
1428 /* I am the schedule, so I'm allowed to do this */
1429 iaxs[callno]->pingid = -1;
1432 ast_debug(1, "I was supposed to send a PING with callno %d, but no such call exists.\n", callno);
1435 ast_mutex_unlock(&iaxsl[callno]);
1438 static int send_ping(const void *data)
1440 #ifdef SCHED_MULTITHREADED
1441 if (schedule_action(__send_ping, data))
1448 static void encmethods_to_str(int e, struct ast_str *buf)
1450 ast_str_set(&buf, 0, "(");
1451 if (e & IAX_ENCRYPT_AES128) {
1452 ast_str_append(&buf, 0, "aes128");
1454 if (e & IAX_ENCRYPT_KEYROTATE) {
1455 ast_str_append(&buf, 0, ",keyrotate");
1457 if (ast_str_strlen(buf) > 1) {
1458 ast_str_append(&buf, 0, ")");
1460 ast_str_set(&buf, 0, "No");
1464 static int get_encrypt_methods(const char *s)
1467 if (!strcasecmp(s, "aes128"))
1468 e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
1469 else if (ast_true(s))
1470 e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
1476 static int send_lagrq(const void *data);
1478 static void __send_lagrq(const void *data)
1480 int callno = (long) data;
1482 ast_mutex_lock(&iaxsl[callno]);
1485 if (iaxs[callno]->peercallno) {
1486 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
1487 iaxs[callno]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, data);
1489 /* I am the schedule, so I'm allowed to do this */
1490 iaxs[callno]->lagid = -1;
1493 ast_debug(1, "I was supposed to send a LAGRQ with callno %d, but no such call exists.\n", callno);
1496 ast_mutex_unlock(&iaxsl[callno]);
1499 static int send_lagrq(const void *data)
1501 #ifdef SCHED_MULTITHREADED
1502 if (schedule_action(__send_lagrq, data))
1509 static unsigned char compress_subclass(format_t subclass)
1513 /* If it's 64 or smaller, just return it */
1514 if (subclass < IAX_FLAG_SC_LOG)
1516 /* Otherwise find its power */
1517 for (x = 0; x < IAX_MAX_SHIFT; x++) {
1518 if (subclass & (1LL << x)) {
1520 ast_log(LOG_WARNING, "Can't compress subclass %Ld\n", (long long) subclass);
1526 return power | IAX_FLAG_SC_LOG;
1529 static format_t uncompress_subclass(unsigned char csub)
1531 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
1532 if (csub & IAX_FLAG_SC_LOG) {
1533 /* special case for 'compressed' -1 */
1537 return 1LL << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
1544 * \note The only member of the peer passed here guaranteed to be set is the name field
1546 static int peer_hash_cb(const void *obj, const int flags)
1548 const struct iax2_peer *peer = obj;
1550 return ast_str_hash(peer->name);
1554 * \note The only member of the peer passed here guaranteed to be set is the name field
1556 static int peer_cmp_cb(void *obj, void *arg, int flags)
1558 struct iax2_peer *peer = obj, *peer2 = arg;
1560 return !strcmp(peer->name, peer2->name) ? CMP_MATCH | CMP_STOP : 0;
1564 * \note The only member of the user passed here guaranteed to be set is the name field
1566 static int user_hash_cb(const void *obj, const int flags)
1568 const struct iax2_user *user = obj;
1570 return ast_str_hash(user->name);
1574 * \note The only member of the user passed here guaranteed to be set is the name field
1576 static int user_cmp_cb(void *obj, void *arg, int flags)
1578 struct iax2_user *user = obj, *user2 = arg;
1580 return !strcmp(user->name, user2->name) ? CMP_MATCH | CMP_STOP : 0;
1584 * \note This funtion calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
1585 * so do not call it with a pvt lock held.
1587 static struct iax2_peer *find_peer(const char *name, int realtime)
1589 struct iax2_peer *peer = NULL;
1590 struct iax2_peer tmp_peer = {
1594 peer = ao2_find(peers, &tmp_peer, OBJ_POINTER);
1596 /* Now go for realtime if applicable */
1597 if(!peer && realtime)
1598 peer = realtime_peer(name, NULL);
1603 static struct iax2_peer *peer_ref(struct iax2_peer *peer)
1609 static inline struct iax2_peer *peer_unref(struct iax2_peer *peer)
1615 static struct iax2_user *find_user(const char *name)
1617 struct iax2_user tmp_user = {
1621 return ao2_find(users, &tmp_user, OBJ_POINTER);
1623 static inline struct iax2_user *user_ref(struct iax2_user *user)
1629 static inline struct iax2_user *user_unref(struct iax2_user *user)
1635 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len)
1637 struct iax2_peer *peer = NULL;
1639 struct ao2_iterator i;
1641 i = ao2_iterator_init(peers, 0);
1642 while ((peer = ao2_iterator_next(&i))) {
1643 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
1644 (peer->addr.sin_port == sin.sin_port)) {
1645 ast_copy_string(host, peer->name, len);
1652 ao2_iterator_destroy(&i);
1655 peer = realtime_peer(NULL, &sin);
1657 ast_copy_string(host, peer->name, len);
1666 /*!\note Assumes the lock on the pvt is already held, when
1667 * iax2_destroy_helper() is called. */
1668 static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
1670 /* Decrement AUTHREQ count if needed */
1671 if (ast_test_flag64(pvt, IAX_MAXAUTHREQ)) {
1672 struct iax2_user *user;
1673 struct iax2_user tmp_user = {
1674 .name = pvt->username,
1677 user = ao2_find(users, &tmp_user, OBJ_POINTER);
1679 ast_atomic_fetchadd_int(&user->curauthreq, -1);
1683 ast_clear_flag64(pvt, IAX_MAXAUTHREQ);
1685 /* No more pings or lagrq's */
1686 AST_SCHED_DEL_SPINLOCK(ast_sched_thread_get_context(sched), pvt->pingid, &iaxsl[pvt->callno]);
1687 AST_SCHED_DEL_SPINLOCK(ast_sched_thread_get_context(sched), pvt->lagid, &iaxsl[pvt->callno]);
1688 ast_sched_thread_del(sched, pvt->autoid);
1689 ast_sched_thread_del(sched, pvt->authid);
1690 ast_sched_thread_del(sched, pvt->initid);
1691 ast_sched_thread_del(sched, pvt->jbid);
1692 ast_sched_thread_del(sched, pvt->keyrotateid);
1695 static void iax2_frame_free(struct iax_frame *fr)
1697 ast_sched_thread_del(sched, fr->retrans);
1701 static int scheduled_destroy(const void *vid)
1703 short callno = PTR_TO_CALLNO(vid);
1704 ast_mutex_lock(&iaxsl[callno]);
1707 ast_log(LOG_DEBUG, "Really destroying %d now...\n", callno);
1709 iax2_destroy(callno);
1711 ast_mutex_unlock(&iaxsl[callno]);
1715 static void free_signaling_queue_entry(struct signaling_queue_entry *s)
1717 ast_free(s->f.data.ptr);
1721 /*! \brief This function must be called once we are sure the other side has
1722 * given us a call number. All signaling is held here until that point. */
1723 static void send_signaling(struct chan_iax2_pvt *pvt)
1725 struct signaling_queue_entry *s = NULL;
1727 while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
1728 iax2_send(pvt, &s->f, 0, -1, 0, 0, 0);
1729 free_signaling_queue_entry(s);
1731 pvt->hold_signaling = 0;
1734 /*! \brief All frames other than that of type AST_FRAME_IAX must be held until
1735 * we have received a destination call number. */
1736 static int queue_signalling(struct chan_iax2_pvt *pvt, struct ast_frame *f)
1738 struct signaling_queue_entry *new;
1740 if (f->frametype == AST_FRAME_IAX || !pvt->hold_signaling) {
1741 return 1; /* do not queue this frame */
1742 } else if (!(new = ast_calloc(1, sizeof(struct signaling_queue_entry)))) {
1743 return -1; /* out of memory */
1746 memcpy(&new->f, f, sizeof(new->f)); /* copy ast_frame into our queue entry */
1748 if (new->f.datalen) { /* if there is data in this frame copy it over as well */
1749 if (!(new->f.data.ptr = ast_calloc(1, new->f.datalen))) {
1750 free_signaling_queue_entry(new);
1753 memcpy(new->f.data.ptr, f->data.ptr, sizeof(*new->f.data.ptr));
1755 AST_LIST_INSERT_TAIL(&pvt->signaling_queue, new, next);
1760 static void pvt_destructor(void *obj)
1762 struct chan_iax2_pvt *pvt = obj;
1763 struct iax_frame *cur = NULL;
1764 struct signaling_queue_entry *s = NULL;
1766 ast_mutex_lock(&iaxsl[pvt->callno]);
1768 iax2_destroy_helper(pvt);
1770 sched_delay_remove(&pvt->addr, pvt->callno_entry);
1771 pvt->callno_entry = NULL;
1774 ast_set_flag64(pvt, IAX_ALREADYGONE);
1776 AST_LIST_TRAVERSE(&frame_queue[pvt->callno], cur, list) {
1777 /* Cancel any pending transmissions */
1781 ast_mutex_unlock(&iaxsl[pvt->callno]);
1783 while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
1784 free_signaling_queue_entry(s);
1788 pvt->reg->callno = 0;
1794 ast_variables_destroy(pvt->vars);
1798 while (jb_getall(pvt->jb, &frame) == JB_OK) {
1799 iax2_frame_free(frame.data);
1802 jb_destroy(pvt->jb);
1803 ast_string_field_free_memory(pvt);
1807 static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, const char *host)
1809 struct chan_iax2_pvt *tmp;
1812 if (!(tmp = ao2_alloc(sizeof(*tmp), pvt_destructor))) {
1816 if (ast_string_field_init(tmp, 32)) {
1828 tmp->keyrotateid = -1;
1830 ast_string_field_set(tmp,exten, "s");
1831 ast_string_field_set(tmp,host, host);
1835 jbconf.max_jitterbuf = maxjitterbuffer;
1836 jbconf.resync_threshold = resyncthreshold;
1837 jbconf.max_contig_interp = maxjitterinterps;
1838 jbconf.target_extra = jittertargetextra;
1839 jb_setconf(tmp->jb,&jbconf);
1841 AST_LIST_HEAD_INIT_NOLOCK(&tmp->dpentries);
1843 tmp->hold_signaling = 1;
1844 AST_LIST_HEAD_INIT_NOLOCK(&tmp->signaling_queue);
1849 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
1851 struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen, fr->cacheable);
1853 size_t afdatalen = new->afdatalen;
1854 memcpy(new, fr, sizeof(*new));
1855 iax_frame_wrap(new, &fr->af);
1856 new->afdatalen = afdatalen;
1859 new->direction = DIRECTION_INGRESS;
1864 /* keep these defined in this order. They are used in find_callno to
1865 * determine whether or not a new call number should be allowed. */
1867 /* do not allow a new call number, only search ones in use for match */
1869 /* search for match first, then allow a new one to be allocated */
1871 /* do not search for match, force a new call number */
1873 /* do not search for match, force a new call number. Signifies call number
1874 * has been calltoken validated */
1875 NEW_ALLOW_CALLTOKEN_VALIDATED = 3,
1878 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, const struct chan_iax2_pvt *cur, int check_dcallno)
1880 if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
1881 (cur->addr.sin_port == sin->sin_port)) {
1882 /* This is the main host */
1883 if ( (cur->peercallno == 0 || cur->peercallno == callno) &&
1884 (check_dcallno ? dcallno == cur->callno : 1) ) {
1885 /* That's us. Be sure we keep track of the peer call number */
1889 if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
1890 (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
1891 /* We're transferring */
1892 if ((dcallno == cur->callno) || (cur->transferring == TRANSFER_MEDIAPASS && cur->transfercallno == callno))
1898 static void update_max_trunk(void)
1900 int max = TRUNK_CALL_START;
1903 /* XXX Prolly don't need locks here XXX */
1904 for (x = TRUNK_CALL_START; x < ARRAY_LEN(iaxs) - 1; x++) {
1912 ast_debug(1, "New max trunk callno is %d\n", max);
1915 static void update_max_nontrunk(void)
1919 /* XXX Prolly don't need locks here XXX */
1920 for (x=1;x<TRUNK_CALL_START - 1; x++) {
1924 maxnontrunkcall = max;
1926 ast_debug(1, "New max nontrunk callno is %d\n", max);
1929 static int make_trunk(unsigned short callno, int locked)
1933 struct callno_entry *callno_entry;
1934 if (iaxs[callno]->oseqno) {
1935 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
1938 if (callno & TRUNK_CALL_START) {
1939 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
1943 if (!(callno_entry = get_unused_callno(1, iaxs[callno]->callno_entry->validated))) {
1944 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
1948 x = callno_entry->callno;
1949 ast_mutex_lock(&iaxsl[x]);
1952 * \note We delete these before switching the slot, because if
1953 * they fire in the meantime, they will generate a warning.
1955 ast_sched_thread_del(sched, iaxs[callno]->pingid);
1956 ast_sched_thread_del(sched, iaxs[callno]->lagid);
1957 iaxs[x] = iaxs[callno];
1958 iaxs[x]->callno = x;
1960 /* since we copied over the pvt from a different callno, make sure the old entry is replaced
1961 * before assigning the new one */
1962 if (iaxs[x]->callno_entry) {
1963 iax2_sched_add(sched, MIN_REUSE_TIME * 1000, replace_callno, iaxs[x]->callno_entry);
1965 iaxs[x]->callno_entry = callno_entry;
1967 iaxs[callno] = NULL;
1968 /* Update the two timers that should have been started */
1969 iaxs[x]->pingid = iax2_sched_add(sched,
1970 ping_time * 1000, send_ping, (void *)(long)x);
1971 iaxs[x]->lagid = iax2_sched_add(sched,
1972 lagrq_time * 1000, send_lagrq, (void *)(long)x);
1975 ast_mutex_unlock(&iaxsl[callno]);
1978 ast_mutex_unlock(&iaxsl[x]);
1980 ast_debug(1, "Made call %d into trunk call %d\n", callno, x);
1981 /* We move this call from a non-trunked to a trunked call */
1983 update_max_nontrunk();
1987 static void store_by_transfercallno(struct chan_iax2_pvt *pvt)
1989 if (!pvt->transfercallno) {
1990 ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
1994 ao2_link(iax_transfercallno_pvts, pvt);
1997 static void remove_by_transfercallno(struct chan_iax2_pvt *pvt)
1999 if (!pvt->transfercallno) {
2000 ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
2004 ao2_unlink(iax_transfercallno_pvts, pvt);
2006 static void store_by_peercallno(struct chan_iax2_pvt *pvt)
2008 if (!pvt->peercallno) {
2009 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
2013 ao2_link(iax_peercallno_pvts, pvt);
2016 static void remove_by_peercallno(struct chan_iax2_pvt *pvt)
2018 if (!pvt->peercallno) {
2019 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
2023 ao2_unlink(iax_peercallno_pvts, pvt);
2026 static int addr_range_delme_cb(void *obj, void *arg, int flags)
2028 struct addr_range *lim = obj;
2033 static int addr_range_hash_cb(const void *obj, const int flags)
2035 const struct addr_range *lim = obj;
2036 return abs((int) lim->ha.netaddr.s_addr);
2039 static int addr_range_cmp_cb(void *obj, void *arg, int flags)
2041 struct addr_range *lim1 = obj, *lim2 = arg;
2042 return ((lim1->ha.netaddr.s_addr == lim2->ha.netaddr.s_addr) &&
2043 (lim1->ha.netmask.s_addr == lim2->ha.netmask.s_addr)) ?
2044 CMP_MATCH | CMP_STOP : 0;
2047 static int peercnt_hash_cb(const void *obj, const int flags)
2049 const struct peercnt *peercnt = obj;
2050 return abs((int) peercnt->addr);
2053 static int peercnt_cmp_cb(void *obj, void *arg, int flags)
2055 struct peercnt *peercnt1 = obj, *peercnt2 = arg;
2056 return (peercnt1->addr == peercnt2->addr) ? CMP_MATCH | CMP_STOP : 0;
2059 static int addr_range_match_address_cb(void *obj, void *arg, int flags)
2061 struct addr_range *addr_range = obj;
2062 struct sockaddr_in *sin = arg;
2064 if ((sin->sin_addr.s_addr & addr_range->ha.netmask.s_addr) == addr_range->ha.netaddr.s_addr) {
2065 return CMP_MATCH | CMP_STOP;
2073 * \brief compares sin to calltoken_ignores table to determine if validation is required.
2075 static int calltoken_required(struct sockaddr_in *sin, const char *name, int subclass)
2077 struct addr_range *addr_range;
2078 struct iax2_peer *peer = NULL;
2079 struct iax2_user *user = NULL;
2080 /* if no username is given, check for guest accounts */
2081 const char *find = S_OR(name, "guest");
2082 int res = 1; /* required by default */
2084 enum calltoken_peer_enum calltoken_required = CALLTOKEN_DEFAULT;
2085 /* There are only two cases in which calltoken validation is not required.
2086 * Case 1. sin falls within the list of address ranges specified in the calltoken optional table and
2087 * the peer definition has not set the requirecalltoken option.
2088 * Case 2. Username is a valid peer/user, and that peer has requirecalltoken set either auto or no.
2091 /* ----- Case 1 ----- */
2092 if ((addr_range = ao2_callback(calltoken_ignores, 0, addr_range_match_address_cb, sin))) {
2093 ao2_ref(addr_range, -1);
2097 /* ----- Case 2 ----- */
2098 if ((subclass == IAX_COMMAND_NEW) && (user = find_user(find))) {
2099 calltoken_required = user->calltoken_required;
2100 } else if ((subclass == IAX_COMMAND_NEW) && (user = realtime_user(find, sin))) {
2101 calltoken_required = user->calltoken_required;
2102 } else if ((subclass != IAX_COMMAND_NEW) && (peer = find_peer(find, 0))) {
2103 calltoken_required = peer->calltoken_required;
2104 } else if ((subclass != IAX_COMMAND_NEW) && (peer = realtime_peer(find, sin))) {
2105 calltoken_required = peer->calltoken_required;
2115 ast_debug(1, "Determining if address %s with username %s requires calltoken validation. Optional = %d calltoken_required = %d \n", ast_inet_ntoa(sin->sin_addr), name, optional, calltoken_required);
2116 if (((calltoken_required == CALLTOKEN_NO) || (calltoken_required == CALLTOKEN_AUTO)) ||
2117 (optional && (calltoken_required == CALLTOKEN_DEFAULT))) {
2127 * \brief set peercnt callno limit.
2130 * First looks in custom definitions. If not found, global limit
2131 * is used. Entries marked as reg already have
2132 * a custom limit set by a registration and are not modified.
2134 static void set_peercnt_limit(struct peercnt *peercnt)
2136 uint16_t limit = global_maxcallno;
2137 struct addr_range *addr_range;
2138 struct sockaddr_in sin = {
2139 .sin_addr.s_addr = peercnt->addr,
2143 if (peercnt->reg && peercnt->limit) {
2144 return; /* this peercnt has a custom limit set by a registration */
2147 if ((addr_range = ao2_callback(callno_limits, 0, addr_range_match_address_cb, &sin))) {
2148 limit = addr_range->limit;
2149 ast_debug(1, "custom addr_range %d found for %s\n", limit, ast_inet_ntoa(sin.sin_addr));
2150 ao2_ref(addr_range, -1);
2153 peercnt->limit = limit;
2158 * \brief sets limits for all peercnts in table. done on reload to reflect changes in conf.
2160 static int set_peercnt_limit_all_cb(void *obj, void *arg, int flags)
2162 struct peercnt *peercnt = obj;
2164 set_peercnt_limit(peercnt);
2165 ast_debug(1, "Reset limits for peercnts table\n");
2172 * \brief returns match if delme is set.
2174 static int prune_addr_range_cb(void *obj, void *arg, int flags)
2176 struct addr_range *addr_range = obj;
2178 return addr_range->delme ? CMP_MATCH : 0;
2183 * \brief modifies peercnt entry in peercnts table. Used to set custom limit or mark a registered ip
2185 static void peercnt_modify(unsigned char reg, uint16_t limit, struct sockaddr_in *sin)
2187 /* this function turns off and on custom callno limits set by peer registration */
2188 struct peercnt *peercnt;
2189 struct peercnt tmp = {
2190 .addr = sin->sin_addr.s_addr,
2193 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2196 peercnt->limit = limit;
2198 set_peercnt_limit(peercnt);
2200 ast_debug(1, "peercnt entry %s modified limit:%d registered:%d", ast_inet_ntoa(sin->sin_addr), peercnt->limit, peercnt->reg);
2201 ao2_ref(peercnt, -1); /* decrement ref from find */
2207 * \brief adds an ip to the peercnts table, increments connection count if it already exists
2209 * \details First searches for the address in the peercnts table. If found
2210 * the current count is incremented. If not found a new peercnt is allocated
2211 * and linked into the peercnts table with a call number count of 1.
2213 static int peercnt_add(struct sockaddr_in *sin)
2215 struct peercnt *peercnt;
2216 unsigned long addr = sin->sin_addr.s_addr;
2218 struct peercnt tmp = {
2222 /* Reasoning for peercnts container lock: Two identical ip addresses
2223 * could be added by different threads at the "same time". Without the container
2224 * lock, both threads could alloc space for the same object and attempt
2225 * to link to table. With the lock, one would create the object and link
2226 * to table while the other would find the already created peercnt object
2227 * rather than creating a new one. */
2229 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2231 } else if ((peercnt = ao2_alloc(sizeof(*peercnt), NULL))) {
2233 /* create and set defaults */
2234 peercnt->addr = addr;
2235 set_peercnt_limit(peercnt);
2236 /* guarantees it does not go away after unlocking table
2237 * ao2_find automatically adds this */
2238 ao2_link(peercnts, peercnt);
2240 ao2_unlock(peercnts);
2244 /* check to see if the address has hit its callno limit. If not increment cur. */
2245 if (peercnt->limit > peercnt->cur) {
2247 ast_debug(1, "ip callno count incremented to %d for %s\n", peercnt->cur, ast_inet_ntoa(sin->sin_addr));
2248 } else { /* max num call numbers for this peer has been reached! */
2249 ast_log(LOG_ERROR, "maxcallnumber limit of %d for %s has been reached!\n", peercnt->limit, ast_inet_ntoa(sin->sin_addr));
2253 /* clean up locks and ref count */
2254 ao2_unlock(peercnt);
2255 ao2_unlock(peercnts);
2256 ao2_ref(peercnt, -1); /* decrement ref from find/alloc, only the container ref remains. */
2263 * \brief decrements a peercnts table entry
2265 static void peercnt_remove(struct peercnt *peercnt)
2267 struct sockaddr_in sin = {
2268 .sin_addr.s_addr = peercnt->addr,
2272 /* Container locked here since peercnt may be unlinked from list. If left unlocked,
2273 * peercnt_add could try and grab this entry from the table and modify it at the
2274 * "same time" this thread attemps to unlink it.*/
2277 ast_debug(1, "ip callno count decremented to %d for %s\n", peercnt->cur, ast_inet_ntoa(sin.sin_addr));
2278 /* if this was the last connection from the peer remove it from table */
2279 if (peercnt->cur == 0) {
2280 ao2_unlink(peercnts, peercnt);/* decrements ref from table, last ref is left to scheduler */
2282 ao2_unlock(peercnts);
2288 * \brief called by scheduler to decrement object
2290 static int peercnt_remove_cb(const void *obj)
2292 struct peercnt *peercnt = (struct peercnt *) obj;
2294 peercnt_remove(peercnt);
2295 ao2_ref(peercnt, -1); /* decrement ref from scheduler */
2302 * \brief decrements peercnts connection count, finds by addr
2304 static int peercnt_remove_by_addr(struct sockaddr_in *sin)
2306 struct peercnt *peercnt;
2307 struct peercnt tmp = {
2308 .addr = sin->sin_addr.s_addr,
2311 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2312 peercnt_remove(peercnt);
2313 ao2_ref(peercnt, -1); /* decrement ref from find */
2320 * \brief Create callno_limit entry based on configuration
2322 static void build_callno_limits(struct ast_variable *v)
2324 struct addr_range *addr_range = NULL;
2325 struct addr_range tmp;
2331 for (; v; v = v->next) {
2335 ha = ast_append_ha("permit", v->name, NULL, &error);
2337 /* check for valid config information */
2339 ast_log(LOG_ERROR, "Call number limit for %s could not be added, Invalid address range\n.", v->name);
2341 } else if ((sscanf(v->value, "%d", &limit) != 1) || (limit < 0)) {
2342 ast_log(LOG_ERROR, "Call number limit for %s could not be added. Invalid limit %s\n.", v->name, v->value);
2347 ast_copy_ha(ha, &tmp.ha);
2348 /* find or create the addr_range */
2349 if ((addr_range = ao2_find(callno_limits, &tmp, OBJ_POINTER))) {
2350 ao2_lock(addr_range);
2352 } else if (!(addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
2354 return; /* out of memory */
2357 /* copy over config data into addr_range object */
2358 ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible for each limit */
2359 ast_free_ha(ha); /* cleanup the tmp ha */
2360 addr_range->limit = limit;
2361 addr_range->delme = 0;
2365 ao2_unlock(addr_range);
2367 ao2_link(callno_limits, addr_range);
2369 ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
2375 * \brief Create calltoken_ignores entry based on configuration
2377 static int add_calltoken_ignore(const char *addr)
2379 struct addr_range tmp;
2380 struct addr_range *addr_range = NULL;
2381 struct ast_ha *ha = NULL;
2384 if (ast_strlen_zero(addr)) {
2385 ast_log(LOG_WARNING, "invalid calltokenoptional %s\n", addr);
2389 ha = ast_append_ha("permit", addr, NULL, &error);
2391 /* check for valid config information */
2393 ast_log(LOG_WARNING, "Error %d creating calltokenoptional entry %s\n", error, addr);
2397 ast_copy_ha(ha, &tmp.ha);
2398 /* find or create the addr_range */
2399 if ((addr_range = ao2_find(calltoken_ignores, &tmp, OBJ_POINTER))) {
2400 ao2_lock(addr_range);
2401 addr_range->delme = 0;
2402 ao2_unlock(addr_range);
2403 } else if ((addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
2404 /* copy over config data into addr_range object */
2405 ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible */
2406 ao2_link(calltoken_ignores, addr_range);
2413 ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
2418 static char *handle_cli_iax2_show_callno_limits(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2420 struct ao2_iterator i;
2421 struct peercnt *peercnt;
2422 struct sockaddr_in sin;
2427 e->command = "iax2 show callnumber usage";
2429 "Usage: iax2 show callnumber usage [IP address]\n"
2430 " Shows current IP addresses which are consuming iax2 call numbers\n";
2435 if (a->argc < 4 || a->argc > 5)
2436 return CLI_SHOWUSAGE;
2438 ast_cli(a->fd, "%-15s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
2439 i = ao2_iterator_init(peercnts, 0);
2440 while ((peercnt = ao2_iterator_next(&i))) {
2441 sin.sin_addr.s_addr = peercnt->addr;
2442 if (a->argc == 5 && (!strcasecmp(a->argv[4], ast_inet_ntoa(sin.sin_addr)))) {
2443 ast_cli(a->fd, "%-15s %-12d %-12d\n", ast_inet_ntoa(sin.sin_addr), peercnt->cur, peercnt->limit);
2447 ast_cli(a->fd, "%-15s %-12d %-12d\n", ast_inet_ntoa(sin.sin_addr), peercnt->cur, peercnt->limit);
2449 ao2_ref(peercnt, -1);
2451 ao2_iterator_destroy(&i);
2454 ast_cli(a->fd, "\nNon-CallToken Validation Limit: %d\nNon-CallToken Validated: %d\n", global_maxcallno_nonval, total_nonval_callno_used);
2455 } else if (a->argc == 5 && !found) {
2456 ast_cli(a->fd, "No callnumber table entries for %s found\n", a->argv[4] );
2465 static struct callno_entry *get_unused_callno(int trunk, int validated)
2467 struct callno_entry *callno_entry = NULL;
2468 if ((!ao2_container_count(callno_pool) && !trunk) || (!ao2_container_count(callno_pool_trunk) && trunk)) {
2469 ast_log(LOG_WARNING, "Out of CallNumbers\n");
2470 /* Minor optimization for the extreme case. */
2474 /* the callno_pool container is locked here primarily to ensure thread
2475 * safety of the total_nonval_callno_used check and increment */
2476 ao2_lock(callno_pool);
2478 /* only a certain number of nonvalidated call numbers should be allocated.
2479 * If there ever is an attack, this separates the calltoken validating
2480 * users from the non calltoken validating users. */
2481 if (!validated && (total_nonval_callno_used >= global_maxcallno_nonval)) {
2482 ast_log(LOG_WARNING, "NON-CallToken callnumber limit is reached. Current:%d Max:%d\n", total_nonval_callno_used, global_maxcallno_nonval);
2483 ao2_unlock(callno_pool);
2487 /* unlink the object from the container, taking over ownership
2488 * of the reference the container had to the object */
2489 callno_entry = ao2_find((trunk ? callno_pool_trunk : callno_pool), NULL, OBJ_POINTER | OBJ_UNLINK | OBJ_CONTINUE);
2492 callno_entry->validated = validated;
2494 total_nonval_callno_used++;
2498 ao2_unlock(callno_pool);
2499 return callno_entry;
2502 static int replace_callno(const void *obj)
2504 struct callno_entry *callno_entry = (struct callno_entry *) obj;
2506 /* the callno_pool container is locked here primarily to ensure thread
2507 * safety of the total_nonval_callno_used check and decrement */
2508 ao2_lock(callno_pool);
2510 if (!callno_entry->validated && (total_nonval_callno_used != 0)) {
2511 total_nonval_callno_used--;
2512 } else if (!callno_entry->validated && (total_nonval_callno_used == 0)) {
2513 ast_log(LOG_ERROR, "Attempted to decrement total non calltoken validated callnumbers below zero... Callno is:%d \n", callno_entry->callno);
2516 if (callno_entry->callno < TRUNK_CALL_START) {
2517 ao2_link(callno_pool, callno_entry);
2519 ao2_link(callno_pool_trunk, callno_entry);
2521 ao2_ref(callno_entry, -1); /* only container ref remains */
2523 ao2_unlock(callno_pool);
2527 static int callno_hash(const void *obj, const int flags)
2529 return abs(ast_random());
2532 static int create_callno_pools(void)
2536 if (!(callno_pool = ao2_container_alloc(CALLNO_POOL_BUCKETS, callno_hash, NULL))) {
2540 if (!(callno_pool_trunk = ao2_container_alloc(CALLNO_POOL_BUCKETS, callno_hash, NULL))) {
2544 /* start at 2, 0 and 1 are reserved */
2545 for (i = 2; i <= IAX_MAX_CALLS; i++) {
2546 struct callno_entry *callno_entry;
2548 if (!(callno_entry = ao2_alloc(sizeof(*callno_entry), NULL))) {
2552 callno_entry->callno = i;
2554 if (i < TRUNK_CALL_START) {
2555 ao2_link(callno_pool, callno_entry);
2557 ao2_link(callno_pool_trunk, callno_entry);
2560 ao2_ref(callno_entry, -1);
2568 * \brief Schedules delayed removal of iax2_pvt call number data
2570 * \note After MIN_REUSE_TIME has passed for a destroyed iax2_pvt, the callno is
2571 * avaliable again, and the address from the previous connection must be decremented
2572 * from the peercnts table. This function schedules these operations to take place.
2574 static void sched_delay_remove(struct sockaddr_in *sin, struct callno_entry *callno_entry)
2577 struct peercnt *peercnt;
2578 struct peercnt tmp = {
2579 .addr = sin->sin_addr.s_addr,
2582 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2583 /* refcount is incremented with ao2_find. keep that ref for the scheduler */
2584 ast_debug(1, "schedule decrement of callno used for %s in %d seconds\n", ast_inet_ntoa(sin->sin_addr), MIN_REUSE_TIME);
2585 i = iax2_sched_add(sched, MIN_REUSE_TIME * 1000, peercnt_remove_cb, peercnt);
2587 ao2_ref(peercnt, -1);
2591 iax2_sched_add(sched, MIN_REUSE_TIME * 1000, replace_callno, callno_entry);
2596 * \brief returns whether or not a frame is capable of starting a new IAX2 dialog.
2598 * \note For this implementation, inbound pokes should _NOT_ be capable of allocating
2601 static inline int attribute_pure iax2_allow_new(int frametype, int subclass, int inbound)
2603 if (frametype != AST_FRAME_IAX) {
2607 case IAX_COMMAND_NEW:
2608 case IAX_COMMAND_REGREQ:
2609 case IAX_COMMAND_FWDOWNL:
2610 case IAX_COMMAND_REGREL:
2612 case IAX_COMMAND_POKE:
2622 * \note Calling this function while holding another pvt lock can cause a deadlock.
2624 static int __find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int return_locked, int check_dcallno)
2628 /* this call is calltoken validated as long as it is either NEW_FORCE
2629 * or NEW_ALLOW_CALLTOKEN_VALIDATED */
2630 int validated = (new > NEW_ALLOW) ? 1 : 0;
2633 if (new <= NEW_ALLOW) {
2635 struct chan_iax2_pvt *pvt;
2636 struct chan_iax2_pvt tmp_pvt = {
2638 .peercallno = callno,
2639 .transfercallno = callno,
2641 .frames_received = check_dcallno,
2644 memcpy(&tmp_pvt.addr, sin, sizeof(tmp_pvt.addr));
2645 /* this works for finding normal call numbers not involving transfering */
2646 if ((pvt = ao2_find(iax_peercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
2647 if (return_locked) {
2648 ast_mutex_lock(&iaxsl[pvt->callno]);
2655 /* this searches for transfer call numbers that might not get caught otherwise */
2656 memset(&tmp_pvt.addr, 0, sizeof(tmp_pvt.addr));
2657 memcpy(&tmp_pvt.transfer, sin, sizeof(tmp_pvt.transfer));
2658 if ((pvt = ao2_find(iax_transfercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
2659 if (return_locked) {
2660 ast_mutex_lock(&iaxsl[pvt->callno]);
2668 /* This will occur on the first response to a message that we initiated,
2669 * such as a PING. */
2671 ast_mutex_lock(&iaxsl[dcallno]);
2673 if (callno && dcallno && iaxs[dcallno] && !iaxs[dcallno]->peercallno && match(sin, callno, dcallno, iaxs[dcallno], check_dcallno)) {
2674 iaxs[dcallno]->peercallno = callno;
2676 store_by_peercallno(iaxs[dcallno]);
2677 if (!res || !return_locked) {
2678 ast_mutex_unlock(&iaxsl[dcallno]);
2683 ast_mutex_unlock(&iaxsl[dcallno]);
2686 /* If we get here, we SHOULD NOT find a call structure for this
2687 callno; if we do, it means that there is a call structure that
2688 has a peer callno but did NOT get entered into the hash table,
2691 If we find a call structure using this old, slow method, output a log
2692 message so we'll know about it. After a few months of leaving this in
2693 place, if we don't hear about people seeing these messages, we can
2694 remove this code for good.
2697 for (x = 1; !res && x < maxnontrunkcall; x++) {
2698 ast_mutex_lock(&iaxsl[x]);
2700 /* Look for an exact match */
2701 if (match(sin, callno, dcallno, iaxs[x], check_dcallno)) {
2705 if (!res || !return_locked)
2706 ast_mutex_unlock(&iaxsl[x]);
2708 for (x = TRUNK_CALL_START; !res && x < maxtrunkcall; x++) {
2709 ast_mutex_lock(&iaxsl[x]);
2711 /* Look for an exact match */
2712 if (match(sin, callno, dcallno, iaxs[x], check_dcallno)) {
2716 if (!res || !return_locked)
2717 ast_mutex_unlock(&iaxsl[x]);
2721 if (!res && (new >= NEW_ALLOW)) {
2722 struct callno_entry *callno_entry;
2723 /* It may seem odd that we look through the peer list for a name for
2724 * this *incoming* call. Well, it is weird. However, users don't
2725 * have an IP address/port number that we can match against. So,
2726 * this is just checking for a peer that has that IP/port and
2727 * assuming that we have a user of the same name. This isn't always
2728 * correct, but it will be changed if needed after authentication. */
2729 if (!iax2_getpeername(*sin, host, sizeof(host)))
2730 snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
2732 if (peercnt_add(sin)) {
2733 /* This address has hit its callnumber limit. When the limit
2734 * is reached, the connection is not added to the peercnts table.*/
2738 if (!(callno_entry = get_unused_callno(0, validated))) {
2739 /* since we ran out of space, remove the peercnt
2740 * entry we added earlier */
2741 peercnt_remove_by_addr(sin);
2742 ast_log(LOG_WARNING, "No more space\n");
2745 x = callno_entry->callno;
2746 ast_mutex_lock(&iaxsl[x]);
2748 iaxs[x] = new_iax(sin, host);
2749 update_max_nontrunk();
2752 ast_debug(1, "Creating new call structure %d\n", x);
2753 iaxs[x]->callno_entry = callno_entry;
2754 iaxs[x]->sockfd = sockfd;
2755 iaxs[x]->addr.sin_port = sin->sin_port;
2756 iaxs[x]->addr.sin_family = sin->sin_family;
2757 iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
2758 iaxs[x]->peercallno = callno;
2759 iaxs[x]->callno = x;
2760 iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
2761 iaxs[x]->expiry = min_reg_expire;
2762 iaxs[x]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
2763 iaxs[x]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
2764 iaxs[x]->amaflags = amaflags;
2765 ast_copy_flags64(iaxs[x], &globalflags, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE | IAX_FORCE_ENCRYPT);
2766 ast_string_field_set(iaxs[x], accountcode, accountcode);
2767 ast_string_field_set(iaxs[x], mohinterpret, mohinterpret);
2768 ast_string_field_set(iaxs[x], mohsuggest, mohsuggest);
2769 ast_string_field_set(iaxs[x], parkinglot, default_parkinglot);
2771 if (iaxs[x]->peercallno) {
2772 store_by_peercallno(iaxs[x]);
2775 ast_log(LOG_WARNING, "Out of resources\n");
2776 ast_mutex_unlock(&iaxsl[x]);
2777 replace_callno(callno_entry);
2781 ast_mutex_unlock(&iaxsl[x]);
2787 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
2789 return __find_callno(callno, dcallno, sin, new, sockfd, 0, full_frame);
2792 static int find_callno_locked(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
2794 return __find_callno(callno, dcallno, sin, new, sockfd, 1, full_frame);
2798 * \brief Queue a frame to a call's owning asterisk channel
2800 * \pre This function assumes that iaxsl[callno] is locked when called.
2802 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
2803 * was valid before calling it, it may no longer be valid after calling it.
2804 * This function may unlock and lock the mutex associated with this callno,
2805 * meaning that another thread may grab it and destroy the call.
2807 static int iax2_queue_frame(int callno, struct ast_frame *f)
2810 if (iaxs[callno] && iaxs[callno]->owner) {
2811 if (ast_channel_trylock(iaxs[callno]->owner)) {
2812 /* Avoid deadlock by pausing and trying again */
2813 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
2815 ast_queue_frame(iaxs[callno]->owner, f);
2816 ast_channel_unlock(iaxs[callno]->owner);
2826 * \brief Queue a hangup frame on the ast_channel owner
2828 * This function queues a hangup frame on the owner of the IAX2 pvt struct that
2829 * is active for the given call number.
2831 * \pre Assumes lock for callno is already held.
2833 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
2834 * was valid before calling it, it may no longer be valid after calling it.
2835 * This function may unlock and lock the mutex associated with this callno,
2836 * meaning that another thread may grab it and destroy the call.
2838 static int iax2_queue_hangup(int callno)
2841 if (iaxs[callno] && iaxs[callno]->owner) {
2842 if (ast_channel_trylock(iaxs[callno]->owner)) {
2843 /* Avoid deadlock by pausing and trying again */
2844 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
2846 ast_queue_hangup(iaxs[callno]->owner);
2847 ast_channel_unlock(iaxs[callno]->owner);
2857 * \brief Queue a control frame on the ast_channel owner
2859 * This function queues a control frame on the owner of the IAX2 pvt struct that
2860 * is active for the given call number.
2862 * \pre Assumes lock for callno is already held.
2864 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
2865 * was valid before calling it, it may no longer be valid after calling it.
2866 * This function may unlock and lock the mutex associated with this callno,
2867 * meaning that another thread may grab it and destroy the call.
2869 static int iax2_queue_control_data(int callno,
2870 enum ast_control_frame_type control, const void *data, size_t datalen)
2873 if (iaxs[callno] && iaxs[callno]->owner) {
2874 if (ast_channel_trylock(iaxs[callno]->owner)) {
2875 /* Avoid deadlock by pausing and trying again */
2876 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
2878 ast_queue_control_data(iaxs[callno]->owner, control, data, datalen);
2879 ast_channel_unlock(iaxs[callno]->owner);
2887 static void destroy_firmware(struct iax_firmware *cur)
2889 /* Close firmware */
2891 munmap((void*)cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh)));
2897 static int try_firmware(char *s)
2900 struct iax_firmware *cur = NULL;
2901 int ifd, fd, res, len, chunk;
2902 struct ast_iax2_firmware_header *fwh, fwh2;
2903 struct MD5Context md5;
2904 unsigned char sum[16], buf[1024];
2907 if (!(s2 = alloca(strlen(s) + 100))) {
2908 ast_log(LOG_WARNING, "Alloca failed!\n");
2912 last = strrchr(s, '/');
2918 snprintf(s2, strlen(s) + 100, "/var/tmp/%s-%ld", last, (unsigned long)ast_random());
2920 if ((res = stat(s, &stbuf) < 0)) {
2921 ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno));
2925 /* Make sure it's not a directory */
2926 if (S_ISDIR(stbuf.st_mode))
2928 ifd = open(s, O_RDONLY);
2930 ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
2933 fd = open(s2, O_RDWR | O_CREAT | O_EXCL, AST_FILE_MODE);
2935 ast_log(LOG_WARNING, "Cannot open '%s' for writing: %s\n", s2, strerror(errno));
2939 /* Unlink our newly created file */
2942 /* Now copy the firmware into it */
2943 len = stbuf.st_size;
2946 if (chunk > sizeof(buf))
2947 chunk = sizeof(buf);
2948 res = read(ifd, buf, chunk);
2950 ast_log(LOG_WARNING, "Only read %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
2955 res = write(fd, buf, chunk);
2957 ast_log(LOG_WARNING, "Only write %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
2965 /* Return to the beginning */
2966 lseek(fd, 0, SEEK_SET);
2967 if ((res = read(fd, &fwh2, sizeof(fwh2))) != sizeof(fwh2)) {
2968 ast_log(LOG_WARNING, "Unable to read firmware header in '%s'\n", s);
2972 if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) {
2973 ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s);
2977 if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) {
2978 ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s);
2982 if (fwh2.devname[sizeof(fwh2.devname) - 1] || ast_strlen_zero((char *)fwh2.devname)) {
2983 ast_log(LOG_WARNING, "No or invalid device type specified for '%s'\n", s);
2987 fwh = (struct ast_iax2_firmware_header*)mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
2988 if (fwh == MAP_FAILED) {
2989 ast_log(LOG_WARNING, "mmap failed: %s\n", strerror(errno));
2994 MD5Update(&md5, fwh->data, ntohl(fwh->datalen));
2995 MD5Final(sum, &md5);
2996 if (memcmp(sum, fwh->chksum, sizeof(sum))) {
2997 ast_log(LOG_WARNING, "Firmware file '%s' fails checksum\n", s);
2998 munmap((void*)fwh, stbuf.st_size);
3003 AST_LIST_TRAVERSE(&firmwares, cur, list) {
3004 if (!strcmp((char *)cur->fwh->devname, (char *)fwh->devname)) {
3005 /* Found a candidate */
3006 if (cur->dead || (ntohs(cur->fwh->version) < ntohs(fwh->version)))
3007 /* The version we have on loaded is older, load this one instead */
3009 /* This version is no newer than what we have. Don't worry about it.
3010 We'll consider it a proper load anyhow though */
3011 munmap((void*)fwh, stbuf.st_size);
3017 if (!cur && ((cur = ast_calloc(1, sizeof(*cur))))) {
3019 AST_LIST_INSERT_TAIL(&firmwares, cur, list);
3024 munmap((void*)cur->fwh, cur->mmaplen);
3029 cur->mmaplen = stbuf.st_size;
3036 static int iax_check_version(char *dev)
3039 struct iax_firmware *cur = NULL;
3041 if (ast_strlen_zero(dev))
3044 AST_LIST_LOCK(&firmwares);
3045 AST_LIST_TRAVERSE(&firmwares, cur, list) {
3046 if (!strcmp(dev, (char *)cur->fwh->devname)) {
3047 res = ntohs(cur->fwh->version);
3051 AST_LIST_UNLOCK(&firmwares);
3056 static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
3059 unsigned int bs = desc & 0xff;
3060 unsigned int start = (desc >> 8) & 0xffffff;
3062 struct iax_firmware *cur;
3064 if (ast_strlen_zero((char *)dev) || !bs)
3069 AST_LIST_LOCK(&firmwares);
3070 AST_LIST_TRAVERSE(&firmwares, cur, list) {
3071 if (strcmp((char *)dev, (char *)cur->fwh->devname))
3073 iax_ie_append_int(ied, IAX_IE_FWBLOCKDESC, desc);
3074 if (start < ntohl(cur->fwh->datalen)) {
3075 bytes = ntohl(cur->fwh->datalen) - start;
3078 iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes);
3081 iax_ie_append(ied, IAX_IE_FWBLOCKDATA);
3089 AST_LIST_UNLOCK(&firmwares);
3095 static void reload_firmware(int unload)
3097 struct iax_firmware *cur = NULL;
3100 char dir[256], fn[256];
3102 AST_LIST_LOCK(&firmwares);
3104 /* Mark all as dead */
3105 AST_LIST_TRAVERSE(&firmwares, cur, list)
3108 /* Now that we have marked them dead... load new ones */
3110 snprintf(dir, sizeof(dir), "%s/firmware/iax", ast_config_AST_DATA_DIR);
3113 while((de = readdir(fwd))) {
3114 if (de->d_name[0] != '.') {
3115 snprintf(fn, sizeof(fn), "%s/%s", dir, de->d_name);
3116 if (!try_firmware(fn)) {
3117 ast_verb(2, "Loaded firmware '%s'\n", de->d_name);
3123 ast_log(LOG_WARNING, "Error opening firmware directory '%s': %s\n", dir, strerror(errno));
3126 /* Clean up leftovers */
3127 AST_LIST_TRAVERSE_SAFE_BEGIN(&firmwares, cur, list) {
3130 AST_LIST_REMOVE_CURRENT(list);
3131 destroy_firmware(cur);
3133 AST_LIST_TRAVERSE_SAFE_END;
3135 AST_LIST_UNLOCK(&firmwares);
3139 * \note This function assumes that iaxsl[callno] is locked when called.
3141 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3142 * was valid before calling it, it may no longer be valid after calling it.
3143 * This function calls iax2_queue_frame(), which may unlock and lock the mutex
3144 * associated with this callno, meaning that another thread may grab it and destroy the call.
3146 static int __do_deliver(void *data)
3148 /* Just deliver the packet by using queueing. This is called by
3149 the IAX thread with the iaxsl lock held. */
3150 struct iax_frame *fr = data;
3152 ast_clear_flag(&fr->af, AST_FRFLAG_HAS_TIMING_INFO);
3153 if (iaxs[fr->callno] && !ast_test_flag64(iaxs[fr->callno], IAX_ALREADYGONE))
3154 iax2_queue_frame(fr->callno, &fr->af);
3155 /* Free our iax frame */
3156 iax2_frame_free(fr);
3157 /* And don't run again */
3161 static int handle_error(void)
3163 /* XXX Ideally we should figure out why an error occurred and then abort those
3164 rather than continuing to try. Unfortunately, the published interface does
3165 not seem to work XXX */
3167 struct sockaddr_in *sin;
3170 struct sock_extended_err e;
3175 m.msg_controllen = sizeof(e);
3177 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
3179 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
3181 if (m.msg_controllen) {
3182 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
3184 ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(sin->sin_addr));
3186 ast_log(LOG_WARNING, "No address detected??\n");
3188 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
3195 static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin, int sockfd)
3198 res = sendto(sockfd, f->data, f->datalen, 0,(struct sockaddr *)sin,
3201 ast_debug(1, "Received error: %s\n", strerror(errno));
3208 static int send_packet(struct iax_frame *f)
3211 int callno = f->callno;
3213 /* Don't send if there was an error, but return error instead */
3214 if (!callno || !iaxs[callno] || iaxs[callno]->error)
3217 /* Called with iaxsl held */
3219 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));
3223 iax_showframe(f, NULL, 0, &iaxs[callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
3224 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->transfer, sizeof(iaxs[callno]->transfer));
3227 iax_showframe(f, NULL, 0, &iaxs[callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
3228 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->addr, sizeof(iaxs[callno]->addr));
3232 ast_debug(1, "Received error: %s\n", strerror(errno));
3241 * \note Since this function calls iax2_queue_hangup(), the pvt struct
3242 * for the given call number may disappear during its execution.
3244 static int iax2_predestroy(int callno)
3246 struct ast_channel *c = NULL;
3247 struct chan_iax2_pvt *pvt = iaxs[callno];
3252 if (!ast_test_flag64(pvt, IAX_ALREADYGONE)) {
3253 iax2_destroy_helper(pvt);
3254 ast_set_flag64(pvt, IAX_ALREADYGONE);
3257 if ((c = pvt->owner)) {
3259 iax2_queue_hangup(callno);
3261 ast_module_unref(ast_module_info->self);
3267 static void iax2_destroy(int callno)
3269 struct chan_iax2_pvt *pvt = NULL;
3270 struct ast_channel *owner = NULL;
3273 if ((pvt = iaxs[callno])) {
3274 iax2_destroy_helper(pvt);
3277 owner = pvt ? pvt->owner : NULL;
3280 if (ast_channel_trylock(owner)) {
3281 ast_debug(3, "Avoiding IAX destroy deadlock\n");
3282 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
3288 iaxs[callno] = NULL;
3295 /* If there's an owner, prod it to give up */
3296 /* It is ok to use ast_queue_hangup() here instead of iax2_queue_hangup()
3297 * because we already hold the owner channel lock. */
3298 ast_queue_hangup(owner);
3301 if (pvt->peercallno) {
3302 remove_by_peercallno(pvt);
3305 if (pvt->transfercallno) {
3306 remove_by_transfercallno(pvt);
3316 ast_channel_unlock(owner);
3319 if (callno & 0x4000) {
3324 static int update_packet(struct iax_frame *f)
3326 /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
3327 struct ast_iax2_full_hdr *fh = f->data;
3328 struct ast_frame af;
3330 /* if frame is encrypted. decrypt before updating it. */
3331 if (f->encmethods) {
3332 decode_frame(&f->mydcx, fh, &af, &f->datalen);
3334 /* Mark this as a retransmission */
3335 fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
3337 f->iseqno = iaxs[f->callno]->iseqno;
3338 fh->iseqno = f->iseqno;
3340 /* Now re-encrypt the frame */
3341 if (f->encmethods) {
3342 /* since this is a retransmit frame, create a new random padding
3343 * before re-encrypting. */
3344 build_rand_pad(f->semirand, sizeof(f->semirand));
3345 encrypt_frame(&f->ecx, fh, f->semirand, &f->datalen);
3350 static int attempt_transmit(const void *data);
3351 static void __attempt_transmit(const void *data)
3353 /* Attempt to transmit the frame to the remote peer...
3354 Called without iaxsl held. */
3355 struct iax_frame *f = (struct iax_frame *)data;
3357 int callno = f->callno;
3358 /* Make sure this call is still active */
3360 ast_mutex_lock(&iaxsl[callno]);
3361 if (callno && iaxs[callno]) {
3362 if ((f->retries < 0) /* Already ACK'd */ ||
3363 (f->retries >= max_retries) /* Too many attempts */) {
3364 /* Record an error if we've transmitted too many times */
3365 if (f->retries >= max_retries) {
3367 /* Transfer timeout */
3368 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
3369 } else if (f->final) {
3370 iax2_destroy(callno);
3372 if (iaxs[callno]->owner)
3373 ast_log(LOG_WARNING, "Max retries exceeded to host %s on %s (type = %d, subclass = %u, 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.integer, f->ts, f->oseqno);
3374 iaxs[callno]->error = ETIMEDOUT;
3375 if (iaxs[callno]->owner) {
3376 struct ast_frame fr = { AST_FRAME_CONTROL, { AST_CONTROL_HANGUP }, .data.uint32 = AST_CAUSE_DESTINATION_OUT_OF_ORDER };
3378 iax2_queue_frame(callno, &fr); /* XXX */
3379 /* Remember, owner could disappear */
3380 if (iaxs[callno] && iaxs[callno]->owner)
3381 iaxs[callno]->owner->hangupcause = AST_CAUSE_DESTINATION_OUT_OF_ORDER;
3383 if (iaxs[callno]->reg) {
3384 memset(&iaxs[callno]->reg->us, 0, sizeof(iaxs[callno]->reg->us));
3385 iaxs[callno]->reg->regstate = REG_STATE_TIMEOUT;
3386 iaxs[callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
3388 iax2_destroy(callno);
3395 /* Update it if it needs it */
3397 /* Attempt transmission */
3400 /* Try again later after 10 times as long */
3402 if (f->retrytime > MAX_RETRY_TIME)
3403 f->retrytime = MAX_RETRY_TIME;
3404 /* Transfer messages max out at one second */
3405 if (f->transfer && (f->retrytime > 1000))
3406 f->retrytime = 1000;
3407 f->retrans = iax2_sched_add(sched, f->retrytime, attempt_transmit, f);
3410 /* Make sure it gets freed */
3416 /* Don't attempt delivery, just remove it from the queue */
3417 AST_LIST_REMOVE(&frame_queue[callno], f, list);
3418 ast_mutex_unlock(&iaxsl[callno]);
3419 f->retrans = -1; /* this is safe because this is the scheduled function */
3420 /* Free the IAX frame */
3422 } else if (callno) {
3423 ast_mutex_unlock(&iaxsl[callno]);
3427 static int attempt_transmit(const void *data)
3429 #ifdef SCHED_MULTITHREADED
3430 if (schedule_action(__attempt_transmit, data))
3432 __attempt_transmit(data);
3436 static char *handle_cli_iax2_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3438 struct iax2_peer *peer = NULL;
3439 struct iax2_user *user = NULL;
3440 static const char * const choices[] = { "all", NULL };
3445 e->command = "iax2 prune realtime";
3447 "Usage: iax2 prune realtime [<peername>|all]\n"
3448 " Prunes object(s) from the cache\n";
3452 cmplt = ast_cli_complete(a->word, choices, a->n);
3454 cmplt = complete_iax2_peers(a->line, a->word, a->pos, a->n - sizeof(choices), IAX_RTCACHEFRIENDS);
3460 return CLI_SHOWUSAGE;
3461 if (!strcmp(a->argv[3], "all")) {
3464 ast_cli(a->fd, "Cache flushed successfully.\n");
3467 peer = find_peer(a->argv[3], 0);
3468 user = find_user(a->argv[3]);
3471 if (ast_test_flag64(peer, IAX_RTCACHEFRIENDS)) {
3472 ast_set_flag64(peer, IAX_RTAUTOCLEAR);
3473 expire_registry(peer_ref(peer));
3474 ast_cli(a->fd, "Peer %s was removed from the cache.\n", a->argv[3]);
3476 ast_cli(a->fd, "Peer %s is not eligible for this operation.\n", a->argv[3]);
3481 if (ast_test_flag64(user, IAX_RTCACHEFRIENDS)) {
3482 ast_set_flag64(user, IAX_RTAUTOCLEAR);
3483 ast_cli(a->fd, "User %s was removed from the cache.\n", a->argv[3]);
3485 ast_cli(a->fd, "User %s is not eligible for this operation.\n", a->argv[3]);
3487 ao2_unlink(users,user);
3491 ast_cli(a->fd, "%s was not found in the cache.\n", a->argv[3]);
3497 static char *handle_cli_iax2_test_losspct(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3501 e->command = "iax2 test losspct";
3503 "Usage: iax2 test losspct <percentage>\n"
3504 " For testing, throws away <percentage> percent of incoming packets\n";
3510 return CLI_SHOWUSAGE;
3512 test_losspct = atoi(a->argv[3]);
3518 static char *handle_cli_iax2_test_late(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3522 e->command = "iax2 test late";
3524 "Usage: iax2 test late <ms>\n"
3525 " For testing, count the next frame as <ms> ms late\n";
3532 return CLI_SHOWUSAGE;
3534 test_late = atoi(a->argv[3]);
3539 static char *handle_cli_iax2_test_resync(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3543 e->command = "iax2 test resync";
3545 "Usage: iax2 test resync <ms>\n"
3546 " For testing, adjust all future frames by <ms> ms\n";
3553 return CLI_SHOWUSAGE;
3555 test_resync = atoi(a->argv[3]);
3560 static char *handle_cli_iax2_test_jitter(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3564 e->command = "iax2 test jitter";
3566 "Usage: iax2 test jitter <ms> <pct>\n"
3567 " For testing, simulate maximum jitter of +/- <ms> on <pct>\n"
3568 " percentage of packets. If <pct> is not specified, adds\n"
3569 " jitter to all packets.\n";
3575 if (a->argc < 4 || a->argc > 5)
3576 return CLI_SHOWUSAGE;
3578 test_jit = atoi(a->argv[3]);
3580 test_jitpct = atoi(a->argv[4]);
3584 #endif /* IAXTESTS */
3586 /*! \brief peer_status: Report Peer status in character string */
3587 /* returns 1 if peer is online, -1 if unmonitored */
3588 static int peer_status(struct iax2_peer *peer, char *status, int statuslen)
3592 if (peer->lastms < 0) {
3593 ast_copy_string(status, "UNREACHABLE", statuslen);
3594 } else if (peer->lastms > peer->maxms) {
3595 snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
3597 } else if (peer->lastms) {
3598 snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
3601 ast_copy_string(status, "UNKNOWN", statuslen);
3604 ast_copy_string(status, "Unmonitored", statuslen);
3610 /*! \brief Show one peer in detail */
3611 static char *handle_cli_iax2_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3615 struct iax2_peer *peer;
3616 char codec_buf[512];
3617 struct ast_str *encmethods = ast_str_alloca(256);
3618 int x = 0, codec = 0, load_realtime = 0;
3622 e->command = "iax2 show peer";
3624 "Usage: iax2 show peer <name>\n"
3625 " Display details on specific IAX peer\n";
3629 return complete_iax2_peers(a->line, a->word, a->pos, a->n, 0);
3634 return CLI_SHOWUSAGE;
3636 load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? 1 : 0;
3638 peer = find_peer(a->argv[3], load_realtime);
3640 encmethods_to_str(peer->encmethods, encmethods);
3641 ast_cli(a->fd, "\n\n");
3642 ast_cli(a->fd, " * Name : %s\n", peer->name);
3643 ast_cli(a->fd, " Secret : %s\n", ast_strlen_zero(peer->secret) ? "<Not set>" : "<Set>");
3644 ast_cli(a->fd, " Context : %s\n", peer->context);
3645 ast_cli(a->fd, " Parking lot : %s\n", peer->parkinglot);
3646 ast_cli(a->fd, " Mailbox : %s\n", peer->mailbox);
3647 ast_cli(a->fd, " Dynamic : %s\n", ast_test_flag64(peer, IAX_DYNAMIC) ? "Yes" : "No");
3648 ast_cli(a->fd, " Callnum limit: %d\n", peer->maxcallno);
3649 ast_cli(a->fd, " Calltoken req: %s\n", (peer->calltoken_required == CALLTOKEN_YES) ? "Yes" : ((peer->calltoken_required == CALLTOKEN_AUTO) ? "Auto" : "No"));
3650 ast_cli(a->fd, " Trunk : %s\n", ast_test_flag64(peer, IAX_TRUNK) ? "Yes" : "No");
3651 ast_cli(a->fd, " Encryption : %s\n", peer->encmethods ? ast_str_buffer(encmethods) : "No");
3652 ast_cli(a->fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
3653 ast_cli(a->fd, " Expire : %d\n", peer->expire);
3654 ast_cli(a->fd, " ACL : %s\n", (peer->ha ? "Yes" : "No"));
3655 ast_cli(a->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));
3656 ast_cli(a->fd, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
3657 ast_cli(a->fd, " Username : %s\n", peer->username);
3658 ast_cli(a->fd, " Codecs : ");
3659 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
3660 ast_cli(a->fd, "%s\n", codec_buf);
3662 ast_cli(a->fd, " Codec Order : (");
3663 for(x = 0; x < 32 ; x++) {
3664 codec = ast_codec_pref_index(&peer->prefs,x);
3667 ast_cli(a->fd, "%s", ast_getformatname(codec));
3668 if(x < 31 && ast_codec_pref_index(&peer->prefs,x+1))
3669 ast_cli(a->fd, "|");
3673 ast_cli(a->fd, "none");
3674 ast_cli(a->fd, ")\n");
3676 ast_cli(a->fd, " Status : ");
3677 peer_status(peer, status, sizeof(status));
3678 ast_cli(a->fd, "%s\n",status);
3679 ast_cli(a->fd, " Qualify : every %dms when OK, every %dms when UNREACHABLE (sample smoothing %s)\n", peer->pokefreqok, peer->pokefreqnotok, peer->smoothing ? "On" : "Off");
3680 ast_cli(a->fd, "\n");
3683 ast_cli(a->fd, "Peer %s not found.\n", a->argv[3]);
3684 ast_cli(a->fd, "\n");
3690 static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags)
3693 struct iax2_peer *peer;
3695 int wordlen = strlen(word);
3696 struct ao2_iterator i;
3698 i = ao2_iterator_init(peers, 0);
3699 while ((peer = ao2_iterator_next(&i))) {
3700 if (!strncasecmp(peer->name, word, wordlen) && ++which > state
3701 && (!flags || ast_test_flag64(peer, flags))) {
3702 res = ast_strdup(peer->name);
3708 ao2_iterator_destroy(&i);
3713 static char *handle_cli_iax2_show_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)