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/stringfields.h"
93 #include "asterisk/presencestate.h"
96 <manager name="Ping" language="en_US">
101 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
104 <para>A 'Ping' action will ellicit a 'Pong' response. Used to keep the
105 manager connection open.</para>
108 <manager name="Events" language="en_US">
113 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
114 <parameter name="EventMask" required="true">
117 <para>If all events should be sent.</para>
120 <para>If no events should be sent.</para>
122 <enum name="system,call,log,...">
123 <para>To select which flags events should have to be sent.</para>
129 <para>Enable/Disable sending of events to this manager client.</para>
132 <manager name="Logoff" language="en_US">
137 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
140 <para>Logoff the current manager session.</para>
143 <manager name="Login" language="en_US">
148 <parameter name="ActionID">
149 <para>ActionID for this transaction. Will be returned.</para>
151 <parameter name="Username" required="true">
152 <para>Username to login with as specified in manager.conf.</para>
154 <parameter name="Secret">
155 <para>Secret to login with as specified in manager.conf.</para>
159 <para>Login Manager.</para>
162 <manager name="Challenge" language="en_US">
164 Generate Challenge for MD5 Auth.
167 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
168 <parameter name="AuthType" required="true">
169 <para>Digest algorithm to use in the challenge. Valid values are:</para>
176 <para>Generate a challenge for MD5 authentication.</para>
179 <manager name="Hangup" language="en_US">
184 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
185 <parameter name="Channel" required="true">
186 <para>The exact channel name to be hungup, or to use a regular expression, set this parameter to: /regex/</para>
187 <para>Example exact channel: SIP/provider-0000012a</para>
188 <para>Example regular expression: /^SIP/provider-.*$/</para>
190 <parameter name="Cause">
191 <para>Numeric hangup cause.</para>
195 <para>Hangup a channel.</para>
198 <manager name="Status" language="en_US">
203 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
204 <parameter name="Channel" required="true">
205 <para>The name of the channel to query for status.</para>
207 <parameter name="Variables">
208 <para>Comma <literal>,</literal> separated list of variable to include.</para>
212 <para>Will return the status information of each channel along with the
213 value for the specified channel variables.</para>
216 <manager name="Setvar" language="en_US">
218 Set a channel variable.
221 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
222 <parameter name="Channel">
223 <para>Channel to set variable for.</para>
225 <parameter name="Variable" required="true">
226 <para>Variable name.</para>
228 <parameter name="Value" required="true">
229 <para>Variable value.</para>
233 <para>Set a global or local channel variable.</para>
235 <para>If a channel name is not provided then the variable is global.</para>
239 <manager name="Getvar" language="en_US">
241 Gets a channel variable.
244 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
245 <parameter name="Channel">
246 <para>Channel to read variable from.</para>
248 <parameter name="Variable" required="true">
249 <para>Variable name.</para>
253 <para>Get the value of a global or local channel variable.</para>
255 <para>If a channel name is not provided then the variable is global.</para>
259 <manager name="GetConfig" language="en_US">
261 Retrieve configuration.
264 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
265 <parameter name="Filename" required="true">
266 <para>Configuration filename (e.g. <filename>foo.conf</filename>).</para>
268 <parameter name="Category">
269 <para>Category in configuration file.</para>
273 <para>This action will dump the contents of a configuration
274 file by category and contents or optionally by specified category only.</para>
277 <manager name="GetConfigJSON" language="en_US">
279 Retrieve configuration (JSON format).
282 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
283 <parameter name="Filename" required="true">
284 <para>Configuration filename (e.g. <filename>foo.conf</filename>).</para>
288 <para>This action will dump the contents of a configuration file by category
289 and contents in JSON format. This only makes sense to be used using rawman over
290 the HTTP interface.</para>
293 <manager name="UpdateConfig" language="en_US">
295 Update basic configuration.
298 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
299 <parameter name="SrcFilename" required="true">
300 <para>Configuration filename to read (e.g. <filename>foo.conf</filename>).</para>
302 <parameter name="DstFilename" required="true">
303 <para>Configuration filename to write (e.g. <filename>foo.conf</filename>)</para>
305 <parameter name="Reload">
306 <para>Whether or not a reload should take place (or name of specific module).</para>
308 <parameter name="Action-XXXXXX">
309 <para>Action to take.</para>
310 <para>X's represent 6 digit number beginning with 000000.</para>
312 <enum name="NewCat" />
313 <enum name="RenameCat" />
314 <enum name="DelCat" />
315 <enum name="EmptyCat" />
316 <enum name="Update" />
317 <enum name="Delete" />
318 <enum name="Append" />
319 <enum name="Insert" />
322 <parameter name="Cat-XXXXXX">
323 <para>Category to operate on.</para>
324 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-XXXXXX']/para[2])" />
326 <parameter name="Var-XXXXXX">
327 <para>Variable to work on.</para>
328 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-XXXXXX']/para[2])" />
330 <parameter name="Value-XXXXXX">
331 <para>Value to work on.</para>
332 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-XXXXXX']/para[2])" />
334 <parameter name="Match-XXXXXX">
335 <para>Extra match required to match line.</para>
336 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-XXXXXX']/para[2])" />
338 <parameter name="Line-XXXXXX">
339 <para>Line in category to operate on (used with delete and insert actions).</para>
340 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-XXXXXX']/para[2])" />
344 <para>This action will modify, create, or delete configuration elements
345 in Asterisk configuration files.</para>
348 <manager name="CreateConfig" language="en_US">
350 Creates an empty file in the configuration directory.
353 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
354 <parameter name="Filename" required="true">
355 <para>The configuration filename to create (e.g. <filename>foo.conf</filename>).</para>
359 <para>This action will create an empty file in the configuration
360 directory. This action is intended to be used before an UpdateConfig
364 <manager name="ListCategories" language="en_US">
366 List categories in configuration file.
369 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
370 <parameter name="Filename" required="true">
371 <para>Configuration filename (e.g. <filename>foo.conf</filename>).</para>
375 <para>This action will dump the categories in a given file.</para>
378 <manager name="Redirect" language="en_US">
380 Redirect (transfer) a call.
383 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
384 <parameter name="Channel" required="true">
385 <para>Channel to redirect.</para>
387 <parameter name="ExtraChannel">
388 <para>Second call leg to transfer (optional).</para>
390 <parameter name="Exten" required="true">
391 <para>Extension to transfer to.</para>
393 <parameter name="ExtraExten">
394 <para>Extension to transfer extrachannel to (optional).</para>
396 <parameter name="Context" required="true">
397 <para>Context to transfer to.</para>
399 <parameter name="ExtraContext">
400 <para>Context to transfer extrachannel to (optional).</para>
402 <parameter name="Priority" required="true">
403 <para>Priority to transfer to.</para>
405 <parameter name="ExtraPriority">
406 <para>Priority to transfer extrachannel to (optional).</para>
410 <para>Redirect (transfer) a call.</para>
413 <manager name="Atxfer" language="en_US">
418 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
419 <parameter name="Channel" required="true">
420 <para>Transferer's channel.</para>
422 <parameter name="Exten" required="true">
423 <para>Extension to transfer to.</para>
425 <parameter name="Context" required="true">
426 <para>Context to transfer to.</para>
428 <parameter name="Priority" required="true">
429 <para>Priority to transfer to.</para>
433 <para>Attended transfer.</para>
436 <manager name="Originate" language="en_US">
441 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
442 <parameter name="Channel" required="true">
443 <para>Channel name to call.</para>
445 <parameter name="Exten">
446 <para>Extension to use (requires <literal>Context</literal> and
447 <literal>Priority</literal>)</para>
449 <parameter name="Context">
450 <para>Context to use (requires <literal>Exten</literal> and
451 <literal>Priority</literal>)</para>
453 <parameter name="Priority">
454 <para>Priority to use (requires <literal>Exten</literal> and
455 <literal>Context</literal>)</para>
457 <parameter name="Application">
458 <para>Application to execute.</para>
460 <parameter name="Data">
461 <para>Data to use (requires <literal>Application</literal>).</para>
463 <parameter name="Timeout" default="30000">
464 <para>How long to wait for call to be answered (in ms.).</para>
466 <parameter name="CallerID">
467 <para>Caller ID to be set on the outgoing channel.</para>
469 <parameter name="Variable">
470 <para>Channel variable to set, multiple Variable: headers are allowed.</para>
472 <parameter name="Account">
473 <para>Account code.</para>
475 <parameter name="EarlyMedia">
476 <para>Set to <literal>true</literal> to force call bridge on early media..</para>
478 <parameter name="Async">
479 <para>Set to <literal>true</literal> for fast origination.</para>
481 <parameter name="Codecs">
482 <para>Comma-separated list of codecs to use for this call.</para>
486 <para>Generates an outgoing call to a
487 <replaceable>Extension</replaceable>/<replaceable>Context</replaceable>/<replaceable>Priority</replaceable>
488 or <replaceable>Application</replaceable>/<replaceable>Data</replaceable></para>
491 <ref type="managerEvent">OriginateResponse</ref>
494 <managerEvent language="en_US" name="OriginateResponse">
495 <managerEventInstance class="EVENT_FLAG_CALL">
496 <synopsis>Raised in response to an Originate command.</synopsis>
498 <parameter name="ActionID" required="false"/>
499 <parameter name="Resonse">
501 <enum name="Failure"/>
502 <enum name="Success"/>
505 <parameter name="Channel"/>
506 <parameter name="Context"/>
507 <parameter name="Exten"/>
508 <parameter name="Reason"/>
509 <parameter name="Uniqueid"/>
510 <parameter name="CallerIDNum"/>
511 <parameter name="CallerIDName"/>
514 <ref type="manager">Originate</ref>
516 </managerEventInstance>
518 <manager name="Command" language="en_US">
520 Execute Asterisk CLI Command.
523 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
524 <parameter name="Command" required="true">
525 <para>Asterisk CLI command to run.</para>
529 <para>Run a CLI command.</para>
532 <manager name="ExtensionState" language="en_US">
534 Check Extension Status.
537 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
538 <parameter name="Exten" required="true">
539 <para>Extension to check state on.</para>
541 <parameter name="Context" required="true">
542 <para>Context for extension.</para>
546 <para>Report the extension state for given extension. If the extension has a hint,
547 will use devicestate to check the status of the device connected to the extension.</para>
548 <para>Will return an <literal>Extension Status</literal> message. The response will include
549 the hint for the extension and the status.</para>
552 <manager name="PresenceState" language="en_US">
557 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
558 <parameter name="Provider" required="true">
559 <para>Presence Provider to check the state of</para>
563 <para>Report the presence state for the given presence provider.</para>
564 <para>Will return a <literal>Presence State</literal> message. The response will include the
565 presence state and, if set, a presence subtype and custom message.</para>
568 <manager name="AbsoluteTimeout" language="en_US">
570 Set absolute timeout.
573 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
574 <parameter name="Channel" required="true">
575 <para>Channel name to hangup.</para>
577 <parameter name="Timeout" required="true">
578 <para>Maximum duration of the call (sec).</para>
582 <para>Hangup a channel after a certain time. Acknowledges set time with
583 <literal>Timeout Set</literal> message.</para>
586 <manager name="MailboxStatus" language="en_US">
591 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
592 <parameter name="Mailbox" required="true">
593 <para>Full mailbox ID <replaceable>mailbox</replaceable>@<replaceable>vm-context</replaceable>.</para>
597 <para>Checks a voicemail account for status.</para>
598 <para>Returns whether there are messages waiting.</para>
599 <para>Message: Mailbox Status.</para>
600 <para>Mailbox: <replaceable>mailboxid</replaceable>.</para>
601 <para>Waiting: <literal>0</literal> if messages waiting, <literal>1</literal>
602 if no messages waiting.</para>
605 <manager name="MailboxCount" language="en_US">
607 Check Mailbox Message Count.
610 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
611 <parameter name="Mailbox" required="true">
612 <para>Full mailbox ID <replaceable>mailbox</replaceable>@<replaceable>vm-context</replaceable>.</para>
616 <para>Checks a voicemail account for new messages.</para>
617 <para>Returns number of urgent, new and old messages.</para>
618 <para>Message: Mailbox Message Count</para>
619 <para>Mailbox: <replaceable>mailboxid</replaceable></para>
620 <para>UrgentMessages: <replaceable>count</replaceable></para>
621 <para>NewMessages: <replaceable>count</replaceable></para>
622 <para>OldMessages: <replaceable>count</replaceable></para>
625 <manager name="ListCommands" language="en_US">
627 List available manager commands.
630 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
633 <para>Returns the action name and synopsis for every action that
634 is available to the user.</para>
637 <manager name="SendText" language="en_US">
639 Send text message to channel.
642 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
643 <parameter name="Channel" required="true">
644 <para>Channel to send message to.</para>
646 <parameter name="Message" required="true">
647 <para>Message to send.</para>
651 <para>Sends A Text Message to a channel while in a call.</para>
654 <manager name="UserEvent" language="en_US">
656 Send an arbitrary event.
659 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
660 <parameter name="UserEvent" required="true">
661 <para>Event string to send.</para>
663 <parameter name="Header1">
664 <para>Content1.</para>
666 <parameter name="HeaderN">
667 <para>ContentN.</para>
671 <para>Send an event to manager sessions.</para>
674 <manager name="WaitEvent" language="en_US">
676 Wait for an event to occur.
679 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
680 <parameter name="Timeout" required="true">
681 <para>Maximum time (in seconds) to wait for events, <literal>-1</literal> means forever.</para>
685 <para>This action will ellicit a <literal>Success</literal> response. Whenever
686 a manager event is queued. Once WaitEvent has been called on an HTTP manager
687 session, events will be generated and queued.</para>
690 <manager name="CoreSettings" language="en_US">
692 Show PBX core settings (version etc).
695 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
698 <para>Query for Core PBX settings.</para>
701 <manager name="CoreStatus" language="en_US">
703 Show PBX core status variables.
706 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
709 <para>Query for Core PBX status.</para>
712 <manager name="Reload" language="en_US">
717 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
718 <parameter name="Module">
719 <para>Name of the module to reload.</para>
723 <para>Send a reload event.</para>
726 <manager name="CoreShowChannels" language="en_US">
728 List currently active channels.
731 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
734 <para>List currently defined channels and some information about them.</para>
737 <manager name="ModuleLoad" language="en_US">
742 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
743 <parameter name="Module">
744 <para>Asterisk module name (including .so extension) or subsystem identifier:</para>
747 <enum name="dnsmgr" />
748 <enum name="extconfig" />
751 <enum name="manager" />
753 <enum name="logger" />
754 <enum name="features" />
756 <enum name="udptl" />
757 <enum name="indications" />
762 <parameter name="LoadType" required="true">
763 <para>The operation to be done on module. Subsystem identifiers may only
767 <enum name="unload" />
768 <enum name="reload" />
770 <para>If no module is specified for a <literal>reload</literal> loadtype,
771 all modules are reloaded.</para>
775 <para>Loads, unloads or reloads an Asterisk module in a running system.</para>
778 <manager name="ModuleCheck" language="en_US">
780 Check if module is loaded.
783 <parameter name="Module" required="true">
784 <para>Asterisk module name (not including extension).</para>
788 <para>Checks if Asterisk module is loaded. Will return Success/Failure.
789 For success returns, the module revision number is included.</para>
792 <manager name="AOCMessage" language="en_US">
794 Generate an Advice of Charge message on a channel.
797 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
798 <parameter name="Channel" required="true">
799 <para>Channel name to generate the AOC message on.</para>
801 <parameter name="ChannelPrefix">
802 <para>Partial channel prefix. By using this option one can match the beginning part
803 of a channel name without having to put the entire name in. For example
804 if a channel name is SIP/snom-00000001 and this value is set to SIP/snom, then
805 that channel matches and the message will be sent. Note however that only
806 the first matched channel has the message sent on it. </para>
808 <parameter name="MsgType" required="true">
809 <para>Defines what type of AOC message to create, AOC-D or AOC-E</para>
815 <parameter name="ChargeType" required="true">
816 <para>Defines what kind of charge this message represents.</para>
820 <enum name="Currency" />
824 <parameter name="UnitAmount(0)">
825 <para>This represents the amount of units charged. The ETSI AOC standard specifies that
826 this value along with the optional UnitType value are entries in a list. To accommodate this
827 these values take an index value starting at 0 which can be used to generate this list of
828 unit entries. For Example, If two unit entires were required this could be achieved by setting the
829 paramter UnitAmount(0)=1234 and UnitAmount(1)=5678. Note that UnitAmount at index 0 is
830 required when ChargeType=Unit, all other entries in the list are optional.
833 <parameter name="UnitType(0)">
834 <para>Defines the type of unit. ETSI AOC standard specifies this as an integer
835 value between 1 and 16, but this value is left open to accept any positive
836 integer. Like the UnitAmount parameter, this value represents a list entry
837 and has an index parameter that starts at 0.
840 <parameter name="CurrencyName">
841 <para>Specifies the currency's name. Note that this value is truncated after 10 characters.</para>
843 <parameter name="CurrencyAmount">
844 <para>Specifies the charge unit amount as a positive integer. This value is required
845 when ChargeType==Currency.</para>
847 <parameter name="CurrencyMultiplier">
848 <para>Specifies the currency multiplier. This value is required when ChargeType==Currency.</para>
850 <enum name="OneThousandth" />
851 <enum name="OneHundredth" />
852 <enum name="OneTenth" />
855 <enum name="Hundred" />
856 <enum name="Thousand" />
859 <parameter name="TotalType" default="Total">
860 <para>Defines what kind of AOC-D total is represented.</para>
862 <enum name="Total" />
863 <enum name="SubTotal" />
866 <parameter name="AOCBillingId">
867 <para>Represents a billing ID associated with an AOC-D or AOC-E message. Note
868 that only the first 3 items of the enum are valid AOC-D billing IDs</para>
870 <enum name="Normal" />
871 <enum name="ReverseCharge" />
872 <enum name="CreditCard" />
873 <enum name="CallFwdUnconditional" />
874 <enum name="CallFwdBusy" />
875 <enum name="CallFwdNoReply" />
876 <enum name="CallDeflection" />
877 <enum name="CallTransfer" />
880 <parameter name="ChargingAssociationId">
881 <para>Charging association identifier. This is optional for AOC-E and can be
882 set to any value between -32768 and 32767</para>
884 <parameter name="ChargingAssociationNumber">
885 <para>Represents the charging association party number. This value is optional
888 <parameter name="ChargingAssociationPlan">
889 <para>Integer representing the charging plan associated with the ChargingAssociationNumber.
890 The value is bits 7 through 1 of the Q.931 octet containing the type-of-number and
891 numbering-plan-identification fields.</para>
895 <para>Generates an AOC-D or AOC-E message on a channel.</para>
898 <function name="AMI_CLIENT" language="en_US">
900 Checks attributes of manager accounts
903 <parameter name="loginname" required="true">
904 <para>Login name, specified in manager.conf</para>
906 <parameter name="field" required="true">
907 <para>The manager account attribute to return</para>
909 <enum name="sessions"><para>The number of sessions for this AMI account</para></enum>
915 Currently, the only supported parameter is "sessions" which will return the current number of
916 active sessions for this AMI account.
920 <manager name="Filter" language="en_US">
922 Dynamically add filters for the current manager session.
925 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
926 <parameter name="Operation">
929 <para>Add a filter.</para>
933 <parameter name="Filter">
934 <para>Filters can be whitelist or blacklist</para>
935 <para>Example whitelist filter: "Event: Newchannel"</para>
936 <para>Example blacklist filter: "!Channel: DAHDI.*"</para>
937 <para>This filter option is used to whitelist or blacklist events per user to be
938 reported with regular expressions and are allowed if both the regex matches
939 and the user has read access as defined in manager.conf. Filters are assumed to be for whitelisting
940 unless preceeded by an exclamation point, which marks it as being black.
941 Evaluation of the filters is as follows:</para>
942 <para>- If no filters are configured all events are reported as normal.</para>
943 <para>- If there are white filters only: implied black all filter processed first, then white filters.</para>
944 <para>- If there are black filters only: implied white all filter processed first, then black filters.</para>
945 <para>- If there are both white and black filters: implied black all filter processed first, then white
946 filters, and lastly black filters.</para>
950 <para>The filters added are only used for the current session.
951 Once the connection is closed the filters are removed.</para>
952 <para>This comand requires the system permission because
953 this command can be used to create filters that may bypass
954 filters defined in manager.conf</para>
957 <manager name="FilterList" language="en_US">
959 Show current event filters for this session
962 <para>The filters displayed are for the current session. Only those filters defined in
963 manager.conf will be present upon starting a new session.</para>
968 /*! \addtogroup Group_AMI AMI functions
976 UNSPECIFIED_CATEGORY,
977 UNSPECIFIED_ARGUMENT,
987 enum add_filter_result {
994 * Linked list of events.
995 * Global events are appended to the list by append_event().
996 * The usecount is the number of stored pointers to the element,
997 * excluding the list pointers. So an element that is only in
998 * the list has a usecount of 0, not 1.
1000 * Clients have a pointer to the last event processed, and for each
1001 * of these clients we track the usecount of the elements.
1002 * If we have a pointer to an entry in the list, it is safe to navigate
1003 * it forward because elements will not be deleted, but only appended.
1004 * The worst that can happen is seeing the pointer still NULL.
1006 * When the usecount of an element drops to 0, and the element is the
1007 * first in the list, we can remove it. Removal is done within the
1008 * main thread, which is woken up for the purpose.
1010 * For simplicity of implementation, we make sure the list is never empty.
1013 int usecount; /*!< # of clients who still need the event */
1015 unsigned int seq; /*!< sequence number */
1016 struct timeval tv; /*!< When event was allocated */
1017 AST_RWLIST_ENTRY(eventqent) eq_next;
1018 char eventdata[1]; /*!< really variable size, allocated by append_event() */
1021 static AST_RWLIST_HEAD_STATIC(all_events, eventqent);
1023 static int displayconnects = 1;
1024 static int allowmultiplelogin = 1;
1025 static int timestampevents;
1026 static int httptimeout = 60;
1027 static int broken_events_action = 0;
1028 static int manager_enabled = 0;
1029 static int webmanager_enabled = 0;
1030 static int manager_debug = 0; /*!< enable some debugging code in the manager */
1031 static int authtimeout;
1032 static int authlimit;
1033 static char *manager_channelvars;
1035 #define DEFAULT_REALM "asterisk"
1036 static char global_realm[MAXHOSTNAMELEN]; /*!< Default realm */
1038 static int block_sockets;
1039 static int unauth_sessions = 0;
1040 static struct ast_event_sub *acl_change_event_subscription;
1042 #define MGR_SHOW_TERMINAL_WIDTH 80
1045 * Descriptor for a manager session, either on the AMI socket or over HTTP.
1048 * AMI session have managerid == 0; the entry is created upon a connect,
1049 * and destroyed with the socket.
1050 * HTTP sessions have managerid != 0, the value is used as a search key
1051 * to lookup sessions (using the mansession_id cookie, or nonce key from
1052 * Digest Authentication http header).
1054 #define MAX_BLACKLIST_CMD_LEN 2
1055 static const struct {
1056 const char *words[AST_MAX_CMD_LEN];
1057 } command_blacklist[] = {
1058 {{ "module", "load", NULL }},
1059 {{ "module", "unload", NULL }},
1060 {{ "restart", "gracefully", NULL }},
1063 static void acl_change_event_cb(const struct ast_event *event, void *userdata);
1065 static void acl_change_event_subscribe(void)
1067 if (!acl_change_event_subscription) {
1068 acl_change_event_subscription = ast_event_subscribe(AST_EVENT_ACL_CHANGE,
1069 acl_change_event_cb, "Manager must react to Named ACL changes", NULL, AST_EVENT_IE_END);
1073 static void acl_change_event_unsubscribe(void)
1075 if (acl_change_event_subscription) {
1076 acl_change_event_subscription = ast_event_unsubscribe(acl_change_event_subscription);
1080 /* In order to understand what the heck is going on with the
1081 * mansession_session and mansession structs, we need to have a bit of a history
1084 * In the beginning, there was the mansession. The mansession contained data that was
1085 * intrinsic to a manager session, such as the time that it started, the name of the logged-in
1086 * user, etc. In addition to these parameters were the f and fd parameters. For typical manager
1087 * sessions, these were used to represent the TCP socket over which the AMI session was taking
1088 * place. It makes perfect sense for these fields to be a part of the session-specific data since
1089 * the session actually defines this information.
1091 * Then came the HTTP AMI sessions. With these, the f and fd fields need to be opened and closed
1092 * for every single action that occurs. Thus the f and fd fields aren't really specific to the session
1093 * but rather to the action that is being executed. Because a single session may execute many commands
1094 * at once, some sort of safety needed to be added in order to be sure that we did not end up with fd
1095 * leaks from one action overwriting the f and fd fields used by a previous action before the previous action
1096 * has had a chance to properly close its handles.
1098 * The initial idea to solve this was to use thread synchronization, but this prevented multiple actions
1099 * from being run at the same time in a single session. Some manager actions may block for a long time, thus
1100 * creating a large queue of actions to execute. In addition, this fix did not address the basic architectural
1101 * issue that for HTTP manager sessions, the f and fd variables are not really a part of the session, but are
1102 * part of the action instead.
1104 * The new idea was to create a structure on the stack for each HTTP Manager action. This structure would
1105 * contain the action-specific information, such as which file to write to. In order to maintain expectations
1106 * of action handlers and not have to change the public API of the manager code, we would need to name this
1107 * new stacked structure 'mansession' and contain within it the old mansession struct that we used to use.
1108 * We renamed the old mansession struct 'mansession_session' to hopefully convey that what is in this structure
1109 * is session-specific data. The structure that it is wrapped in, called a 'mansession' really contains action-specific
1112 struct mansession_session {
1113 /*! \todo XXX need to document which fields it is protecting */
1114 struct ast_sockaddr addr; /*!< address we are connecting from */
1115 FILE *f; /*!< fdopen() on the underlying fd */
1116 int fd; /*!< descriptor used for output. Either the socket (AMI) or a temporary file (HTTP) */
1117 int inuse; /*!< number of HTTP sessions using this entry */
1118 int needdestroy; /*!< Whether an HTTP session should be destroyed */
1119 pthread_t waiting_thread; /*!< Sleeping thread using this descriptor */
1120 uint32_t managerid; /*!< Unique manager identifier, 0 for AMI sessions */
1121 time_t sessionstart; /*!< Session start time */
1122 struct timeval sessionstart_tv; /*!< Session start time */
1123 time_t sessiontimeout; /*!< Session timeout if HTTP */
1124 char username[80]; /*!< Logged in username */
1125 char challenge[10]; /*!< Authentication challenge */
1126 int authenticated; /*!< Authentication status */
1127 int readperm; /*!< Authorization for reading */
1128 int writeperm; /*!< Authorization for writing */
1129 char inbuf[1025]; /*!< Buffer - we use the extra byte to add a '\\0' and simplify parsing */
1130 int inlen; /*!< number of buffered bytes */
1131 struct ao2_container *whitefilters; /*!< Manager event filters - white list */
1132 struct ao2_container *blackfilters; /*!< Manager event filters - black list */
1133 struct ast_variable *chanvars; /*!< Channel variables to set for originate */
1134 int send_events; /*!< XXX what ? */
1135 struct eventqent *last_ev; /*!< last event processed. */
1136 int writetimeout; /*!< Timeout for ast_carefulwrite() */
1138 int pending_event; /*!< Pending events indicator in case when waiting_thread is NULL */
1139 time_t noncetime; /*!< Timer for nonce value expiration */
1140 unsigned long oldnonce; /*!< Stale nonce value */
1141 unsigned long nc; /*!< incremental nonce counter */
1142 AST_LIST_HEAD_NOLOCK(mansession_datastores, ast_datastore) datastores; /*!< Data stores on the session */
1143 AST_LIST_ENTRY(mansession_session) list;
1146 enum mansession_message_parsing {
1148 MESSAGE_LINE_TOO_LONG
1151 /*! \brief In case you didn't read that giant block of text above the mansession_session struct, the
1152 * \ref struct mansession is named this solely to keep the API the same in Asterisk. This structure really
1153 * represents data that is different from Manager action to Manager action. The mansession_session pointer
1154 * contained within points to session-specific data.
1157 struct mansession_session *session;
1158 struct ast_tcptls_session_instance *tcptls_session;
1161 enum mansession_message_parsing parsing;
1163 struct manager_custom_hook *hook;
1167 static struct ao2_container *sessions = NULL;
1169 struct manager_channel_variable {
1170 AST_LIST_ENTRY(manager_channel_variable) entry;
1171 unsigned int isfunc:1;
1172 char name[0]; /* allocate off the end the real size. */
1175 static AST_RWLIST_HEAD_STATIC(channelvars, manager_channel_variable);
1177 /*! \brief user descriptor, as read from the config file.
1179 * \note It is still missing some fields -- e.g. we can have multiple permit and deny
1180 * lines which are not supported here, and readperm/writeperm/writetimeout
1183 struct ast_manager_user {
1185 char *secret; /*!< Secret for logging in */
1186 int readperm; /*!< Authorization for reading */
1187 int writeperm; /*!< Authorization for writing */
1188 int writetimeout; /*!< Per user Timeout for ast_carefulwrite() */
1189 int displayconnects; /*!< XXX unused */
1190 int keep; /*!< mark entries created on a reload */
1191 struct ao2_container *whitefilters; /*!< Manager event filters - white list */
1192 struct ao2_container *blackfilters; /*!< Manager event filters - black list */
1193 struct ast_acl_list *acl; /*!< ACL setting */
1194 char *a1_hash; /*!< precalculated A1 for Digest auth */
1195 struct ast_variable *chanvars; /*!< Channel variables to set for originate */
1196 AST_RWLIST_ENTRY(ast_manager_user) list;
1199 /*! \brief list of users found in the config file */
1200 static AST_RWLIST_HEAD_STATIC(users, ast_manager_user);
1202 /*! \brief list of actions registered */
1203 static AST_RWLIST_HEAD_STATIC(actions, manager_action);
1205 /*! \brief list of hooks registered */
1206 static AST_RWLIST_HEAD_STATIC(manager_hooks, manager_custom_hook);
1208 /*! \brief A container of event documentation nodes */
1209 AO2_GLOBAL_OBJ_STATIC(event_docs);
1211 static void free_channelvars(void);
1213 static enum add_filter_result manager_add_filter(const char *filter_pattern, struct ao2_container *whitefilters, struct ao2_container *blackfilters);
1217 * \brief Find a registered action object.
1219 * \param name Name of AMI action to find.
1221 * \return Reffed action found or NULL
1223 static struct manager_action *action_find(const char *name)
1225 struct manager_action *act;
1227 AST_RWLIST_RDLOCK(&actions);
1228 AST_RWLIST_TRAVERSE(&actions, act, list) {
1229 if (!strcasecmp(name, act->action)) {
1230 ao2_t_ref(act, +1, "found action object");
1234 AST_RWLIST_UNLOCK(&actions);
1239 /*! \brief Add a custom hook to be called when an event is fired */
1240 void ast_manager_register_hook(struct manager_custom_hook *hook)
1242 AST_RWLIST_WRLOCK(&manager_hooks);
1243 AST_RWLIST_INSERT_TAIL(&manager_hooks, hook, list);
1244 AST_RWLIST_UNLOCK(&manager_hooks);
1247 /*! \brief Delete a custom hook to be called when an event is fired */
1248 void ast_manager_unregister_hook(struct manager_custom_hook *hook)
1250 AST_RWLIST_WRLOCK(&manager_hooks);
1251 AST_RWLIST_REMOVE(&manager_hooks, hook, list);
1252 AST_RWLIST_UNLOCK(&manager_hooks);
1255 int check_manager_enabled(void)
1257 return manager_enabled;
1260 int check_webmanager_enabled(void)
1262 return (webmanager_enabled && manager_enabled);
1266 * Grab a reference to the last event, update usecount as needed.
1267 * Can handle a NULL pointer.
1269 static struct eventqent *grab_last(void)
1271 struct eventqent *ret;
1273 AST_RWLIST_WRLOCK(&all_events);
1274 ret = AST_RWLIST_LAST(&all_events);
1275 /* the list is never empty now, but may become so when
1276 * we optimize it in the future, so be prepared.
1279 ast_atomic_fetchadd_int(&ret->usecount, 1);
1281 AST_RWLIST_UNLOCK(&all_events);
1286 * Purge unused events. Remove elements from the head
1287 * as long as their usecount is 0 and there is a next element.
1289 static void purge_events(void)
1291 struct eventqent *ev;
1292 struct timeval now = ast_tvnow();
1294 AST_RWLIST_WRLOCK(&all_events);
1295 while ( (ev = AST_RWLIST_FIRST(&all_events)) &&
1296 ev->usecount == 0 && AST_RWLIST_NEXT(ev, eq_next)) {
1297 AST_RWLIST_REMOVE_HEAD(&all_events, eq_next);
1301 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&all_events, ev, eq_next) {
1302 /* Never release the last event */
1303 if (!AST_RWLIST_NEXT(ev, eq_next)) {
1307 /* 2.5 times whatever the HTTP timeout is (maximum 2.5 hours) is the maximum time that we will definitely cache an event */
1308 if (ev->usecount == 0 && ast_tvdiff_sec(now, ev->tv) > (httptimeout > 3600 ? 3600 : httptimeout) * 2.5) {
1309 AST_RWLIST_REMOVE_CURRENT(eq_next);
1313 AST_RWLIST_TRAVERSE_SAFE_END;
1314 AST_RWLIST_UNLOCK(&all_events);
1318 * helper functions to convert back and forth between
1319 * string and numeric representation of set of flags
1321 static const struct permalias {
1325 { EVENT_FLAG_SYSTEM, "system" },
1326 { EVENT_FLAG_CALL, "call" },
1327 { EVENT_FLAG_LOG, "log" },
1328 { EVENT_FLAG_VERBOSE, "verbose" },
1329 { EVENT_FLAG_COMMAND, "command" },
1330 { EVENT_FLAG_AGENT, "agent" },
1331 { EVENT_FLAG_USER, "user" },
1332 { EVENT_FLAG_CONFIG, "config" },
1333 { EVENT_FLAG_DTMF, "dtmf" },
1334 { EVENT_FLAG_REPORTING, "reporting" },
1335 { EVENT_FLAG_CDR, "cdr" },
1336 { EVENT_FLAG_DIALPLAN, "dialplan" },
1337 { EVENT_FLAG_ORIGINATE, "originate" },
1338 { EVENT_FLAG_AGI, "agi" },
1339 { EVENT_FLAG_CC, "cc" },
1340 { EVENT_FLAG_AOC, "aoc" },
1341 { EVENT_FLAG_TEST, "test" },
1342 { EVENT_FLAG_MESSAGE, "message" },
1347 /*! \brief Checks to see if a string which can be used to evaluate functions should be rejected */
1348 static int function_capable_string_allowed_with_auths(const char *evaluating, int writepermlist)
1350 if (!(writepermlist & EVENT_FLAG_SYSTEM)
1352 strstr(evaluating, "SHELL") || /* NoOp(${SHELL(rm -rf /)}) */
1353 strstr(evaluating, "EVAL") /* NoOp(${EVAL(${some_var_containing_SHELL})}) */
1360 /*! \brief Convert authority code to a list of options for a user. This will only
1361 * display those authority codes that have an explicit match on authority */
1362 static const char *user_authority_to_str(int authority, struct ast_str **res)
1367 ast_str_reset(*res);
1368 for (i = 0; i < ARRAY_LEN(perms) - 1; i++) {
1369 if ((authority & perms[i].num) == perms[i].num) {
1370 ast_str_append(res, 0, "%s%s", sep, perms[i].label);
1375 if (ast_str_strlen(*res) == 0) /* replace empty string with something sensible */
1376 ast_str_append(res, 0, "<none>");
1378 return ast_str_buffer(*res);
1382 /*! \brief Convert authority code to a list of options. Note that the EVENT_FLAG_ALL
1383 * authority will always be returned. */
1384 static const char *authority_to_str(int authority, struct ast_str **res)
1389 ast_str_reset(*res);
1390 for (i = 0; i < ARRAY_LEN(perms) - 1; i++) {
1391 if (authority & perms[i].num) {
1392 ast_str_append(res, 0, "%s%s", sep, perms[i].label);
1397 if (ast_str_strlen(*res) == 0) /* replace empty string with something sensible */
1398 ast_str_append(res, 0, "<none>");
1400 return ast_str_buffer(*res);
1403 /*! Tells you if smallstr exists inside bigstr
1404 which is delim by delim and uses no buf or stringsep
1405 ast_instring("this|that|more","this",'|') == 1;
1407 feel free to move this to app.c -anthm */
1408 static int ast_instring(const char *bigstr, const char *smallstr, const char delim)
1410 const char *val = bigstr, *next;
1413 if ((next = strchr(val, delim))) {
1414 if (!strncmp(val, smallstr, (next - val))) {
1420 return !strcmp(smallstr, val);
1422 } while (*(val = (next + 1)));
1427 static int get_perm(const char *instr)
1435 for (x = 0; x < ARRAY_LEN(perms); x++) {
1436 if (ast_instring(instr, perms[x].label, ',')) {
1437 ret |= perms[x].num;
1445 * A number returns itself, false returns 0, true returns all flags,
1446 * other strings return the flags that are set.
1448 static int strings_to_mask(const char *string)
1452 if (ast_strlen_zero(string)) {
1456 for (p = string; *p; p++) {
1457 if (*p < '0' || *p > '9') {
1461 if (!*p) { /* all digits */
1462 return atoi(string);
1464 if (ast_false(string)) {
1467 if (ast_true(string)) { /* all permissions */
1469 for (x = 0; x < ARRAY_LEN(perms); x++) {
1470 ret |= perms[x].num;
1474 return get_perm(string);
1477 /*! \brief Unreference manager session object.
1478 If no more references, then go ahead and delete it */
1479 static struct mansession_session *unref_mansession(struct mansession_session *s)
1481 int refcount = ao2_ref(s, -1);
1482 if (manager_debug) {
1483 ast_debug(1, "Mansession: %p refcount now %d\n", s, refcount - 1);
1488 static void event_filter_destructor(void *obj)
1490 regex_t *regex_filter = obj;
1491 regfree(regex_filter);
1494 static void session_destructor(void *obj)
1496 struct mansession_session *session = obj;
1497 struct eventqent *eqe = session->last_ev;
1498 struct ast_datastore *datastore;
1500 /* Get rid of each of the data stores on the session */
1501 while ((datastore = AST_LIST_REMOVE_HEAD(&session->datastores, entry))) {
1502 /* Free the data store */
1503 ast_datastore_free(datastore);
1506 if (session->f != NULL) {
1510 ast_atomic_fetchadd_int(&eqe->usecount, -1);
1512 if (session->chanvars) {
1513 ast_variables_destroy(session->chanvars);
1516 if (session->whitefilters) {
1517 ao2_t_callback(session->whitefilters, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL, "unlink all white filters");
1518 ao2_t_ref(session->whitefilters, -1 , "decrement ref for white container, should be last one");
1521 if (session->blackfilters) {
1522 ao2_t_callback(session->blackfilters, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL, "unlink all black filters");
1523 ao2_t_ref(session->blackfilters, -1 , "decrement ref for black container, should be last one");
1527 /*! \brief Allocate manager session structure and add it to the list of sessions */
1528 static struct mansession_session *build_mansession(const struct ast_sockaddr *addr)
1530 struct mansession_session *newsession;
1532 if (!(newsession = ao2_alloc(sizeof(*newsession), session_destructor))) {
1536 if (!(newsession->whitefilters = ao2_container_alloc(1, NULL, NULL))) {
1537 ao2_ref(newsession, -1);
1541 if (!(newsession->blackfilters = ao2_container_alloc(1, NULL, NULL))) {
1542 ao2_ref(newsession, -1); /* session_destructor will cleanup the other filter */
1546 newsession->fd = -1;
1547 newsession->waiting_thread = AST_PTHREADT_NULL;
1548 newsession->writetimeout = 100;
1549 newsession->send_events = -1;
1550 ast_sockaddr_copy(&newsession->addr, addr);
1552 ao2_link(sessions, newsession);
1557 static int mansession_cmp_fn(void *obj, void *arg, int flags)
1559 struct mansession_session *s = obj;
1561 return !strcasecmp(s->username, str) ? CMP_MATCH : 0;
1564 static void session_destroy(struct mansession_session *s)
1566 unref_mansession(s);
1567 ao2_unlink(sessions, s);
1571 static int check_manager_session_inuse(const char *name)
1573 struct mansession_session *session = ao2_find(sessions, (char *) name, 0);
1578 unref_mansession(session);
1585 * lookup an entry in the list of registered users.
1586 * must be called with the list lock held.
1588 static struct ast_manager_user *get_manager_by_name_locked(const char *name)
1590 struct ast_manager_user *user = NULL;
1592 AST_RWLIST_TRAVERSE(&users, user, list) {
1593 if (!strcasecmp(user->username, name)) {
1601 /*! \brief Get displayconnects config option.
1602 * \param session manager session to get parameter from.
1603 * \return displayconnects config option value.
1605 static int manager_displayconnects (struct mansession_session *session)
1607 struct ast_manager_user *user = NULL;
1610 AST_RWLIST_RDLOCK(&users);
1611 if ((user = get_manager_by_name_locked (session->username))) {
1612 ret = user->displayconnects;
1614 AST_RWLIST_UNLOCK(&users);
1619 static char *handle_showmancmd(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1621 struct manager_action *cur;
1622 struct ast_str *authority;
1626 char syntax_title[64], description_title[64], synopsis_title[64], seealso_title[64], arguments_title[64], privilege_title[64];
1631 e->command = "manager show command";
1633 "Usage: manager show command <actionname> [<actionname> [<actionname> [...]]]\n"
1634 " Shows the detailed description for a specific Asterisk manager interface command.\n";
1637 l = strlen(a->word);
1639 AST_RWLIST_RDLOCK(&actions);
1640 AST_RWLIST_TRAVERSE(&actions, cur, list) {
1641 if (!strncasecmp(a->word, cur->action, l) && ++which > a->n) {
1642 ret = ast_strdup(cur->action);
1643 break; /* make sure we exit even if ast_strdup() returns NULL */
1646 AST_RWLIST_UNLOCK(&actions);
1649 authority = ast_str_alloca(80);
1651 return CLI_SHOWUSAGE;
1655 /* setup the titles */
1656 term_color(synopsis_title, "[Synopsis]\n", COLOR_MAGENTA, 0, 40);
1657 term_color(description_title, "[Description]\n", COLOR_MAGENTA, 0, 40);
1658 term_color(syntax_title, "[Syntax]\n", COLOR_MAGENTA, 0, 40);
1659 term_color(seealso_title, "[See Also]\n", COLOR_MAGENTA, 0, 40);
1660 term_color(arguments_title, "[Arguments]\n", COLOR_MAGENTA, 0, 40);
1661 term_color(privilege_title, "[Privilege]\n", COLOR_MAGENTA, 0, 40);
1664 AST_RWLIST_RDLOCK(&actions);
1665 AST_RWLIST_TRAVERSE(&actions, cur, list) {
1666 for (num = 3; num < a->argc; num++) {
1667 if (!strcasecmp(cur->action, a->argv[num])) {
1668 authority_to_str(cur->authority, &authority);
1671 if (cur->docsrc == AST_XML_DOC) {
1672 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",
1674 ast_xmldoc_printable(S_OR(cur->syntax, "Not available"), 1),
1676 ast_xmldoc_printable(S_OR(cur->synopsis, "Not available"), 1),
1678 ast_xmldoc_printable(S_OR(cur->description, "Not available"), 1),
1680 ast_xmldoc_printable(S_OR(cur->arguments, "Not available"), 1),
1682 ast_xmldoc_printable(S_OR(cur->seealso, "Not available"), 1),
1684 ast_xmldoc_printable(S_OR(authority->str, "Not available"), 1));
1688 ast_cli(a->fd, "Action: %s\nSynopsis: %s\nPrivilege: %s\n%s\n",
1689 cur->action, cur->synopsis,
1691 S_OR(cur->description, ""));
1696 AST_RWLIST_UNLOCK(&actions);
1701 static char *handle_mandebug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1705 e->command = "manager set debug [on|off]";
1706 e->usage = "Usage: manager set debug [on|off]\n Show, enable, disable debugging of the manager code.\n";
1713 ast_cli(a->fd, "manager debug is %s\n", manager_debug? "on" : "off");
1714 } else if (a->argc == 4) {
1715 if (!strcasecmp(a->argv[3], "on")) {
1717 } else if (!strcasecmp(a->argv[3], "off")) {
1720 return CLI_SHOWUSAGE;
1726 static char *handle_showmanager(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1728 struct ast_manager_user *user = NULL;
1731 struct ast_str *rauthority = ast_str_alloca(128);
1732 struct ast_str *wauthority = ast_str_alloca(128);
1733 struct ast_variable *v;
1737 e->command = "manager show user";
1739 " Usage: manager show user <user>\n"
1740 " Display all information related to the manager user specified.\n";
1743 l = strlen(a->word);
1748 AST_RWLIST_RDLOCK(&users);
1749 AST_RWLIST_TRAVERSE(&users, user, list) {
1750 if ( !strncasecmp(a->word, user->username, l) && ++which > a->n ) {
1751 ret = ast_strdup(user->username);
1755 AST_RWLIST_UNLOCK(&users);
1760 return CLI_SHOWUSAGE;
1763 AST_RWLIST_RDLOCK(&users);
1765 if (!(user = get_manager_by_name_locked(a->argv[3]))) {
1766 ast_cli(a->fd, "There is no manager called %s\n", a->argv[3]);
1767 AST_RWLIST_UNLOCK(&users);
1771 ast_cli(a->fd, "\n");
1778 "displayconnects: %s\n",
1779 (user->username ? user->username : "(N/A)"),
1780 (user->secret ? "<Set>" : "(N/A)"),
1781 ((user->acl && !ast_acl_list_is_empty(user->acl)) ? "yes" : "no"),
1782 user_authority_to_str(user->readperm, &rauthority),
1783 user_authority_to_str(user->writeperm, &wauthority),
1784 (user->displayconnects ? "yes" : "no"));
1785 ast_cli(a->fd, " Variables: \n");
1786 for (v = user->chanvars ; v ; v = v->next) {
1787 ast_cli(a->fd, " %s = %s\n", v->name, v->value);
1790 AST_RWLIST_UNLOCK(&users);
1795 static char *handle_showmanagers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1797 struct ast_manager_user *user = NULL;
1801 e->command = "manager show users";
1803 "Usage: manager show users\n"
1804 " Prints a listing of all managers that are currently configured on that\n"
1811 return CLI_SHOWUSAGE;
1814 AST_RWLIST_RDLOCK(&users);
1816 /* If there are no users, print out something along those lines */
1817 if (AST_RWLIST_EMPTY(&users)) {
1818 ast_cli(a->fd, "There are no manager users.\n");
1819 AST_RWLIST_UNLOCK(&users);
1823 ast_cli(a->fd, "\nusername\n--------\n");
1825 AST_RWLIST_TRAVERSE(&users, user, list) {
1826 ast_cli(a->fd, "%s\n", user->username);
1830 AST_RWLIST_UNLOCK(&users);
1832 ast_cli(a->fd,"-------------------\n"
1833 "%d manager users configured.\n", count_amu);
1837 /*! \brief CLI command manager list commands */
1838 static char *handle_showmancmds(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1840 struct manager_action *cur;
1842 int space_remaining;
1843 #define HSMC_FORMAT " %-*.*s %-.*s\n"
1846 e->command = "manager show commands";
1848 "Usage: manager show commands\n"
1849 " Prints a listing of all the available Asterisk manager interface commands.\n";
1855 AST_RWLIST_RDLOCK(&actions);
1856 AST_RWLIST_TRAVERSE(&actions, cur, list) {
1857 int incoming_len = strlen(cur->action);
1858 if (incoming_len > name_len) {
1859 name_len = incoming_len;
1863 space_remaining = MGR_SHOW_TERMINAL_WIDTH - name_len - 4;
1864 if (space_remaining < 0) {
1865 space_remaining = 0;
1868 ast_cli(a->fd, HSMC_FORMAT, name_len, name_len, "Action", space_remaining, "Synopsis");
1869 ast_cli(a->fd, HSMC_FORMAT, name_len, name_len, "------", space_remaining, "--------");
1871 AST_RWLIST_TRAVERSE(&actions, cur, list) {
1872 ast_cli(a->fd, HSMC_FORMAT, name_len, name_len, cur->action, space_remaining, cur->synopsis);
1874 AST_RWLIST_UNLOCK(&actions);
1879 /*! \brief CLI command manager list connected */
1880 static char *handle_showmanconn(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1882 struct mansession_session *session;
1883 time_t now = time(NULL);
1884 #define HSMCONN_FORMAT1 " %-15.15s %-55.55s %-10.10s %-10.10s %-8.8s %-8.8s %-5.5s %-5.5s\n"
1885 #define HSMCONN_FORMAT2 " %-15.15s %-55.55s %-10d %-10d %-8d %-8d %-5.5d %-5.5d\n"
1887 struct ao2_iterator i;
1891 e->command = "manager show connected";
1893 "Usage: manager show connected\n"
1894 " Prints a listing of the users that are currently connected to the\n"
1895 "Asterisk manager interface.\n";
1901 ast_cli(a->fd, HSMCONN_FORMAT1, "Username", "IP Address", "Start", "Elapsed", "FileDes", "HttpCnt", "Read", "Write");
1903 i = ao2_iterator_init(sessions, 0);
1904 while ((session = ao2_iterator_next(&i))) {
1906 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);
1908 ao2_unlock(session);
1909 unref_mansession(session);
1911 ao2_iterator_destroy(&i);
1912 ast_cli(a->fd, "%d users connected.\n", count);
1917 /*! \brief CLI command manager list eventq */
1918 /* Should change to "manager show connected" */
1919 static char *handle_showmaneventq(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1921 struct eventqent *s;
1924 e->command = "manager show eventq";
1926 "Usage: manager show eventq\n"
1927 " Prints a listing of all events pending in the Asterisk manger\n"
1933 AST_RWLIST_RDLOCK(&all_events);
1934 AST_RWLIST_TRAVERSE(&all_events, s, eq_next) {
1935 ast_cli(a->fd, "Usecount: %d\n", s->usecount);
1936 ast_cli(a->fd, "Category: %d\n", s->category);
1937 ast_cli(a->fd, "Event:\n%s", s->eventdata);
1939 AST_RWLIST_UNLOCK(&all_events);
1944 /*! \brief CLI command manager reload */
1945 static char *handle_manager_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1949 e->command = "manager reload";
1951 "Usage: manager reload\n"
1952 " Reloads the manager configuration.\n";
1958 return CLI_SHOWUSAGE;
1964 static struct eventqent *advance_event(struct eventqent *e)
1966 struct eventqent *next;
1968 AST_RWLIST_RDLOCK(&all_events);
1969 if ((next = AST_RWLIST_NEXT(e, eq_next))) {
1970 ast_atomic_fetchadd_int(&next->usecount, 1);
1971 ast_atomic_fetchadd_int(&e->usecount, -1);
1973 AST_RWLIST_UNLOCK(&all_events);
1977 #define GET_HEADER_FIRST_MATCH 0
1978 #define GET_HEADER_LAST_MATCH 1
1979 #define GET_HEADER_SKIP_EMPTY 2
1982 * \brief Return a matching header value.
1985 * Generic function to return either the first or the last
1986 * matching header from a list of variables, possibly skipping
1989 * \note At the moment there is only one use of this function in
1990 * this file, so we make it static.
1992 * \note Never returns NULL.
1994 static const char *__astman_get_header(const struct message *m, char *var, int mode)
1996 int x, l = strlen(var);
1997 const char *result = "";
2003 for (x = 0; x < m->hdrcount; x++) {
2004 const char *h = m->headers[x];
2005 if (!strncasecmp(var, h, l) && h[l] == ':') {
2006 const char *value = h + l + 1;
2007 value = ast_skip_blanks(value); /* ignore leading spaces in the value */
2008 /* found a potential candidate */
2009 if ((mode & GET_HEADER_SKIP_EMPTY) && ast_strlen_zero(value)) {
2010 continue; /* not interesting */
2012 if (mode & GET_HEADER_LAST_MATCH) {
2013 result = value; /* record the last match so far */
2024 * \brief Return the first matching variable from an array.
2026 * \note This is the legacy function and is implemented in
2027 * therms of __astman_get_header().
2029 * \note Never returns NULL.
2031 const char *astman_get_header(const struct message *m, char *var)
2033 return __astman_get_header(m, var, GET_HEADER_FIRST_MATCH);
2038 * \brief Process one "Variable:" header value string.
2040 * \param head Current list of AMI variables to get new values added.
2041 * \param hdr_val Header value string to process.
2043 * \return New variable list head.
2045 static struct ast_variable *man_do_variable_value(struct ast_variable *head, const char *hdr_val)
2048 AST_DECLARE_APP_ARGS(args,
2049 AST_APP_ARG(vars)[64];
2052 hdr_val = ast_skip_blanks(hdr_val); /* ignore leading spaces in the value */
2053 parse = ast_strdupa(hdr_val);
2055 /* Break the header value string into name=val pair items. */
2056 AST_STANDARD_APP_ARGS(args, parse);
2060 /* Process each name=val pair item. */
2061 for (y = 0; y < args.argc; y++) {
2062 struct ast_variable *cur;
2066 if (!args.vars[y]) {
2069 var = val = args.vars[y];
2072 /* XXX We may wish to trim whitespace from the strings. */
2073 if (!val || ast_strlen_zero(var)) {
2077 /* Create new variable list node and prepend it to the list. */
2078 cur = ast_variable_new(var, val, "");
2089 struct ast_variable *astman_get_variables(const struct message *m)
2093 struct ast_variable *head = NULL;
2095 static const char var_hdr[] = "Variable:";
2097 /* Process all "Variable:" headers. */
2098 varlen = strlen(var_hdr);
2099 for (x = 0; x < m->hdrcount; x++) {
2100 if (strncasecmp(var_hdr, m->headers[x], varlen)) {
2103 head = man_do_variable_value(head, m->headers[x] + varlen);
2109 /*! \brief access for hooks to send action messages to ami */
2110 int ast_hook_send_action(struct manager_custom_hook *hook, const char *msg)
2114 struct manager_action *act_found;
2115 struct mansession s = {.session = NULL, };
2116 struct message m = { 0 };
2126 /* Create our own copy of the AMI action msg string. */
2127 src = dup_str = ast_strdup(msg);
2132 /* convert msg string to message struct */
2133 curlen = strlen(src);
2134 for (x = 0; x < curlen; x++) {
2135 int cr; /* set if we have \r */
2136 if (src[x] == '\r' && x+1 < curlen && src[x+1] == '\n')
2137 cr = 2; /* Found. Update length to include \r\n */
2138 else if (src[x] == '\n')
2139 cr = 1; /* also accept \n only */
2142 /* don't keep empty lines */
2143 if (x && m.hdrcount < ARRAY_LEN(m.headers)) {
2144 /* ... but trim \r\n and terminate the header string */
2146 m.headers[m.hdrcount++] = src;
2149 curlen -= x; /* remaining size */
2150 src += x; /* update pointer */
2151 x = -1; /* reset loop */
2154 action = astman_get_header(&m, "Action");
2155 if (strcasecmp(action, "login")) {
2156 act_found = action_find(action);
2159 * we have to simulate a session for this action request
2160 * to be able to pass it down for processing
2161 * This is necessary to meet the previous design of manager.c
2164 s.f = (void*)1; /* set this to something so our request will make it through all functions that test it*/
2166 ao2_lock(act_found);
2167 if (act_found->registered && act_found->func) {
2168 if (act_found->module) {
2169 ast_module_ref(act_found->module);
2171 ao2_unlock(act_found);
2172 ret = act_found->func(&s, &m);
2173 ao2_lock(act_found);
2174 if (act_found->module) {
2175 ast_module_unref(act_found->module);
2180 ao2_unlock(act_found);
2181 ao2_t_ref(act_found, -1, "done with found action object");
2190 * helper function to send a string to the socket.
2191 * Return -1 on error (e.g. buffer full).
2193 static int send_string(struct mansession *s, char *string)
2196 FILE *f = s->f ? s->f : s->session->f;
2197 int fd = s->f ? s->fd : s->session->fd;
2199 /* It's a result from one of the hook's action invocation */
2202 * to send responses, we're using the same function
2203 * as for receiving events. We call the event "HookResponse"
2205 s->hook->helper(EVENT_FLAG_HOOKRESPONSE, "HookResponse", string);
2209 if ((res = ast_careful_fwrite(f, fd, string, strlen(string), s->session->writetimeout))) {
2217 * \brief thread local buffer for astman_append
2219 * \note This can not be defined within the astman_append() function
2220 * because it declares a couple of functions that get used to
2221 * initialize the thread local storage key.
2223 AST_THREADSTORAGE(astman_append_buf);
2225 AST_THREADSTORAGE(userevent_buf);
2227 /*! \brief initial allocated size for the astman_append_buf and astman_send_*_va */
2228 #define ASTMAN_APPEND_BUF_INITSIZE 256
2231 * utility functions for creating AMI replies
2233 void astman_append(struct mansession *s, const char *fmt, ...)
2236 struct ast_str *buf;
2238 if (!(buf = ast_str_thread_get(&astman_append_buf, ASTMAN_APPEND_BUF_INITSIZE))) {
2243 ast_str_set_va(&buf, 0, fmt, ap);
2246 if (s->f != NULL || s->session->f != NULL) {
2247 send_string(s, ast_str_buffer(buf));
2249 ast_verbose("fd == -1 in astman_append, should not happen\n");
2253 /*! \note NOTE: XXX this comment is unclear and possibly wrong.
2254 Callers of astman_send_error(), astman_send_response() or astman_send_ack() must EITHER
2255 hold the session lock _or_ be running in an action callback (in which case s->session->busy will
2256 be non-zero). In either of these cases, there is no need to lock-protect the session's
2257 fd, since no other output will be sent (events will be queued), and no input will
2258 be read until either the current action finishes or get_input() obtains the session
2262 /*! \todo XXX MSG_MOREDATA should go to a header file. */
2263 #define MSG_MOREDATA ((char *)astman_send_response)
2265 /*! \brief send a response with an optional message,
2266 * and terminate it with an empty line.
2267 * m is used only to grab the 'ActionID' field.
2269 * Use the explicit constant MSG_MOREDATA to remove the empty line.
2270 * XXX MSG_MOREDATA should go to a header file.
2272 static void astman_send_response_full(struct mansession *s, const struct message *m, char *resp, char *msg, char *listflag)
2274 const char *id = astman_get_header(m, "ActionID");
2276 astman_append(s, "Response: %s\r\n", resp);
2277 if (!ast_strlen_zero(id)) {
2278 astman_append(s, "ActionID: %s\r\n", id);
2281 astman_append(s, "EventList: %s\r\n", listflag); /* Start, complete, cancelled */
2283 if (msg == MSG_MOREDATA) {
2286 astman_append(s, "Message: %s\r\n\r\n", msg);
2288 astman_append(s, "\r\n");
2292 void astman_send_response(struct mansession *s, const struct message *m, char *resp, char *msg)
2294 astman_send_response_full(s, m, resp, msg, NULL);
2297 void astman_send_error(struct mansession *s, const struct message *m, char *error)
2299 astman_send_response_full(s, m, "Error", error, NULL);
2302 void astman_send_error_va(struct mansession *s, const struct message *m, const char *fmt, ...)
2305 struct ast_str *buf;
2308 if (!(buf = ast_str_thread_get(&astman_append_buf, ASTMAN_APPEND_BUF_INITSIZE))) {
2313 ast_str_set_va(&buf, 0, fmt, ap);
2316 /* astman_append will use the same underlying buffer, so copy the message out
2317 * before sending the response */
2318 msg = ast_str_buffer(buf);
2320 msg = ast_strdupa(msg);
2322 astman_send_response_full(s, m, "Error", msg, NULL);
2325 void astman_send_ack(struct mansession *s, const struct message *m, char *msg)
2327 astman_send_response_full(s, m, "Success", msg, NULL);
2330 static void astman_start_ack(struct mansession *s, const struct message *m)
2332 astman_send_response_full(s, m, "Success", MSG_MOREDATA, NULL);
2335 void astman_send_listack(struct mansession *s, const struct message *m, char *msg, char *listflag)
2337 astman_send_response_full(s, m, "Success", msg, listflag);
2340 /*! \brief Lock the 'mansession' structure. */
2341 static void mansession_lock(struct mansession *s)
2343 ast_mutex_lock(&s->lock);
2346 /*! \brief Unlock the 'mansession' structure. */
2347 static void mansession_unlock(struct mansession *s)
2349 ast_mutex_unlock(&s->lock);
2353 Rather than braindead on,off this now can also accept a specific int mask value
2354 or a ',' delim list of mask strings (the same as manager.conf) -anthm
2356 static int set_eventmask(struct mansession *s, const char *eventmask)
2358 int maskint = strings_to_mask(eventmask);
2360 ao2_lock(s->session);
2362 s->session->send_events = maskint;
2364 ao2_unlock(s->session);
2369 static enum ast_security_event_transport_type mansession_get_transport(const struct mansession *s)
2371 return s->tcptls_session->parent->tls_cfg ? AST_SECURITY_EVENT_TRANSPORT_TLS :
2372 AST_SECURITY_EVENT_TRANSPORT_TCP;
2375 static void report_invalid_user(const struct mansession *s, const char *username)
2377 char session_id[32];
2378 struct ast_security_event_inval_acct_id inval_acct_id = {
2379 .common.event_type = AST_SECURITY_EVENT_INVAL_ACCT_ID,
2380 .common.version = AST_SECURITY_EVENT_INVAL_ACCT_ID_VERSION,
2381 .common.service = "AMI",
2382 .common.account_id = username,
2383 .common.session_tv = &s->session->sessionstart_tv,
2384 .common.local_addr = {
2385 .addr = &s->tcptls_session->parent->local_address,
2386 .transport = mansession_get_transport(s),
2388 .common.remote_addr = {
2389 .addr = &s->session->addr,
2390 .transport = mansession_get_transport(s),
2392 .common.session_id = session_id,
2395 snprintf(session_id, sizeof(session_id), "%p", s);
2397 ast_security_event_report(AST_SEC_EVT(&inval_acct_id));
2400 static void report_failed_acl(const struct mansession *s, const char *username)
2402 char session_id[32];
2403 struct ast_security_event_failed_acl failed_acl_event = {
2404 .common.event_type = AST_SECURITY_EVENT_FAILED_ACL,
2405 .common.version = AST_SECURITY_EVENT_FAILED_ACL_VERSION,
2406 .common.service = "AMI",
2407 .common.account_id = username,
2408 .common.session_tv = &s->session->sessionstart_tv,
2409 .common.local_addr = {
2410 .addr = &s->tcptls_session->parent->local_address,
2411 .transport = mansession_get_transport(s),
2413 .common.remote_addr = {
2414 .addr = &s->session->addr,
2415 .transport = mansession_get_transport(s),
2417 .common.session_id = session_id,
2420 snprintf(session_id, sizeof(session_id), "%p", s->session);
2422 ast_security_event_report(AST_SEC_EVT(&failed_acl_event));
2425 static void report_inval_password(const struct mansession *s, const char *username)
2427 char session_id[32];
2428 struct ast_security_event_inval_password inval_password = {
2429 .common.event_type = AST_SECURITY_EVENT_INVAL_PASSWORD,
2430 .common.version = AST_SECURITY_EVENT_INVAL_PASSWORD_VERSION,
2431 .common.service = "AMI",
2432 .common.account_id = username,
2433 .common.session_tv = &s->session->sessionstart_tv,
2434 .common.local_addr = {
2435 .addr = &s->tcptls_session->parent->local_address,
2436 .transport = mansession_get_transport(s),
2438 .common.remote_addr = {
2439 .addr = &s->session->addr,
2440 .transport = mansession_get_transport(s),
2442 .common.session_id = session_id,
2445 snprintf(session_id, sizeof(session_id), "%p", s->session);
2447 ast_security_event_report(AST_SEC_EVT(&inval_password));
2450 static void report_auth_success(const struct mansession *s)
2452 char session_id[32];
2453 struct ast_security_event_successful_auth successful_auth = {
2454 .common.event_type = AST_SECURITY_EVENT_SUCCESSFUL_AUTH,
2455 .common.version = AST_SECURITY_EVENT_SUCCESSFUL_AUTH_VERSION,
2456 .common.service = "AMI",
2457 .common.account_id = s->session->username,
2458 .common.session_tv = &s->session->sessionstart_tv,
2459 .common.local_addr = {
2460 .addr = &s->tcptls_session->parent->local_address,
2461 .transport = mansession_get_transport(s),
2463 .common.remote_addr = {
2464 .addr = &s->session->addr,
2465 .transport = mansession_get_transport(s),
2467 .common.session_id = session_id,
2470 snprintf(session_id, sizeof(session_id), "%p", s->session);
2472 ast_security_event_report(AST_SEC_EVT(&successful_auth));
2475 static void report_req_not_allowed(const struct mansession *s, const char *action)
2477 char session_id[32];
2478 char request_type[64];
2479 struct ast_security_event_req_not_allowed req_not_allowed = {
2480 .common.event_type = AST_SECURITY_EVENT_REQ_NOT_ALLOWED,
2481 .common.version = AST_SECURITY_EVENT_REQ_NOT_ALLOWED_VERSION,
2482 .common.service = "AMI",
2483 .common.account_id = s->session->username,
2484 .common.session_tv = &s->session->sessionstart_tv,
2485 .common.local_addr = {
2486 .addr = &s->tcptls_session->parent->local_address,
2487 .transport = mansession_get_transport(s),
2489 .common.remote_addr = {
2490 .addr = &s->session->addr,
2491 .transport = mansession_get_transport(s),
2493 .common.session_id = session_id,
2495 .request_type = request_type,
2498 snprintf(session_id, sizeof(session_id), "%p", s->session);
2499 snprintf(request_type, sizeof(request_type), "Action: %s", action);
2501 ast_security_event_report(AST_SEC_EVT(&req_not_allowed));
2504 static void report_req_bad_format(const struct mansession *s, const char *action)
2506 char session_id[32];
2507 char request_type[64];
2508 struct ast_security_event_req_bad_format req_bad_format = {
2509 .common.event_type = AST_SECURITY_EVENT_REQ_BAD_FORMAT,
2510 .common.version = AST_SECURITY_EVENT_REQ_BAD_FORMAT_VERSION,
2511 .common.service = "AMI",
2512 .common.account_id = s->session->username,
2513 .common.session_tv = &s->session->sessionstart_tv,
2514 .common.local_addr = {
2515 .addr = &s->tcptls_session->parent->local_address,
2516 .transport = mansession_get_transport(s),
2518 .common.remote_addr = {
2519 .addr = &s->session->addr,
2520 .transport = mansession_get_transport(s),
2522 .common.session_id = session_id,
2524 .request_type = request_type,
2527 snprintf(session_id, sizeof(session_id), "%p", s->session);
2528 snprintf(request_type, sizeof(request_type), "Action: %s", action);
2530 ast_security_event_report(AST_SEC_EVT(&req_bad_format));
2533 static void report_failed_challenge_response(const struct mansession *s,
2534 const char *response, const char *expected_response)
2536 char session_id[32];
2537 struct ast_security_event_chal_resp_failed chal_resp_failed = {
2538 .common.event_type = AST_SECURITY_EVENT_CHAL_RESP_FAILED,
2539 .common.version = AST_SECURITY_EVENT_CHAL_RESP_FAILED_VERSION,
2540 .common.service = "AMI",
2541 .common.account_id = s->session->username,
2542 .common.session_tv = &s->session->sessionstart_tv,
2543 .common.local_addr = {
2544 .addr = &s->tcptls_session->parent->local_address,
2545 .transport = mansession_get_transport(s),
2547 .common.remote_addr = {
2548 .addr = &s->session->addr,
2549 .transport = mansession_get_transport(s),
2551 .common.session_id = session_id,
2553 .challenge = s->session->challenge,
2554 .response = response,
2555 .expected_response = expected_response,
2558 snprintf(session_id, sizeof(session_id), "%p", s->session);
2560 ast_security_event_report(AST_SEC_EVT(&chal_resp_failed));
2563 static void report_session_limit(const struct mansession *s)
2565 char session_id[32];
2566 struct ast_security_event_session_limit session_limit = {
2567 .common.event_type = AST_SECURITY_EVENT_SESSION_LIMIT,
2568 .common.version = AST_SECURITY_EVENT_SESSION_LIMIT_VERSION,
2569 .common.service = "AMI",
2570 .common.account_id = s->session->username,
2571 .common.session_tv = &s->session->sessionstart_tv,
2572 .common.local_addr = {
2573 .addr = &s->tcptls_session->parent->local_address,
2574 .transport = mansession_get_transport(s),
2576 .common.remote_addr = {
2577 .addr = &s->session->addr,
2578 .transport = mansession_get_transport(s),
2580 .common.session_id = session_id,
2583 snprintf(session_id, sizeof(session_id), "%p", s->session);
2585 ast_security_event_report(AST_SEC_EVT(&session_limit));
2589 * Here we start with action_ handlers for AMI actions,
2590 * and the internal functions used by them.
2591 * Generally, the handlers are called action_foo()
2594 /* helper function for action_login() */
2595 static int authenticate(struct mansession *s, const struct message *m)
2597 const char *username = astman_get_header(m, "Username");
2598 const char *password = astman_get_header(m, "Secret");
2600 struct ast_manager_user *user = NULL;
2601 regex_t *regex_filter;
2602 struct ao2_iterator filter_iter;
2604 if (ast_strlen_zero(username)) { /* missing username */
2608 /* locate user in locked state */
2609 AST_RWLIST_WRLOCK(&users);
2611 if (!(user = get_manager_by_name_locked(username))) {
2612 report_invalid_user(s, username);
2613 ast_log(LOG_NOTICE, "%s tried to authenticate with nonexistent user '%s'\n", ast_sockaddr_stringify_addr(&s->session->addr), username);
2614 } else if (user->acl && (ast_apply_acl(user->acl, &s->session->addr, "Manager User ACL: ") == AST_SENSE_DENY)) {
2615 report_failed_acl(s, username);
2616 ast_log(LOG_NOTICE, "%s failed to pass IP ACL as '%s'\n", ast_sockaddr_stringify_addr(&s->session->addr), username);
2617 } else if (!strcasecmp(astman_get_header(m, "AuthType"), "MD5")) {
2618 const char *key = astman_get_header(m, "Key");
2619 if (!ast_strlen_zero(key) && !ast_strlen_zero(s->session->challenge) && user->secret) {
2622 char md5key[256] = "";
2623 struct MD5Context md5;
2624 unsigned char digest[16];
2627 MD5Update(&md5, (unsigned char *) s->session->challenge, strlen(s->session->challenge));
2628 MD5Update(&md5, (unsigned char *) user->secret, strlen(user->secret));
2629 MD5Final(digest, &md5);
2630 for (x = 0; x < 16; x++)
2631 len += sprintf(md5key + len, "%2.2x", digest[x]);
2632 if (!strcmp(md5key, key)) {
2635 report_failed_challenge_response(s, key, md5key);
2638 ast_debug(1, "MD5 authentication is not possible. challenge: '%s'\n",
2639 S_OR(s->session->challenge, ""));
2641 } else if (user->secret) {
2642 if (!strcmp(password, user->secret)) {
2645 report_inval_password(s, username);
2650 ast_log(LOG_NOTICE, "%s failed to authenticate as '%s'\n", ast_sockaddr_stringify_addr(&s->session->addr), username);
2651 AST_RWLIST_UNLOCK(&users);
2657 /* All of the user parameters are copied to the session so that in the event
2658 * of a reload and a configuration change, the session parameters are not
2660 ast_copy_string(s->session->username, username, sizeof(s->session->username));
2661 s->session->readperm = user->readperm;
2662 s->session->writeperm = user->writeperm;
2663 s->session->writetimeout = user->writetimeout;
2664 if (user->chanvars) {
2665 s->session->chanvars = ast_variables_dup(user->chanvars);
2668 filter_iter = ao2_iterator_init(user->whitefilters, 0);
2669 while ((regex_filter = ao2_iterator_next(&filter_iter))) {
2670 ao2_t_link(s->session->whitefilters, regex_filter, "add white user filter to session");
2671 ao2_t_ref(regex_filter, -1, "remove iterator ref");
2673 ao2_iterator_destroy(&filter_iter);
2675 filter_iter = ao2_iterator_init(user->blackfilters, 0);
2676 while ((regex_filter = ao2_iterator_next(&filter_iter))) {
2677 ao2_t_link(s->session->blackfilters, regex_filter, "add black user filter to session");
2678 ao2_t_ref(regex_filter, -1, "remove iterator ref");
2680 ao2_iterator_destroy(&filter_iter);
2682 s->session->sessionstart = time(NULL);
2683 s->session->sessionstart_tv = ast_tvnow();
2684 set_eventmask(s, astman_get_header(m, "Events"));
2686 report_auth_success(s);
2688 AST_RWLIST_UNLOCK(&users);
2692 static int action_ping(struct mansession *s, const struct message *m)
2694 const char *actionid = astman_get_header(m, "ActionID");
2695 struct timeval now = ast_tvnow();
2697 astman_append(s, "Response: Success\r\n");
2698 if (!ast_strlen_zero(actionid)){
2699 astman_append(s, "ActionID: %s\r\n", actionid);
2704 "Timestamp: %ld.%06lu\r\n"
2706 (long) now.tv_sec, (unsigned long) now.tv_usec);
2710 static int action_getconfig(struct mansession *s, const struct message *m)
2712 struct ast_config *cfg;
2713 const char *fn = astman_get_header(m, "Filename");
2714 const char *category = astman_get_header(m, "Category");
2717 char *cur_category = NULL;
2718 struct ast_variable *v;
2719 struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
2721 if (ast_strlen_zero(fn)) {
2722 astman_send_error(s, m, "Filename not specified");
2725 cfg = ast_config_load2(fn, "manager", config_flags);
2726 if (cfg == CONFIG_STATUS_FILEMISSING) {
2727 astman_send_error(s, m, "Config file not found");
2729 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
2730 astman_send_error(s, m, "Config file has invalid format");
2734 astman_start_ack(s, m);
2735 while ((cur_category = ast_category_browse(cfg, cur_category))) {
2736 if (ast_strlen_zero(category) || (!ast_strlen_zero(category) && !strcmp(category, cur_category))) {
2738 astman_append(s, "Category-%06d: %s\r\n", catcount, cur_category);
2739 for (v = ast_variable_browse(cfg, cur_category); v; v = v->next) {
2740 astman_append(s, "Line-%06d-%06d: %s=%s\r\n", catcount, lineno++, v->name, v->value);
2745 if (!ast_strlen_zero(category) && catcount == 0) { /* TODO: actually, a config with no categories doesn't even get loaded */
2746 astman_append(s, "No categories found\r\n");
2748 ast_config_destroy(cfg);
2749 astman_append(s, "\r\n");
2754 static int action_listcategories(struct mansession *s, const struct message *m)
2756 struct ast_config *cfg;
2757 const char *fn = astman_get_header(m, "Filename");
2758 char *category = NULL;
2759 struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
2762 if (ast_strlen_zero(fn)) {
2763 astman_send_error(s, m, "Filename not specified");
2766 if (!(cfg = ast_config_load2(fn, "manager", config_flags))) {
2767 astman_send_error(s, m, "Config file not found");
2769 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
2770 astman_send_error(s, m, "Config file has invalid format");
2773 astman_start_ack(s, m);
2774 while ((category = ast_category_browse(cfg, category))) {
2775 astman_append(s, "Category-%06d: %s\r\n", catcount, category);
2778 if (catcount == 0) { /* TODO: actually, a config with no categories doesn't even get loaded */
2779 astman_append(s, "Error: no categories found\r\n");
2781 ast_config_destroy(cfg);
2782 astman_append(s, "\r\n");
2790 /*! The amount of space in out must be at least ( 2 * strlen(in) + 1 ) */
2791 static void json_escape(char *out, const char *in)
2794 if (*in == '\\' || *in == '\"') {
2804 * \brief Append a JSON escaped string to the manager stream.
2806 * \param s AMI stream to append a string.
2807 * \param str String to append to the stream after JSON escaping it.
2811 static void astman_append_json(struct mansession *s, const char *str)
2815 buf = ast_alloca(2 * strlen(str) + 1);
2816 json_escape(buf, str);
2817 astman_append(s, "%s", buf);
2820 static int action_getconfigjson(struct mansession *s, const struct message *m)
2822 struct ast_config *cfg;
2823 const char *fn = astman_get_header(m, "Filename");
2824 char *category = NULL;
2825 struct ast_variable *v;
2827 struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
2829 if (ast_strlen_zero(fn)) {
2830 astman_send_error(s, m, "Filename not specified");
2834 if (!(cfg = ast_config_load2(fn, "manager", config_flags))) {
2835 astman_send_error(s, m, "Config file not found");
2837 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
2838 astman_send_error(s, m, "Config file has invalid format");
2842 astman_start_ack(s, m);
2843 astman_append(s, "JSON: {");
2844 while ((category = ast_category_browse(cfg, category))) {
2847 astman_append(s, "%s\"", comma1 ? "," : "");
2848 astman_append_json(s, category);
2849 astman_append(s, "\":[");
2851 for (v = ast_variable_browse(cfg, category); v; v = v->next) {
2852 astman_append(s, "%s\"", comma2 ? "," : "");
2853 astman_append_json(s, v->name);
2854 astman_append(s, "\":\"");
2855 astman_append_json(s, v->value);
2856 astman_append(s, "\"");
2859 astman_append(s, "]");
2861 astman_append(s, "}\r\n\r\n");
2863 ast_config_destroy(cfg);
2868 /*! \brief helper function for action_updateconfig */
2869 static enum error_type handle_updates(struct mansession *s, const struct message *m, struct ast_config *cfg, const char *dfn)
2873 const char *action, *cat, *var, *value, *match, *line;
2874 struct ast_category *category;
2875 struct ast_variable *v;
2876 struct ast_str *str1 = ast_str_create(16), *str2 = ast_str_create(16);
2877 enum error_type result = 0;
2879 for (x = 0; x < 100000; x++) { /* 100000 = the max number of allowed updates + 1 */
2880 unsigned int object = 0;
2882 snprintf(hdr, sizeof(hdr), "Action-%06d", x);
2883 action = astman_get_header(m, hdr);
2884 if (ast_strlen_zero(action)) /* breaks the for loop if no action header */
2885 break; /* this could cause problems if actions come in misnumbered */
2887 snprintf(hdr, sizeof(hdr), "Cat-%06d", x);
2888 cat = astman_get_header(m, hdr);
2889 if (ast_strlen_zero(cat)) { /* every action needs a category */
2890 result = UNSPECIFIED_CATEGORY;
2894 snprintf(hdr, sizeof(hdr), "Var-%06d", x);
2895 var = astman_get_header(m, hdr);
2897 snprintf(hdr, sizeof(hdr), "Value-%06d", x);
2898 value = astman_get_header(m, hdr);
2900 if (!ast_strlen_zero(value) && *value == '>') {
2905 snprintf(hdr, sizeof(hdr), "Match-%06d", x);
2906 match = astman_get_header(m, hdr);
2908 snprintf(hdr, sizeof(hdr), "Line-%06d", x);
2909 line = astman_get_header(m, hdr);
2911 if (!strcasecmp(action, "newcat")) {
2912 if (ast_category_get(cfg,cat)) { /* check to make sure the cat doesn't */
2913 result = FAILURE_NEWCAT; /* already exist */
2916 if (!(category = ast_category_new(cat, dfn, -1))) {
2917 result = FAILURE_ALLOCATION;
2920 if (ast_strlen_zero(match)) {
2921 ast_category_append(cfg, category);
2923 ast_category_insert(cfg, category, match);
2925 } else if (!strcasecmp(action, "renamecat")) {
2926 if (ast_strlen_zero(value)) {
2927 result = UNSPECIFIED_ARGUMENT;
2930 if (!(category = ast_category_get(cfg, cat))) {
2931 result = UNKNOWN_CATEGORY;
2934 ast_category_rename(category, value);
2935 } else if (!strcasecmp(action, "delcat")) {
2936 if (ast_category_delete(cfg, cat)) {
2937 result = FAILURE_DELCAT;
2940 } else if (!strcasecmp(action, "emptycat")) {
2941 if (ast_category_empty(cfg, cat)) {
2942 result = FAILURE_EMPTYCAT;
2945 } else if (!strcasecmp(action, "update")) {
2946 if (ast_strlen_zero(var)) {
2947 result = UNSPECIFIED_ARGUMENT;
2950 if (!(category = ast_category_get(cfg,cat))) {
2951 result = UNKNOWN_CATEGORY;
2954 if (ast_variable_update(category, var, value, match, object)) {
2955 result = FAILURE_UPDATE;
2958 } else if (!strcasecmp(action, "delete")) {
2959 if ((ast_strlen_zero(var) && ast_strlen_zero(line))) {
2960 result = UNSPECIFIED_ARGUMENT;
2963 if (!(category = ast_category_get(cfg, cat))) {
2964 result = UNKNOWN_CATEGORY;
2967 if (ast_variable_delete(category, var, match, line)) {
2968 result = FAILURE_DELETE;
2971 } else if (!strcasecmp(action, "append")) {
2972 if (ast_strlen_zero(var)) {
2973 result = UNSPECIFIED_ARGUMENT;
2976 if (!(category = ast_category_get(cfg, cat))) {
2977 result = UNKNOWN_CATEGORY;
2980 if (!(v = ast_variable_new(var, value, dfn))) {
2981 result = FAILURE_ALLOCATION;
2984 if (object || (match && !strcasecmp(match, "object"))) {
2987 ast_variable_append(category, v);
2988 } else if (!strcasecmp(action, "insert")) {
2989 if (ast_strlen_zero(var) || ast_strlen_zero(line)) {
2990 result = UNSPECIFIED_ARGUMENT;
2993 if (!(category = ast_category_get(cfg, cat))) {
2994 result = UNKNOWN_CATEGORY;
2997 if (!(v = ast_variable_new(var, value, dfn))) {
2998 result = FAILURE_ALLOCATION;
3001 ast_variable_insert(category, v, line);
3004 ast_log(LOG_WARNING, "Action-%06d: %s not handled\n", x, action);
3005 result = UNKNOWN_ACTION;
3014 static int action_updateconfig(struct mansession *s, const struct message *m)
3016 struct ast_config *cfg;
3017 const char *sfn = astman_get_header(m, "SrcFilename");
3018 const char *dfn = astman_get_header(m, "DstFilename");
3020 const char *rld = astman_get_header(m, "Reload");
3021 struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
3022 enum error_type result;
3024 if (ast_strlen_zero(sfn) || ast_strlen_zero(dfn)) {
3025 astman_send_error(s, m, "Filename not specified");