/*
* Asterisk -- An open source telephony toolkit.
*
* Copyright (C) 1999 - 2006, Digium, Inc.
*
* Mark Spencer <markster@digium.com>
*
* See http://www.asterisk.org for more information about
* the Asterisk project. Please do not directly contact
* any of the maintainers of this project for assistance;
* the project provides a web site, mailing lists and IRC
* channels for your use.
*
* This program is free software, distributed under the terms of
* the GNU General Public License Version 2. See the LICENSE file
* at the top of the source tree.
*/
/*! \file
*
* \brief The Asterisk Management Interface - AMI
*
* \author Mark Spencer <markster@digium.com>
*
* OpenSSL http://www.openssl.org - for AMI/SSL
*
* At the moment this file contains a number of functions, namely:
*
* - data structures storing AMI state
* - AMI-related API functions, used by internal asterisk components
* - handlers for AMI-related CLI functions
* - handlers for AMI functions (available through the AMI socket)
* - the code for the main AMI listener thread and individual session threads
* - the http handlers invoked for AMI-over-HTTP by the threads in main/http.c
*
* \ref amiconf
*/
/*! \li \ref manager.c uses the configuration file \ref manager.conf and \ref users.conf
* \addtogroup configuration_file
*/
/*! \page manager.conf manager.conf
* \verbinclude manager.conf.sample
*/
/*! \page users.conf users.conf
* \verbinclude users.conf.sample
*/
/*** MODULEINFO
<support_level>core</support_level>
***/
#include "asterisk.h"
#include "asterisk/paths.h" /* use various ast_config_AST_* */
#include <ctype.h>
#include <sys/time.h>
#include <signal.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <regex.h>
#include "asterisk/channel.h"
#include "asterisk/file.h"
#include "asterisk/manager.h"
#include "asterisk/module.h"
#include "asterisk/config.h"
#include "asterisk/callerid.h"
#include "asterisk/lock.h"
#include "asterisk/cli.h"
#include "asterisk/app.h"
#include "asterisk/pbx.h"
#include "asterisk/md5.h"
#include "asterisk/acl.h"
#include "asterisk/utils.h"
#include "asterisk/tcptls.h"
#include "asterisk/http.h"
#include "asterisk/ast_version.h"
#include "asterisk/threadstorage.h"
#include "asterisk/linkedlists.h"
#include "asterisk/term.h"
#include "asterisk/astobj2.h"
#include "asterisk/features.h"
#include "asterisk/security_events.h"
#include "asterisk/aoc.h"
#include "asterisk/strings.h"
#include "asterisk/stringfields.h"
#include "asterisk/presencestate.h"
#include "asterisk/stasis_message_router.h"
#include "asterisk/stasis_channels.h"
#include "asterisk/stasis_bridges.h"
#include "asterisk/test.h"
#include "asterisk/json.h"
#include "asterisk/bridge.h"
#include "asterisk/features_config.h"
#include "asterisk/rtp_engine.h"
#include "asterisk/format_cache.h"
#include "asterisk/translate.h"
#include "asterisk/taskprocessor.h"
/*** DOCUMENTATION
<manager name="Ping" language="en_US">
<synopsis>
Keepalive command.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
</syntax>
<description>
<para>A 'Ping' action will ellicit a 'Pong' response. Used to keep the
manager connection open.</para>
</description>
</manager>
<manager name="Events" language="en_US">
<synopsis>
Control Event Flow.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="EventMask" required="true">
<enumlist>
<enum name="on">
<para>If all events should be sent.</para>
</enum>
<enum name="off">
<para>If no events should be sent.</para>
</enum>
<enum name="system,call,log,...">
<para>To select which flags events should have to be sent.</para>
</enum>
</enumlist>
</parameter>
</syntax>
<description>
<para>Enable/Disable sending of events to this manager client.</para>
</description>
</manager>
<manager name="Logoff" language="en_US">
<synopsis>
Logoff Manager.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
</syntax>
<description>
<para>Logoff the current manager session.</para>
</description>
<see-also>
<ref type="manager">Login</ref>
</see-also>
</manager>
<manager name="Login" language="en_US">
<synopsis>
Login Manager.
</synopsis>
<syntax>
<parameter name="ActionID">
<para>ActionID for this transaction. Will be returned.</para>
</parameter>
<parameter name="Username" required="true">
<para>Username to login with as specified in manager.conf.</para>
</parameter>
<parameter name="Secret">
<para>Secret to login with as specified in manager.conf.</para>
</parameter>
</syntax>
<description>
<para>Login Manager.</para>
</description>
<see-also>
<ref type="manager">Logoff</ref>
</see-also>
</manager>
<manager name="Challenge" language="en_US">
<synopsis>
Generate Challenge for MD5 Auth.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="AuthType" required="true">
<para>Digest algorithm to use in the challenge. Valid values are:</para>
<enumlist>
<enum name="MD5" />
</enumlist>
</parameter>
</syntax>
<description>
<para>Generate a challenge for MD5 authentication.</para>
</description>
</manager>
<manager name="Hangup" language="en_US">
<synopsis>
Hangup channel.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="Channel" required="true">
<para>The exact channel name to be hungup, or to use a regular expression, set this parameter to: /regex/</para>
<para>Example exact channel: SIP/provider-0000012a</para>
<para>Example regular expression: /^SIP/provider-.*$/</para>
</parameter>
<parameter name="Cause">
<para>Numeric hangup cause.</para>
</parameter>
</syntax>
<description>
<para>Hangup a channel.</para>
</description>
</manager>
<manager name="Status" language="en_US">
<synopsis>
List channel status.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="Channel" required="false">
<para>The name of the channel to query for status.</para>
</parameter>
<parameter name="Variables">
<para>Comma <literal>,</literal> separated list of variable to include.</para>
</parameter>
<parameter name="AllVariables">
<para>If set to "true", the Status event will include all channel variables for
the requested channel(s).</para>
<enumlist>
<enum name="true"/>
<enum name="false"/>
</enumlist>
</parameter>
</syntax>
<description>
<para>Will return the status information of each channel along with the
value for the specified channel variables.</para>
</description>
<responses>
<list-elements>
<xi:include xpointer="xpointer(/docs/managerEvent[@name='Status'])" />
</list-elements>
<xi:include xpointer="xpointer(/docs/managerEvent[@name='StatusComplete'])" />
</responses>
</manager>
<managerEvent language="en_US" name="Status">
<managerEventInstance class="EVENT_FLAG_CALL">
<synopsis>Raised in response to a Status command.</synopsis>
<syntax>
<parameter name="ActionID" required="false"/>
<channel_snapshot/>
<parameter name="Type">
<para>Type of channel</para>
</parameter>
<parameter name="DNID">
<para>Dialed number identifier</para>
</parameter>
<parameter name="EffectiveConnectedLineNum">
</parameter>
<parameter name="EffectiveConnectedLineName">
</parameter>
<parameter name="TimeToHangup">
<para>Absolute lifetime of the channel</para>
</parameter>
<parameter name="BridgeID">
<para>Identifier of the bridge the channel is in, may be empty if not in one</para>
</parameter>
<parameter name="Application">
<para>Application currently executing on the channel</para>
</parameter>
<parameter name="Data">
<para>Data given to the currently executing channel</para>
</parameter>
<parameter name="Nativeformats">
<para>Media formats the connected party is willing to send or receive</para>
</parameter>
<parameter name="Readformat">
<para>Media formats that frames from the channel are received in</para>
</parameter>
<parameter name="Readtrans">
<para>Translation path for media received in native formats</para>
</parameter>
<parameter name="Writeformat">
<para>Media formats that frames to the channel are accepted in</para>
</parameter>
<parameter name="Writetrans">
<para>Translation path for media sent to the connected party</para>
</parameter>
<parameter name="Callgroup">
<para>Configured call group on the channel</para>
</parameter>
<parameter name="Pickupgroup">
<para>Configured pickup group on the channel</para>
</parameter>
<parameter name="Seconds">
<para>Number of seconds the channel has been active</para>
</parameter>
</syntax>
<see-also>
<ref type="manager">Status</ref>
</see-also>
</managerEventInstance>
</managerEvent>
<managerEvent language="en_US" name="StatusComplete">
<managerEventInstance class="EVENT_FLAG_CALL">
<synopsis>Raised in response to a Status command.</synopsis>
<syntax>
<parameter name="Items">
<para>Number of Status events returned</para>
</parameter>
</syntax>
<see-also>
<ref type="manager">Status</ref>
</see-also>
</managerEventInstance>
</managerEvent>
<manager name="Setvar" language="en_US">
<synopsis>
Sets a channel variable or function value.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="Channel">
<para>Channel to set variable for.</para>
</parameter>
<parameter name="Variable" required="true">
<para>Variable name, function or expression.</para>
</parameter>
<parameter name="Value" required="true">
<para>Variable or function value.</para>
</parameter>
</syntax>
<description>
<para>This command can be used to set the value of channel variables or dialplan
functions.</para>
<note>
<para>If a channel name is not provided then the variable is considered global.</para>
</note>
</description>
<see-also>
<ref type="manager">Getvar</ref>
</see-also>
</manager>
<manager name="Getvar" language="en_US">
<synopsis>
Gets a channel variable or function value.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="Channel">
<para>Channel to read variable from.</para>
</parameter>
<parameter name="Variable" required="true">
<para>Variable name, function or expression.</para>
</parameter>
</syntax>
<description>
<para>Get the value of a channel variable or function return.</para>
<note>
<para>If a channel name is not provided then the variable is considered global.</para>
</note>
</description>
<see-also>
<ref type="manager">Setvar</ref>
</see-also>
</manager>
<manager name="GetConfig" language="en_US">
<synopsis>
Retrieve configuration.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="Filename" required="true">
<para>Configuration filename (e.g. <filename>foo.conf</filename>).</para>
</parameter>
<parameter name="Category">
<para>Category in configuration file.</para>
</parameter>
<parameter name="Filter">
<para>A comma separated list of
<replaceable>name_regex</replaceable>=<replaceable>value_regex</replaceable>
expressions which will cause only categories whose variables match all expressions
to be considered. The special variable name <literal>TEMPLATES</literal>
can be used to control whether templates are included. Passing
<literal>include</literal> as the value will include templates
along with normal categories. Passing
<literal>restrict</literal> as the value will restrict the operation to
ONLY templates. Not specifying a <literal>TEMPLATES</literal> expression
results in the default behavior which is to not include templates.</para>
</parameter>
</syntax>
<description>
<para>This action will dump the contents of a configuration
file by category and contents or optionally by specified category only.
In the case where a category name is non-unique, a filter may be specified
to match only categories with matching variable values.</para>
</description>
<see-also>
<ref type="manager">GetConfigJSON</ref>
<ref type="manager">UpdateConfig</ref>
<ref type="manager">CreateConfig</ref>
<ref type="manager">ListCategories</ref>
</see-also>
</manager>
<manager name="GetConfigJSON" language="en_US">
<synopsis>
Retrieve configuration (JSON format).
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="Filename" required="true">
<para>Configuration filename (e.g. <filename>foo.conf</filename>).</para>
</parameter>
<parameter name="Category">
<para>Category in configuration file.</para>
</parameter>
<parameter name="Filter">
<xi:include xpointer="xpointer(/docs/manager[@name='GetConfig']/syntax/parameter[@name='Filter']/para[1])" />
</parameter>
</syntax>
<description>
<para>This action will dump the contents of a configuration file by category
and contents in JSON format or optionally by specified category only.
This only makes sense to be used using rawman over the HTTP interface.
In the case where a category name is non-unique, a filter may be specified
to match only categories with matching variable values.</para>
</description>
<see-also>
<ref type="manager">GetConfig</ref>
<ref type="manager">UpdateConfig</ref>
<ref type="manager">CreateConfig</ref>
<ref type="manager">ListCategories</ref>
</see-also>
</manager>
<manager name="UpdateConfig" language="en_US">
<synopsis>
Update basic configuration.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="SrcFilename" required="true">
<para>Configuration filename to read (e.g. <filename>foo.conf</filename>).</para>
</parameter>
<parameter name="DstFilename" required="true">
<para>Configuration filename to write (e.g. <filename>foo.conf</filename>)</para>
</parameter>
<parameter name="Reload">
<para>Whether or not a reload should take place (or name of specific module).</para>
</parameter>
<parameter name="PreserveEffectiveContext">
<para>Whether the effective category contents should be preserved on template change. Default is true (pre 13.2 behavior).</para>
</parameter>
<parameter name="Action-000000">
<para>Action to take.</para>
<para>0's represent 6 digit number beginning with 000000.</para>
<enumlist>
<enum name="NewCat" />
<enum name="RenameCat" />
<enum name="DelCat" />
<enum name="EmptyCat" />
<enum name="Update" />
<enum name="Delete" />
<enum name="Append" />
<enum name="Insert" />
</enumlist>
</parameter>
<parameter name="Cat-000000">
<para>Category to operate on.</para>
<xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-000000']/para[2])" />
</parameter>
<parameter name="Var-000000">
<para>Variable to work on.</para>
<xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-000000']/para[2])" />
</parameter>
<parameter name="Value-000000">
<para>Value to work on.</para>
<xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-000000']/para[2])" />
</parameter>
<parameter name="Match-000000">
<para>Extra match required to match line.</para>
<xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-000000']/para[2])" />
</parameter>
<parameter name="Line-000000">
<para>Line in category to operate on (used with delete and insert actions).</para>
<xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-000000']/para[2])" />
</parameter>
<parameter name="Options-000000">
<para>A comma separated list of action-specific options.</para>
<enumlist>
<enum name="NewCat"><para>One or more of the following... </para>
<enumlist>
<enum name="allowdups"><para>Allow duplicate category names.</para></enum>
<enum name="template"><para>This category is a template.</para></enum>
<enum name="inherit="template[,...]""><para>Templates from which to inherit.</para></enum>
</enumlist>
</enum>
</enumlist>
<para> </para>
<para>The following actions share the same options...</para>
<enumlist>
<enum name="RenameCat"/>
<enum name="DelCat"/>
<enum name="EmptyCat"/>
<enum name="Update"/>
<enum name="Delete"/>
<enum name="Append"/>
<enum name="Insert"><para> </para>
<enumlist>
<enum name="catfilter="<expression>[,...]""><para> </para>
<xi:include xpointer="xpointer(/docs/manager[@name='GetConfig']/syntax/parameter[@name='Filter']/para[1])" />
<para><literal>catfilter</literal> is most useful when a file
contains multiple categories with the same name and you wish to
operate on specific ones instead of all of them.</para>
</enum>
</enumlist>
</enum>
</enumlist>
<xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-000000']/para[2])" />
</parameter>
</syntax>
<description>
<para>This action will modify, create, or delete configuration elements
in Asterisk configuration files.</para>
</description>
<see-also>
<ref type="manager">GetConfig</ref>
<ref type="manager">GetConfigJSON</ref>
<ref type="manager">CreateConfig</ref>
<ref type="manager">ListCategories</ref>
</see-also>
</manager>
<manager name="CreateConfig" language="en_US">
<synopsis>
Creates an empty file in the configuration directory.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="Filename" required="true">
<para>The configuration filename to create (e.g. <filename>foo.conf</filename>).</para>
</parameter>
</syntax>
<description>
<para>This action will create an empty file in the configuration
directory. This action is intended to be used before an UpdateConfig
action.</para>
</description>
<see-also>
<ref type="manager">GetConfig</ref>
<ref type="manager">GetConfigJSON</ref>
<ref type="manager">UpdateConfig</ref>
<ref type="manager">ListCategories</ref>
</see-also>
</manager>
<manager name="ListCategories" language="en_US">
<synopsis>
List categories in configuration file.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="Filename" required="true">
<para>Configuration filename (e.g. <filename>foo.conf</filename>).</para>
</parameter>
</syntax>
<description>
<para>This action will dump the categories in a given file.</para>
</description>
<see-also>
<ref type="manager">GetConfig</ref>
<ref type="manager">GetConfigJSON</ref>
<ref type="manager">UpdateConfig</ref>
<ref type="manager">CreateConfig</ref>
</see-also>
</manager>
<manager name="Redirect" language="en_US">
<synopsis>
Redirect (transfer) a call.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="Channel" required="true">
<para>Channel to redirect.</para>
</parameter>
<parameter name="ExtraChannel">
<para>Second call leg to transfer (optional).</para>
</parameter>
<parameter name="Exten" required="true">
<para>Extension to transfer to.</para>
</parameter>
<parameter name="ExtraExten">
<para>Extension to transfer extrachannel to (optional).</para>
</parameter>
<parameter name="Context" required="true">
<para>Context to transfer to.</para>
</parameter>
<parameter name="ExtraContext">
<para>Context to transfer extrachannel to (optional).</para>
</parameter>
<parameter name="Priority" required="true">
<para>Priority to transfer to.</para>
</parameter>
<parameter name="ExtraPriority">
<para>Priority to transfer extrachannel to (optional).</para>
</parameter>
</syntax>
<description>
<para>Redirect (transfer) a call.</para>
</description>
<see-also>
<ref type="manager">BlindTransfer</ref>
</see-also>
</manager>
<manager name="Atxfer" language="en_US">
<synopsis>
Attended transfer.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="Channel" required="true">
<para>Transferer's channel.</para>
</parameter>
<parameter name="Exten" required="true">
<para>Extension to transfer to.</para>
</parameter>
<parameter name="Context">
<para>Context to transfer to.</para>
</parameter>
</syntax>
<description>
<para>Attended transfer.</para>
</description>
<see-also>
<ref type="managerEvent">AttendedTransfer</ref>
</see-also>
</manager>
<manager name="CancelAtxfer" language="en_US">
<synopsis>
Cancel an attended transfer.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="Channel" required="true">
<para>The transferer channel.</para>
</parameter>
</syntax>
<description>
<para>Cancel an attended transfer. Note, this uses the configured cancel attended transfer
feature option (atxferabort) to cancel the transfer. If not available this action will fail.
</para>
</description>
<see-also>
<ref type="managerEvent">AttendedTransfer</ref>
</see-also>
</manager>
<manager name="Originate" language="en_US">
<synopsis>
Originate a call.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="Channel" required="true">
<para>Channel name to call.</para>
</parameter>
<parameter name="Exten">
<para>Extension to use (requires <literal>Context</literal> and
<literal>Priority</literal>)</para>
</parameter>
<parameter name="Context">
<para>Context to use (requires <literal>Exten</literal> and
<literal>Priority</literal>)</para>
</parameter>
<parameter name="Priority">
<para>Priority to use (requires <literal>Exten</literal> and
<literal>Context</literal>)</para>
</parameter>
<parameter name="Application">
<para>Application to execute.</para>
</parameter>
<parameter name="Data">
<para>Data to use (requires <literal>Application</literal>).</para>
</parameter>
<parameter name="Timeout" default="30000">
<para>How long to wait for call to be answered (in ms.).</para>
</parameter>
<parameter name="CallerID">
<para>Caller ID to be set on the outgoing channel.</para>
</parameter>
<parameter name="Variable">
<para>Channel variable to set, multiple Variable: headers are allowed.</para>
</parameter>
<parameter name="Account">
<para>Account code.</para>
</parameter>
<parameter name="EarlyMedia">
<para>Set to <literal>true</literal> to force call bridge on early media..</para>
</parameter>
<parameter name="Async">
<para>Set to <literal>true</literal> for fast origination.</para>
</parameter>
<parameter name="Codecs">
<para>Comma-separated list of codecs to use for this call.</para>
</parameter>
<parameter name="ChannelId">
<para>Channel UniqueId to be set on the channel.</para>
</parameter>
<parameter name="OtherChannelId">
<para>Channel UniqueId to be set on the second local channel.</para>
</parameter>
</syntax>
<description>
<para>Generates an outgoing call to a
<replaceable>Extension</replaceable>/<replaceable>Context</replaceable>/<replaceable>Priority</replaceable>
or <replaceable>Application</replaceable>/<replaceable>Data</replaceable></para>
</description>
<see-also>
<ref type="managerEvent">OriginateResponse</ref>
</see-also>
</manager>
<managerEvent language="en_US" name="OriginateResponse">
<managerEventInstance class="EVENT_FLAG_CALL">
<synopsis>Raised in response to an Originate command.</synopsis>
<syntax>
<parameter name="ActionID" required="false"/>
<parameter name="Response">
<enumlist>
<enum name="Failure"/>
<enum name="Success"/>
</enumlist>
</parameter>
<parameter name="Channel"/>
<parameter name="Context"/>
<parameter name="Exten"/>
<parameter name="Application"/>
<parameter name="Data"/>
<parameter name="Reason"/>
<parameter name="Uniqueid"/>
<parameter name="CallerIDNum"/>
<parameter name="CallerIDName"/>
</syntax>
<see-also>
<ref type="manager">Originate</ref>
</see-also>
</managerEventInstance>
</managerEvent>
<manager name="Command" language="en_US">
<synopsis>
Execute Asterisk CLI Command.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="Command" required="true">
<para>Asterisk CLI command to run.</para>
</parameter>
</syntax>
<description>
<para>Run a CLI command.</para>
</description>
</manager>
<manager name="ExtensionState" language="en_US">
<synopsis>
Check Extension Status.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="Exten" required="true">
<para>Extension to check state on.</para>
</parameter>
<parameter name="Context" required="true">
<para>Context for extension.</para>
</parameter>
</syntax>
<description>
<para>Report the extension state for given extension. If the extension has a hint,
will use devicestate to check the status of the device connected to the extension.</para>
<para>Will return an <literal>Extension Status</literal> message. The response will include
the hint for the extension and the status.</para>
</description>
<see-also>
<ref type="managerEvent">ExtensionStatus</ref>
</see-also>
</manager>
<manager name="PresenceState" language="en_US">
<synopsis>
Check Presence State
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="Provider" required="true">
<para>Presence Provider to check the state of</para>
</parameter>
</syntax>
<description>
<para>Report the presence state for the given presence provider.</para>
<para>Will return a <literal>Presence State</literal> message. The response will include the
presence state and, if set, a presence subtype and custom message.</para>
</description>
<see-also>
<ref type="managerEvent">PresenceStatus</ref>
</see-also>
</manager>
<manager name="AbsoluteTimeout" language="en_US">
<synopsis>
Set absolute timeout.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="Channel" required="true">
<para>Channel name to hangup.</para>
</parameter>
<parameter name="Timeout" required="true">
<para>Maximum duration of the call (sec).</para>
</parameter>
</syntax>
<description>
<para>Hangup a channel after a certain time. Acknowledges set time with
<literal>Timeout Set</literal> message.</para>
</description>
</manager>
<manager name="MailboxStatus" language="en_US">
<synopsis>
Check mailbox.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="Mailbox" required="true">
<para>Full mailbox ID <replaceable>mailbox</replaceable>@<replaceable>vm-context</replaceable>.</para>
</parameter>
</syntax>
<description>
<para>Checks a voicemail account for status.</para>
<para>Returns whether there are messages waiting.</para>
<para>Message: Mailbox Status.</para>
<para>Mailbox: <replaceable>mailboxid</replaceable>.</para>
<para>Waiting: <literal>0</literal> if messages waiting, <literal>1</literal>
if no messages waiting.</para>
</description>
<see-also>
<ref type="manager">MailboxCount</ref>
</see-also>
</manager>
<manager name="MailboxCount" language="en_US">
<synopsis>
Check Mailbox Message Count.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="Mailbox" required="true">
<para>Full mailbox ID <replaceable>mailbox</replaceable>@<replaceable>vm-context</replaceable>.</para>
</parameter>
</syntax>
<description>
<para>Checks a voicemail account for new messages.</para>
<para>Returns number of urgent, new and old messages.</para>
<para>Message: Mailbox Message Count</para>
<para>Mailbox: <replaceable>mailboxid</replaceable></para>
<para>UrgentMessages: <replaceable>count</replaceable></para>
<para>NewMessages: <replaceable>count</replaceable></para>
<para>OldMessages: <replaceable>count</replaceable></para>
</description>
<see-also>
<ref type="manager">MailboxStatus</ref>
</see-also>
</manager>
<manager name="ListCommands" language="en_US">
<synopsis>
List available manager commands.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
</syntax>
<description>
<para>Returns the action name and synopsis for every action that
is available to the user.</para>
</description>
</manager>
<manager name="SendText" language="en_US">
<synopsis>
Send text message to channel.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="Channel" required="true">
<para>Channel to send message to.</para>
</parameter>
<parameter name="Message" required="true">
<para>Message to send.</para>
</parameter>
</syntax>
<description>
<para>Sends A Text Message to a channel while in a call.</para>
</description>
</manager>
<manager name="UserEvent" language="en_US">
<synopsis>
Send an arbitrary event.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="UserEvent" required="true">
<para>Event string to send.</para>
</parameter>
<parameter name="Header1">
<para>Content1.</para>
</parameter>
<parameter name="HeaderN">
<para>ContentN.</para>
</parameter>
</syntax>
<description>
<para>Send an event to manager sessions.</para>
</description>
<see-also>
<ref type="managerEvent">UserEvent</ref>
<ref type="application">UserEvent</ref>
</see-also>
</manager>
<manager name="WaitEvent" language="en_US">
<synopsis>
Wait for an event to occur.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="Timeout" required="true">
<para>Maximum time (in seconds) to wait for events, <literal>-1</literal> means forever.</para>
</parameter>
</syntax>
<description>
<para>This action will ellicit a <literal>Success</literal> response. Whenever
a manager event is queued. Once WaitEvent has been called on an HTTP manager
session, events will be generated and queued.</para>
</description>
</manager>
<manager name="CoreSettings" language="en_US">
<synopsis>
Show PBX core settings (version etc).
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
</syntax>
<description>
<para>Query for Core PBX settings.</para>
</description>
</manager>
<manager name="CoreStatus" language="en_US">
<synopsis>
Show PBX core status variables.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
</syntax>
<description>
<para>Query for Core PBX status.</para>
</description>
</manager>
<manager name="Reload" language="en_US">
<synopsis>
Send a reload event.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="Module">
<para>Name of the module to reload.</para>
</parameter>
</syntax>
<description>
<para>Send a reload event.</para>
</description>
<see-also>
<ref type="manager">ModuleLoad</ref>
</see-also>
</manager>
<managerEvent language="en_US" name="CoreShowChannel">
<managerEventInstance class="EVENT_FLAG_CALL">
<synopsis>Raised in response to a CoreShowChannels command.</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<channel_snapshot/>
<parameter name="BridgeId">
<para>Identifier of the bridge the channel is in, may be empty if not in one</para>
</parameter>
<parameter name="Application">
<para>Application currently executing on the channel</para>
</parameter>
<parameter name="ApplicationData">
<para>Data given to the currently executing application</para>
</parameter>
<parameter name="Duration">
<para>The amount of time the channel has existed</para>
</parameter>
</syntax>
<see-also>
<ref type="manager">CoreShowChannels</ref>
<ref type="managerEvent">CoreShowChannelsComplete</ref>
</see-also>
</managerEventInstance>
</managerEvent>
<managerEvent language="en_US" name="CoreShowChannelsComplete">
<managerEventInstance class="EVENT_FLAG_CALL">
<synopsis>Raised at the end of the CoreShowChannel list produced by the CoreShowChannels command.</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="EventList">
<para>Conveys the status of the command reponse list</para>
</parameter>
<parameter name="ListItems">
<para>The total number of list items produced</para>
</parameter>
</syntax>
<see-also>
<ref type="manager">CoreShowChannels</ref>
<ref type="managerEvent">CoreShowChannel</ref>
</see-also>
</managerEventInstance>
</managerEvent>
<manager name="CoreShowChannels" language="en_US">
<synopsis>
List currently active channels.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
</syntax>
<description>
<para>List currently defined channels and some information about them.</para>
</description>
<responses>
<list-elements>
<xi:include xpointer="xpointer(/docs/managerEvent[@name='CoreShowChannel'])" />
</list-elements>
<xi:include xpointer="xpointer(/docs/managerEvent[@name='CoreShowChannelsComplete'])" />
</responses>
</manager>
<manager name="LoggerRotate" language="en_US">
<synopsis>
Reload and rotate the Asterisk logger.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
</syntax>
<description>
<para>Reload and rotate the logger. Analogous to the CLI command 'logger rotate'.</para>
</description>
</manager>
<manager name="ModuleLoad" language="en_US">
<synopsis>
Module management.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="Module">
<para>Asterisk module name (including .so extension) or subsystem identifier:</para>
<enumlist>
<enum name="cdr" />
<enum name="dnsmgr" />
<enum name="extconfig" />
<enum name="enum" />
<enum name="acl" />
<enum name="manager" />
<enum name="http" />
<enum name="logger" />
<enum name="features" />
<enum name="dsp" />
<enum name="udptl" />
<enum name="indications" />
<enum name="cel" />
<enum name="plc" />
</enumlist>
</parameter>
<parameter name="LoadType" required="true">
<para>The operation to be done on module. Subsystem identifiers may only
be reloaded.</para>
<enumlist>
<enum name="load" />
<enum name="unload" />
<enum name="reload" />
</enumlist>
<para>If no module is specified for a <literal>reload</literal> loadtype,
all modules are reloaded.</para>
</parameter>
</syntax>
<description>
<para>Loads, unloads or reloads an Asterisk module in a running system.</para>
</description>
<see-also>
<ref type="manager">Reload</ref>
<ref type="manager">ModuleCheck</ref>
</see-also>
</manager>
<manager name="ModuleCheck" language="en_US">
<synopsis>
Check if module is loaded.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="Module" required="true">
<para>Asterisk module name (not including extension).</para>
</parameter>
</syntax>
<description>
<para>Checks if Asterisk module is loaded. Will return Success/Failure.
For success returns, the module revision number is included.</para>
</description>
<see-also>
<ref type="manager">ModuleLoad</ref>
</see-also>
</manager>
<manager name="AOCMessage" language="en_US">
<synopsis>
Generate an Advice of Charge message on a channel.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="Channel" required="true">
<para>Channel name to generate the AOC message on.</para>
</parameter>
<parameter name="ChannelPrefix">
<para>Partial channel prefix. By using this option one can match the beginning part
of a channel name without having to put the entire name in. For example
if a channel name is SIP/snom-00000001 and this value is set to SIP/snom, then
that channel matches and the message will be sent. Note however that only
the first matched channel has the message sent on it. </para>
</parameter>
<parameter name="MsgType" required="true">
<para>Defines what type of AOC message to create, AOC-D or AOC-E</para>
<enumlist>
<enum name="D" />
<enum name="E" />
</enumlist>
</parameter>
<parameter name="ChargeType" required="true">
<para>Defines what kind of charge this message represents.</para>
<enumlist>
<enum name="NA" />
<enum name="FREE" />
<enum name="Currency" />
<enum name="Unit" />
</enumlist>
</parameter>
<parameter name="UnitAmount(0)">
<para>This represents the amount of units charged. The ETSI AOC standard specifies that
this value along with the optional UnitType value are entries in a list. To accommodate this
these values take an index value starting at 0 which can be used to generate this list of
unit entries. For Example, If two unit entires were required this could be achieved by setting the
paramter UnitAmount(0)=1234 and UnitAmount(1)=5678. Note that UnitAmount at index 0 is
required when ChargeType=Unit, all other entries in the list are optional.
</para>
</parameter>
<parameter name="UnitType(0)">
<para>Defines the type of unit. ETSI AOC standard specifies this as an integer
value between 1 and 16, but this value is left open to accept any positive
integer. Like the UnitAmount parameter, this value represents a list entry
and has an index parameter that starts at 0.
</para>
</parameter>
<parameter name="CurrencyName">
<para>Specifies the currency's name. Note that this value is truncated after 10 characters.</para>
</parameter>
<parameter name="CurrencyAmount">
<para>Specifies the charge unit amount as a positive integer. This value is required
when ChargeType==Currency.</para>
</parameter>
<parameter name="CurrencyMultiplier">
<para>Specifies the currency multiplier. This value is required when ChargeType==Currency.</para>
<enumlist>
<enum name="OneThousandth" />
<enum name="OneHundredth" />
<enum name="OneTenth" />
<enum name="One" />
<enum name="Ten" />
<enum name="Hundred" />
<enum name="Thousand" />
</enumlist>
</parameter>
<parameter name="TotalType" default="Total">
<para>Defines what kind of AOC-D total is represented.</para>
<enumlist>
<enum name="Total" />
<enum name="SubTotal" />
</enumlist>
</parameter>
<parameter name="AOCBillingId">
<para>Represents a billing ID associated with an AOC-D or AOC-E message. Note
that only the first 3 items of the enum are valid AOC-D billing IDs</para>
<enumlist>
<enum name="Normal" />
<enum name="ReverseCharge" />
<enum name="CreditCard" />
<enum name="CallFwdUnconditional" />
<enum name="CallFwdBusy" />
<enum name="CallFwdNoReply" />
<enum name="CallDeflection" />
<enum name="CallTransfer" />
</enumlist>
</parameter>
<parameter name="ChargingAssociationId">
<para>Charging association identifier. This is optional for AOC-E and can be
set to any value between -32768 and 32767</para>
</parameter>
<parameter name="ChargingAssociationNumber">
<para>Represents the charging association party number. This value is optional
for AOC-E.</para>
</parameter>
<parameter name="ChargingAssociationPlan">
<para>Integer representing the charging plan associated with the ChargingAssociationNumber.
The value is bits 7 through 1 of the Q.931 octet containing the type-of-number and
numbering-plan-identification fields.</para>
</parameter>
</syntax>
<description>
<para>Generates an AOC-D or AOC-E message on a channel.</para>
</description>
<see-also>
<ref type="managerEvent">AOC-D</ref>
<ref type="managerEvent">AOC-E</ref>
</see-also>
</manager>
<function name="AMI_CLIENT" language="en_US">
<synopsis>
Checks attributes of manager accounts
</synopsis>
<syntax>
<parameter name="loginname" required="true">
<para>Login name, specified in manager.conf</para>
</parameter>
<parameter name="field" required="true">
<para>The manager account attribute to return</para>
<enumlist>
<enum name="sessions"><para>The number of sessions for this AMI account</para></enum>
</enumlist>
</parameter>
</syntax>
<description>
<para>
Currently, the only supported parameter is "sessions" which will return the current number of
active sessions for this AMI account.
</para>
</description>
</function>
<manager name="Filter" language="en_US">
<synopsis>
Dynamically add filters for the current manager session.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="Operation">
<enumlist>
<enum name="Add">
<para>Add a filter.</para>
</enum>
</enumlist>
</parameter>
<parameter name="Filter">
<para>Filters can be whitelist or blacklist</para>
<para>Example whitelist filter: "Event: Newchannel"</para>
<para>Example blacklist filter: "!Channel: DAHDI.*"</para>
<para>This filter option is used to whitelist or blacklist events per user to be
reported with regular expressions and are allowed if both the regex matches
and the user has read access as defined in manager.conf. Filters are assumed to be for whitelisting
unless preceeded by an exclamation point, which marks it as being black.
Evaluation of the filters is as follows:</para>
<para>- If no filters are configured all events are reported as normal.</para>
<para>- If there are white filters only: implied black all filter processed first, then white filters.</para>
<para>- If there are black filters only: implied white all filter processed first, then black filters.</para>
<para>- If there are both white and black filters: implied black all filter processed first, then white
filters, and lastly black filters.</para>
</parameter>
</syntax>
<description>
<para>The filters added are only used for the current session.
Once the connection is closed the filters are removed.</para>
<para>This comand requires the system permission because
this command can be used to create filters that may bypass
filters defined in manager.conf</para>
</description>
<see-also>
<ref type="manager">FilterList</ref>
</see-also>
</manager>
<manager name="FilterList" language="en_US">
<synopsis>
Show current event filters for this session
</synopsis>
<description>
<para>The filters displayed are for the current session. Only those filters defined in
manager.conf will be present upon starting a new session.</para>
</description>
<see-also>
<ref type="manager">Filter</ref>
</see-also>
</manager>
<manager name="BlindTransfer" language="en_US">
<synopsis>
Blind transfer channel(s) to the given destination
</synopsis>
<syntax>
<parameter name="Channel" required="true">
</parameter>
<parameter name="Context">
</parameter>
<parameter name="Exten">
</parameter>
</syntax>
<description>
<para>Redirect all channels currently bridged to the specified channel to the specified destination.</para>
</description>
<see-also>
<ref type="manager">Redirect</ref>
<ref type="managerEvent">BlindTransfer</ref>
</see-also>
</manager>
<managerEvent name="ExtensionStatus" language="en_US">
<managerEventInstance class="EVENT_FLAG_CALL">
<synopsis>Raised when a hint changes due to a device state change.</synopsis>
<syntax>
<parameter name="Exten">
<para>Name of the extension.</para>
</parameter>
<parameter name="Context">
<para>Context that owns the extension.</para>
</parameter>
<parameter name="Hint">
<para>Hint set for the extension</para>
</parameter>
<parameter name="Status">
<para>Numerical value of the extension status. Extension
status is determined by the combined device state of all items
contained in the hint.</para>
<enumlist>
<enum name="-2">
<para>The extension was removed from the dialplan.</para>
</enum>
<enum name="-1">
<para>The extension's hint was removed from the dialplan.</para>
</enum>
<enum name="0">
<para><literal>Idle</literal> - Related device(s) are in an idle
state.</para>
</enum>
<enum name="1">
<para><literal>InUse</literal> - Related device(s) are in active
calls but may take more calls.</para>
</enum>
<enum name="2">
<para><literal>Busy</literal> - Related device(s) are in active
calls and may not take any more calls.</para>
</enum>
<enum name="4">
<para><literal>Unavailable</literal> - Related device(s) are
not reachable.</para>
</enum>
<enum name="8">
<para><literal>Ringing</literal> - Related device(s) are
currently ringing.</para>
</enum>
<enum name="9">
<para><literal>InUse&Ringing</literal> - Related device(s)
are currently ringing and in active calls.</para>
</enum>
<enum name="16">
<para><literal>Hold</literal> - Related device(s) are
currently on hold.</para>
</enum>
<enum name="17">
<para><literal>InUse&Hold</literal> - Related device(s)
are currently on hold and in active calls.</para>
</enum>
</enumlist>
</parameter>
<parameter name="StatusText">
<para>Text representation of <literal>Status</literal>.</para>
<enumlist>
<enum name="Idle" />
<enum name="InUse" />
<enum name="Busy" />
<enum name="Unavailable" />
<enum name="Ringing" />
<enum name="InUse&Ringing" />
<enum name="Hold" />
<enum name="InUse&Hold" />
<enum name="Unknown">
<para>Status does not match any of the above values.</para>
</enum>
</enumlist>
</parameter>
</syntax>
<see-also>
<ref type="manager">ExtensionState</ref>
</see-also>
</managerEventInstance>
</managerEvent>
<managerEvent name="PresenceStatus" language="en_US">
<managerEventInstance class="EVENT_FLAG_CALL">
<synopsis>Raised when a hint changes due to a presence state change.</synopsis>
<syntax>
<parameter name="Exten" />
<parameter name="Context" />
<parameter name="Hint" />
<parameter name="Status" />
<parameter name="Subtype" />
<parameter name="Message" />
</syntax>
<see-also>
<ref type="manager">PresenceState</ref>
</see-also>
</managerEventInstance>
</managerEvent>
***/
/*! \addtogroup Group_AMI AMI functions
*/
/*! @{
Doxygen group */
enum error_type {
UNKNOWN_ACTION = 1,
UNKNOWN_CATEGORY,
UNSPECIFIED_CATEGORY,
UNSPECIFIED_ARGUMENT,
FAILURE_ALLOCATION,
FAILURE_NEWCAT,
FAILURE_DELCAT,
FAILURE_EMPTYCAT,
FAILURE_UPDATE,
FAILURE_DELETE,
FAILURE_APPEND,
FAILURE_TEMPLATE
};
enum add_filter_result {
FILTER_SUCCESS,
FILTER_ALLOC_FAILED,
FILTER_COMPILE_FAIL,
};
/*!
* Linked list of events.
* Global events are appended to the list by append_event().
* The usecount is the number of stored pointers to the element,
* excluding the list pointers. So an element that is only in
* the list has a usecount of 0, not 1.
*
* Clients have a pointer to the last event processed, and for each
* of these clients we track the usecount of the elements.
* If we have a pointer to an entry in the list, it is safe to navigate
* it forward because elements will not be deleted, but only appended.
* The worst that can happen is seeing the pointer still NULL.
*
* When the usecount of an element drops to 0, and the element is the
* first in the list, we can remove it. Removal is done within the
* main thread, which is woken up for the purpose.
*
* For simplicity of implementation, we make sure the list is never empty.
*/
struct eventqent {
int usecount; /*!< # of clients who still need the event */
int category;
unsigned int seq; /*!< sequence number */
struct timeval tv; /*!< When event was allocated */
AST_RWLIST_ENTRY(eventqent) eq_next;
char eventdata[1]; /*!< really variable size, allocated by append_event() */
};
static AST_RWLIST_HEAD_STATIC(all_events, eventqent);
static int displayconnects = 1;
static int allowmultiplelogin = 1;
static int timestampevents;
static int httptimeout = 60;
static int broken_events_action = 0;
static int manager_enabled = 0;
static int subscribed = 0;
static int webmanager_enabled = 0;
static int manager_debug = 0; /*!< enable some debugging code in the manager */
static int authtimeout;
static int authlimit;
static char *manager_channelvars;
#define DEFAULT_REALM "asterisk"
static char global_realm[MAXHOSTNAMELEN]; /*!< Default realm */
static int unauth_sessions = 0;
static struct stasis_subscription *acl_change_sub;
/*! \brief A \ref stasis_topic that all topics AMI cares about will be forwarded to */
static struct stasis_topic *manager_topic;
/*! \brief The \ref stasis_message_router for all \ref stasis messages */
static struct stasis_message_router *stasis_router;
/*! \brief The \ref stasis_subscription for forwarding the RTP topic to the AMI topic */
static struct stasis_forward *rtp_topic_forwarder;
/*! \brief The \ref stasis_subscription for forwarding the Security topic to the AMI topic */
static struct stasis_forward *security_topic_forwarder;
#ifdef TEST_FRAMEWORK
/*! \brief The \ref stasis_subscription for forwarding the Test topic to the AMI topic */
static struct stasis_forward *test_suite_forwarder;
#endif
#define MGR_SHOW_TERMINAL_WIDTH 80
#define MAX_VARS 128
/*! \brief Fake event class used to end sessions at shutdown */
#define EVENT_FLAG_SHUTDOWN -1
/*! \brief
* Descriptor for a manager session, either on the AMI socket or over HTTP.
*
* \note
* AMI session have managerid == 0; the entry is created upon a connect,
* and destroyed with the socket.
* HTTP sessions have managerid != 0, the value is used as a search key
* to lookup sessions (using the mansession_id cookie, or nonce key from
* Digest Authentication http header).
*/
#define MAX_BLACKLIST_CMD_LEN 2
static const struct {
const char *words[AST_MAX_CMD_LEN];
} command_blacklist[] = {
{{ "module", "load", NULL }},
{{ "module", "unload", NULL }},
{{ "restart", "gracefully", NULL }},
};
static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message);
static void acl_change_stasis_subscribe(void)
{
if (!acl_change_sub) {
acl_change_sub = stasis_subscribe(ast_security_topic(),
acl_change_stasis_cb, NULL);
stasis_subscription_accept_message_type(acl_change_sub, ast_named_acl_change_type());
stasis_subscription_set_filter(acl_change_sub, STASIS_SUBSCRIPTION_FILTER_SELECTIVE);
}
}
static void acl_change_stasis_unsubscribe(void)
{
acl_change_sub = stasis_unsubscribe_and_join(acl_change_sub);
}
/* In order to understand what the heck is going on with the
* mansession_session and mansession structs, we need to have a bit of a history
* lesson.
*
* In the beginning, there was the mansession. The mansession contained data that was
* intrinsic to a manager session, such as the time that it started, the name of the logged-in
* user, etc. In addition to these parameters were the f and fd parameters. For typical manager
* sessions, these were used to represent the TCP socket over which the AMI session was taking
* place. It makes perfect sense for these fields to be a part of the session-specific data since
* the session actually defines this information.
*
* Then came the HTTP AMI sessions. With these, the f and fd fields need to be opened and closed
* for every single action that occurs. Thus the f and fd fields aren't really specific to the session
* but rather to the action that is being executed. Because a single session may execute many commands
* at once, some sort of safety needed to be added in order to be sure that we did not end up with fd
* leaks from one action overwriting the f and fd fields used by a previous action before the previous action
* has had a chance to properly close its handles.
*
* The initial idea to solve this was to use thread synchronization, but this prevented multiple actions
* from being run at the same time in a single session. Some manager actions may block for a long time, thus
* creating a large queue of actions to execute. In addition, this fix did not address the basic architectural
* issue that for HTTP manager sessions, the f and fd variables are not really a part of the session, but are
* part of the action instead.
*
* The new idea was to create a structure on the stack for each HTTP Manager action. This structure would
* contain the action-specific information, such as which file to write to. In order to maintain expectations
* of action handlers and not have to change the public API of the manager code, we would need to name this
* new stacked structure 'mansession' and contain within it the old mansession struct that we used to use.
* We renamed the old mansession struct 'mansession_session' to hopefully convey that what is in this structure
* is session-specific data. The structure that it is wrapped in, called a 'mansession' really contains action-specific
* data.
*/
struct mansession_session {
/*! \todo XXX need to document which fields it is protecting */
struct ast_sockaddr addr; /*!< address we are connecting from */
struct ast_iostream *stream; /*!< AMI stream */
int inuse; /*!< number of HTTP sessions using this entry */
int needdestroy; /*!< Whether an HTTP session should be destroyed */
pthread_t waiting_thread; /*!< Sleeping thread using this descriptor */
uint32_t managerid; /*!< Unique manager identifier, 0 for AMI sessions */
time_t sessionstart; /*!< Session start time */
struct timeval sessionstart_tv; /*!< Session start time */
time_t sessiontimeout; /*!< Session timeout if HTTP */
char username[80]; /*!< Logged in username */
char challenge[10]; /*!< Authentication challenge */
int authenticated; /*!< Authentication status */
int readperm; /*!< Authorization for reading */
int writeperm; /*!< Authorization for writing */
char inbuf[1025]; /*!< Buffer - we use the extra byte to add a '\\0' and simplify parsing */
int inlen; /*!< number of buffered bytes */
struct ao2_container *whitefilters; /*!< Manager event filters - white list */
struct ao2_container *blackfilters; /*!< Manager event filters - black list */
struct ast_variable *chanvars; /*!< Channel variables to set for originate */
int send_events; /*!< XXX what ? */
struct eventqent *last_ev; /*!< last event processed. */
int writetimeout; /*!< Timeout for ast_carefulwrite() */
time_t authstart;
int pending_event; /*!< Pending events indicator in case when waiting_thread is NULL */
time_t noncetime; /*!< Timer for nonce value expiration */
unsigned long oldnonce; /*!< Stale nonce value */
unsigned long nc; /*!< incremental nonce counter */
AST_LIST_HEAD_NOLOCK(mansession_datastores, ast_datastore) datastores; /*!< Data stores on the session */
AST_LIST_ENTRY(mansession_session) list;
};
enum mansession_message_parsing {
MESSAGE_OKAY,
MESSAGE_LINE_TOO_LONG
};
/*! \brief In case you didn't read that giant block of text above the mansession_session struct, the
* \ref struct mansession is named this solely to keep the API the same in Asterisk. This structure really
* represents data that is different from Manager action to Manager action. The mansession_session pointer
* contained within points to session-specific data.
*/
struct mansession {
struct mansession_session *session;
struct ast_iostream *stream;
struct ast_tcptls_session_instance *tcptls_session;
enum mansession_message_parsing parsing;
int write_error:1;
struct manager_custom_hook *hook;
ast_mutex_t lock;
};
/*! Active manager connection sessions container. */
static AO2_GLOBAL_OBJ_STATIC(mgr_sessions);
/*! \brief user descriptor, as read from the config file.
*
* \note It is still missing some fields -- e.g. we can have multiple permit and deny
* lines which are not supported here, and readperm/writeperm/writetimeout
* are not stored.
*/
struct ast_manager_user {
char username[80];
char *secret; /*!< Secret for logging in */
int readperm; /*!< Authorization for reading */
int writeperm; /*!< Authorization for writing */
int writetimeout; /*!< Per user Timeout for ast_carefulwrite() */
int displayconnects; /*!< XXX unused */
int allowmultiplelogin; /*!< Per user option*/
int keep; /*!< mark entries created on a reload */
struct ao2_container *whitefilters; /*!< Manager event filters - white list */
struct ao2_container *blackfilters; /*!< Manager event filters - black list */
struct ast_acl_list *acl; /*!< ACL setting */
char *a1_hash; /*!< precalculated A1 for Digest auth */
struct ast_variable *chanvars; /*!< Channel variables to set for originate */
AST_RWLIST_ENTRY(ast_manager_user) list;
};
/*! \brief list of users found in the config file */
static AST_RWLIST_HEAD_STATIC(users, ast_manager_user);
/*! \brief list of actions registered */
static AST_RWLIST_HEAD_STATIC(actions, manager_action);
/*! \brief list of hooks registered */
static AST_RWLIST_HEAD_STATIC(manager_hooks, manager_custom_hook);
#ifdef AST_XML_DOCS
/*! \brief A container of event documentation nodes */
static AO2_GLOBAL_OBJ_STATIC(event_docs);
#endif
static int __attribute__((format(printf, 9, 0))) __manager_event_sessions(
struct ao2_container *sessions,
int category,
const char *event,
int chancount,
struct ast_channel **chans,
const char *file,
int line,
const char *func,
const char *fmt,
...);
static enum add_filter_result manager_add_filter(const char *filter_pattern, struct ao2_container *whitefilters, struct ao2_container *blackfilters);
static int match_filter(struct mansession *s, char *eventdata);
/*!
* @{ \brief Define AMI message types.
*/
STASIS_MESSAGE_TYPE_DEFN(ast_manager_get_generic_type);
/*! @} */
/*!
* \internal
* \brief Find a registered action object.
*
* \param name Name of AMI action to find.
*
* \return Reffed action found or NULL
*/
static struct manager_action *action_find(const char *name)
{
struct manager_action *act;
AST_RWLIST_RDLOCK(&actions);
AST_RWLIST_TRAVERSE(&actions, act, list) {
if (!strcasecmp(name, act->action)) {
ao2_t_ref(act, +1, "found action object");
break;
}
}
AST_RWLIST_UNLOCK(&actions);
return act;
}
struct stasis_topic *ast_manager_get_topic(void)
{
return manager_topic;
}
struct stasis_message_router *ast_manager_get_message_router(void)
{
return stasis_router;
}
static void manager_json_value_str_append(struct ast_json *value, const char *key,
struct ast_str **res)
{
switch (ast_json_typeof(value)) {
case AST_JSON_STRING:
ast_str_append(res, 0, "%s: %s\r\n", key, ast_json_string_get(value));
break;
case AST_JSON_INTEGER:
ast_str_append(res, 0, "%s: %jd\r\n", key, ast_json_integer_get(value));
break;
case AST_JSON_TRUE:
ast_str_append(res, 0, "%s: True\r\n", key);
break;
case AST_JSON_FALSE:
ast_str_append(res, 0, "%s: False\r\n", key);
break;
default:
ast_str_append(res, 0, "%s: \r\n", key);
break;
}
}
static void manager_json_to_ast_str(struct ast_json *obj, const char *key,
struct ast_str **res, key_exclusion_cb exclusion_cb);
static void manager_json_array_with_key(struct ast_json *obj, const char* key,
size_t index, struct ast_str **res,
key_exclusion_cb exclusion_cb)
{
struct ast_str *key_str = ast_str_alloca(64);
ast_str_set(&key_str, 0, "%s(%zu)", key, index);
manager_json_to_ast_str(obj, ast_str_buffer(key_str),
res, exclusion_cb);
}
static void manager_json_obj_with_key(struct ast_json *obj, const char* key,
const char *parent_key, struct ast_str **res,
key_exclusion_cb exclusion_cb)
{
if (parent_key) {
struct ast_str *key_str = ast_str_alloca(64);
ast_str_set(&key_str, 0, "%s/%s", parent_key, key);
manager_json_to_ast_str(obj, ast_str_buffer(key_str),
res, exclusion_cb);
return;
}
manager_json_to_ast_str(obj, key, res, exclusion_cb);
}
void manager_json_to_ast_str(struct ast_json *obj, const char *key,
struct ast_str **res, key_exclusion_cb exclusion_cb)
{
struct ast_json_iter *i;
/* If obj or res is not given, just return */
if (!obj || !res) {
return;
}
if (!*res && !(*res = ast_str_create(1024))) {
return;
}
if (exclusion_cb && key && exclusion_cb(key)) {
return;
}
if (ast_json_typeof(obj) != AST_JSON_OBJECT &&
ast_json_typeof(obj) != AST_JSON_ARRAY) {
manager_json_value_str_append(obj, key, res);
return;
}
if (ast_json_typeof(obj) == AST_JSON_ARRAY) {
size_t j;
for (j = 0; j < ast_json_array_size(obj); ++j) {
manager_json_array_with_key(ast_json_array_get(obj, j),
key, j, res, exclusion_cb);
}
return;
}
for (i = ast_json_object_iter(obj); i;
i = ast_json_object_iter_next(obj, i)) {
manager_json_obj_with_key(ast_json_object_iter_value(i),
ast_json_object_iter_key(i),
key, res, exclusion_cb);
}
}
struct ast_str *ast_manager_str_from_json_object(struct ast_json *blob, key_exclusion_cb exclusion_cb)
{
struct ast_str *res = ast_str_create(1024);
if (!ast_json_is_null(blob)) {
manager_json_to_ast_str(blob, NULL, &res, exclusion_cb);
}
return res;
}
#define manager_event_sessions(sessions, category, event, contents , ...) \
__manager_event_sessions(sessions, category, event, 0, NULL, __FILE__, __LINE__, __PRETTY_FUNCTION__, contents , ## __VA_ARGS__)
#define any_manager_listeners(sessions) \
((sessions && ao2_container_count(sessions)) || !AST_RWLIST_EMPTY(&manager_hooks))
static void manager_default_msg_cb(void *data, struct stasis_subscription *sub,
struct stasis_message *message)
{
struct ao2_container *sessions;
struct ast_manager_event_blob *ev;
if (!stasis_message_can_be_ami(message)) {
/* Not an AMI message; disregard */
return;
}
sessions = ao2_global_obj_ref(mgr_sessions);
if (!any_manager_listeners(sessions)) {
/* Nobody is listening */
ao2_cleanup(sessions);
return;
}
ev = stasis_message_to_ami(message);
if (!ev) {
/* Conversion failure */
ao2_cleanup(sessions);
return;
}
manager_event_sessions(sessions, ev->event_flags, ev->manager_event,
"%s", ev->extra_fields);
ao2_ref(ev, -1);
ao2_cleanup(sessions);
}
static void manager_generic_msg_cb(void *data, struct stasis_subscription *sub,
struct stasis_message *message)
{
struct ast_json_payload *payload;
int class_type;
const char *type;
struct ast_json *event;
struct ast_str *event_buffer;
struct ao2_container *sessions;
sessions = ao2_global_obj_ref(mgr_sessions);
if (!any_manager_listeners(sessions)) {
/* Nobody is listening */
ao2_cleanup(sessions);
return;
}
payload = stasis_message_data(message);
class_type = ast_json_integer_get(ast_json_object_get(payload->json, "class_type"));
type = ast_json_string_get(ast_json_object_get(payload->json, "type"));
event = ast_json_object_get(payload->json, "event");
event_buffer = ast_manager_str_from_json_object(event, NULL);
if (!event_buffer) {
ast_log(AST_LOG_WARNING, "Error while creating payload for event %s\n", type);
ao2_cleanup(sessions);
return;
}
manager_event_sessions(sessions, class_type, type,
"%s", ast_str_buffer(event_buffer));
ast_free(event_buffer);
ao2_cleanup(sessions);
}
void ast_manager_publish_event(const char *type, int class_type, struct ast_json *obj)
{
RAII_VAR(struct ast_json *, event_info, NULL, ast_json_unref);
RAII_VAR(struct ast_json_payload *, payload, NULL, ao2_cleanup);
RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
if (!obj || !ast_manager_get_generic_type()) {
return;
}
ast_json_ref(obj);
event_info = ast_json_pack("{s: s, s: i, s: o}",
"type", type,
"class_type", class_type,
"event", obj);
if (!event_info) {
return;
}
payload = ast_json_payload_create(event_info);
if (!payload) {
return;
}
message = stasis_message_create(ast_manager_get_generic_type(), payload);
if (!message) {
return;
}
stasis_publish(ast_manager_get_topic(), message);
}
/*! \brief Add a custom hook to be called when an event is fired */
void ast_manager_register_hook(struct manager_custom_hook *hook)
{
AST_RWLIST_WRLOCK(&manager_hooks);
AST_RWLIST_INSERT_TAIL(&manager_hooks, hook, list);
AST_RWLIST_UNLOCK(&manager_hooks);
}
/*! \brief Delete a custom hook to be called when an event is fired */
void ast_manager_unregister_hook(struct manager_custom_hook *hook)
{
AST_RWLIST_WRLOCK(&manager_hooks);
AST_RWLIST_REMOVE(&manager_hooks, hook, list);
AST_RWLIST_UNLOCK(&manager_hooks);
}
int check_manager_enabled(void)
{
return manager_enabled;
}
int check_webmanager_enabled(void)
{
return (webmanager_enabled && manager_enabled);
}
/*!
* Grab a reference to the last event, update usecount as needed.
* Can handle a NULL pointer.
*/
static struct eventqent *grab_last(void)
{
struct eventqent *ret;
AST_RWLIST_WRLOCK(&all_events);
ret = AST_RWLIST_LAST(&all_events);
/* the list is never empty now, but may become so when
* we optimize it in the future, so be prepared.
*/
if (ret) {
ast_atomic_fetchadd_int(&ret->usecount, 1);
}
AST_RWLIST_UNLOCK(&all_events);
return ret;
}
/*!
* Purge unused events. Remove elements from the head
* as long as their usecount is 0 and there is a next element.
*/
static void purge_events(void)
{
struct eventqent *ev;
struct timeval now = ast_tvnow();
AST_RWLIST_WRLOCK(&all_events);
while ( (ev = AST_RWLIST_FIRST(&all_events)) &&
ev->usecount == 0 && AST_RWLIST_NEXT(ev, eq_next)) {
AST_RWLIST_REMOVE_HEAD(&all_events, eq_next);
ast_free(ev);
}
AST_RWLIST_TRAVERSE_SAFE_BEGIN(&all_events, ev, eq_next) {
/* Never release the last event */
if (!AST_RWLIST_NEXT(ev, eq_next)) {
break;
}
/* 2.5 times whatever the HTTP timeout is (maximum 2.5 hours) is the maximum time that we will definitely cache an event */
if (ev->usecount == 0 && ast_tvdiff_sec(now, ev->tv) > (httptimeout > 3600 ? 3600 : httptimeout) * 2.5) {
AST_RWLIST_REMOVE_CURRENT(eq_next);
ast_free(ev);
}
}
AST_RWLIST_TRAVERSE_SAFE_END;
AST_RWLIST_UNLOCK(&all_events);
}
/*!
* helper functions to convert back and forth between
* string and numeric representation of set of flags
*/
static const struct permalias {
int num;
const char *label;
} perms[] = {
{ EVENT_FLAG_SYSTEM, "system" },
{ EVENT_FLAG_CALL, "call" },
{ EVENT_FLAG_LOG, "log" },
{ EVENT_FLAG_VERBOSE, "verbose" },
{ EVENT_FLAG_COMMAND, "command" },
{ EVENT_FLAG_AGENT, "agent" },
{ EVENT_FLAG_USER, "user" },
{ EVENT_FLAG_CONFIG, "config" },
{ EVENT_FLAG_DTMF, "dtmf" },
{ EVENT_FLAG_REPORTING, "reporting" },
{ EVENT_FLAG_CDR, "cdr" },
{ EVENT_FLAG_DIALPLAN, "dialplan" },
{ EVENT_FLAG_ORIGINATE, "originate" },
{ EVENT_FLAG_AGI, "agi" },
{ EVENT_FLAG_CC, "cc" },
{ EVENT_FLAG_AOC, "aoc" },
{ EVENT_FLAG_TEST, "test" },
{ EVENT_FLAG_SECURITY, "security" },
{ EVENT_FLAG_MESSAGE, "message" },
{ INT_MAX, "all" },
{ 0, "none" },
};
/*! Maximum string length of the AMI authority permission string buildable from perms[]. */
#define MAX_AUTH_PERM_STRING 150
/*! \brief Checks to see if a string which can be used to evaluate functions should be rejected */
static int function_capable_string_allowed_with_auths(const char *evaluating, int writepermlist)
{
if (!(writepermlist & EVENT_FLAG_SYSTEM)
&& (
strstr(evaluating, "SHELL") || /* NoOp(${SHELL(rm -rf /)}) */
strstr(evaluating, "EVAL") /* NoOp(${EVAL(${some_var_containing_SHELL})}) */
)) {
return 0;
}
return 1;
}
/*! \brief Convert authority code to a list of options for a user. This will only
* display those authority codes that have an explicit match on authority */
static const char *user_authority_to_str(int authority, struct ast_str **res)
{
int i;
char *sep = "";
ast_str_reset(*res);
for (i = 0; i < ARRAY_LEN(perms) - 1; i++) {
if ((authority & perms[i].num) == perms[i].num) {
ast_str_append(res, 0, "%s%s", sep, perms[i].label);
sep = ",";
}
}
if (ast_str_strlen(*res) == 0) {
/* replace empty string with something sensible */
ast_str_append(res, 0, "<none>");
}
return ast_str_buffer(*res);
}
/*! \brief Convert authority code to a list of options. Note that the EVENT_FLAG_ALL
* authority will always be returned. */
static const char *authority_to_str(int authority, struct ast_str **res)
{
int i;
char *sep = "";
ast_str_reset(*res);
if (authority != EVENT_FLAG_SHUTDOWN) {
for (i = 0; i < ARRAY_LEN(perms) - 1; i++) {
if (authority & perms[i].num) {
ast_str_append(res, 0, "%s%s", sep, perms[i].label);
sep = ",";
}
}
}
if (ast_str_strlen(*res) == 0) {
/* replace empty string with something sensible */
ast_str_append(res, 0, "<none>");
}
return ast_str_buffer(*res);
}
/*! Tells you if smallstr exists inside bigstr
which is delim by delim and uses no buf or stringsep
ast_instring("this|that|more","this",'|') == 1;
feel free to move this to app.c -anthm */
static int ast_instring(const char *bigstr, const char *smallstr, const char delim)
{
const char *val = bigstr, *next;
do {
if ((next = strchr(val, delim))) {
if (!strncmp(val, smallstr, (next - val))) {
return 1;
} else {
continue;
}
} else {
return !strcmp(smallstr, val);
}
} while (*(val = (next + 1)));
return 0;
}
static int get_perm(const char *instr)
{
int x = 0, ret = 0;
if (!instr) {
return 0;
}
for (x = 0; x < ARRAY_LEN(perms); x++) {
if (ast_instring(instr, perms[x].label, ',')) {
ret |= perms[x].num;
}
}
return ret;
}
/*!
* A number returns itself, false returns 0, true returns all flags,
* other strings return the flags that are set.
*/
static int strings_to_mask(const char *string)
{
const char *p;
if (ast_strlen_zero(string)) {
return -1;
}
for (p = string; *p; p++) {
if (*p < '0' || *p > '9') {
break;
}
}
if (!*p) { /* all digits */
return atoi(string);
}
if (ast_false(string)) {
return 0;
}
if (ast_true(string)) { /* all permissions */
int x, ret = 0;
for (x = 0; x < ARRAY_LEN(perms); x++) {
ret |= perms[x].num;
}
return ret;
}
return get_perm(string);
}
/*! \brief Unreference manager session object.
If no more references, then go ahead and delete it */
static struct mansession_session *unref_mansession(struct mansession_session *s)
{
int refcount = ao2_ref(s, -1);
if (manager_debug) {
ast_debug(1, "Mansession: %p refcount now %d\n", s, refcount - 1);
}
return NULL;
}
static void event_filter_destructor(void *obj)
{
regex_t *regex_filter = obj;
regfree(regex_filter);
}
static void session_destructor(void *obj)
{
struct mansession_session *session = obj;
struct eventqent *eqe = session->last_ev;
struct ast_datastore *datastore;
/* Get rid of each of the data stores on the session */
while ((datastore = AST_LIST_REMOVE_HEAD(&session->datastores, entry))) {
/* Free the data store */
ast_datastore_free(datastore);
}
if (eqe) {
ast_atomic_fetchadd_int(&eqe->usecount, -1);
}
if (session->chanvars) {
ast_variables_destroy(session->chanvars);
}
if (session->whitefilters) {
ao2_t_ref(session->whitefilters, -1, "decrement ref for white container, should be last one");
}
if (session->blackfilters) {
ao2_t_ref(session->blackfilters, -1, "decrement ref for black container, should be last one");
}
}
/*! \brief Allocate manager session structure and add it to the list of sessions */
static struct mansession_session *build_mansession(const struct ast_sockaddr *addr)
{
struct ao2_container *sessions;
struct mansession_session *newsession;
newsession = ao2_alloc(sizeof(*newsession), session_destructor);
if (!newsession) {
return NULL;
}
newsession->whitefilters = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_MUTEX, 0, NULL, NULL);
newsession->blackfilters = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_MUTEX, 0, NULL, NULL);
if (!newsession->whitefilters || !newsession->blackfilters) {
ao2_ref(newsession, -1);
return NULL;
}
newsession->waiting_thread = AST_PTHREADT_NULL;
newsession->writetimeout = 100;
newsession->send_events = -1;
ast_sockaddr_copy(&newsession->addr, addr);
sessions = ao2_global_obj_ref(mgr_sessions);
if (sessions) {
ao2_link(sessions, newsession);
ao2_ref(sessions, -1);
}
return newsession;
}
static int mansession_cmp_fn(void *obj, void *arg, int flags)
{
struct mansession_session *s = obj;
char *str = arg;
return !strcasecmp(s->username, str) ? CMP_MATCH : 0;
}
static void session_destroy(struct mansession_session *s)
{
struct ao2_container *sessions;
sessions = ao2_global_obj_ref(mgr_sessions);
if (sessions) {
ao2_unlink(sessions, s);
ao2_ref(sessions, -1);
}
unref_mansession(s);
}
static int check_manager_session_inuse(const char *name)
{
struct ao2_container *sessions;
struct mansession_session *session;
int inuse = 0;
sessions = ao2_global_obj_ref(mgr_sessions);
if (sessions) {
session = ao2_find(sessions, (char *) name, 0);
ao2_ref(sessions, -1);
if (session) {
unref_mansession(session);
inuse = 1;
}
}
return inuse;
}
/*!
* lookup an entry in the list of registered users.
* must be called with the list lock held.
*/
static struct ast_manager_user *get_manager_by_name_locked(const char *name)
{
struct ast_manager_user *user = NULL;
AST_RWLIST_TRAVERSE(&users, user, list) {
if (!strcasecmp(user->username, name)) {
break;
}
}
return user;
}
/*! \brief Get displayconnects config option.
* \param session manager session to get parameter from.
* \return displayconnects config option value.
*/
static int manager_displayconnects(struct mansession_session *session)
{
struct ast_manager_user *user = NULL;
int ret = 0;
AST_RWLIST_RDLOCK(&users);
if ((user = get_manager_by_name_locked(session->username))) {
ret = user->displayconnects;
}
AST_RWLIST_UNLOCK(&users);
return ret;
}
#ifdef AST_XML_DOCS
static void print_event_instance(struct ast_cli_args *a, struct ast_xml_doc_item *instance);
#endif
static char *handle_showmancmd(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
struct manager_action *cur;
struct ast_str *authority;
int num;
int l;
const char *auth_str;
#ifdef AST_XML_DOCS
char syntax_title[64], description_title[64], synopsis_title[64], seealso_title[64];
char arguments_title[64], privilege_title[64], final_response_title[64], list_responses_title[64];
#endif
switch (cmd) {
case CLI_INIT:
e->command = "manager show command";
e->usage =
"Usage: manager show command <actionname> [<actionname> [<actionname> [...]]]\n"
" Shows the detailed description for a specific Asterisk manager interface command.\n";
return NULL;
case CLI_GENERATE:
l = strlen(a->word);
AST_RWLIST_RDLOCK(&actions);
AST_RWLIST_TRAVERSE(&actions, cur, list) {
if (!strncasecmp(a->word, cur->action, l)) {
if (ast_cli_completion_add(ast_strdup(cur->action))) {
break;
}
}
}
AST_RWLIST_UNLOCK(&actions);
return NULL;
}
if (a->argc < 4) {
return CLI_SHOWUSAGE;
}
authority = ast_str_alloca(MAX_AUTH_PERM_STRING);
#ifdef AST_XML_DOCS
/* setup the titles */
term_color(synopsis_title, "[Synopsis]\n", COLOR_MAGENTA, 0, 40);
term_color(description_title, "[Description]\n", COLOR_MAGENTA, 0, 40);
term_color(syntax_title, "[Syntax]\n", COLOR_MAGENTA, 0, 40);
term_color(seealso_title, "[See Also]\n", COLOR_MAGENTA, 0, 40);
term_color(arguments_title, "[Arguments]\n", COLOR_MAGENTA, 0, 40);
term_color(privilege_title, "[Privilege]\n", COLOR_MAGENTA, 0, 40);
term_color(final_response_title, "[Final Response]\n", COLOR_MAGENTA, 0, 40);
term_color(list_responses_title, "[List Responses]\n", COLOR_MAGENTA, 0, 40);
#endif
AST_RWLIST_RDLOCK(&actions);
AST_RWLIST_TRAVERSE(&actions, cur, list) {
for (num = 3; num < a->argc; num++) {
if (!strcasecmp(cur->action, a->argv[num])) {
auth_str = authority_to_str(cur->authority, &authority);
#ifdef AST_XML_DOCS
if (cur->docsrc == AST_XML_DOC) {
char *syntax = ast_xmldoc_printable(S_OR(cur->syntax, "Not available"), 1);
char *synopsis = ast_xmldoc_printable(S_OR(cur->synopsis, "Not available"), 1);
char *description = ast_xmldoc_printable(S_OR(cur->description, "Not available"), 1);
char *arguments = ast_xmldoc_printable(S_OR(cur->arguments, "Not available"), 1);
char *seealso = ast_xmldoc_printable(S_OR(cur->seealso, "Not available"), 1);
char *privilege = ast_xmldoc_printable(S_OR(auth_str, "Not available"), 1);
char *responses = ast_xmldoc_printable("None", 1);
if (!syntax || !synopsis || !description || !arguments
|| !seealso || !privilege || !responses) {
ast_free(syntax);
ast_free(synopsis);
ast_free(description);
ast_free(arguments);
ast_free(seealso);
ast_free(privilege);
ast_free(responses);
ast_cli(a->fd, "Allocation failure.\n");
AST_RWLIST_UNLOCK(&actions);
return CLI_FAILURE;
}
ast_cli(a->fd, "%s%s\n\n%s%s\n\n%s%s\n\n%s%s\n\n%s%s\n\n%s%s\n\n%s",
syntax_title, syntax,
synopsis_title, synopsis,
description_title, description,
arguments_title, arguments,
seealso_title, seealso,
privilege_title, privilege,
list_responses_title);
if (!cur->list_responses) {
ast_cli(a->fd, "%s\n\n", responses);
} else {
struct ast_xml_doc_item *temp;
for (temp = cur->list_responses; temp; temp = AST_LIST_NEXT(temp, next)) {
ast_cli(a->fd, "Event: %s\n", temp->name);
print_event_instance(a, temp);
}
}
ast_cli(a->fd, "%s", final_response_title);
if (!cur->final_response) {
ast_cli(a->fd, "%s\n\n", responses);
} else {
ast_cli(a->fd, "Event: %s\n", cur->final_response->name);
print_event_instance(a, cur->final_response);
}
ast_free(syntax);
ast_free(synopsis);
ast_free(description);
ast_free(arguments);
ast_free(seealso);
ast_free(privilege);
ast_free(responses);
} else
#endif
{
ast_cli(a->fd, "Action: %s\nSynopsis: %s\nPrivilege: %s\n%s\n",
cur->action, cur->synopsis,
auth_str,
S_OR(cur->description, ""));
}
}
}
}
AST_RWLIST_UNLOCK(&actions);
return CLI_SUCCESS;
}
static char *handle_mandebug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
switch (cmd) {
case CLI_INIT:
e->command = "manager set debug [on|off]";
e->usage = "Usage: manager set debug [on|off]\n Show, enable, disable debugging of the manager code.\n";
return NULL;
case CLI_GENERATE:
return NULL;
}
if (a->argc == 3) {
ast_cli(a->fd, "manager debug is %s\n", manager_debug? "on" : "off");
} else if (a->argc == 4) {
if (!strcasecmp(a->argv[3], "on")) {
manager_debug = 1;
} else if (!strcasecmp(a->argv[3], "off")) {
manager_debug = 0;
} else {
return CLI_SHOWUSAGE;
}
}
return CLI_SUCCESS;
}
static char *handle_showmanager(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
struct ast_manager_user *user = NULL;
int l;
struct ast_str *rauthority = ast_str_alloca(MAX_AUTH_PERM_STRING);
struct ast_str *wauthority = ast_str_alloca(MAX_AUTH_PERM_STRING);
struct ast_variable *v;
switch (cmd) {
case CLI_INIT:
e->command = "manager show user";
e->usage =
" Usage: manager show user <user>\n"
" Display all information related to the manager user specified.\n";
return NULL;
case CLI_GENERATE:
l = strlen(a->word);
if (a->pos != 3) {
return NULL;
}
AST_RWLIST_RDLOCK(&users);
AST_RWLIST_TRAVERSE(&users, user, list) {
if (!strncasecmp(a->word, user->username, l)) {
if (ast_cli_completion_add(ast_strdup(user->username))) {
break;
}
}
}
AST_RWLIST_UNLOCK(&users);
return NULL;
}
if (a->argc != 4) {
return CLI_SHOWUSAGE;
}
AST_RWLIST_RDLOCK(&users);
if (!(user = get_manager_by_name_locked(a->argv[3]))) {
ast_cli(a->fd, "There is no manager called %s\n", a->argv[3]);
AST_RWLIST_UNLOCK(&users);
return CLI_SUCCESS;
}
ast_cli(a->fd, "\n");
ast_cli(a->fd,
" username: %s\n"
" secret: %s\n"
" ACL: %s\n"
" read perm: %s\n"
" write perm: %s\n"
" displayconnects: %s\n"
"allowmultiplelogin: %s\n",
S_OR(user->username, "(N/A)"),
(user->secret ? "<Set>" : "(N/A)"),
((user->acl && !ast_acl_list_is_empty(user->acl)) ? "yes" : "no"),
user_authority_to_str(user->readperm, &rauthority),
user_authority_to_str(user->writeperm, &wauthority),
(user->displayconnects ? "yes" : "no"),
(user->allowmultiplelogin ? "yes" : "no"));
ast_cli(a->fd, " Variables: \n");
for (v = user->chanvars ; v ; v = v->next) {
ast_cli(a->fd, " %s = %s\n", v->name, v->value);
}
AST_RWLIST_UNLOCK(&users);
return CLI_SUCCESS;
}
static char *handle_showmanagers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
struct ast_manager_user *user = NULL;
int count_amu = 0;
switch (cmd) {
case CLI_INIT:
e->command = "manager show users";
e->usage =
"Usage: manager show users\n"
" Prints a listing of all managers that are currently configured on that\n"
" system.\n";
return NULL;
case CLI_GENERATE:
return NULL;
}
if (a->argc != 3) {
return CLI_SHOWUSAGE;
}
AST_RWLIST_RDLOCK(&users);
/* If there are no users, print out something along those lines */
if (AST_RWLIST_EMPTY(&users)) {
ast_cli(a->fd, "There are no manager users.\n");
AST_RWLIST_UNLOCK(&users);
return CLI_SUCCESS;
}
ast_cli(a->fd, "\nusername\n--------\n");
AST_RWLIST_TRAVERSE(&users, user, list) {
ast_cli(a->fd, "%s\n", user->username);
count_amu++;
}
AST_RWLIST_UNLOCK(&users);
ast_cli(a->fd,"-------------------\n"
"%d manager users configured.\n", count_amu);
return CLI_SUCCESS;
}
/*! \brief CLI command manager list commands */
static char *handle_showmancmds(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
struct manager_action *cur;
int name_len = 1;
int space_remaining;
#define HSMC_FORMAT " %-*.*s %-.*s\n"
switch (cmd) {
case CLI_INIT:
e->command = "manager show commands";
e->usage =
"Usage: manager show commands\n"
" Prints a listing of all the available Asterisk manager interface commands.\n";
return NULL;
case CLI_GENERATE:
return NULL;
}
AST_RWLIST_RDLOCK(&actions);
AST_RWLIST_TRAVERSE(&actions, cur, list) {
int incoming_len = strlen(cur->action);
if (incoming_len > name_len) {
name_len = incoming_len;
}
}
space_remaining = MGR_SHOW_TERMINAL_WIDTH - name_len - 4;
if (space_remaining < 0) {
space_remaining = 0;
}
ast_cli(a->fd, HSMC_FORMAT, name_len, name_len, "Action", space_remaining, "Synopsis");
ast_cli(a->fd, HSMC_FORMAT, name_len, name_len, "------", space_remaining, "--------");
AST_RWLIST_TRAVERSE(&actions, cur, list) {
ast_cli(a->fd, HSMC_FORMAT, name_len, name_len, cur->action, space_remaining, cur->synopsis);
}
AST_RWLIST_UNLOCK(&actions);
return CLI_SUCCESS;
}
/*! \brief CLI command manager list connected */
static char *handle_showmanconn(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
struct ao2_container *sessions;
struct mansession_session *session;
time_t now = time(NULL);
#define HSMCONN_FORMAT1 " %-15.15s %-55.55s %-10.10s %-10.10s %-8.8s %-8.8s %-5.5s %-5.5s\n"
#define HSMCONN_FORMAT2 " %-15.15s %-55.55s %-10d %-10d %-8d %-8d %-5.5d %-5.5d\n"
int count = 0;
struct ao2_iterator i;
switch (cmd) {
case CLI_INIT:
e->command = "manager show connected";
e->usage =
"Usage: manager show connected\n"
" Prints a listing of the users that are currently connected to the\n"
"Asterisk manager interface.\n";
return NULL;
case CLI_GENERATE:
return NULL;
}
ast_cli(a->fd, HSMCONN_FORMAT1, "Username", "IP Address", "Start", "Elapsed", "FileDes", "HttpCnt", "Read", "Write");
sessions = ao2_global_obj_ref(mgr_sessions);
if (sessions) {
i = ao2_iterator_init(sessions, 0);
ao2_ref(sessions, -1);
while ((session = ao2_iterator_next(&i))) {
ao2_lock(session);
ast_cli(a->fd, HSMCONN_FORMAT2, session->username,
ast_sockaddr_stringify_addr(&session->addr),
(int) (session->sessionstart),
(int) (now - session->sessionstart),
session->stream ? ast_iostream_get_fd(session->stream) : -1,
session->inuse,
session->readperm,
session->writeperm);
count++;
ao2_unlock(session);
unref_mansession(session);
}
ao2_iterator_destroy(&i);
}
ast_cli(a->fd, "%d users connected.\n", count);
return CLI_SUCCESS;
}
/*! \brief CLI command manager list eventq */
/* Should change to "manager show connected" */
static char *handle_showmaneventq(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
struct eventqent *s;
switch (cmd) {
case CLI_INIT:
e->command = "manager show eventq";
e->usage =
"Usage: manager show eventq\n"
" Prints a listing of all events pending in the Asterisk manger\n"
"event queue.\n";
return NULL;
case CLI_GENERATE:
return NULL;
}
AST_RWLIST_RDLOCK(&all_events);
AST_RWLIST_TRAVERSE(&all_events, s, eq_next) {
ast_cli(a->fd, "Usecount: %d\n", s->usecount);
ast_cli(a->fd, "Category: %d\n", s->category);
ast_cli(a->fd, "Event:\n%s", s->eventdata);
}
AST_RWLIST_UNLOCK(&all_events);
return CLI_SUCCESS;
}
static int reload_module(void);
/*! \brief CLI command manager reload */
static char *handle_manager_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
switch (cmd) {
case CLI_INIT:
e->command = "manager reload";
e->usage =
"Usage: manager reload\n"
" Reloads the manager configuration.\n";
return NULL;
case CLI_GENERATE:
return NULL;
}
if (a->argc > 2) {
return CLI_SHOWUSAGE;
}
reload_module();
return CLI_SUCCESS;
}
static struct eventqent *advance_event(struct eventqent *e)
{
struct eventqent *next;
AST_RWLIST_RDLOCK(&all_events);
if ((next = AST_RWLIST_NEXT(e, eq_next))) {
ast_atomic_fetchadd_int(&next->usecount, 1);
ast_atomic_fetchadd_int(&e->usecount, -1);
}
AST_RWLIST_UNLOCK(&all_events);
return next;
}
#define GET_HEADER_FIRST_MATCH 0
#define GET_HEADER_LAST_MATCH 1
#define GET_HEADER_SKIP_EMPTY 2
/*!
* \brief Return a matching header value.
*
* \details
* Generic function to return either the first or the last
* matching header from a list of variables, possibly skipping
* empty strings.
*
* \note At the moment there is only one use of this function in
* this file, so we make it static.
*
* \note Never returns NULL.
*/
static const char *__astman_get_header(const struct message *m, char *var, int mode)
{
int x, l = strlen(var);
const char *result = "";
if (!m) {
return result;
}
for (x = 0; x < m->hdrcount; x++) {
const char *h = m->headers[x];
if (!strncasecmp(var, h, l) && h[l] == ':') {
const char *value = h + l + 1;
value = ast_skip_blanks(value); /* ignore leading spaces in the value */
/* found a potential candidate */
if ((mode & GET_HEADER_SKIP_EMPTY) && ast_strlen_zero(value)) {
continue; /* not interesting */
}
if (mode & GET_HEADER_LAST_MATCH) {
result = value; /* record the last match so far */
} else {
return value;
}
}
}
return result;
}
/*!
* \brief Return the first matching variable from an array.
*
* \note This is the legacy function and is implemented in
* therms of __astman_get_header().
*
* \note Never returns NULL.
*/
const char *astman_get_header(const struct message *m, char *var)
{
return __astman_get_header(m, var, GET_HEADER_FIRST_MATCH);
}
/*!
* \brief Append additional headers into the message structure from params.
*
* \note You likely want to initialize m->hdrcount to 0 before calling this.
*/
static void astman_append_headers(struct message *m, const struct ast_variable *params)
{
const struct ast_variable *v;
for (v = params; v && m->hdrcount < ARRAY_LEN(m->headers); v = v->next) {
if (ast_asprintf((char**)&m->headers[m->hdrcount], "%s: %s", v->name, v->value) > -1) {
++m->hdrcount;
}
}
}
/*!
* \brief Free headers inside message structure, but not the message structure itself.
*/
static void astman_free_headers(struct message *m)
{
while (m->hdrcount) {
--m->hdrcount;
ast_free((void *) m->headers[m->hdrcount]);
m->headers[m->hdrcount] = NULL;
}
}
/*!
* \internal
* \brief Process one "Variable:" header value string.
*
* \param head Current list of AMI variables to get new values added.
* \param hdr_val Header value string to process.
*
* \return New variable list head.
*/
static struct ast_variable *man_do_variable_value(struct ast_variable *head, const char *hdr_val)
{
char *parse;
AST_DECLARE_APP_ARGS(args,
AST_APP_ARG(vars)[64];
);
hdr_val = ast_skip_blanks(hdr_val); /* ignore leading spaces in the value */
parse = ast_strdupa(hdr_val);
/* Break the header value string into name=val pair items. */
AST_STANDARD_APP_ARGS(args, parse);
if (args.argc) {
int y;
/* Process each name=val pair item. */
for (y = 0; y < args.argc; y++) {
struct ast_variable *cur;
char *var;
char *val;
if (!args.vars[y]) {
continue;
}
var = val = args.vars[y];
strsep(&val, "=");
/* XXX We may wish to trim whitespace from the strings. */
if (!val || ast_strlen_zero(var)) {
continue;
}
/* Create new variable list node and prepend it to the list. */
cur = ast_variable_new(var, val, "");
if (cur) {
cur->next = head;
head = cur;
}
}
}
return head;
}
struct ast_variable *astman_get_variables(const struct message *m)
{
return astman_get_variables_order(m, ORDER_REVERSE);
}
struct ast_variable *astman_get_variables_order(const struct message *m,
enum variable_orders order)
{
int varlen;
int x;
struct ast_variable *head = NULL;
static const char var_hdr[] = "Variable:";
/* Process all "Variable:" headers. */
varlen = strlen(var_hdr);
for (x = 0; x < m->hdrcount; x++) {
if (strncasecmp(var_hdr, m->headers[x], varlen)) {
continue;
}
head = man_do_variable_value(head, m->headers[x] + varlen);
}
if (order == ORDER_NATURAL) {
head = ast_variables_reverse(head);
}
return head;
}
/*! \brief access for hooks to send action messages to ami */
int ast_hook_send_action(struct manager_custom_hook *hook, const char *msg)
{
const char *action;
int ret = 0;
struct manager_action *act_found;
struct mansession s = {.session = NULL, };
struct message m = { 0 };
char *dup_str;
char *src;
int x = 0;
int curlen;
if (hook == NULL) {
return -1;
}
/* Create our own copy of the AMI action msg string. */
src = dup_str = ast_strdup(msg);
if (!dup_str) {
return -1;
}
/* convert msg string to message struct */
curlen = strlen(src);
for (x = 0; x < curlen; x++) {
int cr; /* set if we have \r */
if (src[x] == '\r' && x+1 < curlen && src[x+1] == '\n')
cr = 2; /* Found. Update length to include \r\n */
else if (src[x] == '\n')
cr = 1; /* also accept \n only */
else
continue;
/* don't keep empty lines */
if (x && m.hdrcount < ARRAY_LEN(m.headers)) {
/* ... but trim \r\n and terminate the header string */
src[x] = '\0';
m.headers[m.hdrcount++] = src;
}
x += cr;
curlen -= x; /* remaining size */
src += x; /* update pointer */
x = -1; /* reset loop */
}
action = astman_get_header(&m, "Action");
do {
if (!strcasecmp(action, "login")) {
break;
}
act_found = action_find(action);
if (!act_found) {
break;
}
/*
* we have to simulate a session for this action request
* to be able to pass it down for processing
* This is necessary to meet the previous design of manager.c
*/
s.hook = hook;
ret = -1;
ao2_lock(act_found);
if (act_found->registered && act_found->func) {
struct ast_module *mod_ref = ast_module_running_ref(act_found->module);
ao2_unlock(act_found);
/* If the action is in a module it must be running. */
if (!act_found->module || mod_ref) {
ret = act_found->func(&s, &m);
ast_module_unref(mod_ref);
}
} else {
ao2_unlock(act_found);
}
ao2_t_ref(act_found, -1, "done with found action object");
} while (0);
ast_free(dup_str);
return ret;
}
/*!
* helper function to send a string to the socket.
* Return -1 on error (e.g. buffer full).
*/
static int send_string(struct mansession *s, char *string)
{
struct ast_iostream *stream;
int len, res;
/* It's a result from one of the hook's action invocation */
if (s->hook) {
/*
* to send responses, we're using the same function
* as for receiving events. We call the event "HookResponse"
*/
s->hook->helper(EVENT_FLAG_HOOKRESPONSE, "HookResponse", string);
return 0;
}
stream = s->stream ? s->stream : s->session->stream;
len = strlen(string);
ast_iostream_set_timeout_inactivity(stream, s->session->writetimeout);
res = ast_iostream_write(stream, string, len);
ast_iostream_set_timeout_disable(stream);
if (res < len) {
s->write_error = 1;
}
return res;
}
/*!
* \brief thread local buffer for astman_append
*
* \note This can not be defined within the astman_append() function
* because it declares a couple of functions that get used to
* initialize the thread local storage key.
*/
AST_THREADSTORAGE(astman_append_buf);
AST_THREADSTORAGE(userevent_buf);
/*! \brief initial allocated size for the astman_append_buf and astman_send_*_va */
#define ASTMAN_APPEND_BUF_INITSIZE 256
/*!
* utility functions for creating AMI replies
*/
void astman_append(struct mansession *s, const char *fmt, ...)
{
int res;
va_list ap;
struct ast_str *buf;
if (!(buf = ast_str_thread_get(&astman_append_buf, ASTMAN_APPEND_BUF_INITSIZE))) {
return;
}
va_start(ap, fmt);
res = ast_str_set_va(&buf, 0, fmt, ap);
va_end(ap);
if (res == AST_DYNSTR_BUILD_FAILED) {
return;
}
if (s->hook || (s->tcptls_session != NULL && s->tcptls_session->stream != NULL)) {
send_string(s, ast_str_buffer(buf));
} else {
ast_verbose("No connection stream in astman_append, should not happen\n");
}
}
/*! \note NOTE: XXX this comment is unclear and possibly wrong.
Callers of astman_send_error(), astman_send_response() or astman_send_ack() must EITHER
hold the session lock _or_ be running in an action callback (in which case s->session->busy will
be non-zero). In either of these cases, there is no need to lock-protect the session's
fd, since no other output will be sent (events will be queued), and no input will
be read until either the current action finishes or get_input() obtains the session
lock.
*/
/*! \todo XXX MSG_MOREDATA should go to a header file. */
#define MSG_MOREDATA ((char *)astman_send_response)
/*! \brief send a response with an optional message,
* and terminate it with an empty line.
* m is used only to grab the 'ActionID' field.
*
* Use the explicit constant MSG_MOREDATA to remove the empty line.
* XXX MSG_MOREDATA should go to a header file.
*/
static void astman_send_response_full(struct mansession *s, const struct message *m, char *resp, char *msg, char *listflag)
{
const char *id = astman_get_header(m, "ActionID");
astman_append(s, "Response: %s\r\n", resp);
if (!ast_strlen_zero(id)) {
astman_append(s, "ActionID: %s\r\n", id);
}
if (listflag) {
astman_append(s, "EventList: %s\r\n", listflag); /* Start, complete, cancelled */
}
if (msg == MSG_MOREDATA) {
return;
} else if (msg) {
astman_append(s, "Message: %s\r\n\r\n", msg);
} else {
astman_append(s, "\r\n");
}
}
void astman_send_response(struct mansession *s, const struct message *m, char *resp, char *msg)
{
astman_send_response_full(s, m, resp, msg, NULL);
}
void astman_send_error(struct mansession *s, const struct message *m, char *error)
{
astman_send_response_full(s, m, "Error", error, NULL);
}
void astman_send_error_va(struct mansession *s, const struct message *m, const char *fmt, ...)
{
int res;
va_list ap;
struct ast_str *buf;
char *msg;
if (!(buf = ast_str_thread_get(&astman_append_buf, ASTMAN_APPEND_BUF_INITSIZE))) {
return;
}
va_start(ap, fmt);
res = ast_str_set_va(&buf, 0, fmt, ap);
va_end(ap);
if (res == AST_DYNSTR_BUILD_FAILED) {
return;
}
/* astman_append will use the same underlying buffer, so copy the message out
* before sending the response */
msg = ast_str_buffer(buf);
if (msg) {
msg = ast_strdupa(msg);
}
astman_send_response_full(s, m, "Error", msg, NULL);
}
void astman_send_ack(struct mansession *s, const struct message *m, char *msg)
{
astman_send_response_full(s, m, "Success", msg, NULL);
}
static void astman_start_ack(struct mansession *s, const struct message *m)
{
astman_send_response_full(s, m, "Success", MSG_MOREDATA, NULL);
}
void astman_send_listack(struct mansession *s, const struct message *m, char *msg, char *listflag)
{
astman_send_response_full(s, m, "Success", msg, listflag);
}
void astman_send_list_complete_start(struct mansession *s, const struct message *m, const char *event_name, int count)
{
const char *id = astman_get_header(m, "ActionID");
astman_append(s, "Event: %s\r\n", event_name);
if (!ast_strlen_zero(id)) {
astman_append(s, "ActionID: %s\r\n", id);
}
astman_append(s,
"EventList: Complete\r\n"
"ListItems: %d\r\n",
count);
}
void astman_send_list_complete_end(struct mansession *s)
{
astman_append(s, "\r\n");
}
/*! \brief Lock the 'mansession' structure. */
static void mansession_lock(struct mansession *s)
{
ast_mutex_lock(&s->lock);
}
/*! \brief Unlock the 'mansession' structure. */
static void mansession_unlock(struct mansession *s)
{
ast_mutex_unlock(&s->lock);
}
/*! \brief
Rather than braindead on,off this now can also accept a specific int mask value
or a ',' delim list of mask strings (the same as manager.conf) -anthm
*/
static int set_eventmask(struct mansession *s, const char *eventmask)
{
int maskint = strings_to_mask(eventmask);
ao2_lock(s->session);
if (maskint >= 0) {
s->session->send_events = maskint;
}
ao2_unlock(s->session);
return maskint;
}
static enum ast_transport mansession_get_transport(const struct mansession *s)
{
return s->tcptls_session->parent->tls_cfg ? AST_TRANSPORT_TLS :
AST_TRANSPORT_TCP;
}
static void report_invalid_user(const struct mansession *s, const char *username)
{
char session_id[32];
struct ast_security_event_inval_acct_id inval_acct_id = {
.common.event_type = AST_SECURITY_EVENT_INVAL_ACCT_ID,
.common.version = AST_SECURITY_EVENT_INVAL_ACCT_ID_VERSION,
.common.service = "AMI",
.common.account_id = username,
.common.session_tv = &s->session->sessionstart_tv,
.common.local_addr = {
.addr = &s->tcptls_session->parent->local_address,
.transport = mansession_get_transport(s),
},
.common.remote_addr = {
.addr = &s->session->addr,
.transport = mansession_get_transport(s),
},
.common.session_id = session_id,
};
snprintf(session_id, sizeof(session_id), "%p", s);
ast_security_event_report(AST_SEC_EVT(&inval_acct_id));
}
static void report_failed_acl(const struct mansession *s, const char *username)
{
char session_id[32];
struct ast_security_event_failed_acl failed_acl_event = {
.common.event_type = AST_SECURITY_EVENT_FAILED_ACL,
.common.version = AST_SECURITY_EVENT_FAILED_ACL_VERSION,
.common.service = "AMI",
.common.account_id = username,
.common.session_tv = &s->session->sessionstart_tv,
.common.local_addr = {
.addr = &s->tcptls_session->parent->local_address,
.transport = mansession_get_transport(s),
},
.common.remote_addr = {
.addr = &s->session->addr,
.transport = mansession_get_transport(s),
},
.common.session_id = session_id,
};
snprintf(session_id, sizeof(session_id), "%p", s->session);
ast_security_event_report(AST_SEC_EVT(&failed_acl_event));
}
static void report_inval_password(const struct mansession *s, const char *username)
{
char session_id[32];
struct ast_security_event_inval_password inval_password = {
.common.event_type = AST_SECURITY_EVENT_INVAL_PASSWORD,
.common.version = AST_SECURITY_EVENT_INVAL_PASSWORD_VERSION,
.common.service = "AMI",
.common.account_id = username,
.common.session_tv = &s->session->sessionstart_tv,
.common.local_addr = {
.addr = &s->tcptls_session->parent->local_address,
.transport = mansession_get_transport(s),
},
.common.remote_addr = {
.addr = &s->session->addr,
.transport = mansession_get_transport(s),
},
.common.session_id = session_id,
};
snprintf(session_id, sizeof(session_id), "%p", s->session);
ast_security_event_report(AST_SEC_EVT(&inval_password));
}
static void report_auth_success(const struct mansession *s)
{
char session_id[32];
struct ast_security_event_successful_auth successful_auth = {
.common.event_type = AST_SECURITY_EVENT_SUCCESSFUL_AUTH,
.common.version = AST_SECURITY_EVENT_SUCCESSFUL_AUTH_VERSION,
.common.service = "AMI",
.common.account_id = s->session->username,
.common.session_tv = &s->session->sessionstart_tv,
.common.local_addr = {
.addr = &s->tcptls_session->parent->local_address,
.transport = mansession_get_transport(s),
},
.common.remote_addr = {
.addr = &s->session->addr,
.transport = mansession_get_transport(s),
},
.common.session_id = session_id,
};
snprintf(session_id, sizeof(session_id), "%p", s->session);
ast_security_event_report(AST_SEC_EVT(&successful_auth));
}
static void report_req_not_allowed(const struct mansession *s, const char *action)
{
char session_id[32];
char request_type[64];
struct ast_security_event_req_not_allowed req_not_allowed = {
.common.event_type = AST_SECURITY_EVENT_REQ_NOT_ALLOWED,
.common.version = AST_SECURITY_EVENT_REQ_NOT_ALLOWED_VERSION,
.common.service = "AMI",
.common.account_id = s->session->username,
.common.session_tv = &s->session->sessionstart_tv,
.common.local_addr = {
.addr = &s->tcptls_session->parent->local_address,
.transport = mansession_get_transport(s),
},
.common.remote_addr = {
.addr = &s->session->addr,
.transport = mansession_get_transport(s),
},
.common.session_id = session_id,
.request_type = request_type,
};
snprintf(session_id, sizeof(session_id), "%p", s->session);
snprintf(request_type, sizeof(request_type), "Action: %s", action);
ast_security_event_report(AST_SEC_EVT(&req_not_allowed));
}
static void report_req_bad_format(const struct mansession *s, const char *action)
{
char session_id[32];
char request_type[64];
struct ast_security_event_req_bad_format req_bad_format = {
.common.event_type = AST_SECURITY_EVENT_REQ_BAD_FORMAT,
.common.version = AST_SECURITY_EVENT_REQ_BAD_FORMAT_VERSION,
.common.service = "AMI",
.common.account_id = s->session->username,
.common.session_tv = &s->session->sessionstart_tv,
.common.local_addr = {
.addr = &s->tcptls_session->parent->local_address,
.transport = mansession_get_transport(s),
},
.common.remote_addr = {
.addr = &s->session->addr,
.transport = mansession_get_transport(s),
},
.common.session_id = session_id,
.request_type = request_type,
};
snprintf(session_id, sizeof(session_id), "%p", s->session);
snprintf(request_type, sizeof(request_type), "Action: %s", action);
ast_security_event_report(AST_SEC_EVT(&req_bad_format));
}
static void report_failed_challenge_response(const struct mansession *s,
const char *response, const char *expected_response)
{
char session_id[32];
struct ast_security_event_chal_resp_failed chal_resp_failed = {
.common.event_type = AST_SECURITY_EVENT_CHAL_RESP_FAILED,
.common.version = AST_SECURITY_EVENT_CHAL_RESP_FAILED_VERSION,
.common.service = "AMI",
.common.account_id = s->session->username,
.common.session_tv = &s->session->sessionstart_tv,
.common.local_addr = {
.addr = &s->tcptls_session->parent->local_address,
.transport = mansession_get_transport(s),
},
.common.remote_addr = {
.addr = &s->session->addr,
.transport = mansession_get_transport(s),
},
.common.session_id = session_id,
.challenge = s->session->challenge,
.response = response,
.expected_response = expected_response,
};
snprintf(session_id, sizeof(session_id), "%p", s->session);
ast_security_event_report(AST_SEC_EVT(&chal_resp_failed));
}
static void report_session_limit(const struct mansession *s)
{
char session_id[32];
struct ast_security_event_session_limit session_limit = {
.common.event_type = AST_SECURITY_EVENT_SESSION_LIMIT,
.common.version = AST_SECURITY_EVENT_SESSION_LIMIT_VERSION,
.common.service = "AMI",
.common.account_id = s->session->username,
.common.session_tv = &s->session->sessionstart_tv,
.common.local_addr = {
.addr = &s->tcptls_session->parent->local_address,
.transport = mansession_get_transport(s),
},
.common.remote_addr = {
.addr = &s->session->addr,
.transport = mansession_get_transport(s),
},
.common.session_id = session_id,
};
snprintf(session_id, sizeof(session_id), "%p", s->session);
ast_security_event_report(AST_SEC_EVT(&session_limit));
}
/*
* Here we start with action_ handlers for AMI actions,
* and the internal functions used by them.
* Generally, the handlers are called action_foo()
*/
/* helper function for action_login() */
static int authenticate(struct mansession *s, const struct message *m)
{
const char *username = astman_get_header(m, "Username");
const char *password = astman_get_header(m, "Secret");
int error = -1;
struct ast_manager_user *user = NULL;
regex_t *regex_filter;
struct ao2_iterator filter_iter;
if (ast_strlen_zero(username)) { /* missing username */
return -1;
}
/* locate user in locked state */
AST_RWLIST_WRLOCK(&users);
if (!(user = get_manager_by_name_locked(username))) {
report_invalid_user(s, username);
ast_log(LOG_NOTICE, "%s tried to authenticate with nonexistent user '%s'\n", ast_sockaddr_stringify_addr(&s->session->addr), username);
} else if (user->acl && (ast_apply_acl(user->acl, &s->session->addr, "Manager User ACL: ") == AST_SENSE_DENY)) {
report_failed_acl(s, username);
ast_log(LOG_NOTICE, "%s failed to pass IP ACL as '%s'\n", ast_sockaddr_stringify_addr(&s->session->addr), username);
} else if (!strcasecmp(astman_get_header(m, "AuthType"), "MD5")) {
const char *key = astman_get_header(m, "Key");
if (!ast_strlen_zero(key) && !ast_strlen_zero(s->session->challenge) && user->secret) {
int x;
int len = 0;
char md5key[256] = "";
struct MD5Context md5;
unsigned char digest[16];
MD5Init(&md5);
MD5Update(&md5, (unsigned char *) s->session->challenge, strlen(s->session->challenge));
MD5Update(&md5, (unsigned char *) user->secret, strlen(user->secret));
MD5Final(digest, &md5);
for (x = 0; x < 16; x++)
len += sprintf(md5key + len, "%02hhx", digest[x]);
if (!strcmp(md5key, key)) {
error = 0;
} else {
report_failed_challenge_response(s, key, md5key);
}
} else {
ast_debug(1, "MD5 authentication is not possible. challenge: '%s'\n",
S_OR(s->session->challenge, ""));
}
} else if (user->secret) {
if (!strcmp(password, user->secret)) {
error = 0;
} else {
report_inval_password(s, username);
}
}
if (error) {
ast_log(LOG_NOTICE, "%s failed to authenticate as '%s'\n", ast_sockaddr_stringify_addr(&s->session->addr), username);
AST_RWLIST_UNLOCK(&users);
return -1;
}
/* auth complete */
/* All of the user parameters are copied to the session so that in the event
* of a reload and a configuration change, the session parameters are not
* changed. */
ast_copy_string(s->session->username, username, sizeof(s->session->username));
s->session->readperm = user->readperm;
s->session->writeperm = user->writeperm;
s->session->writetimeout = user->writetimeout;
if (user->chanvars) {
s->session->chanvars = ast_variables_dup(user->chanvars);
}
filter_iter = ao2_iterator_init(user->whitefilters, 0);
while ((regex_filter = ao2_iterator_next(&filter_iter))) {
ao2_t_link(s->session->whitefilters, regex_filter, "add white user filter to session");
ao2_t_ref(regex_filter, -1, "remove iterator ref");
}
ao2_iterator_destroy(&filter_iter);
filter_iter = ao2_iterator_init(user->blackfilters, 0);
while ((regex_filter = ao2_iterator_next(&filter_iter))) {
ao2_t_link(s->session->blackfilters, regex_filter, "add black user filter to session");
ao2_t_ref(regex_filter, -1, "remove iterator ref");
}
ao2_iterator_destroy(&filter_iter);
s->session->sessionstart = time(NULL);
s->session->sessionstart_tv = ast_tvnow();
set_eventmask(s, astman_get_header(m, "Events"));
report_auth_success(s);
AST_RWLIST_UNLOCK(&users);
return 0;
}
static int action_ping(struct mansession *s, const struct message *m)
{
const char *actionid = astman_get_header(m, "ActionID");
struct timeval now = ast_tvnow();
astman_append(s, "Response: Success\r\n");
if (!ast_strlen_zero(actionid)){
astman_append(s, "ActionID: %s\r\n", actionid);
}
astman_append(
s,
"Ping: Pong\r\n"
"Timestamp: %ld.%06lu\r\n"
"\r\n",
(long) now.tv_sec, (unsigned long) now.tv_usec);
return 0;
}
static int action_getconfig(struct mansession *s, const struct message *m)
{
struct ast_config *cfg;
const char *fn = astman_get_header(m, "Filename");
const char *category = astman_get_header(m, "Category");
const char *filter = astman_get_header(m, "Filter");
const char *category_name;
int catcount = 0;
int lineno = 0;
struct ast_category *cur_category = NULL;
struct ast_variable *v;
struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
if (ast_strlen_zero(fn)) {
astman_send_error(s, m, "Filename not specified");
return 0;
}
cfg = ast_config_load2(fn, "manager", config_flags);
if (cfg == CONFIG_STATUS_FILEMISSING) {
astman_send_error(s, m, "Config file not found");
return 0;
} else if (cfg == CONFIG_STATUS_FILEINVALID) {
astman_send_error(s, m, "Config file has invalid format");
return 0;
}
astman_start_ack(s, m);
while ((cur_category = ast_category_browse_filtered(cfg, category, cur_category, filter))) {
struct ast_str *templates;
category_name = ast_category_get_name(cur_category);
lineno = 0;
astman_append(s, "Category-%06d: %s\r\n", catcount, category_name);
if (ast_category_is_template(cur_category)) {
astman_append(s, "IsTemplate-%06d: %d\r\n", catcount, 1);
}
if ((templates = ast_category_get_templates(cur_category))
&& ast_str_strlen(templates) > 0) {
astman_append(s, "Templates-%06d: %s\r\n", catcount, ast_str_buffer(templates));
ast_free(templates);
}
for (v = ast_category_first(cur_category); v; v = v->next) {
astman_append(s, "Line-%06d-%06d: %s=%s\r\n", catcount, lineno++, v->name, v->value);
}
catcount++;
}
if (!ast_strlen_zero(category) && catcount == 0) { /* TODO: actually, a config with no categories doesn't even get loaded */
astman_append(s, "No categories found\r\n");
}
ast_config_destroy(cfg);
astman_append(s, "\r\n");
return 0;
}
static int action_listcategories(struct mansession *s, const struct message *m)
{
struct ast_config *cfg;
const char *fn = astman_get_header(m, "Filename");
const char *match = astman_get_header(m, "Match");
struct ast_category *category = NULL;
struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
int catcount = 0;
if (ast_strlen_zero(fn)) {
astman_send_error(s, m, "Filename not specified");
return 0;
}
if (!(cfg = ast_config_load2(fn, "manager", config_flags))) {
astman_send_error(s, m, "Config file not found");
return 0;
} else if (cfg == CONFIG_STATUS_FILEINVALID) {
astman_send_error(s, m, "Config file has invalid format");
return 0;
}
astman_start_ack(s, m);
while ((category = ast_category_browse_filtered(cfg, NULL, category, match))) {
astman_append(s, "Category-%06d: %s\r\n", catcount, ast_category_get_name(category));
catcount++;
}
if (catcount == 0) { /* TODO: actually, a config with no categories doesn't even get loaded */
astman_append(s, "Error: no categories found\r\n");
}
ast_config_destroy(cfg);
astman_append(s, "\r\n");
return 0;
}
/*! The amount of space in out must be at least ( 2 * strlen(in) + 1 ) */
static void json_escape(char *out, const char *in)
{
for (; *in; in++) {
if (*in == '\\' || *in == '\"') {
*out++ = '\\';
}
*out++ = *in;
}
*out = '\0';
}
/*!
* \internal
* \brief Append a JSON escaped string to the manager stream.
*
* \param s AMI stream to append a string.
* \param str String to append to the stream after JSON escaping it.
*
* \return Nothing
*/
static void astman_append_json(struct mansession *s, const char *str)
{
char *buf;
buf = ast_alloca(2 * strlen(str) + 1);
json_escape(buf, str);
astman_append(s, "%s", buf);
}
static int action_getconfigjson(struct mansession *s, const struct message *m)
{
struct ast_config *cfg;
const char *fn = astman_get_header(m, "Filename");
const char *filter = astman_get_header(m, "Filter");
const char *category = astman_get_header(m, "Category");
struct ast_category *cur_category = NULL;
const char *category_name;
struct ast_variable *v;
int comma1 = 0;
struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
if (ast_strlen_zero(fn)) {
astman_send_error(s, m, "Filename not specified");
return 0;
}
if (!(cfg = ast_config_load2(fn, "manager", config_flags))) {
astman_send_error(s, m, "Config file not found");
return 0;
} else if (cfg == CONFIG_STATUS_FILEINVALID) {
astman_send_error(s, m, "Config file has invalid format");
return 0;
}
astman_start_ack(s, m);
astman_append(s, "JSON: {");
while ((cur_category = ast_category_browse_filtered(cfg, category, cur_category, filter))) {
int comma2 = 0;
struct ast_str *templates;
category_name = ast_category_get_name(cur_category);
astman_append(s, "%s\"", comma1 ? "," : "");
astman_append_json(s, category_name);
astman_append(s, "\":{");
comma1 = 1;
if (ast_category_is_template(cur_category)) {
astman_append(s, "\"istemplate\":1");
comma2 = 1;
}
if ((templates = ast_category_get_templates(cur_category))
&& ast_str_strlen(templates) > 0) {
astman_append(s, "%s", comma2 ? "," : "");
astman_append(s, "\"templates\":\"%s\"", ast_str_buffer(templates));
ast_free(templates);
comma2 = 1;
}
for (v = ast_category_first(cur_category); v; v = v->next) {
astman_append(s, "%s\"", comma2 ? "," : "");
astman_append_json(s, v->name);
astman_append(s, "\":\"");
astman_append_json(s, v->value);
astman_append(s, "\"");
comma2 = 1;
}
astman_append(s, "}");
}
astman_append(s, "}\r\n\r\n");
ast_config_destroy(cfg);
return 0;
}
/*! \brief helper function for action_updateconfig */
static enum error_type handle_updates(struct mansession *s, const struct message *m, struct ast_config *cfg, const char *dfn)
{
int x;
char hdr[40];
const char *action, *cat, *var, *value, *match, *line, *options;
struct ast_variable *v;
struct ast_str *str1 = ast_str_create(16), *str2 = ast_str_create(16);
enum error_type result = 0;
for (x = 0; x < 100000; x++) { /* 100000 = the max number of allowed updates + 1 */
unsigned int object = 0;
char *dupoptions;
int allowdups = 0;
int istemplate = 0;
int ignoreerror = 0;
char *inherit = NULL;
char *catfilter = NULL;
char *token;
int foundvar = 0;
int foundcat = 0;
struct ast_category *category = NULL;
snprintf(hdr, sizeof(hdr), "Action-%06d", x);
action = astman_get_header(m, hdr);
if (ast_strlen_zero(action)) /* breaks the for loop if no action header */
break; /* this could cause problems if actions come in misnumbered */
snprintf(hdr, sizeof(hdr), "Cat-%06d", x);
cat = astman_get_header(m, hdr);
if (ast_strlen_zero(cat)) { /* every action needs a category */
result = UNSPECIFIED_CATEGORY;
break;
}
snprintf(hdr, sizeof(hdr), "Var-%06d", x);
var = astman_get_header(m, hdr);
snprintf(hdr, sizeof(hdr), "Value-%06d", x);
value = astman_get_header(m, hdr);
if (!ast_strlen_zero(value) && *value == '>') {
object = 1;
value++;
}
snprintf(hdr, sizeof(hdr), "Match-%06d", x);
match = astman_get_header(m, hdr);
snprintf(hdr, sizeof(hdr), "Line-%06d", x);
line = astman_get_header(m, hdr);
snprintf(hdr, sizeof(hdr), "Options-%06d", x);
options = astman_get_header(m, hdr);
if (!ast_strlen_zero(options)) {
dupoptions = ast_strdupa(options);
while ((token = ast_strsep(&dupoptions, ',', AST_STRSEP_STRIP))) {
if (!strcasecmp("allowdups", token)) {
allowdups = 1;
continue;
}
if (!strcasecmp("template", token)) {
istemplate = 1;
continue;
}
if (!strcasecmp("ignoreerror", token)) {
ignoreerror = 1;
continue;
}
if (ast_begins_with(token, "inherit")) {
char *c = ast_strsep(&token, '=', AST_STRSEP_STRIP);
c = ast_strsep(&token, '=', AST_STRSEP_STRIP);
if (c) {
inherit = ast_strdupa(c);
}
continue;
}
if (ast_begins_with(token, "catfilter")) {
char *c = ast_strsep(&token, '=', AST_STRSEP_STRIP);
c = ast_strsep(&token, '=', AST_STRSEP_STRIP);
if (c) {
catfilter = ast_strdupa(c);
}
continue;
}
}
}
if (!strcasecmp(action, "newcat")) {
struct ast_category *template;
char *tmpl_name = NULL;
if (!allowdups) {
if (ast_category_get(cfg, cat, "TEMPLATES=include")) {
if (ignoreerror) {
continue;
} else {
result = FAILURE_NEWCAT; /* already exist */
break;
}
}
}
if (istemplate) {
category = ast_category_new_template(cat, dfn, -1);
} else {
category = ast_category_new(cat, dfn, -1);
}
if (!category) {
result = FAILURE_ALLOCATION;
break;
}
if (inherit) {
while ((tmpl_name = ast_strsep(&inherit, ',', AST_STRSEP_STRIP))) {
if ((template = ast_category_get(cfg, tmpl_name, "TEMPLATES=restrict"))) {
if (ast_category_inherit(category, template)) {
result = FAILURE_ALLOCATION;
break;
}
} else {
ast_category_destroy(category);
category = NULL;
result = FAILURE_TEMPLATE; /* template not found */
break;
}
}
}
if (category != NULL) {
if (ast_strlen_zero(match)) {
ast_category_append(cfg, category);
} else {
if (ast_category_insert(cfg, category, match)) {
ast_category_destroy(category);
result = FAILURE_NEWCAT;
break;
}
}
}
} else if (!strcasecmp(action, "renamecat")) {
if (ast_strlen_zero(value)) {
result = UNSPECIFIED_ARGUMENT;
break;
}
foundcat = 0;
while ((category = ast_category_browse_filtered(cfg, cat, category, catfilter))) {
ast_category_rename(category, value);
foundcat = 1;
}
if (!foundcat) {
result = UNKNOWN_CATEGORY;
break;
}
} else if (!strcasecmp(action, "delcat")) {
foundcat = 0;
while ((category = ast_category_browse_filtered(cfg, cat, category, catfilter))) {
category = ast_category_delete(cfg, category);
foundcat = 1;
}
if (!foundcat && !ignoreerror) {
result = UNKNOWN_CATEGORY;
break;
}
} else if (!strcasecmp(action, "emptycat")) {
foundcat = 0;
while ((category = ast_category_browse_filtered(cfg, cat, category, catfilter))) {
ast_category_empty(category);
foundcat = 1;
}
if (!foundcat) {
result = UNKNOWN_CATEGORY;
break;
}
} else if (!strcasecmp(action, "update")) {
if (ast_strlen_zero(var)) {
result = UNSPECIFIED_ARGUMENT;
break;
}
foundcat = 0;
foundvar = 0;
while ((category = ast_category_browse_filtered(cfg, cat, category, catfilter))) {
if (!ast_variable_update(category, var, value, match, object)) {
foundvar = 1;
}
foundcat = 1;
}
if (!foundcat) {
result = UNKNOWN_CATEGORY;
break;
}
if (!foundvar) {
result = FAILURE_UPDATE;
break;
}
} else if (!strcasecmp(action, "delete")) {
if ((ast_strlen_zero(var) && ast_strlen_zero(line))) {
result = UNSPECIFIED_ARGUMENT;
break;
}
foundcat = 0;
foundvar = 0;
while ((category = ast_category_browse_filtered(cfg, cat, category, catfilter))) {
if (!ast_variable_delete(category, var, match, line)) {
foundvar = 1;
}
foundcat = 1;
}
if (!foundcat) {
result = UNKNOWN_CATEGORY;
break;
}
if (!foundvar && !ignoreerror) {
result = FAILURE_UPDATE;
break;
}
} else if (!strcasecmp(action, "append")) {
if (ast_strlen_zero(var)) {
result = UNSPECIFIED_ARGUMENT;
break;
}
foundcat = 0;
while ((category = ast_category_browse_filtered(cfg, cat, category, catfilter))) {
if (!(v = ast_variable_new(var, value, dfn))) {
result = FAILURE_ALLOCATION;
break;
}
if (object || (match && !strcasecmp(match, "object"))) {
v->object = 1;
}
ast_variable_append(category, v);
foundcat = 1;
}
if (!foundcat) {
result = UNKNOWN_CATEGORY;
break;
}
} else if (!strcasecmp(action, "insert")) {
if (ast_strlen_zero(var) || ast_strlen_zero(line)) {
result = UNSPECIFIED_ARGUMENT;
break;
}
foundcat = 0;
while ((category = ast_category_browse_filtered(cfg, cat, category, catfilter))) {
if (!(v = ast_variable_new(var, value, dfn))) {
result = FAILURE_ALLOCATION;
break;
}
ast_variable_insert(category, v, line);
foundcat = 1;
}
if (!foundcat) {
result = UNKNOWN_CATEGORY;
break;
}
}
else {
ast_log(LOG_WARNING, "Action-%06d: %s not handled\n", x, action);
result = UNKNOWN_ACTION;
break;
}
}
ast_free(str1);
ast_free(str2);
return result;
}
static int action_updateconfig(struct mansession *s, const struct message *m)
{
struct ast_config *cfg;
const char *sfn = astman_get_header(m, "SrcFilename");
const char *dfn = astman_get_header(m, "DstFilename");
int res;
const char *rld = astman_get_header(m, "Reload");
int preserve_effective_context = CONFIG_SAVE_FLAG_PRESERVE_EFFECTIVE_CONTEXT;
const char *preserve_effective_context_string = astman_get_header(m, "PreserveEffectiveContext");
struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
enum error_type result;
if (ast_strlen_zero(sfn) || ast_strlen_zero(dfn)) {
astman_send_error(s, m, "Filename not specified");
return 0;
}
if (!(cfg = ast_config_load2(sfn, "manager", config_flags))) {
astman_send_error(s, m, "Config file not found");
return 0;
} else if (cfg == CONFIG_STATUS_FILEINVALID) {
astman_send_error(s, m, "Config file has invalid format");
return 0;
}
result = handle_updates(s, m, cfg, dfn);
if (!result) {
ast_include_rename(cfg, sfn, dfn); /* change the include references from dfn to sfn, so things match up */
if (!ast_strlen_zero(preserve_effective_context_string) && !ast_true(preserve_effective_context_string)) {
preserve_effective_context = CONFIG_SAVE_FLAG_NONE;
}
res = ast_config_text_file_save2(dfn, cfg, "Manager", preserve_effective_context);
ast_config_destroy(cfg);
if (res) {
astman_send_error(s, m, "Save of config failed");
return 0;
}
astman_send_ack(s, m, NULL);
if (!ast_strlen_zero(rld)) {
if (ast_true(rld)) {
rld = NULL;
}
ast_module_reload(rld);
}
} else {
ast_config_destroy(cfg);
switch(result) {
case UNKNOWN_ACTION:
astman_send_error(s, m, "Unknown action command");
break;
case UNKNOWN_CATEGORY:
astman_send_error(s, m, "Given category does not exist");
break;
case UNSPECIFIED_CATEGORY:
astman_send_error(s, m, "Category not specified");
break;
case UNSPECIFIED_ARGUMENT:
astman_send_error(s, m, "Problem with category, value, or line (if required)");
break;
case FAILURE_ALLOCATION:
astman_send_error(s, m, "Memory allocation failure, this should not happen");
break;
case FAILURE_NEWCAT:
astman_send_error(s, m, "Create category did not complete successfully");
break;
case FAILURE_DELCAT:
astman_send_error(s, m, "Delete category did not complete successfully");
break;
case FAILURE_EMPTYCAT:
astman_send_error(s, m, "Empty category did not complete successfully");
break;
case FAILURE_UPDATE:
astman_send_error(s, m, "Update did not complete successfully");
break;
case FAILURE_DELETE:
astman_send_error(s, m, "Delete did not complete successfully");
break;
case FAILURE_APPEND:
astman_send_error(s, m, "Append did not complete successfully");
break;
case FAILURE_TEMPLATE:
astman_send_error(s, m, "Template category not found");
break;
}
}
return 0;
}
static int action_createconfig(struct mansession *s, const struct message *m)
{
int fd;
const char *fn = astman_get_header(m, "Filename");
struct ast_str *filepath = ast_str_alloca(PATH_MAX);
ast_str_set(&filepath, 0, "%s/", ast_config_AST_CONFIG_DIR);
ast_str_append(&filepath, 0, "%s", fn);
if ((fd = open(ast_str_buffer(filepath), O_CREAT | O_EXCL, AST_FILE_MODE)) != -1) {
close(fd);
astman_send_ack(s, m, "New configuration file created successfully");
} else {
astman_send_error(s, m, strerror(errno));
}
return 0;
}
static int action_waitevent(struct mansession *s, const struct message *m)
{
const char *timeouts = astman_get_header(m, "Timeout");
int timeout = -1;
int x;
int needexit = 0;
const char *id = astman_get_header(m, "ActionID");
char idText[256];
if (!ast_strlen_zero(id)) {
snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
} else {
idText[0] = '\0';
}
if (!ast_strlen_zero(timeouts)) {
sscanf(timeouts, "%30i", &timeout);
if (timeout < -1) {
timeout = -1;
}
/* XXX maybe put an upper bound, or prevent the use of 0 ? */
}
ao2_lock(s->session);
if (s->session->waiting_thread != AST_PTHREADT_NULL) {
pthread_kill(s->session->waiting_thread, SIGURG);
}
if (s->session->managerid) { /* AMI-over-HTTP session */
/*
* Make sure the timeout is within the expire time of the session,
* as the client will likely abort the request if it does not see
* data coming after some amount of time.
*/
time_t now = time(NULL);
int max = s->session->sessiontimeout - now - 10;
if (max < 0) { /* We are already late. Strange but possible. */
max = 0;
}
if (timeout < 0 || timeout > max) {
timeout = max;
}
if (!s->session->send_events) { /* make sure we record events */
s->session->send_events = -1;
}
}
ao2_unlock(s->session);
/* XXX should this go inside the lock ? */
s->session->waiting_thread = pthread_self(); /* let new events wake up this thread */
ast_debug(1, "Starting waiting for an event!\n");
for (x = 0; x < timeout || timeout < 0; x++) {
ao2_lock(s->session);
if (AST_RWLIST_NEXT(s->session->last_ev, eq_next)) {
needexit = 1;
}
/* We can have multiple HTTP session point to the same mansession entry.
* The way we deal with it is not very nice: newcomers kick out the previous
* HTTP session. XXX this needs to be improved.
*/
if (s->session->waiting_thread != pthread_self()) {
needexit = 1;
}
if (s->session->needdestroy) {
needexit = 1;
}
ao2_unlock(s->session);
if (needexit) {
break;
}
if (s->session->managerid == 0) { /* AMI session */
if (ast_wait_for_input(ast_iostream_get_fd(s->session->stream), 1000)) {
break;
}
} else { /* HTTP session */
sleep(1);
}
}
ast_debug(1, "Finished waiting for an event!\n");
ao2_lock(s->session);
if (s->session->waiting_thread == pthread_self()) {
struct eventqent *eqe = s->session->last_ev;
astman_send_response(s, m, "Success", "Waiting for Event completed.");
while ((eqe = advance_event(eqe))) {
if (((s->session->readperm & eqe->category) == eqe->category)
&& ((s->session->send_events & eqe->category) == eqe->category)
&& match_filter(s, eqe->eventdata)) {
astman_append(s, "%s", eqe->eventdata);
}
s->session->last_ev = eqe;
}
astman_append(s,
"Event: WaitEventComplete\r\n"
"%s"
"\r\n", idText);
s->session->waiting_thread = AST_PTHREADT_NULL;
} else {
ast_debug(1, "Abandoning event request!\n");
}
ao2_unlock(s->session);
return 0;
}
static int action_listcommands(struct mansession *s, const struct message *m)
{
struct manager_action *cur;
struct ast_str *temp = ast_str_alloca(MAX_AUTH_PERM_STRING);
astman_start_ack(s, m);
AST_RWLIST_RDLOCK(&actions);
AST_RWLIST_TRAVERSE(&actions, cur, list) {
if ((s->session->writeperm & cur->authority) || cur->authority == 0) {
astman_append(s, "%s: %s (Priv: %s)\r\n",
cur->action, cur->synopsis, authority_to_str(cur->authority, &temp));
}
}
AST_RWLIST_UNLOCK(&actions);
astman_append(s, "\r\n");
return 0;
}
static int action_events(struct mansession *s, const struct message *m)
{
const char *mask =