2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2006, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
21 * \brief The Asterisk Management Interface - AMI
23 * \author Mark Spencer <markster@digium.com>
25 * OpenSSL http://www.openssl.org - for AMI/SSL
27 * At the moment this file contains a number of functions, namely:
29 * - data structures storing AMI state
30 * - AMI-related API functions, used by internal asterisk components
31 * - handlers for AMI-related CLI functions
32 * - handlers for AMI functions (available through the AMI socket)
33 * - the code for the main AMI listener thread and individual session threads
34 * - the http handlers invoked for AMI-over-HTTP by the threads in main/http.c
39 /*! \li \ref manager.c uses the configuration file \ref manager.conf and \ref users.conf
40 * \addtogroup configuration_file
43 /*! \page manager.conf manager.conf
44 * \verbinclude manager.conf.sample
47 /*! \page users.conf users.conf
48 * \verbinclude users.conf.sample
52 <support_level>core</support_level>
57 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
59 #include "asterisk/_private.h"
60 #include "asterisk/paths.h" /* use various ast_config_AST_* */
65 #include <sys/types.h>
68 #include "asterisk/channel.h"
69 #include "asterisk/file.h"
70 #include "asterisk/manager.h"
71 #include "asterisk/module.h"
72 #include "asterisk/config.h"
73 #include "asterisk/callerid.h"
74 #include "asterisk/lock.h"
75 #include "asterisk/cli.h"
76 #include "asterisk/app.h"
77 #include "asterisk/pbx.h"
78 #include "asterisk/md5.h"
79 #include "asterisk/acl.h"
80 #include "asterisk/utils.h"
81 #include "asterisk/tcptls.h"
82 #include "asterisk/http.h"
83 #include "asterisk/ast_version.h"
84 #include "asterisk/threadstorage.h"
85 #include "asterisk/linkedlists.h"
86 #include "asterisk/term.h"
87 #include "asterisk/astobj2.h"
88 #include "asterisk/features.h"
89 #include "asterisk/security_events.h"
90 #include "asterisk/aoc.h"
91 #include "asterisk/strings.h"
92 #include "asterisk/stringfields.h"
93 #include "asterisk/presencestate.h"
94 #include "asterisk/stasis_message_router.h"
95 #include "asterisk/stasis_channels.h"
96 #include "asterisk/stasis_bridges.h"
97 #include "asterisk/test.h"
98 #include "asterisk/json.h"
99 #include "asterisk/bridge.h"
100 #include "asterisk/features_config.h"
101 #include "asterisk/rtp_engine.h"
104 <manager name="Ping" language="en_US">
109 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
112 <para>A 'Ping' action will ellicit a 'Pong' response. Used to keep the
113 manager connection open.</para>
116 <manager name="Events" language="en_US">
121 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
122 <parameter name="EventMask" required="true">
125 <para>If all events should be sent.</para>
128 <para>If no events should be sent.</para>
130 <enum name="system,call,log,...">
131 <para>To select which flags events should have to be sent.</para>
137 <para>Enable/Disable sending of events to this manager client.</para>
140 <manager name="Logoff" language="en_US">
145 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
148 <para>Logoff the current manager session.</para>
151 <manager name="Login" language="en_US">
156 <parameter name="ActionID">
157 <para>ActionID for this transaction. Will be returned.</para>
159 <parameter name="Username" required="true">
160 <para>Username to login with as specified in manager.conf.</para>
162 <parameter name="Secret">
163 <para>Secret to login with as specified in manager.conf.</para>
167 <para>Login Manager.</para>
170 <manager name="Challenge" language="en_US">
172 Generate Challenge for MD5 Auth.
175 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
176 <parameter name="AuthType" required="true">
177 <para>Digest algorithm to use in the challenge. Valid values are:</para>
184 <para>Generate a challenge for MD5 authentication.</para>
187 <manager name="Hangup" language="en_US">
192 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
193 <parameter name="Channel" required="true">
194 <para>The exact channel name to be hungup, or to use a regular expression, set this parameter to: /regex/</para>
195 <para>Example exact channel: SIP/provider-0000012a</para>
196 <para>Example regular expression: /^SIP/provider-.*$/</para>
198 <parameter name="Cause">
199 <para>Numeric hangup cause.</para>
203 <para>Hangup a channel.</para>
206 <manager name="Status" language="en_US">
211 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
212 <parameter name="Channel" required="true">
213 <para>The name of the channel to query for status.</para>
215 <parameter name="Variables">
216 <para>Comma <literal>,</literal> separated list of variable to include.</para>
220 <para>Will return the status information of each channel along with the
221 value for the specified channel variables.</para>
224 <managerEvent language="en_US" name="Status">
225 <managerEventInstance class="EVENT_FLAG_CALL">
226 <synopsis>Raised in response to a Status command.</synopsis>
228 <parameter name="ActionID" required="false"/>
230 <parameter name="Type">
231 <para>Type of channel</para>
233 <parameter name="DNID">
234 <para>Dialed number identifier</para>
236 <parameter name="TimeToHangup">
237 <para>Absolute lifetime of the channel</para>
239 <parameter name="BridgeID">
240 <para>Identifier of the bridge the channel is in, may be empty if not in one</para>
242 <parameter name="Linkedid">
244 <parameter name="Application">
245 <para>Application currently executing on the channel</para>
247 <parameter name="Data">
248 <para>Data given to the currently executing channel</para>
250 <parameter name="Nativeformats">
251 <para>Media formats the connected party is willing to send or receive</para>
253 <parameter name="Readformat">
254 <para>Media formats that frames from the channel are received in</para>
256 <parameter name="Readtrans">
257 <para>Translation path for media received in native formats</para>
259 <parameter name="Writeformat">
260 <para>Media formats that frames to the channel are accepted in</para>
262 <parameter name="Writetrans">
263 <para>Translation path for media sent to the connected party</para>
265 <parameter name="Callgroup">
266 <para>Configured call group on the channel</para>
268 <parameter name="Pickupgroup">
269 <para>Configured pickup group on the channel</para>
271 <parameter name="Seconds">
272 <para>Number of seconds the channel has been active</para>
276 <ref type="manager">Status</ref>
278 </managerEventInstance>
280 <manager name="Setvar" language="en_US">
282 Set a channel variable.
285 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
286 <parameter name="Channel">
287 <para>Channel to set variable for.</para>
289 <parameter name="Variable" required="true">
290 <para>Variable name.</para>
292 <parameter name="Value" required="true">
293 <para>Variable value.</para>
297 <para>Set a global or local channel variable.</para>
299 <para>If a channel name is not provided then the variable is global.</para>
303 <manager name="Getvar" language="en_US">
305 Gets a channel variable.
308 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
309 <parameter name="Channel">
310 <para>Channel to read variable from.</para>
312 <parameter name="Variable" required="true">
313 <para>Variable name.</para>
317 <para>Get the value of a global or local channel variable.</para>
319 <para>If a channel name is not provided then the variable is global.</para>
323 <manager name="GetConfig" language="en_US">
325 Retrieve configuration.
328 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
329 <parameter name="Filename" required="true">
330 <para>Configuration filename (e.g. <filename>foo.conf</filename>).</para>
332 <parameter name="Category">
333 <para>Category in configuration file.</para>
337 <para>This action will dump the contents of a configuration
338 file by category and contents or optionally by specified category only.</para>
341 <manager name="GetConfigJSON" language="en_US">
343 Retrieve configuration (JSON format).
346 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
347 <parameter name="Filename" required="true">
348 <para>Configuration filename (e.g. <filename>foo.conf</filename>).</para>
352 <para>This action will dump the contents of a configuration file by category
353 and contents in JSON format. This only makes sense to be used using rawman over
354 the HTTP interface.</para>
357 <manager name="UpdateConfig" language="en_US">
359 Update basic configuration.
362 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
363 <parameter name="SrcFilename" required="true">
364 <para>Configuration filename to read (e.g. <filename>foo.conf</filename>).</para>
366 <parameter name="DstFilename" required="true">
367 <para>Configuration filename to write (e.g. <filename>foo.conf</filename>)</para>
369 <parameter name="Reload">
370 <para>Whether or not a reload should take place (or name of specific module).</para>
372 <parameter name="Action-XXXXXX">
373 <para>Action to take.</para>
374 <para>X's represent 6 digit number beginning with 000000.</para>
376 <enum name="NewCat" />
377 <enum name="RenameCat" />
378 <enum name="DelCat" />
379 <enum name="EmptyCat" />
380 <enum name="Update" />
381 <enum name="Delete" />
382 <enum name="Append" />
383 <enum name="Insert" />
386 <parameter name="Cat-XXXXXX">
387 <para>Category to operate on.</para>
388 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-XXXXXX']/para[2])" />
390 <parameter name="Var-XXXXXX">
391 <para>Variable to work on.</para>
392 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-XXXXXX']/para[2])" />
394 <parameter name="Value-XXXXXX">
395 <para>Value to work on.</para>
396 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-XXXXXX']/para[2])" />
398 <parameter name="Match-XXXXXX">
399 <para>Extra match required to match line.</para>
400 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-XXXXXX']/para[2])" />
402 <parameter name="Line-XXXXXX">
403 <para>Line in category to operate on (used with delete and insert actions).</para>
404 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-XXXXXX']/para[2])" />
408 <para>This action will modify, create, or delete configuration elements
409 in Asterisk configuration files.</para>
412 <manager name="CreateConfig" language="en_US">
414 Creates an empty file in the configuration directory.
417 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
418 <parameter name="Filename" required="true">
419 <para>The configuration filename to create (e.g. <filename>foo.conf</filename>).</para>
423 <para>This action will create an empty file in the configuration
424 directory. This action is intended to be used before an UpdateConfig
428 <manager name="ListCategories" language="en_US">
430 List categories in configuration file.
433 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
434 <parameter name="Filename" required="true">
435 <para>Configuration filename (e.g. <filename>foo.conf</filename>).</para>
439 <para>This action will dump the categories in a given file.</para>
442 <manager name="Redirect" language="en_US">
444 Redirect (transfer) a call.
447 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
448 <parameter name="Channel" required="true">
449 <para>Channel to redirect.</para>
451 <parameter name="ExtraChannel">
452 <para>Second call leg to transfer (optional).</para>
454 <parameter name="Exten" required="true">
455 <para>Extension to transfer to.</para>
457 <parameter name="ExtraExten">
458 <para>Extension to transfer extrachannel to (optional).</para>
460 <parameter name="Context" required="true">
461 <para>Context to transfer to.</para>
463 <parameter name="ExtraContext">
464 <para>Context to transfer extrachannel to (optional).</para>
466 <parameter name="Priority" required="true">
467 <para>Priority to transfer to.</para>
469 <parameter name="ExtraPriority">
470 <para>Priority to transfer extrachannel to (optional).</para>
474 <para>Redirect (transfer) a call.</para>
477 <manager name="Atxfer" language="en_US">
482 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
483 <parameter name="Channel" required="true">
484 <para>Transferer's channel.</para>
486 <parameter name="Exten" required="true">
487 <para>Extension to transfer to.</para>
489 <parameter name="Context">
490 <para>Context to transfer to.</para>
494 <para>Attended transfer.</para>
497 <manager name="Originate" language="en_US">
502 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
503 <parameter name="Channel" required="true">
504 <para>Channel name to call.</para>
506 <parameter name="Exten">
507 <para>Extension to use (requires <literal>Context</literal> and
508 <literal>Priority</literal>)</para>
510 <parameter name="Context">
511 <para>Context to use (requires <literal>Exten</literal> and
512 <literal>Priority</literal>)</para>
514 <parameter name="Priority">
515 <para>Priority to use (requires <literal>Exten</literal> and
516 <literal>Context</literal>)</para>
518 <parameter name="Application">
519 <para>Application to execute.</para>
521 <parameter name="Data">
522 <para>Data to use (requires <literal>Application</literal>).</para>
524 <parameter name="Timeout" default="30000">
525 <para>How long to wait for call to be answered (in ms.).</para>
527 <parameter name="CallerID">
528 <para>Caller ID to be set on the outgoing channel.</para>
530 <parameter name="Variable">
531 <para>Channel variable to set, multiple Variable: headers are allowed.</para>
533 <parameter name="Account">
534 <para>Account code.</para>
536 <parameter name="EarlyMedia">
537 <para>Set to <literal>true</literal> to force call bridge on early media..</para>
539 <parameter name="Async">
540 <para>Set to <literal>true</literal> for fast origination.</para>
542 <parameter name="Codecs">
543 <para>Comma-separated list of codecs to use for this call.</para>
547 <para>Generates an outgoing call to a
548 <replaceable>Extension</replaceable>/<replaceable>Context</replaceable>/<replaceable>Priority</replaceable>
549 or <replaceable>Application</replaceable>/<replaceable>Data</replaceable></para>
552 <ref type="managerEvent">OriginateResponse</ref>
555 <managerEvent language="en_US" name="OriginateResponse">
556 <managerEventInstance class="EVENT_FLAG_CALL">
557 <synopsis>Raised in response to an Originate command.</synopsis>
559 <parameter name="ActionID" required="false"/>
560 <parameter name="Resonse">
562 <enum name="Failure"/>
563 <enum name="Success"/>
566 <parameter name="Channel"/>
567 <parameter name="Context"/>
568 <parameter name="Exten"/>
569 <parameter name="Reason"/>
570 <parameter name="Uniqueid"/>
571 <parameter name="CallerIDNum"/>
572 <parameter name="CallerIDName"/>
575 <ref type="manager">Originate</ref>
577 </managerEventInstance>
579 <manager name="Command" language="en_US">
581 Execute Asterisk CLI Command.
584 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
585 <parameter name="Command" required="true">
586 <para>Asterisk CLI command to run.</para>
590 <para>Run a CLI command.</para>
593 <manager name="ExtensionState" language="en_US">
595 Check Extension Status.
598 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
599 <parameter name="Exten" required="true">
600 <para>Extension to check state on.</para>
602 <parameter name="Context" required="true">
603 <para>Context for extension.</para>
607 <para>Report the extension state for given extension. If the extension has a hint,
608 will use devicestate to check the status of the device connected to the extension.</para>
609 <para>Will return an <literal>Extension Status</literal> message. The response will include
610 the hint for the extension and the status.</para>
613 <manager name="PresenceState" language="en_US">
618 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
619 <parameter name="Provider" required="true">
620 <para>Presence Provider to check the state of</para>
624 <para>Report the presence state for the given presence provider.</para>
625 <para>Will return a <literal>Presence State</literal> message. The response will include the
626 presence state and, if set, a presence subtype and custom message.</para>
629 <manager name="AbsoluteTimeout" language="en_US">
631 Set absolute timeout.
634 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
635 <parameter name="Channel" required="true">
636 <para>Channel name to hangup.</para>
638 <parameter name="Timeout" required="true">
639 <para>Maximum duration of the call (sec).</para>
643 <para>Hangup a channel after a certain time. Acknowledges set time with
644 <literal>Timeout Set</literal> message.</para>
647 <manager name="MailboxStatus" language="en_US">
652 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
653 <parameter name="Mailbox" required="true">
654 <para>Full mailbox ID <replaceable>mailbox</replaceable>@<replaceable>vm-context</replaceable>.</para>
658 <para>Checks a voicemail account for status.</para>
659 <para>Returns whether there are messages waiting.</para>
660 <para>Message: Mailbox Status.</para>
661 <para>Mailbox: <replaceable>mailboxid</replaceable>.</para>
662 <para>Waiting: <literal>0</literal> if messages waiting, <literal>1</literal>
663 if no messages waiting.</para>
666 <manager name="MailboxCount" language="en_US">
668 Check Mailbox Message Count.
671 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
672 <parameter name="Mailbox" required="true">
673 <para>Full mailbox ID <replaceable>mailbox</replaceable>@<replaceable>vm-context</replaceable>.</para>
677 <para>Checks a voicemail account for new messages.</para>
678 <para>Returns number of urgent, new and old messages.</para>
679 <para>Message: Mailbox Message Count</para>
680 <para>Mailbox: <replaceable>mailboxid</replaceable></para>
681 <para>UrgentMessages: <replaceable>count</replaceable></para>
682 <para>NewMessages: <replaceable>count</replaceable></para>
683 <para>OldMessages: <replaceable>count</replaceable></para>
686 <manager name="ListCommands" language="en_US">
688 List available manager commands.
691 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
694 <para>Returns the action name and synopsis for every action that
695 is available to the user.</para>
698 <manager name="SendText" language="en_US">
700 Send text message to channel.
703 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
704 <parameter name="Channel" required="true">
705 <para>Channel to send message to.</para>
707 <parameter name="Message" required="true">
708 <para>Message to send.</para>
712 <para>Sends A Text Message to a channel while in a call.</para>
715 <manager name="UserEvent" language="en_US">
717 Send an arbitrary event.
720 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
721 <parameter name="UserEvent" required="true">
722 <para>Event string to send.</para>
724 <parameter name="Header1">
725 <para>Content1.</para>
727 <parameter name="HeaderN">
728 <para>ContentN.</para>
732 <para>Send an event to manager sessions.</para>
735 <manager name="WaitEvent" language="en_US">
737 Wait for an event to occur.
740 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
741 <parameter name="Timeout" required="true">
742 <para>Maximum time (in seconds) to wait for events, <literal>-1</literal> means forever.</para>
746 <para>This action will ellicit a <literal>Success</literal> response. Whenever
747 a manager event is queued. Once WaitEvent has been called on an HTTP manager
748 session, events will be generated and queued.</para>
751 <manager name="CoreSettings" language="en_US">
753 Show PBX core settings (version etc).
756 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
759 <para>Query for Core PBX settings.</para>
762 <manager name="CoreStatus" language="en_US">
764 Show PBX core status variables.
767 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
770 <para>Query for Core PBX status.</para>
773 <manager name="Reload" language="en_US">
778 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
779 <parameter name="Module">
780 <para>Name of the module to reload.</para>
784 <para>Send a reload event.</para>
787 <manager name="CoreShowChannels" language="en_US">
789 List currently active channels.
792 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
795 <para>List currently defined channels and some information about them.</para>
798 <manager name="ModuleLoad" language="en_US">
803 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
804 <parameter name="Module">
805 <para>Asterisk module name (including .so extension) or subsystem identifier:</para>
808 <enum name="dnsmgr" />
809 <enum name="extconfig" />
812 <enum name="manager" />
814 <enum name="logger" />
815 <enum name="features" />
817 <enum name="udptl" />
818 <enum name="indications" />
823 <parameter name="LoadType" required="true">
824 <para>The operation to be done on module. Subsystem identifiers may only
828 <enum name="unload" />
829 <enum name="reload" />
831 <para>If no module is specified for a <literal>reload</literal> loadtype,
832 all modules are reloaded.</para>
836 <para>Loads, unloads or reloads an Asterisk module in a running system.</para>
839 <manager name="ModuleCheck" language="en_US">
841 Check if module is loaded.
844 <parameter name="Module" required="true">
845 <para>Asterisk module name (not including extension).</para>
849 <para>Checks if Asterisk module is loaded. Will return Success/Failure.
850 For success returns, the module revision number is included.</para>
853 <manager name="AOCMessage" language="en_US">
855 Generate an Advice of Charge message on a channel.
858 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
859 <parameter name="Channel" required="true">
860 <para>Channel name to generate the AOC message on.</para>
862 <parameter name="ChannelPrefix">
863 <para>Partial channel prefix. By using this option one can match the beginning part
864 of a channel name without having to put the entire name in. For example
865 if a channel name is SIP/snom-00000001 and this value is set to SIP/snom, then
866 that channel matches and the message will be sent. Note however that only
867 the first matched channel has the message sent on it. </para>
869 <parameter name="MsgType" required="true">
870 <para>Defines what type of AOC message to create, AOC-D or AOC-E</para>
876 <parameter name="ChargeType" required="true">
877 <para>Defines what kind of charge this message represents.</para>
881 <enum name="Currency" />
885 <parameter name="UnitAmount(0)">
886 <para>This represents the amount of units charged. The ETSI AOC standard specifies that
887 this value along with the optional UnitType value are entries in a list. To accommodate this
888 these values take an index value starting at 0 which can be used to generate this list of
889 unit entries. For Example, If two unit entires were required this could be achieved by setting the
890 paramter UnitAmount(0)=1234 and UnitAmount(1)=5678. Note that UnitAmount at index 0 is
891 required when ChargeType=Unit, all other entries in the list are optional.
894 <parameter name="UnitType(0)">
895 <para>Defines the type of unit. ETSI AOC standard specifies this as an integer
896 value between 1 and 16, but this value is left open to accept any positive
897 integer. Like the UnitAmount parameter, this value represents a list entry
898 and has an index parameter that starts at 0.
901 <parameter name="CurrencyName">
902 <para>Specifies the currency's name. Note that this value is truncated after 10 characters.</para>
904 <parameter name="CurrencyAmount">
905 <para>Specifies the charge unit amount as a positive integer. This value is required
906 when ChargeType==Currency.</para>
908 <parameter name="CurrencyMultiplier">
909 <para>Specifies the currency multiplier. This value is required when ChargeType==Currency.</para>
911 <enum name="OneThousandth" />
912 <enum name="OneHundredth" />
913 <enum name="OneTenth" />
916 <enum name="Hundred" />
917 <enum name="Thousand" />
920 <parameter name="TotalType" default="Total">
921 <para>Defines what kind of AOC-D total is represented.</para>
923 <enum name="Total" />
924 <enum name="SubTotal" />
927 <parameter name="AOCBillingId">
928 <para>Represents a billing ID associated with an AOC-D or AOC-E message. Note
929 that only the first 3 items of the enum are valid AOC-D billing IDs</para>
931 <enum name="Normal" />
932 <enum name="ReverseCharge" />
933 <enum name="CreditCard" />
934 <enum name="CallFwdUnconditional" />
935 <enum name="CallFwdBusy" />
936 <enum name="CallFwdNoReply" />
937 <enum name="CallDeflection" />
938 <enum name="CallTransfer" />
941 <parameter name="ChargingAssociationId">
942 <para>Charging association identifier. This is optional for AOC-E and can be
943 set to any value between -32768 and 32767</para>
945 <parameter name="ChargingAssociationNumber">
946 <para>Represents the charging association party number. This value is optional
949 <parameter name="ChargingAssociationPlan">
950 <para>Integer representing the charging plan associated with the ChargingAssociationNumber.
951 The value is bits 7 through 1 of the Q.931 octet containing the type-of-number and
952 numbering-plan-identification fields.</para>
956 <para>Generates an AOC-D or AOC-E message on a channel.</para>
959 <function name="AMI_CLIENT" language="en_US">
961 Checks attributes of manager accounts
964 <parameter name="loginname" required="true">
965 <para>Login name, specified in manager.conf</para>
967 <parameter name="field" required="true">
968 <para>The manager account attribute to return</para>
970 <enum name="sessions"><para>The number of sessions for this AMI account</para></enum>
976 Currently, the only supported parameter is "sessions" which will return the current number of
977 active sessions for this AMI account.
981 <manager name="Filter" language="en_US">
983 Dynamically add filters for the current manager session.
986 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
987 <parameter name="Operation">
990 <para>Add a filter.</para>
994 <parameter name="Filter">
995 <para>Filters can be whitelist or blacklist</para>
996 <para>Example whitelist filter: "Event: Newchannel"</para>
997 <para>Example blacklist filter: "!Channel: DAHDI.*"</para>
998 <para>This filter option is used to whitelist or blacklist events per user to be
999 reported with regular expressions and are allowed if both the regex matches
1000 and the user has read access as defined in manager.conf. Filters are assumed to be for whitelisting
1001 unless preceeded by an exclamation point, which marks it as being black.
1002 Evaluation of the filters is as follows:</para>
1003 <para>- If no filters are configured all events are reported as normal.</para>
1004 <para>- If there are white filters only: implied black all filter processed first, then white filters.</para>
1005 <para>- If there are black filters only: implied white all filter processed first, then black filters.</para>
1006 <para>- If there are both white and black filters: implied black all filter processed first, then white
1007 filters, and lastly black filters.</para>
1011 <para>The filters added are only used for the current session.
1012 Once the connection is closed the filters are removed.</para>
1013 <para>This comand requires the system permission because
1014 this command can be used to create filters that may bypass
1015 filters defined in manager.conf</para>
1018 <manager name="FilterList" language="en_US">
1020 Show current event filters for this session
1023 <para>The filters displayed are for the current session. Only those filters defined in
1024 manager.conf will be present upon starting a new session.</para>
1027 <manager name="BlindTransfer" language="en_US">
1029 Blind transfer channel(s) to the given destination
1032 <parameter name="Channel" required="true">
1034 <parameter name="Context">
1036 <parameter name="Exten">
1040 <para>Redirect all channels currently bridged to the specified channel to the specified destination.</para>
1043 <ref type="manager">Redirect</ref>
1048 /*! \addtogroup Group_AMI AMI functions
1056 UNSPECIFIED_CATEGORY,
1057 UNSPECIFIED_ARGUMENT,
1067 enum add_filter_result {
1069 FILTER_ALLOC_FAILED,
1070 FILTER_COMPILE_FAIL,
1074 * Linked list of events.
1075 * Global events are appended to the list by append_event().
1076 * The usecount is the number of stored pointers to the element,
1077 * excluding the list pointers. So an element that is only in
1078 * the list has a usecount of 0, not 1.
1080 * Clients have a pointer to the last event processed, and for each
1081 * of these clients we track the usecount of the elements.
1082 * If we have a pointer to an entry in the list, it is safe to navigate
1083 * it forward because elements will not be deleted, but only appended.
1084 * The worst that can happen is seeing the pointer still NULL.
1086 * When the usecount of an element drops to 0, and the element is the
1087 * first in the list, we can remove it. Removal is done within the
1088 * main thread, which is woken up for the purpose.
1090 * For simplicity of implementation, we make sure the list is never empty.
1093 int usecount; /*!< # of clients who still need the event */
1095 unsigned int seq; /*!< sequence number */
1096 struct timeval tv; /*!< When event was allocated */
1097 AST_RWLIST_ENTRY(eventqent) eq_next;
1098 char eventdata[1]; /*!< really variable size, allocated by append_event() */
1101 static AST_RWLIST_HEAD_STATIC(all_events, eventqent);
1103 static int displayconnects = 1;
1104 static int allowmultiplelogin = 1;
1105 static int timestampevents;
1106 static int httptimeout = 60;
1107 static int broken_events_action = 0;
1108 static int manager_enabled = 0;
1109 static int webmanager_enabled = 0;
1110 static int manager_debug = 0; /*!< enable some debugging code in the manager */
1111 static int authtimeout;
1112 static int authlimit;
1113 static char *manager_channelvars;
1115 #define DEFAULT_REALM "asterisk"
1116 static char global_realm[MAXHOSTNAMELEN]; /*!< Default realm */
1118 static int block_sockets;
1119 static int unauth_sessions = 0;
1120 static struct stasis_subscription *acl_change_sub;
1122 /*! \brief A \ref stasis_topic that all topics AMI cares about will be forwarded to */
1123 static struct stasis_topic *manager_topic;
1125 /*! \brief The \ref stasis_message_router for all \ref stasis messages */
1126 static struct stasis_message_router *stasis_router;
1128 /*! \brief The \ref stasis_subscription for forwarding the RTP topic to the AMI topic */
1129 static struct stasis_subscription *rtp_topic_forwarder;
1131 #define MGR_SHOW_TERMINAL_WIDTH 80
1133 #define MAX_VARS 128
1136 * Descriptor for a manager session, either on the AMI socket or over HTTP.
1139 * AMI session have managerid == 0; the entry is created upon a connect,
1140 * and destroyed with the socket.
1141 * HTTP sessions have managerid != 0, the value is used as a search key
1142 * to lookup sessions (using the mansession_id cookie, or nonce key from
1143 * Digest Authentication http header).
1145 #define MAX_BLACKLIST_CMD_LEN 2
1146 static const struct {
1147 const char *words[AST_MAX_CMD_LEN];
1148 } command_blacklist[] = {
1149 {{ "module", "load", NULL }},
1150 {{ "module", "unload", NULL }},
1151 {{ "restart", "gracefully", NULL }},
1154 static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_topic *topic, struct stasis_message *message);
1156 static void acl_change_stasis_subscribe(void)
1158 if (!acl_change_sub) {
1159 acl_change_sub = stasis_subscribe(ast_security_topic(),
1160 acl_change_stasis_cb, NULL);
1164 static void acl_change_stasis_unsubscribe(void)
1166 acl_change_sub = stasis_unsubscribe_and_join(acl_change_sub);
1169 /* In order to understand what the heck is going on with the
1170 * mansession_session and mansession structs, we need to have a bit of a history
1173 * In the beginning, there was the mansession. The mansession contained data that was
1174 * intrinsic to a manager session, such as the time that it started, the name of the logged-in
1175 * user, etc. In addition to these parameters were the f and fd parameters. For typical manager
1176 * sessions, these were used to represent the TCP socket over which the AMI session was taking
1177 * place. It makes perfect sense for these fields to be a part of the session-specific data since
1178 * the session actually defines this information.
1180 * Then came the HTTP AMI sessions. With these, the f and fd fields need to be opened and closed
1181 * for every single action that occurs. Thus the f and fd fields aren't really specific to the session
1182 * but rather to the action that is being executed. Because a single session may execute many commands
1183 * at once, some sort of safety needed to be added in order to be sure that we did not end up with fd
1184 * leaks from one action overwriting the f and fd fields used by a previous action before the previous action
1185 * has had a chance to properly close its handles.
1187 * The initial idea to solve this was to use thread synchronization, but this prevented multiple actions
1188 * from being run at the same time in a single session. Some manager actions may block for a long time, thus
1189 * creating a large queue of actions to execute. In addition, this fix did not address the basic architectural
1190 * issue that for HTTP manager sessions, the f and fd variables are not really a part of the session, but are
1191 * part of the action instead.
1193 * The new idea was to create a structure on the stack for each HTTP Manager action. This structure would
1194 * contain the action-specific information, such as which file to write to. In order to maintain expectations
1195 * of action handlers and not have to change the public API of the manager code, we would need to name this
1196 * new stacked structure 'mansession' and contain within it the old mansession struct that we used to use.
1197 * We renamed the old mansession struct 'mansession_session' to hopefully convey that what is in this structure
1198 * is session-specific data. The structure that it is wrapped in, called a 'mansession' really contains action-specific
1201 struct mansession_session {
1202 /*! \todo XXX need to document which fields it is protecting */
1203 struct ast_sockaddr addr; /*!< address we are connecting from */
1204 FILE *f; /*!< fdopen() on the underlying fd */
1205 int fd; /*!< descriptor used for output. Either the socket (AMI) or a temporary file (HTTP) */
1206 int inuse; /*!< number of HTTP sessions using this entry */
1207 int needdestroy; /*!< Whether an HTTP session should be destroyed */
1208 pthread_t waiting_thread; /*!< Sleeping thread using this descriptor */
1209 uint32_t managerid; /*!< Unique manager identifier, 0 for AMI sessions */
1210 time_t sessionstart; /*!< Session start time */
1211 struct timeval sessionstart_tv; /*!< Session start time */
1212 time_t sessiontimeout; /*!< Session timeout if HTTP */
1213 char username[80]; /*!< Logged in username */
1214 char challenge[10]; /*!< Authentication challenge */
1215 int authenticated; /*!< Authentication status */
1216 int readperm; /*!< Authorization for reading */
1217 int writeperm; /*!< Authorization for writing */
1218 char inbuf[1025]; /*!< Buffer - we use the extra byte to add a '\\0' and simplify parsing */
1219 int inlen; /*!< number of buffered bytes */
1220 struct ao2_container *whitefilters; /*!< Manager event filters - white list */
1221 struct ao2_container *blackfilters; /*!< Manager event filters - black list */
1222 struct ast_variable *chanvars; /*!< Channel variables to set for originate */
1223 int send_events; /*!< XXX what ? */
1224 struct eventqent *last_ev; /*!< last event processed. */
1225 int writetimeout; /*!< Timeout for ast_carefulwrite() */
1227 int pending_event; /*!< Pending events indicator in case when waiting_thread is NULL */
1228 time_t noncetime; /*!< Timer for nonce value expiration */
1229 unsigned long oldnonce; /*!< Stale nonce value */
1230 unsigned long nc; /*!< incremental nonce counter */
1231 AST_LIST_HEAD_NOLOCK(mansession_datastores, ast_datastore) datastores; /*!< Data stores on the session */
1232 AST_LIST_ENTRY(mansession_session) list;
1235 enum mansession_message_parsing {
1237 MESSAGE_LINE_TOO_LONG
1240 /*! \brief In case you didn't read that giant block of text above the mansession_session struct, the
1241 * \ref struct mansession is named this solely to keep the API the same in Asterisk. This structure really
1242 * represents data that is different from Manager action to Manager action. The mansession_session pointer
1243 * contained within points to session-specific data.
1246 struct mansession_session *session;
1247 struct ast_tcptls_session_instance *tcptls_session;
1250 enum mansession_message_parsing parsing;
1252 struct manager_custom_hook *hook;
1256 static struct ao2_container *sessions = NULL;
1258 /*! \brief user descriptor, as read from the config file.
1260 * \note It is still missing some fields -- e.g. we can have multiple permit and deny
1261 * lines which are not supported here, and readperm/writeperm/writetimeout
1264 struct ast_manager_user {
1266 char *secret; /*!< Secret for logging in */
1267 int readperm; /*!< Authorization for reading */
1268 int writeperm; /*!< Authorization for writing */
1269 int writetimeout; /*!< Per user Timeout for ast_carefulwrite() */
1270 int displayconnects; /*!< XXX unused */
1271 int allowmultiplelogin; /*!< Per user option*/
1272 int keep; /*!< mark entries created on a reload */
1273 struct ao2_container *whitefilters; /*!< Manager event filters - white list */
1274 struct ao2_container *blackfilters; /*!< Manager event filters - black list */
1275 struct ast_acl_list *acl; /*!< ACL setting */
1276 char *a1_hash; /*!< precalculated A1 for Digest auth */
1277 struct ast_variable *chanvars; /*!< Channel variables to set for originate */
1278 AST_RWLIST_ENTRY(ast_manager_user) list;
1281 /*! \brief list of users found in the config file */
1282 static AST_RWLIST_HEAD_STATIC(users, ast_manager_user);
1284 /*! \brief list of actions registered */
1285 static AST_RWLIST_HEAD_STATIC(actions, manager_action);
1287 /*! \brief list of hooks registered */
1288 static AST_RWLIST_HEAD_STATIC(manager_hooks, manager_custom_hook);
1290 /*! \brief A container of event documentation nodes */
1291 AO2_GLOBAL_OBJ_STATIC(event_docs);
1293 static enum add_filter_result manager_add_filter(const char *filter_pattern, struct ao2_container *whitefilters, struct ao2_container *blackfilters);
1296 * @{ \brief Define AMI message types.
1298 STASIS_MESSAGE_TYPE_DEFN(ast_manager_get_generic_type);
1303 * \brief Find a registered action object.
1305 * \param name Name of AMI action to find.
1307 * \return Reffed action found or NULL
1309 static struct manager_action *action_find(const char *name)
1311 struct manager_action *act;
1313 AST_RWLIST_RDLOCK(&actions);
1314 AST_RWLIST_TRAVERSE(&actions, act, list) {
1315 if (!strcasecmp(name, act->action)) {
1316 ao2_t_ref(act, +1, "found action object");
1320 AST_RWLIST_UNLOCK(&actions);
1325 struct stasis_topic *ast_manager_get_topic(void)
1327 return manager_topic;
1330 struct stasis_message_router *ast_manager_get_message_router(void)
1332 return stasis_router;
1335 static void manager_json_value_str_append(struct ast_json *value, const char *key,
1336 struct ast_str **res)
1338 switch (ast_json_typeof(value)) {
1339 case AST_JSON_STRING:
1340 ast_str_append(res, 0, "%s: %s\r\n", key, ast_json_string_get(value));
1342 case AST_JSON_INTEGER:
1343 ast_str_append(res, 0, "%s: %jd\r\n", key, ast_json_integer_get(value));
1346 ast_str_append(res, 0, "%s: True\r\n", key);
1348 case AST_JSON_FALSE:
1349 ast_str_append(res, 0, "%s: False\r\n", key);
1352 ast_str_append(res, 0, "%s: \r\n", key);
1357 static void manager_json_to_ast_str(struct ast_json *obj, const char *key,
1358 struct ast_str **res, key_exclusion_cb exclusion_cb);
1360 static void manager_json_array_with_key(struct ast_json *obj, const char* key,
1361 size_t index, struct ast_str **res,
1362 key_exclusion_cb exclusion_cb)
1364 struct ast_str *key_str = ast_str_alloca(64);
1365 ast_str_set(&key_str, 0, "%s(%zu)", key, index);
1366 manager_json_to_ast_str(obj, ast_str_buffer(key_str),
1370 static void manager_json_obj_with_key(struct ast_json *obj, const char* key,
1371 const char *parent_key, struct ast_str **res,
1372 key_exclusion_cb exclusion_cb)
1375 struct ast_str *key_str = ast_str_alloca(64);
1376 ast_str_set(&key_str, 0, "%s/%s", parent_key, key);
1377 manager_json_to_ast_str(obj, ast_str_buffer(key_str),
1382 manager_json_to_ast_str(obj, key, res, exclusion_cb);
1385 void manager_json_to_ast_str(struct ast_json *obj, const char *key,
1386 struct ast_str **res, key_exclusion_cb exclusion_cb)
1388 struct ast_json_iter *i;
1390 if (!obj || (!res && !(*res) && (!(*res = ast_str_create(1024))))) {
1394 if (exclusion_cb && key && exclusion_cb(key)) {
1398 if (ast_json_typeof(obj) != AST_JSON_OBJECT &&
1399 ast_json_typeof(obj) != AST_JSON_ARRAY) {
1400 manager_json_value_str_append(obj, key, res);
1404 if (ast_json_typeof(obj) == AST_JSON_ARRAY) {
1406 for (j = 0; j < ast_json_array_size(obj); ++j) {
1407 manager_json_array_with_key(ast_json_array_get(obj, j),
1408 key, j, res, exclusion_cb);
1413 for (i = ast_json_object_iter(obj); i;
1414 i = ast_json_object_iter_next(obj, i)) {
1415 manager_json_obj_with_key(ast_json_object_iter_value(i),
1416 ast_json_object_iter_key(i),
1417 key, res, exclusion_cb);
1422 struct ast_str *ast_manager_str_from_json_object(struct ast_json *blob, key_exclusion_cb exclusion_cb)
1424 struct ast_str *res = ast_str_create(1024);
1425 manager_json_to_ast_str(blob, NULL, &res, exclusion_cb);
1429 static void manager_default_msg_cb(void *data, struct stasis_subscription *sub,
1430 struct stasis_topic *topic,
1431 struct stasis_message *message)
1433 RAII_VAR(struct ast_manager_event_blob *, ev, NULL, ao2_cleanup);
1435 ev = stasis_message_to_ami(message);
1438 /* Not and AMI message; disregard */
1442 manager_event(ev->event_flags, ev->manager_event, "%s",
1446 static void manager_generic_msg_cb(void *data, struct stasis_subscription *sub,
1447 struct stasis_topic *topic,
1448 struct stasis_message *message)
1450 struct ast_json_payload *payload = stasis_message_data(message);
1451 int class_type = ast_json_integer_get(ast_json_object_get(payload->json, "class_type"));
1452 const char *type = ast_json_string_get(ast_json_object_get(payload->json, "type"));
1453 struct ast_json *event = ast_json_object_get(payload->json, "event");
1454 RAII_VAR(struct ast_str *, event_buffer, NULL, ast_free);
1456 event_buffer = ast_manager_str_from_json_object(event, NULL);
1457 if (!event_buffer) {
1458 ast_log(AST_LOG_WARNING, "Error while creating payload for event %s\n", type);
1461 manager_event(class_type, type, "%s", ast_str_buffer(event_buffer));
1464 void ast_manager_publish_event(const char *type, int class_type, struct ast_json *obj)
1466 RAII_VAR(struct ast_json *, event_info, NULL, ast_json_unref);
1467 RAII_VAR(struct ast_json_payload *, payload, NULL, ao2_cleanup);
1468 RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
1475 event_info = ast_json_pack("{s: s, s: i, s: o}",
1477 "class_type", class_type,
1483 payload = ast_json_payload_create(event_info);
1487 message = stasis_message_create(ast_manager_get_generic_type(), payload);
1491 stasis_publish(ast_manager_get_topic(), message);
1494 /*! \brief Add a custom hook to be called when an event is fired */
1495 void ast_manager_register_hook(struct manager_custom_hook *hook)
1497 AST_RWLIST_WRLOCK(&manager_hooks);
1498 AST_RWLIST_INSERT_TAIL(&manager_hooks, hook, list);
1499 AST_RWLIST_UNLOCK(&manager_hooks);
1502 /*! \brief Delete a custom hook to be called when an event is fired */
1503 void ast_manager_unregister_hook(struct manager_custom_hook *hook)
1505 AST_RWLIST_WRLOCK(&manager_hooks);
1506 AST_RWLIST_REMOVE(&manager_hooks, hook, list);
1507 AST_RWLIST_UNLOCK(&manager_hooks);
1510 int check_manager_enabled(void)
1512 return manager_enabled;
1515 int check_webmanager_enabled(void)
1517 return (webmanager_enabled && manager_enabled);
1521 * Grab a reference to the last event, update usecount as needed.
1522 * Can handle a NULL pointer.
1524 static struct eventqent *grab_last(void)
1526 struct eventqent *ret;
1528 AST_RWLIST_WRLOCK(&all_events);
1529 ret = AST_RWLIST_LAST(&all_events);
1530 /* the list is never empty now, but may become so when
1531 * we optimize it in the future, so be prepared.
1534 ast_atomic_fetchadd_int(&ret->usecount, 1);
1536 AST_RWLIST_UNLOCK(&all_events);
1541 * Purge unused events. Remove elements from the head
1542 * as long as their usecount is 0 and there is a next element.
1544 static void purge_events(void)
1546 struct eventqent *ev;
1547 struct timeval now = ast_tvnow();
1549 AST_RWLIST_WRLOCK(&all_events);
1550 while ( (ev = AST_RWLIST_FIRST(&all_events)) &&
1551 ev->usecount == 0 && AST_RWLIST_NEXT(ev, eq_next)) {
1552 AST_RWLIST_REMOVE_HEAD(&all_events, eq_next);
1556 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&all_events, ev, eq_next) {
1557 /* Never release the last event */
1558 if (!AST_RWLIST_NEXT(ev, eq_next)) {
1562 /* 2.5 times whatever the HTTP timeout is (maximum 2.5 hours) is the maximum time that we will definitely cache an event */
1563 if (ev->usecount == 0 && ast_tvdiff_sec(now, ev->tv) > (httptimeout > 3600 ? 3600 : httptimeout) * 2.5) {
1564 AST_RWLIST_REMOVE_CURRENT(eq_next);
1568 AST_RWLIST_TRAVERSE_SAFE_END;
1569 AST_RWLIST_UNLOCK(&all_events);
1573 * helper functions to convert back and forth between
1574 * string and numeric representation of set of flags
1576 static const struct permalias {
1580 { EVENT_FLAG_SYSTEM, "system" },
1581 { EVENT_FLAG_CALL, "call" },
1582 { EVENT_FLAG_LOG, "log" },
1583 { EVENT_FLAG_VERBOSE, "verbose" },
1584 { EVENT_FLAG_COMMAND, "command" },
1585 { EVENT_FLAG_AGENT, "agent" },
1586 { EVENT_FLAG_USER, "user" },
1587 { EVENT_FLAG_CONFIG, "config" },
1588 { EVENT_FLAG_DTMF, "dtmf" },
1589 { EVENT_FLAG_REPORTING, "reporting" },
1590 { EVENT_FLAG_CDR, "cdr" },
1591 { EVENT_FLAG_DIALPLAN, "dialplan" },
1592 { EVENT_FLAG_ORIGINATE, "originate" },
1593 { EVENT_FLAG_AGI, "agi" },
1594 { EVENT_FLAG_CC, "cc" },
1595 { EVENT_FLAG_AOC, "aoc" },
1596 { EVENT_FLAG_TEST, "test" },
1597 { EVENT_FLAG_MESSAGE, "message" },
1602 /*! \brief Checks to see if a string which can be used to evaluate functions should be rejected */
1603 static int function_capable_string_allowed_with_auths(const char *evaluating, int writepermlist)
1605 if (!(writepermlist & EVENT_FLAG_SYSTEM)
1607 strstr(evaluating, "SHELL") || /* NoOp(${SHELL(rm -rf /)}) */
1608 strstr(evaluating, "EVAL") /* NoOp(${EVAL(${some_var_containing_SHELL})}) */
1615 /*! \brief Convert authority code to a list of options for a user. This will only
1616 * display those authority codes that have an explicit match on authority */
1617 static const char *user_authority_to_str(int authority, struct ast_str **res)
1622 ast_str_reset(*res);
1623 for (i = 0; i < ARRAY_LEN(perms) - 1; i++) {
1624 if ((authority & perms[i].num) == perms[i].num) {
1625 ast_str_append(res, 0, "%s%s", sep, perms[i].label);
1630 if (ast_str_strlen(*res) == 0) /* replace empty string with something sensible */
1631 ast_str_append(res, 0, "<none>");
1633 return ast_str_buffer(*res);
1637 /*! \brief Convert authority code to a list of options. Note that the EVENT_FLAG_ALL
1638 * authority will always be returned. */
1639 static const char *authority_to_str(int authority, struct ast_str **res)
1644 ast_str_reset(*res);
1645 for (i = 0; i < ARRAY_LEN(perms) - 1; i++) {
1646 if (authority & perms[i].num) {
1647 ast_str_append(res, 0, "%s%s", sep, perms[i].label);
1652 if (ast_str_strlen(*res) == 0) /* replace empty string with something sensible */
1653 ast_str_append(res, 0, "<none>");
1655 return ast_str_buffer(*res);
1658 /*! Tells you if smallstr exists inside bigstr
1659 which is delim by delim and uses no buf or stringsep
1660 ast_instring("this|that|more","this",'|') == 1;
1662 feel free to move this to app.c -anthm */
1663 static int ast_instring(const char *bigstr, const char *smallstr, const char delim)
1665 const char *val = bigstr, *next;
1668 if ((next = strchr(val, delim))) {
1669 if (!strncmp(val, smallstr, (next - val))) {
1675 return !strcmp(smallstr, val);
1677 } while (*(val = (next + 1)));
1682 static int get_perm(const char *instr)
1690 for (x = 0; x < ARRAY_LEN(perms); x++) {
1691 if (ast_instring(instr, perms[x].label, ',')) {
1692 ret |= perms[x].num;
1700 * A number returns itself, false returns 0, true returns all flags,
1701 * other strings return the flags that are set.
1703 static int strings_to_mask(const char *string)
1707 if (ast_strlen_zero(string)) {
1711 for (p = string; *p; p++) {
1712 if (*p < '0' || *p > '9') {
1716 if (!*p) { /* all digits */
1717 return atoi(string);
1719 if (ast_false(string)) {
1722 if (ast_true(string)) { /* all permissions */
1724 for (x = 0; x < ARRAY_LEN(perms); x++) {
1725 ret |= perms[x].num;
1729 return get_perm(string);
1732 /*! \brief Unreference manager session object.
1733 If no more references, then go ahead and delete it */
1734 static struct mansession_session *unref_mansession(struct mansession_session *s)
1736 int refcount = ao2_ref(s, -1);
1737 if (manager_debug) {
1738 ast_debug(1, "Mansession: %p refcount now %d\n", s, refcount - 1);
1743 static void event_filter_destructor(void *obj)
1745 regex_t *regex_filter = obj;
1746 regfree(regex_filter);
1749 static void session_destructor(void *obj)
1751 struct mansession_session *session = obj;
1752 struct eventqent *eqe = session->last_ev;
1753 struct ast_datastore *datastore;
1755 /* Get rid of each of the data stores on the session */
1756 while ((datastore = AST_LIST_REMOVE_HEAD(&session->datastores, entry))) {
1757 /* Free the data store */
1758 ast_datastore_free(datastore);
1761 if (session->f != NULL) {
1765 ast_atomic_fetchadd_int(&eqe->usecount, -1);
1767 if (session->chanvars) {
1768 ast_variables_destroy(session->chanvars);
1771 if (session->whitefilters) {
1772 ao2_t_callback(session->whitefilters, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL, "unlink all white filters");
1773 ao2_t_ref(session->whitefilters, -1 , "decrement ref for white container, should be last one");
1776 if (session->blackfilters) {
1777 ao2_t_callback(session->blackfilters, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL, "unlink all black filters");
1778 ao2_t_ref(session->blackfilters, -1 , "decrement ref for black container, should be last one");
1782 /*! \brief Allocate manager session structure and add it to the list of sessions */
1783 static struct mansession_session *build_mansession(const struct ast_sockaddr *addr)
1785 struct mansession_session *newsession;
1787 if (!(newsession = ao2_alloc(sizeof(*newsession), session_destructor))) {
1791 if (!(newsession->whitefilters = ao2_container_alloc(1, NULL, NULL))) {
1792 ao2_ref(newsession, -1);
1796 if (!(newsession->blackfilters = ao2_container_alloc(1, NULL, NULL))) {
1797 ao2_ref(newsession, -1); /* session_destructor will cleanup the other filter */
1801 newsession->fd = -1;
1802 newsession->waiting_thread = AST_PTHREADT_NULL;
1803 newsession->writetimeout = 100;
1804 newsession->send_events = -1;
1805 ast_sockaddr_copy(&newsession->addr, addr);
1807 ao2_link(sessions, newsession);
1812 static int mansession_cmp_fn(void *obj, void *arg, int flags)
1814 struct mansession_session *s = obj;
1816 return !strcasecmp(s->username, str) ? CMP_MATCH : 0;
1819 static void session_destroy(struct mansession_session *s)
1821 unref_mansession(s);
1822 ao2_unlink(sessions, s);
1826 static int check_manager_session_inuse(const char *name)
1828 struct mansession_session *session = ao2_find(sessions, (char *) name, 0);
1833 unref_mansession(session);
1840 * lookup an entry in the list of registered users.
1841 * must be called with the list lock held.
1843 static struct ast_manager_user *get_manager_by_name_locked(const char *name)
1845 struct ast_manager_user *user = NULL;
1847 AST_RWLIST_TRAVERSE(&users, user, list) {
1848 if (!strcasecmp(user->username, name)) {
1856 /*! \brief Get displayconnects config option.
1857 * \param session manager session to get parameter from.
1858 * \return displayconnects config option value.
1860 static int manager_displayconnects (struct mansession_session *session)
1862 struct ast_manager_user *user = NULL;
1865 AST_RWLIST_RDLOCK(&users);
1866 if ((user = get_manager_by_name_locked (session->username))) {
1867 ret = user->displayconnects;
1869 AST_RWLIST_UNLOCK(&users);
1874 static char *handle_showmancmd(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1876 struct manager_action *cur;
1877 struct ast_str *authority;
1881 char syntax_title[64], description_title[64], synopsis_title[64], seealso_title[64], arguments_title[64], privilege_title[64];
1886 e->command = "manager show command";
1888 "Usage: manager show command <actionname> [<actionname> [<actionname> [...]]]\n"
1889 " Shows the detailed description for a specific Asterisk manager interface command.\n";
1892 l = strlen(a->word);
1894 AST_RWLIST_RDLOCK(&actions);
1895 AST_RWLIST_TRAVERSE(&actions, cur, list) {
1896 if (!strncasecmp(a->word, cur->action, l) && ++which > a->n) {
1897 ret = ast_strdup(cur->action);
1898 break; /* make sure we exit even if ast_strdup() returns NULL */
1901 AST_RWLIST_UNLOCK(&actions);
1904 authority = ast_str_alloca(80);
1906 return CLI_SHOWUSAGE;
1910 /* setup the titles */
1911 term_color(synopsis_title, "[Synopsis]\n", COLOR_MAGENTA, 0, 40);
1912 term_color(description_title, "[Description]\n", COLOR_MAGENTA, 0, 40);
1913 term_color(syntax_title, "[Syntax]\n", COLOR_MAGENTA, 0, 40);
1914 term_color(seealso_title, "[See Also]\n", COLOR_MAGENTA, 0, 40);
1915 term_color(arguments_title, "[Arguments]\n", COLOR_MAGENTA, 0, 40);
1916 term_color(privilege_title, "[Privilege]\n", COLOR_MAGENTA, 0, 40);
1919 AST_RWLIST_RDLOCK(&actions);
1920 AST_RWLIST_TRAVERSE(&actions, cur, list) {
1921 for (num = 3; num < a->argc; num++) {
1922 if (!strcasecmp(cur->action, a->argv[num])) {
1923 authority_to_str(cur->authority, &authority);
1926 if (cur->docsrc == AST_XML_DOC) {
1927 char *syntax = ast_xmldoc_printable(S_OR(cur->syntax, "Not available"), 1);
1928 char *synopsis = ast_xmldoc_printable(S_OR(cur->synopsis, "Not available"), 1);
1929 char *description = ast_xmldoc_printable(S_OR(cur->description, "Not available"), 1);
1930 char *arguments = ast_xmldoc_printable(S_OR(cur->arguments, "Not available"), 1);
1931 char *seealso = ast_xmldoc_printable(S_OR(cur->seealso, "Not available"), 1);
1932 char *privilege = ast_xmldoc_printable(S_OR(authority->str, "Not available"), 1);
1933 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",
1934 syntax_title, syntax,
1935 synopsis_title, synopsis,
1936 description_title, description,
1937 arguments_title, arguments,
1938 seealso_title, seealso,
1939 privilege_title, privilege);
1943 ast_cli(a->fd, "Action: %s\nSynopsis: %s\nPrivilege: %s\n%s\n",
1944 cur->action, cur->synopsis,
1946 S_OR(cur->description, ""));
1951 AST_RWLIST_UNLOCK(&actions);
1956 static char *handle_mandebug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1960 e->command = "manager set debug [on|off]";
1961 e->usage = "Usage: manager set debug [on|off]\n Show, enable, disable debugging of the manager code.\n";
1968 ast_cli(a->fd, "manager debug is %s\n", manager_debug? "on" : "off");
1969 } else if (a->argc == 4) {
1970 if (!strcasecmp(a->argv[3], "on")) {
1972 } else if (!strcasecmp(a->argv[3], "off")) {
1975 return CLI_SHOWUSAGE;
1981 static char *handle_showmanager(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1983 struct ast_manager_user *user = NULL;
1986 struct ast_str *rauthority = ast_str_alloca(128);
1987 struct ast_str *wauthority = ast_str_alloca(128);
1988 struct ast_variable *v;
1992 e->command = "manager show user";
1994 " Usage: manager show user <user>\n"
1995 " Display all information related to the manager user specified.\n";
1998 l = strlen(a->word);
2003 AST_RWLIST_RDLOCK(&users);
2004 AST_RWLIST_TRAVERSE(&users, user, list) {
2005 if ( !strncasecmp(a->word, user->username, l) && ++which > a->n ) {
2006 ret = ast_strdup(user->username);
2010 AST_RWLIST_UNLOCK(&users);
2015 return CLI_SHOWUSAGE;
2018 AST_RWLIST_RDLOCK(&users);
2020 if (!(user = get_manager_by_name_locked(a->argv[3]))) {
2021 ast_cli(a->fd, "There is no manager called %s\n", a->argv[3]);
2022 AST_RWLIST_UNLOCK(&users);
2026 ast_cli(a->fd, "\n");
2033 " displayconnects: %s\n"
2034 "allowmultiplelogin: %s\n",
2035 (user->username ? user->username : "(N/A)"),
2036 (user->secret ? "<Set>" : "(N/A)"),
2037 ((user->acl && !ast_acl_list_is_empty(user->acl)) ? "yes" : "no"),
2038 user_authority_to_str(user->readperm, &rauthority),
2039 user_authority_to_str(user->writeperm, &wauthority),
2040 (user->displayconnects ? "yes" : "no"),
2041 (user->allowmultiplelogin ? "yes" : "no"));
2042 ast_cli(a->fd, " Variables: \n");
2043 for (v = user->chanvars ; v ; v = v->next) {
2044 ast_cli(a->fd, " %s = %s\n", v->name, v->value);
2047 AST_RWLIST_UNLOCK(&users);
2052 static char *handle_showmanagers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2054 struct ast_manager_user *user = NULL;
2058 e->command = "manager show users";
2060 "Usage: manager show users\n"
2061 " Prints a listing of all managers that are currently configured on that\n"
2068 return CLI_SHOWUSAGE;
2071 AST_RWLIST_RDLOCK(&users);
2073 /* If there are no users, print out something along those lines */
2074 if (AST_RWLIST_EMPTY(&users)) {
2075 ast_cli(a->fd, "There are no manager users.\n");
2076 AST_RWLIST_UNLOCK(&users);
2080 ast_cli(a->fd, "\nusername\n--------\n");
2082 AST_RWLIST_TRAVERSE(&users, user, list) {
2083 ast_cli(a->fd, "%s\n", user->username);
2087 AST_RWLIST_UNLOCK(&users);
2089 ast_cli(a->fd,"-------------------\n"
2090 "%d manager users configured.\n", count_amu);
2094 /*! \brief CLI command manager list commands */
2095 static char *handle_showmancmds(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2097 struct manager_action *cur;
2099 int space_remaining;
2100 #define HSMC_FORMAT " %-*.*s %-.*s\n"
2103 e->command = "manager show commands";
2105 "Usage: manager show commands\n"
2106 " Prints a listing of all the available Asterisk manager interface commands.\n";
2112 AST_RWLIST_RDLOCK(&actions);
2113 AST_RWLIST_TRAVERSE(&actions, cur, list) {
2114 int incoming_len = strlen(cur->action);
2115 if (incoming_len > name_len) {
2116 name_len = incoming_len;
2120 space_remaining = MGR_SHOW_TERMINAL_WIDTH - name_len - 4;
2121 if (space_remaining < 0) {
2122 space_remaining = 0;
2125 ast_cli(a->fd, HSMC_FORMAT, name_len, name_len, "Action", space_remaining, "Synopsis");
2126 ast_cli(a->fd, HSMC_FORMAT, name_len, name_len, "------", space_remaining, "--------");
2128 AST_RWLIST_TRAVERSE(&actions, cur, list) {
2129 ast_cli(a->fd, HSMC_FORMAT, name_len, name_len, cur->action, space_remaining, cur->synopsis);
2131 AST_RWLIST_UNLOCK(&actions);
2136 /*! \brief CLI command manager list connected */
2137 static char *handle_showmanconn(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2139 struct mansession_session *session;
2140 time_t now = time(NULL);
2141 #define HSMCONN_FORMAT1 " %-15.15s %-55.55s %-10.10s %-10.10s %-8.8s %-8.8s %-5.5s %-5.5s\n"
2142 #define HSMCONN_FORMAT2 " %-15.15s %-55.55s %-10d %-10d %-8d %-8d %-5.5d %-5.5d\n"
2144 struct ao2_iterator i;
2148 e->command = "manager show connected";
2150 "Usage: manager show connected\n"
2151 " Prints a listing of the users that are currently connected to the\n"
2152 "Asterisk manager interface.\n";
2158 ast_cli(a->fd, HSMCONN_FORMAT1, "Username", "IP Address", "Start", "Elapsed", "FileDes", "HttpCnt", "Read", "Write");
2160 i = ao2_iterator_init(sessions, 0);
2161 while ((session = ao2_iterator_next(&i))) {
2163 ast_cli(a->fd, HSMCONN_FORMAT2, session->username, ast_sockaddr_stringify_addr(&session->addr), (int)(session->sessionstart), (int)(now - session->sessionstart), session->fd, session->inuse, session->readperm, session->writeperm);
2165 ao2_unlock(session);
2166 unref_mansession(session);
2168 ao2_iterator_destroy(&i);
2169 ast_cli(a->fd, "%d users connected.\n", count);
2174 /*! \brief CLI command manager list eventq */
2175 /* Should change to "manager show connected" */
2176 static char *handle_showmaneventq(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2178 struct eventqent *s;
2181 e->command = "manager show eventq";
2183 "Usage: manager show eventq\n"
2184 " Prints a listing of all events pending in the Asterisk manger\n"
2190 AST_RWLIST_RDLOCK(&all_events);
2191 AST_RWLIST_TRAVERSE(&all_events, s, eq_next) {
2192 ast_cli(a->fd, "Usecount: %d\n", s->usecount);
2193 ast_cli(a->fd, "Category: %d\n", s->category);
2194 ast_cli(a->fd, "Event:\n%s", s->eventdata);
2196 AST_RWLIST_UNLOCK(&all_events);
2201 /*! \brief CLI command manager reload */
2202 static char *handle_manager_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2206 e->command = "manager reload";
2208 "Usage: manager reload\n"
2209 " Reloads the manager configuration.\n";
2215 return CLI_SHOWUSAGE;
2221 static struct eventqent *advance_event(struct eventqent *e)
2223 struct eventqent *next;
2225 AST_RWLIST_RDLOCK(&all_events);
2226 if ((next = AST_RWLIST_NEXT(e, eq_next))) {
2227 ast_atomic_fetchadd_int(&next->usecount, 1);
2228 ast_atomic_fetchadd_int(&e->usecount, -1);
2230 AST_RWLIST_UNLOCK(&all_events);
2234 #define GET_HEADER_FIRST_MATCH 0
2235 #define GET_HEADER_LAST_MATCH 1
2236 #define GET_HEADER_SKIP_EMPTY 2
2239 * \brief Return a matching header value.
2242 * Generic function to return either the first or the last
2243 * matching header from a list of variables, possibly skipping
2246 * \note At the moment there is only one use of this function in
2247 * this file, so we make it static.
2249 * \note Never returns NULL.
2251 static const char *__astman_get_header(const struct message *m, char *var, int mode)
2253 int x, l = strlen(var);
2254 const char *result = "";
2260 for (x = 0; x < m->hdrcount; x++) {
2261 const char *h = m->headers[x];
2262 if (!strncasecmp(var, h, l) && h[l] == ':') {
2263 const char *value = h + l + 1;
2264 value = ast_skip_blanks(value); /* ignore leading spaces in the value */
2265 /* found a potential candidate */
2266 if ((mode & GET_HEADER_SKIP_EMPTY) && ast_strlen_zero(value)) {
2267 continue; /* not interesting */
2269 if (mode & GET_HEADER_LAST_MATCH) {
2270 result = value; /* record the last match so far */
2281 * \brief Return the first matching variable from an array.
2283 * \note This is the legacy function and is implemented in
2284 * therms of __astman_get_header().
2286 * \note Never returns NULL.
2288 const char *astman_get_header(const struct message *m, char *var)
2290 return __astman_get_header(m, var, GET_HEADER_FIRST_MATCH);
2295 * \brief Process one "Variable:" header value string.
2297 * \param head Current list of AMI variables to get new values added.
2298 * \param hdr_val Header value string to process.
2300 * \return New variable list head.
2302 static struct ast_variable *man_do_variable_value(struct ast_variable *head, const char *hdr_val)
2305 AST_DECLARE_APP_ARGS(args,
2306 AST_APP_ARG(vars)[64];
2309 hdr_val = ast_skip_blanks(hdr_val); /* ignore leading spaces in the value */
2310 parse = ast_strdupa(hdr_val);
2312 /* Break the header value string into name=val pair items. */
2313 AST_STANDARD_APP_ARGS(args, parse);
2317 /* Process each name=val pair item. */
2318 for (y = 0; y < args.argc; y++) {
2319 struct ast_variable *cur;
2323 if (!args.vars[y]) {
2326 var = val = args.vars[y];
2329 /* XXX We may wish to trim whitespace from the strings. */
2330 if (!val || ast_strlen_zero(var)) {
2334 /* Create new variable list node and prepend it to the list. */
2335 cur = ast_variable_new(var, val, "");
2346 struct ast_variable *astman_get_variables(const struct message *m)
2350 struct ast_variable *head = NULL;
2352 static const char var_hdr[] = "Variable:";
2354 /* Process all "Variable:" headers. */
2355 varlen = strlen(var_hdr);
2356 for (x = 0; x < m->hdrcount; x++) {
2357 if (strncasecmp(var_hdr, m->headers[x], varlen)) {
2360 head = man_do_variable_value(head, m->headers[x] + varlen);
2366 /*! \brief access for hooks to send action messages to ami */
2367 int ast_hook_send_action(struct manager_custom_hook *hook, const char *msg)
2371 struct manager_action *act_found;
2372 struct mansession s = {.session = NULL, };
2373 struct message m = { 0 };
2383 /* Create our own copy of the AMI action msg string. */
2384 src = dup_str = ast_strdup(msg);
2389 /* convert msg string to message struct */
2390 curlen = strlen(src);
2391 for (x = 0; x < curlen; x++) {
2392 int cr; /* set if we have \r */
2393 if (src[x] == '\r' && x+1 < curlen && src[x+1] == '\n')
2394 cr = 2; /* Found. Update length to include \r\n */
2395 else if (src[x] == '\n')
2396 cr = 1; /* also accept \n only */
2399 /* don't keep empty lines */
2400 if (x && m.hdrcount < ARRAY_LEN(m.headers)) {
2401 /* ... but trim \r\n and terminate the header string */
2403 m.headers[m.hdrcount++] = src;
2406 curlen -= x; /* remaining size */
2407 src += x; /* update pointer */
2408 x = -1; /* reset loop */
2411 action = astman_get_header(&m, "Action");
2412 if (strcasecmp(action, "login")) {
2413 act_found = action_find(action);
2416 * we have to simulate a session for this action request
2417 * to be able to pass it down for processing
2418 * This is necessary to meet the previous design of manager.c
2421 s.f = (void*)1; /* set this to something so our request will make it through all functions that test it*/
2423 ao2_lock(act_found);
2424 if (act_found->registered && act_found->func) {
2425 if (act_found->module) {
2426 ast_module_ref(act_found->module);
2428 ao2_unlock(act_found);
2429 ret = act_found->func(&s, &m);
2430 ao2_lock(act_found);
2431 if (act_found->module) {
2432 ast_module_unref(act_found->module);
2437 ao2_unlock(act_found);
2438 ao2_t_ref(act_found, -1, "done with found action object");
2447 * helper function to send a string to the socket.
2448 * Return -1 on error (e.g. buffer full).
2450 static int send_string(struct mansession *s, char *string)
2453 FILE *f = s->f ? s->f : s->session->f;
2454 int fd = s->f ? s->fd : s->session->fd;
2456 /* It's a result from one of the hook's action invocation */
2459 * to send responses, we're using the same function
2460 * as for receiving events. We call the event "HookResponse"
2462 s->hook->helper(EVENT_FLAG_HOOKRESPONSE, "HookResponse", string);
2466 if ((res = ast_careful_fwrite(f, fd, string, strlen(string), s->session->writetimeout))) {
2474 * \brief thread local buffer for astman_append
2476 * \note This can not be defined within the astman_append() function
2477 * because it declares a couple of functions that get used to
2478 * initialize the thread local storage key.
2480 AST_THREADSTORAGE(astman_append_buf);
2482 AST_THREADSTORAGE(userevent_buf);
2484 /*! \brief initial allocated size for the astman_append_buf and astman_send_*_va */
2485 #define ASTMAN_APPEND_BUF_INITSIZE 256
2488 * utility functions for creating AMI replies
2490 void astman_append(struct mansession *s, const char *fmt, ...)
2493 struct ast_str *buf;
2495 if (!(buf = ast_str_thread_get(&astman_append_buf, ASTMAN_APPEND_BUF_INITSIZE))) {
2500 ast_str_set_va(&buf, 0, fmt, ap);
2503 if (s->f != NULL || s->session->f != NULL) {
2504 send_string(s, ast_str_buffer(buf));
2506 ast_verbose("fd == -1 in astman_append, should not happen\n");
2510 /*! \note NOTE: XXX this comment is unclear and possibly wrong.
2511 Callers of astman_send_error(), astman_send_response() or astman_send_ack() must EITHER
2512 hold the session lock _or_ be running in an action callback (in which case s->session->busy will
2513 be non-zero). In either of these cases, there is no need to lock-protect the session's
2514 fd, since no other output will be sent (events will be queued), and no input will
2515 be read until either the current action finishes or get_input() obtains the session
2519 /*! \todo XXX MSG_MOREDATA should go to a header file. */
2520 #define MSG_MOREDATA ((char *)astman_send_response)
2522 /*! \brief send a response with an optional message,
2523 * and terminate it with an empty line.
2524 * m is used only to grab the 'ActionID' field.
2526 * Use the explicit constant MSG_MOREDATA to remove the empty line.
2527 * XXX MSG_MOREDATA should go to a header file.
2529 static void astman_send_response_full(struct mansession *s, const struct message *m, char *resp, char *msg, char *listflag)
2531 const char *id = astman_get_header(m, "ActionID");
2533 astman_append(s, "Response: %s\r\n", resp);
2534 if (!ast_strlen_zero(id)) {
2535 astman_append(s, "ActionID: %s\r\n", id);
2538 astman_append(s, "EventList: %s\r\n", listflag); /* Start, complete, cancelled */
2540 if (msg == MSG_MOREDATA) {
2543 astman_append(s, "Message: %s\r\n\r\n", msg);
2545 astman_append(s, "\r\n");
2549 void astman_send_response(struct mansession *s, const struct message *m, char *resp, char *msg)
2551 astman_send_response_full(s, m, resp, msg, NULL);
2554 void astman_send_error(struct mansession *s, const struct message *m, char *error)
2556 astman_send_response_full(s, m, "Error", error, NULL);
2559 void astman_send_error_va(struct mansession *s, const struct message *m, const char *fmt, ...)
2562 struct ast_str *buf;
2565 if (!(buf = ast_str_thread_get(&astman_append_buf, ASTMAN_APPEND_BUF_INITSIZE))) {
2570 ast_str_set_va(&buf, 0, fmt, ap);
2573 /* astman_append will use the same underlying buffer, so copy the message out
2574 * before sending the response */
2575 msg = ast_str_buffer(buf);
2577 msg = ast_strdupa(msg);
2579 astman_send_response_full(s, m, "Error", msg, NULL);
2582 void astman_send_ack(struct mansession *s, const struct message *m, char *msg)
2584 astman_send_response_full(s, m, "Success", msg, NULL);
2587 static void astman_start_ack(struct mansession *s, const struct message *m)
2589 astman_send_response_full(s, m, "Success", MSG_MOREDATA, NULL);
2592 void astman_send_listack(struct mansession *s, const struct message *m, char *msg, char *listflag)
2594 astman_send_response_full(s, m, "Success", msg, listflag);
2597 /*! \brief Lock the 'mansession' structure. */
2598 static void mansession_lock(struct mansession *s)
2600 ast_mutex_lock(&s->lock);
2603 /*! \brief Unlock the 'mansession' structure. */
2604 static void mansession_unlock(struct mansession *s)
2606 ast_mutex_unlock(&s->lock);
2610 Rather than braindead on,off this now can also accept a specific int mask value
2611 or a ',' delim list of mask strings (the same as manager.conf) -anthm
2613 static int set_eventmask(struct mansession *s, const char *eventmask)
2615 int maskint = strings_to_mask(eventmask);
2617 ao2_lock(s->session);
2619 s->session->send_events = maskint;
2621 ao2_unlock(s->session);
2626 static enum ast_transport mansession_get_transport(const struct mansession *s)
2628 return s->tcptls_session->parent->tls_cfg ? AST_TRANSPORT_TLS :
2632 static void report_invalid_user(const struct mansession *s, const char *username)
2634 char session_id[32];
2635 struct ast_security_event_inval_acct_id inval_acct_id = {
2636 .common.event_type = AST_SECURITY_EVENT_INVAL_ACCT_ID,
2637 .common.version = AST_SECURITY_EVENT_INVAL_ACCT_ID_VERSION,
2638 .common.service = "AMI",
2639 .common.account_id = username,
2640 .common.session_tv = &s->session->sessionstart_tv,
2641 .common.local_addr = {
2642 .addr = &s->tcptls_session->parent->local_address,
2643 .transport = mansession_get_transport(s),
2645 .common.remote_addr = {
2646 .addr = &s->session->addr,
2647 .transport = mansession_get_transport(s),
2649 .common.session_id = session_id,
2652 snprintf(session_id, sizeof(session_id), "%p", s);
2654 ast_security_event_report(AST_SEC_EVT(&inval_acct_id));
2657 static void report_failed_acl(const struct mansession *s, const char *username)
2659 char session_id[32];
2660 struct ast_security_event_failed_acl failed_acl_event = {
2661 .common.event_type = AST_SECURITY_EVENT_FAILED_ACL,
2662 .common.version = AST_SECURITY_EVENT_FAILED_ACL_VERSION,
2663 .common.service = "AMI",
2664 .common.account_id = username,
2665 .common.session_tv = &s->session->sessionstart_tv,
2666 .common.local_addr = {
2667 .addr = &s->tcptls_session->parent->local_address,
2668 .transport = mansession_get_transport(s),
2670 .common.remote_addr = {
2671 .addr = &s->session->addr,
2672 .transport = mansession_get_transport(s),
2674 .common.session_id = session_id,
2677 snprintf(session_id, sizeof(session_id), "%p", s->session);
2679 ast_security_event_report(AST_SEC_EVT(&failed_acl_event));
2682 static void report_inval_password(const struct mansession *s, const char *username)
2684 char session_id[32];
2685 struct ast_security_event_inval_password inval_password = {
2686 .common.event_type = AST_SECURITY_EVENT_INVAL_PASSWORD,
2687 .common.version = AST_SECURITY_EVENT_INVAL_PASSWORD_VERSION,
2688 .common.service = "AMI",
2689 .common.account_id = username,
2690 .common.session_tv = &s->session->sessionstart_tv,
2691 .common.local_addr = {
2692 .addr = &s->tcptls_session->parent->local_address,
2693 .transport = mansession_get_transport(s),
2695 .common.remote_addr = {
2696 .addr = &s->session->addr,
2697 .transport = mansession_get_transport(s),
2699 .common.session_id = session_id,
2702 snprintf(session_id, sizeof(session_id), "%p", s->session);
2704 ast_security_event_report(AST_SEC_EVT(&inval_password));
2707 static void report_auth_success(const struct mansession *s)
2709 char session_id[32];
2710 struct ast_security_event_successful_auth successful_auth = {
2711 .common.event_type = AST_SECURITY_EVENT_SUCCESSFUL_AUTH,
2712 .common.version = AST_SECURITY_EVENT_SUCCESSFUL_AUTH_VERSION,
2713 .common.service = "AMI",
2714 .common.account_id = s->session->username,
2715 .common.session_tv = &s->session->sessionstart_tv,
2716 .common.local_addr = {
2717 .addr = &s->tcptls_session->parent->local_address,
2718 .transport = mansession_get_transport(s),
2720 .common.remote_addr = {
2721 .addr = &s->session->addr,
2722 .transport = mansession_get_transport(s),
2724 .common.session_id = session_id,
2727 snprintf(session_id, sizeof(session_id), "%p", s->session);
2729 ast_security_event_report(AST_SEC_EVT(&successful_auth));
2732 static void report_req_not_allowed(const struct mansession *s, const char *action)
2734 char session_id[32];
2735 char request_type[64];
2736 struct ast_security_event_req_not_allowed req_not_allowed = {
2737 .common.event_type = AST_SECURITY_EVENT_REQ_NOT_ALLOWED,
2738 .common.version = AST_SECURITY_EVENT_REQ_NOT_ALLOWED_VERSION,
2739 .common.service = "AMI",
2740 .common.account_id = s->session->username,
2741 .common.session_tv = &s->session->sessionstart_tv,
2742 .common.local_addr = {
2743 .addr = &s->tcptls_session->parent->local_address,
2744 .transport = mansession_get_transport(s),
2746 .common.remote_addr = {
2747 .addr = &s->session->addr,
2748 .transport = mansession_get_transport(s),
2750 .common.session_id = session_id,
2752 .request_type = request_type,
2755 snprintf(session_id, sizeof(session_id), "%p", s->session);
2756 snprintf(request_type, sizeof(request_type), "Action: %s", action);
2758 ast_security_event_report(AST_SEC_EVT(&req_not_allowed));
2761 static void report_req_bad_format(const struct mansession *s, const char *action)
2763 char session_id[32];
2764 char request_type[64];
2765 struct ast_security_event_req_bad_format req_bad_format = {
2766 .common.event_type = AST_SECURITY_EVENT_REQ_BAD_FORMAT,
2767 .common.version = AST_SECURITY_EVENT_REQ_BAD_FORMAT_VERSION,
2768 .common.service = "AMI",
2769 .common.account_id = s->session->username,
2770 .common.session_tv = &s->session->sessionstart_tv,
2771 .common.local_addr = {
2772 .addr = &s->tcptls_session->parent->local_address,
2773 .transport = mansession_get_transport(s),
2775 .common.remote_addr = {
2776 .addr = &s->session->addr,
2777 .transport = mansession_get_transport(s),
2779 .common.session_id = session_id,
2781 .request_type = request_type,
2784 snprintf(session_id, sizeof(session_id), "%p", s->session);
2785 snprintf(request_type, sizeof(request_type), "Action: %s", action);
2787 ast_security_event_report(AST_SEC_EVT(&req_bad_format));
2790 static void report_failed_challenge_response(const struct mansession *s,
2791 const char *response, const char *expected_response)
2793 char session_id[32];
2794 struct ast_security_event_chal_resp_failed chal_resp_failed = {
2795 .common.event_type = AST_SECURITY_EVENT_CHAL_RESP_FAILED,
2796 .common.version = AST_SECURITY_EVENT_CHAL_RESP_FAILED_VERSION,
2797 .common.service = "AMI",
2798 .common.account_id = s->session->username,
2799 .common.session_tv = &s->session->sessionstart_tv,
2800 .common.local_addr = {
2801 .addr = &s->tcptls_session->parent->local_address,
2802 .transport = mansession_get_transport(s),
2804 .common.remote_addr = {
2805 .addr = &s->session->addr,
2806 .transport = mansession_get_transport(s),
2808 .common.session_id = session_id,
2810 .challenge = s->session->challenge,
2811 .response = response,
2812 .expected_response = expected_response,
2815 snprintf(session_id, sizeof(session_id), "%p", s->session);
2817 ast_security_event_report(AST_SEC_EVT(&chal_resp_failed));
2820 static void report_session_limit(const struct mansession *s)
2822 char session_id[32];
2823 struct ast_security_event_session_limit session_limit = {
2824 .common.event_type = AST_SECURITY_EVENT_SESSION_LIMIT,
2825 .common.version = AST_SECURITY_EVENT_SESSION_LIMIT_VERSION,
2826 .common.service = "AMI",
2827 .common.account_id = s->session->username,
2828 .common.session_tv = &s->session->sessionstart_tv,
2829 .common.local_addr = {
2830 .addr = &s->tcptls_session->parent->local_address,
2831 .transport = mansession_get_transport(s),
2833 .common.remote_addr = {
2834 .addr = &s->session->addr,
2835 .transport = mansession_get_transport(s),
2837 .common.session_id = session_id,
2840 snprintf(session_id, sizeof(session_id), "%p", s->session);
2842 ast_security_event_report(AST_SEC_EVT(&session_limit));
2846 * Here we start with action_ handlers for AMI actions,
2847 * and the internal functions used by them.
2848 * Generally, the handlers are called action_foo()
2851 /* helper function for action_login() */
2852 static int authenticate(struct mansession *s, const struct message *m)
2854 const char *username = astman_get_header(m, "Username");
2855 const char *password = astman_get_header(m, "Secret");
2857 struct ast_manager_user *user = NULL;
2858 regex_t *regex_filter;
2859 struct ao2_iterator filter_iter;
2861 if (ast_strlen_zero(username)) { /* missing username */
2865 /* locate user in locked state */
2866 AST_RWLIST_WRLOCK(&users);
2868 if (!(user = get_manager_by_name_locked(username))) {
2869 report_invalid_user(s, username);
2870 ast_log(LOG_NOTICE, "%s tried to authenticate with nonexistent user '%s'\n", ast_sockaddr_stringify_addr(&s->session->addr), username);
2871 } else if (user->acl && (ast_apply_acl(user->acl, &s->session->addr, "Manager User ACL: ") == AST_SENSE_DENY)) {
2872 report_failed_acl(s, username);
2873 ast_log(LOG_NOTICE, "%s failed to pass IP ACL as '%s'\n", ast_sockaddr_stringify_addr(&s->session->addr), username);
2874 } else if (!strcasecmp(astman_get_header(m, "AuthType"), "MD5")) {
2875 const char *key = astman_get_header(m, "Key");
2876 if (!ast_strlen_zero(key) && !ast_strlen_zero(s->session->challenge) && user->secret) {
2879 char md5key[256] = "";
2880 struct MD5Context md5;
2881 unsigned char digest[16];
2884 MD5Update(&md5, (unsigned char *) s->session->challenge, strlen(s->session->challenge));
2885 MD5Update(&md5, (unsigned char *) user->secret, strlen(user->secret));
2886 MD5Final(digest, &md5);
2887 for (x = 0; x < 16; x++)
2888 len += sprintf(md5key + len, "%2.2x", digest[x]);
2889 if (!strcmp(md5key, key)) {
2892 report_failed_challenge_response(s, key, md5key);
2895 ast_debug(1, "MD5 authentication is not possible. challenge: '%s'\n",
2896 S_OR(s->session->challenge, ""));
2898 } else if (user->secret) {
2899 if (!strcmp(password, user->secret)) {
2902 report_inval_password(s, username);
2907 ast_log(LOG_NOTICE, "%s failed to authenticate as '%s'\n", ast_sockaddr_stringify_addr(&s->session->addr), username);
2908 AST_RWLIST_UNLOCK(&users);
2914 /* All of the user parameters are copied to the session so that in the event
2915 * of a reload and a configuration change, the session parameters are not
2917 ast_copy_string(s->session->username, username, sizeof(s->session->username));
2918 s->session->readperm = user->readperm;
2919 s->session->writeperm = user->writeperm;
2920 s->session->writetimeout = user->writetimeout;
2921 if (user->chanvars) {
2922 s->session->chanvars = ast_variables_dup(user->chanvars);
2925 filter_iter = ao2_iterator_init(user->whitefilters, 0);
2926 while ((regex_filter = ao2_iterator_next(&filter_iter))) {
2927 ao2_t_link(s->session->whitefilters, regex_filter, "add white user filter to session");
2928 ao2_t_ref(regex_filter, -1, "remove iterator ref");
2930 ao2_iterator_destroy(&filter_iter);
2932 filter_iter = ao2_iterator_init(user->blackfilters, 0);
2933 while ((regex_filter = ao2_iterator_next(&filter_iter))) {
2934 ao2_t_link(s->session->blackfilters, regex_filter, "add black user filter to session");
2935 ao2_t_ref(regex_filter, -1, "remove iterator ref");
2937 ao2_iterator_destroy(&filter_iter);
2939 s->session->sessionstart = time(NULL);
2940 s->session->sessionstart_tv = ast_tvnow();
2941 set_eventmask(s, astman_get_header(m, "Events"));
2943 report_auth_success(s);
2945 AST_RWLIST_UNLOCK(&users);
2949 static int action_ping(struct mansession *s, const struct message *m)
2951 const char *actionid = astman_get_header(m, "ActionID");
2952 struct timeval now = ast_tvnow();
2954 astman_append(s, "Response: Success\r\n");
2955 if (!ast_strlen_zero(actionid)){
2956 astman_append(s, "ActionID: %s\r\n", actionid);
2961 "Timestamp: %ld.%06lu\r\n"
2963 (long) now.tv_sec, (unsigned long) now.tv_usec);
2967 static int action_getconfig(struct mansession *s, const struct message *m)
2969 struct ast_config *cfg;
2970 const char *fn = astman_get_header(m, "Filename");
2971 const char *category = astman_get_header(m, "Category");
2974 char *cur_category = NULL;
2975 struct ast_variable *v;
2976 struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
2978 if (ast_strlen_zero(fn)) {
2979 astman_send_error(s, m, "Filename not specified");
2982 cfg = ast_config_load2(fn, "manager", config_flags);
2983 if (cfg == CONFIG_STATUS_FILEMISSING) {
2984 astman_send_error(s, m, "Config file not found");
2986 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
2987 astman_send_error(s, m, "Config file has invalid format");
2991 astman_start_ack(s, m);
2992 while ((cur_category = ast_category_browse(cfg, cur_category))) {
2993 if (ast_strlen_zero(category) || (!ast_strlen_zero(category) && !strcmp(category, cur_category))) {
2995 astman_append(s, "Category-%06d: %s\r\n", catcount, cur_category);
2996 for (v = ast_variable_browse(cfg, cur_category); v; v = v->next) {
2997 astman_append(s, "Line-%06d-%06d: %s=%s\r\n", catcount, lineno++, v->name, v->value);
3002 if (!ast_strlen_zero(category) && catcount == 0) { /* TODO: actually, a config with no categories doesn't even get loaded */
3003 astman_append(s, "No categories found\r\n");
3005 ast_config_destroy(cfg);
3006 astman_append(s, "\r\n");
3011 static int action_listcategories(struct mansession *s, const struct message *m)
3013 struct ast_config *cfg;
3014 const char *fn = astman_get_header(m, "Filename");
3015 char *category = NULL;
3016 struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
3019 if (ast_strlen_zero(fn)) {
3020 astman_send_error(s, m, "Filename not specified");
3023 if (!(cfg = ast_config_load2(fn, "manager", config_flags))) {
3024 astman_send_error(s, m, "Config file not found");
3026 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
3027 astman_send_error(s, m, "Config file has invalid format");
3030 astman_start_ack(s, m);
3031 while ((category = ast_category_browse(cfg, category))) {
3032 astman_append(s, "Category-%06d: %s\r\n", catcount, category);