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
22 * as specified in RFC 5456
24 * \author Mark Spencer <markster@digium.com>
27 * \arg \ref Config_iax
29 * \ingroup channel_drivers
31 * \todo Implement musicclass settings for IAX2 devices
40 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
44 #include <sys/socket.h>
45 #include <netinet/in.h>
46 #include <arpa/inet.h>
47 #include <netinet/in_systm.h>
48 #include <netinet/ip.h>
50 #include <sys/signal.h>
58 #include "asterisk/paths.h" /* need ast_config_AST_DATA_DIR for firmware */
60 #include "asterisk/lock.h"
61 #include "asterisk/frame.h"
62 #include "asterisk/channel.h"
63 #include "asterisk/module.h"
64 #include "asterisk/pbx.h"
65 #include "asterisk/sched.h"
66 #include "asterisk/io.h"
67 #include "asterisk/config.h"
68 #include "asterisk/cli.h"
69 #include "asterisk/translate.h"
70 #include "asterisk/md5.h"
71 #include "asterisk/cdr.h"
72 #include "asterisk/crypto.h"
73 #include "asterisk/acl.h"
74 #include "asterisk/manager.h"
75 #include "asterisk/callerid.h"
76 #include "asterisk/app.h"
77 #include "asterisk/astdb.h"
78 #include "asterisk/musiconhold.h"
79 #include "asterisk/features.h"
80 #include "asterisk/utils.h"
81 #include "asterisk/causes.h"
82 #include "asterisk/localtime.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"
92 #include "asterisk/test.h"
93 #include "asterisk/data.h"
96 #include "iax2-parser.h"
97 #include "iax2-provision.h"
98 #include "jitterbuf.h"
101 <application name="IAX2Provision" language="en_US">
103 Provision a calling IAXy with a given template.
106 <parameter name="template">
107 <para>If not specified, defaults to <literal>default</literal>.</para>
111 <para>Provisions the calling IAXy (assuming the calling entity is in fact an IAXy) with the
112 given <replaceable>template</replaceable>. Returns <literal>-1</literal> on error
113 or <literal>0</literal> on success.</para>
116 <function name="IAXPEER" language="en_US">
118 Gets IAX peer information.
121 <parameter name="peername" required="true">
123 <enum name="CURRENTCHANNEL">
124 <para>If <replaceable>peername</replaceable> is specified to this value, return the IP address of the
125 endpoint of the current channel</para>
129 <parameter name="item">
130 <para>If <replaceable>peername</replaceable> is specified, valid items are:</para>
133 <para>(default) The IP address.</para>
136 <para>The peer's status (if <literal>qualify=yes</literal>)</para>
138 <enum name="mailbox">
139 <para>The configured mailbox.</para>
141 <enum name="context">
142 <para>The configured context.</para>
145 <para>The epoch time of the next expire.</para>
147 <enum name="dynamic">
148 <para>Is it dynamic? (yes/no).</para>
150 <enum name="callerid_name">
151 <para>The configured Caller ID name.</para>
153 <enum name="callerid_num">
154 <para>The configured Caller ID number.</para>
157 <para>The configured codecs.</para>
159 <enum name="codec[x]">
160 <para>Preferred codec index number <replaceable>x</replaceable> (beginning
161 with <literal>0</literal>)</para>
168 <ref type="function">SIPPEER</ref>
171 <function name="IAXVAR" language="en_US">
173 Sets or retrieves a remote variable.
176 <parameter name="varname" required="true" />
180 <manager name="IAXpeers" language="en_US">
185 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
190 <manager name="IAXpeerlist" language="en_US">
195 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
198 <para>List all the IAX peers.</para>
201 <manager name="IAXnetstats" language="en_US">
207 <para>Show IAX channels network statistics.</para>
210 <manager name="IAXregistry" language="en_US">
212 Show IAX registrations.
215 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
218 <para>Show IAX registrations.</para>
223 /* Define SCHED_MULTITHREADED to run the scheduler in a special
224 multithreaded mode. */
225 #define SCHED_MULTITHREADED
227 /* Define DEBUG_SCHED_MULTITHREADED to keep track of where each
228 thread is actually doing. */
229 #define DEBUG_SCHED_MULTITHREAD
233 static int nochecksums = 0;
236 #define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
237 #define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
239 #define DEFAULT_THREAD_COUNT 10
240 #define DEFAULT_MAX_THREAD_COUNT 100
241 #define DEFAULT_RETRY_TIME 1000
242 #define MEMORY_SIZE 100
243 #define DEFAULT_DROP 3
245 #define DEBUG_SUPPORT
247 #define MIN_REUSE_TIME 60 /* Don't reuse a call number within 60 seconds */
249 /* Sample over last 100 units to determine historic jitter */
252 static struct ast_codec_pref prefs;
254 static const char tdesc[] = "Inter Asterisk eXchange Driver (Ver 2)";
257 /*! \brief Maximum transmission unit for the UDP packet in the trunk not to be
258 fragmented. This is based on 1516 - ethernet - ip - udp - iax minus one g711 frame = 1240 */
259 #define MAX_TRUNK_MTU 1240
261 static int global_max_trunk_mtu; /*!< Maximum MTU, 0 if not used */
262 static int trunk_timed, trunk_untimed, trunk_maxmtu, trunk_nmaxmtu ; /*!< Trunk MTU statistics */
264 #define DEFAULT_CONTEXT "default"
266 static char default_parkinglot[AST_MAX_CONTEXT];
268 static char language[MAX_LANGUAGE] = "";
269 static char regcontext[AST_MAX_CONTEXT] = "";
271 static int maxauthreq = 3;
272 static int max_retries = 4;
273 static int ping_time = 21;
274 static int lagrq_time = 10;
275 static int maxjitterbuffer=1000;
276 static int resyncthreshold=1000;
277 static int maxjitterinterps=10;
278 static int jittertargetextra = 40; /* number of milliseconds the new jitter buffer adds on to its size */
280 #define MAX_TRUNKDATA 640 * 200 /*!< 40ms, uncompressed linear * 200 channels */
282 static int trunkfreq = 20;
283 static int trunkmaxsize = MAX_TRUNKDATA;
285 static int authdebug = 1;
286 static int autokill = 0;
287 static int iaxcompat = 0;
288 static int last_authmethod = 0;
290 static int iaxdefaultdpcache=10 * 60; /* Cache dialplan entries for 10 minutes by default */
292 static int iaxdefaulttimeout = 5; /* Default to wait no more than 5 seconds for a reply to come back */
299 static int min_reg_expire;
300 static int max_reg_expire;
302 static int srvlookup = 0;
304 static struct ast_timer *timer; /* Timer for trunking */
306 static struct ast_netsock_list *netsock;
307 static struct ast_netsock_list *outsock; /*!< used if sourceaddress specified and bindaddr == INADDR_ANY */
308 static int defaultsockfd = -1;
310 static int (*iax2_regfunk)(const char *username, int onoff) = NULL;
313 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
315 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
316 ~AST_FORMAT_SLINEAR & \
317 ~AST_FORMAT_SLINEAR16 & \
318 ~AST_FORMAT_SIREN7 & \
319 ~AST_FORMAT_SIREN14 & \
325 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
327 ~AST_FORMAT_G726_AAL2 & \
330 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
334 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
335 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
336 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
338 /* if a pvt has encryption setup done and is running on the call */
339 #define IAX_CALLENCRYPTED(pvt) \
340 (ast_test_flag64(pvt, IAX_ENCRYPTED) && ast_test_flag64(pvt, IAX_KEYPOPULATED))
342 #define IAX_DEBUGDIGEST(msg, key) do { \
344 char digest[33] = ""; \
349 for (idx = 0; idx < 16; idx++) \
350 sprintf(digest + (idx << 1), "%2.2x", (unsigned char) key[idx]); \
352 ast_log(LOG_NOTICE, msg " IAX_COMMAND_RTKEY to rotate key to '%s'\n", digest); \
355 static struct io_context *io;
356 static struct ast_sched_thread *sched;
358 static format_t iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
360 static int iaxdebug = 0;
362 static int iaxtrunkdebug = 0;
364 static int test_losspct = 0;
366 static int test_late = 0;
367 static int test_resync = 0;
368 static int test_jit = 0;
369 static int test_jitpct = 0;
370 #endif /* IAXTESTS */
372 static char accountcode[AST_MAX_ACCOUNT_CODE];
373 static char mohinterpret[MAX_MUSICCLASS];
374 static char mohsuggest[MAX_MUSICCLASS];
375 static int amaflags = 0;
377 static int delayreject = 0;
378 static int iax2_encryption = 0;
380 static struct ast_flags64 globalflags = { 0 };
382 static pthread_t netthreadid = AST_PTHREADT_NULL;
385 IAX_STATE_STARTED = (1 << 0),
386 IAX_STATE_AUTHENTICATED = (1 << 1),
387 IAX_STATE_TBD = (1 << 2),
390 struct iax2_context {
391 char context[AST_MAX_CONTEXT];
392 struct iax2_context *next;
396 #define IAX_HASCALLERID (uint64_t)(1 << 0) /*!< CallerID has been specified */
397 #define IAX_DELME (uint64_t)(1 << 1) /*!< Needs to be deleted */
398 #define IAX_TEMPONLY (uint64_t)(1 << 2) /*!< Temporary (realtime) */
399 #define IAX_TRUNK (uint64_t)(1 << 3) /*!< Treat as a trunk */
400 #define IAX_NOTRANSFER (uint64_t)(1 << 4) /*!< Don't native bridge */
401 #define IAX_USEJITTERBUF (uint64_t)(1 << 5) /*!< Use jitter buffer */
402 #define IAX_DYNAMIC (uint64_t)(1 << 6) /*!< dynamic peer */
403 #define IAX_SENDANI (uint64_t)(1 << 7) /*!< Send ANI along with CallerID */
404 #define IAX_RTSAVE_SYSNAME (uint64_t)(1 << 8) /*!< Save Systname on Realtime Updates */
405 #define IAX_ALREADYGONE (uint64_t)(1 << 9) /*!< Already disconnected */
406 #define IAX_PROVISION (uint64_t)(1 << 10) /*!< This is a provisioning request */
407 #define IAX_QUELCH (uint64_t)(1 << 11) /*!< Whether or not we quelch audio */
408 #define IAX_ENCRYPTED (uint64_t)(1 << 12) /*!< Whether we should assume encrypted tx/rx */
409 #define IAX_KEYPOPULATED (uint64_t)(1 << 13) /*!< Whether we have a key populated */
410 #define IAX_CODEC_USER_FIRST (uint64_t)(1 << 14) /*!< are we willing to let the other guy choose the codec? */
411 #define IAX_CODEC_NOPREFS (uint64_t)(1 << 15) /*!< Force old behaviour by turning off prefs */
412 #define IAX_CODEC_NOCAP (uint64_t)(1 << 16) /*!< only consider requested format and ignore capabilities*/
413 #define IAX_RTCACHEFRIENDS (uint64_t)(1 << 17) /*!< let realtime stay till your reload */
414 #define IAX_RTUPDATE (uint64_t)(1 << 18) /*!< Send a realtime update */
415 #define IAX_RTAUTOCLEAR (uint64_t)(1 << 19) /*!< erase me on expire */
416 #define IAX_FORCEJITTERBUF (uint64_t)(1 << 20) /*!< Force jitterbuffer, even when bridged to a channel that can take jitter */
417 #define IAX_RTIGNOREREGEXPIRE (uint64_t)(1 << 21) /*!< When using realtime, ignore registration expiration */
418 #define IAX_TRUNKTIMESTAMPS (uint64_t)(1 << 22) /*!< Send trunk timestamps */
419 #define IAX_TRANSFERMEDIA (uint64_t)(1 << 23) /*!< When doing IAX2 transfers, transfer media only */
420 #define IAX_MAXAUTHREQ (uint64_t)(1 << 24) /*!< Maximum outstanding AUTHREQ restriction is in place */
421 #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 */
422 #define IAX_ALLOWFWDOWNLOAD (uint64_t)(1 << 26) /*!< Allow the FWDOWNL command? */
423 #define IAX_IMMEDIATE (uint64_t)(1 << 27) /*!< Allow immediate off-hook to extension s */
424 #define IAX_SENDCONNECTEDLINE (uint64_t)(1 << 28) /*!< Allow sending of connected line updates */
425 #define IAX_RECVCONNECTEDLINE (uint64_t)(1 << 29) /*!< Allow receiving of connected line updates */
426 #define IAX_FORCE_ENCRYPT (uint64_t)(1 << 30) /*!< Forces call encryption, if encryption not possible hangup */
427 #define IAX_SHRINKCALLERID (uint64_t)(1 << 31) /*!< Turn on and off caller id shrinking */
428 static int global_rtautoclear = 120;
430 static int reload_config(void);
433 * \brief Call token validation settings.
435 enum calltoken_peer_enum {
436 /*! \brief Default calltoken required unless the ip is in the ignorelist */
437 CALLTOKEN_DEFAULT = 0,
438 /*! \brief Require call token validation. */
440 /*! \brief Require call token validation after a successful registration
441 * using call token validation occurs. */
443 /*! \brief Do not require call token validation. */
448 AST_DECLARE_STRING_FIELDS(
449 AST_STRING_FIELD(name);
450 AST_STRING_FIELD(secret);
451 AST_STRING_FIELD(dbsecret);
452 AST_STRING_FIELD(accountcode);
453 AST_STRING_FIELD(mohinterpret);
454 AST_STRING_FIELD(mohsuggest);
455 AST_STRING_FIELD(inkeys); /*!< Key(s) this user can use to authenticate to us */
456 AST_STRING_FIELD(language);
457 AST_STRING_FIELD(cid_num);
458 AST_STRING_FIELD(cid_name);
459 AST_STRING_FIELD(parkinglot); /*!< Default parkinglot for device */
468 int maxauthreq; /*!< Maximum allowed outstanding AUTHREQs */
469 int curauthreq; /*!< Current number of outstanding AUTHREQs */
470 struct ast_codec_pref prefs;
472 struct iax2_context *contexts;
473 struct ast_variable *vars;
474 enum calltoken_peer_enum calltoken_required; /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
478 AST_DECLARE_STRING_FIELDS(
479 AST_STRING_FIELD(name);
480 AST_STRING_FIELD(username);
481 AST_STRING_FIELD(secret);
482 AST_STRING_FIELD(dbsecret);
483 AST_STRING_FIELD(outkey); /*!< What key we use to talk to this peer */
485 AST_STRING_FIELD(regexten); /*!< Extension to register (if regcontext is used) */
486 AST_STRING_FIELD(context); /*!< For transfers only */
487 AST_STRING_FIELD(peercontext); /*!< Context to pass to peer */
488 AST_STRING_FIELD(mailbox); /*!< Mailbox */
489 AST_STRING_FIELD(mohinterpret);
490 AST_STRING_FIELD(mohsuggest);
491 AST_STRING_FIELD(inkeys); /*!< Key(s) this peer can use to authenticate to us */
492 /* Suggested caller id if registering */
493 AST_STRING_FIELD(cid_num); /*!< Default context (for transfer really) */
494 AST_STRING_FIELD(cid_name); /*!< Default context (for transfer really) */
495 AST_STRING_FIELD(zonetag); /*!< Time Zone */
496 AST_STRING_FIELD(parkinglot); /*!< Default parkinglot for device */
498 struct ast_codec_pref prefs;
499 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
500 struct sockaddr_in addr;
502 int sockfd; /*!< Socket to use for transmission */
507 /* Dynamic Registration fields */
508 struct sockaddr_in defaddr; /*!< Default address if there is one */
509 int authmethods; /*!< Authentication methods (IAX_AUTH_*) */
510 int encmethods; /*!< Encryption methods (IAX_ENCRYPT_*) */
512 int expire; /*!< Schedule entry for expiry */
513 int expiry; /*!< How soon to expire */
514 format_t capability; /*!< Capability */
517 int callno; /*!< Call number of POKE request */
518 int pokeexpire; /*!< Scheduled qualification-related task (ie iax2_poke_peer_s or iax2_poke_noanswer) */
519 int lastms; /*!< How long last response took (in ms), or -1 for no response */
520 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
522 int pokefreqok; /*!< How often to check if the host is up */
523 int pokefreqnotok; /*!< How often to check when the host has been determined to be down */
524 int historicms; /*!< How long recent average responses took */
525 int smoothing; /*!< Sample over how many units to determine historic ms */
526 uint16_t maxcallno; /*!< Max call number limit for this peer. Set on registration */
528 struct ast_event_sub *mwi_event_sub;
531 enum calltoken_peer_enum calltoken_required; /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
534 #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
536 struct iax2_trunk_peer {
539 struct sockaddr_in addr;
540 struct timeval txtrunktime; /*!< Transmit trunktime */
541 struct timeval rxtrunktime; /*!< Receive trunktime */
542 struct timeval lasttxtime; /*!< Last transmitted trunktime */
543 struct timeval trunkact; /*!< Last trunk activity */
544 unsigned int lastsent; /*!< Last sent time */
545 /* Trunk data and length */
546 unsigned char *trunkdata;
547 unsigned int trunkdatalen;
548 unsigned int trunkdataalloc;
552 AST_LIST_ENTRY(iax2_trunk_peer) list;
555 static AST_LIST_HEAD_STATIC(tpeers, iax2_trunk_peer);
557 struct iax_firmware {
558 AST_LIST_ENTRY(iax_firmware) list;
562 struct ast_iax2_firmware_header *fwh;
567 REG_STATE_UNREGISTERED = 0,
570 REG_STATE_REGISTERED,
576 enum iax_transfer_state {
581 TRANSFER_PASSTHROUGH,
585 TRANSFER_MPASSTHROUGH,
590 struct iax2_registry {
591 struct sockaddr_in addr; /*!< Who we connect to for registration purposes */
593 char secret[80]; /*!< Password or key name in []'s */
594 int expire; /*!< Sched ID of expiration */
595 int refresh; /*!< How often to refresh */
596 enum iax_reg_state regstate;
597 int messages; /*!< Message count, low 8 bits = new, high 8 bits = old */
598 int callno; /*!< Associated call number if applicable */
599 struct sockaddr_in us; /*!< Who the server thinks we are */
600 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
601 AST_LIST_ENTRY(iax2_registry) entry;
604 static AST_LIST_HEAD_STATIC(registrations, iax2_registry);
606 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
607 #define MIN_RETRY_TIME 100
608 #define MAX_RETRY_TIME 10000
610 #define MAX_JITTER_BUFFER 50
611 #define MIN_JITTER_BUFFER 10
613 #define DEFAULT_TRUNKDATA 640 * 10 /*!< 40ms, uncompressed linear * 10 channels */
615 #define MAX_TIMESTAMP_SKEW 160 /*!< maximum difference between actual and predicted ts for sending */
617 /* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
618 #define TS_GAP_FOR_JB_RESYNC 5000
620 /* used for first_iax_message and last_iax_message. If this bit is set it was TX, else RX */
621 #define MARK_IAX_SUBCLASS_TX 0x8000
623 static int iaxthreadcount = DEFAULT_THREAD_COUNT;
624 static int iaxmaxthreadcount = DEFAULT_MAX_THREAD_COUNT;
625 static int iaxdynamicthreadcount = 0;
626 static int iaxdynamicthreadnum = 0;
627 static int iaxactivethreadcount = 0;
641 struct chan_iax2_pvt {
642 /*! Socket to send/receive on for this call */
644 /*! Last received voice format */
645 format_t voiceformat;
646 /*! Last received video format */
647 format_t videoformat;
648 /*! Last sent voice format */
649 format_t svoiceformat;
650 /*! Last sent video format */
651 format_t svideoformat;
652 /*! What we are capable of sending */
654 /*! Last received timestamp */
656 /*! Last sent timestamp - never send the same timestamp twice in a single call */
657 unsigned int lastsent;
658 /*! Timestamp of the last video frame sent */
659 unsigned int lastvsent;
660 /*! Next outgoing timestamp if everything is good */
661 unsigned int nextpred;
662 /*! iax frame subclass that began iax2_pvt entry. 0x8000 bit is set on TX */
663 int first_iax_message;
664 /*! Last iax frame subclass sent or received for a iax2_pvt. 0x8000 bit is set on TX */
665 int last_iax_message;
666 /*! True if the last voice we transmitted was not silence/CNG */
667 unsigned int notsilenttx:1;
669 unsigned int pingtime;
670 /*! Max time for initial response */
673 struct sockaddr_in addr;
674 /*! Actual used codec preferences */
675 struct ast_codec_pref prefs;
676 /*! Requested codec preferences */
677 struct ast_codec_pref rprefs;
678 /*! Our call number */
679 unsigned short callno;
680 /*! Our callno_entry entry */
681 struct callno_entry *callno_entry;
683 unsigned short peercallno;
684 /*! Negotiated format, this is only used to remember what format was
685 chosen for an unauthenticated call so that the channel can get
686 created later using the right format */
687 format_t chosenformat;
688 /*! Peer selected format */
690 /*! Peer capability */
691 format_t peercapability;
692 /*! timeval that we base our transmission on */
693 struct timeval offset;
694 /*! timeval that we base our delivery on */
695 struct timeval rxcore;
696 /*! The jitterbuffer */
698 /*! active jb read scheduler id */
702 /*! Error, as discovered by the manager */
704 /*! Owner if we have one */
705 struct ast_channel *owner;
706 /*! What's our state? */
707 struct ast_flags state;
708 /*! Expiry (optional) */
710 /*! Next outgoing sequence number */
711 unsigned char oseqno;
712 /*! Next sequence number they have not yet acknowledged */
713 unsigned char rseqno;
714 /*! Next incoming sequence number */
715 unsigned char iseqno;
716 /*! Last incoming sequence number we have acknowledged */
717 unsigned char aseqno;
719 AST_DECLARE_STRING_FIELDS(
721 AST_STRING_FIELD(peer);
722 /*! Default Context */
723 AST_STRING_FIELD(context);
724 /*! Caller ID if available */
725 AST_STRING_FIELD(cid_num);
726 AST_STRING_FIELD(cid_name);
727 /*! Hidden Caller ID (i.e. ANI) if appropriate */
728 AST_STRING_FIELD(ani);
730 AST_STRING_FIELD(dnid);
732 AST_STRING_FIELD(rdnis);
733 /*! Requested Extension */
734 AST_STRING_FIELD(exten);
735 /*! Expected Username */
736 AST_STRING_FIELD(username);
737 /*! Expected Secret */
738 AST_STRING_FIELD(secret);
740 AST_STRING_FIELD(challenge);
741 /*! Public keys permitted keys for incoming authentication */
742 AST_STRING_FIELD(inkeys);
743 /*! Private key for outgoing authentication */
744 AST_STRING_FIELD(outkey);
745 /*! Preferred language */
746 AST_STRING_FIELD(language);
747 /*! Hostname/peername for naming purposes */
748 AST_STRING_FIELD(host);
750 AST_STRING_FIELD(dproot);
751 AST_STRING_FIELD(accountcode);
752 AST_STRING_FIELD(mohinterpret);
753 AST_STRING_FIELD(mohsuggest);
754 /*! received OSP token */
755 AST_STRING_FIELD(osptoken);
756 /*! Default parkinglot */
757 AST_STRING_FIELD(parkinglot);
759 /*! AUTHREJ all AUTHREP frames */
761 /*! permitted authentication methods */
763 /*! permitted encryption methods */
765 /*! Encryption AES-128 Key */
766 ast_aes_encrypt_key ecx;
767 /*! Decryption AES-128 Key corresponding to ecx */
768 ast_aes_decrypt_key mydcx;
769 /*! Decryption AES-128 Key used to decrypt peer frames */
770 ast_aes_decrypt_key dcx;
771 /*! scheduler id associated with iax_key_rotate
772 * for encrypted calls*/
774 /*! 32 bytes of semi-random data */
775 unsigned char semirand[32];
776 /*! Associated registry */
777 struct iax2_registry *reg;
778 /*! Associated peer for poking */
779 struct iax2_peer *peerpoke;
784 /*! Transferring status */
785 enum iax_transfer_state transferring;
786 /*! Transfer identifier */
788 /*! Who we are IAX transferring to */
789 struct sockaddr_in transfer;
790 /*! What's the new call number for the transfer */
791 unsigned short transfercallno;
792 /*! Transfer encrypt AES-128 Key */
793 ast_aes_encrypt_key tdcx;
795 /*! Status of knowledge of peer ADSI capability */
798 /*! Who we are bridged to */
799 unsigned short bridgecallno;
801 int pingid; /*!< Transmit PING request */
802 int lagid; /*!< Retransmit lag request */
803 int autoid; /*!< Auto hangup for Dialplan requestor */
804 int authid; /*!< Authentication rejection ID */
805 int authfail; /*!< Reason to report failure */
806 int initid; /*!< Initial peer auto-congest ID (based on qualified peers) */
811 AST_LIST_HEAD_NOLOCK(, iax2_dpcache) dpentries;
812 /*! variables inherited from the user definition */
813 struct ast_variable *vars;
814 /*! variables transmitted in a NEW packet */
815 struct ast_variable *iaxvars;
816 /*! last received remote rr */
817 struct iax_rr remote_rr;
818 /*! Current base time: (just for stats) */
820 /*! Dropped frame count: (just for stats) */
822 /*! received frame count: (just for stats) */
824 /*! num bytes used for calltoken ie, even an empty ie should contain 2 */
825 unsigned char calltoken_ie_len;
826 /*! hold all signaling frames from the pbx thread until we have a destination callno */
828 /*! frame queue for signaling frames from pbx thread waiting for destination callno */
829 AST_LIST_HEAD_NOLOCK(signaling_queue, signaling_queue_entry) signaling_queue;
832 struct signaling_queue_entry {
834 AST_LIST_ENTRY(signaling_queue_entry) next;
837 /*! table of available call numbers */
838 static struct ao2_container *callno_pool;
840 /*! table of available trunk call numbers */
841 static struct ao2_container *callno_pool_trunk;
843 static const unsigned int CALLNO_POOL_BUCKETS = 2699;
846 * \brief a list of frames that may need to be retransmitted
848 * \note The contents of this list do not need to be explicitly destroyed
849 * on module unload. This is because all active calls are destroyed, and
850 * all frames in this queue will get destroyed as a part of that process.
852 * \note Contents protected by the iaxsl[] locks
854 static AST_LIST_HEAD_NOLOCK(, iax_frame) frame_queue[IAX_MAX_CALLS + 1];
856 static struct ast_taskprocessor *transmit_processor;
858 static int randomcalltokendata;
860 static const time_t MAX_CALLTOKEN_DELAY = 10;
863 * This module will get much higher performance when doing a lot of
864 * user and peer lookups if the number of buckets is increased from 1.
865 * However, to maintain old behavior for Asterisk 1.4, these are set to
866 * 1 by default. When using multiple buckets, search order through these
867 * containers is considered random, so you will not be able to depend on
868 * the order the entires are specified in iax.conf for matching order. */
870 #define MAX_PEER_BUCKETS 17
872 #define MAX_PEER_BUCKETS 563
874 static struct ao2_container *peers;
876 #define MAX_USER_BUCKETS MAX_PEER_BUCKETS
877 static struct ao2_container *users;
879 /*! Table containing peercnt objects for every ip address consuming a callno */
880 static struct ao2_container *peercnts;
882 /*! Table containing custom callno limit rules for a range of ip addresses. */
883 static struct ao2_container *callno_limits;
885 /*! Table containing ip addresses not requiring calltoken validation */
886 static struct ao2_container *calltoken_ignores;
888 static uint16_t DEFAULT_MAXCALLNO_LIMIT = 2048;
890 static uint16_t DEFAULT_MAXCALLNO_LIMIT_NONVAL = 8192;
892 static uint16_t global_maxcallno;
894 /*! Total num of call numbers allowed to be allocated without calltoken validation */
895 static uint16_t global_maxcallno_nonval;
897 static uint16_t total_nonval_callno_used = 0;
899 /*! peer connection private, keeps track of all the call numbers
900 * consumed by a single ip address */
902 /*! ip address consuming call numbers */
904 /*! Number of call numbers currently used by this ip address */
906 /*! Max call numbers allowed for this ip address */
908 /*! Specifies whether limit is set by a registration or not, if so normal
909 * limit setting rules do not apply to this address. */
913 /*! used by both callno_limits and calltoken_ignores containers */
915 /*! ip address range for custom callno limit rule */
917 /*! callno limit for this ip address range, only used in callno_limits container */
919 /*! delete me marker for reloads */
923 struct callno_entry {
924 /*! callno used for this entry */
926 /*! was this callno calltoken validated or not */
927 unsigned char validated;
930 static AST_LIST_HEAD_STATIC(firmwares, iax_firmware);
933 /*! Extension exists */
934 CACHE_FLAG_EXISTS = (1 << 0),
935 /*! Extension is nonexistent */
936 CACHE_FLAG_NONEXISTENT = (1 << 1),
937 /*! Extension can exist */
938 CACHE_FLAG_CANEXIST = (1 << 2),
939 /*! Waiting to hear back response */
940 CACHE_FLAG_PENDING = (1 << 3),
942 CACHE_FLAG_TIMEOUT = (1 << 4),
943 /*! Request transmitted */
944 CACHE_FLAG_TRANSMITTED = (1 << 5),
946 CACHE_FLAG_UNKNOWN = (1 << 6),
948 CACHE_FLAG_MATCHMORE = (1 << 7),
951 struct iax2_dpcache {
952 char peercontext[AST_MAX_CONTEXT];
953 char exten[AST_MAX_EXTENSION];
955 struct timeval expiry;
957 unsigned short callno;
959 AST_LIST_ENTRY(iax2_dpcache) cache_list;
960 AST_LIST_ENTRY(iax2_dpcache) peer_list;
963 static AST_LIST_HEAD_STATIC(dpcache, iax2_dpcache);
965 static void reg_source_db(struct iax2_peer *p);
966 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
967 static struct iax2_user *realtime_user(const char *username, struct sockaddr_in *sin);
969 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt);
970 static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags);
971 static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state);
973 enum iax2_thread_iostate {
976 IAX_IOSTATE_PROCESSING,
977 IAX_IOSTATE_SCHEDREADY,
980 enum iax2_thread_type {
981 IAX_THREAD_TYPE_POOL,
982 IAX_THREAD_TYPE_DYNAMIC,
985 struct iax2_pkt_buf {
986 AST_LIST_ENTRY(iax2_pkt_buf) entry;
988 unsigned char buf[1];
992 AST_LIST_ENTRY(iax2_thread) list;
993 enum iax2_thread_type type;
994 enum iax2_thread_iostate iostate;
995 #ifdef SCHED_MULTITHREADED
996 void (*schedfunc)(const void *);
997 const void *scheddata;
999 #ifdef DEBUG_SCHED_MULTITHREAD
1005 struct sockaddr_in iosin;
1006 unsigned char readbuf[4096];
1014 ast_mutex_t init_lock;
1015 ast_cond_t init_cond;
1016 /*! if this thread is processing a full frame,
1017 some information about that frame will be stored
1018 here, so we can avoid dispatching any more full
1019 frames for that callno to other threads */
1021 unsigned short callno;
1022 struct sockaddr_in sin;
1026 /*! Queued up full frames for processing. If more full frames arrive for
1027 * a call which this thread is already processing a full frame for, they
1028 * are queued up here. */
1029 AST_LIST_HEAD_NOLOCK(, iax2_pkt_buf) full_frames;
1034 static AST_LIST_HEAD_STATIC(idle_list, iax2_thread);
1035 static AST_LIST_HEAD_STATIC(active_list, iax2_thread);
1036 static AST_LIST_HEAD_STATIC(dynamic_list, iax2_thread);
1038 static void *iax2_process_thread(void *data);
1039 static void iax2_destroy(int callno);
1041 static void signal_condition(ast_mutex_t *lock, ast_cond_t *cond)
1043 ast_mutex_lock(lock);
1044 ast_cond_signal(cond);
1045 ast_mutex_unlock(lock);
1049 * \brief an array of iax2 pvt structures
1051 * The container for active chan_iax2_pvt structures is implemented as an
1052 * array for extremely quick direct access to the correct pvt structure
1053 * based on the local call number. The local call number is used as the
1054 * index into the array where the associated pvt structure is stored.
1056 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS + 1];
1059 * \brief Another container of iax2_pvt structures
1061 * Active IAX2 pvt structs are also stored in this container, if they are a part
1062 * of an active call where we know the remote side's call number. The reason
1063 * for this is that incoming media frames do not contain our call number. So,
1064 * instead of having to iterate the entire iaxs array, we use this container to
1065 * look up calls where the remote side is using a given call number.
1067 static struct ao2_container *iax_peercallno_pvts;
1070 * \brief chan_iax2_pvt structure locks
1072 * These locks are used when accessing a pvt structure in the iaxs array.
1073 * The index used here is the same as used in the iaxs array. It is the
1074 * local call number for the associated pvt struct.
1076 static ast_mutex_t iaxsl[ARRAY_LEN(iaxs)];
1079 * * \brief Another container of iax2_pvt structures
1081 * Active IAX2 pvt stucts used during transfering a call are stored here.
1083 static struct ao2_container *iax_transfercallno_pvts;
1085 /* Flag to use with trunk calls, keeping these calls high up. It halves our effective use
1086 but keeps the division between trunked and non-trunked better. */
1087 #define TRUNK_CALL_START IAX_MAX_CALLS / 2
1089 /* Debug routines... */
1090 static struct sockaddr_in debugaddr;
1092 static void iax_outputframe(struct iax_frame *f, struct ast_iax2_full_hdr *fhi, int rx, struct sockaddr_in *sin, int datalen)
1095 (sin && debugaddr.sin_addr.s_addr &&
1096 (!ntohs(debugaddr.sin_port) ||
1097 debugaddr.sin_port == sin->sin_port) &&
1098 debugaddr.sin_addr.s_addr == sin->sin_addr.s_addr)) {
1100 iax_showframe(f, fhi, rx, sin, datalen);
1103 iax_showframe(f, fhi, rx, sin, datalen);
1109 static void iax_debug_output(const char *data)
1112 ast_verbose("%s", data);
1115 static void iax_error_output(const char *data)
1117 ast_log(LOG_WARNING, "%s", data);
1120 static void __attribute__((format(printf, 1, 2))) jb_error_output(const char *fmt, ...)
1125 va_start(args, fmt);
1126 vsnprintf(buf, sizeof(buf), fmt, args);
1129 ast_log(LOG_ERROR, "%s", buf);
1132 static void __attribute__((format(printf, 1, 2))) jb_warning_output(const char *fmt, ...)
1137 va_start(args, fmt);
1138 vsnprintf(buf, sizeof(buf), fmt, args);
1141 ast_log(LOG_WARNING, "%s", buf);
1144 static void __attribute__((format(printf, 1, 2))) jb_debug_output(const char *fmt, ...)
1149 va_start(args, fmt);
1150 vsnprintf(buf, sizeof(buf), fmt, args);
1153 ast_verbose("%s", buf);
1156 static int maxtrunkcall = TRUNK_CALL_START;
1157 static int maxnontrunkcall = 1;
1159 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);
1160 static int expire_registry(const void *data);
1161 static int iax2_answer(struct ast_channel *c);
1162 static int iax2_call(struct ast_channel *c, char *dest, int timeout);
1163 static int iax2_devicestate(void *data);
1164 static int iax2_digit_begin(struct ast_channel *c, char digit);
1165 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration);
1166 static int iax2_do_register(struct iax2_registry *reg);
1167 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
1168 static int iax2_hangup(struct ast_channel *c);
1169 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen);
1170 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
1171 static int iax2_provision(struct sockaddr_in *end, int sockfd, const char *dest, const char *template, int force);
1172 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
1173 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
1174 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
1175 static int iax2_sendtext(struct ast_channel *c, const char *text);
1176 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
1177 static int iax2_queryoption(struct ast_channel *c, int option, void *data, int *datalen);
1178 static int iax2_transfer(struct ast_channel *c, const char *dest);
1179 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
1180 static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now);
1181 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1182 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1183 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1184 static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int);
1185 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
1186 static struct ast_channel *iax2_request(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause);
1187 static struct ast_frame *iax2_read(struct ast_channel *c);
1188 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
1189 static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
1190 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, time_t regtime);
1191 static void *iax2_dup_variable_datastore(void *);
1192 static void prune_peers(void);
1193 static void prune_users(void);
1194 static void iax2_free_variable_datastore(void *);
1196 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
1197 static int decode_frame(ast_aes_decrypt_key *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen);
1198 static int encrypt_frame(ast_aes_encrypt_key *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen);
1199 static void build_ecx_key(const unsigned char *digest, struct chan_iax2_pvt *pvt);
1200 static void build_rand_pad(unsigned char *buf, ssize_t len);
1201 static struct callno_entry *get_unused_callno(int trunk, int validated);
1202 static int replace_callno(const void *obj);
1203 static void sched_delay_remove(struct sockaddr_in *sin, struct callno_entry *callno_entry);
1205 static const struct ast_channel_tech iax2_tech = {
1207 .description = tdesc,
1208 .capabilities = IAX_CAPABILITY_FULLBANDWIDTH,
1209 .properties = AST_CHAN_TP_WANTSJITTER,
1210 .requester = iax2_request,
1211 .devicestate = iax2_devicestate,
1212 .send_digit_begin = iax2_digit_begin,
1213 .send_digit_end = iax2_digit_end,
1214 .send_text = iax2_sendtext,
1215 .send_image = iax2_sendimage,
1216 .send_html = iax2_sendhtml,
1218 .hangup = iax2_hangup,
1219 .answer = iax2_answer,
1221 .write = iax2_write,
1222 .write_video = iax2_write,
1223 .indicate = iax2_indicate,
1224 .setoption = iax2_setoption,
1225 .queryoption = iax2_queryoption,
1226 .bridge = iax2_bridge,
1227 .transfer = iax2_transfer,
1228 .fixup = iax2_fixup,
1229 .func_channel_read = acf_channel_read,
1232 static void mwi_event_cb(const struct ast_event *event, void *userdata)
1234 /* The MWI subscriptions exist just so the core knows we care about those
1235 * mailboxes. However, we just grab the events out of the cache when it
1236 * is time to send MWI, since it is only sent with a REGACK. */
1239 /*! \brief Send manager event at call setup to link between Asterisk channel name
1240 and IAX2 call identifiers */
1241 static void iax2_ami_channelupdate(struct chan_iax2_pvt *pvt)
1243 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
1244 "Channel: %s\r\nChanneltype: IAX2\r\nIAX2-callno-local: %d\r\nIAX2-callno-remote: %d\r\nIAX2-peer: %s\r\n",
1245 pvt->owner ? pvt->owner->name : "",
1246 pvt->callno, pvt->peercallno, pvt->peer ? pvt->peer : "");
1250 static struct ast_datastore_info iax2_variable_datastore_info = {
1251 .type = "IAX2_VARIABLE",
1252 .duplicate = iax2_dup_variable_datastore,
1253 .destroy = iax2_free_variable_datastore,
1256 static void *iax2_dup_variable_datastore(void *old)
1258 AST_LIST_HEAD(, ast_var_t) *oldlist = old, *newlist;
1259 struct ast_var_t *oldvar, *newvar;
1261 newlist = ast_calloc(sizeof(*newlist), 1);
1263 ast_log(LOG_ERROR, "Unable to duplicate iax2 variables\n");
1267 AST_LIST_HEAD_INIT(newlist);
1268 AST_LIST_LOCK(oldlist);
1269 AST_LIST_TRAVERSE(oldlist, oldvar, entries) {
1270 newvar = ast_var_assign(ast_var_name(oldvar), ast_var_value(oldvar));
1272 AST_LIST_INSERT_TAIL(newlist, newvar, entries);
1274 ast_log(LOG_ERROR, "Unable to duplicate iax2 variable '%s'\n", ast_var_name(oldvar));
1276 AST_LIST_UNLOCK(oldlist);
1280 static void iax2_free_variable_datastore(void *old)
1282 AST_LIST_HEAD(, ast_var_t) *oldlist = old;
1283 struct ast_var_t *oldvar;
1285 AST_LIST_LOCK(oldlist);
1286 while ((oldvar = AST_LIST_REMOVE_HEAD(oldlist, entries))) {
1289 AST_LIST_UNLOCK(oldlist);
1290 AST_LIST_HEAD_DESTROY(oldlist);
1295 /* WARNING: insert_idle_thread should only ever be called within the
1296 * context of an iax2_process_thread() thread.
1298 static void insert_idle_thread(struct iax2_thread *thread)
1300 if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
1301 AST_LIST_LOCK(&dynamic_list);
1302 AST_LIST_INSERT_TAIL(&dynamic_list, thread, list);
1303 AST_LIST_UNLOCK(&dynamic_list);
1305 AST_LIST_LOCK(&idle_list);
1306 AST_LIST_INSERT_TAIL(&idle_list, thread, list);
1307 AST_LIST_UNLOCK(&idle_list);
1313 static struct iax2_thread *find_idle_thread(void)
1315 struct iax2_thread *thread = NULL;
1317 /* Pop the head of the idle list off */
1318 AST_LIST_LOCK(&idle_list);
1319 thread = AST_LIST_REMOVE_HEAD(&idle_list, list);
1320 AST_LIST_UNLOCK(&idle_list);
1322 /* If we popped a thread off the idle list, just return it */
1324 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1328 /* Pop the head of the dynamic list off */
1329 AST_LIST_LOCK(&dynamic_list);
1330 thread = AST_LIST_REMOVE_HEAD(&dynamic_list, list);
1331 AST_LIST_UNLOCK(&dynamic_list);
1333 /* If we popped a thread off the dynamic list, just return it */
1335 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1339 /* If we can't create a new dynamic thread for any reason, return no thread at all */
1340 if (iaxdynamicthreadcount >= iaxmaxthreadcount || !(thread = ast_calloc(1, sizeof(*thread))))
1343 /* Set default values */
1344 ast_atomic_fetchadd_int(&iaxdynamicthreadcount, 1);
1345 thread->threadnum = ast_atomic_fetchadd_int(&iaxdynamicthreadnum, 1);
1346 thread->type = IAX_THREAD_TYPE_DYNAMIC;
1348 /* Initialize lock and condition */
1349 ast_mutex_init(&thread->lock);
1350 ast_cond_init(&thread->cond, NULL);
1351 ast_mutex_init(&thread->init_lock);
1352 ast_cond_init(&thread->init_cond, NULL);
1353 ast_mutex_lock(&thread->init_lock);
1355 /* Create thread and send it on it's way */
1356 if (ast_pthread_create_background(&thread->threadid, NULL, iax2_process_thread, thread)) {
1357 ast_cond_destroy(&thread->cond);
1358 ast_mutex_destroy(&thread->lock);
1363 /* this thread is not processing a full frame (since it is idle),
1364 so ensure that the field for the full frame call number is empty */
1365 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1367 /* Wait for the thread to be ready before returning it to the caller */
1368 ast_cond_wait(&thread->init_cond, &thread->init_lock);
1370 /* Done with init_lock */
1371 ast_mutex_unlock(&thread->init_lock);
1376 #ifdef SCHED_MULTITHREADED
1377 static int __schedule_action(void (*func)(const void *data), const void *data, const char *funcname)
1379 struct iax2_thread *thread = NULL;
1380 static time_t lasterror;
1383 thread = find_idle_thread();
1385 if (thread != NULL) {
1386 thread->schedfunc = func;
1387 thread->scheddata = data;
1388 thread->iostate = IAX_IOSTATE_SCHEDREADY;
1389 #ifdef DEBUG_SCHED_MULTITHREAD
1390 ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc));
1392 signal_condition(&thread->lock, &thread->cond);
1397 ast_debug(1, "Out of idle IAX2 threads for scheduling!\n");
1402 #define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
1405 static int iax2_sched_replace(int id, struct ast_sched_thread *st, int when,
1406 ast_sched_cb callback, const void *data)
1408 ast_sched_thread_del(st, id);
1410 return ast_sched_thread_add(st, when, callback, data);
1413 static int iax2_sched_add(struct ast_sched_thread *st, int when,
1414 ast_sched_cb callback, const void *data)
1416 return ast_sched_thread_add(st, when, callback, data);
1419 static int send_ping(const void *data);
1421 static void __send_ping(const void *data)
1423 int callno = (long) data;
1425 ast_mutex_lock(&iaxsl[callno]);
1428 if (iaxs[callno]->peercallno) {
1429 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
1430 iaxs[callno]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, data);
1432 /* I am the schedule, so I'm allowed to do this */
1433 iaxs[callno]->pingid = -1;
1436 ast_debug(1, "I was supposed to send a PING with callno %d, but no such call exists.\n", callno);
1439 ast_mutex_unlock(&iaxsl[callno]);
1442 static int send_ping(const void *data)
1444 #ifdef SCHED_MULTITHREADED
1445 if (schedule_action(__send_ping, data))
1452 static void encmethods_to_str(int e, struct ast_str *buf)
1454 ast_str_set(&buf, 0, "(");
1455 if (e & IAX_ENCRYPT_AES128) {
1456 ast_str_append(&buf, 0, "aes128");
1458 if (e & IAX_ENCRYPT_KEYROTATE) {
1459 ast_str_append(&buf, 0, ",keyrotate");
1461 if (ast_str_strlen(buf) > 1) {
1462 ast_str_append(&buf, 0, ")");
1464 ast_str_set(&buf, 0, "No");
1468 static int get_encrypt_methods(const char *s)
1471 if (!strcasecmp(s, "aes128"))
1472 e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
1473 else if (ast_true(s))
1474 e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
1480 static int send_lagrq(const void *data);
1482 static void __send_lagrq(const void *data)
1484 int callno = (long) data;
1486 ast_mutex_lock(&iaxsl[callno]);
1489 if (iaxs[callno]->peercallno) {
1490 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
1491 iaxs[callno]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, data);
1493 /* I am the schedule, so I'm allowed to do this */
1494 iaxs[callno]->lagid = -1;
1497 ast_debug(1, "I was supposed to send a LAGRQ with callno %d, but no such call exists.\n", callno);
1500 ast_mutex_unlock(&iaxsl[callno]);
1503 static int send_lagrq(const void *data)
1505 #ifdef SCHED_MULTITHREADED
1506 if (schedule_action(__send_lagrq, data))
1513 static unsigned char compress_subclass(format_t subclass)
1517 /* If it's 64 or smaller, just return it */
1518 if (subclass < IAX_FLAG_SC_LOG)
1520 /* Otherwise find its power */
1521 for (x = 0; x < IAX_MAX_SHIFT; x++) {
1522 if (subclass & (1LL << x)) {
1524 ast_log(LOG_WARNING, "Can't compress subclass %lld\n", (long long) subclass);
1530 return power | IAX_FLAG_SC_LOG;
1533 static format_t uncompress_subclass(unsigned char csub)
1535 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
1536 if (csub & IAX_FLAG_SC_LOG) {
1537 /* special case for 'compressed' -1 */
1541 return 1LL << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
1548 * \note The only member of the peer passed here guaranteed to be set is the name field
1550 static int peer_hash_cb(const void *obj, const int flags)
1552 const struct iax2_peer *peer = obj;
1554 return ast_str_hash(peer->name);
1558 * \note The only member of the peer passed here guaranteed to be set is the name field
1560 static int peer_cmp_cb(void *obj, void *arg, int flags)
1562 struct iax2_peer *peer = obj, *peer2 = arg;
1564 return !strcmp(peer->name, peer2->name) ? CMP_MATCH | CMP_STOP : 0;
1568 * \note The only member of the user passed here guaranteed to be set is the name field
1570 static int user_hash_cb(const void *obj, const int flags)
1572 const struct iax2_user *user = obj;
1574 return ast_str_hash(user->name);
1578 * \note The only member of the user passed here guaranteed to be set is the name field
1580 static int user_cmp_cb(void *obj, void *arg, int flags)
1582 struct iax2_user *user = obj, *user2 = arg;
1584 return !strcmp(user->name, user2->name) ? CMP_MATCH | CMP_STOP : 0;
1588 * \note This funtion calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
1589 * so do not call it with a pvt lock held.
1591 static struct iax2_peer *find_peer(const char *name, int realtime)
1593 struct iax2_peer *peer = NULL;
1594 struct iax2_peer tmp_peer = {
1598 peer = ao2_find(peers, &tmp_peer, OBJ_POINTER);
1600 /* Now go for realtime if applicable */
1601 if(!peer && realtime)
1602 peer = realtime_peer(name, NULL);
1607 static struct iax2_peer *peer_ref(struct iax2_peer *peer)
1613 static inline struct iax2_peer *peer_unref(struct iax2_peer *peer)
1619 static struct iax2_user *find_user(const char *name)
1621 struct iax2_user tmp_user = {
1625 return ao2_find(users, &tmp_user, OBJ_POINTER);
1627 static inline struct iax2_user *user_ref(struct iax2_user *user)
1633 static inline struct iax2_user *user_unref(struct iax2_user *user)
1639 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len)
1641 struct iax2_peer *peer = NULL;
1643 struct ao2_iterator i;
1645 i = ao2_iterator_init(peers, 0);
1646 while ((peer = ao2_iterator_next(&i))) {
1647 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
1648 (peer->addr.sin_port == sin.sin_port)) {
1649 ast_copy_string(host, peer->name, len);
1656 ao2_iterator_destroy(&i);
1659 peer = realtime_peer(NULL, &sin);
1661 ast_copy_string(host, peer->name, len);
1670 /*!\note Assumes the lock on the pvt is already held, when
1671 * iax2_destroy_helper() is called. */
1672 static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
1674 /* Decrement AUTHREQ count if needed */
1675 if (ast_test_flag64(pvt, IAX_MAXAUTHREQ)) {
1676 struct iax2_user *user;
1677 struct iax2_user tmp_user = {
1678 .name = pvt->username,
1681 user = ao2_find(users, &tmp_user, OBJ_POINTER);
1683 ast_atomic_fetchadd_int(&user->curauthreq, -1);
1687 ast_clear_flag64(pvt, IAX_MAXAUTHREQ);
1689 /* No more pings or lagrq's */
1690 AST_SCHED_DEL_SPINLOCK(ast_sched_thread_get_context(sched), pvt->pingid, &iaxsl[pvt->callno]);
1691 AST_SCHED_DEL_SPINLOCK(ast_sched_thread_get_context(sched), pvt->lagid, &iaxsl[pvt->callno]);
1692 ast_sched_thread_del(sched, pvt->autoid);
1693 ast_sched_thread_del(sched, pvt->authid);
1694 ast_sched_thread_del(sched, pvt->initid);
1695 ast_sched_thread_del(sched, pvt->jbid);
1696 ast_sched_thread_del(sched, pvt->keyrotateid);
1699 static void iax2_frame_free(struct iax_frame *fr)
1701 ast_sched_thread_del(sched, fr->retrans);
1705 static int scheduled_destroy(const void *vid)
1707 unsigned short callno = PTR_TO_CALLNO(vid);
1708 ast_mutex_lock(&iaxsl[callno]);
1711 ast_log(LOG_DEBUG, "Really destroying %d now...\n", callno);
1713 iax2_destroy(callno);
1715 ast_mutex_unlock(&iaxsl[callno]);
1719 static void free_signaling_queue_entry(struct signaling_queue_entry *s)
1721 ast_free(s->f.data.ptr);
1725 /*! \brief This function must be called once we are sure the other side has
1726 * given us a call number. All signaling is held here until that point. */
1727 static void send_signaling(struct chan_iax2_pvt *pvt)
1729 struct signaling_queue_entry *s = NULL;
1731 while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
1732 iax2_send(pvt, &s->f, 0, -1, 0, 0, 0);
1733 free_signaling_queue_entry(s);
1735 pvt->hold_signaling = 0;
1738 /*! \brief All frames other than that of type AST_FRAME_IAX must be held until
1739 * we have received a destination call number. */
1740 static int queue_signalling(struct chan_iax2_pvt *pvt, struct ast_frame *f)
1742 struct signaling_queue_entry *new;
1744 if (f->frametype == AST_FRAME_IAX || !pvt->hold_signaling) {
1745 return 1; /* do not queue this frame */
1746 } else if (!(new = ast_calloc(1, sizeof(struct signaling_queue_entry)))) {
1747 return -1; /* out of memory */
1750 memcpy(&new->f, f, sizeof(new->f)); /* copy ast_frame into our queue entry */
1752 if (new->f.datalen) { /* if there is data in this frame copy it over as well */
1753 if (!(new->f.data.ptr = ast_calloc(1, new->f.datalen))) {
1754 free_signaling_queue_entry(new);
1757 memcpy(new->f.data.ptr, f->data.ptr, sizeof(*new->f.data.ptr));
1759 AST_LIST_INSERT_TAIL(&pvt->signaling_queue, new, next);
1764 static void pvt_destructor(void *obj)
1766 struct chan_iax2_pvt *pvt = obj;
1767 struct iax_frame *cur = NULL;
1768 struct signaling_queue_entry *s = NULL;
1770 ast_mutex_lock(&iaxsl[pvt->callno]);
1772 iax2_destroy_helper(pvt);
1774 sched_delay_remove(&pvt->addr, pvt->callno_entry);
1775 pvt->callno_entry = NULL;
1778 ast_set_flag64(pvt, IAX_ALREADYGONE);
1780 AST_LIST_TRAVERSE(&frame_queue[pvt->callno], cur, list) {
1781 /* Cancel any pending transmissions */
1785 ast_mutex_unlock(&iaxsl[pvt->callno]);
1787 while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
1788 free_signaling_queue_entry(s);
1792 pvt->reg->callno = 0;
1798 ast_variables_destroy(pvt->vars);
1802 while (jb_getall(pvt->jb, &frame) == JB_OK) {
1803 iax2_frame_free(frame.data);
1806 jb_destroy(pvt->jb);
1807 ast_string_field_free_memory(pvt);
1811 static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, const char *host)
1813 struct chan_iax2_pvt *tmp;
1816 if (!(tmp = ao2_alloc(sizeof(*tmp), pvt_destructor))) {
1820 if (ast_string_field_init(tmp, 32)) {
1832 tmp->keyrotateid = -1;
1834 ast_string_field_set(tmp,exten, "s");
1835 ast_string_field_set(tmp,host, host);
1839 jbconf.max_jitterbuf = maxjitterbuffer;
1840 jbconf.resync_threshold = resyncthreshold;
1841 jbconf.max_contig_interp = maxjitterinterps;
1842 jbconf.target_extra = jittertargetextra;
1843 jb_setconf(tmp->jb,&jbconf);
1845 AST_LIST_HEAD_INIT_NOLOCK(&tmp->dpentries);
1847 tmp->hold_signaling = 1;
1848 AST_LIST_HEAD_INIT_NOLOCK(&tmp->signaling_queue);
1853 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
1855 struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen, fr->cacheable);
1857 size_t afdatalen = new->afdatalen;
1858 memcpy(new, fr, sizeof(*new));
1859 iax_frame_wrap(new, &fr->af);
1860 new->afdatalen = afdatalen;
1863 new->direction = DIRECTION_INGRESS;
1868 /* keep these defined in this order. They are used in find_callno to
1869 * determine whether or not a new call number should be allowed. */
1871 /* do not allow a new call number, only search ones in use for match */
1873 /* search for match first, then allow a new one to be allocated */
1875 /* do not search for match, force a new call number */
1877 /* do not search for match, force a new call number. Signifies call number
1878 * has been calltoken validated */
1879 NEW_ALLOW_CALLTOKEN_VALIDATED = 3,
1882 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, const struct chan_iax2_pvt *cur, int check_dcallno)
1884 if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
1885 (cur->addr.sin_port == sin->sin_port)) {
1886 /* This is the main host */
1887 if ( (cur->peercallno == 0 || cur->peercallno == callno) &&
1888 (check_dcallno ? dcallno == cur->callno : 1) ) {
1889 /* That's us. Be sure we keep track of the peer call number */
1893 if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
1894 (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
1895 /* We're transferring */
1896 if ((dcallno == cur->callno) || (cur->transferring == TRANSFER_MEDIAPASS && cur->transfercallno == callno))
1902 static void update_max_trunk(void)
1904 int max = TRUNK_CALL_START;
1907 /* XXX Prolly don't need locks here XXX */
1908 for (x = TRUNK_CALL_START; x < ARRAY_LEN(iaxs) - 1; x++) {
1916 ast_debug(1, "New max trunk callno is %d\n", max);
1919 static void update_max_nontrunk(void)
1923 /* XXX Prolly don't need locks here XXX */
1924 for (x=1;x<TRUNK_CALL_START - 1; x++) {
1928 maxnontrunkcall = max;
1930 ast_debug(1, "New max nontrunk callno is %d\n", max);
1933 static int make_trunk(unsigned short callno, int locked)
1937 struct callno_entry *callno_entry;
1938 if (iaxs[callno]->oseqno) {
1939 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
1942 if (callno & TRUNK_CALL_START) {
1943 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
1947 if (!(callno_entry = get_unused_callno(1, iaxs[callno]->callno_entry->validated))) {
1948 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
1952 x = callno_entry->callno;
1953 ast_mutex_lock(&iaxsl[x]);
1956 * \note We delete these before switching the slot, because if
1957 * they fire in the meantime, they will generate a warning.
1959 ast_sched_thread_del(sched, iaxs[callno]->pingid);
1960 ast_sched_thread_del(sched, iaxs[callno]->lagid);
1961 iaxs[callno]->lagid = iaxs[callno]->pingid = -1;
1962 iaxs[x] = iaxs[callno];
1963 iaxs[x]->callno = x;
1965 /* since we copied over the pvt from a different callno, make sure the old entry is replaced
1966 * before assigning the new one */
1967 if (iaxs[x]->callno_entry) {
1968 iax2_sched_add(sched, MIN_REUSE_TIME * 1000, replace_callno, iaxs[x]->callno_entry);
1970 iaxs[x]->callno_entry = callno_entry;
1972 iaxs[callno] = NULL;
1973 /* Update the two timers that should have been started */
1974 iaxs[x]->pingid = iax2_sched_add(sched,
1975 ping_time * 1000, send_ping, (void *)(long)x);
1976 iaxs[x]->lagid = iax2_sched_add(sched,
1977 lagrq_time * 1000, send_lagrq, (void *)(long)x);
1980 ast_mutex_unlock(&iaxsl[callno]);
1983 ast_mutex_unlock(&iaxsl[x]);
1985 ast_debug(1, "Made call %d into trunk call %d\n", callno, x);
1986 /* We move this call from a non-trunked to a trunked call */
1988 update_max_nontrunk();
1992 static void store_by_transfercallno(struct chan_iax2_pvt *pvt)
1994 if (!pvt->transfercallno) {
1995 ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
1999 ao2_link(iax_transfercallno_pvts, pvt);
2002 static void remove_by_transfercallno(struct chan_iax2_pvt *pvt)
2004 if (!pvt->transfercallno) {
2005 ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
2009 ao2_unlink(iax_transfercallno_pvts, pvt);
2011 static void store_by_peercallno(struct chan_iax2_pvt *pvt)
2013 if (!pvt->peercallno) {
2014 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
2018 ao2_link(iax_peercallno_pvts, pvt);
2021 static void remove_by_peercallno(struct chan_iax2_pvt *pvt)
2023 if (!pvt->peercallno) {
2024 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
2028 ao2_unlink(iax_peercallno_pvts, pvt);
2031 static int addr_range_delme_cb(void *obj, void *arg, int flags)
2033 struct addr_range *lim = obj;
2038 static int addr_range_hash_cb(const void *obj, const int flags)
2040 const struct addr_range *lim = obj;
2041 struct sockaddr_in sin;
2042 ast_sockaddr_to_sin(&lim->ha.addr, &sin);
2043 return abs((int) sin.sin_addr.s_addr);
2046 static int addr_range_cmp_cb(void *obj, void *arg, int flags)
2048 struct addr_range *lim1 = obj, *lim2 = arg;
2049 return (!(ast_sockaddr_cmp_addr(&lim1->ha.addr, &lim2->ha.addr)) &&
2050 !(ast_sockaddr_cmp_addr(&lim1->ha.netmask, &lim2->ha.netmask))) ?
2051 CMP_MATCH | CMP_STOP : 0;
2054 static int peercnt_hash_cb(const void *obj, const int flags)
2056 const struct peercnt *peercnt = obj;
2057 return abs((int) peercnt->addr);
2060 static int peercnt_cmp_cb(void *obj, void *arg, int flags)
2062 struct peercnt *peercnt1 = obj, *peercnt2 = arg;
2063 return (peercnt1->addr == peercnt2->addr) ? CMP_MATCH | CMP_STOP : 0;
2066 static int addr_range_match_address_cb(void *obj, void *arg, int flags)
2068 struct addr_range *addr_range = obj;
2069 struct sockaddr_in *sin = arg;
2070 struct sockaddr_in ha_netmask_sin;
2071 struct sockaddr_in ha_addr_sin;
2073 ast_sockaddr_to_sin(&addr_range->ha.netmask, &ha_netmask_sin);
2074 ast_sockaddr_to_sin(&addr_range->ha.addr, &ha_addr_sin);
2076 if ((sin->sin_addr.s_addr & ha_netmask_sin.sin_addr.s_addr) == ha_addr_sin.sin_addr.s_addr) {
2077 return CMP_MATCH | CMP_STOP;
2085 * \brief compares sin to calltoken_ignores table to determine if validation is required.
2087 static int calltoken_required(struct sockaddr_in *sin, const char *name, int subclass)
2089 struct addr_range *addr_range;
2090 struct iax2_peer *peer = NULL;
2091 struct iax2_user *user = NULL;
2092 /* if no username is given, check for guest accounts */
2093 const char *find = S_OR(name, "guest");
2094 int res = 1; /* required by default */
2096 enum calltoken_peer_enum calltoken_required = CALLTOKEN_DEFAULT;
2097 /* There are only two cases in which calltoken validation is not required.
2098 * Case 1. sin falls within the list of address ranges specified in the calltoken optional table and
2099 * the peer definition has not set the requirecalltoken option.
2100 * Case 2. Username is a valid peer/user, and that peer has requirecalltoken set either auto or no.
2103 /* ----- Case 1 ----- */
2104 if ((addr_range = ao2_callback(calltoken_ignores, 0, addr_range_match_address_cb, sin))) {
2105 ao2_ref(addr_range, -1);
2109 /* ----- Case 2 ----- */
2110 if ((subclass == IAX_COMMAND_NEW) && (user = find_user(find))) {
2111 calltoken_required = user->calltoken_required;
2112 } else if ((subclass == IAX_COMMAND_NEW) && (user = realtime_user(find, sin))) {
2113 calltoken_required = user->calltoken_required;
2114 } else if ((subclass != IAX_COMMAND_NEW) && (peer = find_peer(find, 0))) {
2115 calltoken_required = peer->calltoken_required;
2116 } else if ((subclass != IAX_COMMAND_NEW) && (peer = realtime_peer(find, sin))) {
2117 calltoken_required = peer->calltoken_required;
2127 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);
2128 if (((calltoken_required == CALLTOKEN_NO) || (calltoken_required == CALLTOKEN_AUTO)) ||
2129 (optional && (calltoken_required == CALLTOKEN_DEFAULT))) {
2139 * \brief set peercnt callno limit.
2142 * First looks in custom definitions. If not found, global limit
2143 * is used. Entries marked as reg already have
2144 * a custom limit set by a registration and are not modified.
2146 static void set_peercnt_limit(struct peercnt *peercnt)
2148 uint16_t limit = global_maxcallno;
2149 struct addr_range *addr_range;
2150 struct sockaddr_in sin = {
2151 .sin_addr.s_addr = peercnt->addr,
2155 if (peercnt->reg && peercnt->limit) {
2156 return; /* this peercnt has a custom limit set by a registration */
2159 if ((addr_range = ao2_callback(callno_limits, 0, addr_range_match_address_cb, &sin))) {
2160 limit = addr_range->limit;
2161 ast_debug(1, "custom addr_range %d found for %s\n", limit, ast_inet_ntoa(sin.sin_addr));
2162 ao2_ref(addr_range, -1);
2165 peercnt->limit = limit;
2170 * \brief sets limits for all peercnts in table. done on reload to reflect changes in conf.
2172 static int set_peercnt_limit_all_cb(void *obj, void *arg, int flags)
2174 struct peercnt *peercnt = obj;
2176 set_peercnt_limit(peercnt);
2177 ast_debug(1, "Reset limits for peercnts table\n");
2184 * \brief returns match if delme is set.
2186 static int prune_addr_range_cb(void *obj, void *arg, int flags)
2188 struct addr_range *addr_range = obj;
2190 return addr_range->delme ? CMP_MATCH : 0;
2195 * \brief modifies peercnt entry in peercnts table. Used to set custom limit or mark a registered ip
2197 static void peercnt_modify(unsigned char reg, uint16_t limit, struct sockaddr_in *sin)
2199 /* this function turns off and on custom callno limits set by peer registration */
2200 struct peercnt *peercnt;
2201 struct peercnt tmp = {
2202 .addr = sin->sin_addr.s_addr,
2205 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2208 peercnt->limit = limit;
2210 set_peercnt_limit(peercnt);
2212 ast_debug(1, "peercnt entry %s modified limit:%d registered:%d", ast_inet_ntoa(sin->sin_addr), peercnt->limit, peercnt->reg);
2213 ao2_ref(peercnt, -1); /* decrement ref from find */
2219 * \brief adds an ip to the peercnts table, increments connection count if it already exists
2221 * \details First searches for the address in the peercnts table. If found
2222 * the current count is incremented. If not found a new peercnt is allocated
2223 * and linked into the peercnts table with a call number count of 1.
2225 static int peercnt_add(struct sockaddr_in *sin)
2227 struct peercnt *peercnt;
2228 unsigned long addr = sin->sin_addr.s_addr;
2230 struct peercnt tmp = {
2234 /* Reasoning for peercnts container lock: Two identical ip addresses
2235 * could be added by different threads at the "same time". Without the container
2236 * lock, both threads could alloc space for the same object and attempt
2237 * to link to table. With the lock, one would create the object and link
2238 * to table while the other would find the already created peercnt object
2239 * rather than creating a new one. */
2241 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2243 } else if ((peercnt = ao2_alloc(sizeof(*peercnt), NULL))) {
2245 /* create and set defaults */
2246 peercnt->addr = addr;
2247 set_peercnt_limit(peercnt);
2248 /* guarantees it does not go away after unlocking table
2249 * ao2_find automatically adds this */
2250 ao2_link(peercnts, peercnt);
2252 ao2_unlock(peercnts);
2256 /* check to see if the address has hit its callno limit. If not increment cur. */
2257 if (peercnt->limit > peercnt->cur) {
2259 ast_debug(1, "ip callno count incremented to %d for %s\n", peercnt->cur, ast_inet_ntoa(sin->sin_addr));
2260 } else { /* max num call numbers for this peer has been reached! */
2261 ast_log(LOG_ERROR, "maxcallnumber limit of %d for %s has been reached!\n", peercnt->limit, ast_inet_ntoa(sin->sin_addr));
2265 /* clean up locks and ref count */
2266 ao2_unlock(peercnt);
2267 ao2_unlock(peercnts);
2268 ao2_ref(peercnt, -1); /* decrement ref from find/alloc, only the container ref remains. */
2275 * \brief decrements a peercnts table entry
2277 static void peercnt_remove(struct peercnt *peercnt)
2279 struct sockaddr_in sin = {
2280 .sin_addr.s_addr = peercnt->addr,
2284 /* Container locked here since peercnt may be unlinked from list. If left unlocked,
2285 * peercnt_add could try and grab this entry from the table and modify it at the
2286 * "same time" this thread attemps to unlink it.*/
2289 ast_debug(1, "ip callno count decremented to %d for %s\n", peercnt->cur, ast_inet_ntoa(sin.sin_addr));
2290 /* if this was the last connection from the peer remove it from table */
2291 if (peercnt->cur == 0) {
2292 ao2_unlink(peercnts, peercnt);/* decrements ref from table, last ref is left to scheduler */
2294 ao2_unlock(peercnts);
2300 * \brief called by scheduler to decrement object
2302 static int peercnt_remove_cb(const void *obj)
2304 struct peercnt *peercnt = (struct peercnt *) obj;
2306 peercnt_remove(peercnt);
2307 ao2_ref(peercnt, -1); /* decrement ref from scheduler */
2314 * \brief decrements peercnts connection count, finds by addr
2316 static int peercnt_remove_by_addr(struct sockaddr_in *sin)
2318 struct peercnt *peercnt;
2319 struct peercnt tmp = {
2320 .addr = sin->sin_addr.s_addr,
2323 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2324 peercnt_remove(peercnt);
2325 ao2_ref(peercnt, -1); /* decrement ref from find */
2332 * \brief Create callno_limit entry based on configuration
2334 static void build_callno_limits(struct ast_variable *v)
2336 struct addr_range *addr_range = NULL;
2337 struct addr_range tmp;
2343 for (; v; v = v->next) {
2347 ha = ast_append_ha("permit", v->name, NULL, &error);
2349 /* check for valid config information */
2351 ast_log(LOG_ERROR, "Call number limit for %s could not be added, Invalid address range\n.", v->name);
2353 } else if ((sscanf(v->value, "%d", &limit) != 1) || (limit < 0)) {
2354 ast_log(LOG_ERROR, "Call number limit for %s could not be added. Invalid limit %s\n.", v->name, v->value);
2359 ast_copy_ha(ha, &tmp.ha);
2360 /* find or create the addr_range */
2361 if ((addr_range = ao2_find(callno_limits, &tmp, OBJ_POINTER))) {
2362 ao2_lock(addr_range);
2364 } else if (!(addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
2366 return; /* out of memory */
2369 /* copy over config data into addr_range object */
2370 ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible for each limit */
2371 ast_free_ha(ha); /* cleanup the tmp ha */
2372 addr_range->limit = limit;
2373 addr_range->delme = 0;
2377 ao2_unlock(addr_range);
2379 ao2_link(callno_limits, addr_range);
2381 ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
2387 * \brief Create calltoken_ignores entry based on configuration
2389 static int add_calltoken_ignore(const char *addr)
2391 struct addr_range tmp;
2392 struct addr_range *addr_range = NULL;
2393 struct ast_ha *ha = NULL;
2396 if (ast_strlen_zero(addr)) {
2397 ast_log(LOG_WARNING, "invalid calltokenoptional %s\n", addr);
2401 ha = ast_append_ha("permit", addr, NULL, &error);
2403 /* check for valid config information */
2405 ast_log(LOG_WARNING, "Error %d creating calltokenoptional entry %s\n", error, addr);
2409 ast_copy_ha(ha, &tmp.ha);
2410 /* find or create the addr_range */
2411 if ((addr_range = ao2_find(calltoken_ignores, &tmp, OBJ_POINTER))) {
2412 ao2_lock(addr_range);
2413 addr_range->delme = 0;
2414 ao2_unlock(addr_range);
2415 } else if ((addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
2416 /* copy over config data into addr_range object */
2417 ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible */
2418 ao2_link(calltoken_ignores, addr_range);
2425 ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
2430 static char *handle_cli_iax2_show_callno_limits(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2432 struct ao2_iterator i;
2433 struct peercnt *peercnt;
2434 struct sockaddr_in sin;
2439 e->command = "iax2 show callnumber usage";
2441 "Usage: iax2 show callnumber usage [IP address]\n"
2442 " Shows current IP addresses which are consuming iax2 call numbers\n";
2447 if (a->argc < 4 || a->argc > 5)
2448 return CLI_SHOWUSAGE;
2450 ast_cli(a->fd, "%-15s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
2451 i = ao2_iterator_init(peercnts, 0);
2452 while ((peercnt = ao2_iterator_next(&i))) {
2453 sin.sin_addr.s_addr = peercnt->addr;
2454 if (a->argc == 5 && (!strcasecmp(a->argv[4], ast_inet_ntoa(sin.sin_addr)))) {
2455 ast_cli(a->fd, "%-15s %-12d %-12d\n", ast_inet_ntoa(sin.sin_addr), peercnt->cur, peercnt->limit);
2459 ast_cli(a->fd, "%-15s %-12d %-12d\n", ast_inet_ntoa(sin.sin_addr), peercnt->cur, peercnt->limit);
2461 ao2_ref(peercnt, -1);
2463 ao2_iterator_destroy(&i);
2466 ast_cli(a->fd, "\nNon-CallToken Validation Callno Limit: %d\n"
2467 "Non-CallToken Validated Callno Used: %d\n",
2468 global_maxcallno_nonval,
2469 total_nonval_callno_used);
2471 ast_cli(a->fd, "Total Available Callno: %d\n"
2472 "Regular Callno Available: %d\n"
2473 "Trunk Callno Available: %d\n",
2474 ao2_container_count(callno_pool) + ao2_container_count(callno_pool_trunk),
2475 ao2_container_count(callno_pool),
2476 ao2_container_count(callno_pool_trunk));
2477 } else if (a->argc == 5 && !found) {
2478 ast_cli(a->fd, "No callnumber table entries for %s found\n", a->argv[4] );
2488 static struct callno_entry *get_unused_callno(int trunk, int validated)
2490 struct callno_entry *callno_entry = NULL;
2491 if ((!ao2_container_count(callno_pool) && !trunk) || (!ao2_container_count(callno_pool_trunk) && trunk)) {
2492 ast_log(LOG_WARNING, "Out of CallNumbers\n");
2493 /* Minor optimization for the extreme case. */
2497 /* the callno_pool container is locked here primarily to ensure thread
2498 * safety of the total_nonval_callno_used check and increment */
2499 ao2_lock(callno_pool);
2501 /* only a certain number of nonvalidated call numbers should be allocated.
2502 * If there ever is an attack, this separates the calltoken validating
2503 * users from the non calltoken validating users. */
2504 if (!validated && (total_nonval_callno_used >= global_maxcallno_nonval)) {
2505 ast_log(LOG_WARNING, "NON-CallToken callnumber limit is reached. Current:%d Max:%d\n", total_nonval_callno_used, global_maxcallno_nonval);
2506 ao2_unlock(callno_pool);
2510 /* unlink the object from the container, taking over ownership
2511 * of the reference the container had to the object */
2512 callno_entry = ao2_find((trunk ? callno_pool_trunk : callno_pool), NULL, OBJ_POINTER | OBJ_UNLINK | OBJ_CONTINUE);
2515 callno_entry->validated = validated;
2517 total_nonval_callno_used++;
2521 ao2_unlock(callno_pool);
2522 return callno_entry;
2525 static int replace_callno(const void *obj)
2527 struct callno_entry *callno_entry = (struct callno_entry *) obj;
2529 /* the callno_pool container is locked here primarily to ensure thread
2530 * safety of the total_nonval_callno_used check and decrement */
2531 ao2_lock(callno_pool);
2533 if (!callno_entry->validated && (total_nonval_callno_used != 0)) {
2534 total_nonval_callno_used--;
2535 } else if (!callno_entry->validated && (total_nonval_callno_used == 0)) {
2536 ast_log(LOG_ERROR, "Attempted to decrement total non calltoken validated callnumbers below zero... Callno is:%d \n", callno_entry->callno);
2539 if (callno_entry->callno < TRUNK_CALL_START) {
2540 ao2_link(callno_pool, callno_entry);
2542 ao2_link(callno_pool_trunk, callno_entry);
2544 ao2_ref(callno_entry, -1); /* only container ref remains */
2546 ao2_unlock(callno_pool);
2550 static int callno_hash(const void *obj, const int flags)
2552 return abs(ast_random());
2555 static int create_callno_pools(void)
2559 if (!(callno_pool = ao2_container_alloc(CALLNO_POOL_BUCKETS, callno_hash, NULL))) {
2563 if (!(callno_pool_trunk = ao2_container_alloc(CALLNO_POOL_BUCKETS, callno_hash, NULL))) {
2567 /* start at 2, 0 and 1 are reserved */
2568 for (i = 2; i <= IAX_MAX_CALLS; i++) {
2569 struct callno_entry *callno_entry;
2571 if (!(callno_entry = ao2_alloc(sizeof(*callno_entry), NULL))) {
2575 callno_entry->callno = i;
2577 if (i < TRUNK_CALL_START) {
2578 ao2_link(callno_pool, callno_entry);
2580 ao2_link(callno_pool_trunk, callno_entry);
2583 ao2_ref(callno_entry, -1);
2591 * \brief Schedules delayed removal of iax2_pvt call number data
2593 * \note After MIN_REUSE_TIME has passed for a destroyed iax2_pvt, the callno is
2594 * avaliable again, and the address from the previous connection must be decremented
2595 * from the peercnts table. This function schedules these operations to take place.
2597 static void sched_delay_remove(struct sockaddr_in *sin, struct callno_entry *callno_entry)
2600 struct peercnt *peercnt;
2601 struct peercnt tmp = {
2602 .addr = sin->sin_addr.s_addr,
2605 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2606 /* refcount is incremented with ao2_find. keep that ref for the scheduler */
2607 ast_debug(1, "schedule decrement of callno used for %s in %d seconds\n", ast_inet_ntoa(sin->sin_addr), MIN_REUSE_TIME);
2608 i = iax2_sched_add(sched, MIN_REUSE_TIME * 1000, peercnt_remove_cb, peercnt);
2610 ao2_ref(peercnt, -1);
2614 iax2_sched_add(sched, MIN_REUSE_TIME * 1000, replace_callno, callno_entry);
2619 * \brief returns whether or not a frame is capable of starting a new IAX2 dialog.
2621 * \note For this implementation, inbound pokes should _NOT_ be capable of allocating
2624 static inline int attribute_pure iax2_allow_new(int frametype, int subclass, int inbound)
2626 if (frametype != AST_FRAME_IAX) {
2630 case IAX_COMMAND_NEW:
2631 case IAX_COMMAND_REGREQ:
2632 case IAX_COMMAND_FWDOWNL:
2633 case IAX_COMMAND_REGREL:
2635 case IAX_COMMAND_POKE:
2645 * \note Calling this function while holding another pvt lock can cause a deadlock.
2647 static int __find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int return_locked, int check_dcallno)
2651 /* this call is calltoken validated as long as it is either NEW_FORCE
2652 * or NEW_ALLOW_CALLTOKEN_VALIDATED */
2653 int validated = (new > NEW_ALLOW) ? 1 : 0;
2656 if (new <= NEW_ALLOW) {
2658 struct chan_iax2_pvt *pvt;
2659 struct chan_iax2_pvt tmp_pvt = {
2661 .peercallno = callno,
2662 .transfercallno = callno,
2664 .frames_received = check_dcallno,
2667 memcpy(&tmp_pvt.addr, sin, sizeof(tmp_pvt.addr));
2668 /* this works for finding normal call numbers not involving transfering */
2669 if ((pvt = ao2_find(iax_peercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
2670 if (return_locked) {
2671 ast_mutex_lock(&iaxsl[pvt->callno]);
2678 /* this searches for transfer call numbers that might not get caught otherwise */
2679 memset(&tmp_pvt.addr, 0, sizeof(tmp_pvt.addr));
2680 memcpy(&tmp_pvt.transfer, sin, sizeof(tmp_pvt.transfer));
2681 if ((pvt = ao2_find(iax_transfercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
2682 if (return_locked) {
2683 ast_mutex_lock(&iaxsl[pvt->callno]);
2691 /* This will occur on the first response to a message that we initiated,
2692 * such as a PING. */
2694 ast_mutex_lock(&iaxsl[dcallno]);
2696 if (callno && dcallno && iaxs[dcallno] && !iaxs[dcallno]->peercallno && match(sin, callno, dcallno, iaxs[dcallno], check_dcallno)) {
2697 iaxs[dcallno]->peercallno = callno;
2699 store_by_peercallno(iaxs[dcallno]);
2700 if (!res || !return_locked) {
2701 ast_mutex_unlock(&iaxsl[dcallno]);
2706 ast_mutex_unlock(&iaxsl[dcallno]);
2709 /* If we get here, we SHOULD NOT find a call structure for this
2710 callno; if we do, it means that there is a call structure that
2711 has a peer callno but did NOT get entered into the hash table,
2714 If we find a call structure using this old, slow method, output a log
2715 message so we'll know about it. After a few months of leaving this in
2716 place, if we don't hear about people seeing these messages, we can
2717 remove this code for good.
2720 for (x = 1; !res && x < maxnontrunkcall; x++) {
2721 ast_mutex_lock(&iaxsl[x]);
2723 /* Look for an exact match */
2724 if (match(sin, callno, dcallno, iaxs[x], check_dcallno)) {
2728 if (!res || !return_locked)
2729 ast_mutex_unlock(&iaxsl[x]);
2731 for (x = TRUNK_CALL_START; !res && x < maxtrunkcall; x++) {
2732 ast_mutex_lock(&iaxsl[x]);
2734 /* Look for an exact match */
2735 if (match(sin, callno, dcallno, iaxs[x], check_dcallno)) {
2739 if (!res || !return_locked)
2740 ast_mutex_unlock(&iaxsl[x]);
2744 if (!res && (new >= NEW_ALLOW)) {
2745 struct callno_entry *callno_entry;
2746 /* It may seem odd that we look through the peer list for a name for
2747 * this *incoming* call. Well, it is weird. However, users don't
2748 * have an IP address/port number that we can match against. So,
2749 * this is just checking for a peer that has that IP/port and
2750 * assuming that we have a user of the same name. This isn't always
2751 * correct, but it will be changed if needed after authentication. */
2752 if (!iax2_getpeername(*sin, host, sizeof(host)))
2753 snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
2755 if (peercnt_add(sin)) {
2756 /* This address has hit its callnumber limit. When the limit
2757 * is reached, the connection is not added to the peercnts table.*/
2761 if (!(callno_entry = get_unused_callno(0, validated))) {
2762 /* since we ran out of space, remove the peercnt
2763 * entry we added earlier */
2764 peercnt_remove_by_addr(sin);
2765 ast_log(LOG_WARNING, "No more space\n");
2768 x = callno_entry->callno;
2769 ast_mutex_lock(&iaxsl[x]);
2771 iaxs[x] = new_iax(sin, host);
2772 update_max_nontrunk();
2775 ast_debug(1, "Creating new call structure %d\n", x);
2776 iaxs[x]->callno_entry = callno_entry;
2777 iaxs[x]->sockfd = sockfd;
2778 iaxs[x]->addr.sin_port = sin->sin_port;
2779 iaxs[x]->addr.sin_family = sin->sin_family;
2780 iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
2781 iaxs[x]->peercallno = callno;
2782 iaxs[x]->callno = x;
2783 iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
2784 iaxs[x]->expiry = min_reg_expire;
2785 iaxs[x]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
2786 iaxs[x]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
2787 iaxs[x]->amaflags = amaflags;
2788 ast_copy_flags64(iaxs[x], &globalflags, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE | IAX_FORCE_ENCRYPT);
2789 ast_string_field_set(iaxs[x], accountcode, accountcode);
2790 ast_string_field_set(iaxs[x], mohinterpret, mohinterpret);
2791 ast_string_field_set(iaxs[x], mohsuggest, mohsuggest);
2792 ast_string_field_set(iaxs[x], parkinglot, default_parkinglot);
2794 if (iaxs[x]->peercallno) {
2795 store_by_peercallno(iaxs[x]);
2798 ast_log(LOG_WARNING, "Out of resources\n");
2799 ast_mutex_unlock(&iaxsl[x]);
2800 replace_callno(callno_entry);
2804 ast_mutex_unlock(&iaxsl[x]);
2810 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
2812 return __find_callno(callno, dcallno, sin, new, sockfd, 0, full_frame);
2815 static int find_callno_locked(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
2817 return __find_callno(callno, dcallno, sin, new, sockfd, 1, full_frame);
2821 * \brief Queue a frame to a call's owning asterisk channel
2823 * \pre This function assumes that iaxsl[callno] is locked when called.
2825 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
2826 * was valid before calling it, it may no longer be valid after calling it.
2827 * This function may unlock and lock the mutex associated with this callno,
2828 * meaning that another thread may grab it and destroy the call.
2830 static int iax2_queue_frame(int callno, struct ast_frame *f)
2833 if (iaxs[callno] && iaxs[callno]->owner) {
2834 if (ast_channel_trylock(iaxs[callno]->owner)) {
2835 /* Avoid deadlock by pausing and trying again */
2836 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
2838 ast_queue_frame(iaxs[callno]->owner, f);
2839 ast_channel_unlock(iaxs[callno]->owner);
2849 * \brief Queue a hangup frame on the ast_channel owner
2851 * This function queues a hangup frame on the owner of the IAX2 pvt struct that
2852 * is active for the given call number.
2854 * \pre Assumes lock for callno is already held.
2856 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
2857 * was valid before calling it, it may no longer be valid after calling it.
2858 * This function may unlock and lock the mutex associated with this callno,
2859 * meaning that another thread may grab it and destroy the call.
2861 static int iax2_queue_hangup(int callno)
2864 if (iaxs[callno] && iaxs[callno]->owner) {
2865 if (ast_channel_trylock(iaxs[callno]->owner)) {
2866 /* Avoid deadlock by pausing and trying again */
2867 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
2869 ast_queue_hangup(iaxs[callno]->owner);
2870 ast_channel_unlock(iaxs[callno]->owner);
2880 * \brief Queue a control frame on the ast_channel owner
2882 * This function queues a control frame on the owner of the IAX2 pvt struct that
2883 * is active for the given call number.
2885 * \pre Assumes lock for callno is already held.
2887 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
2888 * was valid before calling it, it may no longer be valid after calling it.
2889 * This function may unlock and lock the mutex associated with this callno,
2890 * meaning that another thread may grab it and destroy the call.
2892 static int iax2_queue_control_data(int callno,
2893 enum ast_control_frame_type control, const void *data, size_t datalen)
2896 if (iaxs[callno] && iaxs[callno]->owner) {
2897 if (ast_channel_trylock(iaxs[callno]->owner)) {
2898 /* Avoid deadlock by pausing and trying again */
2899 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
2901 ast_queue_control_data(iaxs[callno]->owner, control, data, datalen);
2902 ast_channel_unlock(iaxs[callno]->owner);
2910 static void destroy_firmware(struct iax_firmware *cur)
2912 /* Close firmware */
2914 munmap((void*)cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh)));
2920 static int try_firmware(char *s)
2923 struct iax_firmware *cur = NULL;
2924 int ifd, fd, res, len, chunk;
2925 struct ast_iax2_firmware_header *fwh, fwh2;
2926 struct MD5Context md5;
2927 unsigned char sum[16], buf[1024];
2930 if (!(s2 = alloca(strlen(s) + 100))) {
2931 ast_log(LOG_WARNING, "Alloca failed!\n");
2935 last = strrchr(s, '/');
2941 snprintf(s2, strlen(s) + 100, "/var/tmp/%s-%ld", last, (unsigned long)ast_random());
2943 if ((res = stat(s, &stbuf) < 0)) {
2944 ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno));
2948 /* Make sure it's not a directory */
2949 if (S_ISDIR(stbuf.st_mode))
2951 ifd = open(s, O_RDONLY);
2953 ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
2956 fd = open(s2, O_RDWR | O_CREAT | O_EXCL, AST_FILE_MODE);
2958 ast_log(LOG_WARNING, "Cannot open '%s' for writing: %s\n", s2, strerror(errno));
2962 /* Unlink our newly created file */
2965 /* Now copy the firmware into it */
2966 len = stbuf.st_size;
2969 if (chunk > sizeof(buf))
2970 chunk = sizeof(buf);
2971 res = read(ifd, buf, chunk);
2973 ast_log(LOG_WARNING, "Only read %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
2978 res = write(fd, buf, chunk);
2980 ast_log(LOG_WARNING, "Only write %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
2988 /* Return to the beginning */
2989 lseek(fd, 0, SEEK_SET);
2990 if ((res = read(fd, &fwh2, sizeof(fwh2))) != sizeof(fwh2)) {
2991 ast_log(LOG_WARNING, "Unable to read firmware header in '%s'\n", s);
2995 if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) {
2996 ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s);
3000 if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) {
3001 ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s);
3005 if (fwh2.devname[sizeof(fwh2.devname) - 1] || ast_strlen_zero((char *)fwh2.devname)) {
3006 ast_log(LOG_WARNING, "No or invalid device type specified for '%s'\n", s);
3010 fwh = (struct ast_iax2_firmware_header*)mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
3011 if (fwh == MAP_FAILED) {
3012 ast_log(LOG_WARNING, "mmap failed: %s\n", strerror(errno));
3017 MD5Update(&md5, fwh->data, ntohl(fwh->datalen));
3018 MD5Final(sum, &md5);
3019 if (memcmp(sum, fwh->chksum, sizeof(sum))) {
3020 ast_log(LOG_WARNING, "Firmware file '%s' fails checksum\n", s);
3021 munmap((void*)fwh, stbuf.st_size);
3026 AST_LIST_TRAVERSE(&firmwares, cur, list) {
3027 if (!strcmp((char *)cur->fwh->devname, (char *)fwh->devname)) {
3028 /* Found a candidate */
3029 if (cur->dead || (ntohs(cur->fwh->version) < ntohs(fwh->version)))
3030 /* The version we have on loaded is older, load this one instead */
3032 /* This version is no newer than what we have. Don't worry about it.
3033 We'll consider it a proper load anyhow though */
3034 munmap((void*)fwh, stbuf.st_size);
3040 if (!cur && ((cur = ast_calloc(1, sizeof(*cur))))) {
3042 AST_LIST_INSERT_TAIL(&firmwares, cur, list);
3047 munmap((void*)cur->fwh, cur->mmaplen);
3052 cur->mmaplen = stbuf.st_size;
3059 static int iax_check_version(char *dev)
3062 struct iax_firmware *cur = NULL;
3064 if (ast_strlen_zero(dev))
3067 AST_LIST_LOCK(&firmwares);
3068 AST_LIST_TRAVERSE(&firmwares, cur, list) {
3069 if (!strcmp(dev, (char *)cur->fwh->devname)) {
3070 res = ntohs(cur->fwh->version);
3074 AST_LIST_UNLOCK(&firmwares);
3079 static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
3082 unsigned int bs = desc & 0xff;
3083 unsigned int start = (desc >> 8) & 0xffffff;
3085 struct iax_firmware *cur;
3087 if (ast_strlen_zero((char *)dev) || !bs)
3092 AST_LIST_LOCK(&firmwares);
3093 AST_LIST_TRAVERSE(&firmwares, cur, list) {
3094 if (strcmp((char *)dev, (char *)cur->fwh->devname))
3096 iax_ie_append_int(ied, IAX_IE_FWBLOCKDESC, desc);
3097 if (start < ntohl(cur->fwh->datalen)) {
3098 bytes = ntohl(cur->fwh->datalen) - start;
3101 iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes);
3104 iax_ie_append(ied, IAX_IE_FWBLOCKDATA);
3112 AST_LIST_UNLOCK(&firmwares);
3118 static void reload_firmware(int unload)
3120 struct iax_firmware *cur = NULL;
3123 char dir[256], fn[256];
3125 AST_LIST_LOCK(&firmwares);
3127 /* Mark all as dead */
3128 AST_LIST_TRAVERSE(&firmwares, cur, list)
3131 /* Now that we have marked them dead... load new ones */
3133 snprintf(dir, sizeof(dir), "%s/firmware/iax", ast_config_AST_DATA_DIR);
3136 while((de = readdir(fwd))) {
3137 if (de->d_name[0] != '.') {
3138 snprintf(fn, sizeof(fn), "%s/%s", dir, de->d_name);
3139 if (!try_firmware(fn)) {
3140 ast_verb(2, "Loaded firmware '%s'\n", de->d_name);
3146 ast_log(LOG_WARNING, "Error opening firmware directory '%s': %s\n", dir, strerror(errno));
3149 /* Clean up leftovers */
3150 AST_LIST_TRAVERSE_SAFE_BEGIN(&firmwares, cur, list) {
3153 AST_LIST_REMOVE_CURRENT(list);
3154 destroy_firmware(cur);
3156 AST_LIST_TRAVERSE_SAFE_END;
3158 AST_LIST_UNLOCK(&firmwares);
3162 * \note This function assumes that iaxsl[callno] is locked when called.
3164 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3165 * was valid before calling it, it may no longer be valid after calling it.
3166 * This function calls iax2_queue_frame(), which may unlock and lock the mutex
3167 * associated with this callno, meaning that another thread may grab it and destroy the call.
3169 static int __do_deliver(void *data)
3171 /* Just deliver the packet by using queueing. This is called by
3172 the IAX thread with the iaxsl lock held. */
3173 struct iax_frame *fr = data;
3175 ast_clear_flag(&fr->af, AST_FRFLAG_HAS_TIMING_INFO);
3176 if (iaxs[fr->callno] && !ast_test_flag64(iaxs[fr->callno], IAX_ALREADYGONE))
3177 iax2_queue_frame(fr->callno, &fr->af);
3178 /* Free our iax frame */
3179 iax2_frame_free(fr);
3180 /* And don't run again */
3184 static int handle_error(void)
3186 /* XXX Ideally we should figure out why an error occurred and then abort those
3187 rather than continuing to try. Unfortunately, the published interface does
3188 not seem to work XXX */
3190 struct sockaddr_in *sin;
3193 struct sock_extended_err e;
3198 m.msg_controllen = sizeof(e);
3200 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
3202 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
3204 if (m.msg_controllen) {
3205 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
3207 ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(sin->sin_addr));
3209 ast_log(LOG_WARNING, "No address detected??\n");
3211 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
3218 static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin, int sockfd)
3221 res = sendto(sockfd, f->data, f->datalen, 0,(struct sockaddr *)sin,
3224 ast_debug(1, "Received error: %s\n", strerror(errno));
3231 static int send_packet(struct iax_frame *f)
3234 int callno = f->callno;
3236 /* Don't send if there was an error, but return error instead */
3237 if (!callno || !iaxs[callno] || iaxs[callno]->error)
3240 /* Called with iaxsl held */
3242 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));
3246 iax_showframe(f, NULL, 0, &iaxs[callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
3247 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->transfer, sizeof(iaxs[callno]->transfer));
3250 iax_showframe(f, NULL, 0, &iaxs[callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
3251 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->addr, sizeof(iaxs[callno]->addr));
3255 ast_debug(1, "Received error: %s\n", strerror(errno));
3264 * \note Since this function calls iax2_queue_hangup(), the pvt struct
3265 * for the given call number may disappear during its execution.
3267 static int iax2_predestroy(int callno)
3269 struct ast_channel *c = NULL;
3270 struct chan_iax2_pvt *pvt = iaxs[callno];
3275 if (!ast_test_flag64(pvt, IAX_ALREADYGONE)) {
3276 iax2_destroy_helper(pvt);
3277 ast_set_flag64(pvt, IAX_ALREADYGONE);
3280 if ((c = pvt->owner)) {
3282 iax2_queue_hangup(callno);
3284 ast_module_unref(ast_module_info->self);
3290 static void iax2_destroy(int callno)
3292 struct chan_iax2_pvt *pvt = NULL;
3293 struct ast_channel *owner = NULL;
3296 if ((pvt = iaxs[callno])) {
3298 /* iax2_destroy_helper gets called from this function later on. When
3299 * called twice, we get the (previously) familiar FRACK! errors in
3300 * devmode, from the scheduler. An alternative to this approach is to
3301 * reset the scheduler entries to -1 when they're deleted in
3302 * iax2_destroy_helper(). That approach was previously decided to be
3303 * "wrong" because "the memory is going to be deallocated anyway. Why
3304 * should we be resetting those values?" */
3305 iax2_destroy_helper(pvt);
3309 owner = pvt ? pvt->owner : NULL;
3312 if (ast_channel_trylock(owner)) {
3313 ast_debug(3, "Avoiding IAX destroy deadlock\n");
3314 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
3320 iaxs[callno] = NULL;
3327 /* If there's an owner, prod it to give up */
3328 /* It is ok to use ast_queue_hangup() here instead of iax2_queue_hangup()
3329 * because we already hold the owner channel lock. */
3330 ast_queue_hangup(owner);
3333 if (pvt->peercallno) {
3334 remove_by_peercallno(pvt);
3337 if (pvt->transfercallno) {
3338 remove_by_transfercallno(pvt);
3348 ast_channel_unlock(owner);
3351 if (callno & 0x4000) {
3356 static int update_packet(struct iax_frame *f)
3358 /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
3359 struct ast_iax2_full_hdr *fh = f->data;
3360 struct ast_frame af;
3362 /* if frame is encrypted. decrypt before updating it. */
3363 if (f->encmethods) {
3364 decode_frame(&f->mydcx, fh, &af, &f->datalen);
3366 /* Mark this as a retransmission */
3367 fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
3369 f->iseqno = iaxs[f->callno]->iseqno;
3370 fh->iseqno = f->iseqno;
3372 /* Now re-encrypt the frame */
3373 if (f->encmethods) {
3374 /* since this is a retransmit frame, create a new random padding
3375 * before re-encrypting. */
3376 build_rand_pad(f->semirand, sizeof(f->semirand));
3377 encrypt_frame(&f->ecx, fh, f->semirand, &f->datalen);
3382 static int attempt_transmit(const void *data);
3383 static void __attempt_transmit(const void *data)
3385 /* Attempt to transmit the frame to the remote peer...
3386 Called without iaxsl held. */
3387 struct iax_frame *f = (struct iax_frame *)data;
3389 int callno = f->callno;
3390 /* Make sure this call is still active */
3392 ast_mutex_lock(&iaxsl[callno]);
3393 if (callno && iaxs[callno]) {
3394 if ((f->retries < 0) /* Already ACK'd */ ||
3395 (f->retries >= max_retries) /* Too many attempts */) {
3396 /* Record an error if we've transmitted too many times */
3397 if (f->retries >= max_retries) {
3399 /* Transfer timeout */
3400 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
3401 } else if (f->final) {
3402 iax2_destroy(callno);
3404 if (iaxs[callno]->owner)
3405 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);
3406 iaxs[callno]->error = ETIMEDOUT;
3407 if (iaxs[callno]->owner) {
3408 struct ast_frame fr = { AST_FRAME_CONTROL, { AST_CONTROL_HANGUP }, .data.uint32 = AST_CAUSE_DESTINATION_OUT_OF_ORDER };
3410 iax2_queue_frame(callno, &fr); /* XXX */
3411 /* Remember, owner could disappear */
3412 if (iaxs[callno] && iaxs[callno]->owner)
3413 iaxs[callno]->owner->hangupcause = AST_CAUSE_DESTINATION_OUT_OF_ORDER;
3415 if (iaxs[callno]->reg) {
3416 memset(&iaxs[callno]->reg->us, 0, sizeof(iaxs[callno]->reg->us));
3417 iaxs[callno]->reg->regstate = REG_STATE_TIMEOUT;
3418 iaxs[callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
3420 iax2_destroy(callno);
3427 /* Update it if it needs it */
3429 /* Attempt transmission */
3432 /* Try again later after 10 times as long */
3434 if (f->retrytime > MAX_RETRY_TIME)
3435 f->retrytime = MAX_RETRY_TIME;
3436 /* Transfer messages max out at one second */
3437 if (f->transfer && (f->retrytime > 1000))
3438 f->retrytime = 1000;
3439 f->retrans = iax2_sched_add(sched, f->retrytime, attempt_transmit, f);
3442 /* Make sure it gets freed */
3448 /* Don't attempt delivery, just remove it from the queue */
3449 AST_LIST_REMOVE(&frame_queue[callno], f, list);
3450 ast_mutex_unlock(&iaxsl[callno]);
3451 f->retrans = -1; /* this is safe because this is the scheduled function */
3452 /* Free the IAX frame */
3454 } else if (callno) {
3455 ast_mutex_unlock(&iaxsl[callno]);
3459 static int attempt_transmit(const void *data)
3461 #ifdef SCHED_MULTITHREADED
3462 if (schedule_action(__attempt_transmit, data))
3464 __attempt_transmit(data);
3468 static char *handle_cli_iax2_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3470 struct iax2_peer *peer = NULL;
3471 struct iax2_user *user = NULL;
3472 static const char * const choices[] = { "all", NULL };
3477 e->command = "iax2 prune realtime";
3479 "Usage: iax2 prune realtime [<peername>|all]\n"
3480 " Prunes object(s) from the cache\n";
3484 cmplt = ast_cli_complete(a->word, choices, a->n);
3486 cmplt = complete_iax2_peers(a->line, a->word, a->pos, a->n - sizeof(choices), IAX_RTCACHEFRIENDS);
3492 return CLI_SHOWUSAGE;
3493 if (!strcmp(a->argv[3], "all")) {
3496 ast_cli(a->fd, "Cache flushed successfully.\n");
3499 peer = find_peer(a->argv[3], 0);
3500 user = find_user(a->argv[3]);
3503 if (ast_test_flag64(peer, IAX_RTCACHEFRIENDS)) {
3504 ast_set_flag64(peer, IAX_RTAUTOCLEAR);
3505 expire_registry(peer_ref(peer));
3506 ast_cli(a->fd, "Peer %s was removed from the cache.\n", a->argv[3]);
3508 ast_cli(a->fd, "Peer %s is not eligible for this operation.\n", a->argv[3]);
3513 if (ast_test_flag64(user, IAX_RTCACHEFRIENDS)) {
3514 ast_set_flag64(user, IAX_RTAUTOCLEAR);
3515 ast_cli(a->fd, "User %s was removed from the cache.\n", a->argv[3]);
3517 ast_cli(a->fd, "User %s is not eligible for this operation.\n", a->argv[3]);
3519 ao2_unlink(users,user);
3523 ast_cli(a->fd, "%s was not found in the cache.\n", a->argv[3]);
3529 static char *handle_cli_iax2_test_losspct(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3533 e->command = "iax2 test losspct";
3535 "Usage: iax2 test losspct <percentage>\n"
3536 " For testing, throws away <percentage> percent of incoming packets\n";
3542 return CLI_SHOWUSAGE;
3544 test_losspct = atoi(a->argv[3]);
3550 static char *handle_cli_iax2_test_late(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3554 e->command = "iax2 test late";
3556 "Usage: iax2 test late <ms>\n"
3557 " For testing, count the next frame as <ms> ms late\n";
3564 return CLI_SHOWUSAGE;
3566 test_late = atoi(a->argv[3]);
3571 static char *handle_cli_iax2_test_resync(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3575 e->command = "iax2 test resync";
3577 "Usage: iax2 test resync <ms>\n"
3578 " For testing, adjust all future frames by <ms> ms\n";
3585 return CLI_SHOWUSAGE;
3587 test_resync = atoi(a->argv[3]);
3592 static char *handle_cli_iax2_test_jitter(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3596 e->command = "iax2 test jitter";
3598 "Usage: iax2 test jitter <ms> <pct>\n"
3599 " For testing, simulate maximum jitter of +/- <ms> on <pct>\n"
3600 " percentage of packets. If <pct> is not specified, adds\n"
3601 " jitter to all packets.\n";
3607 if (a->argc < 4 || a->argc > 5)
3608 return CLI_SHOWUSAGE;
3610 test_jit = atoi(a->argv[3]);
3612 test_jitpct = atoi(a->argv[4]);
3616 #endif /* IAXTESTS */
3618 /*! \brief peer_status: Report Peer status in character string */
3619 /* returns 1 if peer is online, -1 if unmonitored */
3620 static int peer_status(struct iax2_peer *peer, char *status, int statuslen)
3624 if (peer->lastms < 0) {
3625 ast_copy_string(status, "UNREACHABLE", statuslen);
3626 } else if (peer->lastms > peer->maxms) {
3627 snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
3629 } else if (peer->lastms) {
3630 snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
3633 ast_copy_string(status, "UNKNOWN", statuslen);
3636 ast_copy_string(status, "Unmonitored", statuslen);
3642 /*! \brief Show one peer in detail */
3643 static char *handle_cli_iax2_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3647 struct iax2_peer *peer;
3648 char codec_buf[512];
3649 struct ast_str *encmethods = ast_str_alloca(256);
3650 int x = 0, codec = 0, load_realtime = 0;
3654 e->command = "iax2 show peer";
3656 "Usage: iax2 show peer <name>\n"
3657 " Display details on specific IAX peer\n";
3661 return complete_iax2_peers(a->line, a->word, a->pos, a->n, 0);
3666 return CLI_SHOWUSAGE;
3668 load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? 1 : 0;
3670 peer = find_peer(a->argv[3], load_realtime);
3672 encmethods_to_str(peer->encmethods, encmethods);
3673 ast_cli(a->fd, "\n\n");
3674 ast_cli(a->fd, " * Name : %s\n", peer->name);
3675 ast_cli(a->fd, " Secret : %s\n", ast_strlen_zero(peer->secret) ? "<Not set>" : "<Set>");
3676 ast_cli(a->fd, " Context : %s\n", peer->context);
3677 ast_cli(a->fd, " Parking lot : %s\n", peer->parkinglot);
3678 ast_cli(a->fd, " Mailbox : %s\n", peer->mailbox);
3679 ast_cli(a->fd, " Dynamic : %s\n", ast_test_flag64(peer, IAX_DYNAMIC) ? "Yes" : "No");
3680 ast_cli(a->fd, " Callnum limit: %d\n", peer->maxcallno);
3681 ast_cli(a->fd, " Calltoken req: %s\n", (peer->calltoken_required == CALLTOKEN_YES) ? "Yes" : ((peer->calltoken_required == CALLTOKEN_AUTO) ? "Auto" : "No"));
3682 ast_cli(a->fd, " Trunk : %s\n", ast_test_flag64(peer, IAX_TRUNK) ? "Yes" : "No");
3683 ast_cli(a->fd, " Encryption : %s\n", peer->encmethods ? ast_str_buffer(encmethods) : "No");
3684 ast_cli(a->fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
3685 ast_cli(a->fd, " Expire : %d\n", peer->expire);
3686 ast_cli(a->fd, " ACL : %s\n", (peer->ha ? "Yes" : "No"));
3687 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));
3688 ast_cli(a->fd, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
3689 ast_cli(a->fd, " Username : %s\n", peer->username);
3690 ast_cli(a->fd, " Codecs : ");
3691 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
3692 ast_cli(a->fd, "%s\n", codec_buf);
3694 ast_cli(a->fd, " Codec Order : (");
3695 for(x = 0; x < 32 ; x++) {
3696 codec = ast_codec_pref_index(&peer->prefs,x);
3699 ast_cli(a->fd, "%s", ast_getformatname(codec));
3700 if(x < 31 && ast_codec_pref_index(&peer->prefs,x+1))
3701 ast_cli(a->fd, "|");
3705 ast_cli(a->fd, "none");
3706 ast_cli(a->fd, ")\n");