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/aoc.h"
84 #include "asterisk/stringfields.h"
85 #include "asterisk/presencestate.h"
88 <manager name="Ping" language="en_US">
93 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
96 <para>A 'Ping' action will ellicit a 'Pong' response. Used to keep the
97 manager connection open.</para>
100 <manager name="Events" language="en_US">
105 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
106 <parameter name="EventMask" required="true">
109 <para>If all events should be sent.</para>
112 <para>If no events should be sent.</para>
114 <enum name="system,call,log,...">
115 <para>To select which flags events should have to be sent.</para>
121 <para>Enable/Disable sending of events to this manager client.</para>
124 <manager name="Logoff" language="en_US">
129 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
132 <para>Logoff the current manager session.</para>
135 <manager name="Login" language="en_US">
140 <parameter name="ActionID">
141 <para>ActionID for this transaction. Will be returned.</para>
143 <parameter name="Username" required="true">
144 <para>Username to login with as specified in manager.conf.</para>
146 <parameter name="Secret">
147 <para>Secret to login with as specified in manager.conf.</para>
151 <para>Login Manager.</para>
154 <manager name="Challenge" language="en_US">
156 Generate Challenge for MD5 Auth.
159 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
160 <parameter name="AuthType" required="true">
161 <para>Digest algorithm to use in the challenge. Valid values are:</para>
168 <para>Generate a challenge for MD5 authentication.</para>
171 <manager name="Hangup" language="en_US">
176 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
177 <parameter name="Channel" required="true">
178 <para>The exact channel name to be hungup, or to use a regular expression, set this parameter to: /regex/</para>
179 <para>Example exact channel: SIP/provider-0000012a</para>
180 <para>Example regular expression: /^SIP/provider-.*$/</para>
182 <parameter name="Cause">
183 <para>Numeric hangup cause.</para>
187 <para>Hangup a channel.</para>
190 <manager name="Status" language="en_US">
195 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
196 <parameter name="Channel" required="true">
197 <para>The name of the channel to query for status.</para>
199 <parameter name="Variables">
200 <para>Comma <literal>,</literal> separated list of variable to include.</para>
204 <para>Will return the status information of each channel along with the
205 value for the specified channel variables.</para>
208 <manager name="Setvar" language="en_US">
210 Set a channel variable.
213 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
214 <parameter name="Channel">
215 <para>Channel to set variable for.</para>
217 <parameter name="Variable" required="true">
218 <para>Variable name.</para>
220 <parameter name="Value" required="true">
221 <para>Variable value.</para>
225 <para>Set a global or local channel variable.</para>
227 <para>If a channel name is not provided then the variable is global.</para>
231 <manager name="Getvar" language="en_US">
233 Gets a channel variable.
236 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
237 <parameter name="Channel">
238 <para>Channel to read variable from.</para>
240 <parameter name="Variable" required="true">
241 <para>Variable name.</para>
245 <para>Get the value of a global or local channel variable.</para>
247 <para>If a channel name is not provided then the variable is global.</para>
251 <manager name="GetConfig" language="en_US">
253 Retrieve configuration.
256 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
257 <parameter name="Filename" required="true">
258 <para>Configuration filename (e.g. <filename>foo.conf</filename>).</para>
260 <parameter name="Category">
261 <para>Category in configuration file.</para>
265 <para>This action will dump the contents of a configuration
266 file by category and contents or optionally by specified category only.</para>
269 <manager name="GetConfigJSON" language="en_US">
271 Retrieve configuration (JSON format).
274 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
275 <parameter name="Filename" required="true">
276 <para>Configuration filename (e.g. <filename>foo.conf</filename>).</para>
280 <para>This action will dump the contents of a configuration file by category
281 and contents in JSON format. This only makes sense to be used using rawman over
282 the HTTP interface.</para>
285 <manager name="UpdateConfig" language="en_US">
287 Update basic configuration.
290 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
291 <parameter name="SrcFilename" required="true">
292 <para>Configuration filename to read (e.g. <filename>foo.conf</filename>).</para>
294 <parameter name="DstFilename" required="true">
295 <para>Configuration filename to write (e.g. <filename>foo.conf</filename>)</para>
297 <parameter name="Reload">
298 <para>Whether or not a reload should take place (or name of specific module).</para>
300 <parameter name="Action-XXXXXX">
301 <para>Action to take.</para>
302 <para>X's represent 6 digit number beginning with 000000.</para>
304 <enum name="NewCat" />
305 <enum name="RenameCat" />
306 <enum name="DelCat" />
307 <enum name="EmptyCat" />
308 <enum name="Update" />
309 <enum name="Delete" />
310 <enum name="Append" />
311 <enum name="Insert" />
314 <parameter name="Cat-XXXXXX">
315 <para>Category to operate on.</para>
316 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-XXXXXX']/para[2])" />
318 <parameter name="Var-XXXXXX">
319 <para>Variable to work on.</para>
320 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-XXXXXX']/para[2])" />
322 <parameter name="Value-XXXXXX">
323 <para>Value to work on.</para>
324 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-XXXXXX']/para[2])" />
326 <parameter name="Match-XXXXXX">
327 <para>Extra match required to match line.</para>
328 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-XXXXXX']/para[2])" />
330 <parameter name="Line-XXXXXX">
331 <para>Line in category to operate on (used with delete and insert actions).</para>
332 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-XXXXXX']/para[2])" />
336 <para>This action will modify, create, or delete configuration elements
337 in Asterisk configuration files.</para>
340 <manager name="CreateConfig" language="en_US">
342 Creates an empty file in the configuration directory.
345 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
346 <parameter name="Filename" required="true">
347 <para>The configuration filename to create (e.g. <filename>foo.conf</filename>).</para>
351 <para>This action will create an empty file in the configuration
352 directory. This action is intended to be used before an UpdateConfig
356 <manager name="ListCategories" language="en_US">
358 List categories in configuration file.
361 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
362 <parameter name="Filename" required="true">
363 <para>Configuration filename (e.g. <filename>foo.conf</filename>).</para>
367 <para>This action will dump the categories in a given file.</para>
370 <manager name="Redirect" language="en_US">
372 Redirect (transfer) a call.
375 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
376 <parameter name="Channel" required="true">
377 <para>Channel to redirect.</para>
379 <parameter name="ExtraChannel">
380 <para>Second call leg to transfer (optional).</para>
382 <parameter name="Exten" required="true">
383 <para>Extension to transfer to.</para>
385 <parameter name="ExtraExten">
386 <para>Extension to transfer extrachannel to (optional).</para>
388 <parameter name="Context" required="true">
389 <para>Context to transfer to.</para>
391 <parameter name="ExtraContext">
392 <para>Context to transfer extrachannel to (optional).</para>
394 <parameter name="Priority" required="true">
395 <para>Priority to transfer to.</para>
397 <parameter name="ExtraPriority">
398 <para>Priority to transfer extrachannel to (optional).</para>
402 <para>Redirect (transfer) a call.</para>
405 <manager name="Atxfer" language="en_US">
410 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
411 <parameter name="Channel" required="true">
412 <para>Transferer's channel.</para>
414 <parameter name="Exten" required="true">
415 <para>Extension to transfer to.</para>
417 <parameter name="Context" required="true">
418 <para>Context to transfer to.</para>
420 <parameter name="Priority" required="true">
421 <para>Priority to transfer to.</para>
425 <para>Attended transfer.</para>
428 <manager name="Originate" language="en_US">
433 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
434 <parameter name="Channel" required="true">
435 <para>Channel name to call.</para>
437 <parameter name="Exten">
438 <para>Extension to use (requires <literal>Context</literal> and
439 <literal>Priority</literal>)</para>
441 <parameter name="Context">
442 <para>Context to use (requires <literal>Exten</literal> and
443 <literal>Priority</literal>)</para>
445 <parameter name="Priority">
446 <para>Priority to use (requires <literal>Exten</literal> and
447 <literal>Context</literal>)</para>
449 <parameter name="Application">
450 <para>Application to execute.</para>
452 <parameter name="Data">
453 <para>Data to use (requires <literal>Application</literal>).</para>
455 <parameter name="Timeout" default="30000">
456 <para>How long to wait for call to be answered (in ms.).</para>
458 <parameter name="CallerID">
459 <para>Caller ID to be set on the outgoing channel.</para>
461 <parameter name="Variable">
462 <para>Channel variable to set, multiple Variable: headers are allowed.</para>
464 <parameter name="Account">
465 <para>Account code.</para>
467 <parameter name="Async">
468 <para>Set to <literal>true</literal> for fast origination.</para>
470 <parameter name="Codecs">
471 <para>Comma-separated list of codecs to use for this call.</para>
475 <para>Generates an outgoing call to a
476 <replaceable>Extension</replaceable>/<replaceable>Context</replaceable>/<replaceable>Priority</replaceable>
477 or <replaceable>Application</replaceable>/<replaceable>Data</replaceable></para>
480 <manager name="Command" language="en_US">
482 Execute Asterisk CLI Command.
485 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
486 <parameter name="Command" required="true">
487 <para>Asterisk CLI command to run.</para>
491 <para>Run a CLI command.</para>
494 <manager name="ExtensionState" language="en_US">
496 Check Extension Status.
499 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
500 <parameter name="Exten" required="true">
501 <para>Extension to check state on.</para>
503 <parameter name="Context" required="true">
504 <para>Context for extension.</para>
508 <para>Report the extension state for given extension. If the extension has a hint,
509 will use devicestate to check the status of the device connected to the extension.</para>
510 <para>Will return an <literal>Extension Status</literal> message. The response will include
511 the hint for the extension and the status.</para>
514 <manager name="PresenceState" language="en_US">
519 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
520 <parameter name="Provider" required="true">
521 <para>Presence Provider to check the state of</para>
525 <para>Report the presence state for the given presence provider.</para>
526 <para>Will return a <literal>Presence State</literal> message. The response will include the
527 presence state and, if set, a presence subtype and custom message.</para>
530 <manager name="AbsoluteTimeout" language="en_US">
532 Set absolute timeout.
535 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
536 <parameter name="Channel" required="true">
537 <para>Channel name to hangup.</para>
539 <parameter name="Timeout" required="true">
540 <para>Maximum duration of the call (sec).</para>
544 <para>Hangup a channel after a certain time. Acknowledges set time with
545 <literal>Timeout Set</literal> message.</para>
548 <manager name="MailboxStatus" language="en_US">
553 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
554 <parameter name="Mailbox" required="true">
555 <para>Full mailbox ID <replaceable>mailbox</replaceable>@<replaceable>vm-context</replaceable>.</para>
559 <para>Checks a voicemail account for status.</para>
560 <para>Returns number of messages.</para>
561 <para>Message: Mailbox Status.</para>
562 <para>Mailbox: <replaceable>mailboxid</replaceable>.</para>
563 <para>Waiting: <replaceable>count</replaceable>.</para>
566 <manager name="MailboxCount" language="en_US">
568 Check Mailbox Message Count.
571 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
572 <parameter name="Mailbox" required="true">
573 <para>Full mailbox ID <replaceable>mailbox</replaceable>@<replaceable>vm-context</replaceable>.</para>
577 <para>Checks a voicemail account for new messages.</para>
578 <para>Returns number of urgent, new and old messages.</para>
579 <para>Message: Mailbox Message Count</para>
580 <para>Mailbox: <replaceable>mailboxid</replaceable></para>
581 <para>UrgentMessages: <replaceable>count</replaceable></para>
582 <para>NewMessages: <replaceable>count</replaceable></para>
583 <para>OldMessages: <replaceable>count</replaceable></para>
586 <manager name="ListCommands" language="en_US">
588 List available manager commands.
591 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
594 <para>Returns the action name and synopsis for every action that
595 is available to the user.</para>
598 <manager name="SendText" language="en_US">
600 Send text message to channel.
603 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
604 <parameter name="Channel" required="true">
605 <para>Channel to send message to.</para>
607 <parameter name="Message" required="true">
608 <para>Message to send.</para>
612 <para>Sends A Text Message to a channel while in a call.</para>
615 <manager name="UserEvent" language="en_US">
617 Send an arbitrary event.
620 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
621 <parameter name="UserEvent" required="true">
622 <para>Event string to send.</para>
624 <parameter name="Header1">
625 <para>Content1.</para>
627 <parameter name="HeaderN">
628 <para>ContentN.</para>
632 <para>Send an event to manager sessions.</para>
635 <manager name="WaitEvent" language="en_US">
637 Wait for an event to occur.
640 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
641 <parameter name="Timeout" required="true">
642 <para>Maximum time (in seconds) to wait for events, <literal>-1</literal> means forever.</para>
646 <para>This action will ellicit a <literal>Success</literal> response. Whenever
647 a manager event is queued. Once WaitEvent has been called on an HTTP manager
648 session, events will be generated and queued.</para>
651 <manager name="CoreSettings" language="en_US">
653 Show PBX core settings (version etc).
656 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
659 <para>Query for Core PBX settings.</para>
662 <manager name="CoreStatus" language="en_US">
664 Show PBX core status variables.
667 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
670 <para>Query for Core PBX status.</para>
673 <manager name="Reload" language="en_US">
678 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
679 <parameter name="Module">
680 <para>Name of the module to reload.</para>
684 <para>Send a reload event.</para>
687 <manager name="CoreShowChannels" language="en_US">
689 List currently active channels.
692 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
695 <para>List currently defined channels and some information about them.</para>
698 <manager name="ModuleLoad" language="en_US">
703 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
704 <parameter name="Module">
705 <para>Asterisk module name (including .so extension) or subsystem identifier:</para>
709 <enum name="dnsmgr" />
710 <enum name="extconfig" />
711 <enum name="manager" />
716 <parameter name="LoadType" required="true">
717 <para>The operation to be done on module.</para>
720 <enum name="unload" />
721 <enum name="reload" />
723 <para>If no module is specified for a <literal>reload</literal> loadtype,
724 all modules are reloaded.</para>
728 <para>Loads, unloads or reloads an Asterisk module in a running system.</para>
731 <manager name="ModuleCheck" language="en_US">
733 Check if module is loaded.
736 <parameter name="Module" required="true">
737 <para>Asterisk module name (not including extension).</para>
741 <para>Checks if Asterisk module is loaded. Will return Success/Failure.
742 For success returns, the module revision number is included.</para>
745 <manager name="AOCMessage" language="en_US">
747 Generate an Advice of Charge message on a channel.
750 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
751 <parameter name="Channel" required="true">
752 <para>Channel name to generate the AOC message on.</para>
754 <parameter name="ChannelPrefix">
755 <para>Partial channel prefix. By using this option one can match the beginning part
756 of a channel name without having to put the entire name in. For example
757 if a channel name is SIP/snom-00000001 and this value is set to SIP/snom, then
758 that channel matches and the message will be sent. Note however that only
759 the first matched channel has the message sent on it. </para>
761 <parameter name="MsgType" required="true">
762 <para>Defines what type of AOC message to create, AOC-D or AOC-E</para>
768 <parameter name="ChargeType" required="true">
769 <para>Defines what kind of charge this message represents.</para>
773 <enum name="Currency" />
777 <parameter name="UnitAmount(0)">
778 <para>This represents the amount of units charged. The ETSI AOC standard specifies that
779 this value along with the optional UnitType value are entries in a list. To accommodate this
780 these values take an index value starting at 0 which can be used to generate this list of
781 unit entries. For Example, If two unit entires were required this could be achieved by setting the
782 paramter UnitAmount(0)=1234 and UnitAmount(1)=5678. Note that UnitAmount at index 0 is
783 required when ChargeType=Unit, all other entries in the list are optional.
786 <parameter name="UnitType(0)">
787 <para>Defines the type of unit. ETSI AOC standard specifies this as an integer
788 value between 1 and 16, but this value is left open to accept any positive
789 integer. Like the UnitAmount parameter, this value represents a list entry
790 and has an index parameter that starts at 0.
793 <parameter name="CurrencyName">
794 <para>Specifies the currency's name. Note that this value is truncated after 10 characters.</para>
796 <parameter name="CurrencyAmount">
797 <para>Specifies the charge unit amount as a positive integer. This value is required
798 when ChargeType==Currency.</para>
800 <parameter name="CurrencyMultiplier">
801 <para>Specifies the currency multiplier. This value is required when ChargeType==Currency.</para>
803 <enum name="OneThousandth" />
804 <enum name="OneHundredth" />
805 <enum name="OneTenth" />
808 <enum name="Hundred" />
809 <enum name="Thousand" />
812 <parameter name="TotalType" default="Total">
813 <para>Defines what kind of AOC-D total is represented.</para>
815 <enum name="Total" />
816 <enum name="SubTotal" />
819 <parameter name="AOCBillingId">
820 <para>Represents a billing ID associated with an AOC-D or AOC-E message. Note
821 that only the first 3 items of the enum are valid AOC-D billing IDs</para>
823 <enum name="Normal" />
824 <enum name="ReverseCharge" />
825 <enum name="CreditCard" />
826 <enum name="CallFwdUnconditional" />
827 <enum name="CallFwdBusy" />
828 <enum name="CallFwdNoReply" />
829 <enum name="CallDeflection" />
830 <enum name="CallTransfer" />
833 <parameter name="ChargingAssociationId">
834 <para>Charging association identifier. This is optional for AOC-E and can be
835 set to any value between -32768 and 32767</para>
837 <parameter name="ChargingAssociationNumber">
838 <para>Represents the charging association party number. This value is optional
841 <parameter name="ChargingAssociationPlan">
842 <para>Integer representing the charging plan associated with the ChargingAssociationNumber.
843 The value is bits 7 through 1 of the Q.931 octet containing the type-of-number and
844 numbering-plan-identification fields.</para>
848 <para>Generates an AOC-D or AOC-E message on a channel.</para>
851 <manager name="Filter" language="en_US">
853 Dynamically add filters for the current manager session.
856 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
857 <parameter name="Operation">
860 <para>Add a filter.</para>
864 <parameter name="Filter">
865 <para>Filters can be whitelist or blacklist</para>
866 <para>Example whitelist filter: "Event: Newchannel"</para>
867 <para>Example blacklist filter: "!Channel: DAHDI.*"</para>
868 <para>This filter option is used to whitelist or blacklist events per user to be
869 reported with regular expressions and are allowed if both the regex matches
870 and the user has read access as defined in manager.conf. Filters are assumed to be for whitelisting
871 unless preceeded by an exclamation point, which marks it as being black.
872 Evaluation of the filters is as follows:</para>
873 <para>- If no filters are configured all events are reported as normal.</para>
874 <para>- If there are white filters only: implied black all filter processed first, then white filters.</para>
875 <para>- If there are black filters only: implied white all filter processed first, then black filters.</para>
876 <para>- If there are both white and black filters: implied black all filter processed first, then white
877 filters, and lastly black filters.</para>
881 <para>The filters added are only used for the current session.
882 Once the connection is closed the filters are removed.</para>
883 <para>This comand requires the system permission because
884 this command can be used to create filters that may bypass
885 filters defined in manager.conf</para>
888 <manager name="FilterList" language="en_US">
890 Show current event filters for this session
893 <para>The filters displayed are for the current session. Only those filters defined in
894 manager.conf will be present upon starting a new session.</para>
902 UNSPECIFIED_CATEGORY,
903 UNSPECIFIED_ARGUMENT,
913 enum add_filter_result {
920 * Linked list of events.
921 * Global events are appended to the list by append_event().
922 * The usecount is the number of stored pointers to the element,
923 * excluding the list pointers. So an element that is only in
924 * the list has a usecount of 0, not 1.
926 * Clients have a pointer to the last event processed, and for each
927 * of these clients we track the usecount of the elements.
928 * If we have a pointer to an entry in the list, it is safe to navigate
929 * it forward because elements will not be deleted, but only appended.
930 * The worst that can happen is seeing the pointer still NULL.
932 * When the usecount of an element drops to 0, and the element is the
933 * first in the list, we can remove it. Removal is done within the
934 * main thread, which is woken up for the purpose.
936 * For simplicity of implementation, we make sure the list is never empty.
939 int usecount; /*!< # of clients who still need the event */
941 unsigned int seq; /*!< sequence number */
942 struct timeval tv; /*!< When event was allocated */
943 AST_RWLIST_ENTRY(eventqent) eq_next;
944 char eventdata[1]; /*!< really variable size, allocated by append_event() */
947 static AST_RWLIST_HEAD_STATIC(all_events, eventqent);
949 static int displayconnects = 1;
950 static int allowmultiplelogin = 1;
951 static int timestampevents;
952 static int httptimeout = 60;
953 static int broken_events_action = 0;
954 static int manager_enabled = 0;
955 static int webmanager_enabled = 0;
956 static int manager_debug = 0; /*!< enable some debugging code in the manager */
957 static int authtimeout;
958 static int authlimit;
959 static char *manager_channelvars;
961 #define DEFAULT_REALM "asterisk"
962 static char global_realm[MAXHOSTNAMELEN]; /*!< Default realm */
964 static int block_sockets;
965 static int unauth_sessions = 0;
969 * Descriptor for a manager session, either on the AMI socket or over HTTP.
972 * AMI session have managerid == 0; the entry is created upon a connect,
973 * and destroyed with the socket.
974 * HTTP sessions have managerid != 0, the value is used as a search key
975 * to lookup sessions (using the mansession_id cookie, or nonce key from
976 * Digest Authentication http header).
978 #define MAX_BLACKLIST_CMD_LEN 2
979 static const struct {
980 const char *words[AST_MAX_CMD_LEN];
981 } command_blacklist[] = {
982 {{ "module", "load", NULL }},
983 {{ "module", "unload", NULL }},
984 {{ "restart", "gracefully", NULL }},
987 /* In order to understand what the heck is going on with the
988 * mansession_session and mansession structs, we need to have a bit of a history
991 * In the beginning, there was the mansession. The mansession contained data that was
992 * intrinsic to a manager session, such as the time that it started, the name of the logged-in
993 * user, etc. In addition to these parameters were the f and fd parameters. For typical manager
994 * sessions, these were used to represent the TCP socket over which the AMI session was taking
995 * place. It makes perfect sense for these fields to be a part of the session-specific data since
996 * the session actually defines this information.
998 * Then came the HTTP AMI sessions. With these, the f and fd fields need to be opened and closed
999 * for every single action that occurs. Thus the f and fd fields aren't really specific to the session
1000 * but rather to the action that is being executed. Because a single session may execute many commands
1001 * at once, some sort of safety needed to be added in order to be sure that we did not end up with fd
1002 * leaks from one action overwriting the f and fd fields used by a previous action before the previous action
1003 * has had a chance to properly close its handles.
1005 * The initial idea to solve this was to use thread synchronization, but this prevented multiple actions
1006 * from being run at the same time in a single session. Some manager actions may block for a long time, thus
1007 * creating a large queue of actions to execute. In addition, this fix did not address the basic architectural
1008 * issue that for HTTP manager sessions, the f and fd variables are not really a part of the session, but are
1009 * part of the action instead.
1011 * The new idea was to create a structure on the stack for each HTTP Manager action. This structure would
1012 * contain the action-specific information, such as which file to write to. In order to maintain expectations
1013 * of action handlers and not have to change the public API of the manager code, we would need to name this
1014 * new stacked structure 'mansession' and contain within it the old mansession struct that we used to use.
1015 * We renamed the old mansession struct 'mansession_session' to hopefully convey that what is in this structure
1016 * is session-specific data. The structure that it is wrapped in, called a 'mansession' really contains action-specific
1019 struct mansession_session {
1020 /*! \todo XXX need to document which fields it is protecting */
1021 struct sockaddr_in sin; /*!< address we are connecting from */
1022 FILE *f; /*!< fdopen() on the underlying fd */
1023 int fd; /*!< descriptor used for output. Either the socket (AMI) or a temporary file (HTTP) */
1024 int inuse; /*!< number of HTTP sessions using this entry */
1025 int needdestroy; /*!< Whether an HTTP session should be destroyed */
1026 pthread_t waiting_thread; /*!< Sleeping thread using this descriptor */
1027 uint32_t managerid; /*!< Unique manager identifier, 0 for AMI sessions */
1028 time_t sessionstart; /*!< Session start time */
1029 struct timeval sessionstart_tv; /*!< Session start time */
1030 time_t sessiontimeout; /*!< Session timeout if HTTP */
1031 char username[80]; /*!< Logged in username */
1032 char challenge[10]; /*!< Authentication challenge */
1033 int authenticated; /*!< Authentication status */
1034 int readperm; /*!< Authorization for reading */
1035 int writeperm; /*!< Authorization for writing */
1036 char inbuf[1025]; /*!< Buffer - we use the extra byte to add a '\0' and simplify parsing */
1037 int inlen; /*!< number of buffered bytes */
1038 struct ao2_container *whitefilters; /*!< Manager event filters - white list */
1039 struct ao2_container *blackfilters; /*!< Manager event filters - black list */
1040 int send_events; /*!< XXX what ? */
1041 struct eventqent *last_ev; /*!< last event processed. */
1042 int writetimeout; /*!< Timeout for ast_carefulwrite() */
1044 int pending_event; /*!< Pending events indicator in case when waiting_thread is NULL */
1045 time_t noncetime; /*!< Timer for nonce value expiration */
1046 unsigned long oldnonce; /*!< Stale nonce value */
1047 unsigned long nc; /*!< incremental nonce counter */
1048 AST_LIST_HEAD_NOLOCK(mansession_datastores, ast_datastore) datastores; /*!< Data stores on the session */
1049 AST_LIST_ENTRY(mansession_session) list;
1052 /*! \brief In case you didn't read that giant block of text above the mansession_session struct, the
1053 * \ref struct mansession is named this solely to keep the API the same in Asterisk. This structure really
1054 * represents data that is different from Manager action to Manager action. The mansession_session pointer
1055 * contained within points to session-specific data.
1058 struct mansession_session *session;
1059 struct ast_tcptls_session_instance *tcptls_session;
1063 struct manager_custom_hook *hook;
1067 static struct ao2_container *sessions = NULL;
1069 struct manager_channel_variable {
1070 AST_LIST_ENTRY(manager_channel_variable) entry;
1071 unsigned int isfunc:1;
1072 char name[0]; /* allocate off the end the real size. */
1075 static AST_RWLIST_HEAD_STATIC(channelvars, manager_channel_variable);
1077 /*! \brief user descriptor, as read from the config file.
1079 * \note It is still missing some fields -- e.g. we can have multiple permit and deny
1080 * lines which are not supported here, and readperm/writeperm/writetimeout
1083 struct ast_manager_user {
1085 char *secret; /*!< Secret for logging in */
1086 struct ast_ha *ha; /*!< ACL setting */
1087 int readperm; /*!< Authorization for reading */
1088 int writeperm; /*!< Authorization for writing */
1089 int writetimeout; /*!< Per user Timeout for ast_carefulwrite() */
1090 int displayconnects; /*!< XXX unused */
1091 int keep; /*!< mark entries created on a reload */
1092 struct ao2_container *whitefilters; /*!< Manager event filters - white list */
1093 struct ao2_container *blackfilters; /*!< Manager event filters - black list */
1094 char *a1_hash; /*!< precalculated A1 for Digest auth */
1095 AST_RWLIST_ENTRY(ast_manager_user) list;
1098 /*! \brief list of users found in the config file */
1099 static AST_RWLIST_HEAD_STATIC(users, ast_manager_user);
1101 /*! \brief list of actions registered */
1102 static AST_RWLIST_HEAD_STATIC(actions, manager_action);
1104 /*! \brief list of hooks registered */
1105 static AST_RWLIST_HEAD_STATIC(manager_hooks, manager_custom_hook);
1107 static void free_channelvars(void);
1109 static enum add_filter_result manager_add_filter(const char *filter_pattern, struct ao2_container *whitefilters, struct ao2_container *blackfilters);
1113 * \brief Find a registered action object.
1115 * \param name Name of AMI action to find.
1117 * \return Reffed action found or NULL
1119 static struct manager_action *action_find(const char *name)
1121 struct manager_action *act;
1123 AST_RWLIST_RDLOCK(&actions);
1124 AST_RWLIST_TRAVERSE(&actions, act, list) {
1125 if (!strcasecmp(name, act->action)) {
1126 ao2_t_ref(act, +1, "found action object");
1130 AST_RWLIST_UNLOCK(&actions);
1135 /*! \brief Add a custom hook to be called when an event is fired */
1136 void ast_manager_register_hook(struct manager_custom_hook *hook)
1138 AST_RWLIST_WRLOCK(&manager_hooks);
1139 AST_RWLIST_INSERT_TAIL(&manager_hooks, hook, list);
1140 AST_RWLIST_UNLOCK(&manager_hooks);
1143 /*! \brief Delete a custom hook to be called when an event is fired */
1144 void ast_manager_unregister_hook(struct manager_custom_hook *hook)
1146 AST_RWLIST_WRLOCK(&manager_hooks);
1147 AST_RWLIST_REMOVE(&manager_hooks, hook, list);
1148 AST_RWLIST_UNLOCK(&manager_hooks);
1151 int check_manager_enabled(void)
1153 return manager_enabled;
1156 int check_webmanager_enabled(void)
1158 return (webmanager_enabled && manager_enabled);
1162 * Grab a reference to the last event, update usecount as needed.
1163 * Can handle a NULL pointer.
1165 static struct eventqent *grab_last(void)
1167 struct eventqent *ret;
1169 AST_RWLIST_WRLOCK(&all_events);
1170 ret = AST_RWLIST_LAST(&all_events);
1171 /* the list is never empty now, but may become so when
1172 * we optimize it in the future, so be prepared.
1175 ast_atomic_fetchadd_int(&ret->usecount, 1);
1177 AST_RWLIST_UNLOCK(&all_events);
1182 * Purge unused events. Remove elements from the head
1183 * as long as their usecount is 0 and there is a next element.
1185 static void purge_events(void)
1187 struct eventqent *ev;
1188 struct timeval now = ast_tvnow();
1190 AST_RWLIST_WRLOCK(&all_events);
1191 while ( (ev = AST_RWLIST_FIRST(&all_events)) &&
1192 ev->usecount == 0 && AST_RWLIST_NEXT(ev, eq_next)) {
1193 AST_RWLIST_REMOVE_HEAD(&all_events, eq_next);
1197 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&all_events, ev, eq_next) {
1198 /* Never release the last event */
1199 if (!AST_RWLIST_NEXT(ev, eq_next)) {
1203 /* 2.5 times whatever the HTTP timeout is (maximum 2.5 hours) is the maximum time that we will definitely cache an event */
1204 if (ev->usecount == 0 && ast_tvdiff_sec(now, ev->tv) > (httptimeout > 3600 ? 3600 : httptimeout) * 2.5) {
1205 AST_RWLIST_REMOVE_CURRENT(eq_next);
1209 AST_RWLIST_TRAVERSE_SAFE_END;
1210 AST_RWLIST_UNLOCK(&all_events);
1214 * helper functions to convert back and forth between
1215 * string and numeric representation of set of flags
1217 static const struct permalias {
1221 { EVENT_FLAG_SYSTEM, "system" },
1222 { EVENT_FLAG_CALL, "call" },
1223 { EVENT_FLAG_LOG, "log" },
1224 { EVENT_FLAG_VERBOSE, "verbose" },
1225 { EVENT_FLAG_COMMAND, "command" },
1226 { EVENT_FLAG_AGENT, "agent" },
1227 { EVENT_FLAG_USER, "user" },
1228 { EVENT_FLAG_CONFIG, "config" },
1229 { EVENT_FLAG_DTMF, "dtmf" },
1230 { EVENT_FLAG_REPORTING, "reporting" },
1231 { EVENT_FLAG_CDR, "cdr" },
1232 { EVENT_FLAG_DIALPLAN, "dialplan" },
1233 { EVENT_FLAG_ORIGINATE, "originate" },
1234 { EVENT_FLAG_AGI, "agi" },
1235 { EVENT_FLAG_CC, "cc" },
1236 { EVENT_FLAG_AOC, "aoc" },
1237 { EVENT_FLAG_TEST, "test" },
1238 { EVENT_FLAG_MESSAGE, "message" },
1243 /*! \brief Checks to see if a string which can be used to evaluate functions should be rejected */
1244 static int function_capable_string_allowed_with_auths(const char *evaluating, int writepermlist)
1246 if (!(writepermlist & EVENT_FLAG_SYSTEM)
1248 strstr(evaluating, "SHELL") || /* NoOp(${SHELL(rm -rf /)}) */
1249 strstr(evaluating, "EVAL") /* NoOp(${EVAL(${some_var_containing_SHELL})}) */
1256 /*! \brief Convert authority code to a list of options */
1257 static const char *authority_to_str(int authority, struct ast_str **res)
1262 ast_str_reset(*res);
1263 for (i = 0; i < ARRAY_LEN(perms) - 1; i++) {
1264 if (authority & perms[i].num) {
1265 ast_str_append(res, 0, "%s%s", sep, perms[i].label);
1270 if (ast_str_strlen(*res) == 0) /* replace empty string with something sensible */
1271 ast_str_append(res, 0, "<none>");
1273 return ast_str_buffer(*res);
1276 /*! Tells you if smallstr exists inside bigstr
1277 which is delim by delim and uses no buf or stringsep
1278 ast_instring("this|that|more","this",'|') == 1;
1280 feel free to move this to app.c -anthm */
1281 static int ast_instring(const char *bigstr, const char *smallstr, const char delim)
1283 const char *val = bigstr, *next;
1286 if ((next = strchr(val, delim))) {
1287 if (!strncmp(val, smallstr, (next - val))) {
1293 return !strcmp(smallstr, val);
1295 } while (*(val = (next + 1)));
1300 static int get_perm(const char *instr)
1308 for (x = 0; x < ARRAY_LEN(perms); x++) {
1309 if (ast_instring(instr, perms[x].label, ',')) {
1310 ret |= perms[x].num;
1318 * A number returns itself, false returns 0, true returns all flags,
1319 * other strings return the flags that are set.
1321 static int strings_to_mask(const char *string)
1325 if (ast_strlen_zero(string)) {
1329 for (p = string; *p; p++) {
1330 if (*p < '0' || *p > '9') {
1334 if (!*p) { /* all digits */
1335 return atoi(string);
1337 if (ast_false(string)) {
1340 if (ast_true(string)) { /* all permissions */
1342 for (x = 0; x < ARRAY_LEN(perms); x++) {
1343 ret |= perms[x].num;
1347 return get_perm(string);
1350 /*! \brief Unreference manager session object.
1351 If no more references, then go ahead and delete it */
1352 static struct mansession_session *unref_mansession(struct mansession_session *s)
1354 int refcount = ao2_ref(s, -1);
1355 if (manager_debug) {
1356 ast_debug(1, "Mansession: %p refcount now %d\n", s, refcount - 1);
1361 static void event_filter_destructor(void *obj)
1363 regex_t *regex_filter = obj;
1364 regfree(regex_filter);
1367 static void session_destructor(void *obj)
1369 struct mansession_session *session = obj;
1370 struct eventqent *eqe = session->last_ev;
1371 struct ast_datastore *datastore;
1373 /* Get rid of each of the data stores on the session */
1374 while ((datastore = AST_LIST_REMOVE_HEAD(&session->datastores, entry))) {
1375 /* Free the data store */
1376 ast_datastore_free(datastore);
1379 if (session->f != NULL) {
1383 ast_atomic_fetchadd_int(&eqe->usecount, -1);
1386 if (session->whitefilters) {
1387 ao2_t_callback(session->whitefilters, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL, "unlink all white filters");
1388 ao2_t_ref(session->whitefilters, -1 , "decrement ref for white container, should be last one");
1391 if (session->blackfilters) {
1392 ao2_t_callback(session->blackfilters, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL, "unlink all black filters");
1393 ao2_t_ref(session->blackfilters, -1 , "decrement ref for black container, should be last one");
1397 /*! \brief Allocate manager session structure and add it to the list of sessions */
1398 static struct mansession_session *build_mansession(struct sockaddr_in sin)
1400 struct mansession_session *newsession;
1402 if (!(newsession = ao2_alloc(sizeof(*newsession), session_destructor))) {
1406 if (!(newsession->whitefilters = ao2_container_alloc(1, NULL, NULL))) {
1407 ao2_ref(newsession, -1);
1411 if (!(newsession->blackfilters = ao2_container_alloc(1, NULL, NULL))) {
1412 ao2_ref(newsession, -1); /* session_destructor will cleanup the other filter */
1416 newsession->fd = -1;
1417 newsession->waiting_thread = AST_PTHREADT_NULL;
1418 newsession->writetimeout = 100;
1419 newsession->send_events = -1;
1420 newsession->sin = sin;
1422 ao2_link(sessions, newsession);
1427 static int mansession_cmp_fn(void *obj, void *arg, int flags)
1429 struct mansession_session *s = obj;
1431 return !strcasecmp(s->username, str) ? CMP_MATCH : 0;
1434 static void session_destroy(struct mansession_session *s)
1436 unref_mansession(s);
1437 ao2_unlink(sessions, s);
1441 static int check_manager_session_inuse(const char *name)
1443 struct mansession_session *session = ao2_find(sessions, (char *) name, 0);
1448 unref_mansession(session);
1455 * lookup an entry in the list of registered users.
1456 * must be called with the list lock held.
1458 static struct ast_manager_user *get_manager_by_name_locked(const char *name)
1460 struct ast_manager_user *user = NULL;
1462 AST_RWLIST_TRAVERSE(&users, user, list) {
1463 if (!strcasecmp(user->username, name)) {
1471 /*! \brief Get displayconnects config option.
1472 * \param session manager session to get parameter from.
1473 * \return displayconnects config option value.
1475 static int manager_displayconnects (struct mansession_session *session)
1477 struct ast_manager_user *user = NULL;
1480 AST_RWLIST_RDLOCK(&users);
1481 if ((user = get_manager_by_name_locked (session->username))) {
1482 ret = user->displayconnects;
1484 AST_RWLIST_UNLOCK(&users);
1489 static char *handle_showmancmd(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1491 struct manager_action *cur;
1492 struct ast_str *authority;
1496 char syntax_title[64], description_title[64], synopsis_title[64], seealso_title[64], arguments_title[64];
1501 e->command = "manager show command";
1503 "Usage: manager show command <actionname> [<actionname> [<actionname> [...]]]\n"
1504 " Shows the detailed description for a specific Asterisk manager interface command.\n";
1507 l = strlen(a->word);
1509 AST_RWLIST_RDLOCK(&actions);
1510 AST_RWLIST_TRAVERSE(&actions, cur, list) {
1511 if (!strncasecmp(a->word, cur->action, l) && ++which > a->n) {
1512 ret = ast_strdup(cur->action);
1513 break; /* make sure we exit even if ast_strdup() returns NULL */
1516 AST_RWLIST_UNLOCK(&actions);
1519 authority = ast_str_alloca(80);
1521 return CLI_SHOWUSAGE;
1525 /* setup the titles */
1526 term_color(synopsis_title, "[Synopsis]\n", COLOR_MAGENTA, 0, 40);
1527 term_color(description_title, "[Description]\n", COLOR_MAGENTA, 0, 40);
1528 term_color(syntax_title, "[Syntax]\n", COLOR_MAGENTA, 0, 40);
1529 term_color(seealso_title, "[See Also]\n", COLOR_MAGENTA, 0, 40);
1530 term_color(arguments_title, "[Arguments]\n", COLOR_MAGENTA, 0, 40);
1533 AST_RWLIST_RDLOCK(&actions);
1534 AST_RWLIST_TRAVERSE(&actions, cur, list) {
1535 for (num = 3; num < a->argc; num++) {
1536 if (!strcasecmp(cur->action, a->argv[num])) {
1538 if (cur->docsrc == AST_XML_DOC) {
1539 ast_cli(a->fd, "%s%s\n\n%s%s\n\n%s%s\n\n%s%s\n\n%s%s\n\n",
1541 ast_xmldoc_printable(S_OR(cur->syntax, "Not available"), 1),
1543 ast_xmldoc_printable(S_OR(cur->synopsis, "Not available"), 1),
1545 ast_xmldoc_printable(S_OR(cur->description, "Not available"), 1),
1547 ast_xmldoc_printable(S_OR(cur->arguments, "Not available"), 1),
1549 ast_xmldoc_printable(S_OR(cur->seealso, "Not available"), 1));
1553 ast_cli(a->fd, "Action: %s\nSynopsis: %s\nPrivilege: %s\n%s\n",
1554 cur->action, cur->synopsis,
1555 authority_to_str(cur->authority, &authority),
1556 S_OR(cur->description, ""));
1561 AST_RWLIST_UNLOCK(&actions);
1566 static char *handle_mandebug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1570 e->command = "manager set debug [on|off]";
1571 e->usage = "Usage: manager set debug [on|off]\n Show, enable, disable debugging of the manager code.\n";
1578 ast_cli(a->fd, "manager debug is %s\n", manager_debug? "on" : "off");
1579 } else if (a->argc == 4) {
1580 if (!strcasecmp(a->argv[3], "on")) {
1582 } else if (!strcasecmp(a->argv[3], "off")) {
1585 return CLI_SHOWUSAGE;
1591 static char *handle_showmanager(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1593 struct ast_manager_user *user = NULL;
1596 struct ast_str *rauthority = ast_str_alloca(128);
1597 struct ast_str *wauthority = ast_str_alloca(128);
1601 e->command = "manager show user";
1603 " Usage: manager show user <user>\n"
1604 " Display all information related to the manager user specified.\n";
1607 l = strlen(a->word);
1612 AST_RWLIST_RDLOCK(&users);
1613 AST_RWLIST_TRAVERSE(&users, user, list) {
1614 if ( !strncasecmp(a->word, user->username, l) && ++which > a->n ) {
1615 ret = ast_strdup(user->username);
1619 AST_RWLIST_UNLOCK(&users);
1624 return CLI_SHOWUSAGE;
1627 AST_RWLIST_RDLOCK(&users);
1629 if (!(user = get_manager_by_name_locked(a->argv[3]))) {
1630 ast_cli(a->fd, "There is no manager called %s\n", a->argv[3]);
1631 AST_RWLIST_UNLOCK(&users);
1635 ast_cli(a->fd, "\n");
1642 "displayconnects: %s\n",
1643 (user->username ? user->username : "(N/A)"),
1644 (user->secret ? "<Set>" : "(N/A)"),
1645 (user->ha ? "yes" : "no"),
1646 authority_to_str(user->readperm, &rauthority),
1647 authority_to_str(user->writeperm, &wauthority),
1648 (user->displayconnects ? "yes" : "no"));
1650 AST_RWLIST_UNLOCK(&users);
1655 static char *handle_showmanagers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1657 struct ast_manager_user *user = NULL;
1661 e->command = "manager show users";
1663 "Usage: manager show users\n"
1664 " Prints a listing of all managers that are currently configured on that\n"
1671 return CLI_SHOWUSAGE;
1674 AST_RWLIST_RDLOCK(&users);
1676 /* If there are no users, print out something along those lines */
1677 if (AST_RWLIST_EMPTY(&users)) {
1678 ast_cli(a->fd, "There are no manager users.\n");
1679 AST_RWLIST_UNLOCK(&users);
1683 ast_cli(a->fd, "\nusername\n--------\n");
1685 AST_RWLIST_TRAVERSE(&users, user, list) {
1686 ast_cli(a->fd, "%s\n", user->username);
1690 AST_RWLIST_UNLOCK(&users);
1692 ast_cli(a->fd,"-------------------\n"
1693 "%d manager users configured.\n", count_amu);
1697 /*! \brief CLI command manager list commands */
1698 static char *handle_showmancmds(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1700 struct manager_action *cur;
1701 struct ast_str *authority;
1702 #define HSMC_FORMAT " %-15.15s %-15.15s %-55.55s\n"
1705 e->command = "manager show commands";
1707 "Usage: manager show commands\n"
1708 " Prints a listing of all the available Asterisk manager interface commands.\n";
1713 authority = ast_str_alloca(80);
1714 ast_cli(a->fd, HSMC_FORMAT, "Action", "Privilege", "Synopsis");
1715 ast_cli(a->fd, HSMC_FORMAT, "------", "---------", "--------");
1717 AST_RWLIST_RDLOCK(&actions);
1718 AST_RWLIST_TRAVERSE(&actions, cur, list) {
1719 ast_cli(a->fd, HSMC_FORMAT, cur->action, authority_to_str(cur->authority, &authority), cur->synopsis);
1721 AST_RWLIST_UNLOCK(&actions);
1726 /*! \brief CLI command manager list connected */
1727 static char *handle_showmanconn(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1729 struct mansession_session *session;
1730 time_t now = time(NULL);
1731 #define HSMCONN_FORMAT1 " %-15.15s %-15.15s %-10.10s %-10.10s %-8.8s %-8.8s %-5.5s %-5.5s\n"
1732 #define HSMCONN_FORMAT2 " %-15.15s %-15.15s %-10d %-10d %-8d %-8d %-5.5d %-5.5d\n"
1734 struct ao2_iterator i;
1738 e->command = "manager show connected";
1740 "Usage: manager show connected\n"
1741 " Prints a listing of the users that are currently connected to the\n"
1742 "Asterisk manager interface.\n";
1748 ast_cli(a->fd, HSMCONN_FORMAT1, "Username", "IP Address", "Start", "Elapsed", "FileDes", "HttpCnt", "Read", "Write");
1750 i = ao2_iterator_init(sessions, 0);
1751 while ((session = ao2_iterator_next(&i))) {
1753 ast_cli(a->fd, HSMCONN_FORMAT2, session->username, ast_inet_ntoa(session->sin.sin_addr), (int)(session->sessionstart), (int)(now - session->sessionstart), session->fd, session->inuse, session->readperm, session->writeperm);
1755 ao2_unlock(session);
1756 unref_mansession(session);
1758 ao2_iterator_destroy(&i);
1759 ast_cli(a->fd, "%d users connected.\n", count);
1764 /*! \brief CLI command manager list eventq */
1765 /* Should change to "manager show connected" */
1766 static char *handle_showmaneventq(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1768 struct eventqent *s;
1771 e->command = "manager show eventq";
1773 "Usage: manager show eventq\n"
1774 " Prints a listing of all events pending in the Asterisk manger\n"
1780 AST_RWLIST_RDLOCK(&all_events);
1781 AST_RWLIST_TRAVERSE(&all_events, s, eq_next) {
1782 ast_cli(a->fd, "Usecount: %d\n", s->usecount);
1783 ast_cli(a->fd, "Category: %d\n", s->category);
1784 ast_cli(a->fd, "Event:\n%s", s->eventdata);
1786 AST_RWLIST_UNLOCK(&all_events);
1791 /*! \brief CLI command manager reload */
1792 static char *handle_manager_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1796 e->command = "manager reload";
1798 "Usage: manager reload\n"
1799 " Reloads the manager configuration.\n";
1805 return CLI_SHOWUSAGE;
1811 static struct eventqent *advance_event(struct eventqent *e)
1813 struct eventqent *next;
1815 AST_RWLIST_RDLOCK(&all_events);
1816 if ((next = AST_RWLIST_NEXT(e, eq_next))) {
1817 ast_atomic_fetchadd_int(&next->usecount, 1);
1818 ast_atomic_fetchadd_int(&e->usecount, -1);
1820 AST_RWLIST_UNLOCK(&all_events);
1824 #define GET_HEADER_FIRST_MATCH 0
1825 #define GET_HEADER_LAST_MATCH 1
1826 #define GET_HEADER_SKIP_EMPTY 2
1829 * \brief Return a matching header value.
1832 * Generic function to return either the first or the last
1833 * matching header from a list of variables, possibly skipping
1836 * \note At the moment there is only one use of this function in
1837 * this file, so we make it static.
1839 * \note Never returns NULL.
1841 static const char *__astman_get_header(const struct message *m, char *var, int mode)
1843 int x, l = strlen(var);
1844 const char *result = "";
1846 for (x = 0; x < m->hdrcount; x++) {
1847 const char *h = m->headers[x];
1848 if (!strncasecmp(var, h, l) && h[l] == ':') {
1849 const char *value = h + l + 1;
1850 value = ast_skip_blanks(value); /* ignore leading spaces in the value */
1851 /* found a potential candidate */
1852 if ((mode & GET_HEADER_SKIP_EMPTY) && ast_strlen_zero(value)) {
1853 continue; /* not interesting */
1855 if (mode & GET_HEADER_LAST_MATCH) {
1856 result = value; /* record the last match so far */
1867 * \brief Return the first matching variable from an array.
1869 * \note This is the legacy function and is implemented in
1870 * therms of __astman_get_header().
1872 * \note Never returns NULL.
1874 const char *astman_get_header(const struct message *m, char *var)
1876 return __astman_get_header(m, var, GET_HEADER_FIRST_MATCH);
1881 * \brief Process one "Variable:" header value string.
1883 * \param head Current list of AMI variables to get new values added.
1884 * \param hdr_val Header value string to process.
1886 * \return New variable list head.
1888 static struct ast_variable *man_do_variable_value(struct ast_variable *head, const char *hdr_val)
1891 AST_DECLARE_APP_ARGS(args,
1892 AST_APP_ARG(vars)[64];
1895 hdr_val = ast_skip_blanks(hdr_val); /* ignore leading spaces in the value */
1896 parse = ast_strdupa(hdr_val);
1898 /* Break the header value string into name=val pair items. */
1899 AST_STANDARD_APP_ARGS(args, parse);
1903 /* Process each name=val pair item. */
1904 for (y = 0; y < args.argc; y++) {
1905 struct ast_variable *cur;
1909 if (!args.vars[y]) {
1912 var = val = args.vars[y];
1915 /* XXX We may wish to trim whitespace from the strings. */
1916 if (!val || ast_strlen_zero(var)) {
1920 /* Create new variable list node and prepend it to the list. */
1921 cur = ast_variable_new(var, val, "");
1932 struct ast_variable *astman_get_variables(const struct message *m)
1936 struct ast_variable *head = NULL;
1938 static const char var_hdr[] = "Variable:";
1940 /* Process all "Variable:" headers. */
1941 varlen = strlen(var_hdr);
1942 for (x = 0; x < m->hdrcount; x++) {
1943 if (strncasecmp(var_hdr, m->headers[x], varlen)) {
1946 head = man_do_variable_value(head, m->headers[x] + varlen);
1952 /*! \brief access for hooks to send action messages to ami */
1953 int ast_hook_send_action(struct manager_custom_hook *hook, const char *msg)
1957 struct manager_action *act_found;
1958 struct mansession s = {.session = NULL, };
1959 struct message m = { 0 };
1969 /* Create our own copy of the AMI action msg string. */
1970 src = dup_str = ast_strdup(msg);
1975 /* convert msg string to message struct */
1976 curlen = strlen(src);
1977 for (x = 0; x < curlen; x++) {
1978 int cr; /* set if we have \r */
1979 if (src[x] == '\r' && x+1 < curlen && src[x+1] == '\n')
1980 cr = 2; /* Found. Update length to include \r\n */
1981 else if (src[x] == '\n')
1982 cr = 1; /* also accept \n only */
1985 /* don't keep empty lines */
1986 if (x && m.hdrcount < ARRAY_LEN(m.headers)) {
1987 /* ... but trim \r\n and terminate the header string */
1989 m.headers[m.hdrcount++] = src;
1992 curlen -= x; /* remaining size */
1993 src += x; /* update pointer */
1994 x = -1; /* reset loop */
1997 action = astman_get_header(&m, "Action");
1998 if (strcasecmp(action, "login")) {
1999 act_found = action_find(action);
2002 * we have to simulate a session for this action request
2003 * to be able to pass it down for processing
2004 * This is necessary to meet the previous design of manager.c
2007 s.f = (void*)1; /* set this to something so our request will make it through all functions that test it*/
2009 ao2_lock(act_found);
2010 if (act_found->registered && act_found->func) {
2011 if (act_found->module) {
2012 ast_module_ref(act_found->module);
2014 ao2_unlock(act_found);
2015 ret = act_found->func(&s, &m);
2016 ao2_lock(act_found);
2017 if (act_found->module) {
2018 ast_module_unref(act_found->module);
2023 ao2_unlock(act_found);
2024 ao2_t_ref(act_found, -1, "done with found action object");
2033 * helper function to send a string to the socket.
2034 * Return -1 on error (e.g. buffer full).
2036 static int send_string(struct mansession *s, char *string)
2039 FILE *f = s->f ? s->f : s->session->f;
2040 int fd = s->f ? s->fd : s->session->fd;
2042 /* It's a result from one of the hook's action invocation */
2045 * to send responses, we're using the same function
2046 * as for receiving events. We call the event "HookResponse"
2048 s->hook->helper(EVENT_FLAG_HOOKRESPONSE, "HookResponse", string);
2052 if ((res = ast_careful_fwrite(f, fd, string, strlen(string), s->session->writetimeout))) {
2060 * \brief thread local buffer for astman_append
2062 * \note This can not be defined within the astman_append() function
2063 * because it declares a couple of functions that get used to
2064 * initialize the thread local storage key.
2066 AST_THREADSTORAGE(astman_append_buf);
2068 AST_THREADSTORAGE(userevent_buf);
2070 /*! \brief initial allocated size for the astman_append_buf and astman_send_*_va */
2071 #define ASTMAN_APPEND_BUF_INITSIZE 256
2074 * utility functions for creating AMI replies
2076 void astman_append(struct mansession *s, const char *fmt, ...)
2079 struct ast_str *buf;
2081 if (!(buf = ast_str_thread_get(&astman_append_buf, ASTMAN_APPEND_BUF_INITSIZE))) {
2086 ast_str_set_va(&buf, 0, fmt, ap);
2089 if (s->f != NULL || s->session->f != NULL) {
2090 send_string(s, ast_str_buffer(buf));
2092 ast_verbose("fd == -1 in astman_append, should not happen\n");
2096 /*! \note NOTE: XXX this comment is unclear and possibly wrong.
2097 Callers of astman_send_error(), astman_send_response() or astman_send_ack() must EITHER
2098 hold the session lock _or_ be running in an action callback (in which case s->session->busy will
2099 be non-zero). In either of these cases, there is no need to lock-protect the session's
2100 fd, since no other output will be sent (events will be queued), and no input will
2101 be read until either the current action finishes or get_input() obtains the session
2105 /*! \todo XXX MSG_MOREDATA should go to a header file. */
2106 #define MSG_MOREDATA ((char *)astman_send_response)
2108 /*! \brief send a response with an optional message,
2109 * and terminate it with an empty line.
2110 * m is used only to grab the 'ActionID' field.
2112 * Use the explicit constant MSG_MOREDATA to remove the empty line.
2113 * XXX MSG_MOREDATA should go to a header file.
2115 static void astman_send_response_full(struct mansession *s, const struct message *m, char *resp, char *msg, char *listflag)
2117 const char *id = astman_get_header(m, "ActionID");
2119 astman_append(s, "Response: %s\r\n", resp);
2120 if (!ast_strlen_zero(id)) {
2121 astman_append(s, "ActionID: %s\r\n", id);
2124 astman_append(s, "EventList: %s\r\n", listflag); /* Start, complete, cancelled */
2126 if (msg == MSG_MOREDATA) {
2129 astman_append(s, "Message: %s\r\n\r\n", msg);
2131 astman_append(s, "\r\n");
2135 void astman_send_response(struct mansession *s, const struct message *m, char *resp, char *msg)
2137 astman_send_response_full(s, m, resp, msg, NULL);
2140 void astman_send_error(struct mansession *s, const struct message *m, char *error)
2142 astman_send_response_full(s, m, "Error", error, NULL);
2145 void astman_send_error_va(struct mansession *s, const struct message *m, const char *fmt, ...)
2148 struct ast_str *buf;
2150 if (!(buf = ast_str_thread_get(&astman_append_buf, ASTMAN_APPEND_BUF_INITSIZE))) {
2155 ast_str_set_va(&buf, 0, fmt, ap);
2158 astman_send_response_full(s, m, "Error", ast_str_buffer(buf), NULL);
2162 void astman_send_ack(struct mansession *s, const struct message *m, char *msg)
2164 astman_send_response_full(s, m, "Success", msg, NULL);
2167 static void astman_start_ack(struct mansession *s, const struct message *m)
2169 astman_send_response_full(s, m, "Success", MSG_MOREDATA, NULL);
2172 void astman_send_listack(struct mansession *s, const struct message *m, char *msg, char *listflag)
2174 astman_send_response_full(s, m, "Success", msg, listflag);
2177 /*! \brief Lock the 'mansession' structure. */
2178 static void mansession_lock(struct mansession *s)
2180 ast_mutex_lock(&s->lock);
2183 /*! \brief Unlock the 'mansession' structure. */
2184 static void mansession_unlock(struct mansession *s)
2186 ast_mutex_unlock(&s->lock);
2190 Rather than braindead on,off this now can also accept a specific int mask value
2191 or a ',' delim list of mask strings (the same as manager.conf) -anthm
2193 static int set_eventmask(struct mansession *s, const char *eventmask)
2195 int maskint = strings_to_mask(eventmask);
2197 ao2_lock(s->session);
2199 s->session->send_events = maskint;
2201 ao2_unlock(s->session);
2206 static enum ast_security_event_transport_type mansession_get_transport(const struct mansession *s)
2208 return s->tcptls_session->parent->tls_cfg ? AST_SECURITY_EVENT_TRANSPORT_TLS :
2209 AST_SECURITY_EVENT_TRANSPORT_TCP;
2212 static void report_invalid_user(const struct mansession *s, const char *username)
2214 struct ast_sockaddr addr_remote;
2215 char session_id[32];
2216 struct ast_security_event_inval_acct_id inval_acct_id = {
2217 .common.event_type = AST_SECURITY_EVENT_INVAL_ACCT_ID,
2218 .common.version = AST_SECURITY_EVENT_INVAL_ACCT_ID_VERSION,
2219 .common.service = "AMI",
2220 .common.account_id = username,
2221 .common.session_tv = &s->session->sessionstart_tv,
2222 .common.local_addr = {
2223 .addr = &s->tcptls_session->parent->local_address,
2224 .transport = mansession_get_transport(s),
2226 .common.remote_addr = {
2227 .addr = &addr_remote,
2228 .transport = mansession_get_transport(s),
2230 .common.session_id = session_id,
2233 ast_sockaddr_from_sin(&addr_remote, &s->session->sin);
2235 snprintf(session_id, sizeof(session_id), "%p", s);
2237 ast_security_event_report(AST_SEC_EVT(&inval_acct_id));
2240 static void report_failed_acl(const struct mansession *s, const char *username)
2242 struct ast_sockaddr addr_remote;
2243 char session_id[32];
2244 struct ast_security_event_failed_acl failed_acl_event = {
2245 .common.event_type = AST_SECURITY_EVENT_FAILED_ACL,
2246 .common.version = AST_SECURITY_EVENT_FAILED_ACL_VERSION,
2247 .common.service = "AMI",
2248 .common.account_id = username,
2249 .common.session_tv = &s->session->sessionstart_tv,
2250 .common.local_addr = {
2251 .addr = &s->tcptls_session->parent->local_address,
2252 .transport = mansession_get_transport(s),
2254 .common.remote_addr = {
2255 .addr = &addr_remote,
2256 .transport = mansession_get_transport(s),
2258 .common.session_id = session_id,
2261 ast_sockaddr_from_sin(&addr_remote, &s->session->sin);
2263 snprintf(session_id, sizeof(session_id), "%p", s->session);
2265 ast_security_event_report(AST_SEC_EVT(&failed_acl_event));
2268 static void report_inval_password(const struct mansession *s, const char *username)
2270 struct ast_sockaddr addr_remote;
2271 char session_id[32];
2272 struct ast_security_event_inval_password inval_password = {
2273 .common.event_type = AST_SECURITY_EVENT_INVAL_PASSWORD,
2274 .common.version = AST_SECURITY_EVENT_INVAL_PASSWORD_VERSION,
2275 .common.service = "AMI",
2276 .common.account_id = username,
2277 .common.session_tv = &s->session->sessionstart_tv,
2278 .common.local_addr = {
2279 .addr = &s->tcptls_session->parent->local_address,
2280 .transport = mansession_get_transport(s),
2282 .common.remote_addr = {
2283 .addr = &addr_remote,
2284 .transport = mansession_get_transport(s),
2286 .common.session_id = session_id,
2289 ast_sockaddr_from_sin(&addr_remote, &s->session->sin);
2291 snprintf(session_id, sizeof(session_id), "%p", s->session);
2293 ast_security_event_report(AST_SEC_EVT(&inval_password));
2296 static void report_auth_success(const struct mansession *s)
2298 struct ast_sockaddr addr_remote;
2299 char session_id[32];
2300 struct ast_security_event_successful_auth successful_auth = {
2301 .common.event_type = AST_SECURITY_EVENT_SUCCESSFUL_AUTH,
2302 .common.version = AST_SECURITY_EVENT_SUCCESSFUL_AUTH_VERSION,
2303 .common.service = "AMI",
2304 .common.account_id = s->session->username,
2305 .common.session_tv = &s->session->sessionstart_tv,
2306 .common.local_addr = {
2307 .addr = &s->tcptls_session->parent->local_address,
2308 .transport = mansession_get_transport(s),
2310 .common.remote_addr = {
2311 .addr = &addr_remote,
2312 .transport = mansession_get_transport(s),
2314 .common.session_id = session_id,
2317 ast_sockaddr_from_sin(&addr_remote, &s->session->sin);
2319 snprintf(session_id, sizeof(session_id), "%p", s->session);
2321 ast_security_event_report(AST_SEC_EVT(&successful_auth));
2324 static void report_req_not_allowed(const struct mansession *s, const char *action)
2326 struct ast_sockaddr addr_remote;
2327 char session_id[32];
2328 char request_type[64];
2329 struct ast_security_event_req_not_allowed req_not_allowed = {
2330 .common.event_type = AST_SECURITY_EVENT_REQ_NOT_ALLOWED,
2331 .common.version = AST_SECURITY_EVENT_REQ_NOT_ALLOWED_VERSION,
2332 .common.service = "AMI",
2333 .common.account_id = s->session->username,
2334 .common.session_tv = &s->session->sessionstart_tv,
2335 .common.local_addr = {
2336 .addr = &s->tcptls_session->parent->local_address,
2337 .transport = mansession_get_transport(s),
2339 .common.remote_addr = {
2340 .addr = &addr_remote,
2341 .transport = mansession_get_transport(s),
2343 .common.session_id = session_id,
2345 .request_type = request_type,
2348 ast_sockaddr_from_sin(&addr_remote, &s->session->sin);
2350 snprintf(session_id, sizeof(session_id), "%p", s->session);
2351 snprintf(request_type, sizeof(request_type), "Action: %s", action);
2353 ast_security_event_report(AST_SEC_EVT(&req_not_allowed));
2356 static void report_req_bad_format(const struct mansession *s, const char *action)
2358 struct ast_sockaddr addr_remote;
2359 char session_id[32];
2360 char request_type[64];
2361 struct ast_security_event_req_bad_format req_bad_format = {
2362 .common.event_type = AST_SECURITY_EVENT_REQ_BAD_FORMAT,
2363 .common.version = AST_SECURITY_EVENT_REQ_BAD_FORMAT_VERSION,
2364 .common.service = "AMI",
2365 .common.account_id = s->session->username,
2366 .common.session_tv = &s->session->sessionstart_tv,
2367 .common.local_addr = {
2368 .addr = &s->tcptls_session->parent->local_address,
2369 .transport = mansession_get_transport(s),
2371 .common.remote_addr = {
2372 .addr = &addr_remote,
2373 .transport = mansession_get_transport(s),
2375 .common.session_id = session_id,
2377 .request_type = request_type,
2380 ast_sockaddr_from_sin(&addr_remote, &s->session->sin);
2382 snprintf(session_id, sizeof(session_id), "%p", s->session);
2383 snprintf(request_type, sizeof(request_type), "Action: %s", action);
2385 ast_security_event_report(AST_SEC_EVT(&req_bad_format));
2388 static void report_failed_challenge_response(const struct mansession *s,
2389 const char *response, const char *expected_response)
2391 struct ast_sockaddr addr_remote;
2392 char session_id[32];
2393 struct ast_security_event_chal_resp_failed chal_resp_failed = {
2394 .common.event_type = AST_SECURITY_EVENT_CHAL_RESP_FAILED,
2395 .common.version = AST_SECURITY_EVENT_CHAL_RESP_FAILED_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 = &addr_remote,
2405 .transport = mansession_get_transport(s),
2407 .common.session_id = session_id,
2409 .challenge = s->session->challenge,
2410 .response = response,
2411 .expected_response = expected_response,
2414 ast_sockaddr_from_sin(&addr_remote, &s->session->sin);
2416 snprintf(session_id, sizeof(session_id), "%p", s->session);
2418 ast_security_event_report(AST_SEC_EVT(&chal_resp_failed));
2421 static void report_session_limit(const struct mansession *s)
2423 struct ast_sockaddr addr_remote;
2424 char session_id[32];
2425 struct ast_security_event_session_limit session_limit = {
2426 .common.event_type = AST_SECURITY_EVENT_SESSION_LIMIT,
2427 .common.version = AST_SECURITY_EVENT_SESSION_LIMIT_VERSION,
2428 .common.service = "AMI",
2429 .common.account_id = s->session->username,
2430 .common.session_tv = &s->session->sessionstart_tv,
2431 .common.local_addr = {
2432 .addr = &s->tcptls_session->parent->local_address,
2433 .transport = mansession_get_transport(s),
2435 .common.remote_addr = {
2436 .addr = &addr_remote,
2437 .transport = mansession_get_transport(s),
2439 .common.session_id = session_id,
2442 ast_sockaddr_from_sin(&addr_remote, &s->session->sin);
2444 snprintf(session_id, sizeof(session_id), "%p", s->session);
2446 ast_security_event_report(AST_SEC_EVT(&session_limit));
2450 * Here we start with action_ handlers for AMI actions,
2451 * and the internal functions used by them.
2452 * Generally, the handlers are called action_foo()
2455 /* helper function for action_login() */
2456 static int authenticate(struct mansession *s, const struct message *m)
2458 const char *username = astman_get_header(m, "Username");
2459 const char *password = astman_get_header(m, "Secret");
2461 struct ast_manager_user *user = NULL;
2462 regex_t *regex_filter;
2463 struct ao2_iterator filter_iter;
2464 struct ast_sockaddr addr;
2466 if (ast_strlen_zero(username)) { /* missing username */
2470 /* locate user in locked state */
2471 AST_RWLIST_WRLOCK(&users);
2473 ast_sockaddr_from_sin(&addr, &s->session->sin);
2475 if (!(user = get_manager_by_name_locked(username))) {
2476 report_invalid_user(s, username);
2477 ast_log(LOG_NOTICE, "%s tried to authenticate with nonexistent user '%s'\n", ast_inet_ntoa(s->session->sin.sin_addr), username);
2478 } else if (user->ha && !ast_apply_ha(user->ha, &addr)) {
2479 report_failed_acl(s, username);
2480 ast_log(LOG_NOTICE, "%s failed to pass IP ACL as '%s'\n", ast_inet_ntoa(s->session->sin.sin_addr), username);
2481 } else if (!strcasecmp(astman_get_header(m, "AuthType"), "MD5")) {
2482 const char *key = astman_get_header(m, "Key");
2483 if (!ast_strlen_zero(key) && !ast_strlen_zero(s->session->challenge) && user->secret) {
2486 char md5key[256] = "";
2487 struct MD5Context md5;
2488 unsigned char digest[16];
2491 MD5Update(&md5, (unsigned char *) s->session->challenge, strlen(s->session->challenge));
2492 MD5Update(&md5, (unsigned char *) user->secret, strlen(user->secret));
2493 MD5Final(digest, &md5);
2494 for (x = 0; x < 16; x++)
2495 len += sprintf(md5key + len, "%2.2x", digest[x]);
2496 if (!strcmp(md5key, key)) {
2499 report_failed_challenge_response(s, key, md5key);
2502 ast_debug(1, "MD5 authentication is not possible. challenge: '%s'\n",
2503 S_OR(s->session->challenge, ""));
2505 } else if (user->secret) {
2506 if (!strcmp(password, user->secret)) {
2509 report_inval_password(s, username);
2514 ast_log(LOG_NOTICE, "%s failed to authenticate as '%s'\n", ast_inet_ntoa(s->session->sin.sin_addr), username);
2515 AST_RWLIST_UNLOCK(&users);
2521 /* All of the user parameters are copied to the session so that in the event
2522 * of a reload and a configuration change, the session parameters are not
2524 ast_copy_string(s->session->username, username, sizeof(s->session->username));
2525 s->session->readperm = user->readperm;
2526 s->session->writeperm = user->writeperm;
2527 s->session->writetimeout = user->writetimeout;
2529 filter_iter = ao2_iterator_init(user->whitefilters, 0);
2530 while ((regex_filter = ao2_iterator_next(&filter_iter))) {
2531 ao2_t_link(s->session->whitefilters, regex_filter, "add white user filter to session");
2532 ao2_t_ref(regex_filter, -1, "remove iterator ref");
2534 ao2_iterator_destroy(&filter_iter);
2536 filter_iter = ao2_iterator_init(user->blackfilters, 0);
2537 while ((regex_filter = ao2_iterator_next(&filter_iter))) {
2538 ao2_t_link(s->session->blackfilters, regex_filter, "add black user filter to session");
2539 ao2_t_ref(regex_filter, -1, "remove iterator ref");
2541 ao2_iterator_destroy(&filter_iter);
2543 s->session->sessionstart = time(NULL);
2544 s->session->sessionstart_tv = ast_tvnow();
2545 set_eventmask(s, astman_get_header(m, "Events"));
2547 report_auth_success(s);
2549 AST_RWLIST_UNLOCK(&users);
2553 static int action_ping(struct mansession *s, const struct message *m)
2555 const char *actionid = astman_get_header(m, "ActionID");
2556 struct timeval now = ast_tvnow();
2558 astman_append(s, "Response: Success\r\n");
2559 if (!ast_strlen_zero(actionid)){
2560 astman_append(s, "ActionID: %s\r\n", actionid);
2565 "Timestamp: %ld.%06lu\r\n"
2567 (long) now.tv_sec, (unsigned long) now.tv_usec);
2571 static int action_getconfig(struct mansession *s, const struct message *m)
2573 struct ast_config *cfg;
2574 const char *fn = astman_get_header(m, "Filename");
2575 const char *category = astman_get_header(m, "Category");
2578 char *cur_category = NULL;
2579 struct ast_variable *v;
2580 struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
2582 if (ast_strlen_zero(fn)) {
2583 astman_send_error(s, m, "Filename not specified");
2586 cfg = ast_config_load2(fn, "manager", config_flags);
2587 if (cfg == CONFIG_STATUS_FILEMISSING) {
2588 astman_send_error(s, m, "Config file not found");
2590 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
2591 astman_send_error(s, m, "Config file has invalid format");
2595 astman_start_ack(s, m);
2596 while ((cur_category = ast_category_browse(cfg, cur_category))) {
2597 if (ast_strlen_zero(category) || (!ast_strlen_zero(category) && !strcmp(category, cur_category))) {
2599 astman_append(s, "Category-%06d: %s\r\n", catcount, cur_category);
2600 for (v = ast_variable_browse(cfg, cur_category); v; v = v->next) {
2601 astman_append(s, "Line-%06d-%06d: %s=%s\r\n", catcount, lineno++, v->name, v->value);
2606 if (!ast_strlen_zero(category) && catcount == 0) { /* TODO: actually, a config with no categories doesn't even get loaded */
2607 astman_append(s, "No categories found\r\n");
2609 ast_config_destroy(cfg);
2610 astman_append(s, "\r\n");
2615 static int action_listcategories(struct mansession *s, const struct message *m)
2617 struct ast_config *cfg;
2618 const char *fn = astman_get_header(m, "Filename");
2619 char *category = NULL;
2620 struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
2623 if (ast_strlen_zero(fn)) {
2624 astman_send_error(s, m, "Filename not specified");
2627 if (!(cfg = ast_config_load2(fn, "manager", config_flags))) {
2628 astman_send_error(s, m, "Config file not found");
2630 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
2631 astman_send_error(s, m, "Config file has invalid format");
2634 astman_start_ack(s, m);
2635 while ((category = ast_category_browse(cfg, category))) {
2636 astman_append(s, "Category-%06d: %s\r\n", catcount, category);
2639 if (catcount == 0) { /* TODO: actually, a config with no categories doesn't even get loaded */
2640 astman_append(s, "Error: no categories found\r\n");
2642 ast_config_destroy(cfg);
2643 astman_append(s, "\r\n");
2651 /*! The amount of space in out must be at least ( 2 * strlen(in) + 1 ) */
2652 static void json_escape(char *out, const char *in)
2655 if (*in == '\\' || *in == '\"') {
2665 * \brief Append a JSON escaped string to the manager stream.
2667 * \param s AMI stream to append a string.
2668 * \param str String to append to the stream after JSON escaping it.
2672 static void astman_append_json(struct mansession *s, const char *str)
2676 buf = alloca(2 * strlen(str) + 1);
2677 json_escape(buf, str);
2678 astman_append(s, "%s", buf);
2681 static int action_getconfigjson(struct mansession *s, const struct message *m)
2683 struct ast_config *cfg;
2684 const char *fn = astman_get_header(m, "Filename");
2685 char *category = NULL;
2686 struct ast_variable *v;
2688 struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
2690 if (ast_strlen_zero(fn)) {
2691 astman_send_error(s, m, "Filename not specified");
2695 if (!(cfg = ast_config_load2(fn, "manager", config_flags))) {
2696 astman_send_error(s, m, "Config file not found");
2698 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
2699 astman_send_error(s, m, "Config file has invalid format");
2703 astman_start_ack(s, m);
2704 astman_append(s, "JSON: {");
2705 while ((category = ast_category_browse(cfg, category))) {
2708 astman_append(s, "%s\"", comma1 ? "," : "");
2709 astman_append_json(s, category);
2710 astman_append(s, "\":[");
2712 for (v = ast_variable_browse(cfg, category); v; v = v->next) {
2713 astman_append(s, "%s\"", comma2 ? "," : "");
2714 astman_append_json(s, v->name);
2715 astman_append(s, "\":\"");
2716 astman_append_json(s, v->value);
2717 astman_append(s, "\"");
2720 astman_append(s, "]");
2722 astman_append(s, "}\r\n\r\n");
2724 ast_config_destroy(cfg);
2729 /*! \brief helper function for action_updateconfig */
2730 static enum error_type handle_updates(struct mansession *s, const struct message *m, struct ast_config *cfg, const char *dfn)
2734 const char *action, *cat, *var, *value, *match, *line;
2735 struct ast_category *category;
2736 struct ast_variable *v;
2737 struct ast_str *str1 = ast_str_create(16), *str2 = ast_str_create(16);
2738 enum error_type result = 0;
2740 for (x = 0; x < 100000; x++) { /* 100000 = the max number of allowed updates + 1 */
2741 unsigned int object = 0;
2743 snprintf(hdr, sizeof(hdr), "Action-%06d", x);
2744 action = astman_get_header(m, hdr);
2745 if (ast_strlen_zero(action)) /* breaks the for loop if no action header */
2746 break; /* this could cause problems if actions come in misnumbered */
2748 snprintf(hdr, sizeof(hdr), "Cat-%06d", x);
2749 cat = astman_get_header(m, hdr);
2750 if (ast_strlen_zero(cat)) { /* every action needs a category */
2751 result = UNSPECIFIED_CATEGORY;
2755 snprintf(hdr, sizeof(hdr), "Var-%06d", x);
2756 var = astman_get_header(m, hdr);
2758 snprintf(hdr, sizeof(hdr), "Value-%06d", x);
2759 value = astman_get_header(m, hdr);
2761 if (!ast_strlen_zero(value) && *value == '>') {
2766 snprintf(hdr, sizeof(hdr), "Match-%06d", x);
2767 match = astman_get_header(m, hdr);
2769 snprintf(hdr, sizeof(hdr), "Line-%06d", x);
2770 line = astman_get_header(m, hdr);
2772 if (!strcasecmp(action, "newcat")) {
2773 if (ast_category_get(cfg,cat)) { /* check to make sure the cat doesn't */
2774 result = FAILURE_NEWCAT; /* already exist */
2777 if (!(category = ast_category_new(cat, dfn, -1))) {
2778 result = FAILURE_ALLOCATION;
2781 if (ast_strlen_zero(match)) {
2782 ast_category_append(cfg, category);
2784 ast_category_insert(cfg, category, match);
2786 } else if (!strcasecmp(action, "renamecat")) {
2787 if (ast_strlen_zero(value)) {
2788 result = UNSPECIFIED_ARGUMENT;
2791 if (!(category = ast_category_get(cfg, cat))) {
2792 result = UNKNOWN_CATEGORY;
2795 ast_category_rename(category, value);
2796 } else if (!strcasecmp(action, "delcat")) {
2797 if (ast_category_delete(cfg, cat)) {
2798 result = FAILURE_DELCAT;
2801 } else if (!strcasecmp(action, "emptycat")) {
2802 if (ast_category_empty(cfg, cat)) {
2803 result = FAILURE_EMPTYCAT;
2806 } else if (!strcasecmp(action, "update")) {
2807 if (ast_strlen_zero(var)) {
2808 result = UNSPECIFIED_ARGUMENT;
2811 if (!(category = ast_category_get(cfg,cat))) {
2812 result = UNKNOWN_CATEGORY;
2815 if (ast_variable_update(category, var, value, match, object)) {
2816 result = FAILURE_UPDATE;
2819 } else if (!strcasecmp(action, "delete")) {
2820 if ((ast_strlen_zero(var) && ast_strlen_zero(line))) {
2821 result = UNSPECIFIED_ARGUMENT;
2824 if (!(category = ast_category_get(cfg, cat))) {
2825 result = UNKNOWN_CATEGORY;
2828 if (ast_variable_delete(category, var, match, line)) {
2829 result = FAILURE_DELETE;
2832 } else if (!strcasecmp(action, "append")) {
2833 if (ast_strlen_zero(var)) {
2834 result = UNSPECIFIED_ARGUMENT;
2837 if (!(category = ast_category_get(cfg, cat))) {
2838 result = UNKNOWN_CATEGORY;
2841 if (!(v = ast_variable_new(var, value, dfn))) {
2842 result = FAILURE_ALLOCATION;
2845 if (object || (match && !strcasecmp(match, "object"))) {
2848 ast_variable_append(category, v);
2849 } else if (!strcasecmp(action, "insert")) {
2850 if (ast_strlen_zero(var) || ast_strlen_zero(line)) {
2851 result = UNSPECIFIED_ARGUMENT;
2854 if (!(category = ast_category_get(cfg, cat))) {
2855 result = UNKNOWN_CATEGORY;
2858 if (!(v = ast_variable_new(var, value, dfn))) {
2859 result = FAILURE_ALLOCATION;
2862 ast_variable_insert(category, v, line);
2865 ast_log(LOG_WARNING, "Action-%06d: %s not handled\n", x, action);
2866 result = UNKNOWN_ACTION;
2875 static int action_updateconfig(struct mansession *s, const struct message *m)
2877 struct ast_config *cfg;
2878 const char *sfn = astman_get_header(m, "SrcFilename");
2879 const char *dfn = astman_get_header(m, "DstFilename");
2881 const char *rld = astman_get_header(m, "Reload");
2882 struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
2883 enum error_type result;
2885 if (ast_strlen_zero(sfn) || ast_strlen_zero(dfn)) {
2886 astman_send_error(s, m, "Filename not specified");
2889 if (!(cfg = ast_config_load2(sfn, "manager", config_flags))) {
2890 astman_send_error(s, m, "Config file not found");
2892 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
2893 astman_send_error(s, m, "Config file has invalid format");
2896 result = handle_updates(s, m, cfg, dfn);
2898 ast_include_rename(cfg, sfn, dfn); /* change the include references from dfn to sfn, so things match up */
2899 res = ast_config_text_file_save(dfn, cfg, "Manager");
2900 ast_config_destroy(cfg);
2902 astman_send_error(s, m, "Save of config failed");
2905 astman_send_ack(s, m, NULL);
2906 if (!ast_strlen_zero(rld)) {
2907 if (ast_true(rld)) {
2910 ast_module_reload(rld);
2913 ast_config_destroy(cfg);
2915 case UNKNOWN_ACTION:
2916 astman_send_error(s, m, "Unknown action command");
2918 case UNKNOWN_CATEGORY:
2919 astman_send_error(s, m, "Given category does not exist");
2921 case UNSPECIFIED_CATEGORY:
2922 astman_send_error(s, m, "Category not specified");
2924 case UNSPECIFIED_ARGUMENT:
2925 astman_send_error(s, m, "Problem with category, value, or line (if required)");
2927 case FAILURE_ALLOCATION:
2928 astman_send_error(s, m, "Memory allocation failure, this should not happen");
2930 case FAILURE_NEWCAT:
2931 astman_send_error(s, m, "Create category did not complete successfully");
2933 case FAILURE_DELCAT:
2934 astman_send_error(s, m, "Delete category did not complete successfully");
2936 case FAILURE_EMPTYCAT:
2937 astman_send_error(s, m, "Empty category did not complete successfully");
2939 case FAILURE_UPDATE:
2940 astman_send_error(s, m, "Update did not complete successfully");
2942 case FAILURE_DELETE:
2943 astman_send_error(s, m, "Delete did not complete successfully");
2945 case FAILURE_APPEND:
2946 astman_send_error(s, m, "Append did not complete successfully");
2953 static int action_createconfig(struct mansession *s, const struct message *m)
2956 const char *fn = astman_get_header(m, "Filename");
2957 struct ast_str *filepath = ast_str_alloca(PATH_MAX);
2958 ast_str_set(&filepath, 0, "%s/", ast_config_AST_CONFIG_DIR);
2959 ast_str_append(&filepath, 0, "%s", fn);
2961 if ((fd = open(ast_str_buffer(filepath), O_CREAT | O_EXCL, AST_FILE_MODE)) != -1) {
2963 astman_send_ack(s, m, "New configuration file created successfully");
2965 astman_send_error(s, m, strerror(errno));
2971 static int action_waitevent(struct mansession *s, const struct message *m)
2973 const char *timeouts = astman_get_header(m, "Timeout");
2977 const char *id = astman_get_header(m, "ActionID");
2980 if (!ast_strlen_zero(id)) {
2981 snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
2986 if (!ast_strlen_zero(timeouts)) {
2987 sscanf(timeouts, "%30i", &timeout);
2991 /* XXX maybe put an upper bound, or prevent the use of 0 ? */
2994 ao2_lock(s->session);
2995 if (s->session->waiting_thread != AST_PTHREADT_NULL) {
2996 pthread_kill(s->session->waiting_thread, SIGURG);
2999 if (s->session->managerid) { /* AMI-over-HTTP session */
3001 * Make sure the timeout is within the expire time of the session,
3002 * as the client will likely abort the request if it does not see
3003 * data coming after some amount of time.
3005 time_t now = time(NULL);
3006 int max = s->session->sessiontimeout - now - 10;
3008 if (max < 0) { /* We are already late. Strange but possible. */
3011 if (timeout < 0 || timeout > max) {
3014 if (!s->session->send_events) { /* make sure we record events */
3015 s->session->send_events = -1;
3018 ao2_unlock(s->session);
3020 /* XXX should this go inside the lock ? */
3021 s->session->waiting_thread = pthread_self(); /* let new events wake up this thread */
3022 ast_debug(1, "Starting waiting for an event!\n");
3024 for (x = 0; x < timeout || timeout < 0; x++) {
3025 ao2_lock(s->session);
3026 if (AST_RWLIST_NEXT(s->session->last_ev, eq_next)) {
3029 /* We can have multiple HTTP session point to the same mansession entry.
3030 * The way we deal with it is not very nice: newcomers kick out the previous
3031 * HTTP session. XXX this needs to be improved.
3033 if (s->session->waiting_thread != pthread_self()) {
3036 if (s->session->needdestroy) {
3039 ao2_unlock(s->session);
3043 if (s->session->managerid == 0) { /* AMI session */
3044 if (ast_wait_for_input(s->session->fd, 1000)) {
3047 } else { /* HTTP session */
3051 ast_debug(1, "Finished waiting for an event!\n");
3053 ao2_lock(s->session);
3054 if (s->session->waiting_thread == pthread_self()) {
3055 struct eventqent *eqe = s->session->last_ev;
3056 astman_send_response(s, m, "Success", "Waiting for Event completed.");
3057 while ((eqe = advance_event(eqe))) {
3058 if (((s->session->readperm & eqe->category) == eqe->category) &&
3059 ((s->session->send_events & eqe->category) == eqe->category)) {
3060 astman_append(s, "%s", eqe->eventdata);
3062 s->session->last_ev = eqe;
3065 "Event: WaitEventComplete\r\n"
3068 s->session->waiting_thread = AST_PTHREADT_NULL;
3070 ast_debug(1, "Abandoning event request!\n");
3072 ao2_unlock(s->session);
3077 static int action_listcommands(struct mansession *s, const struct message *m)
3079 struct manager_action *cur;
3080 struct ast_str *temp = ast_str_alloca(256);
3082 astman_start_ack(s, m);
3083 AST_RWLIST_RDLOCK(&actions);
3084 AST_RWLIST_TRAVERSE(&actions, cur, list) {
3085 if ((s->session->writeperm & cur->authority) || cur->authority == 0) {
3086 astman_append(s, "%s: %s (Priv: %s)\r\n",
3087 cur->action, cur->synopsis, authority_to_str(cur->authority, &temp));
3090 AST_RWLIST_UNLOCK(&actions);
3091 astman_append(s, "\r\n");
3096 static int action_events(struct mansession *s, const struct message *m)
3098 const char *mask = astman_get_header(m, "EventMask");
3100 const char *id = astman_get_header(m, "ActionID");
3103 if (!ast_strlen_zero(id)) {
3104 snprintf(id_text, sizeof(id_text), "ActionID: %s\r\n", id);
3109 res = set_eventmask(s, mask);
3110 if (broken_events_action) {
3111 /* if this option is set we should not return a response on
3112 * error, or when all events are set */
3115 for (x = 0; x < ARRAY_LEN(perms); x++) {
3116 if (!strcasecmp(perms[x].label, "all") && res == perms[x].num) {
3120 astman_append(s, "Response: Success\r\n%s"
3121 "Events: On\r\n\r\n", id_text);
3122 } else if (res == 0)
3123 astman_append(s, "Response: Success\r\n%s"
3124 "Events: Off\r\n\r\n", id_text);
3129 astman_append(s, "Response: Success\r\n%s"
3130 "Events: On\r\n\r\n", id_text);
3132 astman_append(s, "Response: Success\r\n%s"
3133 "Events: Off\r\n\r\n", id_text);
3135 astman_send_error(s, m, "Invalid event mask");
3140 static int action_logoff(struct mansession *s, const struct message *m)
3142 astman_send_response(s, m, "Goodbye", "Thanks for all the fish.");
3146 static int action_login(struct mansession *s, const struct message *m)
3149 /* still authenticated - don't process again */
3150 if (s->session->authenticated) {
3151 astman_send_ack(s, m, "Already authenticated");
3155 if (authenticate(s, m)) {
3157 astman_send_error(s, m, "Authentication failed");
3160 s->session->authenticated = 1;
3161 ast_atomic_fetchadd_int(&unauth_sessions, -1);
3162 if (manager_displayconnects(s->session)) {
3163 ast_verb(2, "%sManager '%s' logged on from %s\n", (s->session->managerid ? "HTTP " : ""), s->session->username, ast_inet_ntoa(s->session->sin.sin_addr));
3165 astman_send_ack(s, m, "Authentication accepted");
3166 if ((s->session->send_events & EVENT_FLAG_SYSTEM)
3167 && ast_test_flag(&ast_options, AST_OPT_FLAG_FULLY_BOOTED)) {
3168 struct ast_str *auth = ast_str_alloca(80);
3169 const char *cat_str = authority_to_str(EVENT_FLAG_SYSTEM, &auth);
3170 astman_append(s, "Event: FullyBooted\r\n"
3172 "Status: Fully Booted\r\n\r\n", cat_str);
3177 static int action_challenge(struct mansession *s, const struct message *m)
3179 const char *authtype = astman_get_header(m, "AuthType");
3181 if (!strcasecmp(authtype, "MD5")) {
3182 if (ast_strlen_zero(s->session->challenge)) {
3183 snprintf(s->session->challenge, sizeof(s->session->challenge), "%ld", ast_random());
3186 astman_start_ack(s, m);
3187 astman_append(s, "Challenge: %s\r\n\r\n", s->session->challenge);
3188 mansession_unlock(s);
3190 astman_send_error(s, m, "Must specify AuthType");
3195 static int action_hangup(struct mansession *s, const struct message *m)
3197 struct ast_channel *c = NULL;
3198 int causecode = 0; /* all values <= 0 mean 'do not set hangupcause in channel' */
3199 const char *id = astman_get_header(m, "ActionID");
3200 const char *name_or_regex = astman_get_header(m, "Channel");
3201 const char *cause = astman_get_header(m, "Cause");
3202 char idText[256] = "";
3204 struct ast_channel_iterator *iter = NULL;
3205 struct ast_str *regex_string;
3206 int channels_matched = 0;
3208 if (ast_strlen_zero(name_or_regex)) {
3209 astman_send_error(s, m, "No channel specified");
3213 if (!ast_strlen_zero(id)) {
3214 snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
3217 if (!ast_strlen_zero(cause)) {
3219 causecode = strtol(cause, &endptr, 10);
3220 if (causecode < 0 || causecode > 127 || *endptr != '\0') {
3221 ast_log(LOG_NOTICE, "Invalid 'Cause: %s' in manager action Hangup\n", cause);
3222 /* keep going, better to hangup without cause than to not hang up at all */
3223 causecode = 0; /* do not set channel's hangupcause */
3227 /************************************************/
3228 /* Regular explicit match channel byname hangup */
3230 if (name_or_regex[0] != '/') {
3231 if (!(c = ast_channel_get_by_name(name_or_regex))) {
3232 ast_log(LOG_NOTICE, "!!!!!!!!!! Can't find channel to hang up!\n");
3233 astman_send_error(s, m, "No such channel");
3237 ast_verb(3, "%sManager '%s' from %s, hanging up channel: %s\n",
3238 (s->session->managerid ? "HTTP " : ""),
3239 s->session->username,
3240 ast_inet_ntoa(s->session->sin.sin_addr),
3241 ast_channel_name(c));
3243 ast_channel_softhangup_withcause_locked(c, causecode);
3244 c = ast_channel_unref(c);
3246 astman_send_ack(s, m, "Channel Hungup");
3251 /***********************************************/
3252 /* find and hangup any channels matching regex */
3254 regex_string = ast_str_create(strlen(name_or_regex));
3256 /* Make "/regex/" into "regex" */
3257 if (ast_regex_string_to_regex_pattern(name_or_regex, regex_string) != 0) {
3258 astman_send_error(s, m, "Regex format invalid, Channel param should be /regex/");
3259 ast_free(regex_string);
3263 /* if regex compilation fails, hangup fails */
3264 if (regcomp(®exbuf, ast_str_buffer(regex_string), REG_EXTENDED | REG_NOSUB)) {
3265 astman_send_error_va(s, m, "Regex compile failed on: %s\n", name_or_regex);
3266 ast_free(regex_string);
3270 astman_send_listack(s, m, "Channels hung up will follow", "start");
3272 for (iter = ast_channel_iterator_all_new(); iter && (c = ast_channel_iterator_next(iter)); ) {
3273 if (regexec(®exbuf, ast_channel_name(c), 0, NULL, 0)) {
3274 ast_channel_unref(c);
3278 ast_verb(3, "%sManager '%s' from %s, hanging up channel: %s\n",
3279 (s->session->managerid ? "HTTP " : ""),
3280 s->session->username,
3281 ast_inet_ntoa(s->session->sin.sin_addr),
3282 ast_channel_name(c));
3284 ast_channel_softhangup_withcause_locked(c, causecode);
3288 "Event: ChannelHungup\r\n"
3291 "\r\n", ast_channel_name(c), idText);
3293 ast_channel_unref(c);
3296 ast_channel_iterator_destroy(iter);
3298 ast_free(regex_string);
3301 "Event: ChannelsHungupListComplete\r\n"
3302 "EventList: Complete\r\n"
3305 "\r\n", channels_matched, idText);
3310 static int action_setvar(struct mansession *s, const struct message *m)
3312 struct ast_channel *c = NULL;
3313 const char *name = astman_get_header(m, "Channel");
3314 const char *varname = astman_get_header(m, "Variable");
3315 const char *varval = astman_get_header(m, "Value");
3318 if (ast_strlen_zero(varname)) {
3319 astman_send_error(s, m, "No variable specified");
3323 if (!ast_strlen_zero(name)) {
3324 if (!(c = ast_channel_get_by_name(name))) {
3325 astman_send_error(s, m, "No such channel");
3330 res = pbx_builtin_setvar_helper(c, varname, S_OR(varval, ""));
3333 c = ast_channel_unref(c);
3336 astman_send_ack(s, m, "Variable Set");
3338 astman_send_error(s, m, "Variable not set");
3343 static int action_getvar(struct mansession *s, const struct message *m)
3345 struct ast_channel *c = NULL;
3346 const char *name = astman_get_header(m, "Channel");
3347 const char *varname = astman_get_header(m, "Variable");
3349 char workspace[1024];
3351 if (ast_strlen_zero(varname)) {
3352 astman_send_error(s, m, "No variable specified");
3356 /* We don't want users with insufficient permissions using certain functions. */
3357 if (!(function_capable_string_allowed_with_auths(varname, s->session->writeperm))) {
3358 astman_send_error(s, m, "GetVar Access Forbidden: Variable");
3362 if (!ast_strlen_zero(name)) {
3363 if (!(c = ast_channel_get_by_name(name))) {
3364 astman_send_error(s, m, "No such channel");
3369 workspace[0] = '\0';
3370 if (varname[strlen(varname) - 1] == ')') {
3372 c = ast_dummy_channel_alloc();
3374 ast_func_read(c, (char *) varname, workspace, sizeof(workspace));
3376 ast_log(LOG_ERROR, "Unable to allocate bogus channel for variable substitution. Function results may be blank.\n");
3378 ast_func_read(c, (char *) varname, workspace, sizeof(workspace));
3382 pbx_retrieve_variable(c, varname, &varval, workspace, sizeof(workspace), NULL);
3386 c = ast_channel_unref(c);
3389 astman_start_ack(s, m);
3390 astman_append(s, "Variable: %s\r\nValue: %s\r\n\r\n", varname, S_OR(varval, ""));
3395 /*! \brief Manager "status" command to show channels */
3396 /* Needs documentation... */
3397 static int action_status(struct mansession *s, const struct message *m)
3399 const char *name = astman_get_header(m, "Channel");
3400 const char *cvariables = astman_get_header(m, "Variables");
3401 char *variables = ast_strdupa(S_OR(cvariables, ""));
3402 struct ast_channel *c;
3404 struct timeval now = ast_tvnow();
3405 long elapsed_seconds = 0;
3407 int all = ast_strlen_zero(name); /* set if we want all channels */
3408 const char *id = astman_get_header(m, "ActionID");
3410 AST_DECLARE_APP_ARGS(vars,
3411 AST_APP_ARG(name)[100];
3413 struct ast_str *str = ast_str_create(1000);
3414 struct ast_channel_iterator *iter = NULL;
3416 if (!ast_strlen_zero(id)) {
3417 snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
3422 if (!(function_capable_string_allowed_with_auths(variables, s->session->writeperm))) {
3423 astman_send_error(s, m, "Status Access Forbidden: Variables");
3428 if (!(iter = ast_channel_iterator_all_new())) {
3430 astman_send_error(s, m, "Memory Allocation Failure");
3433 c = ast_channel_iterator_next(iter);
3435 if (!(c = ast_channel_get_by_name(name))) {
3436 astman_send_error(s, m, "No such channel");
3442 astman_send_ack(s, m, "Channel status will follow");
3444 if (!ast_strlen_zero(cvariables)) {
3445 AST_STANDARD_APP_ARGS(vars, variables);
3448 /* if we look by name, we break after the first iteration */
3449 for (; c; c = ast_channel_iterator_next(iter)) {
3450 ast_channel_lock(c);
3452 if (!ast_strlen_zero(cvariables)) {
3455 for (i = 0; i < vars.argc; i++) {
3456 char valbuf[512], *ret = NULL;
3458 if (vars.name[i][strlen(vars.name[i]) - 1] == ')') {
3459 if (ast_func_read(c, vars.name[i], valbuf, sizeof(valbuf)) < 0) {
3464 pbx_retrieve_variable(c, vars.name[i], &ret, valbuf, sizeof(valbuf), NULL);
3467 ast_str_append(&str, 0, "Variable: %s=%s\r\n", vars.name[i], ret);
3472 if (ast_channel_internal_bridged_channel(c)) {
3473 snprintf(bridge, sizeof(bridge), "BridgedChannel: %s\r\nBridgedUniqueid: %s\r\n", ast_channel_name(ast_channel_internal_bridged_channel(c)), ast_channel_uniqueid(ast_channel_internal_bridged_channel(c)));
3477 if (ast_channel_pbx(c)) {
3478 if (ast_channel_cdr(c)) {
3479 elapsed_seconds = now.tv_sec - ast_channel_cdr(c)->start.tv_sec;
3483 "Privilege: Call\r\n"
3485 "CallerIDNum: %s\r\n"
3486 "CallerIDName: %s\r\n"
3487 "ConnectedLineNum: %s\r\n"
3488 "ConnectedLineName: %s\r\n"
3489 "Accountcode: %s\r\n"
3490 "ChannelState: %d\r\n"
3491 "ChannelStateDesc: %s\r\n"