2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2006, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
21 * \brief Implementation of Inter-Asterisk eXchange Version 2
23 * \author Mark Spencer <markster@digium.com>
26 * \arg \ref Config_iax
28 * \ingroup channel_drivers
30 * \todo Implement musicclass settings for IAX2 devices
39 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
43 #include <sys/socket.h>
44 #include <netinet/in.h>
45 #include <arpa/inet.h>
46 #include <netinet/in_systm.h>
47 #include <netinet/ip.h>
49 #include <sys/signal.h>
57 #include "asterisk/paths.h" /* need ast_config_AST_DATA_DIR for firmware */
59 #include "asterisk/lock.h"
60 #include "asterisk/frame.h"
61 #include "asterisk/channel.h"
62 #include "asterisk/module.h"
63 #include "asterisk/pbx.h"
64 #include "asterisk/sched.h"
65 #include "asterisk/io.h"
66 #include "asterisk/config.h"
67 #include "asterisk/cli.h"
68 #include "asterisk/translate.h"
69 #include "asterisk/md5.h"
70 #include "asterisk/cdr.h"
71 #include "asterisk/crypto.h"
72 #include "asterisk/acl.h"
73 #include "asterisk/manager.h"
74 #include "asterisk/callerid.h"
75 #include "asterisk/app.h"
76 #include "asterisk/astdb.h"
77 #include "asterisk/musiconhold.h"
78 #include "asterisk/features.h"
79 #include "asterisk/utils.h"
80 #include "asterisk/causes.h"
81 #include "asterisk/localtime.h"
82 #include "asterisk/aes.h"
83 #include "asterisk/dnsmgr.h"
84 #include "asterisk/devicestate.h"
85 #include "asterisk/netsock.h"
86 #include "asterisk/stringfields.h"
87 #include "asterisk/linkedlists.h"
88 #include "asterisk/event.h"
89 #include "asterisk/astobj2.h"
90 #include "asterisk/timing.h"
91 #include "asterisk/taskprocessor.h"
94 #include "iax2-parser.h"
95 #include "iax2-provision.h"
96 #include "jitterbuf.h"
99 <application name="IAX2Provision" language="en_US">
101 Provision a calling IAXy with a given template.
104 <parameter name="template">
105 <para>If not specified, defaults to <literal>default</literal>.</para>
109 <para>Provisions the calling IAXy (assuming the calling entity is in fact an IAXy) with the
110 given <replaceable>template</replaceable>. Returns <literal>-1</literal> on error
111 or <literal>0</literal> on success.</para>
114 <function name="IAXPEER" language="en_US">
116 Gets IAX peer information.
119 <parameter name="peername" required="true">
121 <enum name="CURRENTCHANNEL">
122 <para>If <replaceable>peername</replaceable> is specified to this value, return the IP address of the
123 endpoint of the current channel</para>
127 <parameter name="item">
128 <para>If <replaceable>peername</replaceable> is specified, valid items are:</para>
131 <para>(default) The IP address.</para>
134 <para>The peer's status (if <literal>qualify=yes</literal>)</para>
136 <enum name="mailbox">
137 <para>The configured mailbox.</para>
139 <enum name="context">
140 <para>The configured context.</para>
143 <para>The epoch time of the next expire.</para>
145 <enum name="dynamic">
146 <para>Is it dynamic? (yes/no).</para>
148 <enum name="callerid_name">
149 <para>The configured Caller ID name.</para>
151 <enum name="callerid_num">
152 <para>The configured Caller ID number.</para>
155 <para>The configured codecs.</para>
157 <enum name="codec[x]">
158 <para>Preferred codec index number <replaceable>x</replaceable> (beginning
159 with <literal>0</literal>)</para>
166 <ref type="function">SIPPEER</ref>
169 <function name="IAXVAR" language="en_US">
171 Sets or retrieves a remote variable.
174 <parameter name="varname" required="true" />
178 <manager name="IAXpeers" language="en_US">
183 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
188 <manager name="IAXpeerlist" language="en_US">
193 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
196 <para>List all the IAX peers.</para>
199 <manager name="IAXnetstats" language="en_US">
205 <para>Show IAX channels network statistics.</para>
208 <manager name="IAXregistry" language="en_US">
210 Show IAX registrations.
213 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
216 <para>Show IAX registrations.</para>
221 /* Define SCHED_MULTITHREADED to run the scheduler in a special
222 multithreaded mode. */
223 #define SCHED_MULTITHREADED
225 /* Define DEBUG_SCHED_MULTITHREADED to keep track of where each
226 thread is actually doing. */
227 #define DEBUG_SCHED_MULTITHREAD
231 static int nochecksums = 0;
234 #define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
235 #define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
237 #define DEFAULT_THREAD_COUNT 10
238 #define DEFAULT_MAX_THREAD_COUNT 100
239 #define DEFAULT_RETRY_TIME 1000
240 #define MEMORY_SIZE 100
241 #define DEFAULT_DROP 3
243 #define DEBUG_SUPPORT
245 #define MIN_REUSE_TIME 60 /* Don't reuse a call number within 60 seconds */
247 /* Sample over last 100 units to determine historic jitter */
250 static struct ast_codec_pref prefs;
252 static const char tdesc[] = "Inter Asterisk eXchange Driver (Ver 2)";
255 /*! \brief Maximum transmission unit for the UDP packet in the trunk not to be
256 fragmented. This is based on 1516 - ethernet - ip - udp - iax minus one g711 frame = 1240 */
257 #define MAX_TRUNK_MTU 1240
259 static int global_max_trunk_mtu; /*!< Maximum MTU, 0 if not used */
260 static int trunk_timed, trunk_untimed, trunk_maxmtu, trunk_nmaxmtu ; /*!< Trunk MTU statistics */
262 #define DEFAULT_CONTEXT "default"
264 static char default_parkinglot[AST_MAX_CONTEXT];
266 static char language[MAX_LANGUAGE] = "";
267 static char regcontext[AST_MAX_CONTEXT] = "";
269 static int maxauthreq = 3;
270 static int max_retries = 4;
271 static int ping_time = 21;
272 static int lagrq_time = 10;
273 static int maxjitterbuffer=1000;
274 static int resyncthreshold=1000;
275 static int maxjitterinterps=10;
276 static int jittertargetextra = 40; /* number of milliseconds the new jitter buffer adds on to its size */
278 #define MAX_TRUNKDATA 640 * 200 /*!< 40ms, uncompressed linear * 200 channels */
280 static int trunkfreq = 20;
281 static int trunkmaxsize = MAX_TRUNKDATA;
283 static int authdebug = 1;
284 static int autokill = 0;
285 static int iaxcompat = 0;
286 static int last_authmethod = 0;
288 static int iaxdefaultdpcache=10 * 60; /* Cache dialplan entries for 10 minutes by default */
290 static int iaxdefaulttimeout = 5; /* Default to wait no more than 5 seconds for a reply to come back */
297 static int min_reg_expire;
298 static int max_reg_expire;
300 static int srvlookup = 0;
302 static struct ast_timer *timer; /* Timer for trunking */
304 static struct ast_netsock_list *netsock;
305 static struct ast_netsock_list *outsock; /*!< used if sourceaddress specified and bindaddr == INADDR_ANY */
306 static int defaultsockfd = -1;
308 static int (*iax2_regfunk)(const char *username, int onoff) = NULL;
311 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
313 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
314 ~AST_FORMAT_SLINEAR & \
315 ~AST_FORMAT_SLINEAR16 & \
316 ~AST_FORMAT_SIREN7 & \
317 ~AST_FORMAT_SIREN14 & \
322 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
324 ~AST_FORMAT_G726_AAL2 & \
327 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
331 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
332 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
333 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
335 /* if a pvt has encryption setup done and is running on the call */
336 #define IAX_CALLENCRYPTED(pvt) \
337 (ast_test_flag64(pvt, IAX_ENCRYPTED) && ast_test_flag64(pvt, IAX_KEYPOPULATED))
339 #define IAX_DEBUGDIGEST(msg, key) do { \
341 char digest[33] = ""; \
346 for (idx = 0; idx < 16; idx++) \
347 sprintf(digest + (idx << 1), "%2.2x", (unsigned char) key[idx]); \
349 ast_log(LOG_NOTICE, msg " IAX_COMMAND_RTKEY to rotate key to '%s'\n", digest); \
352 static struct io_context *io;
353 static struct ast_sched_thread *sched;
355 static format_t iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
357 static int iaxdebug = 0;
359 static int iaxtrunkdebug = 0;
361 static int test_losspct = 0;
363 static int test_late = 0;
364 static int test_resync = 0;
365 static int test_jit = 0;
366 static int test_jitpct = 0;
367 #endif /* IAXTESTS */
369 static char accountcode[AST_MAX_ACCOUNT_CODE];
370 static char mohinterpret[MAX_MUSICCLASS];
371 static char mohsuggest[MAX_MUSICCLASS];
372 static int amaflags = 0;
374 static int delayreject = 0;
375 static int iax2_encryption = 0;
377 static struct ast_flags64 globalflags = { 0 };
379 static pthread_t netthreadid = AST_PTHREADT_NULL;
382 IAX_STATE_STARTED = (1 << 0),
383 IAX_STATE_AUTHENTICATED = (1 << 1),
384 IAX_STATE_TBD = (1 << 2),
387 struct iax2_context {
388 char context[AST_MAX_CONTEXT];
389 struct iax2_context *next;
393 #define IAX_HASCALLERID (uint64_t)(1 << 0) /*!< CallerID has been specified */
394 #define IAX_DELME (uint64_t)(1 << 1) /*!< Needs to be deleted */
395 #define IAX_TEMPONLY (uint64_t)(1 << 2) /*!< Temporary (realtime) */
396 #define IAX_TRUNK (uint64_t)(1 << 3) /*!< Treat as a trunk */
397 #define IAX_NOTRANSFER (uint64_t)(1 << 4) /*!< Don't native bridge */
398 #define IAX_USEJITTERBUF (uint64_t)(1 << 5) /*!< Use jitter buffer */
399 #define IAX_DYNAMIC (uint64_t)(1 << 6) /*!< dynamic peer */
400 #define IAX_SENDANI (uint64_t)(1 << 7) /*!< Send ANI along with CallerID */
401 #define IAX_RTSAVE_SYSNAME (uint64_t)(1 << 8) /*!< Save Systname on Realtime Updates */
402 #define IAX_ALREADYGONE (uint64_t)(1 << 9) /*!< Already disconnected */
403 #define IAX_PROVISION (uint64_t)(1 << 10) /*!< This is a provisioning request */
404 #define IAX_QUELCH (uint64_t)(1 << 11) /*!< Whether or not we quelch audio */
405 #define IAX_ENCRYPTED (uint64_t)(1 << 12) /*!< Whether we should assume encrypted tx/rx */
406 #define IAX_KEYPOPULATED (uint64_t)(1 << 13) /*!< Whether we have a key populated */
407 #define IAX_CODEC_USER_FIRST (uint64_t)(1 << 14) /*!< are we willing to let the other guy choose the codec? */
408 #define IAX_CODEC_NOPREFS (uint64_t)(1 << 15) /*!< Force old behaviour by turning off prefs */
409 #define IAX_CODEC_NOCAP (uint64_t)(1 << 16) /*!< only consider requested format and ignore capabilities*/
410 #define IAX_RTCACHEFRIENDS (uint64_t)(1 << 17) /*!< let realtime stay till your reload */
411 #define IAX_RTUPDATE (uint64_t)(1 << 18) /*!< Send a realtime update */
412 #define IAX_RTAUTOCLEAR (uint64_t)(1 << 19) /*!< erase me on expire */
413 #define IAX_FORCEJITTERBUF (uint64_t)(1 << 20) /*!< Force jitterbuffer, even when bridged to a channel that can take jitter */
414 #define IAX_RTIGNOREREGEXPIRE (uint64_t)(1 << 21) /*!< When using realtime, ignore registration expiration */
415 #define IAX_TRUNKTIMESTAMPS (uint64_t)(1 << 22) /*!< Send trunk timestamps */
416 #define IAX_TRANSFERMEDIA (uint64_t)(1 << 23) /*!< When doing IAX2 transfers, transfer media only */
417 #define IAX_MAXAUTHREQ (uint64_t)(1 << 24) /*!< Maximum outstanding AUTHREQ restriction is in place */
418 #define IAX_DELAYPBXSTART (uint64_t)(1 << 25) /*!< Don't start a PBX on the channel until the peer sends us a response, so that we've achieved a three-way handshake with them before sending voice or anything else */
419 #define IAX_ALLOWFWDOWNLOAD (uint64_t)(1 << 26) /*!< Allow the FWDOWNL command? */
420 #define IAX_IMMEDIATE (uint64_t)(1 << 27) /*!< Allow immediate off-hook to extension s */
421 #define IAX_SENDCONNECTEDLINE (uint64_t)(1 << 28) /*!< Allow sending of connected line updates */
422 #define IAX_RECVCONNECTEDLINE (uint64_t)(1 << 29) /*!< Allow receiving of connected line updates */
423 #define IAX_FORCE_ENCRYPT (uint64_t)(1 << 30) /*!< Forces call encryption, if encryption not possible hangup */
424 #define IAX_SHRINKCALLERID (uint64_t)(1 << 31) /*!< Turn on and off caller id shrinking */
425 static int global_rtautoclear = 120;
427 static int reload_config(void);
430 * \brief Call token validation settings.
432 enum calltoken_peer_enum {
433 /*! \brief Default calltoken required unless the ip is in the ignorelist */
434 CALLTOKEN_DEFAULT = 0,
435 /*! \brief Require call token validation. */
437 /*! \brief Require call token validation after a successful registration
438 * using call token validation occurs. */
440 /*! \brief Do not require call token validation. */
445 AST_DECLARE_STRING_FIELDS(
446 AST_STRING_FIELD(name);
447 AST_STRING_FIELD(secret);
448 AST_STRING_FIELD(dbsecret);
449 AST_STRING_FIELD(accountcode);
450 AST_STRING_FIELD(mohinterpret);
451 AST_STRING_FIELD(mohsuggest);
452 AST_STRING_FIELD(inkeys); /*!< Key(s) this user can use to authenticate to us */
453 AST_STRING_FIELD(language);
454 AST_STRING_FIELD(cid_num);
455 AST_STRING_FIELD(cid_name);
456 AST_STRING_FIELD(parkinglot); /*!< Default parkinglot for device */
465 int maxauthreq; /*!< Maximum allowed outstanding AUTHREQs */
466 int curauthreq; /*!< Current number of outstanding AUTHREQs */
467 struct ast_codec_pref prefs;
469 struct iax2_context *contexts;
470 struct ast_variable *vars;
471 enum calltoken_peer_enum calltoken_required; /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
475 AST_DECLARE_STRING_FIELDS(
476 AST_STRING_FIELD(name);
477 AST_STRING_FIELD(username);
478 AST_STRING_FIELD(secret);
479 AST_STRING_FIELD(dbsecret);
480 AST_STRING_FIELD(outkey); /*!< What key we use to talk to this peer */
482 AST_STRING_FIELD(regexten); /*!< Extension to register (if regcontext is used) */
483 AST_STRING_FIELD(context); /*!< For transfers only */
484 AST_STRING_FIELD(peercontext); /*!< Context to pass to peer */
485 AST_STRING_FIELD(mailbox); /*!< Mailbox */
486 AST_STRING_FIELD(mohinterpret);
487 AST_STRING_FIELD(mohsuggest);
488 AST_STRING_FIELD(inkeys); /*!< Key(s) this peer can use to authenticate to us */
489 /* Suggested caller id if registering */
490 AST_STRING_FIELD(cid_num); /*!< Default context (for transfer really) */
491 AST_STRING_FIELD(cid_name); /*!< Default context (for transfer really) */
492 AST_STRING_FIELD(zonetag); /*!< Time Zone */
493 AST_STRING_FIELD(parkinglot); /*!< Default parkinglot for device */
495 struct ast_codec_pref prefs;
496 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
497 struct sockaddr_in addr;
499 int sockfd; /*!< Socket to use for transmission */
504 /* Dynamic Registration fields */
505 struct sockaddr_in defaddr; /*!< Default address if there is one */
506 int authmethods; /*!< Authentication methods (IAX_AUTH_*) */
507 int encmethods; /*!< Encryption methods (IAX_ENCRYPT_*) */
509 int expire; /*!< Schedule entry for expiry */
510 int expiry; /*!< How soon to expire */
511 format_t capability; /*!< Capability */
514 int callno; /*!< Call number of POKE request */
515 int pokeexpire; /*!< Scheduled qualification-related task (ie iax2_poke_peer_s or iax2_poke_noanswer) */
516 int lastms; /*!< How long last response took (in ms), or -1 for no response */
517 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
519 int pokefreqok; /*!< How often to check if the host is up */
520 int pokefreqnotok; /*!< How often to check when the host has been determined to be down */
521 int historicms; /*!< How long recent average responses took */
522 int smoothing; /*!< Sample over how many units to determine historic ms */
523 uint16_t maxcallno; /*!< Max call number limit for this peer. Set on registration */
525 struct ast_event_sub *mwi_event_sub;
528 enum calltoken_peer_enum calltoken_required; /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
531 #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
533 struct iax2_trunk_peer {
536 struct sockaddr_in addr;
537 struct timeval txtrunktime; /*!< Transmit trunktime */
538 struct timeval rxtrunktime; /*!< Receive trunktime */
539 struct timeval lasttxtime; /*!< Last transmitted trunktime */
540 struct timeval trunkact; /*!< Last trunk activity */
541 unsigned int lastsent; /*!< Last sent time */
542 /* Trunk data and length */
543 unsigned char *trunkdata;
544 unsigned int trunkdatalen;
545 unsigned int trunkdataalloc;
549 AST_LIST_ENTRY(iax2_trunk_peer) list;
552 static AST_LIST_HEAD_STATIC(tpeers, iax2_trunk_peer);
554 struct iax_firmware {
555 AST_LIST_ENTRY(iax_firmware) list;
559 struct ast_iax2_firmware_header *fwh;
564 REG_STATE_UNREGISTERED = 0,
567 REG_STATE_REGISTERED,
573 enum iax_transfer_state {
578 TRANSFER_PASSTHROUGH,
582 TRANSFER_MPASSTHROUGH,
587 struct iax2_registry {
588 struct sockaddr_in addr; /*!< Who we connect to for registration purposes */
590 char secret[80]; /*!< Password or key name in []'s */
591 int expire; /*!< Sched ID of expiration */
592 int refresh; /*!< How often to refresh */
593 enum iax_reg_state regstate;
594 int messages; /*!< Message count, low 8 bits = new, high 8 bits = old */
595 int callno; /*!< Associated call number if applicable */
596 struct sockaddr_in us; /*!< Who the server thinks we are */
597 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
598 AST_LIST_ENTRY(iax2_registry) entry;
601 static AST_LIST_HEAD_STATIC(registrations, iax2_registry);
603 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
604 #define MIN_RETRY_TIME 100
605 #define MAX_RETRY_TIME 10000
607 #define MAX_JITTER_BUFFER 50
608 #define MIN_JITTER_BUFFER 10
610 #define DEFAULT_TRUNKDATA 640 * 10 /*!< 40ms, uncompressed linear * 10 channels */
612 #define MAX_TIMESTAMP_SKEW 160 /*!< maximum difference between actual and predicted ts for sending */
614 /* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
615 #define TS_GAP_FOR_JB_RESYNC 5000
617 /* used for first_iax_message and last_iax_message. If this bit is set it was TX, else RX */
618 #define MARK_IAX_SUBCLASS_TX 0x8000
620 static int iaxthreadcount = DEFAULT_THREAD_COUNT;
621 static int iaxmaxthreadcount = DEFAULT_MAX_THREAD_COUNT;
622 static int iaxdynamicthreadcount = 0;
623 static int iaxdynamicthreadnum = 0;
624 static int iaxactivethreadcount = 0;
638 struct chan_iax2_pvt {
639 /*! Socket to send/receive on for this call */
641 /*! Last received voice format */
642 format_t voiceformat;
643 /*! Last received video format */
644 format_t videoformat;
645 /*! Last sent voice format */
646 format_t svoiceformat;
647 /*! Last sent video format */
648 format_t svideoformat;
649 /*! What we are capable of sending */
651 /*! Last received timestamp */
653 /*! Last sent timestamp - never send the same timestamp twice in a single call */
654 unsigned int lastsent;
655 /*! Timestamp of the last video frame sent */
656 unsigned int lastvsent;
657 /*! Next outgoing timestamp if everything is good */
658 unsigned int nextpred;
659 /*! iax frame subclass that began iax2_pvt entry. 0x8000 bit is set on TX */
660 int first_iax_message;
661 /*! Last iax frame subclass sent or received for a iax2_pvt. 0x8000 bit is set on TX */
662 int last_iax_message;
663 /*! True if the last voice we transmitted was not silence/CNG */
664 unsigned int notsilenttx:1;
666 unsigned int pingtime;
667 /*! Max time for initial response */
670 struct sockaddr_in addr;
671 /*! Actual used codec preferences */
672 struct ast_codec_pref prefs;
673 /*! Requested codec preferences */
674 struct ast_codec_pref rprefs;
675 /*! Our call number */
676 unsigned short callno;
677 /*! Our callno_entry entry */
678 struct callno_entry *callno_entry;
680 unsigned short peercallno;
681 /*! Negotiated format, this is only used to remember what format was
682 chosen for an unauthenticated call so that the channel can get
683 created later using the right format */
684 format_t chosenformat;
685 /*! Peer selected format */
687 /*! Peer capability */
688 format_t peercapability;
689 /*! timeval that we base our transmission on */
690 struct timeval offset;
691 /*! timeval that we base our delivery on */
692 struct timeval rxcore;
693 /*! The jitterbuffer */
695 /*! active jb read scheduler id */
699 /*! Error, as discovered by the manager */
701 /*! Owner if we have one */
702 struct ast_channel *owner;
703 /*! What's our state? */
704 struct ast_flags state;
705 /*! Expiry (optional) */
707 /*! Next outgoing sequence number */
708 unsigned char oseqno;
709 /*! Next sequence number they have not yet acknowledged */
710 unsigned char rseqno;
711 /*! Next incoming sequence number */
712 unsigned char iseqno;
713 /*! Last incoming sequence number we have acknowledged */
714 unsigned char aseqno;
716 AST_DECLARE_STRING_FIELDS(
718 AST_STRING_FIELD(peer);
719 /*! Default Context */
720 AST_STRING_FIELD(context);
721 /*! Caller ID if available */
722 AST_STRING_FIELD(cid_num);
723 AST_STRING_FIELD(cid_name);
724 /*! Hidden Caller ID (i.e. ANI) if appropriate */
725 AST_STRING_FIELD(ani);
727 AST_STRING_FIELD(dnid);
729 AST_STRING_FIELD(rdnis);
730 /*! Requested Extension */
731 AST_STRING_FIELD(exten);
732 /*! Expected Username */
733 AST_STRING_FIELD(username);
734 /*! Expected Secret */
735 AST_STRING_FIELD(secret);
737 AST_STRING_FIELD(challenge);
738 /*! Public keys permitted keys for incoming authentication */
739 AST_STRING_FIELD(inkeys);
740 /*! Private key for outgoing authentication */
741 AST_STRING_FIELD(outkey);
742 /*! Preferred language */
743 AST_STRING_FIELD(language);
744 /*! Hostname/peername for naming purposes */
745 AST_STRING_FIELD(host);
747 AST_STRING_FIELD(dproot);
748 AST_STRING_FIELD(accountcode);
749 AST_STRING_FIELD(mohinterpret);
750 AST_STRING_FIELD(mohsuggest);
751 /*! received OSP token */
752 AST_STRING_FIELD(osptoken);
753 /*! Default parkinglot */
754 AST_STRING_FIELD(parkinglot);
756 /*! AUTHREJ all AUTHREP frames */
758 /*! permitted authentication methods */
760 /*! permitted encryption methods */
762 /*! Encryption AES-128 Key */
763 ast_aes_encrypt_key ecx;
764 /*! Decryption AES-128 Key corresponding to ecx */
765 ast_aes_decrypt_key mydcx;
766 /*! Decryption AES-128 Key used to decrypt peer frames */
767 ast_aes_decrypt_key dcx;
768 /*! scheduler id associated with iax_key_rotate
769 * for encrypted calls*/
771 /*! 32 bytes of semi-random data */
772 unsigned char semirand[32];
773 /*! Associated registry */
774 struct iax2_registry *reg;
775 /*! Associated peer for poking */
776 struct iax2_peer *peerpoke;
781 /*! Transferring status */
782 enum iax_transfer_state transferring;
783 /*! Transfer identifier */
785 /*! Who we are IAX transferring to */
786 struct sockaddr_in transfer;
787 /*! What's the new call number for the transfer */
788 unsigned short transfercallno;
789 /*! Transfer encrypt AES-128 Key */
790 ast_aes_encrypt_key tdcx;
792 /*! Status of knowledge of peer ADSI capability */
795 /*! Who we are bridged to */
796 unsigned short bridgecallno;
798 int pingid; /*!< Transmit PING request */
799 int lagid; /*!< Retransmit lag request */
800 int autoid; /*!< Auto hangup for Dialplan requestor */
801 int authid; /*!< Authentication rejection ID */
802 int authfail; /*!< Reason to report failure */
803 int initid; /*!< Initial peer auto-congest ID (based on qualified peers) */
808 AST_LIST_HEAD_NOLOCK(, iax2_dpcache) dpentries;
809 /*! variables inherited from the user definition */
810 struct ast_variable *vars;
811 /*! variables transmitted in a NEW packet */
812 struct ast_variable *iaxvars;
813 /*! last received remote rr */
814 struct iax_rr remote_rr;
815 /*! Current base time: (just for stats) */
817 /*! Dropped frame count: (just for stats) */
819 /*! received frame count: (just for stats) */
821 /*! num bytes used for calltoken ie, even an empty ie should contain 2 */
822 unsigned char calltoken_ie_len;
823 /*! hold all signaling frames from the pbx thread until we have a destination callno */
825 /*! frame queue for signaling frames from pbx thread waiting for destination callno */
826 AST_LIST_HEAD_NOLOCK(signaling_queue, signaling_queue_entry) signaling_queue;
829 struct signaling_queue_entry {
831 AST_LIST_ENTRY(signaling_queue_entry) next;
834 /*! table of available call numbers */
835 static struct ao2_container *callno_pool;
837 /*! table of available trunk call numbers */
838 static struct ao2_container *callno_pool_trunk;
840 static const unsigned int CALLNO_POOL_BUCKETS = 2699;
843 * \brief a list of frames that may need to be retransmitted
845 * \note The contents of this list do not need to be explicitly destroyed
846 * on module unload. This is because all active calls are destroyed, and
847 * all frames in this queue will get destroyed as a part of that process.
849 * \note Contents protected by the iaxsl[] locks
851 static AST_LIST_HEAD_NOLOCK(, iax_frame) frame_queue[IAX_MAX_CALLS + 1];
853 static struct ast_taskprocessor *transmit_processor;
855 static int randomcalltokendata;
857 static const time_t MAX_CALLTOKEN_DELAY = 10;
860 * This module will get much higher performance when doing a lot of
861 * user and peer lookups if the number of buckets is increased from 1.
862 * However, to maintain old behavior for Asterisk 1.4, these are set to
863 * 1 by default. When using multiple buckets, search order through these
864 * containers is considered random, so you will not be able to depend on
865 * the order the entires are specified in iax.conf for matching order. */
867 #define MAX_PEER_BUCKETS 17
869 #define MAX_PEER_BUCKETS 563
871 static struct ao2_container *peers;
873 #define MAX_USER_BUCKETS MAX_PEER_BUCKETS
874 static struct ao2_container *users;
876 /*! Table containing peercnt objects for every ip address consuming a callno */
877 static struct ao2_container *peercnts;
879 /*! Table containing custom callno limit rules for a range of ip addresses. */
880 static struct ao2_container *callno_limits;
882 /*! Table containing ip addresses not requiring calltoken validation */
883 static struct ao2_container *calltoken_ignores;
885 static uint16_t DEFAULT_MAXCALLNO_LIMIT = 2048;
887 static uint16_t DEFAULT_MAXCALLNO_LIMIT_NONVAL = 8192;
889 static uint16_t global_maxcallno;
891 /*! Total num of call numbers allowed to be allocated without calltoken validation */
892 static uint16_t global_maxcallno_nonval;
894 static uint16_t total_nonval_callno_used = 0;
896 /*! peer connection private, keeps track of all the call numbers
897 * consumed by a single ip address */
899 /*! ip address consuming call numbers */
901 /*! Number of call numbers currently used by this ip address */
903 /*! Max call numbers allowed for this ip address */
905 /*! Specifies whether limit is set by a registration or not, if so normal
906 * limit setting rules do not apply to this address. */
910 /*! used by both callno_limits and calltoken_ignores containers */
912 /*! ip address range for custom callno limit rule */
914 /*! callno limit for this ip address range, only used in callno_limits container */
916 /*! delete me marker for reloads */
920 struct callno_entry {
921 /*! callno used for this entry */
923 /*! was this callno calltoken validated or not */
924 unsigned char validated;
927 static AST_LIST_HEAD_STATIC(firmwares, iax_firmware);
930 /*! Extension exists */
931 CACHE_FLAG_EXISTS = (1 << 0),
932 /*! Extension is nonexistent */
933 CACHE_FLAG_NONEXISTENT = (1 << 1),
934 /*! Extension can exist */
935 CACHE_FLAG_CANEXIST = (1 << 2),
936 /*! Waiting to hear back response */
937 CACHE_FLAG_PENDING = (1 << 3),
939 CACHE_FLAG_TIMEOUT = (1 << 4),
940 /*! Request transmitted */
941 CACHE_FLAG_TRANSMITTED = (1 << 5),
943 CACHE_FLAG_UNKNOWN = (1 << 6),
945 CACHE_FLAG_MATCHMORE = (1 << 7),
948 struct iax2_dpcache {
949 char peercontext[AST_MAX_CONTEXT];
950 char exten[AST_MAX_EXTENSION];
952 struct timeval expiry;
954 unsigned short callno;
956 AST_LIST_ENTRY(iax2_dpcache) cache_list;
957 AST_LIST_ENTRY(iax2_dpcache) peer_list;
960 static AST_LIST_HEAD_STATIC(dpcache, iax2_dpcache);
962 static void reg_source_db(struct iax2_peer *p);
963 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
964 static struct iax2_user *realtime_user(const char *username, struct sockaddr_in *sin);
966 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt);
967 static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags);
968 static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state);
970 enum iax2_thread_iostate {
973 IAX_IOSTATE_PROCESSING,
974 IAX_IOSTATE_SCHEDREADY,
977 enum iax2_thread_type {
978 IAX_THREAD_TYPE_POOL,
979 IAX_THREAD_TYPE_DYNAMIC,
982 struct iax2_pkt_buf {
983 AST_LIST_ENTRY(iax2_pkt_buf) entry;
985 unsigned char buf[1];
989 AST_LIST_ENTRY(iax2_thread) list;
990 enum iax2_thread_type type;
991 enum iax2_thread_iostate iostate;
992 #ifdef SCHED_MULTITHREADED
993 void (*schedfunc)(const void *);
994 const void *scheddata;
996 #ifdef DEBUG_SCHED_MULTITHREAD
1002 struct sockaddr_in iosin;
1003 unsigned char readbuf[4096];
1011 ast_mutex_t init_lock;
1012 ast_cond_t init_cond;
1013 /*! if this thread is processing a full frame,
1014 some information about that frame will be stored
1015 here, so we can avoid dispatching any more full
1016 frames for that callno to other threads */
1018 unsigned short callno;
1019 struct sockaddr_in sin;
1023 /*! Queued up full frames for processing. If more full frames arrive for
1024 * a call which this thread is already processing a full frame for, they
1025 * are queued up here. */
1026 AST_LIST_HEAD_NOLOCK(, iax2_pkt_buf) full_frames;
1030 static AST_LIST_HEAD_STATIC(idle_list, iax2_thread);
1031 static AST_LIST_HEAD_STATIC(active_list, iax2_thread);
1032 static AST_LIST_HEAD_STATIC(dynamic_list, iax2_thread);
1034 static void *iax2_process_thread(void *data);
1035 static void iax2_destroy(int callno);
1037 static void signal_condition(ast_mutex_t *lock, ast_cond_t *cond)
1039 ast_mutex_lock(lock);
1040 ast_cond_signal(cond);
1041 ast_mutex_unlock(lock);
1045 * \brief an array of iax2 pvt structures
1047 * The container for active chan_iax2_pvt structures is implemented as an
1048 * array for extremely quick direct access to the correct pvt structure
1049 * based on the local call number. The local call number is used as the
1050 * index into the array where the associated pvt structure is stored.
1052 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS + 1];
1055 * \brief Another container of iax2_pvt structures
1057 * Active IAX2 pvt structs are also stored in this container, if they are a part
1058 * of an active call where we know the remote side's call number. The reason
1059 * for this is that incoming media frames do not contain our call number. So,
1060 * instead of having to iterate the entire iaxs array, we use this container to
1061 * look up calls where the remote side is using a given call number.
1063 static struct ao2_container *iax_peercallno_pvts;
1066 * \brief chan_iax2_pvt structure locks
1068 * These locks are used when accessing a pvt structure in the iaxs array.
1069 * The index used here is the same as used in the iaxs array. It is the
1070 * local call number for the associated pvt struct.
1072 static ast_mutex_t iaxsl[ARRAY_LEN(iaxs)];
1075 * * \brief Another container of iax2_pvt structures
1077 * Active IAX2 pvt stucts used during transfering a call are stored here.
1079 static struct ao2_container *iax_transfercallno_pvts;
1081 /* Flag to use with trunk calls, keeping these calls high up. It halves our effective use
1082 but keeps the division between trunked and non-trunked better. */
1083 #define TRUNK_CALL_START IAX_MAX_CALLS / 2
1085 /* Debug routines... */
1086 static struct sockaddr_in debugaddr;
1088 static void iax_outputframe(struct iax_frame *f, struct ast_iax2_full_hdr *fhi, int rx, struct sockaddr_in *sin, int datalen)
1091 (sin && debugaddr.sin_addr.s_addr &&
1092 (!ntohs(debugaddr.sin_port) ||
1093 debugaddr.sin_port == sin->sin_port) &&
1094 debugaddr.sin_addr.s_addr == sin->sin_addr.s_addr)) {
1096 iax_showframe(f, fhi, rx, sin, datalen);
1099 iax_showframe(f, fhi, rx, sin, datalen);
1105 static void iax_debug_output(const char *data)
1108 ast_verbose("%s", data);
1111 static void iax_error_output(const char *data)
1113 ast_log(LOG_WARNING, "%s", data);
1116 static void __attribute__((format(printf, 1, 2))) jb_error_output(const char *fmt, ...)
1121 va_start(args, fmt);
1122 vsnprintf(buf, sizeof(buf), fmt, args);
1125 ast_log(LOG_ERROR, "%s", buf);
1128 static void __attribute__((format(printf, 1, 2))) jb_warning_output(const char *fmt, ...)
1133 va_start(args, fmt);
1134 vsnprintf(buf, sizeof(buf), fmt, args);
1137 ast_log(LOG_WARNING, "%s", buf);
1140 static void __attribute__((format(printf, 1, 2))) jb_debug_output(const char *fmt, ...)
1145 va_start(args, fmt);
1146 vsnprintf(buf, sizeof(buf), fmt, args);
1149 ast_verbose("%s", buf);
1152 static int maxtrunkcall = TRUNK_CALL_START;
1153 static int maxnontrunkcall = 1;
1155 static enum ast_bridge_result iax2_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc, int timeoutms);
1156 static int expire_registry(const void *data);
1157 static int iax2_answer(struct ast_channel *c);
1158 static int iax2_call(struct ast_channel *c, char *dest, int timeout);
1159 static int iax2_devicestate(void *data);
1160 static int iax2_digit_begin(struct ast_channel *c, char digit);
1161 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration);
1162 static int iax2_do_register(struct iax2_registry *reg);
1163 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
1164 static int iax2_hangup(struct ast_channel *c);
1165 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen);
1166 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
1167 static int iax2_provision(struct sockaddr_in *end, int sockfd, const char *dest, const char *template, int force);
1168 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
1169 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
1170 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
1171 static int iax2_sendtext(struct ast_channel *c, const char *text);
1172 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
1173 static int iax2_transfer(struct ast_channel *c, const char *dest);
1174 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
1175 static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now);
1176 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1177 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1178 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1179 static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int);
1180 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
1181 static struct ast_channel *iax2_request(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause);
1182 static struct ast_frame *iax2_read(struct ast_channel *c);
1183 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
1184 static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
1185 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, time_t regtime);
1186 static void *iax2_dup_variable_datastore(void *);
1187 static void prune_peers(void);
1188 static void prune_users(void);
1189 static void iax2_free_variable_datastore(void *);
1191 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
1192 static int decode_frame(ast_aes_decrypt_key *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen);
1193 static int encrypt_frame(ast_aes_encrypt_key *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen);
1194 static void build_ecx_key(const unsigned char *digest, struct chan_iax2_pvt *pvt);
1195 static void build_rand_pad(unsigned char *buf, ssize_t len);
1196 static struct callno_entry *get_unused_callno(int trunk, int validated);
1197 static int replace_callno(const void *obj);
1198 static void sched_delay_remove(struct sockaddr_in *sin, struct callno_entry *callno_entry);
1200 static const struct ast_channel_tech iax2_tech = {
1202 .description = tdesc,
1203 .capabilities = IAX_CAPABILITY_FULLBANDWIDTH,
1204 .properties = AST_CHAN_TP_WANTSJITTER,
1205 .requester = iax2_request,
1206 .devicestate = iax2_devicestate,
1207 .send_digit_begin = iax2_digit_begin,
1208 .send_digit_end = iax2_digit_end,
1209 .send_text = iax2_sendtext,
1210 .send_image = iax2_sendimage,
1211 .send_html = iax2_sendhtml,
1213 .hangup = iax2_hangup,
1214 .answer = iax2_answer,
1216 .write = iax2_write,
1217 .write_video = iax2_write,
1218 .indicate = iax2_indicate,
1219 .setoption = iax2_setoption,
1220 .bridge = iax2_bridge,
1221 .transfer = iax2_transfer,
1222 .fixup = iax2_fixup,
1223 .func_channel_read = acf_channel_read,
1226 static void mwi_event_cb(const struct ast_event *event, void *userdata)
1228 /* The MWI subscriptions exist just so the core knows we care about those
1229 * mailboxes. However, we just grab the events out of the cache when it
1230 * is time to send MWI, since it is only sent with a REGACK. */
1233 /*! \brief Send manager event at call setup to link between Asterisk channel name
1234 and IAX2 call identifiers */
1235 static void iax2_ami_channelupdate(struct chan_iax2_pvt *pvt)
1237 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
1238 "Channel: %s\r\nChanneltype: IAX2\r\nIAX2-callno-local: %d\r\nIAX2-callno-remote: %d\r\nIAX2-peer: %s\r\n",
1239 pvt->owner ? pvt->owner->name : "",
1240 pvt->callno, pvt->peercallno, pvt->peer ? pvt->peer : "");
1244 static struct ast_datastore_info iax2_variable_datastore_info = {
1245 .type = "IAX2_VARIABLE",
1246 .duplicate = iax2_dup_variable_datastore,
1247 .destroy = iax2_free_variable_datastore,
1250 static void *iax2_dup_variable_datastore(void *old)
1252 AST_LIST_HEAD(, ast_var_t) *oldlist = old, *newlist;
1253 struct ast_var_t *oldvar, *newvar;
1255 newlist = ast_calloc(sizeof(*newlist), 1);
1257 ast_log(LOG_ERROR, "Unable to duplicate iax2 variables\n");
1261 AST_LIST_HEAD_INIT(newlist);
1262 AST_LIST_LOCK(oldlist);
1263 AST_LIST_TRAVERSE(oldlist, oldvar, entries) {
1264 newvar = ast_var_assign(ast_var_name(oldvar), ast_var_value(oldvar));
1266 AST_LIST_INSERT_TAIL(newlist, newvar, entries);
1268 ast_log(LOG_ERROR, "Unable to duplicate iax2 variable '%s'\n", ast_var_name(oldvar));
1270 AST_LIST_UNLOCK(oldlist);
1274 static void iax2_free_variable_datastore(void *old)
1276 AST_LIST_HEAD(, ast_var_t) *oldlist = old;
1277 struct ast_var_t *oldvar;
1279 AST_LIST_LOCK(oldlist);
1280 while ((oldvar = AST_LIST_REMOVE_HEAD(oldlist, entries))) {
1283 AST_LIST_UNLOCK(oldlist);
1284 AST_LIST_HEAD_DESTROY(oldlist);
1289 /* WARNING: insert_idle_thread should only ever be called within the
1290 * context of an iax2_process_thread() thread.
1292 static void insert_idle_thread(struct iax2_thread *thread)
1294 if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
1295 AST_LIST_LOCK(&dynamic_list);
1296 AST_LIST_INSERT_TAIL(&dynamic_list, thread, list);
1297 AST_LIST_UNLOCK(&dynamic_list);
1299 AST_LIST_LOCK(&idle_list);
1300 AST_LIST_INSERT_TAIL(&idle_list, thread, list);
1301 AST_LIST_UNLOCK(&idle_list);
1307 static struct iax2_thread *find_idle_thread(void)
1309 struct iax2_thread *thread = NULL;
1311 /* Pop the head of the idle list off */
1312 AST_LIST_LOCK(&idle_list);
1313 thread = AST_LIST_REMOVE_HEAD(&idle_list, list);
1314 AST_LIST_UNLOCK(&idle_list);
1316 /* If we popped a thread off the idle list, just return it */
1318 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1322 /* Pop the head of the dynamic list off */
1323 AST_LIST_LOCK(&dynamic_list);
1324 thread = AST_LIST_REMOVE_HEAD(&dynamic_list, list);
1325 AST_LIST_UNLOCK(&dynamic_list);
1327 /* If we popped a thread off the dynamic list, just return it */
1329 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1333 /* If we can't create a new dynamic thread for any reason, return no thread at all */
1334 if (iaxdynamicthreadcount >= iaxmaxthreadcount || !(thread = ast_calloc(1, sizeof(*thread))))
1337 /* Set default values */
1338 ast_atomic_fetchadd_int(&iaxdynamicthreadcount, 1);
1339 thread->threadnum = ast_atomic_fetchadd_int(&iaxdynamicthreadnum, 1);
1340 thread->type = IAX_THREAD_TYPE_DYNAMIC;
1342 /* Initialize lock and condition */
1343 ast_mutex_init(&thread->lock);
1344 ast_cond_init(&thread->cond, NULL);
1345 ast_mutex_init(&thread->init_lock);
1346 ast_cond_init(&thread->init_cond, NULL);
1347 ast_mutex_lock(&thread->init_lock);
1349 /* Create thread and send it on it's way */
1350 if (ast_pthread_create_detached_background(&thread->threadid, NULL, iax2_process_thread, thread)) {
1351 ast_cond_destroy(&thread->cond);
1352 ast_mutex_destroy(&thread->lock);
1357 /* this thread is not processing a full frame (since it is idle),
1358 so ensure that the field for the full frame call number is empty */
1359 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1361 /* Wait for the thread to be ready before returning it to the caller */
1362 ast_cond_wait(&thread->init_cond, &thread->init_lock);
1364 /* Done with init_lock */
1365 ast_mutex_unlock(&thread->init_lock);
1370 #ifdef SCHED_MULTITHREADED
1371 static int __schedule_action(void (*func)(const void *data), const void *data, const char *funcname)
1373 struct iax2_thread *thread = NULL;
1374 static time_t lasterror;
1377 thread = find_idle_thread();
1379 if (thread != NULL) {
1380 thread->schedfunc = func;
1381 thread->scheddata = data;
1382 thread->iostate = IAX_IOSTATE_SCHEDREADY;
1383 #ifdef DEBUG_SCHED_MULTITHREAD
1384 ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc));
1386 signal_condition(&thread->lock, &thread->cond);
1391 ast_debug(1, "Out of idle IAX2 threads for scheduling!\n");
1396 #define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
1399 static int iax2_sched_replace(int id, struct ast_sched_thread *st, int when,
1400 ast_sched_cb callback, const void *data)
1402 ast_sched_thread_del(st, id);
1404 return ast_sched_thread_add(st, when, callback, data);
1407 static int iax2_sched_add(struct ast_sched_thread *st, int when,
1408 ast_sched_cb callback, const void *data)
1410 return ast_sched_thread_add(st, when, callback, data);
1413 static int send_ping(const void *data);
1415 static void __send_ping(const void *data)
1417 int callno = (long) data;
1419 ast_mutex_lock(&iaxsl[callno]);
1422 if (iaxs[callno]->peercallno) {
1423 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
1424 iaxs[callno]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, data);
1426 /* I am the schedule, so I'm allowed to do this */
1427 iaxs[callno]->pingid = -1;
1430 ast_debug(1, "I was supposed to send a PING with callno %d, but no such call exists.\n", callno);
1433 ast_mutex_unlock(&iaxsl[callno]);
1436 static int send_ping(const void *data)
1438 #ifdef SCHED_MULTITHREADED
1439 if (schedule_action(__send_ping, data))
1446 static void encmethods_to_str(int e, struct ast_str *buf)
1448 ast_str_set(&buf, 0, "(");
1449 if (e & IAX_ENCRYPT_AES128) {
1450 ast_str_append(&buf, 0, "aes128");
1452 if (e & IAX_ENCRYPT_KEYROTATE) {
1453 ast_str_append(&buf, 0, ",keyrotate");
1455 if (ast_str_strlen(buf) > 1) {
1456 ast_str_append(&buf, 0, ")");
1458 ast_str_set(&buf, 0, "No");
1462 static int get_encrypt_methods(const char *s)
1465 if (!strcasecmp(s, "aes128"))
1466 e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
1467 else if (ast_true(s))
1468 e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
1474 static int send_lagrq(const void *data);
1476 static void __send_lagrq(const void *data)
1478 int callno = (long) data;
1480 ast_mutex_lock(&iaxsl[callno]);
1483 if (iaxs[callno]->peercallno) {
1484 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
1485 iaxs[callno]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, data);
1487 /* I am the schedule, so I'm allowed to do this */
1488 iaxs[callno]->lagid = -1;
1491 ast_debug(1, "I was supposed to send a LAGRQ with callno %d, but no such call exists.\n", callno);
1494 ast_mutex_unlock(&iaxsl[callno]);
1497 static int send_lagrq(const void *data)
1499 #ifdef SCHED_MULTITHREADED
1500 if (schedule_action(__send_lagrq, data))
1507 static unsigned char compress_subclass(format_t subclass)
1511 /* If it's 64 or smaller, just return it */
1512 if (subclass < IAX_FLAG_SC_LOG)
1514 /* Otherwise find its power */
1515 for (x = 0; x < IAX_MAX_SHIFT; x++) {
1516 if (subclass & (1LL << x)) {
1518 ast_log(LOG_WARNING, "Can't compress subclass %lld\n", (long long) subclass);
1524 return power | IAX_FLAG_SC_LOG;
1527 static format_t uncompress_subclass(unsigned char csub)
1529 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
1530 if (csub & IAX_FLAG_SC_LOG) {
1531 /* special case for 'compressed' -1 */
1535 return 1LL << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
1542 * \note The only member of the peer passed here guaranteed to be set is the name field
1544 static int peer_hash_cb(const void *obj, const int flags)
1546 const struct iax2_peer *peer = obj;
1548 return ast_str_hash(peer->name);
1552 * \note The only member of the peer passed here guaranteed to be set is the name field
1554 static int peer_cmp_cb(void *obj, void *arg, int flags)
1556 struct iax2_peer *peer = obj, *peer2 = arg;
1558 return !strcmp(peer->name, peer2->name) ? CMP_MATCH | CMP_STOP : 0;
1562 * \note The only member of the user passed here guaranteed to be set is the name field
1564 static int user_hash_cb(const void *obj, const int flags)
1566 const struct iax2_user *user = obj;
1568 return ast_str_hash(user->name);
1572 * \note The only member of the user passed here guaranteed to be set is the name field
1574 static int user_cmp_cb(void *obj, void *arg, int flags)
1576 struct iax2_user *user = obj, *user2 = arg;
1578 return !strcmp(user->name, user2->name) ? CMP_MATCH | CMP_STOP : 0;
1582 * \note This funtion calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
1583 * so do not call it with a pvt lock held.
1585 static struct iax2_peer *find_peer(const char *name, int realtime)
1587 struct iax2_peer *peer = NULL;
1588 struct iax2_peer tmp_peer = {
1592 peer = ao2_find(peers, &tmp_peer, OBJ_POINTER);
1594 /* Now go for realtime if applicable */
1595 if(!peer && realtime)
1596 peer = realtime_peer(name, NULL);
1601 static struct iax2_peer *peer_ref(struct iax2_peer *peer)
1607 static inline struct iax2_peer *peer_unref(struct iax2_peer *peer)
1613 static struct iax2_user *find_user(const char *name)
1615 struct iax2_user tmp_user = {
1619 return ao2_find(users, &tmp_user, OBJ_POINTER);
1621 static inline struct iax2_user *user_ref(struct iax2_user *user)
1627 static inline struct iax2_user *user_unref(struct iax2_user *user)
1633 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len)
1635 struct iax2_peer *peer = NULL;
1637 struct ao2_iterator i;
1639 i = ao2_iterator_init(peers, 0);
1640 while ((peer = ao2_iterator_next(&i))) {
1641 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
1642 (peer->addr.sin_port == sin.sin_port)) {
1643 ast_copy_string(host, peer->name, len);
1650 ao2_iterator_destroy(&i);
1653 peer = realtime_peer(NULL, &sin);
1655 ast_copy_string(host, peer->name, len);
1664 /*!\note Assumes the lock on the pvt is already held, when
1665 * iax2_destroy_helper() is called. */
1666 static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
1668 /* Decrement AUTHREQ count if needed */
1669 if (ast_test_flag64(pvt, IAX_MAXAUTHREQ)) {
1670 struct iax2_user *user;
1671 struct iax2_user tmp_user = {
1672 .name = pvt->username,
1675 user = ao2_find(users, &tmp_user, OBJ_POINTER);
1677 ast_atomic_fetchadd_int(&user->curauthreq, -1);
1681 ast_clear_flag64(pvt, IAX_MAXAUTHREQ);
1683 /* No more pings or lagrq's */
1684 AST_SCHED_DEL_SPINLOCK(ast_sched_thread_get_context(sched), pvt->pingid, &iaxsl[pvt->callno]);
1685 AST_SCHED_DEL_SPINLOCK(ast_sched_thread_get_context(sched), pvt->lagid, &iaxsl[pvt->callno]);
1686 ast_sched_thread_del(sched, pvt->autoid);
1687 ast_sched_thread_del(sched, pvt->authid);
1688 ast_sched_thread_del(sched, pvt->initid);
1689 ast_sched_thread_del(sched, pvt->jbid);
1690 ast_sched_thread_del(sched, pvt->keyrotateid);
1693 static void iax2_frame_free(struct iax_frame *fr)
1695 ast_sched_thread_del(sched, fr->retrans);
1699 static int scheduled_destroy(const void *vid)
1701 unsigned short callno = PTR_TO_CALLNO(vid);
1702 ast_mutex_lock(&iaxsl[callno]);
1705 ast_log(LOG_DEBUG, "Really destroying %d now...\n", callno);
1707 iax2_destroy(callno);
1709 ast_mutex_unlock(&iaxsl[callno]);
1713 static void free_signaling_queue_entry(struct signaling_queue_entry *s)
1715 ast_free(s->f.data.ptr);
1719 /*! \brief This function must be called once we are sure the other side has
1720 * given us a call number. All signaling is held here until that point. */
1721 static void send_signaling(struct chan_iax2_pvt *pvt)
1723 struct signaling_queue_entry *s = NULL;
1725 while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
1726 iax2_send(pvt, &s->f, 0, -1, 0, 0, 0);
1727 free_signaling_queue_entry(s);
1729 pvt->hold_signaling = 0;
1732 /*! \brief All frames other than that of type AST_FRAME_IAX must be held until
1733 * we have received a destination call number. */
1734 static int queue_signalling(struct chan_iax2_pvt *pvt, struct ast_frame *f)
1736 struct signaling_queue_entry *new;
1738 if (f->frametype == AST_FRAME_IAX || !pvt->hold_signaling) {
1739 return 1; /* do not queue this frame */
1740 } else if (!(new = ast_calloc(1, sizeof(struct signaling_queue_entry)))) {
1741 return -1; /* out of memory */
1744 memcpy(&new->f, f, sizeof(new->f)); /* copy ast_frame into our queue entry */
1746 if (new->f.datalen) { /* if there is data in this frame copy it over as well */
1747 if (!(new->f.data.ptr = ast_calloc(1, new->f.datalen))) {
1748 free_signaling_queue_entry(new);
1751 memcpy(new->f.data.ptr, f->data.ptr, sizeof(*new->f.data.ptr));
1753 AST_LIST_INSERT_TAIL(&pvt->signaling_queue, new, next);
1758 static void pvt_destructor(void *obj)
1760 struct chan_iax2_pvt *pvt = obj;
1761 struct iax_frame *cur = NULL;
1762 struct signaling_queue_entry *s = NULL;
1764 ast_mutex_lock(&iaxsl[pvt->callno]);
1766 iax2_destroy_helper(pvt);
1768 sched_delay_remove(&pvt->addr, pvt->callno_entry);
1769 pvt->callno_entry = NULL;
1772 ast_set_flag64(pvt, IAX_ALREADYGONE);
1774 AST_LIST_TRAVERSE(&frame_queue[pvt->callno], cur, list) {
1775 /* Cancel any pending transmissions */
1779 ast_mutex_unlock(&iaxsl[pvt->callno]);
1781 while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
1782 free_signaling_queue_entry(s);
1786 pvt->reg->callno = 0;
1792 ast_variables_destroy(pvt->vars);
1796 while (jb_getall(pvt->jb, &frame) == JB_OK) {
1797 iax2_frame_free(frame.data);
1800 jb_destroy(pvt->jb);
1801 ast_string_field_free_memory(pvt);
1805 static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, const char *host)
1807 struct chan_iax2_pvt *tmp;
1810 if (!(tmp = ao2_alloc(sizeof(*tmp), pvt_destructor))) {
1814 if (ast_string_field_init(tmp, 32)) {
1826 tmp->keyrotateid = -1;
1828 ast_string_field_set(tmp,exten, "s");
1829 ast_string_field_set(tmp,host, host);
1833 jbconf.max_jitterbuf = maxjitterbuffer;
1834 jbconf.resync_threshold = resyncthreshold;
1835 jbconf.max_contig_interp = maxjitterinterps;
1836 jbconf.target_extra = jittertargetextra;
1837 jb_setconf(tmp->jb,&jbconf);
1839 AST_LIST_HEAD_INIT_NOLOCK(&tmp->dpentries);
1841 tmp->hold_signaling = 1;
1842 AST_LIST_HEAD_INIT_NOLOCK(&tmp->signaling_queue);
1847 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
1849 struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen, fr->cacheable);
1851 size_t afdatalen = new->afdatalen;
1852 memcpy(new, fr, sizeof(*new));
1853 iax_frame_wrap(new, &fr->af);
1854 new->afdatalen = afdatalen;
1857 new->direction = DIRECTION_INGRESS;
1862 /* keep these defined in this order. They are used in find_callno to
1863 * determine whether or not a new call number should be allowed. */
1865 /* do not allow a new call number, only search ones in use for match */
1867 /* search for match first, then allow a new one to be allocated */
1869 /* do not search for match, force a new call number */
1871 /* do not search for match, force a new call number. Signifies call number
1872 * has been calltoken validated */
1873 NEW_ALLOW_CALLTOKEN_VALIDATED = 3,
1876 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, const struct chan_iax2_pvt *cur, int check_dcallno)
1878 if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
1879 (cur->addr.sin_port == sin->sin_port)) {
1880 /* This is the main host */
1881 if ( (cur->peercallno == 0 || cur->peercallno == callno) &&
1882 (check_dcallno ? dcallno == cur->callno : 1) ) {
1883 /* That's us. Be sure we keep track of the peer call number */
1887 if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
1888 (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
1889 /* We're transferring */
1890 if ((dcallno == cur->callno) || (cur->transferring == TRANSFER_MEDIAPASS && cur->transfercallno == callno))
1896 static void update_max_trunk(void)
1898 int max = TRUNK_CALL_START;
1901 /* XXX Prolly don't need locks here XXX */
1902 for (x = TRUNK_CALL_START; x < ARRAY_LEN(iaxs) - 1; x++) {
1910 ast_debug(1, "New max trunk callno is %d\n", max);
1913 static void update_max_nontrunk(void)
1917 /* XXX Prolly don't need locks here XXX */
1918 for (x=1;x<TRUNK_CALL_START - 1; x++) {
1922 maxnontrunkcall = max;
1924 ast_debug(1, "New max nontrunk callno is %d\n", max);
1927 static int make_trunk(unsigned short callno, int locked)
1931 struct callno_entry *callno_entry;
1932 if (iaxs[callno]->oseqno) {
1933 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
1936 if (callno & TRUNK_CALL_START) {
1937 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
1941 if (!(callno_entry = get_unused_callno(1, iaxs[callno]->callno_entry->validated))) {
1942 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
1946 x = callno_entry->callno;
1947 ast_mutex_lock(&iaxsl[x]);
1950 * \note We delete these before switching the slot, because if
1951 * they fire in the meantime, they will generate a warning.
1953 ast_sched_thread_del(sched, iaxs[callno]->pingid);
1954 ast_sched_thread_del(sched, iaxs[callno]->lagid);
1955 iaxs[x] = iaxs[callno];
1956 iaxs[x]->callno = x;
1958 /* since we copied over the pvt from a different callno, make sure the old entry is replaced
1959 * before assigning the new one */
1960 if (iaxs[x]->callno_entry) {
1961 iax2_sched_add(sched, MIN_REUSE_TIME * 1000, replace_callno, iaxs[x]->callno_entry);
1963 iaxs[x]->callno_entry = callno_entry;
1965 iaxs[callno] = NULL;
1966 /* Update the two timers that should have been started */
1967 iaxs[x]->pingid = iax2_sched_add(sched,
1968 ping_time * 1000, send_ping, (void *)(long)x);
1969 iaxs[x]->lagid = iax2_sched_add(sched,
1970 lagrq_time * 1000, send_lagrq, (void *)(long)x);
1973 ast_mutex_unlock(&iaxsl[callno]);
1976 ast_mutex_unlock(&iaxsl[x]);
1978 ast_debug(1, "Made call %d into trunk call %d\n", callno, x);
1979 /* We move this call from a non-trunked to a trunked call */
1981 update_max_nontrunk();
1985 static void store_by_transfercallno(struct chan_iax2_pvt *pvt)
1987 if (!pvt->transfercallno) {
1988 ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
1992 ao2_link(iax_transfercallno_pvts, pvt);
1995 static void remove_by_transfercallno(struct chan_iax2_pvt *pvt)
1997 if (!pvt->transfercallno) {
1998 ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
2002 ao2_unlink(iax_transfercallno_pvts, pvt);
2004 static void store_by_peercallno(struct chan_iax2_pvt *pvt)
2006 if (!pvt->peercallno) {
2007 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
2011 ao2_link(iax_peercallno_pvts, pvt);
2014 static void remove_by_peercallno(struct chan_iax2_pvt *pvt)
2016 if (!pvt->peercallno) {
2017 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
2021 ao2_unlink(iax_peercallno_pvts, pvt);
2024 static int addr_range_delme_cb(void *obj, void *arg, int flags)
2026 struct addr_range *lim = obj;
2031 static int addr_range_hash_cb(const void *obj, const int flags)
2033 const struct addr_range *lim = obj;
2034 return abs((int) lim->ha.netaddr.s_addr);
2037 static int addr_range_cmp_cb(void *obj, void *arg, int flags)
2039 struct addr_range *lim1 = obj, *lim2 = arg;
2040 return ((lim1->ha.netaddr.s_addr == lim2->ha.netaddr.s_addr) &&
2041 (lim1->ha.netmask.s_addr == lim2->ha.netmask.s_addr)) ?
2042 CMP_MATCH | CMP_STOP : 0;
2045 static int peercnt_hash_cb(const void *obj, const int flags)
2047 const struct peercnt *peercnt = obj;
2048 return abs((int) peercnt->addr);
2051 static int peercnt_cmp_cb(void *obj, void *arg, int flags)
2053 struct peercnt *peercnt1 = obj, *peercnt2 = arg;
2054 return (peercnt1->addr == peercnt2->addr) ? CMP_MATCH | CMP_STOP : 0;
2057 static int addr_range_match_address_cb(void *obj, void *arg, int flags)
2059 struct addr_range *addr_range = obj;
2060 struct sockaddr_in *sin = arg;
2062 if ((sin->sin_addr.s_addr & addr_range->ha.netmask.s_addr) == addr_range->ha.netaddr.s_addr) {
2063 return CMP_MATCH | CMP_STOP;
2071 * \brief compares sin to calltoken_ignores table to determine if validation is required.
2073 static int calltoken_required(struct sockaddr_in *sin, const char *name, int subclass)
2075 struct addr_range *addr_range;
2076 struct iax2_peer *peer = NULL;
2077 struct iax2_user *user = NULL;
2078 /* if no username is given, check for guest accounts */
2079 const char *find = S_OR(name, "guest");
2080 int res = 1; /* required by default */
2082 enum calltoken_peer_enum calltoken_required = CALLTOKEN_DEFAULT;
2083 /* There are only two cases in which calltoken validation is not required.
2084 * Case 1. sin falls within the list of address ranges specified in the calltoken optional table and
2085 * the peer definition has not set the requirecalltoken option.
2086 * Case 2. Username is a valid peer/user, and that peer has requirecalltoken set either auto or no.
2089 /* ----- Case 1 ----- */
2090 if ((addr_range = ao2_callback(calltoken_ignores, 0, addr_range_match_address_cb, sin))) {
2091 ao2_ref(addr_range, -1);
2095 /* ----- Case 2 ----- */
2096 if ((subclass == IAX_COMMAND_NEW) && (user = find_user(find))) {
2097 calltoken_required = user->calltoken_required;
2098 } else if ((subclass == IAX_COMMAND_NEW) && (user = realtime_user(find, sin))) {
2099 calltoken_required = user->calltoken_required;
2100 } else if ((subclass != IAX_COMMAND_NEW) && (peer = find_peer(find, 0))) {
2101 calltoken_required = peer->calltoken_required;
2102 } else if ((subclass != IAX_COMMAND_NEW) && (peer = realtime_peer(find, sin))) {
2103 calltoken_required = peer->calltoken_required;
2113 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);
2114 if (((calltoken_required == CALLTOKEN_NO) || (calltoken_required == CALLTOKEN_AUTO)) ||
2115 (optional && (calltoken_required == CALLTOKEN_DEFAULT))) {
2125 * \brief set peercnt callno limit.
2128 * First looks in custom definitions. If not found, global limit
2129 * is used. Entries marked as reg already have
2130 * a custom limit set by a registration and are not modified.
2132 static void set_peercnt_limit(struct peercnt *peercnt)
2134 uint16_t limit = global_maxcallno;
2135 struct addr_range *addr_range;
2136 struct sockaddr_in sin = {
2137 .sin_addr.s_addr = peercnt->addr,
2141 if (peercnt->reg && peercnt->limit) {
2142 return; /* this peercnt has a custom limit set by a registration */
2145 if ((addr_range = ao2_callback(callno_limits, 0, addr_range_match_address_cb, &sin))) {
2146 limit = addr_range->limit;
2147 ast_debug(1, "custom addr_range %d found for %s\n", limit, ast_inet_ntoa(sin.sin_addr));
2148 ao2_ref(addr_range, -1);
2151 peercnt->limit = limit;
2156 * \brief sets limits for all peercnts in table. done on reload to reflect changes in conf.
2158 static int set_peercnt_limit_all_cb(void *obj, void *arg, int flags)
2160 struct peercnt *peercnt = obj;
2162 set_peercnt_limit(peercnt);
2163 ast_debug(1, "Reset limits for peercnts table\n");
2170 * \brief returns match if delme is set.
2172 static int prune_addr_range_cb(void *obj, void *arg, int flags)
2174 struct addr_range *addr_range = obj;
2176 return addr_range->delme ? CMP_MATCH : 0;
2181 * \brief modifies peercnt entry in peercnts table. Used to set custom limit or mark a registered ip
2183 static void peercnt_modify(unsigned char reg, uint16_t limit, struct sockaddr_in *sin)
2185 /* this function turns off and on custom callno limits set by peer registration */
2186 struct peercnt *peercnt;
2187 struct peercnt tmp = {
2188 .addr = sin->sin_addr.s_addr,
2191 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2194 peercnt->limit = limit;
2196 set_peercnt_limit(peercnt);
2198 ast_debug(1, "peercnt entry %s modified limit:%d registered:%d", ast_inet_ntoa(sin->sin_addr), peercnt->limit, peercnt->reg);
2199 ao2_ref(peercnt, -1); /* decrement ref from find */
2205 * \brief adds an ip to the peercnts table, increments connection count if it already exists
2207 * \details First searches for the address in the peercnts table. If found
2208 * the current count is incremented. If not found a new peercnt is allocated
2209 * and linked into the peercnts table with a call number count of 1.
2211 static int peercnt_add(struct sockaddr_in *sin)
2213 struct peercnt *peercnt;
2214 unsigned long addr = sin->sin_addr.s_addr;
2216 struct peercnt tmp = {
2220 /* Reasoning for peercnts container lock: Two identical ip addresses
2221 * could be added by different threads at the "same time". Without the container
2222 * lock, both threads could alloc space for the same object and attempt
2223 * to link to table. With the lock, one would create the object and link
2224 * to table while the other would find the already created peercnt object
2225 * rather than creating a new one. */
2227 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2229 } else if ((peercnt = ao2_alloc(sizeof(*peercnt), NULL))) {
2231 /* create and set defaults */
2232 peercnt->addr = addr;
2233 set_peercnt_limit(peercnt);
2234 /* guarantees it does not go away after unlocking table
2235 * ao2_find automatically adds this */
2236 ao2_link(peercnts, peercnt);
2238 ao2_unlock(peercnts);
2242 /* check to see if the address has hit its callno limit. If not increment cur. */
2243 if (peercnt->limit > peercnt->cur) {
2245 ast_debug(1, "ip callno count incremented to %d for %s\n", peercnt->cur, ast_inet_ntoa(sin->sin_addr));
2246 } else { /* max num call numbers for this peer has been reached! */
2247 ast_log(LOG_ERROR, "maxcallnumber limit of %d for %s has been reached!\n", peercnt->limit, ast_inet_ntoa(sin->sin_addr));
2251 /* clean up locks and ref count */
2252 ao2_unlock(peercnt);
2253 ao2_unlock(peercnts);
2254 ao2_ref(peercnt, -1); /* decrement ref from find/alloc, only the container ref remains. */
2261 * \brief decrements a peercnts table entry
2263 static void peercnt_remove(struct peercnt *peercnt)
2265 struct sockaddr_in sin = {
2266 .sin_addr.s_addr = peercnt->addr,
2270 /* Container locked here since peercnt may be unlinked from list. If left unlocked,
2271 * peercnt_add could try and grab this entry from the table and modify it at the
2272 * "same time" this thread attemps to unlink it.*/
2275 ast_debug(1, "ip callno count decremented to %d for %s\n", peercnt->cur, ast_inet_ntoa(sin.sin_addr));
2276 /* if this was the last connection from the peer remove it from table */
2277 if (peercnt->cur == 0) {
2278 ao2_unlink(peercnts, peercnt);/* decrements ref from table, last ref is left to scheduler */
2280 ao2_unlock(peercnts);
2286 * \brief called by scheduler to decrement object
2288 static int peercnt_remove_cb(const void *obj)
2290 struct peercnt *peercnt = (struct peercnt *) obj;
2292 peercnt_remove(peercnt);
2293 ao2_ref(peercnt, -1); /* decrement ref from scheduler */
2300 * \brief decrements peercnts connection count, finds by addr
2302 static int peercnt_remove_by_addr(struct sockaddr_in *sin)
2304 struct peercnt *peercnt;
2305 struct peercnt tmp = {
2306 .addr = sin->sin_addr.s_addr,
2309 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2310 peercnt_remove(peercnt);
2311 ao2_ref(peercnt, -1); /* decrement ref from find */
2318 * \brief Create callno_limit entry based on configuration
2320 static void build_callno_limits(struct ast_variable *v)
2322 struct addr_range *addr_range = NULL;
2323 struct addr_range tmp;
2329 for (; v; v = v->next) {
2333 ha = ast_append_ha("permit", v->name, NULL, &error);
2335 /* check for valid config information */
2337 ast_log(LOG_ERROR, "Call number limit for %s could not be added, Invalid address range\n.", v->name);
2339 } else if ((sscanf(v->value, "%d", &limit) != 1) || (limit < 0)) {
2340 ast_log(LOG_ERROR, "Call number limit for %s could not be added. Invalid limit %s\n.", v->name, v->value);
2345 ast_copy_ha(ha, &tmp.ha);
2346 /* find or create the addr_range */
2347 if ((addr_range = ao2_find(callno_limits, &tmp, OBJ_POINTER))) {
2348 ao2_lock(addr_range);
2350 } else if (!(addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
2352 return; /* out of memory */
2355 /* copy over config data into addr_range object */
2356 ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible for each limit */
2357 ast_free_ha(ha); /* cleanup the tmp ha */
2358 addr_range->limit = limit;
2359 addr_range->delme = 0;
2363 ao2_unlock(addr_range);
2365 ao2_link(callno_limits, addr_range);
2367 ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
2373 * \brief Create calltoken_ignores entry based on configuration
2375 static int add_calltoken_ignore(const char *addr)
2377 struct addr_range tmp;
2378 struct addr_range *addr_range = NULL;
2379 struct ast_ha *ha = NULL;
2382 if (ast_strlen_zero(addr)) {
2383 ast_log(LOG_WARNING, "invalid calltokenoptional %s\n", addr);
2387 ha = ast_append_ha("permit", addr, NULL, &error);
2389 /* check for valid config information */
2391 ast_log(LOG_WARNING, "Error %d creating calltokenoptional entry %s\n", error, addr);
2395 ast_copy_ha(ha, &tmp.ha);
2396 /* find or create the addr_range */
2397 if ((addr_range = ao2_find(calltoken_ignores, &tmp, OBJ_POINTER))) {
2398 ao2_lock(addr_range);
2399 addr_range->delme = 0;
2400 ao2_unlock(addr_range);
2401 } else if ((addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
2402 /* copy over config data into addr_range object */
2403 ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible */
2404 ao2_link(calltoken_ignores, addr_range);
2411 ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
2416 static char *handle_cli_iax2_show_callno_limits(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2418 struct ao2_iterator i;
2419 struct peercnt *peercnt;
2420 struct sockaddr_in sin;
2425 e->command = "iax2 show callnumber usage";
2427 "Usage: iax2 show callnumber usage [IP address]\n"
2428 " Shows current IP addresses which are consuming iax2 call numbers\n";
2433 if (a->argc < 4 || a->argc > 5)
2434 return CLI_SHOWUSAGE;
2436 ast_cli(a->fd, "%-15s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
2437 i = ao2_iterator_init(peercnts, 0);
2438 while ((peercnt = ao2_iterator_next(&i))) {
2439 sin.sin_addr.s_addr = peercnt->addr;
2440 if (a->argc == 5 && (!strcasecmp(a->argv[4], ast_inet_ntoa(sin.sin_addr)))) {
2441 ast_cli(a->fd, "%-15s %-12d %-12d\n", ast_inet_ntoa(sin.sin_addr), peercnt->cur, peercnt->limit);
2445 ast_cli(a->fd, "%-15s %-12d %-12d\n", ast_inet_ntoa(sin.sin_addr), peercnt->cur, peercnt->limit);
2447 ao2_ref(peercnt, -1);
2449 ao2_iterator_destroy(&i);
2452 ast_cli(a->fd, "\nNon-CallToken Validation Callno Limit: %d\n"
2453 "Non-CallToken Validated Callno Used: %d\n",
2454 global_maxcallno_nonval,
2455 total_nonval_callno_used);
2457 ast_cli(a->fd, "Total Available Callno: %d\n"
2458 "Regular Callno Available: %d\n"
2459 "Trunk Callno Available: %d\n",
2460 ao2_container_count(callno_pool) + ao2_container_count(callno_pool_trunk),
2461 ao2_container_count(callno_pool),
2462 ao2_container_count(callno_pool_trunk));
2463 } else if (a->argc == 5 && !found) {
2464 ast_cli(a->fd, "No callnumber table entries for %s found\n", a->argv[4] );
2474 static struct callno_entry *get_unused_callno(int trunk, int validated)
2476 struct callno_entry *callno_entry = NULL;
2477 if ((!ao2_container_count(callno_pool) && !trunk) || (!ao2_container_count(callno_pool_trunk) && trunk)) {
2478 ast_log(LOG_WARNING, "Out of CallNumbers\n");
2479 /* Minor optimization for the extreme case. */
2483 /* the callno_pool container is locked here primarily to ensure thread
2484 * safety of the total_nonval_callno_used check and increment */
2485 ao2_lock(callno_pool);
2487 /* only a certain number of nonvalidated call numbers should be allocated.
2488 * If there ever is an attack, this separates the calltoken validating
2489 * users from the non calltoken validating users. */
2490 if (!validated && (total_nonval_callno_used >= global_maxcallno_nonval)) {
2491 ast_log(LOG_WARNING, "NON-CallToken callnumber limit is reached. Current:%d Max:%d\n", total_nonval_callno_used, global_maxcallno_nonval);
2492 ao2_unlock(callno_pool);
2496 /* unlink the object from the container, taking over ownership
2497 * of the reference the container had to the object */
2498 callno_entry = ao2_find((trunk ? callno_pool_trunk : callno_pool), NULL, OBJ_POINTER | OBJ_UNLINK | OBJ_CONTINUE);
2501 callno_entry->validated = validated;
2503 total_nonval_callno_used++;
2507 ao2_unlock(callno_pool);
2508 return callno_entry;
2511 static int replace_callno(const void *obj)
2513 struct callno_entry *callno_entry = (struct callno_entry *) obj;
2515 /* the callno_pool container is locked here primarily to ensure thread
2516 * safety of the total_nonval_callno_used check and decrement */
2517 ao2_lock(callno_pool);
2519 if (!callno_entry->validated && (total_nonval_callno_used != 0)) {
2520 total_nonval_callno_used--;
2521 } else if (!callno_entry->validated && (total_nonval_callno_used == 0)) {
2522 ast_log(LOG_ERROR, "Attempted to decrement total non calltoken validated callnumbers below zero... Callno is:%d \n", callno_entry->callno);
2525 if (callno_entry->callno < TRUNK_CALL_START) {
2526 ao2_link(callno_pool, callno_entry);
2528 ao2_link(callno_pool_trunk, callno_entry);
2530 ao2_ref(callno_entry, -1); /* only container ref remains */
2532 ao2_unlock(callno_pool);
2536 static int callno_hash(const void *obj, const int flags)
2538 return abs(ast_random());
2541 static int create_callno_pools(void)
2545 if (!(callno_pool = ao2_container_alloc(CALLNO_POOL_BUCKETS, callno_hash, NULL))) {
2549 if (!(callno_pool_trunk = ao2_container_alloc(CALLNO_POOL_BUCKETS, callno_hash, NULL))) {
2553 /* start at 2, 0 and 1 are reserved */
2554 for (i = 2; i <= IAX_MAX_CALLS; i++) {
2555 struct callno_entry *callno_entry;
2557 if (!(callno_entry = ao2_alloc(sizeof(*callno_entry), NULL))) {
2561 callno_entry->callno = i;
2563 if (i < TRUNK_CALL_START) {
2564 ao2_link(callno_pool, callno_entry);
2566 ao2_link(callno_pool_trunk, callno_entry);
2569 ao2_ref(callno_entry, -1);
2577 * \brief Schedules delayed removal of iax2_pvt call number data
2579 * \note After MIN_REUSE_TIME has passed for a destroyed iax2_pvt, the callno is
2580 * avaliable again, and the address from the previous connection must be decremented
2581 * from the peercnts table. This function schedules these operations to take place.
2583 static void sched_delay_remove(struct sockaddr_in *sin, struct callno_entry *callno_entry)
2586 struct peercnt *peercnt;
2587 struct peercnt tmp = {
2588 .addr = sin->sin_addr.s_addr,
2591 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2592 /* refcount is incremented with ao2_find. keep that ref for the scheduler */
2593 ast_debug(1, "schedule decrement of callno used for %s in %d seconds\n", ast_inet_ntoa(sin->sin_addr), MIN_REUSE_TIME);
2594 i = iax2_sched_add(sched, MIN_REUSE_TIME * 1000, peercnt_remove_cb, peercnt);
2596 ao2_ref(peercnt, -1);
2600 iax2_sched_add(sched, MIN_REUSE_TIME * 1000, replace_callno, callno_entry);
2605 * \brief returns whether or not a frame is capable of starting a new IAX2 dialog.
2607 * \note For this implementation, inbound pokes should _NOT_ be capable of allocating
2610 static inline int attribute_pure iax2_allow_new(int frametype, int subclass, int inbound)
2612 if (frametype != AST_FRAME_IAX) {
2616 case IAX_COMMAND_NEW:
2617 case IAX_COMMAND_REGREQ:
2618 case IAX_COMMAND_FWDOWNL:
2619 case IAX_COMMAND_REGREL:
2621 case IAX_COMMAND_POKE:
2631 * \note Calling this function while holding another pvt lock can cause a deadlock.
2633 static int __find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int return_locked, int check_dcallno)
2637 /* this call is calltoken validated as long as it is either NEW_FORCE
2638 * or NEW_ALLOW_CALLTOKEN_VALIDATED */
2639 int validated = (new > NEW_ALLOW) ? 1 : 0;
2642 if (new <= NEW_ALLOW) {
2644 struct chan_iax2_pvt *pvt;
2645 struct chan_iax2_pvt tmp_pvt = {
2647 .peercallno = callno,
2648 .transfercallno = callno,
2650 .frames_received = check_dcallno,
2653 memcpy(&tmp_pvt.addr, sin, sizeof(tmp_pvt.addr));
2654 /* this works for finding normal call numbers not involving transfering */
2655 if ((pvt = ao2_find(iax_peercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
2656 if (return_locked) {
2657 ast_mutex_lock(&iaxsl[pvt->callno]);
2664 /* this searches for transfer call numbers that might not get caught otherwise */
2665 memset(&tmp_pvt.addr, 0, sizeof(tmp_pvt.addr));
2666 memcpy(&tmp_pvt.transfer, sin, sizeof(tmp_pvt.transfer));
2667 if ((pvt = ao2_find(iax_transfercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
2668 if (return_locked) {
2669 ast_mutex_lock(&iaxsl[pvt->callno]);
2677 /* This will occur on the first response to a message that we initiated,
2678 * such as a PING. */
2680 ast_mutex_lock(&iaxsl[dcallno]);
2682 if (callno && dcallno && iaxs[dcallno] && !iaxs[dcallno]->peercallno && match(sin, callno, dcallno, iaxs[dcallno], check_dcallno)) {
2683 iaxs[dcallno]->peercallno = callno;
2685 store_by_peercallno(iaxs[dcallno]);
2686 if (!res || !return_locked) {
2687 ast_mutex_unlock(&iaxsl[dcallno]);
2692 ast_mutex_unlock(&iaxsl[dcallno]);
2695 /* If we get here, we SHOULD NOT find a call structure for this
2696 callno; if we do, it means that there is a call structure that
2697 has a peer callno but did NOT get entered into the hash table,
2700 If we find a call structure using this old, slow method, output a log
2701 message so we'll know about it. After a few months of leaving this in
2702 place, if we don't hear about people seeing these messages, we can
2703 remove this code for good.
2706 for (x = 1; !res && x < maxnontrunkcall; x++) {
2707 ast_mutex_lock(&iaxsl[x]);
2709 /* Look for an exact match */
2710 if (match(sin, callno, dcallno, iaxs[x], check_dcallno)) {
2714 if (!res || !return_locked)
2715 ast_mutex_unlock(&iaxsl[x]);
2717 for (x = TRUNK_CALL_START; !res && x < maxtrunkcall; x++) {
2718 ast_mutex_lock(&iaxsl[x]);
2720 /* Look for an exact match */
2721 if (match(sin, callno, dcallno, iaxs[x], check_dcallno)) {
2725 if (!res || !return_locked)
2726 ast_mutex_unlock(&iaxsl[x]);
2730 if (!res && (new >= NEW_ALLOW)) {
2731 struct callno_entry *callno_entry;
2732 /* It may seem odd that we look through the peer list for a name for
2733 * this *incoming* call. Well, it is weird. However, users don't
2734 * have an IP address/port number that we can match against. So,
2735 * this is just checking for a peer that has that IP/port and
2736 * assuming that we have a user of the same name. This isn't always
2737 * correct, but it will be changed if needed after authentication. */
2738 if (!iax2_getpeername(*sin, host, sizeof(host)))
2739 snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
2741 if (peercnt_add(sin)) {
2742 /* This address has hit its callnumber limit. When the limit
2743 * is reached, the connection is not added to the peercnts table.*/
2747 if (!(callno_entry = get_unused_callno(0, validated))) {
2748 /* since we ran out of space, remove the peercnt
2749 * entry we added earlier */
2750 peercnt_remove_by_addr(sin);
2751 ast_log(LOG_WARNING, "No more space\n");
2754 x = callno_entry->callno;
2755 ast_mutex_lock(&iaxsl[x]);
2757 iaxs[x] = new_iax(sin, host);
2758 update_max_nontrunk();
2761 ast_debug(1, "Creating new call structure %d\n", x);
2762 iaxs[x]->callno_entry = callno_entry;
2763 iaxs[x]->sockfd = sockfd;
2764 iaxs[x]->addr.sin_port = sin->sin_port;
2765 iaxs[x]->addr.sin_family = sin->sin_family;
2766 iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
2767 iaxs[x]->peercallno = callno;
2768 iaxs[x]->callno = x;
2769 iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
2770 iaxs[x]->expiry = min_reg_expire;
2771 iaxs[x]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
2772 iaxs[x]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
2773 iaxs[x]->amaflags = amaflags;
2774 ast_copy_flags64(iaxs[x], &globalflags, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE | IAX_FORCE_ENCRYPT);
2775 ast_string_field_set(iaxs[x], accountcode, accountcode);
2776 ast_string_field_set(iaxs[x], mohinterpret, mohinterpret);
2777 ast_string_field_set(iaxs[x], mohsuggest, mohsuggest);
2778 ast_string_field_set(iaxs[x], parkinglot, default_parkinglot);
2780 if (iaxs[x]->peercallno) {
2781 store_by_peercallno(iaxs[x]);
2784 ast_log(LOG_WARNING, "Out of resources\n");
2785 ast_mutex_unlock(&iaxsl[x]);
2786 replace_callno(callno_entry);
2790 ast_mutex_unlock(&iaxsl[x]);
2796 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
2798 return __find_callno(callno, dcallno, sin, new, sockfd, 0, full_frame);
2801 static int find_callno_locked(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
2803 return __find_callno(callno, dcallno, sin, new, sockfd, 1, full_frame);
2807 * \brief Queue a frame to a call's owning asterisk channel
2809 * \pre This function assumes that iaxsl[callno] is locked when called.
2811 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
2812 * was valid before calling it, it may no longer be valid after calling it.
2813 * This function may unlock and lock the mutex associated with this callno,
2814 * meaning that another thread may grab it and destroy the call.
2816 static int iax2_queue_frame(int callno, struct ast_frame *f)
2819 if (iaxs[callno] && iaxs[callno]->owner) {
2820 if (ast_channel_trylock(iaxs[callno]->owner)) {
2821 /* Avoid deadlock by pausing and trying again */
2822 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
2824 ast_queue_frame(iaxs[callno]->owner, f);
2825 ast_channel_unlock(iaxs[callno]->owner);
2835 * \brief Queue a hangup frame on the ast_channel owner
2837 * This function queues a hangup frame on the owner of the IAX2 pvt struct that
2838 * is active for the given call number.
2840 * \pre Assumes lock for callno is already held.
2842 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
2843 * was valid before calling it, it may no longer be valid after calling it.
2844 * This function may unlock and lock the mutex associated with this callno,
2845 * meaning that another thread may grab it and destroy the call.
2847 static int iax2_queue_hangup(int callno)
2850 if (iaxs[callno] && iaxs[callno]->owner) {
2851 if (ast_channel_trylock(iaxs[callno]->owner)) {
2852 /* Avoid deadlock by pausing and trying again */
2853 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
2855 ast_queue_hangup(iaxs[callno]->owner);
2856 ast_channel_unlock(iaxs[callno]->owner);
2866 * \brief Queue a control frame on the ast_channel owner
2868 * This function queues a control frame on the owner of the IAX2 pvt struct that
2869 * is active for the given call number.
2871 * \pre Assumes lock for callno is already held.
2873 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
2874 * was valid before calling it, it may no longer be valid after calling it.
2875 * This function may unlock and lock the mutex associated with this callno,
2876 * meaning that another thread may grab it and destroy the call.
2878 static int iax2_queue_control_data(int callno,
2879 enum ast_control_frame_type control, const void *data, size_t datalen)
2882 if (iaxs[callno] && iaxs[callno]->owner) {
2883 if (ast_channel_trylock(iaxs[callno]->owner)) {
2884 /* Avoid deadlock by pausing and trying again */
2885 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
2887 ast_queue_control_data(iaxs[callno]->owner, control, data, datalen);
2888 ast_channel_unlock(iaxs[callno]->owner);
2896 static void destroy_firmware(struct iax_firmware *cur)
2898 /* Close firmware */
2900 munmap((void*)cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh)));
2906 static int try_firmware(char *s)
2909 struct iax_firmware *cur = NULL;
2910 int ifd, fd, res, len, chunk;
2911 struct ast_iax2_firmware_header *fwh, fwh2;
2912 struct MD5Context md5;
2913 unsigned char sum[16], buf[1024];
2916 if (!(s2 = alloca(strlen(s) + 100))) {
2917 ast_log(LOG_WARNING, "Alloca failed!\n");
2921 last = strrchr(s, '/');
2927 snprintf(s2, strlen(s) + 100, "/var/tmp/%s-%ld", last, (unsigned long)ast_random());
2929 if ((res = stat(s, &stbuf) < 0)) {
2930 ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno));
2934 /* Make sure it's not a directory */
2935 if (S_ISDIR(stbuf.st_mode))
2937 ifd = open(s, O_RDONLY);
2939 ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
2942 fd = open(s2, O_RDWR | O_CREAT | O_EXCL, AST_FILE_MODE);
2944 ast_log(LOG_WARNING, "Cannot open '%s' for writing: %s\n", s2, strerror(errno));
2948 /* Unlink our newly created file */
2951 /* Now copy the firmware into it */
2952 len = stbuf.st_size;
2955 if (chunk > sizeof(buf))
2956 chunk = sizeof(buf);
2957 res = read(ifd, buf, chunk);
2959 ast_log(LOG_WARNING, "Only read %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
2964 res = write(fd, buf, chunk);
2966 ast_log(LOG_WARNING, "Only write %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
2974 /* Return to the beginning */
2975 lseek(fd, 0, SEEK_SET);
2976 if ((res = read(fd, &fwh2, sizeof(fwh2))) != sizeof(fwh2)) {
2977 ast_log(LOG_WARNING, "Unable to read firmware header in '%s'\n", s);
2981 if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) {
2982 ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s);
2986 if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) {
2987 ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s);
2991 if (fwh2.devname[sizeof(fwh2.devname) - 1] || ast_strlen_zero((char *)fwh2.devname)) {
2992 ast_log(LOG_WARNING, "No or invalid device type specified for '%s'\n", s);
2996 fwh = (struct ast_iax2_firmware_header*)mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
2997 if (fwh == MAP_FAILED) {
2998 ast_log(LOG_WARNING, "mmap failed: %s\n", strerror(errno));
3003 MD5Update(&md5, fwh->data, ntohl(fwh->datalen));
3004 MD5Final(sum, &md5);
3005 if (memcmp(sum, fwh->chksum, sizeof(sum))) {
3006 ast_log(LOG_WARNING, "Firmware file '%s' fails checksum\n", s);
3007 munmap((void*)fwh, stbuf.st_size);
3012 AST_LIST_TRAVERSE(&firmwares, cur, list) {
3013 if (!strcmp((char *)cur->fwh->devname, (char *)fwh->devname)) {
3014 /* Found a candidate */
3015 if (cur->dead || (ntohs(cur->fwh->version) < ntohs(fwh->version)))
3016 /* The version we have on loaded is older, load this one instead */
3018 /* This version is no newer than what we have. Don't worry about it.
3019 We'll consider it a proper load anyhow though */
3020 munmap((void*)fwh, stbuf.st_size);
3026 if (!cur && ((cur = ast_calloc(1, sizeof(*cur))))) {
3028 AST_LIST_INSERT_TAIL(&firmwares, cur, list);
3033 munmap((void*)cur->fwh, cur->mmaplen);
3038 cur->mmaplen = stbuf.st_size;
3045 static int iax_check_version(char *dev)
3048 struct iax_firmware *cur = NULL;
3050 if (ast_strlen_zero(dev))
3053 AST_LIST_LOCK(&firmwares);
3054 AST_LIST_TRAVERSE(&firmwares, cur, list) {
3055 if (!strcmp(dev, (char *)cur->fwh->devname)) {
3056 res = ntohs(cur->fwh->version);
3060 AST_LIST_UNLOCK(&firmwares);
3065 static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
3068 unsigned int bs = desc & 0xff;
3069 unsigned int start = (desc >> 8) & 0xffffff;
3071 struct iax_firmware *cur;
3073 if (ast_strlen_zero((char *)dev) || !bs)
3078 AST_LIST_LOCK(&firmwares);
3079 AST_LIST_TRAVERSE(&firmwares, cur, list) {
3080 if (strcmp((char *)dev, (char *)cur->fwh->devname))
3082 iax_ie_append_int(ied, IAX_IE_FWBLOCKDESC, desc);
3083 if (start < ntohl(cur->fwh->datalen)) {
3084 bytes = ntohl(cur->fwh->datalen) - start;
3087 iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes);
3090 iax_ie_append(ied, IAX_IE_FWBLOCKDATA);
3098 AST_LIST_UNLOCK(&firmwares);
3104 static void reload_firmware(int unload)
3106 struct iax_firmware *cur = NULL;
3109 char dir[256], fn[256];
3111 AST_LIST_LOCK(&firmwares);
3113 /* Mark all as dead */
3114 AST_LIST_TRAVERSE(&firmwares, cur, list)
3117 /* Now that we have marked them dead... load new ones */
3119 snprintf(dir, sizeof(dir), "%s/firmware/iax", ast_config_AST_DATA_DIR);
3122 while((de = readdir(fwd))) {
3123 if (de->d_name[0] != '.') {
3124 snprintf(fn, sizeof(fn), "%s/%s", dir, de->d_name);
3125 if (!try_firmware(fn)) {
3126 ast_verb(2, "Loaded firmware '%s'\n", de->d_name);
3132 ast_log(LOG_WARNING, "Error opening firmware directory '%s': %s\n", dir, strerror(errno));
3135 /* Clean up leftovers */
3136 AST_LIST_TRAVERSE_SAFE_BEGIN(&firmwares, cur, list) {
3139 AST_LIST_REMOVE_CURRENT(list);
3140 destroy_firmware(cur);
3142 AST_LIST_TRAVERSE_SAFE_END;
3144 AST_LIST_UNLOCK(&firmwares);
3148 * \note This function assumes that iaxsl[callno] is locked when called.
3150 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3151 * was valid before calling it, it may no longer be valid after calling it.
3152 * This function calls iax2_queue_frame(), which may unlock and lock the mutex
3153 * associated with this callno, meaning that another thread may grab it and destroy the call.
3155 static int __do_deliver(void *data)
3157 /* Just deliver the packet by using queueing. This is called by
3158 the IAX thread with the iaxsl lock held. */
3159 struct iax_frame *fr = data;
3161 ast_clear_flag(&fr->af, AST_FRFLAG_HAS_TIMING_INFO);
3162 if (iaxs[fr->callno] && !ast_test_flag64(iaxs[fr->callno], IAX_ALREADYGONE))
3163 iax2_queue_frame(fr->callno, &fr->af);
3164 /* Free our iax frame */
3165 iax2_frame_free(fr);
3166 /* And don't run again */
3170 static int handle_error(void)
3172 /* XXX Ideally we should figure out why an error occurred and then abort those
3173 rather than continuing to try. Unfortunately, the published interface does
3174 not seem to work XXX */
3176 struct sockaddr_in *sin;
3179 struct sock_extended_err e;
3184 m.msg_controllen = sizeof(e);
3186 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
3188 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
3190 if (m.msg_controllen) {
3191 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
3193 ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(sin->sin_addr));
3195 ast_log(LOG_WARNING, "No address detected??\n");
3197 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
3204 static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin, int sockfd)
3207 res = sendto(sockfd, f->data, f->datalen, 0,(struct sockaddr *)sin,
3210 ast_debug(1, "Received error: %s\n", strerror(errno));
3217 static int send_packet(struct iax_frame *f)
3220 int callno = f->callno;
3222 /* Don't send if there was an error, but return error instead */
3223 if (!callno || !iaxs[callno] || iaxs[callno]->error)
3226 /* Called with iaxsl held */
3228 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));
3232 iax_showframe(f, NULL, 0, &iaxs[callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
3233 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->transfer, sizeof(iaxs[callno]->transfer));
3236 iax_showframe(f, NULL, 0, &iaxs[callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
3237 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->addr, sizeof(iaxs[callno]->addr));