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/event.h"
91 #include "asterisk/aoc.h"
92 #include "asterisk/strings.h"
93 #include "asterisk/stringfields.h"
94 #include "asterisk/presencestate.h"
95 #include "asterisk/stasis.h"
96 #include "asterisk/stasis_message_router.h"
97 #include "asterisk/test.h"
98 #include "asterisk/json.h"
99 #include "asterisk/bridging.h"
100 #include "asterisk/features_config.h"
103 <manager name="Ping" language="en_US">
108 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
111 <para>A 'Ping' action will ellicit a 'Pong' response. Used to keep the
112 manager connection open.</para>
115 <manager name="Events" language="en_US">
120 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
121 <parameter name="EventMask" required="true">
124 <para>If all events should be sent.</para>
127 <para>If no events should be sent.</para>
129 <enum name="system,call,log,...">
130 <para>To select which flags events should have to be sent.</para>
136 <para>Enable/Disable sending of events to this manager client.</para>
139 <manager name="Logoff" language="en_US">
144 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
147 <para>Logoff the current manager session.</para>
150 <manager name="Login" language="en_US">
155 <parameter name="ActionID">
156 <para>ActionID for this transaction. Will be returned.</para>
158 <parameter name="Username" required="true">
159 <para>Username to login with as specified in manager.conf.</para>
161 <parameter name="Secret">
162 <para>Secret to login with as specified in manager.conf.</para>
166 <para>Login Manager.</para>
169 <manager name="Challenge" language="en_US">
171 Generate Challenge for MD5 Auth.
174 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
175 <parameter name="AuthType" required="true">
176 <para>Digest algorithm to use in the challenge. Valid values are:</para>
183 <para>Generate a challenge for MD5 authentication.</para>
186 <manager name="Hangup" language="en_US">
191 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
192 <parameter name="Channel" required="true">
193 <para>The exact channel name to be hungup, or to use a regular expression, set this parameter to: /regex/</para>
194 <para>Example exact channel: SIP/provider-0000012a</para>
195 <para>Example regular expression: /^SIP/provider-.*$/</para>
197 <parameter name="Cause">
198 <para>Numeric hangup cause.</para>
202 <para>Hangup a channel.</para>
205 <manager name="Status" language="en_US">
210 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
211 <parameter name="Channel" required="true">
212 <para>The name of the channel to query for status.</para>
214 <parameter name="Variables">
215 <para>Comma <literal>,</literal> separated list of variable to include.</para>
219 <para>Will return the status information of each channel along with the
220 value for the specified channel variables.</para>
223 <manager name="Setvar" language="en_US">
225 Set a channel variable.
228 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
229 <parameter name="Channel">
230 <para>Channel to set variable for.</para>
232 <parameter name="Variable" required="true">
233 <para>Variable name.</para>
235 <parameter name="Value" required="true">
236 <para>Variable value.</para>
240 <para>Set a global or local channel variable.</para>
242 <para>If a channel name is not provided then the variable is global.</para>
246 <manager name="Getvar" language="en_US">
248 Gets a channel variable.
251 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
252 <parameter name="Channel">
253 <para>Channel to read variable from.</para>
255 <parameter name="Variable" required="true">
256 <para>Variable name.</para>
260 <para>Get the value of a global or local channel variable.</para>
262 <para>If a channel name is not provided then the variable is global.</para>
266 <manager name="GetConfig" language="en_US">
268 Retrieve configuration.
271 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
272 <parameter name="Filename" required="true">
273 <para>Configuration filename (e.g. <filename>foo.conf</filename>).</para>
275 <parameter name="Category">
276 <para>Category in configuration file.</para>
280 <para>This action will dump the contents of a configuration
281 file by category and contents or optionally by specified category only.</para>
284 <manager name="GetConfigJSON" language="en_US">
286 Retrieve configuration (JSON format).
289 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
290 <parameter name="Filename" required="true">
291 <para>Configuration filename (e.g. <filename>foo.conf</filename>).</para>
295 <para>This action will dump the contents of a configuration file by category
296 and contents in JSON format. This only makes sense to be used using rawman over
297 the HTTP interface.</para>
300 <manager name="UpdateConfig" language="en_US">
302 Update basic configuration.
305 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
306 <parameter name="SrcFilename" required="true">
307 <para>Configuration filename to read (e.g. <filename>foo.conf</filename>).</para>
309 <parameter name="DstFilename" required="true">
310 <para>Configuration filename to write (e.g. <filename>foo.conf</filename>)</para>
312 <parameter name="Reload">
313 <para>Whether or not a reload should take place (or name of specific module).</para>
315 <parameter name="Action-XXXXXX">
316 <para>Action to take.</para>
317 <para>X's represent 6 digit number beginning with 000000.</para>
319 <enum name="NewCat" />
320 <enum name="RenameCat" />
321 <enum name="DelCat" />
322 <enum name="EmptyCat" />
323 <enum name="Update" />
324 <enum name="Delete" />
325 <enum name="Append" />
326 <enum name="Insert" />
329 <parameter name="Cat-XXXXXX">
330 <para>Category to operate on.</para>
331 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-XXXXXX']/para[2])" />
333 <parameter name="Var-XXXXXX">
334 <para>Variable to work on.</para>
335 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-XXXXXX']/para[2])" />
337 <parameter name="Value-XXXXXX">
338 <para>Value to work on.</para>
339 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-XXXXXX']/para[2])" />
341 <parameter name="Match-XXXXXX">
342 <para>Extra match required to match line.</para>
343 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-XXXXXX']/para[2])" />
345 <parameter name="Line-XXXXXX">
346 <para>Line in category to operate on (used with delete and insert actions).</para>
347 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-XXXXXX']/para[2])" />
351 <para>This action will modify, create, or delete configuration elements
352 in Asterisk configuration files.</para>
355 <manager name="CreateConfig" language="en_US">
357 Creates an empty file in the configuration directory.
360 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
361 <parameter name="Filename" required="true">
362 <para>The configuration filename to create (e.g. <filename>foo.conf</filename>).</para>
366 <para>This action will create an empty file in the configuration
367 directory. This action is intended to be used before an UpdateConfig
371 <manager name="ListCategories" language="en_US">
373 List categories in configuration file.
376 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
377 <parameter name="Filename" required="true">
378 <para>Configuration filename (e.g. <filename>foo.conf</filename>).</para>
382 <para>This action will dump the categories in a given file.</para>
385 <manager name="Redirect" language="en_US">
387 Redirect (transfer) a call.
390 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
391 <parameter name="Channel" required="true">
392 <para>Channel to redirect.</para>
394 <parameter name="ExtraChannel">
395 <para>Second call leg to transfer (optional).</para>
397 <parameter name="Exten" required="true">
398 <para>Extension to transfer to.</para>
400 <parameter name="ExtraExten">
401 <para>Extension to transfer extrachannel to (optional).</para>
403 <parameter name="Context" required="true">
404 <para>Context to transfer to.</para>
406 <parameter name="ExtraContext">
407 <para>Context to transfer extrachannel to (optional).</para>
409 <parameter name="Priority" required="true">
410 <para>Priority to transfer to.</para>
412 <parameter name="ExtraPriority">
413 <para>Priority to transfer extrachannel to (optional).</para>
417 <para>Redirect (transfer) a call.</para>
420 <manager name="Atxfer" language="en_US">
425 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
426 <parameter name="Channel" required="true">
427 <para>Transferer's channel.</para>
429 <parameter name="Exten" required="true">
430 <para>Extension to transfer to.</para>
432 <parameter name="Context" required="true">
433 <para>Context to transfer to.</para>
435 <parameter name="Priority" required="true">
436 <para>Priority to transfer to.</para>
440 <para>Attended transfer.</para>
443 <manager name="Originate" language="en_US">
448 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
449 <parameter name="Channel" required="true">
450 <para>Channel name to call.</para>
452 <parameter name="Exten">
453 <para>Extension to use (requires <literal>Context</literal> and
454 <literal>Priority</literal>)</para>
456 <parameter name="Context">
457 <para>Context to use (requires <literal>Exten</literal> and
458 <literal>Priority</literal>)</para>
460 <parameter name="Priority">
461 <para>Priority to use (requires <literal>Exten</literal> and
462 <literal>Context</literal>)</para>
464 <parameter name="Application">
465 <para>Application to execute.</para>
467 <parameter name="Data">
468 <para>Data to use (requires <literal>Application</literal>).</para>
470 <parameter name="Timeout" default="30000">
471 <para>How long to wait for call to be answered (in ms.).</para>
473 <parameter name="CallerID">
474 <para>Caller ID to be set on the outgoing channel.</para>
476 <parameter name="Variable">
477 <para>Channel variable to set, multiple Variable: headers are allowed.</para>
479 <parameter name="Account">
480 <para>Account code.</para>
482 <parameter name="EarlyMedia">
483 <para>Set to <literal>true</literal> to force call bridge on early media..</para>
485 <parameter name="Async">
486 <para>Set to <literal>true</literal> for fast origination.</para>
488 <parameter name="Codecs">
489 <para>Comma-separated list of codecs to use for this call.</para>
493 <para>Generates an outgoing call to a
494 <replaceable>Extension</replaceable>/<replaceable>Context</replaceable>/<replaceable>Priority</replaceable>
495 or <replaceable>Application</replaceable>/<replaceable>Data</replaceable></para>
498 <ref type="managerEvent">OriginateResponse</ref>
501 <managerEvent language="en_US" name="OriginateResponse">
502 <managerEventInstance class="EVENT_FLAG_CALL">
503 <synopsis>Raised in response to an Originate command.</synopsis>
505 <parameter name="ActionID" required="false"/>
506 <parameter name="Resonse">
508 <enum name="Failure"/>
509 <enum name="Success"/>
512 <parameter name="Channel"/>
513 <parameter name="Context"/>
514 <parameter name="Exten"/>
515 <parameter name="Reason"/>
516 <parameter name="Uniqueid"/>
517 <parameter name="CallerIDNum"/>
518 <parameter name="CallerIDName"/>
521 <ref type="manager">Originate</ref>
523 </managerEventInstance>
525 <manager name="Command" language="en_US">
527 Execute Asterisk CLI Command.
530 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
531 <parameter name="Command" required="true">
532 <para>Asterisk CLI command to run.</para>
536 <para>Run a CLI command.</para>
539 <manager name="ExtensionState" language="en_US">
541 Check Extension Status.
544 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
545 <parameter name="Exten" required="true">
546 <para>Extension to check state on.</para>
548 <parameter name="Context" required="true">
549 <para>Context for extension.</para>
553 <para>Report the extension state for given extension. If the extension has a hint,
554 will use devicestate to check the status of the device connected to the extension.</para>
555 <para>Will return an <literal>Extension Status</literal> message. The response will include
556 the hint for the extension and the status.</para>
559 <manager name="PresenceState" language="en_US">
564 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
565 <parameter name="Provider" required="true">
566 <para>Presence Provider to check the state of</para>
570 <para>Report the presence state for the given presence provider.</para>
571 <para>Will return a <literal>Presence State</literal> message. The response will include the
572 presence state and, if set, a presence subtype and custom message.</para>
575 <manager name="AbsoluteTimeout" language="en_US">
577 Set absolute timeout.
580 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
581 <parameter name="Channel" required="true">
582 <para>Channel name to hangup.</para>
584 <parameter name="Timeout" required="true">
585 <para>Maximum duration of the call (sec).</para>
589 <para>Hangup a channel after a certain time. Acknowledges set time with
590 <literal>Timeout Set</literal> message.</para>
593 <manager name="MailboxStatus" language="en_US">
598 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
599 <parameter name="Mailbox" required="true">
600 <para>Full mailbox ID <replaceable>mailbox</replaceable>@<replaceable>vm-context</replaceable>.</para>
604 <para>Checks a voicemail account for status.</para>
605 <para>Returns whether there are messages waiting.</para>
606 <para>Message: Mailbox Status.</para>
607 <para>Mailbox: <replaceable>mailboxid</replaceable>.</para>
608 <para>Waiting: <literal>0</literal> if messages waiting, <literal>1</literal>
609 if no messages waiting.</para>
612 <manager name="MailboxCount" language="en_US">
614 Check Mailbox Message Count.
617 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
618 <parameter name="Mailbox" required="true">
619 <para>Full mailbox ID <replaceable>mailbox</replaceable>@<replaceable>vm-context</replaceable>.</para>
623 <para>Checks a voicemail account for new messages.</para>
624 <para>Returns number of urgent, new and old messages.</para>
625 <para>Message: Mailbox Message Count</para>
626 <para>Mailbox: <replaceable>mailboxid</replaceable></para>
627 <para>UrgentMessages: <replaceable>count</replaceable></para>
628 <para>NewMessages: <replaceable>count</replaceable></para>
629 <para>OldMessages: <replaceable>count</replaceable></para>
632 <manager name="ListCommands" language="en_US">
634 List available manager commands.
637 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
640 <para>Returns the action name and synopsis for every action that
641 is available to the user.</para>
644 <manager name="SendText" language="en_US">
646 Send text message to channel.
649 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
650 <parameter name="Channel" required="true">
651 <para>Channel to send message to.</para>
653 <parameter name="Message" required="true">
654 <para>Message to send.</para>
658 <para>Sends A Text Message to a channel while in a call.</para>
661 <manager name="UserEvent" language="en_US">
663 Send an arbitrary event.
666 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
667 <parameter name="UserEvent" required="true">
668 <para>Event string to send.</para>
670 <parameter name="Header1">
671 <para>Content1.</para>
673 <parameter name="HeaderN">
674 <para>ContentN.</para>
678 <para>Send an event to manager sessions.</para>
681 <manager name="WaitEvent" language="en_US">
683 Wait for an event to occur.
686 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
687 <parameter name="Timeout" required="true">
688 <para>Maximum time (in seconds) to wait for events, <literal>-1</literal> means forever.</para>
692 <para>This action will ellicit a <literal>Success</literal> response. Whenever
693 a manager event is queued. Once WaitEvent has been called on an HTTP manager
694 session, events will be generated and queued.</para>
697 <manager name="CoreSettings" language="en_US">
699 Show PBX core settings (version etc).
702 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
705 <para>Query for Core PBX settings.</para>
708 <manager name="CoreStatus" language="en_US">
710 Show PBX core status variables.
713 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
716 <para>Query for Core PBX status.</para>
719 <manager name="Reload" language="en_US">
724 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
725 <parameter name="Module">
726 <para>Name of the module to reload.</para>
730 <para>Send a reload event.</para>
733 <manager name="CoreShowChannels" language="en_US">
735 List currently active channels.
738 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
741 <para>List currently defined channels and some information about them.</para>
744 <manager name="ModuleLoad" language="en_US">
749 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
750 <parameter name="Module">
751 <para>Asterisk module name (including .so extension) or subsystem identifier:</para>
754 <enum name="dnsmgr" />
755 <enum name="extconfig" />
758 <enum name="manager" />
760 <enum name="logger" />
761 <enum name="features" />
763 <enum name="udptl" />
764 <enum name="indications" />
769 <parameter name="LoadType" required="true">
770 <para>The operation to be done on module. Subsystem identifiers may only
774 <enum name="unload" />
775 <enum name="reload" />
777 <para>If no module is specified for a <literal>reload</literal> loadtype,
778 all modules are reloaded.</para>
782 <para>Loads, unloads or reloads an Asterisk module in a running system.</para>
785 <manager name="ModuleCheck" language="en_US">
787 Check if module is loaded.
790 <parameter name="Module" required="true">
791 <para>Asterisk module name (not including extension).</para>
795 <para>Checks if Asterisk module is loaded. Will return Success/Failure.
796 For success returns, the module revision number is included.</para>
799 <manager name="AOCMessage" language="en_US">
801 Generate an Advice of Charge message on a channel.
804 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
805 <parameter name="Channel" required="true">
806 <para>Channel name to generate the AOC message on.</para>
808 <parameter name="ChannelPrefix">
809 <para>Partial channel prefix. By using this option one can match the beginning part
810 of a channel name without having to put the entire name in. For example
811 if a channel name is SIP/snom-00000001 and this value is set to SIP/snom, then
812 that channel matches and the message will be sent. Note however that only
813 the first matched channel has the message sent on it. </para>
815 <parameter name="MsgType" required="true">
816 <para>Defines what type of AOC message to create, AOC-D or AOC-E</para>
822 <parameter name="ChargeType" required="true">
823 <para>Defines what kind of charge this message represents.</para>
827 <enum name="Currency" />
831 <parameter name="UnitAmount(0)">
832 <para>This represents the amount of units charged. The ETSI AOC standard specifies that
833 this value along with the optional UnitType value are entries in a list. To accommodate this
834 these values take an index value starting at 0 which can be used to generate this list of
835 unit entries. For Example, If two unit entires were required this could be achieved by setting the
836 paramter UnitAmount(0)=1234 and UnitAmount(1)=5678. Note that UnitAmount at index 0 is
837 required when ChargeType=Unit, all other entries in the list are optional.
840 <parameter name="UnitType(0)">
841 <para>Defines the type of unit. ETSI AOC standard specifies this as an integer
842 value between 1 and 16, but this value is left open to accept any positive
843 integer. Like the UnitAmount parameter, this value represents a list entry
844 and has an index parameter that starts at 0.
847 <parameter name="CurrencyName">
848 <para>Specifies the currency's name. Note that this value is truncated after 10 characters.</para>
850 <parameter name="CurrencyAmount">
851 <para>Specifies the charge unit amount as a positive integer. This value is required
852 when ChargeType==Currency.</para>
854 <parameter name="CurrencyMultiplier">
855 <para>Specifies the currency multiplier. This value is required when ChargeType==Currency.</para>
857 <enum name="OneThousandth" />
858 <enum name="OneHundredth" />
859 <enum name="OneTenth" />
862 <enum name="Hundred" />
863 <enum name="Thousand" />
866 <parameter name="TotalType" default="Total">
867 <para>Defines what kind of AOC-D total is represented.</para>
869 <enum name="Total" />
870 <enum name="SubTotal" />
873 <parameter name="AOCBillingId">
874 <para>Represents a billing ID associated with an AOC-D or AOC-E message. Note
875 that only the first 3 items of the enum are valid AOC-D billing IDs</para>
877 <enum name="Normal" />
878 <enum name="ReverseCharge" />
879 <enum name="CreditCard" />
880 <enum name="CallFwdUnconditional" />
881 <enum name="CallFwdBusy" />
882 <enum name="CallFwdNoReply" />
883 <enum name="CallDeflection" />
884 <enum name="CallTransfer" />
887 <parameter name="ChargingAssociationId">
888 <para>Charging association identifier. This is optional for AOC-E and can be
889 set to any value between -32768 and 32767</para>
891 <parameter name="ChargingAssociationNumber">
892 <para>Represents the charging association party number. This value is optional
895 <parameter name="ChargingAssociationPlan">
896 <para>Integer representing the charging plan associated with the ChargingAssociationNumber.
897 The value is bits 7 through 1 of the Q.931 octet containing the type-of-number and
898 numbering-plan-identification fields.</para>
902 <para>Generates an AOC-D or AOC-E message on a channel.</para>
905 <function name="AMI_CLIENT" language="en_US">
907 Checks attributes of manager accounts
910 <parameter name="loginname" required="true">
911 <para>Login name, specified in manager.conf</para>
913 <parameter name="field" required="true">
914 <para>The manager account attribute to return</para>
916 <enum name="sessions"><para>The number of sessions for this AMI account</para></enum>
922 Currently, the only supported parameter is "sessions" which will return the current number of
923 active sessions for this AMI account.
927 <manager name="Filter" language="en_US">
929 Dynamically add filters for the current manager session.
932 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
933 <parameter name="Operation">
936 <para>Add a filter.</para>
940 <parameter name="Filter">
941 <para>Filters can be whitelist or blacklist</para>
942 <para>Example whitelist filter: "Event: Newchannel"</para>
943 <para>Example blacklist filter: "!Channel: DAHDI.*"</para>
944 <para>This filter option is used to whitelist or blacklist events per user to be
945 reported with regular expressions and are allowed if both the regex matches
946 and the user has read access as defined in manager.conf. Filters are assumed to be for whitelisting
947 unless preceeded by an exclamation point, which marks it as being black.
948 Evaluation of the filters is as follows:</para>
949 <para>- If no filters are configured all events are reported as normal.</para>
950 <para>- If there are white filters only: implied black all filter processed first, then white filters.</para>
951 <para>- If there are black filters only: implied white all filter processed first, then black filters.</para>
952 <para>- If there are both white and black filters: implied black all filter processed first, then white
953 filters, and lastly black filters.</para>
957 <para>The filters added are only used for the current session.
958 Once the connection is closed the filters are removed.</para>
959 <para>This comand requires the system permission because
960 this command can be used to create filters that may bypass
961 filters defined in manager.conf</para>
964 <manager name="FilterList" language="en_US">
966 Show current event filters for this session
969 <para>The filters displayed are for the current session. Only those filters defined in
970 manager.conf will be present upon starting a new session.</para>
973 <manager name="BlindTransfer" language="en_US">
975 Blind transfer channel(s) to the given destination
978 <parameter name="Channel" required="true">
980 <parameter name="Context">
982 <parameter name="Exten">
986 <para>Redirect all channels currently bridged to the specified channel to the specified destination.</para>
989 <ref type="manager">Redirect</ref>
994 /*! \addtogroup Group_AMI AMI functions
1002 UNSPECIFIED_CATEGORY,
1003 UNSPECIFIED_ARGUMENT,
1013 enum add_filter_result {
1015 FILTER_ALLOC_FAILED,
1016 FILTER_COMPILE_FAIL,
1020 * Linked list of events.
1021 * Global events are appended to the list by append_event().
1022 * The usecount is the number of stored pointers to the element,
1023 * excluding the list pointers. So an element that is only in
1024 * the list has a usecount of 0, not 1.
1026 * Clients have a pointer to the last event processed, and for each
1027 * of these clients we track the usecount of the elements.
1028 * If we have a pointer to an entry in the list, it is safe to navigate
1029 * it forward because elements will not be deleted, but only appended.
1030 * The worst that can happen is seeing the pointer still NULL.
1032 * When the usecount of an element drops to 0, and the element is the
1033 * first in the list, we can remove it. Removal is done within the
1034 * main thread, which is woken up for the purpose.
1036 * For simplicity of implementation, we make sure the list is never empty.
1039 int usecount; /*!< # of clients who still need the event */
1041 unsigned int seq; /*!< sequence number */
1042 struct timeval tv; /*!< When event was allocated */
1043 AST_RWLIST_ENTRY(eventqent) eq_next;
1044 char eventdata[1]; /*!< really variable size, allocated by append_event() */
1047 static AST_RWLIST_HEAD_STATIC(all_events, eventqent);
1049 static int displayconnects = 1;
1050 static int allowmultiplelogin = 1;
1051 static int timestampevents;
1052 static int httptimeout = 60;
1053 static int broken_events_action = 0;
1054 static int manager_enabled = 0;
1055 static int webmanager_enabled = 0;
1056 static int manager_debug = 0; /*!< enable some debugging code in the manager */
1057 static int authtimeout;
1058 static int authlimit;
1059 static char *manager_channelvars;
1061 #define DEFAULT_REALM "asterisk"
1062 static char global_realm[MAXHOSTNAMELEN]; /*!< Default realm */
1064 static int block_sockets;
1065 static int unauth_sessions = 0;
1066 static struct stasis_subscription *acl_change_sub;
1068 /*! \brief A \ref stasis_topic that all topics AMI cares about will be forwarded to */
1069 static struct stasis_topic *manager_topic;
1071 /*! \brief The \ref stasis_message_router for all \ref stasis messages */
1072 static struct stasis_message_router *stasis_router;
1074 #define MGR_SHOW_TERMINAL_WIDTH 80
1076 #define MAX_VARS 128
1079 * Descriptor for a manager session, either on the AMI socket or over HTTP.
1082 * AMI session have managerid == 0; the entry is created upon a connect,
1083 * and destroyed with the socket.
1084 * HTTP sessions have managerid != 0, the value is used as a search key
1085 * to lookup sessions (using the mansession_id cookie, or nonce key from
1086 * Digest Authentication http header).
1088 #define MAX_BLACKLIST_CMD_LEN 2
1089 static const struct {
1090 const char *words[AST_MAX_CMD_LEN];
1091 } command_blacklist[] = {
1092 {{ "module", "load", NULL }},
1093 {{ "module", "unload", NULL }},
1094 {{ "restart", "gracefully", NULL }},
1097 static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_topic *topic, struct stasis_message *message);
1099 static void acl_change_stasis_subscribe(void)
1101 if (!acl_change_sub) {
1102 acl_change_sub = stasis_subscribe(ast_security_topic(),
1103 acl_change_stasis_cb, NULL);
1107 static void acl_change_stasis_unsubscribe(void)
1109 acl_change_sub = stasis_unsubscribe_and_join(acl_change_sub);
1112 /* In order to understand what the heck is going on with the
1113 * mansession_session and mansession structs, we need to have a bit of a history
1116 * In the beginning, there was the mansession. The mansession contained data that was
1117 * intrinsic to a manager session, such as the time that it started, the name of the logged-in
1118 * user, etc. In addition to these parameters were the f and fd parameters. For typical manager
1119 * sessions, these were used to represent the TCP socket over which the AMI session was taking
1120 * place. It makes perfect sense for these fields to be a part of the session-specific data since
1121 * the session actually defines this information.
1123 * Then came the HTTP AMI sessions. With these, the f and fd fields need to be opened and closed
1124 * for every single action that occurs. Thus the f and fd fields aren't really specific to the session
1125 * but rather to the action that is being executed. Because a single session may execute many commands
1126 * at once, some sort of safety needed to be added in order to be sure that we did not end up with fd
1127 * leaks from one action overwriting the f and fd fields used by a previous action before the previous action
1128 * has had a chance to properly close its handles.
1130 * The initial idea to solve this was to use thread synchronization, but this prevented multiple actions
1131 * from being run at the same time in a single session. Some manager actions may block for a long time, thus
1132 * creating a large queue of actions to execute. In addition, this fix did not address the basic architectural
1133 * issue that for HTTP manager sessions, the f and fd variables are not really a part of the session, but are
1134 * part of the action instead.
1136 * The new idea was to create a structure on the stack for each HTTP Manager action. This structure would
1137 * contain the action-specific information, such as which file to write to. In order to maintain expectations
1138 * of action handlers and not have to change the public API of the manager code, we would need to name this
1139 * new stacked structure 'mansession' and contain within it the old mansession struct that we used to use.
1140 * We renamed the old mansession struct 'mansession_session' to hopefully convey that what is in this structure
1141 * is session-specific data. The structure that it is wrapped in, called a 'mansession' really contains action-specific
1144 struct mansession_session {
1145 /*! \todo XXX need to document which fields it is protecting */
1146 struct ast_sockaddr addr; /*!< address we are connecting from */
1147 FILE *f; /*!< fdopen() on the underlying fd */
1148 int fd; /*!< descriptor used for output. Either the socket (AMI) or a temporary file (HTTP) */
1149 int inuse; /*!< number of HTTP sessions using this entry */
1150 int needdestroy; /*!< Whether an HTTP session should be destroyed */
1151 pthread_t waiting_thread; /*!< Sleeping thread using this descriptor */
1152 uint32_t managerid; /*!< Unique manager identifier, 0 for AMI sessions */
1153 time_t sessionstart; /*!< Session start time */
1154 struct timeval sessionstart_tv; /*!< Session start time */
1155 time_t sessiontimeout; /*!< Session timeout if HTTP */
1156 char username[80]; /*!< Logged in username */
1157 char challenge[10]; /*!< Authentication challenge */
1158 int authenticated; /*!< Authentication status */
1159 int readperm; /*!< Authorization for reading */
1160 int writeperm; /*!< Authorization for writing */
1161 char inbuf[1025]; /*!< Buffer - we use the extra byte to add a '\\0' and simplify parsing */
1162 int inlen; /*!< number of buffered bytes */
1163 struct ao2_container *whitefilters; /*!< Manager event filters - white list */
1164 struct ao2_container *blackfilters; /*!< Manager event filters - black list */
1165 struct ast_variable *chanvars; /*!< Channel variables to set for originate */
1166 int send_events; /*!< XXX what ? */
1167 struct eventqent *last_ev; /*!< last event processed. */
1168 int writetimeout; /*!< Timeout for ast_carefulwrite() */
1170 int pending_event; /*!< Pending events indicator in case when waiting_thread is NULL */
1171 time_t noncetime; /*!< Timer for nonce value expiration */
1172 unsigned long oldnonce; /*!< Stale nonce value */
1173 unsigned long nc; /*!< incremental nonce counter */
1174 AST_LIST_HEAD_NOLOCK(mansession_datastores, ast_datastore) datastores; /*!< Data stores on the session */
1175 AST_LIST_ENTRY(mansession_session) list;
1178 enum mansession_message_parsing {
1180 MESSAGE_LINE_TOO_LONG
1183 /*! \brief In case you didn't read that giant block of text above the mansession_session struct, the
1184 * \ref struct mansession is named this solely to keep the API the same in Asterisk. This structure really
1185 * represents data that is different from Manager action to Manager action. The mansession_session pointer
1186 * contained within points to session-specific data.
1189 struct mansession_session *session;
1190 struct ast_tcptls_session_instance *tcptls_session;
1193 enum mansession_message_parsing parsing;
1195 struct manager_custom_hook *hook;
1199 static struct ao2_container *sessions = NULL;
1201 /*! \brief user descriptor, as read from the config file.
1203 * \note It is still missing some fields -- e.g. we can have multiple permit and deny
1204 * lines which are not supported here, and readperm/writeperm/writetimeout
1207 struct ast_manager_user {
1209 char *secret; /*!< Secret for logging in */
1210 int readperm; /*!< Authorization for reading */
1211 int writeperm; /*!< Authorization for writing */
1212 int writetimeout; /*!< Per user Timeout for ast_carefulwrite() */
1213 int displayconnects; /*!< XXX unused */
1214 int keep; /*!< mark entries created on a reload */
1215 struct ao2_container *whitefilters; /*!< Manager event filters - white list */
1216 struct ao2_container *blackfilters; /*!< Manager event filters - black list */
1217 struct ast_acl_list *acl; /*!< ACL setting */
1218 char *a1_hash; /*!< precalculated A1 for Digest auth */
1219 struct ast_variable *chanvars; /*!< Channel variables to set for originate */
1220 AST_RWLIST_ENTRY(ast_manager_user) list;
1223 /*! \brief list of users found in the config file */
1224 static AST_RWLIST_HEAD_STATIC(users, ast_manager_user);
1226 /*! \brief list of actions registered */
1227 static AST_RWLIST_HEAD_STATIC(actions, manager_action);
1229 /*! \brief list of hooks registered */
1230 static AST_RWLIST_HEAD_STATIC(manager_hooks, manager_custom_hook);
1232 /*! \brief A container of event documentation nodes */
1233 AO2_GLOBAL_OBJ_STATIC(event_docs);
1235 static enum add_filter_result manager_add_filter(const char *filter_pattern, struct ao2_container *whitefilters, struct ao2_container *blackfilters);
1238 * @{ \brief Define AMI message types.
1240 STASIS_MESSAGE_TYPE_DEFN(ast_manager_get_generic_type);
1245 * \brief Find a registered action object.
1247 * \param name Name of AMI action to find.
1249 * \return Reffed action found or NULL
1251 static struct manager_action *action_find(const char *name)
1253 struct manager_action *act;
1255 AST_RWLIST_RDLOCK(&actions);
1256 AST_RWLIST_TRAVERSE(&actions, act, list) {
1257 if (!strcasecmp(name, act->action)) {
1258 ao2_t_ref(act, +1, "found action object");
1262 AST_RWLIST_UNLOCK(&actions);
1267 struct stasis_topic *ast_manager_get_topic(void)
1269 return manager_topic;
1272 struct stasis_message_router *ast_manager_get_message_router(void)
1274 return stasis_router;
1277 struct ast_str *ast_manager_str_from_json_object(struct ast_json *blob, key_exclusion_cb exclusion_cb)
1279 struct ast_str *output_str = ast_str_create(32);
1280 struct ast_json *value;
1281 struct ast_json_iter *iter;
1287 for (iter = ast_json_object_iter(blob); iter; iter = ast_json_object_iter_next(blob, iter)) {
1288 key = ast_json_object_iter_key(iter);
1289 value = ast_json_object_iter_value(iter);
1291 if (exclusion_cb && exclusion_cb(key)) {
1294 switch (ast_json_typeof(value)) {
1295 case AST_JSON_STRING:
1296 ast_str_append(&output_str, 0, "%s: %s\r\n", key, ast_json_string_get(value));
1298 case AST_JSON_INTEGER:
1299 ast_str_append(&output_str, 0, "%s: %jd\r\n", key, ast_json_integer_get(value));
1302 ast_str_append(&output_str, 0, "%s: True\r\n", key);
1304 case AST_JSON_FALSE:
1305 ast_str_append(&output_str, 0, "%s: False\r\n", key);
1308 ast_str_append(&output_str, 0, "%s: \r\n", key);
1320 static void manager_default_msg_cb(void *data, struct stasis_subscription *sub,
1321 struct stasis_topic *topic,
1322 struct stasis_message *message)
1324 RAII_VAR(struct ast_manager_event_blob *, ev, NULL, ao2_cleanup);
1326 ev = stasis_message_to_ami(message);
1329 /* Not and AMI message; disregard */
1333 manager_event(ev->event_flags, ev->manager_event, "%s",
1337 static void manager_generic_msg_cb(void *data, struct stasis_subscription *sub,
1338 struct stasis_topic *topic,
1339 struct stasis_message *message)
1341 struct ast_json_payload *payload = stasis_message_data(message);
1342 int class_type = ast_json_integer_get(ast_json_object_get(payload->json, "class_type"));
1343 const char *type = ast_json_string_get(ast_json_object_get(payload->json, "type"));
1344 struct ast_json *event = ast_json_object_get(payload->json, "event");
1345 RAII_VAR(struct ast_str *, event_buffer, NULL, ast_free);
1347 event_buffer = ast_manager_str_from_json_object(event, NULL);
1348 if (!event_buffer) {
1349 ast_log(AST_LOG_WARNING, "Error while creating payload for event %s\n", type);
1352 manager_event(class_type, type, "%s", ast_str_buffer(event_buffer));
1355 void ast_manager_publish_event(const char *type, int class_type, struct ast_json *obj)
1357 RAII_VAR(struct ast_json *, event_info, NULL, ast_json_unref);
1358 RAII_VAR(struct ast_json_payload *, payload, NULL, ao2_cleanup);
1359 RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
1366 event_info = ast_json_pack("{s: s, s: i, s: o}",
1368 "class_type", class_type,
1374 payload = ast_json_payload_create(event_info);
1378 message = stasis_message_create(ast_manager_get_generic_type(), payload);
1382 stasis_publish(ast_manager_get_topic(), message);
1385 /*! \brief Add a custom hook to be called when an event is fired */
1386 void ast_manager_register_hook(struct manager_custom_hook *hook)
1388 AST_RWLIST_WRLOCK(&manager_hooks);
1389 AST_RWLIST_INSERT_TAIL(&manager_hooks, hook, list);
1390 AST_RWLIST_UNLOCK(&manager_hooks);
1393 /*! \brief Delete a custom hook to be called when an event is fired */
1394 void ast_manager_unregister_hook(struct manager_custom_hook *hook)
1396 AST_RWLIST_WRLOCK(&manager_hooks);
1397 AST_RWLIST_REMOVE(&manager_hooks, hook, list);
1398 AST_RWLIST_UNLOCK(&manager_hooks);
1401 int check_manager_enabled(void)
1403 return manager_enabled;
1406 int check_webmanager_enabled(void)
1408 return (webmanager_enabled && manager_enabled);
1412 * Grab a reference to the last event, update usecount as needed.
1413 * Can handle a NULL pointer.
1415 static struct eventqent *grab_last(void)
1417 struct eventqent *ret;
1419 AST_RWLIST_WRLOCK(&all_events);
1420 ret = AST_RWLIST_LAST(&all_events);
1421 /* the list is never empty now, but may become so when
1422 * we optimize it in the future, so be prepared.
1425 ast_atomic_fetchadd_int(&ret->usecount, 1);
1427 AST_RWLIST_UNLOCK(&all_events);
1432 * Purge unused events. Remove elements from the head
1433 * as long as their usecount is 0 and there is a next element.
1435 static void purge_events(void)
1437 struct eventqent *ev;
1438 struct timeval now = ast_tvnow();
1440 AST_RWLIST_WRLOCK(&all_events);
1441 while ( (ev = AST_RWLIST_FIRST(&all_events)) &&
1442 ev->usecount == 0 && AST_RWLIST_NEXT(ev, eq_next)) {
1443 AST_RWLIST_REMOVE_HEAD(&all_events, eq_next);
1447 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&all_events, ev, eq_next) {
1448 /* Never release the last event */
1449 if (!AST_RWLIST_NEXT(ev, eq_next)) {
1453 /* 2.5 times whatever the HTTP timeout is (maximum 2.5 hours) is the maximum time that we will definitely cache an event */
1454 if (ev->usecount == 0 && ast_tvdiff_sec(now, ev->tv) > (httptimeout > 3600 ? 3600 : httptimeout) * 2.5) {
1455 AST_RWLIST_REMOVE_CURRENT(eq_next);
1459 AST_RWLIST_TRAVERSE_SAFE_END;
1460 AST_RWLIST_UNLOCK(&all_events);
1464 * helper functions to convert back and forth between
1465 * string and numeric representation of set of flags
1467 static const struct permalias {
1471 { EVENT_FLAG_SYSTEM, "system" },
1472 { EVENT_FLAG_CALL, "call" },
1473 { EVENT_FLAG_LOG, "log" },
1474 { EVENT_FLAG_VERBOSE, "verbose" },
1475 { EVENT_FLAG_COMMAND, "command" },
1476 { EVENT_FLAG_AGENT, "agent" },
1477 { EVENT_FLAG_USER, "user" },
1478 { EVENT_FLAG_CONFIG, "config" },
1479 { EVENT_FLAG_DTMF, "dtmf" },
1480 { EVENT_FLAG_REPORTING, "reporting" },
1481 { EVENT_FLAG_CDR, "cdr" },
1482 { EVENT_FLAG_DIALPLAN, "dialplan" },
1483 { EVENT_FLAG_ORIGINATE, "originate" },
1484 { EVENT_FLAG_AGI, "agi" },
1485 { EVENT_FLAG_CC, "cc" },
1486 { EVENT_FLAG_AOC, "aoc" },
1487 { EVENT_FLAG_TEST, "test" },
1488 { EVENT_FLAG_MESSAGE, "message" },
1493 /*! \brief Checks to see if a string which can be used to evaluate functions should be rejected */
1494 static int function_capable_string_allowed_with_auths(const char *evaluating, int writepermlist)
1496 if (!(writepermlist & EVENT_FLAG_SYSTEM)
1498 strstr(evaluating, "SHELL") || /* NoOp(${SHELL(rm -rf /)}) */
1499 strstr(evaluating, "EVAL") /* NoOp(${EVAL(${some_var_containing_SHELL})}) */
1506 /*! \brief Convert authority code to a list of options for a user. This will only
1507 * display those authority codes that have an explicit match on authority */
1508 static const char *user_authority_to_str(int authority, struct ast_str **res)
1513 ast_str_reset(*res);
1514 for (i = 0; i < ARRAY_LEN(perms) - 1; i++) {
1515 if ((authority & perms[i].num) == perms[i].num) {
1516 ast_str_append(res, 0, "%s%s", sep, perms[i].label);
1521 if (ast_str_strlen(*res) == 0) /* replace empty string with something sensible */
1522 ast_str_append(res, 0, "<none>");
1524 return ast_str_buffer(*res);
1528 /*! \brief Convert authority code to a list of options. Note that the EVENT_FLAG_ALL
1529 * authority will always be returned. */
1530 static const char *authority_to_str(int authority, struct ast_str **res)
1535 ast_str_reset(*res);
1536 for (i = 0; i < ARRAY_LEN(perms) - 1; i++) {
1537 if (authority & perms[i].num) {
1538 ast_str_append(res, 0, "%s%s", sep, perms[i].label);
1543 if (ast_str_strlen(*res) == 0) /* replace empty string with something sensible */
1544 ast_str_append(res, 0, "<none>");
1546 return ast_str_buffer(*res);
1549 /*! Tells you if smallstr exists inside bigstr
1550 which is delim by delim and uses no buf or stringsep
1551 ast_instring("this|that|more","this",'|') == 1;
1553 feel free to move this to app.c -anthm */
1554 static int ast_instring(const char *bigstr, const char *smallstr, const char delim)
1556 const char *val = bigstr, *next;
1559 if ((next = strchr(val, delim))) {
1560 if (!strncmp(val, smallstr, (next - val))) {
1566 return !strcmp(smallstr, val);
1568 } while (*(val = (next + 1)));
1573 static int get_perm(const char *instr)
1581 for (x = 0; x < ARRAY_LEN(perms); x++) {
1582 if (ast_instring(instr, perms[x].label, ',')) {
1583 ret |= perms[x].num;
1591 * A number returns itself, false returns 0, true returns all flags,
1592 * other strings return the flags that are set.
1594 static int strings_to_mask(const char *string)
1598 if (ast_strlen_zero(string)) {
1602 for (p = string; *p; p++) {
1603 if (*p < '0' || *p > '9') {
1607 if (!*p) { /* all digits */
1608 return atoi(string);
1610 if (ast_false(string)) {
1613 if (ast_true(string)) { /* all permissions */
1615 for (x = 0; x < ARRAY_LEN(perms); x++) {
1616 ret |= perms[x].num;
1620 return get_perm(string);
1623 /*! \brief Unreference manager session object.
1624 If no more references, then go ahead and delete it */
1625 static struct mansession_session *unref_mansession(struct mansession_session *s)
1627 int refcount = ao2_ref(s, -1);
1628 if (manager_debug) {
1629 ast_debug(1, "Mansession: %p refcount now %d\n", s, refcount - 1);
1634 static void event_filter_destructor(void *obj)
1636 regex_t *regex_filter = obj;
1637 regfree(regex_filter);
1640 static void session_destructor(void *obj)
1642 struct mansession_session *session = obj;
1643 struct eventqent *eqe = session->last_ev;
1644 struct ast_datastore *datastore;
1646 /* Get rid of each of the data stores on the session */
1647 while ((datastore = AST_LIST_REMOVE_HEAD(&session->datastores, entry))) {
1648 /* Free the data store */
1649 ast_datastore_free(datastore);
1652 if (session->f != NULL) {
1656 ast_atomic_fetchadd_int(&eqe->usecount, -1);
1658 if (session->chanvars) {
1659 ast_variables_destroy(session->chanvars);
1662 if (session->whitefilters) {
1663 ao2_t_callback(session->whitefilters, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL, "unlink all white filters");
1664 ao2_t_ref(session->whitefilters, -1 , "decrement ref for white container, should be last one");
1667 if (session->blackfilters) {
1668 ao2_t_callback(session->blackfilters, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL, "unlink all black filters");
1669 ao2_t_ref(session->blackfilters, -1 , "decrement ref for black container, should be last one");
1673 /*! \brief Allocate manager session structure and add it to the list of sessions */
1674 static struct mansession_session *build_mansession(const struct ast_sockaddr *addr)
1676 struct mansession_session *newsession;
1678 if (!(newsession = ao2_alloc(sizeof(*newsession), session_destructor))) {
1682 if (!(newsession->whitefilters = ao2_container_alloc(1, NULL, NULL))) {
1683 ao2_ref(newsession, -1);
1687 if (!(newsession->blackfilters = ao2_container_alloc(1, NULL, NULL))) {
1688 ao2_ref(newsession, -1); /* session_destructor will cleanup the other filter */
1692 newsession->fd = -1;
1693 newsession->waiting_thread = AST_PTHREADT_NULL;
1694 newsession->writetimeout = 100;
1695 newsession->send_events = -1;
1696 ast_sockaddr_copy(&newsession->addr, addr);
1698 ao2_link(sessions, newsession);
1703 static int mansession_cmp_fn(void *obj, void *arg, int flags)
1705 struct mansession_session *s = obj;
1707 return !strcasecmp(s->username, str) ? CMP_MATCH : 0;
1710 static void session_destroy(struct mansession_session *s)
1712 unref_mansession(s);
1713 ao2_unlink(sessions, s);
1717 static int check_manager_session_inuse(const char *name)
1719 struct mansession_session *session = ao2_find(sessions, (char *) name, 0);
1724 unref_mansession(session);
1731 * lookup an entry in the list of registered users.
1732 * must be called with the list lock held.
1734 static struct ast_manager_user *get_manager_by_name_locked(const char *name)
1736 struct ast_manager_user *user = NULL;
1738 AST_RWLIST_TRAVERSE(&users, user, list) {
1739 if (!strcasecmp(user->username, name)) {
1747 /*! \brief Get displayconnects config option.
1748 * \param session manager session to get parameter from.
1749 * \return displayconnects config option value.
1751 static int manager_displayconnects (struct mansession_session *session)
1753 struct ast_manager_user *user = NULL;
1756 AST_RWLIST_RDLOCK(&users);
1757 if ((user = get_manager_by_name_locked (session->username))) {
1758 ret = user->displayconnects;
1760 AST_RWLIST_UNLOCK(&users);
1765 static char *handle_showmancmd(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1767 struct manager_action *cur;
1768 struct ast_str *authority;
1772 char syntax_title[64], description_title[64], synopsis_title[64], seealso_title[64], arguments_title[64], privilege_title[64];
1777 e->command = "manager show command";
1779 "Usage: manager show command <actionname> [<actionname> [<actionname> [...]]]\n"
1780 " Shows the detailed description for a specific Asterisk manager interface command.\n";
1783 l = strlen(a->word);
1785 AST_RWLIST_RDLOCK(&actions);
1786 AST_RWLIST_TRAVERSE(&actions, cur, list) {
1787 if (!strncasecmp(a->word, cur->action, l) && ++which > a->n) {
1788 ret = ast_strdup(cur->action);
1789 break; /* make sure we exit even if ast_strdup() returns NULL */
1792 AST_RWLIST_UNLOCK(&actions);
1795 authority = ast_str_alloca(80);
1797 return CLI_SHOWUSAGE;
1801 /* setup the titles */
1802 term_color(synopsis_title, "[Synopsis]\n", COLOR_MAGENTA, 0, 40);
1803 term_color(description_title, "[Description]\n", COLOR_MAGENTA, 0, 40);
1804 term_color(syntax_title, "[Syntax]\n", COLOR_MAGENTA, 0, 40);
1805 term_color(seealso_title, "[See Also]\n", COLOR_MAGENTA, 0, 40);
1806 term_color(arguments_title, "[Arguments]\n", COLOR_MAGENTA, 0, 40);
1807 term_color(privilege_title, "[Privilege]\n", COLOR_MAGENTA, 0, 40);
1810 AST_RWLIST_RDLOCK(&actions);
1811 AST_RWLIST_TRAVERSE(&actions, cur, list) {
1812 for (num = 3; num < a->argc; num++) {
1813 if (!strcasecmp(cur->action, a->argv[num])) {
1814 authority_to_str(cur->authority, &authority);
1817 if (cur->docsrc == AST_XML_DOC) {
1818 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",
1820 ast_xmldoc_printable(S_OR(cur->syntax, "Not available"), 1),
1822 ast_xmldoc_printable(S_OR(cur->synopsis, "Not available"), 1),
1824 ast_xmldoc_printable(S_OR(cur->description, "Not available"), 1),
1826 ast_xmldoc_printable(S_OR(cur->arguments, "Not available"), 1),
1828 ast_xmldoc_printable(S_OR(cur->seealso, "Not available"), 1),
1830 ast_xmldoc_printable(S_OR(authority->str, "Not available"), 1));
1834 ast_cli(a->fd, "Action: %s\nSynopsis: %s\nPrivilege: %s\n%s\n",
1835 cur->action, cur->synopsis,
1837 S_OR(cur->description, ""));
1842 AST_RWLIST_UNLOCK(&actions);
1847 static char *handle_mandebug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1851 e->command = "manager set debug [on|off]";
1852 e->usage = "Usage: manager set debug [on|off]\n Show, enable, disable debugging of the manager code.\n";
1859 ast_cli(a->fd, "manager debug is %s\n", manager_debug? "on" : "off");
1860 } else if (a->argc == 4) {
1861 if (!strcasecmp(a->argv[3], "on")) {
1863 } else if (!strcasecmp(a->argv[3], "off")) {
1866 return CLI_SHOWUSAGE;
1872 static char *handle_showmanager(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1874 struct ast_manager_user *user = NULL;
1877 struct ast_str *rauthority = ast_str_alloca(128);
1878 struct ast_str *wauthority = ast_str_alloca(128);
1879 struct ast_variable *v;
1883 e->command = "manager show user";
1885 " Usage: manager show user <user>\n"
1886 " Display all information related to the manager user specified.\n";
1889 l = strlen(a->word);
1894 AST_RWLIST_RDLOCK(&users);
1895 AST_RWLIST_TRAVERSE(&users, user, list) {
1896 if ( !strncasecmp(a->word, user->username, l) && ++which > a->n ) {
1897 ret = ast_strdup(user->username);
1901 AST_RWLIST_UNLOCK(&users);
1906 return CLI_SHOWUSAGE;
1909 AST_RWLIST_RDLOCK(&users);
1911 if (!(user = get_manager_by_name_locked(a->argv[3]))) {
1912 ast_cli(a->fd, "There is no manager called %s\n", a->argv[3]);
1913 AST_RWLIST_UNLOCK(&users);
1917 ast_cli(a->fd, "\n");
1924 "displayconnects: %s\n",
1925 (user->username ? user->username : "(N/A)"),
1926 (user->secret ? "<Set>" : "(N/A)"),
1927 ((user->acl && !ast_acl_list_is_empty(user->acl)) ? "yes" : "no"),
1928 user_authority_to_str(user->readperm, &rauthority),
1929 user_authority_to_str(user->writeperm, &wauthority),
1930 (user->displayconnects ? "yes" : "no"));
1931 ast_cli(a->fd, " Variables: \n");
1932 for (v = user->chanvars ; v ; v = v->next) {
1933 ast_cli(a->fd, " %s = %s\n", v->name, v->value);
1936 AST_RWLIST_UNLOCK(&users);
1941 static char *handle_showmanagers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1943 struct ast_manager_user *user = NULL;
1947 e->command = "manager show users";
1949 "Usage: manager show users\n"
1950 " Prints a listing of all managers that are currently configured on that\n"
1957 return CLI_SHOWUSAGE;
1960 AST_RWLIST_RDLOCK(&users);
1962 /* If there are no users, print out something along those lines */
1963 if (AST_RWLIST_EMPTY(&users)) {
1964 ast_cli(a->fd, "There are no manager users.\n");
1965 AST_RWLIST_UNLOCK(&users);
1969 ast_cli(a->fd, "\nusername\n--------\n");
1971 AST_RWLIST_TRAVERSE(&users, user, list) {
1972 ast_cli(a->fd, "%s\n", user->username);
1976 AST_RWLIST_UNLOCK(&users);
1978 ast_cli(a->fd,"-------------------\n"
1979 "%d manager users configured.\n", count_amu);
1983 /*! \brief CLI command manager list commands */
1984 static char *handle_showmancmds(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1986 struct manager_action *cur;
1988 int space_remaining;
1989 #define HSMC_FORMAT " %-*.*s %-.*s\n"
1992 e->command = "manager show commands";
1994 "Usage: manager show commands\n"
1995 " Prints a listing of all the available Asterisk manager interface commands.\n";
2001 AST_RWLIST_RDLOCK(&actions);
2002 AST_RWLIST_TRAVERSE(&actions, cur, list) {
2003 int incoming_len = strlen(cur->action);
2004 if (incoming_len > name_len) {
2005 name_len = incoming_len;
2009 space_remaining = MGR_SHOW_TERMINAL_WIDTH - name_len - 4;
2010 if (space_remaining < 0) {
2011 space_remaining = 0;
2014 ast_cli(a->fd, HSMC_FORMAT, name_len, name_len, "Action", space_remaining, "Synopsis");
2015 ast_cli(a->fd, HSMC_FORMAT, name_len, name_len, "------", space_remaining, "--------");
2017 AST_RWLIST_TRAVERSE(&actions, cur, list) {
2018 ast_cli(a->fd, HSMC_FORMAT, name_len, name_len, cur->action, space_remaining, cur->synopsis);
2020 AST_RWLIST_UNLOCK(&actions);
2025 /*! \brief CLI command manager list connected */
2026 static char *handle_showmanconn(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2028 struct mansession_session *session;
2029 time_t now = time(NULL);
2030 #define HSMCONN_FORMAT1 " %-15.15s %-55.55s %-10.10s %-10.10s %-8.8s %-8.8s %-5.5s %-5.5s\n"
2031 #define HSMCONN_FORMAT2 " %-15.15s %-55.55s %-10d %-10d %-8d %-8d %-5.5d %-5.5d\n"
2033 struct ao2_iterator i;
2037 e->command = "manager show connected";
2039 "Usage: manager show connected\n"
2040 " Prints a listing of the users that are currently connected to the\n"
2041 "Asterisk manager interface.\n";
2047 ast_cli(a->fd, HSMCONN_FORMAT1, "Username", "IP Address", "Start", "Elapsed", "FileDes", "HttpCnt", "Read", "Write");
2049 i = ao2_iterator_init(sessions, 0);
2050 while ((session = ao2_iterator_next(&i))) {
2052 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);
2054 ao2_unlock(session);
2055 unref_mansession(session);
2057 ao2_iterator_destroy(&i);
2058 ast_cli(a->fd, "%d users connected.\n", count);
2063 /*! \brief CLI command manager list eventq */
2064 /* Should change to "manager show connected" */
2065 static char *handle_showmaneventq(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2067 struct eventqent *s;
2070 e->command = "manager show eventq";
2072 "Usage: manager show eventq\n"
2073 " Prints a listing of all events pending in the Asterisk manger\n"
2079 AST_RWLIST_RDLOCK(&all_events);
2080 AST_RWLIST_TRAVERSE(&all_events, s, eq_next) {
2081 ast_cli(a->fd, "Usecount: %d\n", s->usecount);
2082 ast_cli(a->fd, "Category: %d\n", s->category);
2083 ast_cli(a->fd, "Event:\n%s", s->eventdata);
2085 AST_RWLIST_UNLOCK(&all_events);
2090 /*! \brief CLI command manager reload */
2091 static char *handle_manager_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2095 e->command = "manager reload";
2097 "Usage: manager reload\n"
2098 " Reloads the manager configuration.\n";
2104 return CLI_SHOWUSAGE;
2110 static struct eventqent *advance_event(struct eventqent *e)
2112 struct eventqent *next;
2114 AST_RWLIST_RDLOCK(&all_events);
2115 if ((next = AST_RWLIST_NEXT(e, eq_next))) {
2116 ast_atomic_fetchadd_int(&next->usecount, 1);
2117 ast_atomic_fetchadd_int(&e->usecount, -1);
2119 AST_RWLIST_UNLOCK(&all_events);
2123 #define GET_HEADER_FIRST_MATCH 0
2124 #define GET_HEADER_LAST_MATCH 1
2125 #define GET_HEADER_SKIP_EMPTY 2
2128 * \brief Return a matching header value.
2131 * Generic function to return either the first or the last
2132 * matching header from a list of variables, possibly skipping
2135 * \note At the moment there is only one use of this function in
2136 * this file, so we make it static.
2138 * \note Never returns NULL.
2140 static const char *__astman_get_header(const struct message *m, char *var, int mode)
2142 int x, l = strlen(var);
2143 const char *result = "";
2149 for (x = 0; x < m->hdrcount; x++) {
2150 const char *h = m->headers[x];
2151 if (!strncasecmp(var, h, l) && h[l] == ':') {
2152 const char *value = h + l + 1;
2153 value = ast_skip_blanks(value); /* ignore leading spaces in the value */
2154 /* found a potential candidate */
2155 if ((mode & GET_HEADER_SKIP_EMPTY) && ast_strlen_zero(value)) {
2156 continue; /* not interesting */
2158 if (mode & GET_HEADER_LAST_MATCH) {
2159 result = value; /* record the last match so far */
2170 * \brief Return the first matching variable from an array.
2172 * \note This is the legacy function and is implemented in
2173 * therms of __astman_get_header().
2175 * \note Never returns NULL.
2177 const char *astman_get_header(const struct message *m, char *var)
2179 return __astman_get_header(m, var, GET_HEADER_FIRST_MATCH);
2184 * \brief Process one "Variable:" header value string.
2186 * \param head Current list of AMI variables to get new values added.
2187 * \param hdr_val Header value string to process.
2189 * \return New variable list head.
2191 static struct ast_variable *man_do_variable_value(struct ast_variable *head, const char *hdr_val)
2194 AST_DECLARE_APP_ARGS(args,
2195 AST_APP_ARG(vars)[64];
2198 hdr_val = ast_skip_blanks(hdr_val); /* ignore leading spaces in the value */
2199 parse = ast_strdupa(hdr_val);
2201 /* Break the header value string into name=val pair items. */
2202 AST_STANDARD_APP_ARGS(args, parse);
2206 /* Process each name=val pair item. */
2207 for (y = 0; y < args.argc; y++) {
2208 struct ast_variable *cur;
2212 if (!args.vars[y]) {
2215 var = val = args.vars[y];
2218 /* XXX We may wish to trim whitespace from the strings. */
2219 if (!val || ast_strlen_zero(var)) {
2223 /* Create new variable list node and prepend it to the list. */
2224 cur = ast_variable_new(var, val, "");
2235 struct ast_variable *astman_get_variables(const struct message *m)
2239 struct ast_variable *head = NULL;
2241 static const char var_hdr[] = "Variable:";
2243 /* Process all "Variable:" headers. */
2244 varlen = strlen(var_hdr);
2245 for (x = 0; x < m->hdrcount; x++) {
2246 if (strncasecmp(var_hdr, m->headers[x], varlen)) {
2249 head = man_do_variable_value(head, m->headers[x] + varlen);
2255 /*! \brief access for hooks to send action messages to ami */
2256 int ast_hook_send_action(struct manager_custom_hook *hook, const char *msg)
2260 struct manager_action *act_found;
2261 struct mansession s = {.session = NULL, };
2262 struct message m = { 0 };
2272 /* Create our own copy of the AMI action msg string. */
2273 src = dup_str = ast_strdup(msg);
2278 /* convert msg string to message struct */
2279 curlen = strlen(src);
2280 for (x = 0; x < curlen; x++) {
2281 int cr; /* set if we have \r */
2282 if (src[x] == '\r' && x+1 < curlen && src[x+1] == '\n')
2283 cr = 2; /* Found. Update length to include \r\n */
2284 else if (src[x] == '\n')
2285 cr = 1; /* also accept \n only */
2288 /* don't keep empty lines */
2289 if (x && m.hdrcount < ARRAY_LEN(m.headers)) {
2290 /* ... but trim \r\n and terminate the header string */
2292 m.headers[m.hdrcount++] = src;
2295 curlen -= x; /* remaining size */
2296 src += x; /* update pointer */
2297 x = -1; /* reset loop */
2300 action = astman_get_header(&m, "Action");
2301 if (strcasecmp(action, "login")) {
2302 act_found = action_find(action);
2305 * we have to simulate a session for this action request
2306 * to be able to pass it down for processing
2307 * This is necessary to meet the previous design of manager.c
2310 s.f = (void*)1; /* set this to something so our request will make it through all functions that test it*/
2312 ao2_lock(act_found);
2313 if (act_found->registered && act_found->func) {
2314 if (act_found->module) {
2315 ast_module_ref(act_found->module);
2317 ao2_unlock(act_found);
2318 ret = act_found->func(&s, &m);
2319 ao2_lock(act_found);
2320 if (act_found->module) {
2321 ast_module_unref(act_found->module);
2326 ao2_unlock(act_found);
2327 ao2_t_ref(act_found, -1, "done with found action object");
2336 * helper function to send a string to the socket.
2337 * Return -1 on error (e.g. buffer full).
2339 static int send_string(struct mansession *s, char *string)
2342 FILE *f = s->f ? s->f : s->session->f;
2343 int fd = s->f ? s->fd : s->session->fd;
2345 /* It's a result from one of the hook's action invocation */
2348 * to send responses, we're using the same function
2349 * as for receiving events. We call the event "HookResponse"
2351 s->hook->helper(EVENT_FLAG_HOOKRESPONSE, "HookResponse", string);
2355 if ((res = ast_careful_fwrite(f, fd, string, strlen(string), s->session->writetimeout))) {
2363 * \brief thread local buffer for astman_append
2365 * \note This can not be defined within the astman_append() function
2366 * because it declares a couple of functions that get used to
2367 * initialize the thread local storage key.
2369 AST_THREADSTORAGE(astman_append_buf);
2371 AST_THREADSTORAGE(userevent_buf);
2373 /*! \brief initial allocated size for the astman_append_buf and astman_send_*_va */
2374 #define ASTMAN_APPEND_BUF_INITSIZE 256
2377 * utility functions for creating AMI replies
2379 void astman_append(struct mansession *s, const char *fmt, ...)
2382 struct ast_str *buf;
2384 if (!(buf = ast_str_thread_get(&astman_append_buf, ASTMAN_APPEND_BUF_INITSIZE))) {
2389 ast_str_set_va(&buf, 0, fmt, ap);
2392 if (s->f != NULL || s->session->f != NULL) {
2393 send_string(s, ast_str_buffer(buf));
2395 ast_verbose("fd == -1 in astman_append, should not happen\n");
2399 /*! \note NOTE: XXX this comment is unclear and possibly wrong.
2400 Callers of astman_send_error(), astman_send_response() or astman_send_ack() must EITHER
2401 hold the session lock _or_ be running in an action callback (in which case s->session->busy will
2402 be non-zero). In either of these cases, there is no need to lock-protect the session's
2403 fd, since no other output will be sent (events will be queued), and no input will
2404 be read until either the current action finishes or get_input() obtains the session
2408 /*! \todo XXX MSG_MOREDATA should go to a header file. */
2409 #define MSG_MOREDATA ((char *)astman_send_response)
2411 /*! \brief send a response with an optional message,
2412 * and terminate it with an empty line.
2413 * m is used only to grab the 'ActionID' field.
2415 * Use the explicit constant MSG_MOREDATA to remove the empty line.
2416 * XXX MSG_MOREDATA should go to a header file.
2418 static void astman_send_response_full(struct mansession *s, const struct message *m, char *resp, char *msg, char *listflag)
2420 const char *id = astman_get_header(m, "ActionID");
2422 astman_append(s, "Response: %s\r\n", resp);
2423 if (!ast_strlen_zero(id)) {
2424 astman_append(s, "ActionID: %s\r\n", id);
2427 astman_append(s, "EventList: %s\r\n", listflag); /* Start, complete, cancelled */
2429 if (msg == MSG_MOREDATA) {
2432 astman_append(s, "Message: %s\r\n\r\n", msg);
2434 astman_append(s, "\r\n");
2438 void astman_send_response(struct mansession *s, const struct message *m, char *resp, char *msg)
2440 astman_send_response_full(s, m, resp, msg, NULL);
2443 void astman_send_error(struct mansession *s, const struct message *m, char *error)
2445 astman_send_response_full(s, m, "Error", error, NULL);
2448 void astman_send_error_va(struct mansession *s, const struct message *m, const char *fmt, ...)
2451 struct ast_str *buf;
2454 if (!(buf = ast_str_thread_get(&astman_append_buf, ASTMAN_APPEND_BUF_INITSIZE))) {
2459 ast_str_set_va(&buf, 0, fmt, ap);
2462 /* astman_append will use the same underlying buffer, so copy the message out
2463 * before sending the response */
2464 msg = ast_str_buffer(buf);
2466 msg = ast_strdupa(msg);
2468 astman_send_response_full(s, m, "Error", msg, NULL);
2471 void astman_send_ack(struct mansession *s, const struct message *m, char *msg)
2473 astman_send_response_full(s, m, "Success", msg, NULL);
2476 static void astman_start_ack(struct mansession *s, const struct message *m)
2478 astman_send_response_full(s, m, "Success", MSG_MOREDATA, NULL);
2481 void astman_send_listack(struct mansession *s, const struct message *m, char *msg, char *listflag)
2483 astman_send_response_full(s, m, "Success", msg, listflag);
2486 /*! \brief Lock the 'mansession' structure. */
2487 static void mansession_lock(struct mansession *s)
2489 ast_mutex_lock(&s->lock);
2492 /*! \brief Unlock the 'mansession' structure. */
2493 static void mansession_unlock(struct mansession *s)
2495 ast_mutex_unlock(&s->lock);
2499 Rather than braindead on,off this now can also accept a specific int mask value
2500 or a ',' delim list of mask strings (the same as manager.conf) -anthm
2502 static int set_eventmask(struct mansession *s, const char *eventmask)
2504 int maskint = strings_to_mask(eventmask);
2506 ao2_lock(s->session);
2508 s->session->send_events = maskint;
2510 ao2_unlock(s->session);
2515 static enum ast_transport mansession_get_transport(const struct mansession *s)
2517 return s->tcptls_session->parent->tls_cfg ? AST_TRANSPORT_TLS :
2521 static void report_invalid_user(const struct mansession *s, const char *username)
2523 char session_id[32];
2524 struct ast_security_event_inval_acct_id inval_acct_id = {
2525 .common.event_type = AST_SECURITY_EVENT_INVAL_ACCT_ID,
2526 .common.version = AST_SECURITY_EVENT_INVAL_ACCT_ID_VERSION,
2527 .common.service = "AMI",
2528 .common.account_id = username,
2529 .common.session_tv = &s->session->sessionstart_tv,
2530 .common.local_addr = {
2531 .addr = &s->tcptls_session->parent->local_address,
2532 .transport = mansession_get_transport(s),
2534 .common.remote_addr = {
2535 .addr = &s->session->addr,
2536 .transport = mansession_get_transport(s),
2538 .common.session_id = session_id,
2541 snprintf(session_id, sizeof(session_id), "%p", s);
2543 ast_security_event_report(AST_SEC_EVT(&inval_acct_id));
2546 static void report_failed_acl(const struct mansession *s, const char *username)
2548 char session_id[32];
2549 struct ast_security_event_failed_acl failed_acl_event = {
2550 .common.event_type = AST_SECURITY_EVENT_FAILED_ACL,
2551 .common.version = AST_SECURITY_EVENT_FAILED_ACL_VERSION,
2552 .common.service = "AMI",
2553 .common.account_id = username,
2554 .common.session_tv = &s->session->sessionstart_tv,
2555 .common.local_addr = {
2556 .addr = &s->tcptls_session->parent->local_address,
2557 .transport = mansession_get_transport(s),
2559 .common.remote_addr = {
2560 .addr = &s->session->addr,
2561 .transport = mansession_get_transport(s),
2563 .common.session_id = session_id,
2566 snprintf(session_id, sizeof(session_id), "%p", s->session);
2568 ast_security_event_report(AST_SEC_EVT(&failed_acl_event));
2571 static void report_inval_password(const struct mansession *s, const char *username)
2573 char session_id[32];
2574 struct ast_security_event_inval_password inval_password = {
2575 .common.event_type = AST_SECURITY_EVENT_INVAL_PASSWORD,
2576 .common.version = AST_SECURITY_EVENT_INVAL_PASSWORD_VERSION,
2577 .common.service = "AMI",
2578 .common.account_id = username,
2579 .common.session_tv = &s->session->sessionstart_tv,
2580 .common.local_addr = {
2581 .addr = &s->tcptls_session->parent->local_address,
2582 .transport = mansession_get_transport(s),
2584 .common.remote_addr = {
2585 .addr = &s->session->addr,
2586 .transport = mansession_get_transport(s),
2588 .common.session_id = session_id,
2591 snprintf(session_id, sizeof(session_id), "%p", s->session);
2593 ast_security_event_report(AST_SEC_EVT(&inval_password));
2596 static void report_auth_success(const struct mansession *s)
2598 char session_id[32];
2599 struct ast_security_event_successful_auth successful_auth = {
2600 .common.event_type = AST_SECURITY_EVENT_SUCCESSFUL_AUTH,
2601 .common.version = AST_SECURITY_EVENT_SUCCESSFUL_AUTH_VERSION,
2602 .common.service = "AMI",
2603 .common.account_id = s->session->username,
2604 .common.session_tv = &s->session->sessionstart_tv,
2605 .common.local_addr = {
2606 .addr = &s->tcptls_session->parent->local_address,
2607 .transport = mansession_get_transport(s),
2609 .common.remote_addr = {
2610 .addr = &s->session->addr,
2611 .transport = mansession_get_transport(s),
2613 .common.session_id = session_id,
2616 snprintf(session_id, sizeof(session_id), "%p", s->session);
2618 ast_security_event_report(AST_SEC_EVT(&successful_auth));
2621 static void report_req_not_allowed(const struct mansession *s, const char *action)
2623 char session_id[32];
2624 char request_type[64];
2625 struct ast_security_event_req_not_allowed req_not_allowed = {
2626 .common.event_type = AST_SECURITY_EVENT_REQ_NOT_ALLOWED,
2627 .common.version = AST_SECURITY_EVENT_REQ_NOT_ALLOWED_VERSION,
2628 .common.service = "AMI",
2629 .common.account_id = s->session->username,
2630 .common.session_tv = &s->session->sessionstart_tv,
2631 .common.local_addr = {
2632 .addr = &s->tcptls_session->parent->local_address,
2633 .transport = mansession_get_transport(s),
2635 .common.remote_addr = {
2636 .addr = &s->session->addr,
2637 .transport = mansession_get_transport(s),
2639 .common.session_id = session_id,
2641 .request_type = request_type,
2644 snprintf(session_id, sizeof(session_id), "%p", s->session);
2645 snprintf(request_type, sizeof(request_type), "Action: %s", action);
2647 ast_security_event_report(AST_SEC_EVT(&req_not_allowed));
2650 static void report_req_bad_format(const struct mansession *s, const char *action)
2652 char session_id[32];
2653 char request_type[64];
2654 struct ast_security_event_req_bad_format req_bad_format = {
2655 .common.event_type = AST_SECURITY_EVENT_REQ_BAD_FORMAT,
2656 .common.version = AST_SECURITY_EVENT_REQ_BAD_FORMAT_VERSION,
2657 .common.service = "AMI",
2658 .common.account_id = s->session->username,
2659 .common.session_tv = &s->session->sessionstart_tv,
2660 .common.local_addr = {
2661 .addr = &s->tcptls_session->parent->local_address,
2662 .transport = mansession_get_transport(s),
2664 .common.remote_addr = {
2665 .addr = &s->session->addr,
2666 .transport = mansession_get_transport(s),
2668 .common.session_id = session_id,
2670 .request_type = request_type,
2673 snprintf(session_id, sizeof(session_id), "%p", s->session);
2674 snprintf(request_type, sizeof(request_type), "Action: %s", action);
2676 ast_security_event_report(AST_SEC_EVT(&req_bad_format));
2679 static void report_failed_challenge_response(const struct mansession *s,
2680 const char *response, const char *expected_response)
2682 char session_id[32];
2683 struct ast_security_event_chal_resp_failed chal_resp_failed = {
2684 .common.event_type = AST_SECURITY_EVENT_CHAL_RESP_FAILED,
2685 .common.version = AST_SECURITY_EVENT_CHAL_RESP_FAILED_VERSION,
2686 .common.service = "AMI",
2687 .common.account_id = s->session->username,
2688 .common.session_tv = &s->session->sessionstart_tv,
2689 .common.local_addr = {
2690 .addr = &s->tcptls_session->parent->local_address,
2691 .transport = mansession_get_transport(s),
2693 .common.remote_addr = {
2694 .addr = &s->session->addr,
2695 .transport = mansession_get_transport(s),
2697 .common.session_id = session_id,
2699 .challenge = s->session->challenge,
2700 .response = response,
2701 .expected_response = expected_response,
2704 snprintf(session_id, sizeof(session_id), "%p", s->session);
2706 ast_security_event_report(AST_SEC_EVT(&chal_resp_failed));
2709 static void report_session_limit(const struct mansession *s)
2711 char session_id[32];
2712 struct ast_security_event_session_limit session_limit = {
2713 .common.event_type = AST_SECURITY_EVENT_SESSION_LIMIT,
2714 .common.version = AST_SECURITY_EVENT_SESSION_LIMIT_VERSION,
2715 .common.service = "AMI",
2716 .common.account_id = s->session->username,
2717 .common.session_tv = &s->session->sessionstart_tv,
2718 .common.local_addr = {
2719 .addr = &s->tcptls_session->parent->local_address,
2720 .transport = mansession_get_transport(s),
2722 .common.remote_addr = {
2723 .addr = &s->session->addr,
2724 .transport = mansession_get_transport(s),
2726 .common.session_id = session_id,
2729 snprintf(session_id, sizeof(session_id), "%p", s->session);
2731 ast_security_event_report(AST_SEC_EVT(&session_limit));
2735 * Here we start with action_ handlers for AMI actions,
2736 * and the internal functions used by them.
2737 * Generally, the handlers are called action_foo()
2740 /* helper function for action_login() */
2741 static int authenticate(struct mansession *s, const struct message *m)
2743 const char *username = astman_get_header(m, "Username");
2744 const char *password = astman_get_header(m, "Secret");
2746 struct ast_manager_user *user = NULL;
2747 regex_t *regex_filter;
2748 struct ao2_iterator filter_iter;
2750 if (ast_strlen_zero(username)) { /* missing username */
2754 /* locate user in locked state */
2755 AST_RWLIST_WRLOCK(&users);
2757 if (!(user = get_manager_by_name_locked(username))) {
2758 report_invalid_user(s, username);
2759 ast_log(LOG_NOTICE, "%s tried to authenticate with nonexistent user '%s'\n", ast_sockaddr_stringify_addr(&s->session->addr), username);
2760 } else if (user->acl && (ast_apply_acl(user->acl, &s->session->addr, "Manager User ACL: ") == AST_SENSE_DENY)) {
2761 report_failed_acl(s, username);
2762 ast_log(LOG_NOTICE, "%s failed to pass IP ACL as '%s'\n", ast_sockaddr_stringify_addr(&s->session->addr), username);
2763 } else if (!strcasecmp(astman_get_header(m, "AuthType"), "MD5")) {
2764 const char *key = astman_get_header(m, "Key");
2765 if (!ast_strlen_zero(key) && !ast_strlen_zero(s->session->challenge) && user->secret) {
2768 char md5key[256] = "";
2769 struct MD5Context md5;
2770 unsigned char digest[16];
2773 MD5Update(&md5, (unsigned char *) s->session->challenge, strlen(s->session->challenge));
2774 MD5Update(&md5, (unsigned char *) user->secret, strlen(user->secret));
2775 MD5Final(digest, &md5);
2776 for (x = 0; x < 16; x++)
2777 len += sprintf(md5key + len, "%2.2x", digest[x]);
2778 if (!strcmp(md5key, key)) {
2781 report_failed_challenge_response(s, key, md5key);
2784 ast_debug(1, "MD5 authentication is not possible. challenge: '%s'\n",
2785 S_OR(s->session->challenge, ""));
2787 } else if (user->secret) {
2788 if (!strcmp(password, user->secret)) {
2791 report_inval_password(s, username);
2796 ast_log(LOG_NOTICE, "%s failed to authenticate as '%s'\n", ast_sockaddr_stringify_addr(&s->session->addr), username);
2797 AST_RWLIST_UNLOCK(&users);
2803 /* All of the user parameters are copied to the session so that in the event
2804 * of a reload and a configuration change, the session parameters are not
2806 ast_copy_string(s->session->username, username, sizeof(s->session->username));
2807 s->session->readperm = user->readperm;
2808 s->session->writeperm = user->writeperm;
2809 s->session->writetimeout = user->writetimeout;
2810 if (user->chanvars) {
2811 s->session->chanvars = ast_variables_dup(user->chanvars);
2814 filter_iter = ao2_iterator_init(user->whitefilters, 0);
2815 while ((regex_filter = ao2_iterator_next(&filter_iter))) {
2816 ao2_t_link(s->session->whitefilters, regex_filter, "add white user filter to session");
2817 ao2_t_ref(regex_filter, -1, "remove iterator ref");
2819 ao2_iterator_destroy(&filter_iter);
2821 filter_iter = ao2_iterator_init(user->blackfilters, 0);
2822 while ((regex_filter = ao2_iterator_next(&filter_iter))) {
2823 ao2_t_link(s->session->blackfilters, regex_filter, "add black user filter to session");
2824 ao2_t_ref(regex_filter, -1, "remove iterator ref");
2826 ao2_iterator_destroy(&filter_iter);
2828 s->session->sessionstart = time(NULL);
2829 s->session->sessionstart_tv = ast_tvnow();
2830 set_eventmask(s, astman_get_header(m, "Events"));
2832 report_auth_success(s);
2834 AST_RWLIST_UNLOCK(&users);
2838 static int action_ping(struct mansession *s, const struct message *m)
2840 const char *actionid = astman_get_header(m, "ActionID");
2841 struct timeval now = ast_tvnow();
2843 astman_append(s, "Response: Success\r\n");
2844 if (!ast_strlen_zero(actionid)){
2845 astman_append(s, "ActionID: %s\r\n", actionid);
2850 "Timestamp: %ld.%06lu\r\n"
2852 (long) now.tv_sec, (unsigned long) now.tv_usec);
2856 static int action_getconfig(struct mansession *s, const struct message *m)
2858 struct ast_config *cfg;
2859 const char *fn = astman_get_header(m, "Filename");
2860 const char *category = astman_get_header(m, "Category");
2863 char *cur_category = NULL;
2864 struct ast_variable *v;
2865 struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
2867 if (ast_strlen_zero(fn)) {
2868 astman_send_error(s, m, "Filename not specified");
2871 cfg = ast_config_load2(fn, "manager", config_flags);
2872 if (cfg == CONFIG_STATUS_FILEMISSING) {
2873 astman_send_error(s, m, "Config file not found");
2875 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
2876 astman_send_error(s, m, "Config file has invalid format");
2880 astman_start_ack(s, m);
2881 while ((cur_category = ast_category_browse(cfg, cur_category))) {
2882 if (ast_strlen_zero(category) || (!ast_strlen_zero(category) && !strcmp(category, cur_category))) {
2884 astman_append(s, "Category-%06d: %s\r\n", catcount, cur_category);
2885 for (v = ast_variable_browse(cfg, cur_category); v; v = v->next) {
2886 astman_append(s, "Line-%06d-%06d: %s=%s\r\n", catcount, lineno++, v->name, v->value);
2891 if (!ast_strlen_zero(category) && catcount == 0) { /* TODO: actually, a config with no categories doesn't even get loaded */
2892 astman_append(s, "No categories found\r\n");
2894 ast_config_destroy(cfg);
2895 astman_append(s, "\r\n");
2900 static int action_listcategories(struct mansession *s, const struct message *m)
2902 struct ast_config *cfg;
2903 const char *fn = astman_get_header(m, "Filename");
2904 char *category = NULL;
2905 struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
2908 if (ast_strlen_zero(fn)) {
2909 astman_send_error(s, m, "Filename not specified");
2912 if (!(cfg = ast_config_load2(fn, "manager", config_flags))) {
2913 astman_send_error(s, m, "Config file not found");
2915 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
2916 astman_send_error(s, m, "Config file has invalid format");
2919 astman_start_ack(s, m);
2920 while ((category = ast_category_browse(cfg, category))) {
2921 astman_append(s, "Category-%06d: %s\r\n", catcount, category);
2924 if (catcount == 0) { /* TODO: actually, a config with no categories doesn't even get loaded */
2925 astman_append(s, "Error: no categories found\r\n");
2927 ast_config_destroy(cfg);
2928 astman_append(s, "\r\n");
2936 /*! The amount of space in out must be at least ( 2 * strlen(in) + 1 ) */
2937 static void json_escape(char *out, const char *in)
2940 if (*in == '\\' || *in == '\"') {
2950 * \brief Append a JSON escaped string to the manager stream.
2952 * \param s AMI stream to append a string.
2953 * \param str String to append to the stream after JSON escaping it.
2957 static void astman_append_json(struct mansession *s, const char *str)
2961 buf = ast_alloca(2 * strlen(str) + 1);
2962 json_escape(buf, str);
2963 astman_append(s, "%s", buf);
2966 static int action_getconfigjson(struct mansession *s, const struct message *m)
2968 struct ast_config *cfg;
2969 const char *fn = astman_get_header(m, "Filename");
2970 char *category = NULL;
2971 struct ast_variable *v;
2973 struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
2975 if (ast_strlen_zero(fn)) {
2976 astman_send_error(s, m, "Filename not specified");
2980 if (!(cfg = ast_config_load2(fn, "manager", config_flags))) {
2981 astman_send_error(s, m, "Config file not found");
2983 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
2984 astman_send_error(s, m, "Config file has invalid format");
2988 astman_start_ack(s, m);
2989 astman_append(s, "JSON: {");
2990 while ((category = ast_category_browse(cfg, category))) {
2993 astman_append(s, "%s\"", comma1 ? "," : "");
2994 astman_append_json(s, category);
2995 astman_append(s, "\":[");
2997 for (v = ast_variable_browse(cfg, category); v; v = v->next) {
2998 astman_append(s, "%s\"", comma2 ? "," : "");
2999 astman_append_json(s, v->name);
3000 astman_append(s, "\":\"");
3001 astman_append_json(s, v->value);
3002 astman_append(s, "\"");
3005 astman_append(s, "]");
3007 astman_append(s, "}\r\n\r\n");
3009 ast_config_destroy(cfg);
3014 /*! \brief helper function for action_updateconfig */
3015 static enum error_type handle_updates(struct mansession *s, const struct message *m, struct ast_config *cfg, const char *dfn)
3019 const char *action, *cat, *var, *value, *match, *line;
3020 struct ast_category *category;
3021 struct ast_variable *v;
3022 struct ast_str *str1 = ast_str_create(16), *str2 = ast_str_create(16);
3023 enum error_type result = 0;
3025 for (x = 0; x < 100000; x++) { /* 100000 = the max number of allowed updates + 1 */
3026 unsigned int object = 0;
3028 snprintf(hdr, sizeof(hdr), "Action-%06d", x);
3029 action = astman_get_header(m, hdr);
3030 if (ast_strlen_zero(action)) /* breaks the for loop if no action header */
3031 break; /* this could cause problems if actions come in misnumbered */
3033 snprintf(hdr, sizeof(hdr), "Cat-%06d", x);
3034 cat = astman_get_header(m, hdr);
3035 if (ast_strlen_zero(cat)) { /* every action needs a category */
3036 result = UNSPECIFIED_CATEGORY;
3040 snprintf(hdr, sizeof(hdr), "Var-%06d", x);
3041 var = astman_get_header(m, hdr);
3043 snprintf(hdr, sizeof(hdr), "Value-%06d", x);
3044 value = astman_get_header(m, hdr);
3046 if (!ast_strlen_zero(value) && *value == '>') {
3051 snprintf(hdr, sizeof(hdr), "Match-%06d", x);
3052 match = astman_get_header(m, hdr);
3054 snprintf(hdr, sizeof(hdr), "Line-%06d", x);