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 * \extref 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 /*! \addtogroup Group_AMI AMI functions
45 <support_level>core</support_level>
50 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
52 #include "asterisk/_private.h"
53 #include "asterisk/paths.h" /* use various ast_config_AST_* */
58 #include <sys/types.h>
61 #include "asterisk/channel.h"
62 #include "asterisk/file.h"
63 #include "asterisk/manager.h"
64 #include "asterisk/module.h"
65 #include "asterisk/config.h"
66 #include "asterisk/callerid.h"
67 #include "asterisk/lock.h"
68 #include "asterisk/cli.h"
69 #include "asterisk/app.h"
70 #include "asterisk/pbx.h"
71 #include "asterisk/md5.h"
72 #include "asterisk/acl.h"
73 #include "asterisk/utils.h"
74 #include "asterisk/tcptls.h"
75 #include "asterisk/http.h"
76 #include "asterisk/ast_version.h"
77 #include "asterisk/threadstorage.h"
78 #include "asterisk/linkedlists.h"
79 #include "asterisk/term.h"
80 #include "asterisk/astobj2.h"
81 #include "asterisk/features.h"
82 #include "asterisk/security_events.h"
83 #include "asterisk/event.h"
84 #include "asterisk/aoc.h"
85 #include "asterisk/stringfields.h"
86 #include "asterisk/presencestate.h"
89 <manager name="Ping" language="en_US">
94 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
97 <para>A 'Ping' action will ellicit a 'Pong' response. Used to keep the
98 manager connection open.</para>
101 <manager name="Events" language="en_US">
106 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
107 <parameter name="EventMask" required="true">
110 <para>If all events should be sent.</para>
113 <para>If no events should be sent.</para>
115 <enum name="system,call,log,...">
116 <para>To select which flags events should have to be sent.</para>
122 <para>Enable/Disable sending of events to this manager client.</para>
125 <manager name="Logoff" language="en_US">
130 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
133 <para>Logoff the current manager session.</para>
136 <manager name="Login" language="en_US">
141 <parameter name="ActionID">
142 <para>ActionID for this transaction. Will be returned.</para>
144 <parameter name="Username" required="true">
145 <para>Username to login with as specified in manager.conf.</para>
147 <parameter name="Secret">
148 <para>Secret to login with as specified in manager.conf.</para>
152 <para>Login Manager.</para>
155 <manager name="Challenge" language="en_US">
157 Generate Challenge for MD5 Auth.
160 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
161 <parameter name="AuthType" required="true">
162 <para>Digest algorithm to use in the challenge. Valid values are:</para>
169 <para>Generate a challenge for MD5 authentication.</para>
172 <manager name="Hangup" language="en_US">
177 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
178 <parameter name="Channel" required="true">
179 <para>The exact channel name to be hungup, or to use a regular expression, set this parameter to: /regex/</para>
180 <para>Example exact channel: SIP/provider-0000012a</para>
181 <para>Example regular expression: /^SIP/provider-.*$/</para>
183 <parameter name="Cause">
184 <para>Numeric hangup cause.</para>
188 <para>Hangup a channel.</para>
191 <manager name="Status" language="en_US">
196 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
197 <parameter name="Channel" required="true">
198 <para>The name of the channel to query for status.</para>
200 <parameter name="Variables">
201 <para>Comma <literal>,</literal> separated list of variable to include.</para>
205 <para>Will return the status information of each channel along with the
206 value for the specified channel variables.</para>
209 <manager name="Setvar" language="en_US">
211 Set a channel variable.
214 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
215 <parameter name="Channel">
216 <para>Channel to set variable for.</para>
218 <parameter name="Variable" required="true">
219 <para>Variable name.</para>
221 <parameter name="Value" required="true">
222 <para>Variable value.</para>
226 <para>Set a global or local channel variable.</para>
228 <para>If a channel name is not provided then the variable is global.</para>
232 <manager name="Getvar" language="en_US">
234 Gets a channel variable.
237 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
238 <parameter name="Channel">
239 <para>Channel to read variable from.</para>
241 <parameter name="Variable" required="true">
242 <para>Variable name.</para>
246 <para>Get the value of a global or local channel variable.</para>
248 <para>If a channel name is not provided then the variable is global.</para>
252 <manager name="GetConfig" language="en_US">
254 Retrieve configuration.
257 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
258 <parameter name="Filename" required="true">
259 <para>Configuration filename (e.g. <filename>foo.conf</filename>).</para>
261 <parameter name="Category">
262 <para>Category in configuration file.</para>
266 <para>This action will dump the contents of a configuration
267 file by category and contents or optionally by specified category only.</para>
270 <manager name="GetConfigJSON" language="en_US">
272 Retrieve configuration (JSON format).
275 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
276 <parameter name="Filename" required="true">
277 <para>Configuration filename (e.g. <filename>foo.conf</filename>).</para>
281 <para>This action will dump the contents of a configuration file by category
282 and contents in JSON format. This only makes sense to be used using rawman over
283 the HTTP interface.</para>
286 <manager name="UpdateConfig" language="en_US">
288 Update basic configuration.
291 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
292 <parameter name="SrcFilename" required="true">
293 <para>Configuration filename to read (e.g. <filename>foo.conf</filename>).</para>
295 <parameter name="DstFilename" required="true">
296 <para>Configuration filename to write (e.g. <filename>foo.conf</filename>)</para>
298 <parameter name="Reload">
299 <para>Whether or not a reload should take place (or name of specific module).</para>
301 <parameter name="Action-XXXXXX">
302 <para>Action to take.</para>
303 <para>X's represent 6 digit number beginning with 000000.</para>
305 <enum name="NewCat" />
306 <enum name="RenameCat" />
307 <enum name="DelCat" />
308 <enum name="EmptyCat" />
309 <enum name="Update" />
310 <enum name="Delete" />
311 <enum name="Append" />
312 <enum name="Insert" />
315 <parameter name="Cat-XXXXXX">
316 <para>Category to operate on.</para>
317 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-XXXXXX']/para[2])" />
319 <parameter name="Var-XXXXXX">
320 <para>Variable to work on.</para>
321 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-XXXXXX']/para[2])" />
323 <parameter name="Value-XXXXXX">
324 <para>Value to work on.</para>
325 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-XXXXXX']/para[2])" />
327 <parameter name="Match-XXXXXX">
328 <para>Extra match required to match line.</para>
329 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-XXXXXX']/para[2])" />
331 <parameter name="Line-XXXXXX">
332 <para>Line in category to operate on (used with delete and insert actions).</para>
333 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-XXXXXX']/para[2])" />
337 <para>This action will modify, create, or delete configuration elements
338 in Asterisk configuration files.</para>
341 <manager name="CreateConfig" language="en_US">
343 Creates an empty file in the configuration directory.
346 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
347 <parameter name="Filename" required="true">
348 <para>The configuration filename to create (e.g. <filename>foo.conf</filename>).</para>
352 <para>This action will create an empty file in the configuration
353 directory. This action is intended to be used before an UpdateConfig
357 <manager name="ListCategories" language="en_US">
359 List categories in configuration file.
362 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
363 <parameter name="Filename" required="true">
364 <para>Configuration filename (e.g. <filename>foo.conf</filename>).</para>
368 <para>This action will dump the categories in a given file.</para>
371 <manager name="Redirect" language="en_US">
373 Redirect (transfer) a call.
376 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
377 <parameter name="Channel" required="true">
378 <para>Channel to redirect.</para>
380 <parameter name="ExtraChannel">
381 <para>Second call leg to transfer (optional).</para>
383 <parameter name="Exten" required="true">
384 <para>Extension to transfer to.</para>
386 <parameter name="ExtraExten">
387 <para>Extension to transfer extrachannel to (optional).</para>
389 <parameter name="Context" required="true">
390 <para>Context to transfer to.</para>
392 <parameter name="ExtraContext">
393 <para>Context to transfer extrachannel to (optional).</para>
395 <parameter name="Priority" required="true">
396 <para>Priority to transfer to.</para>
398 <parameter name="ExtraPriority">
399 <para>Priority to transfer extrachannel to (optional).</para>
403 <para>Redirect (transfer) a call.</para>
406 <manager name="Atxfer" language="en_US">
411 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
412 <parameter name="Channel" required="true">
413 <para>Transferer's channel.</para>
415 <parameter name="Exten" required="true">
416 <para>Extension to transfer to.</para>
418 <parameter name="Context" required="true">
419 <para>Context to transfer to.</para>
421 <parameter name="Priority" required="true">
422 <para>Priority to transfer to.</para>
426 <para>Attended transfer.</para>
429 <manager name="Originate" language="en_US">
434 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
435 <parameter name="Channel" required="true">
436 <para>Channel name to call.</para>
438 <parameter name="Exten">
439 <para>Extension to use (requires <literal>Context</literal> and
440 <literal>Priority</literal>)</para>
442 <parameter name="Context">
443 <para>Context to use (requires <literal>Exten</literal> and
444 <literal>Priority</literal>)</para>
446 <parameter name="Priority">
447 <para>Priority to use (requires <literal>Exten</literal> and
448 <literal>Context</literal>)</para>
450 <parameter name="Application">
451 <para>Application to execute.</para>
453 <parameter name="Data">
454 <para>Data to use (requires <literal>Application</literal>).</para>
456 <parameter name="Timeout" default="30000">
457 <para>How long to wait for call to be answered (in ms.).</para>
459 <parameter name="CallerID">
460 <para>Caller ID to be set on the outgoing channel.</para>
462 <parameter name="Variable">
463 <para>Channel variable to set, multiple Variable: headers are allowed.</para>
465 <parameter name="Account">
466 <para>Account code.</para>
468 <parameter name="Async">
469 <para>Set to <literal>true</literal> for fast origination.</para>
471 <parameter name="Codecs">
472 <para>Comma-separated list of codecs to use for this call.</para>
476 <para>Generates an outgoing call to a
477 <replaceable>Extension</replaceable>/<replaceable>Context</replaceable>/<replaceable>Priority</replaceable>
478 or <replaceable>Application</replaceable>/<replaceable>Data</replaceable></para>
481 <ref type="managerEvent">OriginateResponse</ref>
484 <managerEvent language="en_US" name="OriginateResponse">
485 <managerEventInstance class="EVENT_FLAG_CALL">
486 <synopsis>Raised in response to an Originate command.</synopsis>
488 <parameter name="ActionID" required="false"/>
489 <parameter name="Resonse">
491 <enum name="Failure"/>
492 <enum name="Success"/>
495 <parameter name="Channel"/>
496 <parameter name="Context"/>
497 <parameter name="Exten"/>
498 <parameter name="Reason"/>
499 <parameter name="Uniqueid"/>
500 <parameter name="CallerIDNum"/>
501 <parameter name="CallerIDName"/>
504 <ref type="manager">Originate</ref>
506 </managerEventInstance>
508 <manager name="Command" language="en_US">
510 Execute Asterisk CLI Command.
513 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
514 <parameter name="Command" required="true">
515 <para>Asterisk CLI command to run.</para>
519 <para>Run a CLI command.</para>
522 <manager name="ExtensionState" language="en_US">
524 Check Extension Status.
527 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
528 <parameter name="Exten" required="true">
529 <para>Extension to check state on.</para>
531 <parameter name="Context" required="true">
532 <para>Context for extension.</para>
536 <para>Report the extension state for given extension. If the extension has a hint,
537 will use devicestate to check the status of the device connected to the extension.</para>
538 <para>Will return an <literal>Extension Status</literal> message. The response will include
539 the hint for the extension and the status.</para>
542 <manager name="PresenceState" language="en_US">
547 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
548 <parameter name="Provider" required="true">
549 <para>Presence Provider to check the state of</para>
553 <para>Report the presence state for the given presence provider.</para>
554 <para>Will return a <literal>Presence State</literal> message. The response will include the
555 presence state and, if set, a presence subtype and custom message.</para>
558 <manager name="AbsoluteTimeout" language="en_US">
560 Set absolute timeout.
563 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
564 <parameter name="Channel" required="true">
565 <para>Channel name to hangup.</para>
567 <parameter name="Timeout" required="true">
568 <para>Maximum duration of the call (sec).</para>
572 <para>Hangup a channel after a certain time. Acknowledges set time with
573 <literal>Timeout Set</literal> message.</para>
576 <manager name="MailboxStatus" language="en_US">
581 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
582 <parameter name="Mailbox" required="true">
583 <para>Full mailbox ID <replaceable>mailbox</replaceable>@<replaceable>vm-context</replaceable>.</para>
587 <para>Checks a voicemail account for status.</para>
588 <para>Returns number of messages.</para>
589 <para>Message: Mailbox Status.</para>
590 <para>Mailbox: <replaceable>mailboxid</replaceable>.</para>
591 <para>Waiting: <replaceable>count</replaceable>.</para>
594 <manager name="MailboxCount" language="en_US">
596 Check Mailbox Message Count.
599 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
600 <parameter name="Mailbox" required="true">
601 <para>Full mailbox ID <replaceable>mailbox</replaceable>@<replaceable>vm-context</replaceable>.</para>
605 <para>Checks a voicemail account for new messages.</para>
606 <para>Returns number of urgent, new and old messages.</para>
607 <para>Message: Mailbox Message Count</para>
608 <para>Mailbox: <replaceable>mailboxid</replaceable></para>
609 <para>UrgentMessages: <replaceable>count</replaceable></para>
610 <para>NewMessages: <replaceable>count</replaceable></para>
611 <para>OldMessages: <replaceable>count</replaceable></para>
614 <manager name="ListCommands" language="en_US">
616 List available manager commands.
619 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
622 <para>Returns the action name and synopsis for every action that
623 is available to the user.</para>
626 <manager name="SendText" language="en_US">
628 Send text message to channel.
631 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
632 <parameter name="Channel" required="true">
633 <para>Channel to send message to.</para>
635 <parameter name="Message" required="true">
636 <para>Message to send.</para>
640 <para>Sends A Text Message to a channel while in a call.</para>
643 <manager name="UserEvent" language="en_US">
645 Send an arbitrary event.
648 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
649 <parameter name="UserEvent" required="true">
650 <para>Event string to send.</para>
652 <parameter name="Header1">
653 <para>Content1.</para>
655 <parameter name="HeaderN">
656 <para>ContentN.</para>
660 <para>Send an event to manager sessions.</para>
663 <manager name="WaitEvent" language="en_US">
665 Wait for an event to occur.
668 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
669 <parameter name="Timeout" required="true">
670 <para>Maximum time (in seconds) to wait for events, <literal>-1</literal> means forever.</para>
674 <para>This action will ellicit a <literal>Success</literal> response. Whenever
675 a manager event is queued. Once WaitEvent has been called on an HTTP manager
676 session, events will be generated and queued.</para>
679 <manager name="CoreSettings" language="en_US">
681 Show PBX core settings (version etc).
684 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
687 <para>Query for Core PBX settings.</para>
690 <manager name="CoreStatus" language="en_US">
692 Show PBX core status variables.
695 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
698 <para>Query for Core PBX status.</para>
701 <manager name="Reload" language="en_US">
706 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
707 <parameter name="Module">
708 <para>Name of the module to reload.</para>
712 <para>Send a reload event.</para>
715 <manager name="CoreShowChannels" language="en_US">
717 List currently active channels.
720 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
723 <para>List currently defined channels and some information about them.</para>
726 <manager name="ModuleLoad" language="en_US">
731 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
732 <parameter name="Module">
733 <para>Asterisk module name (including .so extension) or subsystem identifier:</para>
737 <enum name="dnsmgr" />
738 <enum name="extconfig" />
739 <enum name="manager" />
744 <parameter name="LoadType" required="true">
745 <para>The operation to be done on module.</para>
748 <enum name="unload" />
749 <enum name="reload" />
751 <para>If no module is specified for a <literal>reload</literal> loadtype,
752 all modules are reloaded.</para>
756 <para>Loads, unloads or reloads an Asterisk module in a running system.</para>
759 <manager name="ModuleCheck" language="en_US">
761 Check if module is loaded.
764 <parameter name="Module" required="true">
765 <para>Asterisk module name (not including extension).</para>
769 <para>Checks if Asterisk module is loaded. Will return Success/Failure.
770 For success returns, the module revision number is included.</para>
773 <manager name="AOCMessage" language="en_US">
775 Generate an Advice of Charge message on a channel.
778 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
779 <parameter name="Channel" required="true">
780 <para>Channel name to generate the AOC message on.</para>
782 <parameter name="ChannelPrefix">
783 <para>Partial channel prefix. By using this option one can match the beginning part
784 of a channel name without having to put the entire name in. For example
785 if a channel name is SIP/snom-00000001 and this value is set to SIP/snom, then
786 that channel matches and the message will be sent. Note however that only
787 the first matched channel has the message sent on it. </para>
789 <parameter name="MsgType" required="true">
790 <para>Defines what type of AOC message to create, AOC-D or AOC-E</para>
796 <parameter name="ChargeType" required="true">
797 <para>Defines what kind of charge this message represents.</para>
801 <enum name="Currency" />
805 <parameter name="UnitAmount(0)">
806 <para>This represents the amount of units charged. The ETSI AOC standard specifies that
807 this value along with the optional UnitType value are entries in a list. To accommodate this
808 these values take an index value starting at 0 which can be used to generate this list of
809 unit entries. For Example, If two unit entires were required this could be achieved by setting the
810 paramter UnitAmount(0)=1234 and UnitAmount(1)=5678. Note that UnitAmount at index 0 is
811 required when ChargeType=Unit, all other entries in the list are optional.
814 <parameter name="UnitType(0)">
815 <para>Defines the type of unit. ETSI AOC standard specifies this as an integer
816 value between 1 and 16, but this value is left open to accept any positive
817 integer. Like the UnitAmount parameter, this value represents a list entry
818 and has an index parameter that starts at 0.
821 <parameter name="CurrencyName">
822 <para>Specifies the currency's name. Note that this value is truncated after 10 characters.</para>
824 <parameter name="CurrencyAmount">
825 <para>Specifies the charge unit amount as a positive integer. This value is required
826 when ChargeType==Currency.</para>
828 <parameter name="CurrencyMultiplier">
829 <para>Specifies the currency multiplier. This value is required when ChargeType==Currency.</para>
831 <enum name="OneThousandth" />
832 <enum name="OneHundredth" />
833 <enum name="OneTenth" />
836 <enum name="Hundred" />
837 <enum name="Thousand" />
840 <parameter name="TotalType" default="Total">
841 <para>Defines what kind of AOC-D total is represented.</para>
843 <enum name="Total" />
844 <enum name="SubTotal" />
847 <parameter name="AOCBillingId">
848 <para>Represents a billing ID associated with an AOC-D or AOC-E message. Note
849 that only the first 3 items of the enum are valid AOC-D billing IDs</para>
851 <enum name="Normal" />
852 <enum name="ReverseCharge" />
853 <enum name="CreditCard" />
854 <enum name="CallFwdUnconditional" />
855 <enum name="CallFwdBusy" />
856 <enum name="CallFwdNoReply" />
857 <enum name="CallDeflection" />
858 <enum name="CallTransfer" />
861 <parameter name="ChargingAssociationId">
862 <para>Charging association identifier. This is optional for AOC-E and can be
863 set to any value between -32768 and 32767</para>
865 <parameter name="ChargingAssociationNumber">
866 <para>Represents the charging association party number. This value is optional
869 <parameter name="ChargingAssociationPlan">
870 <para>Integer representing the charging plan associated with the ChargingAssociationNumber.
871 The value is bits 7 through 1 of the Q.931 octet containing the type-of-number and
872 numbering-plan-identification fields.</para>
876 <para>Generates an AOC-D or AOC-E message on a channel.</para>
879 <manager name="Filter" language="en_US">
881 Dynamically add filters for the current manager session.
884 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
885 <parameter name="Operation">
888 <para>Add a filter.</para>
892 <parameter name="Filter">
893 <para>Filters can be whitelist or blacklist</para>
894 <para>Example whitelist filter: "Event: Newchannel"</para>
895 <para>Example blacklist filter: "!Channel: DAHDI.*"</para>
896 <para>This filter option is used to whitelist or blacklist events per user to be
897 reported with regular expressions and are allowed if both the regex matches
898 and the user has read access as defined in manager.conf. Filters are assumed to be for whitelisting
899 unless preceeded by an exclamation point, which marks it as being black.
900 Evaluation of the filters is as follows:</para>
901 <para>- If no filters are configured all events are reported as normal.</para>
902 <para>- If there are white filters only: implied black all filter processed first, then white filters.</para>
903 <para>- If there are black filters only: implied white all filter processed first, then black filters.</para>
904 <para>- If there are both white and black filters: implied black all filter processed first, then white
905 filters, and lastly black filters.</para>
909 <para>The filters added are only used for the current session.
910 Once the connection is closed the filters are removed.</para>
911 <para>This comand requires the system permission because
912 this command can be used to create filters that may bypass
913 filters defined in manager.conf</para>
916 <manager name="FilterList" language="en_US">
918 Show current event filters for this session
921 <para>The filters displayed are for the current session. Only those filters defined in
922 manager.conf will be present upon starting a new session.</para>
930 UNSPECIFIED_CATEGORY,
931 UNSPECIFIED_ARGUMENT,
941 enum add_filter_result {
948 * Linked list of events.
949 * Global events are appended to the list by append_event().
950 * The usecount is the number of stored pointers to the element,
951 * excluding the list pointers. So an element that is only in
952 * the list has a usecount of 0, not 1.
954 * Clients have a pointer to the last event processed, and for each
955 * of these clients we track the usecount of the elements.
956 * If we have a pointer to an entry in the list, it is safe to navigate
957 * it forward because elements will not be deleted, but only appended.
958 * The worst that can happen is seeing the pointer still NULL.
960 * When the usecount of an element drops to 0, and the element is the
961 * first in the list, we can remove it. Removal is done within the
962 * main thread, which is woken up for the purpose.
964 * For simplicity of implementation, we make sure the list is never empty.
967 int usecount; /*!< # of clients who still need the event */
969 unsigned int seq; /*!< sequence number */
970 struct timeval tv; /*!< When event was allocated */
971 AST_RWLIST_ENTRY(eventqent) eq_next;
972 char eventdata[1]; /*!< really variable size, allocated by append_event() */
975 static AST_RWLIST_HEAD_STATIC(all_events, eventqent);
977 static int displayconnects = 1;
978 static int allowmultiplelogin = 1;
979 static int timestampevents;
980 static int httptimeout = 60;
981 static int broken_events_action = 0;
982 static int manager_enabled = 0;
983 static int webmanager_enabled = 0;
984 static int manager_debug = 0; /*!< enable some debugging code in the manager */
985 static int authtimeout;
986 static int authlimit;
987 static char *manager_channelvars;
989 #define DEFAULT_REALM "asterisk"
990 static char global_realm[MAXHOSTNAMELEN]; /*!< Default realm */
992 static int block_sockets;
993 static int unauth_sessions = 0;
994 static struct ast_event_sub *acl_change_event_subscription;
997 * Descriptor for a manager session, either on the AMI socket or over HTTP.
1000 * AMI session have managerid == 0; the entry is created upon a connect,
1001 * and destroyed with the socket.
1002 * HTTP sessions have managerid != 0, the value is used as a search key
1003 * to lookup sessions (using the mansession_id cookie, or nonce key from
1004 * Digest Authentication http header).
1006 #define MAX_BLACKLIST_CMD_LEN 2
1007 static const struct {
1008 const char *words[AST_MAX_CMD_LEN];
1009 } command_blacklist[] = {
1010 {{ "module", "load", NULL }},
1011 {{ "module", "unload", NULL }},
1012 {{ "restart", "gracefully", NULL }},
1015 static void acl_change_event_cb(const struct ast_event *event, void *userdata);
1017 static void acl_change_event_subscribe(void)
1019 if (!acl_change_event_subscription) {
1020 acl_change_event_subscription = ast_event_subscribe(AST_EVENT_ACL_CHANGE,
1021 acl_change_event_cb, "Manager must react to Named ACL changes", NULL, AST_EVENT_IE_END);
1025 static void acl_change_event_unsubscribe(void)
1027 if (acl_change_event_subscription) {
1028 acl_change_event_subscription = ast_event_unsubscribe(acl_change_event_subscription);
1032 /* In order to understand what the heck is going on with the
1033 * mansession_session and mansession structs, we need to have a bit of a history
1036 * In the beginning, there was the mansession. The mansession contained data that was
1037 * intrinsic to a manager session, such as the time that it started, the name of the logged-in
1038 * user, etc. In addition to these parameters were the f and fd parameters. For typical manager
1039 * sessions, these were used to represent the TCP socket over which the AMI session was taking
1040 * place. It makes perfect sense for these fields to be a part of the session-specific data since
1041 * the session actually defines this information.
1043 * Then came the HTTP AMI sessions. With these, the f and fd fields need to be opened and closed
1044 * for every single action that occurs. Thus the f and fd fields aren't really specific to the session
1045 * but rather to the action that is being executed. Because a single session may execute many commands
1046 * at once, some sort of safety needed to be added in order to be sure that we did not end up with fd
1047 * leaks from one action overwriting the f and fd fields used by a previous action before the previous action
1048 * has had a chance to properly close its handles.
1050 * The initial idea to solve this was to use thread synchronization, but this prevented multiple actions
1051 * from being run at the same time in a single session. Some manager actions may block for a long time, thus
1052 * creating a large queue of actions to execute. In addition, this fix did not address the basic architectural
1053 * issue that for HTTP manager sessions, the f and fd variables are not really a part of the session, but are
1054 * part of the action instead.
1056 * The new idea was to create a structure on the stack for each HTTP Manager action. This structure would
1057 * contain the action-specific information, such as which file to write to. In order to maintain expectations
1058 * of action handlers and not have to change the public API of the manager code, we would need to name this
1059 * new stacked structure 'mansession' and contain within it the old mansession struct that we used to use.
1060 * We renamed the old mansession struct 'mansession_session' to hopefully convey that what is in this structure
1061 * is session-specific data. The structure that it is wrapped in, called a 'mansession' really contains action-specific
1064 struct mansession_session {
1065 /*! \todo XXX need to document which fields it is protecting */
1066 struct ast_sockaddr addr; /*!< address we are connecting from */
1067 FILE *f; /*!< fdopen() on the underlying fd */
1068 int fd; /*!< descriptor used for output. Either the socket (AMI) or a temporary file (HTTP) */
1069 int inuse; /*!< number of HTTP sessions using this entry */
1070 int needdestroy; /*!< Whether an HTTP session should be destroyed */
1071 pthread_t waiting_thread; /*!< Sleeping thread using this descriptor */
1072 uint32_t managerid; /*!< Unique manager identifier, 0 for AMI sessions */
1073 time_t sessionstart; /*!< Session start time */
1074 struct timeval sessionstart_tv; /*!< Session start time */
1075 time_t sessiontimeout; /*!< Session timeout if HTTP */
1076 char username[80]; /*!< Logged in username */
1077 char challenge[10]; /*!< Authentication challenge */
1078 int authenticated; /*!< Authentication status */
1079 int readperm; /*!< Authorization for reading */
1080 int writeperm; /*!< Authorization for writing */
1081 char inbuf[1025]; /*!< Buffer - we use the extra byte to add a '\0' and simplify parsing */
1082 int inlen; /*!< number of buffered bytes */
1083 struct ao2_container *whitefilters; /*!< Manager event filters - white list */
1084 struct ao2_container *blackfilters; /*!< Manager event filters - black list */
1085 int send_events; /*!< XXX what ? */
1086 struct eventqent *last_ev; /*!< last event processed. */
1087 int writetimeout; /*!< Timeout for ast_carefulwrite() */
1089 int pending_event; /*!< Pending events indicator in case when waiting_thread is NULL */
1090 time_t noncetime; /*!< Timer for nonce value expiration */
1091 unsigned long oldnonce; /*!< Stale nonce value */
1092 unsigned long nc; /*!< incremental nonce counter */
1093 AST_LIST_HEAD_NOLOCK(mansession_datastores, ast_datastore) datastores; /*!< Data stores on the session */
1094 AST_LIST_ENTRY(mansession_session) list;
1097 /*! \brief In case you didn't read that giant block of text above the mansession_session struct, the
1098 * \ref struct mansession is named this solely to keep the API the same in Asterisk. This structure really
1099 * represents data that is different from Manager action to Manager action. The mansession_session pointer
1100 * contained within points to session-specific data.
1103 struct mansession_session *session;
1104 struct ast_tcptls_session_instance *tcptls_session;
1108 struct manager_custom_hook *hook;
1112 static struct ao2_container *sessions = NULL;
1114 struct manager_channel_variable {
1115 AST_LIST_ENTRY(manager_channel_variable) entry;
1116 unsigned int isfunc:1;
1117 char name[0]; /* allocate off the end the real size. */
1120 static AST_RWLIST_HEAD_STATIC(channelvars, manager_channel_variable);
1122 /*! \brief user descriptor, as read from the config file.
1124 * \note It is still missing some fields -- e.g. we can have multiple permit and deny
1125 * lines which are not supported here, and readperm/writeperm/writetimeout
1128 struct ast_manager_user {
1130 char *secret; /*!< Secret for logging in */
1131 int readperm; /*!< Authorization for reading */
1132 int writeperm; /*!< Authorization for writing */
1133 int writetimeout; /*!< Per user Timeout for ast_carefulwrite() */
1134 int displayconnects; /*!< XXX unused */
1135 int keep; /*!< mark entries created on a reload */
1136 struct ao2_container *whitefilters; /*!< Manager event filters - white list */
1137 struct ao2_container *blackfilters; /*!< Manager event filters - black list */
1138 struct ast_acl_list *acl; /*!< ACL setting */
1139 char *a1_hash; /*!< precalculated A1 for Digest auth */
1140 AST_RWLIST_ENTRY(ast_manager_user) list;
1143 /*! \brief list of users found in the config file */
1144 static AST_RWLIST_HEAD_STATIC(users, ast_manager_user);
1146 /*! \brief list of actions registered */
1147 static AST_RWLIST_HEAD_STATIC(actions, manager_action);
1149 /*! \brief list of hooks registered */
1150 static AST_RWLIST_HEAD_STATIC(manager_hooks, manager_custom_hook);
1152 /*! \brief A container of event documentation nodes */
1153 AO2_GLOBAL_OBJ_STATIC(event_docs);
1155 static void free_channelvars(void);
1157 static enum add_filter_result manager_add_filter(const char *filter_pattern, struct ao2_container *whitefilters, struct ao2_container *blackfilters);
1161 * \brief Find a registered action object.
1163 * \param name Name of AMI action to find.
1165 * \return Reffed action found or NULL
1167 static struct manager_action *action_find(const char *name)
1169 struct manager_action *act;
1171 AST_RWLIST_RDLOCK(&actions);
1172 AST_RWLIST_TRAVERSE(&actions, act, list) {
1173 if (!strcasecmp(name, act->action)) {
1174 ao2_t_ref(act, +1, "found action object");
1178 AST_RWLIST_UNLOCK(&actions);
1183 /*! \brief Add a custom hook to be called when an event is fired */
1184 void ast_manager_register_hook(struct manager_custom_hook *hook)
1186 AST_RWLIST_WRLOCK(&manager_hooks);
1187 AST_RWLIST_INSERT_TAIL(&manager_hooks, hook, list);
1188 AST_RWLIST_UNLOCK(&manager_hooks);
1191 /*! \brief Delete a custom hook to be called when an event is fired */
1192 void ast_manager_unregister_hook(struct manager_custom_hook *hook)
1194 AST_RWLIST_WRLOCK(&manager_hooks);
1195 AST_RWLIST_REMOVE(&manager_hooks, hook, list);
1196 AST_RWLIST_UNLOCK(&manager_hooks);
1199 int check_manager_enabled(void)
1201 return manager_enabled;
1204 int check_webmanager_enabled(void)
1206 return (webmanager_enabled && manager_enabled);
1210 * Grab a reference to the last event, update usecount as needed.
1211 * Can handle a NULL pointer.
1213 static struct eventqent *grab_last(void)
1215 struct eventqent *ret;
1217 AST_RWLIST_WRLOCK(&all_events);
1218 ret = AST_RWLIST_LAST(&all_events);
1219 /* the list is never empty now, but may become so when
1220 * we optimize it in the future, so be prepared.
1223 ast_atomic_fetchadd_int(&ret->usecount, 1);
1225 AST_RWLIST_UNLOCK(&all_events);
1230 * Purge unused events. Remove elements from the head
1231 * as long as their usecount is 0 and there is a next element.
1233 static void purge_events(void)
1235 struct eventqent *ev;
1236 struct timeval now = ast_tvnow();
1238 AST_RWLIST_WRLOCK(&all_events);
1239 while ( (ev = AST_RWLIST_FIRST(&all_events)) &&
1240 ev->usecount == 0 && AST_RWLIST_NEXT(ev, eq_next)) {
1241 AST_RWLIST_REMOVE_HEAD(&all_events, eq_next);
1245 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&all_events, ev, eq_next) {
1246 /* Never release the last event */
1247 if (!AST_RWLIST_NEXT(ev, eq_next)) {
1251 /* 2.5 times whatever the HTTP timeout is (maximum 2.5 hours) is the maximum time that we will definitely cache an event */
1252 if (ev->usecount == 0 && ast_tvdiff_sec(now, ev->tv) > (httptimeout > 3600 ? 3600 : httptimeout) * 2.5) {
1253 AST_RWLIST_REMOVE_CURRENT(eq_next);
1257 AST_RWLIST_TRAVERSE_SAFE_END;
1258 AST_RWLIST_UNLOCK(&all_events);
1262 * helper functions to convert back and forth between
1263 * string and numeric representation of set of flags
1265 static const struct permalias {
1269 { EVENT_FLAG_SYSTEM, "system" },
1270 { EVENT_FLAG_CALL, "call" },
1271 { EVENT_FLAG_LOG, "log" },
1272 { EVENT_FLAG_VERBOSE, "verbose" },
1273 { EVENT_FLAG_COMMAND, "command" },
1274 { EVENT_FLAG_AGENT, "agent" },
1275 { EVENT_FLAG_USER, "user" },
1276 { EVENT_FLAG_CONFIG, "config" },
1277 { EVENT_FLAG_DTMF, "dtmf" },
1278 { EVENT_FLAG_REPORTING, "reporting" },
1279 { EVENT_FLAG_CDR, "cdr" },
1280 { EVENT_FLAG_DIALPLAN, "dialplan" },
1281 { EVENT_FLAG_ORIGINATE, "originate" },
1282 { EVENT_FLAG_AGI, "agi" },
1283 { EVENT_FLAG_CC, "cc" },
1284 { EVENT_FLAG_AOC, "aoc" },
1285 { EVENT_FLAG_TEST, "test" },
1286 { EVENT_FLAG_MESSAGE, "message" },
1291 /*! \brief Checks to see if a string which can be used to evaluate functions should be rejected */
1292 static int function_capable_string_allowed_with_auths(const char *evaluating, int writepermlist)
1294 if (!(writepermlist & EVENT_FLAG_SYSTEM)
1296 strstr(evaluating, "SHELL") || /* NoOp(${SHELL(rm -rf /)}) */
1297 strstr(evaluating, "EVAL") /* NoOp(${EVAL(${some_var_containing_SHELL})}) */
1304 /*! \brief Convert authority code to a list of options */
1305 static const char *authority_to_str(int authority, struct ast_str **res)
1310 ast_str_reset(*res);
1311 for (i = 0; i < ARRAY_LEN(perms) - 1; i++) {
1312 if (authority & perms[i].num) {
1313 ast_str_append(res, 0, "%s%s", sep, perms[i].label);
1318 if (ast_str_strlen(*res) == 0) /* replace empty string with something sensible */
1319 ast_str_append(res, 0, "<none>");
1321 return ast_str_buffer(*res);
1324 /*! Tells you if smallstr exists inside bigstr
1325 which is delim by delim and uses no buf or stringsep
1326 ast_instring("this|that|more","this",'|') == 1;
1328 feel free to move this to app.c -anthm */
1329 static int ast_instring(const char *bigstr, const char *smallstr, const char delim)
1331 const char *val = bigstr, *next;
1334 if ((next = strchr(val, delim))) {
1335 if (!strncmp(val, smallstr, (next - val))) {
1341 return !strcmp(smallstr, val);
1343 } while (*(val = (next + 1)));
1348 static int get_perm(const char *instr)
1356 for (x = 0; x < ARRAY_LEN(perms); x++) {
1357 if (ast_instring(instr, perms[x].label, ',')) {
1358 ret |= perms[x].num;
1366 * A number returns itself, false returns 0, true returns all flags,
1367 * other strings return the flags that are set.
1369 static int strings_to_mask(const char *string)
1373 if (ast_strlen_zero(string)) {
1377 for (p = string; *p; p++) {
1378 if (*p < '0' || *p > '9') {
1382 if (!*p) { /* all digits */
1383 return atoi(string);
1385 if (ast_false(string)) {
1388 if (ast_true(string)) { /* all permissions */
1390 for (x = 0; x < ARRAY_LEN(perms); x++) {
1391 ret |= perms[x].num;
1395 return get_perm(string);
1398 /*! \brief Unreference manager session object.
1399 If no more references, then go ahead and delete it */
1400 static struct mansession_session *unref_mansession(struct mansession_session *s)
1402 int refcount = ao2_ref(s, -1);
1403 if (manager_debug) {
1404 ast_debug(1, "Mansession: %p refcount now %d\n", s, refcount - 1);
1409 static void event_filter_destructor(void *obj)
1411 regex_t *regex_filter = obj;
1412 regfree(regex_filter);
1415 static void session_destructor(void *obj)
1417 struct mansession_session *session = obj;
1418 struct eventqent *eqe = session->last_ev;
1419 struct ast_datastore *datastore;
1421 /* Get rid of each of the data stores on the session */
1422 while ((datastore = AST_LIST_REMOVE_HEAD(&session->datastores, entry))) {
1423 /* Free the data store */
1424 ast_datastore_free(datastore);
1427 if (session->f != NULL) {
1431 ast_atomic_fetchadd_int(&eqe->usecount, -1);
1434 if (session->whitefilters) {
1435 ao2_t_callback(session->whitefilters, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL, "unlink all white filters");
1436 ao2_t_ref(session->whitefilters, -1 , "decrement ref for white container, should be last one");
1439 if (session->blackfilters) {
1440 ao2_t_callback(session->blackfilters, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL, "unlink all black filters");
1441 ao2_t_ref(session->blackfilters, -1 , "decrement ref for black container, should be last one");
1445 /*! \brief Allocate manager session structure and add it to the list of sessions */
1446 static struct mansession_session *build_mansession(const struct ast_sockaddr *addr)
1448 struct mansession_session *newsession;
1450 if (!(newsession = ao2_alloc(sizeof(*newsession), session_destructor))) {
1454 if (!(newsession->whitefilters = ao2_container_alloc(1, NULL, NULL))) {
1455 ao2_ref(newsession, -1);
1459 if (!(newsession->blackfilters = ao2_container_alloc(1, NULL, NULL))) {
1460 ao2_ref(newsession, -1); /* session_destructor will cleanup the other filter */
1464 newsession->fd = -1;
1465 newsession->waiting_thread = AST_PTHREADT_NULL;
1466 newsession->writetimeout = 100;
1467 newsession->send_events = -1;
1468 ast_sockaddr_copy(&newsession->addr, addr);
1470 ao2_link(sessions, newsession);
1475 static int mansession_cmp_fn(void *obj, void *arg, int flags)
1477 struct mansession_session *s = obj;
1479 return !strcasecmp(s->username, str) ? CMP_MATCH : 0;
1482 static void session_destroy(struct mansession_session *s)
1484 unref_mansession(s);
1485 ao2_unlink(sessions, s);
1489 static int check_manager_session_inuse(const char *name)
1491 struct mansession_session *session = ao2_find(sessions, (char *) name, 0);
1496 unref_mansession(session);
1503 * lookup an entry in the list of registered users.
1504 * must be called with the list lock held.
1506 static struct ast_manager_user *get_manager_by_name_locked(const char *name)
1508 struct ast_manager_user *user = NULL;
1510 AST_RWLIST_TRAVERSE(&users, user, list) {
1511 if (!strcasecmp(user->username, name)) {
1519 /*! \brief Get displayconnects config option.
1520 * \param session manager session to get parameter from.
1521 * \return displayconnects config option value.
1523 static int manager_displayconnects (struct mansession_session *session)
1525 struct ast_manager_user *user = NULL;
1528 AST_RWLIST_RDLOCK(&users);
1529 if ((user = get_manager_by_name_locked (session->username))) {
1530 ret = user->displayconnects;
1532 AST_RWLIST_UNLOCK(&users);
1537 static char *handle_showmancmd(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1539 struct manager_action *cur;
1540 struct ast_str *authority;
1544 char syntax_title[64], description_title[64], synopsis_title[64], seealso_title[64], arguments_title[64];
1549 e->command = "manager show command";
1551 "Usage: manager show command <actionname> [<actionname> [<actionname> [...]]]\n"
1552 " Shows the detailed description for a specific Asterisk manager interface command.\n";
1555 l = strlen(a->word);
1557 AST_RWLIST_RDLOCK(&actions);
1558 AST_RWLIST_TRAVERSE(&actions, cur, list) {
1559 if (!strncasecmp(a->word, cur->action, l) && ++which > a->n) {
1560 ret = ast_strdup(cur->action);
1561 break; /* make sure we exit even if ast_strdup() returns NULL */
1564 AST_RWLIST_UNLOCK(&actions);
1567 authority = ast_str_alloca(80);
1569 return CLI_SHOWUSAGE;
1573 /* setup the titles */
1574 term_color(synopsis_title, "[Synopsis]\n", COLOR_MAGENTA, 0, 40);
1575 term_color(description_title, "[Description]\n", COLOR_MAGENTA, 0, 40);
1576 term_color(syntax_title, "[Syntax]\n", COLOR_MAGENTA, 0, 40);
1577 term_color(seealso_title, "[See Also]\n", COLOR_MAGENTA, 0, 40);
1578 term_color(arguments_title, "[Arguments]\n", COLOR_MAGENTA, 0, 40);
1581 AST_RWLIST_RDLOCK(&actions);
1582 AST_RWLIST_TRAVERSE(&actions, cur, list) {
1583 for (num = 3; num < a->argc; num++) {
1584 if (!strcasecmp(cur->action, a->argv[num])) {
1586 if (cur->docsrc == AST_XML_DOC) {
1587 ast_cli(a->fd, "%s%s\n\n%s%s\n\n%s%s\n\n%s%s\n\n%s%s\n\n",
1589 ast_xmldoc_printable(S_OR(cur->syntax, "Not available"), 1),
1591 ast_xmldoc_printable(S_OR(cur->synopsis, "Not available"), 1),
1593 ast_xmldoc_printable(S_OR(cur->description, "Not available"), 1),
1595 ast_xmldoc_printable(S_OR(cur->arguments, "Not available"), 1),
1597 ast_xmldoc_printable(S_OR(cur->seealso, "Not available"), 1));
1601 ast_cli(a->fd, "Action: %s\nSynopsis: %s\nPrivilege: %s\n%s\n",
1602 cur->action, cur->synopsis,
1603 authority_to_str(cur->authority, &authority),
1604 S_OR(cur->description, ""));
1609 AST_RWLIST_UNLOCK(&actions);
1614 static char *handle_mandebug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1618 e->command = "manager set debug [on|off]";
1619 e->usage = "Usage: manager set debug [on|off]\n Show, enable, disable debugging of the manager code.\n";
1626 ast_cli(a->fd, "manager debug is %s\n", manager_debug? "on" : "off");
1627 } else if (a->argc == 4) {
1628 if (!strcasecmp(a->argv[3], "on")) {
1630 } else if (!strcasecmp(a->argv[3], "off")) {
1633 return CLI_SHOWUSAGE;
1639 static char *handle_showmanager(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1641 struct ast_manager_user *user = NULL;
1644 struct ast_str *rauthority = ast_str_alloca(128);
1645 struct ast_str *wauthority = ast_str_alloca(128);
1649 e->command = "manager show user";
1651 " Usage: manager show user <user>\n"
1652 " Display all information related to the manager user specified.\n";
1655 l = strlen(a->word);
1660 AST_RWLIST_RDLOCK(&users);
1661 AST_RWLIST_TRAVERSE(&users, user, list) {
1662 if ( !strncasecmp(a->word, user->username, l) && ++which > a->n ) {
1663 ret = ast_strdup(user->username);
1667 AST_RWLIST_UNLOCK(&users);
1672 return CLI_SHOWUSAGE;
1675 AST_RWLIST_RDLOCK(&users);
1677 if (!(user = get_manager_by_name_locked(a->argv[3]))) {
1678 ast_cli(a->fd, "There is no manager called %s\n", a->argv[3]);
1679 AST_RWLIST_UNLOCK(&users);
1683 ast_cli(a->fd, "\n");
1690 "displayconnects: %s\n",
1691 (user->username ? user->username : "(N/A)"),
1692 (user->secret ? "<Set>" : "(N/A)"),
1693 ((user->acl && !ast_acl_list_is_empty(user->acl)) ? "yes" : "no"),
1694 authority_to_str(user->readperm, &rauthority),
1695 authority_to_str(user->writeperm, &wauthority),
1696 (user->displayconnects ? "yes" : "no"));
1698 AST_RWLIST_UNLOCK(&users);
1703 static char *handle_showmanagers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1705 struct ast_manager_user *user = NULL;
1709 e->command = "manager show users";
1711 "Usage: manager show users\n"
1712 " Prints a listing of all managers that are currently configured on that\n"
1719 return CLI_SHOWUSAGE;
1722 AST_RWLIST_RDLOCK(&users);
1724 /* If there are no users, print out something along those lines */
1725 if (AST_RWLIST_EMPTY(&users)) {
1726 ast_cli(a->fd, "There are no manager users.\n");
1727 AST_RWLIST_UNLOCK(&users);
1731 ast_cli(a->fd, "\nusername\n--------\n");
1733 AST_RWLIST_TRAVERSE(&users, user, list) {
1734 ast_cli(a->fd, "%s\n", user->username);
1738 AST_RWLIST_UNLOCK(&users);
1740 ast_cli(a->fd,"-------------------\n"
1741 "%d manager users configured.\n", count_amu);
1745 /*! \brief CLI command manager list commands */
1746 static char *handle_showmancmds(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1748 struct manager_action *cur;
1749 struct ast_str *authority;
1750 #define HSMC_FORMAT " %-15.15s %-15.15s %-55.55s\n"
1753 e->command = "manager show commands";
1755 "Usage: manager show commands\n"
1756 " Prints a listing of all the available Asterisk manager interface commands.\n";
1761 authority = ast_str_alloca(80);
1762 ast_cli(a->fd, HSMC_FORMAT, "Action", "Privilege", "Synopsis");
1763 ast_cli(a->fd, HSMC_FORMAT, "------", "---------", "--------");
1765 AST_RWLIST_RDLOCK(&actions);
1766 AST_RWLIST_TRAVERSE(&actions, cur, list) {
1767 ast_cli(a->fd, HSMC_FORMAT, cur->action, authority_to_str(cur->authority, &authority), cur->synopsis);
1769 AST_RWLIST_UNLOCK(&actions);
1774 /*! \brief CLI command manager list connected */
1775 static char *handle_showmanconn(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1777 struct mansession_session *session;
1778 time_t now = time(NULL);
1779 #define HSMCONN_FORMAT1 " %-15.15s %-55.55s %-10.10s %-10.10s %-8.8s %-8.8s %-5.5s %-5.5s\n"
1780 #define HSMCONN_FORMAT2 " %-15.15s %-55.55s %-10d %-10d %-8d %-8d %-5.5d %-5.5d\n"
1782 struct ao2_iterator i;
1786 e->command = "manager show connected";
1788 "Usage: manager show connected\n"
1789 " Prints a listing of the users that are currently connected to the\n"
1790 "Asterisk manager interface.\n";
1796 ast_cli(a->fd, HSMCONN_FORMAT1, "Username", "IP Address", "Start", "Elapsed", "FileDes", "HttpCnt", "Read", "Write");
1798 i = ao2_iterator_init(sessions, 0);
1799 while ((session = ao2_iterator_next(&i))) {
1801 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);
1803 ao2_unlock(session);
1804 unref_mansession(session);
1806 ao2_iterator_destroy(&i);
1807 ast_cli(a->fd, "%d users connected.\n", count);
1812 /*! \brief CLI command manager list eventq */
1813 /* Should change to "manager show connected" */
1814 static char *handle_showmaneventq(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1816 struct eventqent *s;
1819 e->command = "manager show eventq";
1821 "Usage: manager show eventq\n"
1822 " Prints a listing of all events pending in the Asterisk manger\n"
1828 AST_RWLIST_RDLOCK(&all_events);
1829 AST_RWLIST_TRAVERSE(&all_events, s, eq_next) {
1830 ast_cli(a->fd, "Usecount: %d\n", s->usecount);
1831 ast_cli(a->fd, "Category: %d\n", s->category);
1832 ast_cli(a->fd, "Event:\n%s", s->eventdata);
1834 AST_RWLIST_UNLOCK(&all_events);
1839 /*! \brief CLI command manager reload */
1840 static char *handle_manager_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1844 e->command = "manager reload";
1846 "Usage: manager reload\n"
1847 " Reloads the manager configuration.\n";
1853 return CLI_SHOWUSAGE;
1859 static struct eventqent *advance_event(struct eventqent *e)
1861 struct eventqent *next;
1863 AST_RWLIST_RDLOCK(&all_events);
1864 if ((next = AST_RWLIST_NEXT(e, eq_next))) {
1865 ast_atomic_fetchadd_int(&next->usecount, 1);
1866 ast_atomic_fetchadd_int(&e->usecount, -1);
1868 AST_RWLIST_UNLOCK(&all_events);
1872 #define GET_HEADER_FIRST_MATCH 0
1873 #define GET_HEADER_LAST_MATCH 1
1874 #define GET_HEADER_SKIP_EMPTY 2
1877 * \brief Return a matching header value.
1880 * Generic function to return either the first or the last
1881 * matching header from a list of variables, possibly skipping
1884 * \note At the moment there is only one use of this function in
1885 * this file, so we make it static.
1887 * \note Never returns NULL.
1889 static const char *__astman_get_header(const struct message *m, char *var, int mode)
1891 int x, l = strlen(var);
1892 const char *result = "";
1894 for (x = 0; x < m->hdrcount; x++) {
1895 const char *h = m->headers[x];
1896 if (!strncasecmp(var, h, l) && h[l] == ':') {
1897 const char *value = h + l + 1;
1898 value = ast_skip_blanks(value); /* ignore leading spaces in the value */
1899 /* found a potential candidate */
1900 if ((mode & GET_HEADER_SKIP_EMPTY) && ast_strlen_zero(value)) {
1901 continue; /* not interesting */
1903 if (mode & GET_HEADER_LAST_MATCH) {
1904 result = value; /* record the last match so far */
1915 * \brief Return the first matching variable from an array.
1917 * \note This is the legacy function and is implemented in
1918 * therms of __astman_get_header().
1920 * \note Never returns NULL.
1922 const char *astman_get_header(const struct message *m, char *var)
1924 return __astman_get_header(m, var, GET_HEADER_FIRST_MATCH);
1929 * \brief Process one "Variable:" header value string.
1931 * \param head Current list of AMI variables to get new values added.
1932 * \param hdr_val Header value string to process.
1934 * \return New variable list head.
1936 static struct ast_variable *man_do_variable_value(struct ast_variable *head, const char *hdr_val)
1939 AST_DECLARE_APP_ARGS(args,
1940 AST_APP_ARG(vars)[64];
1943 hdr_val = ast_skip_blanks(hdr_val); /* ignore leading spaces in the value */
1944 parse = ast_strdupa(hdr_val);
1946 /* Break the header value string into name=val pair items. */
1947 AST_STANDARD_APP_ARGS(args, parse);
1951 /* Process each name=val pair item. */
1952 for (y = 0; y < args.argc; y++) {
1953 struct ast_variable *cur;
1957 if (!args.vars[y]) {
1960 var = val = args.vars[y];
1963 /* XXX We may wish to trim whitespace from the strings. */
1964 if (!val || ast_strlen_zero(var)) {
1968 /* Create new variable list node and prepend it to the list. */
1969 cur = ast_variable_new(var, val, "");
1980 struct ast_variable *astman_get_variables(const struct message *m)
1984 struct ast_variable *head = NULL;
1986 static const char var_hdr[] = "Variable:";
1988 /* Process all "Variable:" headers. */
1989 varlen = strlen(var_hdr);
1990 for (x = 0; x < m->hdrcount; x++) {
1991 if (strncasecmp(var_hdr, m->headers[x], varlen)) {
1994 head = man_do_variable_value(head, m->headers[x] + varlen);
2000 /*! \brief access for hooks to send action messages to ami */
2001 int ast_hook_send_action(struct manager_custom_hook *hook, const char *msg)
2005 struct manager_action *act_found;
2006 struct mansession s = {.session = NULL, };
2007 struct message m = { 0 };
2017 /* Create our own copy of the AMI action msg string. */
2018 src = dup_str = ast_strdup(msg);
2023 /* convert msg string to message struct */
2024 curlen = strlen(src);
2025 for (x = 0; x < curlen; x++) {
2026 int cr; /* set if we have \r */
2027 if (src[x] == '\r' && x+1 < curlen && src[x+1] == '\n')
2028 cr = 2; /* Found. Update length to include \r\n */
2029 else if (src[x] == '\n')
2030 cr = 1; /* also accept \n only */
2033 /* don't keep empty lines */
2034 if (x && m.hdrcount < ARRAY_LEN(m.headers)) {
2035 /* ... but trim \r\n and terminate the header string */
2037 m.headers[m.hdrcount++] = src;
2040 curlen -= x; /* remaining size */
2041 src += x; /* update pointer */
2042 x = -1; /* reset loop */
2045 action = astman_get_header(&m, "Action");
2046 if (strcasecmp(action, "login")) {
2047 act_found = action_find(action);
2050 * we have to simulate a session for this action request
2051 * to be able to pass it down for processing
2052 * This is necessary to meet the previous design of manager.c
2055 s.f = (void*)1; /* set this to something so our request will make it through all functions that test it*/
2057 ao2_lock(act_found);
2058 if (act_found->registered && act_found->func) {
2059 if (act_found->module) {
2060 ast_module_ref(act_found->module);
2062 ao2_unlock(act_found);
2063 ret = act_found->func(&s, &m);
2064 ao2_lock(act_found);
2065 if (act_found->module) {
2066 ast_module_unref(act_found->module);
2071 ao2_unlock(act_found);
2072 ao2_t_ref(act_found, -1, "done with found action object");
2081 * helper function to send a string to the socket.
2082 * Return -1 on error (e.g. buffer full).
2084 static int send_string(struct mansession *s, char *string)
2087 FILE *f = s->f ? s->f : s->session->f;
2088 int fd = s->f ? s->fd : s->session->fd;
2090 /* It's a result from one of the hook's action invocation */
2093 * to send responses, we're using the same function
2094 * as for receiving events. We call the event "HookResponse"
2096 s->hook->helper(EVENT_FLAG_HOOKRESPONSE, "HookResponse", string);
2100 if ((res = ast_careful_fwrite(f, fd, string, strlen(string), s->session->writetimeout))) {
2108 * \brief thread local buffer for astman_append
2110 * \note This can not be defined within the astman_append() function
2111 * because it declares a couple of functions that get used to
2112 * initialize the thread local storage key.
2114 AST_THREADSTORAGE(astman_append_buf);
2116 AST_THREADSTORAGE(userevent_buf);
2118 /*! \brief initial allocated size for the astman_append_buf and astman_send_*_va */
2119 #define ASTMAN_APPEND_BUF_INITSIZE 256
2122 * utility functions for creating AMI replies
2124 void astman_append(struct mansession *s, const char *fmt, ...)
2127 struct ast_str *buf;
2129 if (!(buf = ast_str_thread_get(&astman_append_buf, ASTMAN_APPEND_BUF_INITSIZE))) {
2134 ast_str_set_va(&buf, 0, fmt, ap);
2137 if (s->f != NULL || s->session->f != NULL) {
2138 send_string(s, ast_str_buffer(buf));
2140 ast_verbose("fd == -1 in astman_append, should not happen\n");
2144 /*! \note NOTE: XXX this comment is unclear and possibly wrong.
2145 Callers of astman_send_error(), astman_send_response() or astman_send_ack() must EITHER
2146 hold the session lock _or_ be running in an action callback (in which case s->session->busy will
2147 be non-zero). In either of these cases, there is no need to lock-protect the session's
2148 fd, since no other output will be sent (events will be queued), and no input will
2149 be read until either the current action finishes or get_input() obtains the session
2153 /*! \todo XXX MSG_MOREDATA should go to a header file. */
2154 #define MSG_MOREDATA ((char *)astman_send_response)
2156 /*! \brief send a response with an optional message,
2157 * and terminate it with an empty line.
2158 * m is used only to grab the 'ActionID' field.
2160 * Use the explicit constant MSG_MOREDATA to remove the empty line.
2161 * XXX MSG_MOREDATA should go to a header file.
2163 static void astman_send_response_full(struct mansession *s, const struct message *m, char *resp, char *msg, char *listflag)
2165 const char *id = astman_get_header(m, "ActionID");
2167 astman_append(s, "Response: %s\r\n", resp);
2168 if (!ast_strlen_zero(id)) {
2169 astman_append(s, "ActionID: %s\r\n", id);
2172 astman_append(s, "EventList: %s\r\n", listflag); /* Start, complete, cancelled */
2174 if (msg == MSG_MOREDATA) {
2177 astman_append(s, "Message: %s\r\n\r\n", msg);
2179 astman_append(s, "\r\n");
2183 void astman_send_response(struct mansession *s, const struct message *m, char *resp, char *msg)
2185 astman_send_response_full(s, m, resp, msg, NULL);
2188 void astman_send_error(struct mansession *s, const struct message *m, char *error)
2190 astman_send_response_full(s, m, "Error", error, NULL);
2193 void astman_send_error_va(struct mansession *s, const struct message *m, const char *fmt, ...)
2196 struct ast_str *buf;
2198 if (!(buf = ast_str_thread_get(&astman_append_buf, ASTMAN_APPEND_BUF_INITSIZE))) {
2203 ast_str_set_va(&buf, 0, fmt, ap);
2206 astman_send_response_full(s, m, "Error", ast_str_buffer(buf), NULL);
2210 void astman_send_ack(struct mansession *s, const struct message *m, char *msg)
2212 astman_send_response_full(s, m, "Success", msg, NULL);
2215 static void astman_start_ack(struct mansession *s, const struct message *m)
2217 astman_send_response_full(s, m, "Success", MSG_MOREDATA, NULL);
2220 void astman_send_listack(struct mansession *s, const struct message *m, char *msg, char *listflag)
2222 astman_send_response_full(s, m, "Success", msg, listflag);
2225 /*! \brief Lock the 'mansession' structure. */
2226 static void mansession_lock(struct mansession *s)
2228 ast_mutex_lock(&s->lock);
2231 /*! \brief Unlock the 'mansession' structure. */
2232 static void mansession_unlock(struct mansession *s)
2234 ast_mutex_unlock(&s->lock);
2238 Rather than braindead on,off this now can also accept a specific int mask value
2239 or a ',' delim list of mask strings (the same as manager.conf) -anthm
2241 static int set_eventmask(struct mansession *s, const char *eventmask)
2243 int maskint = strings_to_mask(eventmask);
2245 ao2_lock(s->session);
2247 s->session->send_events = maskint;
2249 ao2_unlock(s->session);
2254 static enum ast_security_event_transport_type mansession_get_transport(const struct mansession *s)
2256 return s->tcptls_session->parent->tls_cfg ? AST_SECURITY_EVENT_TRANSPORT_TLS :
2257 AST_SECURITY_EVENT_TRANSPORT_TCP;
2260 static void report_invalid_user(const struct mansession *s, const char *username)
2262 char session_id[32];
2263 struct ast_security_event_inval_acct_id inval_acct_id = {
2264 .common.event_type = AST_SECURITY_EVENT_INVAL_ACCT_ID,
2265 .common.version = AST_SECURITY_EVENT_INVAL_ACCT_ID_VERSION,
2266 .common.service = "AMI",
2267 .common.account_id = username,
2268 .common.session_tv = &s->session->sessionstart_tv,
2269 .common.local_addr = {
2270 .addr = &s->tcptls_session->parent->local_address,
2271 .transport = mansession_get_transport(s),
2273 .common.remote_addr = {
2274 .addr = &s->session->addr,
2275 .transport = mansession_get_transport(s),
2277 .common.session_id = session_id,
2280 snprintf(session_id, sizeof(session_id), "%p", s);
2282 ast_security_event_report(AST_SEC_EVT(&inval_acct_id));
2285 static void report_failed_acl(const struct mansession *s, const char *username)
2287 char session_id[32];
2288 struct ast_security_event_failed_acl failed_acl_event = {
2289 .common.event_type = AST_SECURITY_EVENT_FAILED_ACL,
2290 .common.version = AST_SECURITY_EVENT_FAILED_ACL_VERSION,
2291 .common.service = "AMI",
2292 .common.account_id = username,
2293 .common.session_tv = &s->session->sessionstart_tv,
2294 .common.local_addr = {
2295 .addr = &s->tcptls_session->parent->local_address,
2296 .transport = mansession_get_transport(s),
2298 .common.remote_addr = {
2299 .addr = &s->session->addr,
2300 .transport = mansession_get_transport(s),
2302 .common.session_id = session_id,
2305 snprintf(session_id, sizeof(session_id), "%p", s->session);
2307 ast_security_event_report(AST_SEC_EVT(&failed_acl_event));
2310 static void report_inval_password(const struct mansession *s, const char *username)
2312 char session_id[32];
2313 struct ast_security_event_inval_password inval_password = {
2314 .common.event_type = AST_SECURITY_EVENT_INVAL_PASSWORD,
2315 .common.version = AST_SECURITY_EVENT_INVAL_PASSWORD_VERSION,
2316 .common.service = "AMI",
2317 .common.account_id = username,
2318 .common.session_tv = &s->session->sessionstart_tv,
2319 .common.local_addr = {
2320 .addr = &s->tcptls_session->parent->local_address,
2321 .transport = mansession_get_transport(s),
2323 .common.remote_addr = {
2324 .addr = &s->session->addr,
2325 .transport = mansession_get_transport(s),
2327 .common.session_id = session_id,
2330 snprintf(session_id, sizeof(session_id), "%p", s->session);
2332 ast_security_event_report(AST_SEC_EVT(&inval_password));
2335 static void report_auth_success(const struct mansession *s)
2337 char session_id[32];
2338 struct ast_security_event_successful_auth successful_auth = {
2339 .common.event_type = AST_SECURITY_EVENT_SUCCESSFUL_AUTH,
2340 .common.version = AST_SECURITY_EVENT_SUCCESSFUL_AUTH_VERSION,
2341 .common.service = "AMI",
2342 .common.account_id = s->session->username,
2343 .common.session_tv = &s->session->sessionstart_tv,
2344 .common.local_addr = {
2345 .addr = &s->tcptls_session->parent->local_address,
2346 .transport = mansession_get_transport(s),
2348 .common.remote_addr = {
2349 .addr = &s->session->addr,
2350 .transport = mansession_get_transport(s),
2352 .common.session_id = session_id,
2355 snprintf(session_id, sizeof(session_id), "%p", s->session);
2357 ast_security_event_report(AST_SEC_EVT(&successful_auth));
2360 static void report_req_not_allowed(const struct mansession *s, const char *action)
2362 char session_id[32];
2363 char request_type[64];
2364 struct ast_security_event_req_not_allowed req_not_allowed = {
2365 .common.event_type = AST_SECURITY_EVENT_REQ_NOT_ALLOWED,
2366 .common.version = AST_SECURITY_EVENT_REQ_NOT_ALLOWED_VERSION,
2367 .common.service = "AMI",
2368 .common.account_id = s->session->username,
2369 .common.session_tv = &s->session->sessionstart_tv,
2370 .common.local_addr = {
2371 .addr = &s->tcptls_session->parent->local_address,
2372 .transport = mansession_get_transport(s),
2374 .common.remote_addr = {
2375 .addr = &s->session->addr,
2376 .transport = mansession_get_transport(s),
2378 .common.session_id = session_id,
2380 .request_type = request_type,
2383 snprintf(session_id, sizeof(session_id), "%p", s->session);
2384 snprintf(request_type, sizeof(request_type), "Action: %s", action);
2386 ast_security_event_report(AST_SEC_EVT(&req_not_allowed));
2389 static void report_req_bad_format(const struct mansession *s, const char *action)
2391 char session_id[32];
2392 char request_type[64];
2393 struct ast_security_event_req_bad_format req_bad_format = {
2394 .common.event_type = AST_SECURITY_EVENT_REQ_BAD_FORMAT,
2395 .common.version = AST_SECURITY_EVENT_REQ_BAD_FORMAT_VERSION,
2396 .common.service = "AMI",
2397 .common.account_id = s->session->username,
2398 .common.session_tv = &s->session->sessionstart_tv,
2399 .common.local_addr = {
2400 .addr = &s->tcptls_session->parent->local_address,
2401 .transport = mansession_get_transport(s),
2403 .common.remote_addr = {
2404 .addr = &s->session->addr,
2405 .transport = mansession_get_transport(s),
2407 .common.session_id = session_id,
2409 .request_type = request_type,
2412 snprintf(session_id, sizeof(session_id), "%p", s->session);
2413 snprintf(request_type, sizeof(request_type), "Action: %s", action);
2415 ast_security_event_report(AST_SEC_EVT(&req_bad_format));
2418 static void report_failed_challenge_response(const struct mansession *s,
2419 const char *response, const char *expected_response)
2421 char session_id[32];
2422 struct ast_security_event_chal_resp_failed chal_resp_failed = {
2423 .common.event_type = AST_SECURITY_EVENT_CHAL_RESP_FAILED,
2424 .common.version = AST_SECURITY_EVENT_CHAL_RESP_FAILED_VERSION,
2425 .common.service = "AMI",
2426 .common.account_id = s->session->username,
2427 .common.session_tv = &s->session->sessionstart_tv,
2428 .common.local_addr = {
2429 .addr = &s->tcptls_session->parent->local_address,
2430 .transport = mansession_get_transport(s),
2432 .common.remote_addr = {
2433 .addr = &s->session->addr,
2434 .transport = mansession_get_transport(s),
2436 .common.session_id = session_id,
2438 .challenge = s->session->challenge,
2439 .response = response,
2440 .expected_response = expected_response,
2443 snprintf(session_id, sizeof(session_id), "%p", s->session);
2445 ast_security_event_report(AST_SEC_EVT(&chal_resp_failed));
2448 static void report_session_limit(const struct mansession *s)
2450 char session_id[32];
2451 struct ast_security_event_session_limit session_limit = {
2452 .common.event_type = AST_SECURITY_EVENT_SESSION_LIMIT,
2453 .common.version = AST_SECURITY_EVENT_SESSION_LIMIT_VERSION,
2454 .common.service = "AMI",
2455 .common.account_id = s->session->username,
2456 .common.session_tv = &s->session->sessionstart_tv,
2457 .common.local_addr = {
2458 .addr = &s->tcptls_session->parent->local_address,
2459 .transport = mansession_get_transport(s),
2461 .common.remote_addr = {
2462 .addr = &s->session->addr,
2463 .transport = mansession_get_transport(s),
2465 .common.session_id = session_id,
2468 snprintf(session_id, sizeof(session_id), "%p", s->session);
2470 ast_security_event_report(AST_SEC_EVT(&session_limit));
2474 * Here we start with action_ handlers for AMI actions,
2475 * and the internal functions used by them.
2476 * Generally, the handlers are called action_foo()
2479 /* helper function for action_login() */
2480 static int authenticate(struct mansession *s, const struct message *m)
2482 const char *username = astman_get_header(m, "Username");
2483 const char *password = astman_get_header(m, "Secret");
2485 struct ast_manager_user *user = NULL;
2486 regex_t *regex_filter;
2487 struct ao2_iterator filter_iter;
2489 if (ast_strlen_zero(username)) { /* missing username */
2493 /* locate user in locked state */
2494 AST_RWLIST_WRLOCK(&users);
2496 if (!(user = get_manager_by_name_locked(username))) {
2497 report_invalid_user(s, username);
2498 ast_log(LOG_NOTICE, "%s tried to authenticate with nonexistent user '%s'\n", ast_sockaddr_stringify_addr(&s->session->addr), username);
2499 } else if (user->acl && (ast_apply_acl(user->acl, &s->session->addr, "Manager User ACL: ") == AST_SENSE_DENY)) {
2500 report_failed_acl(s, username);
2501 ast_log(LOG_NOTICE, "%s failed to pass IP ACL as '%s'\n", ast_sockaddr_stringify_addr(&s->session->addr), username);
2502 } else if (!strcasecmp(astman_get_header(m, "AuthType"), "MD5")) {
2503 const char *key = astman_get_header(m, "Key");
2504 if (!ast_strlen_zero(key) && !ast_strlen_zero(s->session->challenge) && user->secret) {
2507 char md5key[256] = "";
2508 struct MD5Context md5;
2509 unsigned char digest[16];
2512 MD5Update(&md5, (unsigned char *) s->session->challenge, strlen(s->session->challenge));
2513 MD5Update(&md5, (unsigned char *) user->secret, strlen(user->secret));
2514 MD5Final(digest, &md5);
2515 for (x = 0; x < 16; x++)
2516 len += sprintf(md5key + len, "%2.2x", digest[x]);
2517 if (!strcmp(md5key, key)) {
2520 report_failed_challenge_response(s, key, md5key);
2523 ast_debug(1, "MD5 authentication is not possible. challenge: '%s'\n",
2524 S_OR(s->session->challenge, ""));
2526 } else if (user->secret) {
2527 if (!strcmp(password, user->secret)) {
2530 report_inval_password(s, username);
2535 ast_log(LOG_NOTICE, "%s failed to authenticate as '%s'\n", ast_sockaddr_stringify_addr(&s->session->addr), username);
2536 AST_RWLIST_UNLOCK(&users);
2542 /* All of the user parameters are copied to the session so that in the event
2543 * of a reload and a configuration change, the session parameters are not
2545 ast_copy_string(s->session->username, username, sizeof(s->session->username));
2546 s->session->readperm = user->readperm;
2547 s->session->writeperm = user->writeperm;
2548 s->session->writetimeout = user->writetimeout;
2550 filter_iter = ao2_iterator_init(user->whitefilters, 0);
2551 while ((regex_filter = ao2_iterator_next(&filter_iter))) {
2552 ao2_t_link(s->session->whitefilters, regex_filter, "add white user filter to session");
2553 ao2_t_ref(regex_filter, -1, "remove iterator ref");
2555 ao2_iterator_destroy(&filter_iter);
2557 filter_iter = ao2_iterator_init(user->blackfilters, 0);
2558 while ((regex_filter = ao2_iterator_next(&filter_iter))) {
2559 ao2_t_link(s->session->blackfilters, regex_filter, "add black user filter to session");
2560 ao2_t_ref(regex_filter, -1, "remove iterator ref");
2562 ao2_iterator_destroy(&filter_iter);
2564 s->session->sessionstart = time(NULL);
2565 s->session->sessionstart_tv = ast_tvnow();
2566 set_eventmask(s, astman_get_header(m, "Events"));
2568 report_auth_success(s);
2570 AST_RWLIST_UNLOCK(&users);
2574 static int action_ping(struct mansession *s, const struct message *m)
2576 const char *actionid = astman_get_header(m, "ActionID");
2577 struct timeval now = ast_tvnow();
2579 astman_append(s, "Response: Success\r\n");
2580 if (!ast_strlen_zero(actionid)){
2581 astman_append(s, "ActionID: %s\r\n", actionid);
2586 "Timestamp: %ld.%06lu\r\n"
2588 (long) now.tv_sec, (unsigned long) now.tv_usec);
2592 static int action_getconfig(struct mansession *s, const struct message *m)
2594 struct ast_config *cfg;
2595 const char *fn = astman_get_header(m, "Filename");
2596 const char *category = astman_get_header(m, "Category");
2599 char *cur_category = NULL;
2600 struct ast_variable *v;
2601 struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
2603 if (ast_strlen_zero(fn)) {
2604 astman_send_error(s, m, "Filename not specified");
2607 cfg = ast_config_load2(fn, "manager", config_flags);
2608 if (cfg == CONFIG_STATUS_FILEMISSING) {
2609 astman_send_error(s, m, "Config file not found");
2611 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
2612 astman_send_error(s, m, "Config file has invalid format");
2616 astman_start_ack(s, m);
2617 while ((cur_category = ast_category_browse(cfg, cur_category))) {
2618 if (ast_strlen_zero(category) || (!ast_strlen_zero(category) && !strcmp(category, cur_category))) {
2620 astman_append(s, "Category-%06d: %s\r\n", catcount, cur_category);
2621 for (v = ast_variable_browse(cfg, cur_category); v; v = v->next) {
2622 astman_append(s, "Line-%06d-%06d: %s=%s\r\n", catcount, lineno++, v->name, v->value);
2627 if (!ast_strlen_zero(category) && catcount == 0) { /* TODO: actually, a config with no categories doesn't even get loaded */
2628 astman_append(s, "No categories found\r\n");
2630 ast_config_destroy(cfg);
2631 astman_append(s, "\r\n");
2636 static int action_listcategories(struct mansession *s, const struct message *m)
2638 struct ast_config *cfg;
2639 const char *fn = astman_get_header(m, "Filename");
2640 char *category = NULL;
2641 struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
2644 if (ast_strlen_zero(fn)) {
2645 astman_send_error(s, m, "Filename not specified");
2648 if (!(cfg = ast_config_load2(fn, "manager", config_flags))) {
2649 astman_send_error(s, m, "Config file not found");
2651 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
2652 astman_send_error(s, m, "Config file has invalid format");
2655 astman_start_ack(s, m);
2656 while ((category = ast_category_browse(cfg, category))) {
2657 astman_append(s, "Category-%06d: %s\r\n", catcount, category);
2660 if (catcount == 0) { /* TODO: actually, a config with no categories doesn't even get loaded */
2661 astman_append(s, "Error: no categories found\r\n");
2663 ast_config_destroy(cfg);
2664 astman_append(s, "\r\n");
2672 /*! The amount of space in out must be at least ( 2 * strlen(in) + 1 ) */
2673 static void json_escape(char *out, const char *in)
2676 if (*in == '\\' || *in == '\"') {
2686 * \brief Append a JSON escaped string to the manager stream.
2688 * \param s AMI stream to append a string.
2689 * \param str String to append to the stream after JSON escaping it.
2693 static void astman_append_json(struct mansession *s, const char *str)
2697 buf = ast_alloca(2 * strlen(str) + 1);
2698 json_escape(buf, str);
2699 astman_append(s, "%s", buf);
2702 static int action_getconfigjson(struct mansession *s, const struct message *m)
2704 struct ast_config *cfg;
2705 const char *fn = astman_get_header(m, "Filename");
2706 char *category = NULL;
2707 struct ast_variable *v;
2709 struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
2711 if (ast_strlen_zero(fn)) {
2712 astman_send_error(s, m, "Filename not specified");
2716 if (!(cfg = ast_config_load2(fn, "manager", config_flags))) {
2717 astman_send_error(s, m, "Config file not found");
2719 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
2720 astman_send_error(s, m, "Config file has invalid format");
2724 astman_start_ack(s, m);
2725 astman_append(s, "JSON: {");
2726 while ((category = ast_category_browse(cfg, category))) {
2729 astman_append(s, "%s\"", comma1 ? "," : "");
2730 astman_append_json(s, category);
2731 astman_append(s, "\":[");
2733 for (v = ast_variable_browse(cfg, category); v; v = v->next) {
2734 astman_append(s, "%s\"", comma2 ? "," : "");
2735 astman_append_json(s, v->name);
2736 astman_append(s, "\":\"");
2737 astman_append_json(s, v->value);
2738 astman_append(s, "\"");
2741 astman_append(s, "]");
2743 astman_append(s, "}\r\n\r\n");
2745 ast_config_destroy(cfg);
2750 /*! \brief helper function for action_updateconfig */
2751 static enum error_type handle_updates(struct mansession *s, const struct message *m, struct ast_config *cfg, const char *dfn)
2755 const char *action, *cat, *var, *value, *match, *line;
2756 struct ast_category *category;
2757 struct ast_variable *v;
2758 struct ast_str *str1 = ast_str_create(16), *str2 = ast_str_create(16);
2759 enum error_type result = 0;
2761 for (x = 0; x < 100000; x++) { /* 100000 = the max number of allowed updates + 1 */
2762 unsigned int object = 0;
2764 snprintf(hdr, sizeof(hdr), "Action-%06d", x);
2765 action = astman_get_header(m, hdr);
2766 if (ast_strlen_zero(action)) /* breaks the for loop if no action header */
2767 break; /* this could cause problems if actions come in misnumbered */
2769 snprintf(hdr, sizeof(hdr), "Cat-%06d", x);
2770 cat = astman_get_header(m, hdr);
2771 if (ast_strlen_zero(cat)) { /* every action needs a category */
2772 result = UNSPECIFIED_CATEGORY;
2776 snprintf(hdr, sizeof(hdr), "Var-%06d", x);
2777 var = astman_get_header(m, hdr);
2779 snprintf(hdr, sizeof(hdr), "Value-%06d", x);
2780 value = astman_get_header(m, hdr);
2782 if (!ast_strlen_zero(value) && *value == '>') {
2787 snprintf(hdr, sizeof(hdr), "Match-%06d", x);
2788 match = astman_get_header(m, hdr);
2790 snprintf(hdr, sizeof(hdr), "Line-%06d", x);
2791 line = astman_get_header(m, hdr);
2793 if (!strcasecmp(action, "newcat")) {
2794 if (ast_category_get(cfg,cat)) { /* check to make sure the cat doesn't */
2795 result = FAILURE_NEWCAT; /* already exist */
2798 if (!(category = ast_category_new(cat, dfn, -1))) {
2799 result = FAILURE_ALLOCATION;
2802 if (ast_strlen_zero(match)) {
2803 ast_category_append(cfg, category);
2805 ast_category_insert(cfg, category, match);
2807 } else if (!strcasecmp(action, "renamecat")) {
2808 if (ast_strlen_zero(value)) {
2809 result = UNSPECIFIED_ARGUMENT;
2812 if (!(category = ast_category_get(cfg, cat))) {
2813 result = UNKNOWN_CATEGORY;
2816 ast_category_rename(category, value);
2817 } else if (!strcasecmp(action, "delcat")) {
2818 if (ast_category_delete(cfg, cat)) {
2819 result = FAILURE_DELCAT;
2822 } else if (!strcasecmp(action, "emptycat")) {
2823 if (ast_category_empty(cfg, cat)) {
2824 result = FAILURE_EMPTYCAT;
2827 } else if (!strcasecmp(action, "update")) {
2828 if (ast_strlen_zero(var)) {
2829 result = UNSPECIFIED_ARGUMENT;
2832 if (!(category = ast_category_get(cfg,cat))) {
2833 result = UNKNOWN_CATEGORY;
2836 if (ast_variable_update(category, var, value, match, object)) {
2837 result = FAILURE_UPDATE;
2840 } else if (!strcasecmp(action, "delete")) {
2841 if ((ast_strlen_zero(var) && ast_strlen_zero(line))) {
2842 result = UNSPECIFIED_ARGUMENT;
2845 if (!(category = ast_category_get(cfg, cat))) {
2846 result = UNKNOWN_CATEGORY;
2849 if (ast_variable_delete(category, var, match, line)) {
2850 result = FAILURE_DELETE;
2853 } else if (!strcasecmp(action, "append")) {
2854 if (ast_strlen_zero(var)) {
2855 result = UNSPECIFIED_ARGUMENT;
2858 if (!(category = ast_category_get(cfg, cat))) {
2859 result = UNKNOWN_CATEGORY;
2862 if (!(v = ast_variable_new(var, value, dfn))) {
2863 result = FAILURE_ALLOCATION;
2866 if (object || (match && !strcasecmp(match, "object"))) {
2869 ast_variable_append(category, v);
2870 } else if (!strcasecmp(action, "insert")) {
2871 if (ast_strlen_zero(var) || ast_strlen_zero(line)) {
2872 result = UNSPECIFIED_ARGUMENT;
2875 if (!(category = ast_category_get(cfg, cat))) {
2876 result = UNKNOWN_CATEGORY;
2879 if (!(v = ast_variable_new(var, value, dfn))) {
2880 result = FAILURE_ALLOCATION;
2883 ast_variable_insert(category, v, line);
2886 ast_log(LOG_WARNING, "Action-%06d: %s not handled\n", x, action);
2887 result = UNKNOWN_ACTION;
2896 static int action_updateconfig(struct mansession *s, const struct message *m)
2898 struct ast_config *cfg;
2899 const char *sfn = astman_get_header(m, "SrcFilename");
2900 const char *dfn = astman_get_header(m, "DstFilename");
2902 const char *rld = astman_get_header(m, "Reload");
2903 struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
2904 enum error_type result;
2906 if (ast_strlen_zero(sfn) || ast_strlen_zero(dfn)) {
2907 astman_send_error(s, m, "Filename not specified");
2910 if (!(cfg = ast_config_load2(sfn, "manager", config_flags))) {
2911 astman_send_error(s, m, "Config file not found");
2913 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
2914 astman_send_error(s, m, "Config file has invalid format");
2917 result = handle_updates(s, m, cfg, dfn);
2919 ast_include_rename(cfg, sfn, dfn); /* change the include references from dfn to sfn, so things match up */
2920 res = ast_config_text_file_save(dfn, cfg, "Manager");
2921 ast_config_destroy(cfg);
2923 astman_send_error(s, m, "Save of config failed");
2926 astman_send_ack(s, m, NULL);
2927 if (!ast_strlen_zero(rld)) {
2928 if (ast_true(rld)) {
2931 ast_module_reload(rld);
2934 ast_config_destroy(cfg);
2936 case UNKNOWN_ACTION:
2937 astman_send_error(s, m, "Unknown action command");
2939 case UNKNOWN_CATEGORY:
2940 astman_send_error(s, m, "Given category does not exist");
2942 case UNSPECIFIED_CATEGORY:
2943 astman_send_error(s, m, "Category not specified");
2945 case UNSPECIFIED_ARGUMENT:
2946 astman_send_error(s, m, "Problem with category, value, or line (if required)");
2948 case FAILURE_ALLOCATION:
2949 astman_send_error(s, m, "Memory allocation failure, this should not happen");
2951 case FAILURE_NEWCAT:
2952 astman_send_error(s, m, "Create category did not complete successfully");
2954 case FAILURE_DELCAT:
2955 astman_send_error(s, m, "Delete category did not complete successfully");
2957 case FAILURE_EMPTYCAT:
2958 astman_send_error(s, m, "Empty category did not complete successfully");
2960 case FAILURE_UPDATE:
2961 astman_send_error(s, m, "Update did not complete successfully");
2963 case FAILURE_DELETE:
2964 astman_send_error(s, m, "Delete did not complete successfully");
2966 case FAILURE_APPEND:
2967 astman_send_error(s, m, "Append did not complete successfully");
2974 static int action_createconfig(struct mansession *s, const struct message *m)
2977 const char *fn = astman_get_header(m, "Filename");
2978 struct ast_str *filepath = ast_str_alloca(PATH_MAX);
2979 ast_str_set(&filepath, 0, "%s/", ast_config_AST_CONFIG_DIR);
2980 ast_str_append(&filepath, 0, "%s", fn);
2982 if ((fd = open(ast_str_buffer(filepath), O_CREAT | O_EXCL, AST_FILE_MODE)) != -1) {
2984 astman_send_ack(s, m, "New configuration file created successfully");
2986 astman_send_error(s, m, strerror(errno));
2992 static int action_waitevent(struct mansession *s, const struct message *m)
2994 const char *timeouts = astman_get_header(m, "Timeout");
2998 const char *id = astman_get_header(m, "ActionID");
3001 if (!ast_strlen_zero(id)) {
3002 snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
3007 if (!ast_strlen_zero(timeouts)) {
3008 sscanf(timeouts, "%30i", &timeout);
3012 /* XXX maybe put an upper bound, or prevent the use of 0 ? */
3015 ao2_lock(s->session);
3016 if (s->session->waiting_thread != AST_PTHREADT_NULL) {
3017 pthread_kill(s->session->waiting_thread, SIGURG);
3020 if (s->session->managerid) { /* AMI-over-HTTP session */
3022 * Make sure the timeout is within the expire time of the session,
3023 * as the client will likely abort the request if it does not see
3024 * data coming after some amount of time.
3026 time_t now = time(NULL);
3027 int max = s->session->sessiontimeout - now - 10;
3029 if (max < 0) { /* We are already late. Strange but possible. */
3032 if (timeout < 0 || timeout > max) {
3035 if (!s->session->send_events) { /* make sure we record events */
3036 s->session->send_events = -1;
3039 ao2_unlock(s->session);
3041 /* XXX should this go inside the lock ? */
3042 s->session->waiting_thread = pthread_self(); /* let new events wake up this thread */
3043 ast_debug(1, "Starting waiting for an event!\n");
3045 for (x = 0; x < timeout || timeout < 0; x++) {
3046 ao2_lock(s->session);
3047 if (AST_RWLIST_NEXT(s->session->last_ev, eq_next)) {
3050 /* We can have multiple HTTP session point to the same mansession entry.
3051 * The way we deal with it is not very nice: newcomers kick out the previous
3052 * HTTP session. XXX this needs to be improved.
3054 if (s->session->waiting_thread != pthread_self()) {
3057 if (s->session->needdestroy) {
3060 ao2_unlock(s->session);
3064 if (s->session->managerid == 0) { /* AMI session */
3065 if (ast_wait_for_input(s->session->fd, 1000)) {
3068 } else { /* HTTP session */
3072 ast_debug(1, "Finished waiting for an event!\n");
3074 ao2_lock(s->session);
3075 if (s->session->waiting_thread == pthread_self()) {
3076 struct eventqent *eqe = s->session->last_ev;
3077 astman_send_response(s, m, "Success", "Waiting for Event completed.");
3078 while ((eqe = advance_event(eqe))) {
3079 if (((s->session->readperm & eqe->category) == eqe->category) &&
3080 ((s->session->send_events & eqe->category) == eqe->category)) {
3081 astman_append(s, "%s", eqe->eventdata);
3083 s->session->last_ev = eqe;
3086 "Event: WaitEventComplete\r\n"
3089 s->session->waiting_thread = AST_PTHREADT_NULL;
3091 ast_debug(1, "Abandoning event request!\n");
3093 ao2_unlock(s->session);
3098 static int action_listcommands(struct mansession *s, const struct message *m)
3100 struct manager_action *cur;
3101 struct ast_str *temp = ast_str_alloca(256);
3103 astman_start_ack(s, m);
3104 AST_RWLIST_RDLOCK(&actions);
3105 AST_RWLIST_TRAVERSE(&actions, cur, list) {
3106 if ((s->session->writeperm & cur->authority) || cur->authority == 0) {
3107 astman_append(s, "%s: %s (Priv: %s)\r\n",
3108 cur->action, cur->synopsis, authority_to_str(cur->authority, &temp));
3111 AST_RWLIST_UNLOCK(&actions);
3112 astman_append(s, "\r\n");
3117 static int action_events(struct mansession *s, const struct message *m)
3119 const char *mask = astman_get_header(m, "EventMask");
3121 const char *id = astman_get_header(m, "ActionID");
3124 if (!ast_strlen_zero(id)) {
3125 snprintf(id_text, sizeof(id_text), "ActionID: %s\r\n", id);
3130 res = set_eventmask(s, mask);
3131 if (broken_events_action) {
3132 /* if this option is set we should not return a response on
3133 * error, or when all events are set */
3136 for (x = 0; x < ARRAY_LEN(perms); x++) {
3137 if (!strcasecmp(perms[x].label, "all") && res == perms[x].num) {
3141 astman_append(s, "Response: Success\r\n%s"
3142 "Events: On\r\n\r\n", id_text);
3143 } else if (res == 0)
3144 astman_append(s, "Response: Success\r\n%s"
3145 "Events: Off\r\n\r\n", id_text);
3150 astman_append(s, "Response: Success\r\n%s"
3151 "Events: On\r\n\r\n", id_text);
3153 astman_append(s, "Response: Success\r\n%s"
3154 "Events: Off\r\n\r\n", id_text);
3156 astman_send_error(s, m, "Invalid event mask");
3161 static int action_logoff(struct mansession *s, const struct message *m)
3163 astman_send_response(s, m, "Goodbye", "Thanks for all the fish.");
3167 static int action_login(struct mansession *s, const struct message *m)
3170 /* still authenticated - don't process again */
3171 if (s->session->authenticated) {
3172 astman_send_ack(s, m, "Already authenticated");
3176 if (authenticate(s, m)) {
3178 astman_send_error(s, m, "Authentication failed");
3181 s->session->authenticated = 1;
3182 ast_atomic_fetchadd_int(&unauth_sessions, -1);
3183 if (manager_displayconnects(s->session)) {
3184 ast_verb(2, "%sManager '%s' logged on from %s\n", (s->session->managerid ? "HTTP " : ""), s->session->username, ast_sockaddr_stringify_addr(&s->session->addr));
3186 astman_send_ack(s, m, "Authentication accepted");
3187 if ((s->session->send_events & EVENT_FLAG_SYSTEM)
3188 && ast_test_flag(&ast_options, AST_OPT_FLAG_FULLY_BOOTED)) {
3189 struct ast_str *auth = ast_str_alloca(80);
3190 const char *cat_str = authority_to_str(EVENT_FLAG_SYSTEM, &auth);
3191 astman_append(s, "Event: FullyBooted\r\n"
3193 "Status: Fully Booted\r\n\r\n", cat_str);
3198 static int action_challenge(struct mansession *s, const struct message *m)
3200 const char *authtype = astman_get_header(m, "AuthType");
3202 if (!strcasecmp(authtype, "MD5")) {
3203 if (ast_strlen_zero(s->session->challenge)) {
3204 snprintf(s->session->challenge, sizeof(s->session->challenge), "%ld", ast_random());
3207 astman_start_ack(s, m);
3208 astman_append(s, "Challenge: %s\r\n\r\n", s->session->challenge);
3209 mansession_unlock(s);
3211 astman_send_error(s, m, "Must specify AuthType");
3216 static int action_hangup(struct mansession *s, const struct message *m)
3218 struct ast_channel *c = NULL;
3219 int causecode = 0; /* all values <= 0 mean 'do not set hangupcause in channel' */
3220 const char *id = astman_get_header(m, "ActionID");
3221 const char *name_or_regex = astman_get_header(m, "Channel");
3222 const char *cause = astman_get_header(m, "Cause");
3225 struct ast_channel_iterator *iter = NULL;
3226 struct ast_str *regex_string;
3227 int channels_matched = 0;
3229 if (ast_strlen_zero(name_or_regex)) {
3230 astman_send_error(s, m, "No channel specified");
3234 if (!ast_strlen_zero(id)) {
3235 snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
3240 if (!ast_strlen_zero(cause)) {
3242 causecode = strtol(cause, &endptr, 10);
3243 if (causecode < 0 || causecode > 127 || *endptr != '\0') {
3244 ast_log(LOG_NOTICE, "Invalid 'Cause: %s' in manager action Hangup\n", cause);
3245 /* keep going, better to hangup without cause than to not hang up at all */
3246 causecode = 0; /* do not set channel's hangupcause */
3250 /************************************************/
3251 /* Regular explicit match channel byname hangup */
3253 if (name_or_regex[0] != '/') {
3254 if (!(c = ast_channel_get_by_name(name_or_regex))) {
3255 ast_log(LOG_NOTICE, "!!!!!!!!!! Can't find channel to hang up!\n");
3256 astman_send_error(s, m, "No such channel");
3260 ast_verb(3, "%sManager '%s' from %s, hanging up channel: %s\n",
3261 (s->session->managerid ? "HTTP " : ""),
3262 s->session->username,
3263 ast_sockaddr_stringify_addr(&s->session->addr),
3264 ast_channel_name(c));
3266 ast_channel_softhangup_withcause_locked(c, causecode);
3267 c = ast_channel_unref(c);
3269 astman_send_ack(s, m, "Channel Hungup");
3274 /***********************************************/
3275 /* find and hangup any channels matching regex */
3277 regex_string = ast_str_create(strlen(name_or_regex));
3278 if (!regex_string) {
3279 astman_send_error(s, m, "Memory Allocation Failure");
3283 /* Make "/regex/" into "regex" */
3284 if (ast_regex_string_to_regex_pattern(name_or_regex, ®ex_string) != 0) {
3285 astman_send_error(s, m, "Regex format invalid, Channel param should be /regex/");
3286 ast_free(regex_string);
3290 /* if regex compilation fails, hangup fails */
3291 if (regcomp(®exbuf, ast_str_buffer(regex_string), REG_EXTENDED | REG_NOSUB)) {
3292 astman_send_error_va(s, m, "Regex compile failed on: %s\n", name_or_regex);
3293 ast_free(regex_string);
3297 astman_send_listack(s, m, "Channels hung up will follow", "start");
3299 iter = ast_channel_iterator_all_new();
3301 for (; (c = ast_channel_iterator_next(iter)); ast_channel_unref(c)) {
3302 if (regexec(®exbuf, ast_channel_name(c), 0, NULL, 0)) {
3306 ast_verb(3, "%sManager '%s' from %s, hanging up channel: %s\n",
3307 (s->session->managerid ? "HTTP " : ""),
3308 s->session->username,
3309 ast_sockaddr_stringify_addr(&s->session->addr),
3310 ast_channel_name(c));
3312 ast_channel_softhangup_withcause_locked(c, causecode);
3316 "Event: ChannelHungup\r\n"
3319 "\r\n", ast_channel_name(c), idText);
3321 ast_channel_iterator_destroy(iter);
3325 ast_free(regex_string);
3328 "Event: ChannelsHungupListComplete\r\n"
3329 "EventList: Complete\r\n"
3332 "\r\n", channels_matched, idText);
3337 static int action_setvar(struct mansession *s, const struct message *m)
3339 struct ast_channel *c = NULL;
3340 const char *name = astman_get_header(m, "Channel");
3341 const char *varname = astman_get_header(m, "Variable");
3342 const char *varval = astman_get_header(m, "Value");
3345 if (ast_strlen_zero(varname)) {
3346 astman_send_error(s, m, "No variable specified");
3350 if (!ast_strlen_zero(name)) {
3351 if (!(c = ast_channel_get_by_name(name))) {
3352 astman_send_error(s, m, "No such channel");
3357 res = pbx_builtin_setvar_helper(c, varname, S_OR(varval, ""));
3360 c = ast_channel_unref(c);
3363 astman_send_ack(s, m, "Variable Set");
3365 astman_send_error(s, m, "Variable not set");
3370 static int action_getvar(struct mansession *s, const struct message *m)
3372 struct ast_channel *c = NULL;
3373 const char *name = astman_get_header(m, "Channel");
3374 const char *varname = astman_get_header(m, "Variable");
3376 char workspace[1024];
3378 if (ast_strlen_zero(varname)) {
3379 astman_send_error(s, m, "No variable specified");
3383 /* We don't want users with insufficient permissions using certain functions. */
3384 if (!(function_capable_string_allowed_with_auths(varname, s->session->writeperm))) {
3385 astman_send_error(s, m, "GetVar Access Forbidden: Variable");
3389 if (!ast_strlen_zero(name)) {
3390 if (!(c = ast_channel_get_by_name(name))) {
3391 astman_send_error(s, m, "No such channel");
3396 workspace[0] = '\0';
3397 if (varname[strlen(varname) - 1] == ')') {
3399 c = ast_dummy_channel_alloc();
3401 ast_func_read(c, (char *) varname, workspace, sizeof(workspace));
3403 ast_log(LOG_ERROR, "Unable to allocate bogus channel for variable substitution. Function results may be blank.\n");
3405 ast_func_read(c, (char *) varname, workspace, sizeof(workspace));
3409 pbx_retrieve_variable(c, varname, &varval, workspace, sizeof(workspace), NULL);
3413 c = ast_channel_unref(c);
3416 astman_start_ack(s, m);
3417 astman_append(s, "Variable: %s\r\nValue: %s\r\n\r\n", varname, S_OR(varval, ""));
3422 /*! \brief Manager "status" command to show channels */
3423 /* Needs documentation... */
3424 static int action_status(struct mansession *s, const struct message *m)
3426 const char *name = astman_get_header(m, "Channel");
3427 const char *cvariables = astman_get_header(m, "Variables");
3428 char *variables = ast_strdupa(S_OR(cvariables, ""));
3429 struct ast_channel *c;
3431 struct timeval now = ast_tvnow();
3432 long elapsed_seconds = 0;
3434 int all = ast_strlen_zero(name); /* set if we want all channels */
3435 const char *id = astman_get_header(m, "ActionID");
3437 AST_DECLARE_APP_ARGS(vars,
3438 AST_APP_ARG(name)[100];
3440 struct ast_str *str = ast_str_create(1000);
3441 struct ast_channel_iterator *iter = NULL;
3443 if (!ast_strlen_zero(id)) {
3444 snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
3449 if (!(function_capable_string_allowed_with_auths(variables, s->session->writeperm))) {
3450 astman_send_error(s, m, "Status Access Forbidden: Variables");
3455 if (!(iter = ast_channel_iterator_all_new())) {
3457 astman_send_error(s, m, "Memory Allocation Failure");
3460 c = ast_channel_iterator_next(iter);
3462 if (!(c = ast_channel_get_by_name(name))) {
3463 astman_send_error(s, m, "No such channel");
3469 astman_send_ack(s, m, "Channel status will follow");
3471 if (!ast_strlen_zero(cvariables)) {
3472 AST_STANDARD_APP_ARGS(vars, variables);
3475 /* if we look by name, we break after the first iteration */
3476 for (; c; c = ast_channel_iterator_next(iter)) {
3477 ast_channel_lock(c);
3479 if (!ast_strlen_zero(cvariables)) {
3482 for (i = 0; i < vars.argc; i++) {
3483 char valbuf[512], *ret = NULL;
3485 if (vars.name[i][strlen(vars.name[i]) - 1] == ')') {
3486 if (ast_func_read(c, vars.name[i], valbuf, sizeof(valbuf)) < 0) {
3491 pbx_retrieve_variable(c, vars.name[i], &ret, valbuf, sizeof(valbuf), NULL);