2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2006, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
21 * \brief The Asterisk Management Interface - AMI
23 * \author Mark Spencer <markster@digium.com>
25 * OpenSSL http://www.openssl.org - for AMI/SSL
27 * At the moment this file contains a number of functions, namely:
29 * - data structures storing AMI state
30 * - AMI-related API functions, used by internal asterisk components
31 * - handlers for AMI-related CLI functions
32 * - handlers for AMI functions (available through the AMI socket)
33 * - the code for the main AMI listener thread and individual session threads
34 * - the http handlers invoked for AMI-over-HTTP by the threads in main/http.c
39 /*! \li \ref manager.c uses the configuration file \ref manager.conf and \ref users.conf
40 * \addtogroup configuration_file
43 /*! \page manager.conf manager.conf
44 * \verbinclude manager.conf.sample
47 /*! \page users.conf users.conf
48 * \verbinclude users.conf.sample
52 <support_level>core</support_level>
57 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
59 #include "asterisk/_private.h"
60 #include "asterisk/paths.h" /* use various ast_config_AST_* */
65 #include <sys/types.h>
68 #include "asterisk/channel.h"
69 #include "asterisk/file.h"
70 #include "asterisk/manager.h"
71 #include "asterisk/module.h"
72 #include "asterisk/config.h"
73 #include "asterisk/callerid.h"
74 #include "asterisk/lock.h"
75 #include "asterisk/cli.h"
76 #include "asterisk/app.h"
77 #include "asterisk/pbx.h"
78 #include "asterisk/md5.h"
79 #include "asterisk/acl.h"
80 #include "asterisk/utils.h"
81 #include "asterisk/tcptls.h"
82 #include "asterisk/http.h"
83 #include "asterisk/ast_version.h"
84 #include "asterisk/threadstorage.h"
85 #include "asterisk/linkedlists.h"
86 #include "asterisk/term.h"
87 #include "asterisk/astobj2.h"
88 #include "asterisk/features.h"
89 #include "asterisk/security_events.h"
90 #include "asterisk/event.h"
91 #include "asterisk/aoc.h"
92 #include "asterisk/stringfields.h"
93 #include "asterisk/presencestate.h"
96 <manager name="Ping" language="en_US">
101 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
104 <para>A 'Ping' action will ellicit a 'Pong' response. Used to keep the
105 manager connection open.</para>
108 <manager name="Events" language="en_US">
113 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
114 <parameter name="EventMask" required="true">
117 <para>If all events should be sent.</para>
120 <para>If no events should be sent.</para>
122 <enum name="system,call,log,...">
123 <para>To select which flags events should have to be sent.</para>
129 <para>Enable/Disable sending of events to this manager client.</para>
132 <manager name="Logoff" language="en_US">
137 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
140 <para>Logoff the current manager session.</para>
143 <manager name="Login" language="en_US">
148 <parameter name="ActionID">
149 <para>ActionID for this transaction. Will be returned.</para>
151 <parameter name="Username" required="true">
152 <para>Username to login with as specified in manager.conf.</para>
154 <parameter name="Secret">
155 <para>Secret to login with as specified in manager.conf.</para>
159 <para>Login Manager.</para>
162 <manager name="Challenge" language="en_US">
164 Generate Challenge for MD5 Auth.
167 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
168 <parameter name="AuthType" required="true">
169 <para>Digest algorithm to use in the challenge. Valid values are:</para>
176 <para>Generate a challenge for MD5 authentication.</para>
179 <manager name="Hangup" language="en_US">
184 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
185 <parameter name="Channel" required="true">
186 <para>The exact channel name to be hungup, or to use a regular expression, set this parameter to: /regex/</para>
187 <para>Example exact channel: SIP/provider-0000012a</para>
188 <para>Example regular expression: /^SIP/provider-.*$/</para>
190 <parameter name="Cause">
191 <para>Numeric hangup cause.</para>
195 <para>Hangup a channel.</para>
198 <manager name="Status" language="en_US">
203 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
204 <parameter name="Channel" required="true">
205 <para>The name of the channel to query for status.</para>
207 <parameter name="Variables">
208 <para>Comma <literal>,</literal> separated list of variable to include.</para>
212 <para>Will return the status information of each channel along with the
213 value for the specified channel variables.</para>
216 <manager name="Setvar" language="en_US">
218 Set a channel variable.
221 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
222 <parameter name="Channel">
223 <para>Channel to set variable for.</para>
225 <parameter name="Variable" required="true">
226 <para>Variable name.</para>
228 <parameter name="Value" required="true">
229 <para>Variable value.</para>
233 <para>Set a global or local channel variable.</para>
235 <para>If a channel name is not provided then the variable is global.</para>
239 <manager name="Getvar" language="en_US">
241 Gets a channel variable.
244 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
245 <parameter name="Channel">
246 <para>Channel to read variable from.</para>
248 <parameter name="Variable" required="true">
249 <para>Variable name.</para>
253 <para>Get the value of a global or local channel variable.</para>
255 <para>If a channel name is not provided then the variable is global.</para>
259 <manager name="GetConfig" language="en_US">
261 Retrieve configuration.
264 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
265 <parameter name="Filename" required="true">
266 <para>Configuration filename (e.g. <filename>foo.conf</filename>).</para>
268 <parameter name="Category">
269 <para>Category in configuration file.</para>
273 <para>This action will dump the contents of a configuration
274 file by category and contents or optionally by specified category only.</para>
277 <manager name="GetConfigJSON" language="en_US">
279 Retrieve configuration (JSON format).
282 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
283 <parameter name="Filename" required="true">
284 <para>Configuration filename (e.g. <filename>foo.conf</filename>).</para>
288 <para>This action will dump the contents of a configuration file by category
289 and contents in JSON format. This only makes sense to be used using rawman over
290 the HTTP interface.</para>
293 <manager name="UpdateConfig" language="en_US">
295 Update basic configuration.
298 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
299 <parameter name="SrcFilename" required="true">
300 <para>Configuration filename to read (e.g. <filename>foo.conf</filename>).</para>
302 <parameter name="DstFilename" required="true">
303 <para>Configuration filename to write (e.g. <filename>foo.conf</filename>)</para>
305 <parameter name="Reload">
306 <para>Whether or not a reload should take place (or name of specific module).</para>
308 <parameter name="Action-XXXXXX">
309 <para>Action to take.</para>
310 <para>X's represent 6 digit number beginning with 000000.</para>
312 <enum name="NewCat" />
313 <enum name="RenameCat" />
314 <enum name="DelCat" />
315 <enum name="EmptyCat" />
316 <enum name="Update" />
317 <enum name="Delete" />
318 <enum name="Append" />
319 <enum name="Insert" />
322 <parameter name="Cat-XXXXXX">
323 <para>Category to operate on.</para>
324 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-XXXXXX']/para[2])" />
326 <parameter name="Var-XXXXXX">
327 <para>Variable to work on.</para>
328 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-XXXXXX']/para[2])" />
330 <parameter name="Value-XXXXXX">
331 <para>Value to work on.</para>
332 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-XXXXXX']/para[2])" />
334 <parameter name="Match-XXXXXX">
335 <para>Extra match required to match line.</para>
336 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-XXXXXX']/para[2])" />
338 <parameter name="Line-XXXXXX">
339 <para>Line in category to operate on (used with delete and insert actions).</para>
340 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-XXXXXX']/para[2])" />
344 <para>This action will modify, create, or delete configuration elements
345 in Asterisk configuration files.</para>
348 <manager name="CreateConfig" language="en_US">
350 Creates an empty file in the configuration directory.
353 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
354 <parameter name="Filename" required="true">
355 <para>The configuration filename to create (e.g. <filename>foo.conf</filename>).</para>
359 <para>This action will create an empty file in the configuration
360 directory. This action is intended to be used before an UpdateConfig
364 <manager name="ListCategories" language="en_US">
366 List categories in configuration file.
369 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
370 <parameter name="Filename" required="true">
371 <para>Configuration filename (e.g. <filename>foo.conf</filename>).</para>
375 <para>This action will dump the categories in a given file.</para>
378 <manager name="Redirect" language="en_US">
380 Redirect (transfer) a call.
383 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
384 <parameter name="Channel" required="true">
385 <para>Channel to redirect.</para>
387 <parameter name="ExtraChannel">
388 <para>Second call leg to transfer (optional).</para>
390 <parameter name="Exten" required="true">
391 <para>Extension to transfer to.</para>
393 <parameter name="ExtraExten">
394 <para>Extension to transfer extrachannel to (optional).</para>
396 <parameter name="Context" required="true">
397 <para>Context to transfer to.</para>
399 <parameter name="ExtraContext">
400 <para>Context to transfer extrachannel to (optional).</para>
402 <parameter name="Priority" required="true">
403 <para>Priority to transfer to.</para>
405 <parameter name="ExtraPriority">
406 <para>Priority to transfer extrachannel to (optional).</para>
410 <para>Redirect (transfer) a call.</para>
413 <manager name="Atxfer" language="en_US">
418 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
419 <parameter name="Channel" required="true">
420 <para>Transferer's channel.</para>
422 <parameter name="Exten" required="true">
423 <para>Extension to transfer to.</para>
425 <parameter name="Context" required="true">
426 <para>Context to transfer to.</para>
428 <parameter name="Priority" required="true">
429 <para>Priority to transfer to.</para>
433 <para>Attended transfer.</para>
436 <manager name="Originate" language="en_US">
441 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
442 <parameter name="Channel" required="true">
443 <para>Channel name to call.</para>
445 <parameter name="Exten">
446 <para>Extension to use (requires <literal>Context</literal> and
447 <literal>Priority</literal>)</para>
449 <parameter name="Context">
450 <para>Context to use (requires <literal>Exten</literal> and
451 <literal>Priority</literal>)</para>
453 <parameter name="Priority">
454 <para>Priority to use (requires <literal>Exten</literal> and
455 <literal>Context</literal>)</para>
457 <parameter name="Application">
458 <para>Application to execute.</para>
460 <parameter name="Data">
461 <para>Data to use (requires <literal>Application</literal>).</para>
463 <parameter name="Timeout" default="30000">
464 <para>How long to wait for call to be answered (in ms.).</para>
466 <parameter name="CallerID">
467 <para>Caller ID to be set on the outgoing channel.</para>
469 <parameter name="Variable">
470 <para>Channel variable to set, multiple Variable: headers are allowed.</para>
472 <parameter name="Account">
473 <para>Account code.</para>
475 <parameter name="EarlyMedia">
476 <para>Set to <literal>true</literal> to force call bridge on early media..</para>
478 <parameter name="Async">
479 <para>Set to <literal>true</literal> for fast origination.</para>
481 <parameter name="Codecs">
482 <para>Comma-separated list of codecs to use for this call.</para>
486 <para>Generates an outgoing call to a
487 <replaceable>Extension</replaceable>/<replaceable>Context</replaceable>/<replaceable>Priority</replaceable>
488 or <replaceable>Application</replaceable>/<replaceable>Data</replaceable></para>
491 <ref type="managerEvent">OriginateResponse</ref>
494 <managerEvent language="en_US" name="OriginateResponse">
495 <managerEventInstance class="EVENT_FLAG_CALL">
496 <synopsis>Raised in response to an Originate command.</synopsis>
498 <parameter name="ActionID" required="false"/>
499 <parameter name="Resonse">
501 <enum name="Failure"/>
502 <enum name="Success"/>
505 <parameter name="Channel"/>
506 <parameter name="Context"/>
507 <parameter name="Exten"/>
508 <parameter name="Reason"/>
509 <parameter name="Uniqueid"/>
510 <parameter name="CallerIDNum"/>
511 <parameter name="CallerIDName"/>
514 <ref type="manager">Originate</ref>
516 </managerEventInstance>
518 <manager name="Command" language="en_US">
520 Execute Asterisk CLI Command.
523 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
524 <parameter name="Command" required="true">
525 <para>Asterisk CLI command to run.</para>
529 <para>Run a CLI command.</para>
532 <manager name="ExtensionState" language="en_US">
534 Check Extension Status.
537 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
538 <parameter name="Exten" required="true">
539 <para>Extension to check state on.</para>
541 <parameter name="Context" required="true">
542 <para>Context for extension.</para>
546 <para>Report the extension state for given extension. If the extension has a hint,
547 will use devicestate to check the status of the device connected to the extension.</para>
548 <para>Will return an <literal>Extension Status</literal> message. The response will include
549 the hint for the extension and the status.</para>
552 <manager name="PresenceState" language="en_US">
557 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
558 <parameter name="Provider" required="true">
559 <para>Presence Provider to check the state of</para>
563 <para>Report the presence state for the given presence provider.</para>
564 <para>Will return a <literal>Presence State</literal> message. The response will include the
565 presence state and, if set, a presence subtype and custom message.</para>
568 <manager name="AbsoluteTimeout" language="en_US">
570 Set absolute timeout.
573 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
574 <parameter name="Channel" required="true">
575 <para>Channel name to hangup.</para>
577 <parameter name="Timeout" required="true">
578 <para>Maximum duration of the call (sec).</para>
582 <para>Hangup a channel after a certain time. Acknowledges set time with
583 <literal>Timeout Set</literal> message.</para>
586 <manager name="MailboxStatus" language="en_US">
591 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
592 <parameter name="Mailbox" required="true">
593 <para>Full mailbox ID <replaceable>mailbox</replaceable>@<replaceable>vm-context</replaceable>.</para>
597 <para>Checks a voicemail account for status.</para>
598 <para>Returns whether there are messages waiting.</para>
599 <para>Message: Mailbox Status.</para>
600 <para>Mailbox: <replaceable>mailboxid</replaceable>.</para>
601 <para>Waiting: <literal>0</literal> if messages waiting, <literal>1</literal>
602 if no messages waiting.</para>
605 <manager name="MailboxCount" language="en_US">
607 Check Mailbox Message Count.
610 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
611 <parameter name="Mailbox" required="true">
612 <para>Full mailbox ID <replaceable>mailbox</replaceable>@<replaceable>vm-context</replaceable>.</para>
616 <para>Checks a voicemail account for new messages.</para>
617 <para>Returns number of urgent, new and old messages.</para>
618 <para>Message: Mailbox Message Count</para>
619 <para>Mailbox: <replaceable>mailboxid</replaceable></para>
620 <para>UrgentMessages: <replaceable>count</replaceable></para>
621 <para>NewMessages: <replaceable>count</replaceable></para>
622 <para>OldMessages: <replaceable>count</replaceable></para>
625 <manager name="ListCommands" language="en_US">
627 List available manager commands.
630 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
633 <para>Returns the action name and synopsis for every action that
634 is available to the user.</para>
637 <manager name="SendText" language="en_US">
639 Send text message to channel.
642 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
643 <parameter name="Channel" required="true">
644 <para>Channel to send message to.</para>
646 <parameter name="Message" required="true">
647 <para>Message to send.</para>
651 <para>Sends A Text Message to a channel while in a call.</para>
654 <manager name="UserEvent" language="en_US">
656 Send an arbitrary event.
659 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
660 <parameter name="UserEvent" required="true">
661 <para>Event string to send.</para>
663 <parameter name="Header1">
664 <para>Content1.</para>
666 <parameter name="HeaderN">
667 <para>ContentN.</para>
671 <para>Send an event to manager sessions.</para>
674 <manager name="WaitEvent" language="en_US">
676 Wait for an event to occur.
679 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
680 <parameter name="Timeout" required="true">
681 <para>Maximum time (in seconds) to wait for events, <literal>-1</literal> means forever.</para>
685 <para>This action will ellicit a <literal>Success</literal> response. Whenever
686 a manager event is queued. Once WaitEvent has been called on an HTTP manager
687 session, events will be generated and queued.</para>
690 <manager name="CoreSettings" language="en_US">
692 Show PBX core settings (version etc).
695 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
698 <para>Query for Core PBX settings.</para>
701 <manager name="CoreStatus" language="en_US">
703 Show PBX core status variables.
706 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
709 <para>Query for Core PBX status.</para>
712 <manager name="Reload" language="en_US">
717 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
718 <parameter name="Module">
719 <para>Name of the module to reload.</para>
723 <para>Send a reload event.</para>
726 <manager name="CoreShowChannels" language="en_US">
728 List currently active channels.
731 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
734 <para>List currently defined channels and some information about them.</para>
737 <manager name="ModuleLoad" language="en_US">
742 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
743 <parameter name="Module">
744 <para>Asterisk module name (including .so extension) or subsystem identifier:</para>
747 <enum name="dnsmgr" />
748 <enum name="extconfig" />
751 <enum name="manager" />
753 <enum name="logger" />
754 <enum name="features" />
756 <enum name="udptl" />
757 <enum name="indications" />
762 <parameter name="LoadType" required="true">
763 <para>The operation to be done on module. Subsystem identifiers may only
767 <enum name="unload" />
768 <enum name="reload" />
770 <para>If no module is specified for a <literal>reload</literal> loadtype,
771 all modules are reloaded.</para>
775 <para>Loads, unloads or reloads an Asterisk module in a running system.</para>
778 <manager name="ModuleCheck" language="en_US">
780 Check if module is loaded.
783 <parameter name="Module" required="true">
784 <para>Asterisk module name (not including extension).</para>
788 <para>Checks if Asterisk module is loaded. Will return Success/Failure.
789 For success returns, the module revision number is included.</para>
792 <manager name="AOCMessage" language="en_US">
794 Generate an Advice of Charge message on a channel.
797 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
798 <parameter name="Channel" required="true">
799 <para>Channel name to generate the AOC message on.</para>
801 <parameter name="ChannelPrefix">
802 <para>Partial channel prefix. By using this option one can match the beginning part
803 of a channel name without having to put the entire name in. For example
804 if a channel name is SIP/snom-00000001 and this value is set to SIP/snom, then
805 that channel matches and the message will be sent. Note however that only
806 the first matched channel has the message sent on it. </para>
808 <parameter name="MsgType" required="true">
809 <para>Defines what type of AOC message to create, AOC-D or AOC-E</para>
815 <parameter name="ChargeType" required="true">
816 <para>Defines what kind of charge this message represents.</para>
820 <enum name="Currency" />
824 <parameter name="UnitAmount(0)">
825 <para>This represents the amount of units charged. The ETSI AOC standard specifies that
826 this value along with the optional UnitType value are entries in a list. To accommodate this
827 these values take an index value starting at 0 which can be used to generate this list of
828 unit entries. For Example, If two unit entires were required this could be achieved by setting the
829 paramter UnitAmount(0)=1234 and UnitAmount(1)=5678. Note that UnitAmount at index 0 is
830 required when ChargeType=Unit, all other entries in the list are optional.
833 <parameter name="UnitType(0)">
834 <para>Defines the type of unit. ETSI AOC standard specifies this as an integer
835 value between 1 and 16, but this value is left open to accept any positive
836 integer. Like the UnitAmount parameter, this value represents a list entry
837 and has an index parameter that starts at 0.
840 <parameter name="CurrencyName">
841 <para>Specifies the currency's name. Note that this value is truncated after 10 characters.</para>
843 <parameter name="CurrencyAmount">
844 <para>Specifies the charge unit amount as a positive integer. This value is required
845 when ChargeType==Currency.</para>
847 <parameter name="CurrencyMultiplier">
848 <para>Specifies the currency multiplier. This value is required when ChargeType==Currency.</para>
850 <enum name="OneThousandth" />
851 <enum name="OneHundredth" />
852 <enum name="OneTenth" />
855 <enum name="Hundred" />
856 <enum name="Thousand" />
859 <parameter name="TotalType" default="Total">
860 <para>Defines what kind of AOC-D total is represented.</para>
862 <enum name="Total" />
863 <enum name="SubTotal" />
866 <parameter name="AOCBillingId">
867 <para>Represents a billing ID associated with an AOC-D or AOC-E message. Note
868 that only the first 3 items of the enum are valid AOC-D billing IDs</para>
870 <enum name="Normal" />
871 <enum name="ReverseCharge" />
872 <enum name="CreditCard" />
873 <enum name="CallFwdUnconditional" />
874 <enum name="CallFwdBusy" />
875 <enum name="CallFwdNoReply" />
876 <enum name="CallDeflection" />
877 <enum name="CallTransfer" />
880 <parameter name="ChargingAssociationId">
881 <para>Charging association identifier. This is optional for AOC-E and can be
882 set to any value between -32768 and 32767</para>
884 <parameter name="ChargingAssociationNumber">
885 <para>Represents the charging association party number. This value is optional
888 <parameter name="ChargingAssociationPlan">
889 <para>Integer representing the charging plan associated with the ChargingAssociationNumber.
890 The value is bits 7 through 1 of the Q.931 octet containing the type-of-number and
891 numbering-plan-identification fields.</para>
895 <para>Generates an AOC-D or AOC-E message on a channel.</para>
898 <function name="AMI_CLIENT" language="en_US">
900 Checks attributes of manager accounts
903 <parameter name="loginname" required="true">
904 <para>Login name, specified in manager.conf</para>
906 <parameter name="field" required="true">
907 <para>The manager account attribute to return</para>
909 <enum name="sessions"><para>The number of sessions for this AMI account</para></enum>
915 Currently, the only supported parameter is "sessions" which will return the current number of
916 active sessions for this AMI account.
920 <manager name="Filter" language="en_US">
922 Dynamically add filters for the current manager session.
925 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
926 <parameter name="Operation">
929 <para>Add a filter.</para>
933 <parameter name="Filter">
934 <para>Filters can be whitelist or blacklist</para>
935 <para>Example whitelist filter: "Event: Newchannel"</para>
936 <para>Example blacklist filter: "!Channel: DAHDI.*"</para>
937 <para>This filter option is used to whitelist or blacklist events per user to be
938 reported with regular expressions and are allowed if both the regex matches
939 and the user has read access as defined in manager.conf. Filters are assumed to be for whitelisting
940 unless preceeded by an exclamation point, which marks it as being black.
941 Evaluation of the filters is as follows:</para>
942 <para>- If no filters are configured all events are reported as normal.</para>
943 <para>- If there are white filters only: implied black all filter processed first, then white filters.</para>
944 <para>- If there are black filters only: implied white all filter processed first, then black filters.</para>
945 <para>- If there are both white and black filters: implied black all filter processed first, then white
946 filters, and lastly black filters.</para>
950 <para>The filters added are only used for the current session.
951 Once the connection is closed the filters are removed.</para>
952 <para>This comand requires the system permission because
953 this command can be used to create filters that may bypass
954 filters defined in manager.conf</para>
957 <manager name="FilterList" language="en_US">
959 Show current event filters for this session
962 <para>The filters displayed are for the current session. Only those filters defined in
963 manager.conf will be present upon starting a new session.</para>
968 /*! \addtogroup Group_AMI AMI functions
976 UNSPECIFIED_CATEGORY,
977 UNSPECIFIED_ARGUMENT,
987 enum add_filter_result {
994 * Linked list of events.
995 * Global events are appended to the list by append_event().
996 * The usecount is the number of stored pointers to the element,
997 * excluding the list pointers. So an element that is only in
998 * the list has a usecount of 0, not 1.
1000 * Clients have a pointer to the last event processed, and for each
1001 * of these clients we track the usecount of the elements.
1002 * If we have a pointer to an entry in the list, it is safe to navigate
1003 * it forward because elements will not be deleted, but only appended.
1004 * The worst that can happen is seeing the pointer still NULL.
1006 * When the usecount of an element drops to 0, and the element is the
1007 * first in the list, we can remove it. Removal is done within the
1008 * main thread, which is woken up for the purpose.
1010 * For simplicity of implementation, we make sure the list is never empty.
1013 int usecount; /*!< # of clients who still need the event */
1015 unsigned int seq; /*!< sequence number */
1016 struct timeval tv; /*!< When event was allocated */
1017 AST_RWLIST_ENTRY(eventqent) eq_next;
1018 char eventdata[1]; /*!< really variable size, allocated by append_event() */
1021 static AST_RWLIST_HEAD_STATIC(all_events, eventqent);
1023 static int displayconnects = 1;
1024 static int allowmultiplelogin = 1;
1025 static int timestampevents;
1026 static int httptimeout = 60;
1027 static int broken_events_action = 0;
1028 static int manager_enabled = 0;
1029 static int webmanager_enabled = 0;
1030 static int manager_debug = 0; /*!< enable some debugging code in the manager */
1031 static int authtimeout;
1032 static int authlimit;
1033 static char *manager_channelvars;
1035 #define DEFAULT_REALM "asterisk"
1036 static char global_realm[MAXHOSTNAMELEN]; /*!< Default realm */
1038 static int block_sockets;
1039 static int unauth_sessions = 0;
1040 static struct ast_event_sub *acl_change_event_subscription;
1042 #define MGR_SHOW_TERMINAL_WIDTH 80
1045 * Descriptor for a manager session, either on the AMI socket or over HTTP.
1048 * AMI session have managerid == 0; the entry is created upon a connect,
1049 * and destroyed with the socket.
1050 * HTTP sessions have managerid != 0, the value is used as a search key
1051 * to lookup sessions (using the mansession_id cookie, or nonce key from
1052 * Digest Authentication http header).
1054 #define MAX_BLACKLIST_CMD_LEN 2
1055 static const struct {
1056 const char *words[AST_MAX_CMD_LEN];
1057 } command_blacklist[] = {
1058 {{ "module", "load", NULL }},
1059 {{ "module", "unload", NULL }},
1060 {{ "restart", "gracefully", NULL }},
1063 static void acl_change_event_cb(const struct ast_event *event, void *userdata);
1065 static void acl_change_event_subscribe(void)
1067 if (!acl_change_event_subscription) {
1068 acl_change_event_subscription = ast_event_subscribe(AST_EVENT_ACL_CHANGE,
1069 acl_change_event_cb, "Manager must react to Named ACL changes", NULL, AST_EVENT_IE_END);
1073 static void acl_change_event_unsubscribe(void)
1075 if (acl_change_event_subscription) {
1076 acl_change_event_subscription = ast_event_unsubscribe(acl_change_event_subscription);
1080 /* In order to understand what the heck is going on with the
1081 * mansession_session and mansession structs, we need to have a bit of a history
1084 * In the beginning, there was the mansession. The mansession contained data that was
1085 * intrinsic to a manager session, such as the time that it started, the name of the logged-in
1086 * user, etc. In addition to these parameters were the f and fd parameters. For typical manager
1087 * sessions, these were used to represent the TCP socket over which the AMI session was taking
1088 * place. It makes perfect sense for these fields to be a part of the session-specific data since
1089 * the session actually defines this information.
1091 * Then came the HTTP AMI sessions. With these, the f and fd fields need to be opened and closed
1092 * for every single action that occurs. Thus the f and fd fields aren't really specific to the session
1093 * but rather to the action that is being executed. Because a single session may execute many commands
1094 * at once, some sort of safety needed to be added in order to be sure that we did not end up with fd
1095 * leaks from one action overwriting the f and fd fields used by a previous action before the previous action
1096 * has had a chance to properly close its handles.
1098 * The initial idea to solve this was to use thread synchronization, but this prevented multiple actions
1099 * from being run at the same time in a single session. Some manager actions may block for a long time, thus
1100 * creating a large queue of actions to execute. In addition, this fix did not address the basic architectural
1101 * issue that for HTTP manager sessions, the f and fd variables are not really a part of the session, but are
1102 * part of the action instead.
1104 * The new idea was to create a structure on the stack for each HTTP Manager action. This structure would
1105 * contain the action-specific information, such as which file to write to. In order to maintain expectations
1106 * of action handlers and not have to change the public API of the manager code, we would need to name this
1107 * new stacked structure 'mansession' and contain within it the old mansession struct that we used to use.
1108 * We renamed the old mansession struct 'mansession_session' to hopefully convey that what is in this structure
1109 * is session-specific data. The structure that it is wrapped in, called a 'mansession' really contains action-specific
1112 struct mansession_session {
1113 /*! \todo XXX need to document which fields it is protecting */
1114 struct ast_sockaddr addr; /*!< address we are connecting from */
1115 FILE *f; /*!< fdopen() on the underlying fd */
1116 int fd; /*!< descriptor used for output. Either the socket (AMI) or a temporary file (HTTP) */
1117 int inuse; /*!< number of HTTP sessions using this entry */
1118 int needdestroy; /*!< Whether an HTTP session should be destroyed */
1119 pthread_t waiting_thread; /*!< Sleeping thread using this descriptor */
1120 uint32_t managerid; /*!< Unique manager identifier, 0 for AMI sessions */
1121 time_t sessionstart; /*!< Session start time */
1122 struct timeval sessionstart_tv; /*!< Session start time */
1123 time_t sessiontimeout; /*!< Session timeout if HTTP */
1124 char username[80]; /*!< Logged in username */
1125 char challenge[10]; /*!< Authentication challenge */
1126 int authenticated; /*!< Authentication status */
1127 int readperm; /*!< Authorization for reading */
1128 int writeperm; /*!< Authorization for writing */
1129 char inbuf[1025]; /*!< Buffer - we use the extra byte to add a '\\0' and simplify parsing */
1130 int inlen; /*!< number of buffered bytes */
1131 struct ao2_container *whitefilters; /*!< Manager event filters - white list */
1132 struct ao2_container *blackfilters; /*!< Manager event filters - black list */
1133 struct ast_variable *chanvars; /*!< Channel variables to set for originate */
1134 int send_events; /*!< XXX what ? */
1135 struct eventqent *last_ev; /*!< last event processed. */
1136 int writetimeout; /*!< Timeout for ast_carefulwrite() */
1138 int pending_event; /*!< Pending events indicator in case when waiting_thread is NULL */
1139 time_t noncetime; /*!< Timer for nonce value expiration */
1140 unsigned long oldnonce; /*!< Stale nonce value */
1141 unsigned long nc; /*!< incremental nonce counter */
1142 AST_LIST_HEAD_NOLOCK(mansession_datastores, ast_datastore) datastores; /*!< Data stores on the session */
1143 AST_LIST_ENTRY(mansession_session) list;
1146 enum mansession_message_parsing {
1148 MESSAGE_LINE_TOO_LONG
1151 /*! \brief In case you didn't read that giant block of text above the mansession_session struct, the
1152 * \ref struct mansession is named this solely to keep the API the same in Asterisk. This structure really
1153 * represents data that is different from Manager action to Manager action. The mansession_session pointer
1154 * contained within points to session-specific data.
1157 struct mansession_session *session;
1158 struct ast_tcptls_session_instance *tcptls_session;
1161 enum mansession_message_parsing parsing;
1163 struct manager_custom_hook *hook;
1167 static struct ao2_container *sessions = NULL;
1169 struct manager_channel_variable {
1170 AST_LIST_ENTRY(manager_channel_variable) entry;
1171 unsigned int isfunc:1;
1172 char name[0]; /* allocate off the end the real size. */
1175 static AST_RWLIST_HEAD_STATIC(channelvars, manager_channel_variable);
1177 /*! \brief user descriptor, as read from the config file.
1179 * \note It is still missing some fields -- e.g. we can have multiple permit and deny
1180 * lines which are not supported here, and readperm/writeperm/writetimeout
1183 struct ast_manager_user {
1185 char *secret; /*!< Secret for logging in */
1186 int readperm; /*!< Authorization for reading */
1187 int writeperm; /*!< Authorization for writing */
1188 int writetimeout; /*!< Per user Timeout for ast_carefulwrite() */
1189 int displayconnects; /*!< XXX unused */
1190 int keep; /*!< mark entries created on a reload */
1191 struct ao2_container *whitefilters; /*!< Manager event filters - white list */
1192 struct ao2_container *blackfilters; /*!< Manager event filters - black list */
1193 struct ast_acl_list *acl; /*!< ACL setting */
1194 char *a1_hash; /*!< precalculated A1 for Digest auth */
1195 struct ast_variable *chanvars; /*!< Channel variables to set for originate */
1196 AST_RWLIST_ENTRY(ast_manager_user) list;
1199 /*! \brief list of users found in the config file */
1200 static AST_RWLIST_HEAD_STATIC(users, ast_manager_user);
1202 /*! \brief list of actions registered */
1203 static AST_RWLIST_HEAD_STATIC(actions, manager_action);
1205 /*! \brief list of hooks registered */
1206 static AST_RWLIST_HEAD_STATIC(manager_hooks, manager_custom_hook);
1208 /*! \brief A container of event documentation nodes */
1209 AO2_GLOBAL_OBJ_STATIC(event_docs);
1211 static void free_channelvars(void);
1213 static enum add_filter_result manager_add_filter(const char *filter_pattern, struct ao2_container *whitefilters, struct ao2_container *blackfilters);
1217 * \brief Find a registered action object.
1219 * \param name Name of AMI action to find.
1221 * \return Reffed action found or NULL
1223 static struct manager_action *action_find(const char *name)
1225 struct manager_action *act;
1227 AST_RWLIST_RDLOCK(&actions);
1228 AST_RWLIST_TRAVERSE(&actions, act, list) {
1229 if (!strcasecmp(name, act->action)) {
1230 ao2_t_ref(act, +1, "found action object");
1234 AST_RWLIST_UNLOCK(&actions);
1239 /*! \brief Add a custom hook to be called when an event is fired */
1240 void ast_manager_register_hook(struct manager_custom_hook *hook)
1242 AST_RWLIST_WRLOCK(&manager_hooks);
1243 AST_RWLIST_INSERT_TAIL(&manager_hooks, hook, list);
1244 AST_RWLIST_UNLOCK(&manager_hooks);
1247 /*! \brief Delete a custom hook to be called when an event is fired */
1248 void ast_manager_unregister_hook(struct manager_custom_hook *hook)
1250 AST_RWLIST_WRLOCK(&manager_hooks);
1251 AST_RWLIST_REMOVE(&manager_hooks, hook, list);
1252 AST_RWLIST_UNLOCK(&manager_hooks);
1255 int check_manager_enabled(void)
1257 return manager_enabled;
1260 int check_webmanager_enabled(void)
1262 return (webmanager_enabled && manager_enabled);
1266 * Grab a reference to the last event, update usecount as needed.
1267 * Can handle a NULL pointer.
1269 static struct eventqent *grab_last(void)
1271 struct eventqent *ret;
1273 AST_RWLIST_WRLOCK(&all_events);
1274 ret = AST_RWLIST_LAST(&all_events);
1275 /* the list is never empty now, but may become so when
1276 * we optimize it in the future, so be prepared.
1279 ast_atomic_fetchadd_int(&ret->usecount, 1);
1281 AST_RWLIST_UNLOCK(&all_events);
1286 * Purge unused events. Remove elements from the head
1287 * as long as their usecount is 0 and there is a next element.
1289 static void purge_events(void)
1291 struct eventqent *ev;
1292 struct timeval now = ast_tvnow();
1294 AST_RWLIST_WRLOCK(&all_events);
1295 while ( (ev = AST_RWLIST_FIRST(&all_events)) &&
1296 ev->usecount == 0 && AST_RWLIST_NEXT(ev, eq_next)) {
1297 AST_RWLIST_REMOVE_HEAD(&all_events, eq_next);
1301 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&all_events, ev, eq_next) {
1302 /* Never release the last event */
1303 if (!AST_RWLIST_NEXT(ev, eq_next)) {
1307 /* 2.5 times whatever the HTTP timeout is (maximum 2.5 hours) is the maximum time that we will definitely cache an event */
1308 if (ev->usecount == 0 && ast_tvdiff_sec(now, ev->tv) > (httptimeout > 3600 ? 3600 : httptimeout) * 2.5) {
1309 AST_RWLIST_REMOVE_CURRENT(eq_next);
1313 AST_RWLIST_TRAVERSE_SAFE_END;
1314 AST_RWLIST_UNLOCK(&all_events);
1318 * helper functions to convert back and forth between
1319 * string and numeric representation of set of flags
1321 static const struct permalias {
1325 { EVENT_FLAG_SYSTEM, "system" },
1326 { EVENT_FLAG_CALL, "call" },
1327 { EVENT_FLAG_LOG, "log" },
1328 { EVENT_FLAG_VERBOSE, "verbose" },
1329 { EVENT_FLAG_COMMAND, "command" },
1330 { EVENT_FLAG_AGENT, "agent" },
1331 { EVENT_FLAG_USER, "user" },
1332 { EVENT_FLAG_CONFIG, "config" },
1333 { EVENT_FLAG_DTMF, "dtmf" },
1334 { EVENT_FLAG_REPORTING, "reporting" },
1335 { EVENT_FLAG_CDR, "cdr" },
1336 { EVENT_FLAG_DIALPLAN, "dialplan" },
1337 { EVENT_FLAG_ORIGINATE, "originate" },
1338 { EVENT_FLAG_AGI, "agi" },
1339 { EVENT_FLAG_CC, "cc" },
1340 { EVENT_FLAG_AOC, "aoc" },
1341 { EVENT_FLAG_TEST, "test" },
1342 { EVENT_FLAG_MESSAGE, "message" },
1347 /*! \brief Checks to see if a string which can be used to evaluate functions should be rejected */
1348 static int function_capable_string_allowed_with_auths(const char *evaluating, int writepermlist)
1350 if (!(writepermlist & EVENT_FLAG_SYSTEM)
1352 strstr(evaluating, "SHELL") || /* NoOp(${SHELL(rm -rf /)}) */
1353 strstr(evaluating, "EVAL") /* NoOp(${EVAL(${some_var_containing_SHELL})}) */
1360 /*! \brief Convert authority code to a list of options */
1361 static const char *authority_to_str(int authority, struct ast_str **res)
1366 ast_str_reset(*res);
1367 for (i = 0; i < ARRAY_LEN(perms) - 1; i++) {
1368 if (authority & perms[i].num) {
1369 ast_str_append(res, 0, "%s%s", sep, perms[i].label);
1374 if (ast_str_strlen(*res) == 0) /* replace empty string with something sensible */
1375 ast_str_append(res, 0, "<none>");
1377 return ast_str_buffer(*res);
1380 /*! Tells you if smallstr exists inside bigstr
1381 which is delim by delim and uses no buf or stringsep
1382 ast_instring("this|that|more","this",'|') == 1;
1384 feel free to move this to app.c -anthm */
1385 static int ast_instring(const char *bigstr, const char *smallstr, const char delim)
1387 const char *val = bigstr, *next;
1390 if ((next = strchr(val, delim))) {
1391 if (!strncmp(val, smallstr, (next - val))) {
1397 return !strcmp(smallstr, val);
1399 } while (*(val = (next + 1)));
1404 static int get_perm(const char *instr)
1412 for (x = 0; x < ARRAY_LEN(perms); x++) {
1413 if (ast_instring(instr, perms[x].label, ',')) {
1414 ret |= perms[x].num;
1422 * A number returns itself, false returns 0, true returns all flags,
1423 * other strings return the flags that are set.
1425 static int strings_to_mask(const char *string)
1429 if (ast_strlen_zero(string)) {
1433 for (p = string; *p; p++) {
1434 if (*p < '0' || *p > '9') {
1438 if (!*p) { /* all digits */
1439 return atoi(string);
1441 if (ast_false(string)) {
1444 if (ast_true(string)) { /* all permissions */
1446 for (x = 0; x < ARRAY_LEN(perms); x++) {
1447 ret |= perms[x].num;
1451 return get_perm(string);
1454 /*! \brief Unreference manager session object.
1455 If no more references, then go ahead and delete it */
1456 static struct mansession_session *unref_mansession(struct mansession_session *s)
1458 int refcount = ao2_ref(s, -1);
1459 if (manager_debug) {
1460 ast_debug(1, "Mansession: %p refcount now %d\n", s, refcount - 1);
1465 static void event_filter_destructor(void *obj)
1467 regex_t *regex_filter = obj;
1468 regfree(regex_filter);
1471 static void session_destructor(void *obj)
1473 struct mansession_session *session = obj;
1474 struct eventqent *eqe = session->last_ev;
1475 struct ast_datastore *datastore;
1477 /* Get rid of each of the data stores on the session */
1478 while ((datastore = AST_LIST_REMOVE_HEAD(&session->datastores, entry))) {
1479 /* Free the data store */
1480 ast_datastore_free(datastore);
1483 if (session->f != NULL) {
1487 ast_atomic_fetchadd_int(&eqe->usecount, -1);
1489 if (session->chanvars) {
1490 ast_variables_destroy(session->chanvars);
1493 if (session->whitefilters) {
1494 ao2_t_callback(session->whitefilters, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL, "unlink all white filters");
1495 ao2_t_ref(session->whitefilters, -1 , "decrement ref for white container, should be last one");
1498 if (session->blackfilters) {
1499 ao2_t_callback(session->blackfilters, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL, "unlink all black filters");
1500 ao2_t_ref(session->blackfilters, -1 , "decrement ref for black container, should be last one");
1504 /*! \brief Allocate manager session structure and add it to the list of sessions */
1505 static struct mansession_session *build_mansession(const struct ast_sockaddr *addr)
1507 struct mansession_session *newsession;
1509 if (!(newsession = ao2_alloc(sizeof(*newsession), session_destructor))) {
1513 if (!(newsession->whitefilters = ao2_container_alloc(1, NULL, NULL))) {
1514 ao2_ref(newsession, -1);
1518 if (!(newsession->blackfilters = ao2_container_alloc(1, NULL, NULL))) {
1519 ao2_ref(newsession, -1); /* session_destructor will cleanup the other filter */
1523 newsession->fd = -1;
1524 newsession->waiting_thread = AST_PTHREADT_NULL;
1525 newsession->writetimeout = 100;
1526 newsession->send_events = -1;
1527 ast_sockaddr_copy(&newsession->addr, addr);
1529 ao2_link(sessions, newsession);
1534 static int mansession_cmp_fn(void *obj, void *arg, int flags)
1536 struct mansession_session *s = obj;
1538 return !strcasecmp(s->username, str) ? CMP_MATCH : 0;
1541 static void session_destroy(struct mansession_session *s)
1543 unref_mansession(s);
1544 ao2_unlink(sessions, s);
1548 static int check_manager_session_inuse(const char *name)
1550 struct mansession_session *session = ao2_find(sessions, (char *) name, 0);
1555 unref_mansession(session);
1562 * lookup an entry in the list of registered users.
1563 * must be called with the list lock held.
1565 static struct ast_manager_user *get_manager_by_name_locked(const char *name)
1567 struct ast_manager_user *user = NULL;
1569 AST_RWLIST_TRAVERSE(&users, user, list) {
1570 if (!strcasecmp(user->username, name)) {
1578 /*! \brief Get displayconnects config option.
1579 * \param session manager session to get parameter from.
1580 * \return displayconnects config option value.
1582 static int manager_displayconnects (struct mansession_session *session)
1584 struct ast_manager_user *user = NULL;
1587 AST_RWLIST_RDLOCK(&users);
1588 if ((user = get_manager_by_name_locked (session->username))) {
1589 ret = user->displayconnects;
1591 AST_RWLIST_UNLOCK(&users);
1596 static char *handle_showmancmd(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1598 struct manager_action *cur;
1599 struct ast_str *authority;
1603 char syntax_title[64], description_title[64], synopsis_title[64], seealso_title[64], arguments_title[64], privilege_title[64];
1608 e->command = "manager show command";
1610 "Usage: manager show command <actionname> [<actionname> [<actionname> [...]]]\n"
1611 " Shows the detailed description for a specific Asterisk manager interface command.\n";
1614 l = strlen(a->word);
1616 AST_RWLIST_RDLOCK(&actions);
1617 AST_RWLIST_TRAVERSE(&actions, cur, list) {
1618 if (!strncasecmp(a->word, cur->action, l) && ++which > a->n) {
1619 ret = ast_strdup(cur->action);
1620 break; /* make sure we exit even if ast_strdup() returns NULL */
1623 AST_RWLIST_UNLOCK(&actions);
1626 authority = ast_str_alloca(80);
1628 return CLI_SHOWUSAGE;
1632 /* setup the titles */
1633 term_color(synopsis_title, "[Synopsis]\n", COLOR_MAGENTA, 0, 40);
1634 term_color(description_title, "[Description]\n", COLOR_MAGENTA, 0, 40);
1635 term_color(syntax_title, "[Syntax]\n", COLOR_MAGENTA, 0, 40);
1636 term_color(seealso_title, "[See Also]\n", COLOR_MAGENTA, 0, 40);
1637 term_color(arguments_title, "[Arguments]\n", COLOR_MAGENTA, 0, 40);
1638 term_color(privilege_title, "[Privilege]\n", COLOR_MAGENTA, 0,40);
1641 AST_RWLIST_RDLOCK(&actions);
1642 AST_RWLIST_TRAVERSE(&actions, cur, list) {
1643 for (num = 3; num < a->argc; num++) {
1644 if (!strcasecmp(cur->action, a->argv[num])) {
1645 authority_to_str(cur->authority, &authority);
1648 if (cur->docsrc == AST_XML_DOC) {
1649 ast_cli(a->fd, "%s%s\n\n%s%s\n\n%s%s\n\n%s%s\n\n%s%s\n\n%s%s\n\n",
1651 ast_xmldoc_printable(S_OR(cur->syntax, "Not available"), 1),
1653 ast_xmldoc_printable(S_OR(cur->synopsis, "Not available"), 1),
1655 ast_xmldoc_printable(S_OR(cur->description, "Not available"), 1),
1657 ast_xmldoc_printable(S_OR(cur->arguments, "Not available"), 1),
1659 ast_xmldoc_printable(S_OR(cur->seealso, "Not available"), 1),
1661 ast_xmldoc_printable(S_OR(authority->str, "Not available"), 1));
1665 ast_cli(a->fd, "Action: %s\nSynopsis: %s\nPrivilege: %s\n%s\n",
1666 cur->action, cur->synopsis,
1668 S_OR(cur->description, ""));
1673 AST_RWLIST_UNLOCK(&actions);
1678 static char *handle_mandebug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1682 e->command = "manager set debug [on|off]";
1683 e->usage = "Usage: manager set debug [on|off]\n Show, enable, disable debugging of the manager code.\n";
1690 ast_cli(a->fd, "manager debug is %s\n", manager_debug? "on" : "off");
1691 } else if (a->argc == 4) {
1692 if (!strcasecmp(a->argv[3], "on")) {
1694 } else if (!strcasecmp(a->argv[3], "off")) {
1697 return CLI_SHOWUSAGE;
1703 static char *handle_showmanager(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1705 struct ast_manager_user *user = NULL;
1708 struct ast_str *rauthority = ast_str_alloca(128);
1709 struct ast_str *wauthority = ast_str_alloca(128);
1710 struct ast_variable *v;
1714 e->command = "manager show user";
1716 " Usage: manager show user <user>\n"
1717 " Display all information related to the manager user specified.\n";
1720 l = strlen(a->word);
1725 AST_RWLIST_RDLOCK(&users);
1726 AST_RWLIST_TRAVERSE(&users, user, list) {
1727 if ( !strncasecmp(a->word, user->username, l) && ++which > a->n ) {
1728 ret = ast_strdup(user->username);
1732 AST_RWLIST_UNLOCK(&users);
1737 return CLI_SHOWUSAGE;
1740 AST_RWLIST_RDLOCK(&users);
1742 if (!(user = get_manager_by_name_locked(a->argv[3]))) {
1743 ast_cli(a->fd, "There is no manager called %s\n", a->argv[3]);
1744 AST_RWLIST_UNLOCK(&users);
1748 ast_cli(a->fd, "\n");
1755 "displayconnects: %s\n",
1756 (user->username ? user->username : "(N/A)"),
1757 (user->secret ? "<Set>" : "(N/A)"),
1758 ((user->acl && !ast_acl_list_is_empty(user->acl)) ? "yes" : "no"),
1759 authority_to_str(user->readperm, &rauthority),
1760 authority_to_str(user->writeperm, &wauthority),
1761 (user->displayconnects ? "yes" : "no"));
1762 ast_cli(a->fd, " Variables: \n");
1763 for (v = user->chanvars ; v ; v = v->next) {
1764 ast_cli(a->fd, " %s = %s\n", v->name, v->value);
1767 AST_RWLIST_UNLOCK(&users);
1772 static char *handle_showmanagers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1774 struct ast_manager_user *user = NULL;
1778 e->command = "manager show users";
1780 "Usage: manager show users\n"
1781 " Prints a listing of all managers that are currently configured on that\n"
1788 return CLI_SHOWUSAGE;
1791 AST_RWLIST_RDLOCK(&users);
1793 /* If there are no users, print out something along those lines */
1794 if (AST_RWLIST_EMPTY(&users)) {
1795 ast_cli(a->fd, "There are no manager users.\n");
1796 AST_RWLIST_UNLOCK(&users);
1800 ast_cli(a->fd, "\nusername\n--------\n");
1802 AST_RWLIST_TRAVERSE(&users, user, list) {
1803 ast_cli(a->fd, "%s\n", user->username);
1807 AST_RWLIST_UNLOCK(&users);
1809 ast_cli(a->fd,"-------------------\n"
1810 "%d manager users configured.\n", count_amu);
1814 /*! \brief CLI command manager list commands */
1815 static char *handle_showmancmds(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1817 struct manager_action *cur;
1819 int space_remaining;
1820 #define HSMC_FORMAT " %-*.*s %-.*s\n"
1823 e->command = "manager show commands";
1825 "Usage: manager show commands\n"
1826 " Prints a listing of all the available Asterisk manager interface commands.\n";
1832 AST_RWLIST_RDLOCK(&actions);
1833 AST_RWLIST_TRAVERSE(&actions, cur, list) {
1834 int incoming_len = strlen(cur->action);
1835 if (incoming_len > name_len) {
1836 name_len = incoming_len;
1840 space_remaining = MGR_SHOW_TERMINAL_WIDTH - name_len - 4;
1841 if (space_remaining < 0) {
1842 space_remaining = 0;
1845 ast_cli(a->fd, HSMC_FORMAT, name_len, name_len, "Action", space_remaining, "Synopsis");
1846 ast_cli(a->fd, HSMC_FORMAT, name_len, name_len, "------", space_remaining, "--------");
1848 AST_RWLIST_TRAVERSE(&actions, cur, list) {
1849 ast_cli(a->fd, HSMC_FORMAT, name_len, name_len, cur->action, space_remaining, cur->synopsis);
1851 AST_RWLIST_UNLOCK(&actions);
1856 /*! \brief CLI command manager list connected */
1857 static char *handle_showmanconn(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1859 struct mansession_session *session;
1860 time_t now = time(NULL);
1861 #define HSMCONN_FORMAT1 " %-15.15s %-55.55s %-10.10s %-10.10s %-8.8s %-8.8s %-5.5s %-5.5s\n"
1862 #define HSMCONN_FORMAT2 " %-15.15s %-55.55s %-10d %-10d %-8d %-8d %-5.5d %-5.5d\n"
1864 struct ao2_iterator i;
1868 e->command = "manager show connected";
1870 "Usage: manager show connected\n"
1871 " Prints a listing of the users that are currently connected to the\n"
1872 "Asterisk manager interface.\n";
1878 ast_cli(a->fd, HSMCONN_FORMAT1, "Username", "IP Address", "Start", "Elapsed", "FileDes", "HttpCnt", "Read", "Write");
1880 i = ao2_iterator_init(sessions, 0);
1881 while ((session = ao2_iterator_next(&i))) {
1883 ast_cli(a->fd, HSMCONN_FORMAT2, session->username, ast_sockaddr_stringify_addr(&session->addr), (int)(session->sessionstart), (int)(now - session->sessionstart), session->fd, session->inuse, session->readperm, session->writeperm);
1885 ao2_unlock(session);
1886 unref_mansession(session);
1888 ao2_iterator_destroy(&i);
1889 ast_cli(a->fd, "%d users connected.\n", count);
1894 /*! \brief CLI command manager list eventq */
1895 /* Should change to "manager show connected" */
1896 static char *handle_showmaneventq(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1898 struct eventqent *s;
1901 e->command = "manager show eventq";
1903 "Usage: manager show eventq\n"
1904 " Prints a listing of all events pending in the Asterisk manger\n"
1910 AST_RWLIST_RDLOCK(&all_events);
1911 AST_RWLIST_TRAVERSE(&all_events, s, eq_next) {
1912 ast_cli(a->fd, "Usecount: %d\n", s->usecount);
1913 ast_cli(a->fd, "Category: %d\n", s->category);
1914 ast_cli(a->fd, "Event:\n%s", s->eventdata);
1916 AST_RWLIST_UNLOCK(&all_events);
1921 /*! \brief CLI command manager reload */
1922 static char *handle_manager_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1926 e->command = "manager reload";
1928 "Usage: manager reload\n"
1929 " Reloads the manager configuration.\n";
1935 return CLI_SHOWUSAGE;
1941 static struct eventqent *advance_event(struct eventqent *e)
1943 struct eventqent *next;
1945 AST_RWLIST_RDLOCK(&all_events);
1946 if ((next = AST_RWLIST_NEXT(e, eq_next))) {
1947 ast_atomic_fetchadd_int(&next->usecount, 1);
1948 ast_atomic_fetchadd_int(&e->usecount, -1);
1950 AST_RWLIST_UNLOCK(&all_events);
1954 #define GET_HEADER_FIRST_MATCH 0
1955 #define GET_HEADER_LAST_MATCH 1
1956 #define GET_HEADER_SKIP_EMPTY 2
1959 * \brief Return a matching header value.
1962 * Generic function to return either the first or the last
1963 * matching header from a list of variables, possibly skipping
1966 * \note At the moment there is only one use of this function in
1967 * this file, so we make it static.
1969 * \note Never returns NULL.
1971 static const char *__astman_get_header(const struct message *m, char *var, int mode)
1973 int x, l = strlen(var);
1974 const char *result = "";
1980 for (x = 0; x < m->hdrcount; x++) {
1981 const char *h = m->headers[x];
1982 if (!strncasecmp(var, h, l) && h[l] == ':') {
1983 const char *value = h + l + 1;
1984 value = ast_skip_blanks(value); /* ignore leading spaces in the value */
1985 /* found a potential candidate */
1986 if ((mode & GET_HEADER_SKIP_EMPTY) && ast_strlen_zero(value)) {
1987 continue; /* not interesting */
1989 if (mode & GET_HEADER_LAST_MATCH) {
1990 result = value; /* record the last match so far */
2001 * \brief Return the first matching variable from an array.
2003 * \note This is the legacy function and is implemented in
2004 * therms of __astman_get_header().
2006 * \note Never returns NULL.
2008 const char *astman_get_header(const struct message *m, char *var)
2010 return __astman_get_header(m, var, GET_HEADER_FIRST_MATCH);
2015 * \brief Process one "Variable:" header value string.
2017 * \param head Current list of AMI variables to get new values added.
2018 * \param hdr_val Header value string to process.
2020 * \return New variable list head.
2022 static struct ast_variable *man_do_variable_value(struct ast_variable *head, const char *hdr_val)
2025 AST_DECLARE_APP_ARGS(args,
2026 AST_APP_ARG(vars)[64];
2029 hdr_val = ast_skip_blanks(hdr_val); /* ignore leading spaces in the value */
2030 parse = ast_strdupa(hdr_val);
2032 /* Break the header value string into name=val pair items. */
2033 AST_STANDARD_APP_ARGS(args, parse);
2037 /* Process each name=val pair item. */
2038 for (y = 0; y < args.argc; y++) {
2039 struct ast_variable *cur;
2043 if (!args.vars[y]) {
2046 var = val = args.vars[y];
2049 /* XXX We may wish to trim whitespace from the strings. */
2050 if (!val || ast_strlen_zero(var)) {
2054 /* Create new variable list node and prepend it to the list. */
2055 cur = ast_variable_new(var, val, "");
2066 struct ast_variable *astman_get_variables(const struct message *m)
2070 struct ast_variable *head = NULL;
2072 static const char var_hdr[] = "Variable:";
2074 /* Process all "Variable:" headers. */
2075 varlen = strlen(var_hdr);
2076 for (x = 0; x < m->hdrcount; x++) {
2077 if (strncasecmp(var_hdr, m->headers[x], varlen)) {
2080 head = man_do_variable_value(head, m->headers[x] + varlen);
2086 /*! \brief access for hooks to send action messages to ami */
2087 int ast_hook_send_action(struct manager_custom_hook *hook, const char *msg)
2091 struct manager_action *act_found;
2092 struct mansession s = {.session = NULL, };
2093 struct message m = { 0 };
2103 /* Create our own copy of the AMI action msg string. */
2104 src = dup_str = ast_strdup(msg);
2109 /* convert msg string to message struct */
2110 curlen = strlen(src);
2111 for (x = 0; x < curlen; x++) {
2112 int cr; /* set if we have \r */
2113 if (src[x] == '\r' && x+1 < curlen && src[x+1] == '\n')
2114 cr = 2; /* Found. Update length to include \r\n */
2115 else if (src[x] == '\n')
2116 cr = 1; /* also accept \n only */
2119 /* don't keep empty lines */
2120 if (x && m.hdrcount < ARRAY_LEN(m.headers)) {
2121 /* ... but trim \r\n and terminate the header string */
2123 m.headers[m.hdrcount++] = src;
2126 curlen -= x; /* remaining size */
2127 src += x; /* update pointer */
2128 x = -1; /* reset loop */
2131 action = astman_get_header(&m, "Action");
2132 if (strcasecmp(action, "login")) {
2133 act_found = action_find(action);
2136 * we have to simulate a session for this action request
2137 * to be able to pass it down for processing
2138 * This is necessary to meet the previous design of manager.c
2141 s.f = (void*)1; /* set this to something so our request will make it through all functions that test it*/
2143 ao2_lock(act_found);
2144 if (act_found->registered && act_found->func) {
2145 if (act_found->module) {
2146 ast_module_ref(act_found->module);
2148 ao2_unlock(act_found);
2149 ret = act_found->func(&s, &m);
2150 ao2_lock(act_found);
2151 if (act_found->module) {
2152 ast_module_unref(act_found->module);
2157 ao2_unlock(act_found);
2158 ao2_t_ref(act_found, -1, "done with found action object");
2167 * helper function to send a string to the socket.
2168 * Return -1 on error (e.g. buffer full).
2170 static int send_string(struct mansession *s, char *string)
2173 FILE *f = s->f ? s->f : s->session->f;
2174 int fd = s->f ? s->fd : s->session->fd;
2176 /* It's a result from one of the hook's action invocation */
2179 * to send responses, we're using the same function
2180 * as for receiving events. We call the event "HookResponse"
2182 s->hook->helper(EVENT_FLAG_HOOKRESPONSE, "HookResponse", string);
2186 if ((res = ast_careful_fwrite(f, fd, string, strlen(string), s->session->writetimeout))) {
2194 * \brief thread local buffer for astman_append
2196 * \note This can not be defined within the astman_append() function
2197 * because it declares a couple of functions that get used to
2198 * initialize the thread local storage key.
2200 AST_THREADSTORAGE(astman_append_buf);
2202 AST_THREADSTORAGE(userevent_buf);
2204 /*! \brief initial allocated size for the astman_append_buf and astman_send_*_va */
2205 #define ASTMAN_APPEND_BUF_INITSIZE 256
2208 * utility functions for creating AMI replies
2210 void astman_append(struct mansession *s, const char *fmt, ...)
2213 struct ast_str *buf;
2215 if (!(buf = ast_str_thread_get(&astman_append_buf, ASTMAN_APPEND_BUF_INITSIZE))) {
2220 ast_str_set_va(&buf, 0, fmt, ap);
2223 if (s->f != NULL || s->session->f != NULL) {
2224 send_string(s, ast_str_buffer(buf));
2226 ast_verbose("fd == -1 in astman_append, should not happen\n");
2230 /*! \note NOTE: XXX this comment is unclear and possibly wrong.
2231 Callers of astman_send_error(), astman_send_response() or astman_send_ack() must EITHER
2232 hold the session lock _or_ be running in an action callback (in which case s->session->busy will
2233 be non-zero). In either of these cases, there is no need to lock-protect the session's
2234 fd, since no other output will be sent (events will be queued), and no input will
2235 be read until either the current action finishes or get_input() obtains the session
2239 /*! \todo XXX MSG_MOREDATA should go to a header file. */
2240 #define MSG_MOREDATA ((char *)astman_send_response)
2242 /*! \brief send a response with an optional message,
2243 * and terminate it with an empty line.
2244 * m is used only to grab the 'ActionID' field.
2246 * Use the explicit constant MSG_MOREDATA to remove the empty line.
2247 * XXX MSG_MOREDATA should go to a header file.
2249 static void astman_send_response_full(struct mansession *s, const struct message *m, char *resp, char *msg, char *listflag)
2251 const char *id = astman_get_header(m, "ActionID");
2253 astman_append(s, "Response: %s\r\n", resp);
2254 if (!ast_strlen_zero(id)) {
2255 astman_append(s, "ActionID: %s\r\n", id);
2258 astman_append(s, "EventList: %s\r\n", listflag); /* Start, complete, cancelled */
2260 if (msg == MSG_MOREDATA) {
2263 astman_append(s, "Message: %s\r\n\r\n", msg);
2265 astman_append(s, "\r\n");
2269 void astman_send_response(struct mansession *s, const struct message *m, char *resp, char *msg)
2271 astman_send_response_full(s, m, resp, msg, NULL);
2274 void astman_send_error(struct mansession *s, const struct message *m, char *error)
2276 astman_send_response_full(s, m, "Error", error, NULL);
2279 void astman_send_error_va(struct mansession *s, const struct message *m, const char *fmt, ...)
2282 struct ast_str *buf;
2284 if (!(buf = ast_str_thread_get(&astman_append_buf, ASTMAN_APPEND_BUF_INITSIZE))) {
2289 ast_str_set_va(&buf, 0, fmt, ap);
2292 astman_send_response_full(s, m, "Error", ast_str_buffer(buf), NULL);
2296 void astman_send_ack(struct mansession *s, const struct message *m, char *msg)
2298 astman_send_response_full(s, m, "Success", msg, NULL);
2301 static void astman_start_ack(struct mansession *s, const struct message *m)
2303 astman_send_response_full(s, m, "Success", MSG_MOREDATA, NULL);
2306 void astman_send_listack(struct mansession *s, const struct message *m, char *msg, char *listflag)
2308 astman_send_response_full(s, m, "Success", msg, listflag);
2311 /*! \brief Lock the 'mansession' structure. */
2312 static void mansession_lock(struct mansession *s)
2314 ast_mutex_lock(&s->lock);
2317 /*! \brief Unlock the 'mansession' structure. */
2318 static void mansession_unlock(struct mansession *s)
2320 ast_mutex_unlock(&s->lock);
2324 Rather than braindead on,off this now can also accept a specific int mask value
2325 or a ',' delim list of mask strings (the same as manager.conf) -anthm
2327 static int set_eventmask(struct mansession *s, const char *eventmask)
2329 int maskint = strings_to_mask(eventmask);
2331 ao2_lock(s->session);
2333 s->session->send_events = maskint;
2335 ao2_unlock(s->session);
2340 static enum ast_security_event_transport_type mansession_get_transport(const struct mansession *s)
2342 return s->tcptls_session->parent->tls_cfg ? AST_SECURITY_EVENT_TRANSPORT_TLS :
2343 AST_SECURITY_EVENT_TRANSPORT_TCP;
2346 static void report_invalid_user(const struct mansession *s, const char *username)
2348 char session_id[32];
2349 struct ast_security_event_inval_acct_id inval_acct_id = {
2350 .common.event_type = AST_SECURITY_EVENT_INVAL_ACCT_ID,
2351 .common.version = AST_SECURITY_EVENT_INVAL_ACCT_ID_VERSION,
2352 .common.service = "AMI",
2353 .common.account_id = username,
2354 .common.session_tv = &s->session->sessionstart_tv,
2355 .common.local_addr = {
2356 .addr = &s->tcptls_session->parent->local_address,
2357 .transport = mansession_get_transport(s),
2359 .common.remote_addr = {
2360 .addr = &s->session->addr,
2361 .transport = mansession_get_transport(s),
2363 .common.session_id = session_id,
2366 snprintf(session_id, sizeof(session_id), "%p", s);
2368 ast_security_event_report(AST_SEC_EVT(&inval_acct_id));
2371 static void report_failed_acl(const struct mansession *s, const char *username)
2373 char session_id[32];
2374 struct ast_security_event_failed_acl failed_acl_event = {
2375 .common.event_type = AST_SECURITY_EVENT_FAILED_ACL,
2376 .common.version = AST_SECURITY_EVENT_FAILED_ACL_VERSION,
2377 .common.service = "AMI",
2378 .common.account_id = username,
2379 .common.session_tv = &s->session->sessionstart_tv,
2380 .common.local_addr = {
2381 .addr = &s->tcptls_session->parent->local_address,
2382 .transport = mansession_get_transport(s),
2384 .common.remote_addr = {
2385 .addr = &s->session->addr,
2386 .transport = mansession_get_transport(s),
2388 .common.session_id = session_id,
2391 snprintf(session_id, sizeof(session_id), "%p", s->session);
2393 ast_security_event_report(AST_SEC_EVT(&failed_acl_event));
2396 static void report_inval_password(const struct mansession *s, const char *username)
2398 char session_id[32];
2399 struct ast_security_event_inval_password inval_password = {
2400 .common.event_type = AST_SECURITY_EVENT_INVAL_PASSWORD,
2401 .common.version = AST_SECURITY_EVENT_INVAL_PASSWORD_VERSION,
2402 .common.service = "AMI",
2403 .common.account_id = username,
2404 .common.session_tv = &s->session->sessionstart_tv,
2405 .common.local_addr = {
2406 .addr = &s->tcptls_session->parent->local_address,
2407 .transport = mansession_get_transport(s),
2409 .common.remote_addr = {
2410 .addr = &s->session->addr,
2411 .transport = mansession_get_transport(s),
2413 .common.session_id = session_id,
2416 snprintf(session_id, sizeof(session_id), "%p", s->session);
2418 ast_security_event_report(AST_SEC_EVT(&inval_password));
2421 static void report_auth_success(const struct mansession *s)
2423 char session_id[32];
2424 struct ast_security_event_successful_auth successful_auth = {
2425 .common.event_type = AST_SECURITY_EVENT_SUCCESSFUL_AUTH,
2426 .common.version = AST_SECURITY_EVENT_SUCCESSFUL_AUTH_VERSION,
2427 .common.service = "AMI",
2428 .common.account_id = s->session->username,
2429 .common.session_tv = &s->session->sessionstart_tv,
2430 .common.local_addr = {
2431 .addr = &s->tcptls_session->parent->local_address,
2432 .transport = mansession_get_transport(s),
2434 .common.remote_addr = {
2435 .addr = &s->session->addr,
2436 .transport = mansession_get_transport(s),
2438 .common.session_id = session_id,
2441 snprintf(session_id, sizeof(session_id), "%p", s->session);
2443 ast_security_event_report(AST_SEC_EVT(&successful_auth));
2446 static void report_req_not_allowed(const struct mansession *s, const char *action)
2448 char session_id[32];
2449 char request_type[64];
2450 struct ast_security_event_req_not_allowed req_not_allowed = {
2451 .common.event_type = AST_SECURITY_EVENT_REQ_NOT_ALLOWED,
2452 .common.version = AST_SECURITY_EVENT_REQ_NOT_ALLOWED_VERSION,
2453 .common.service = "AMI",
2454 .common.account_id = s->session->username,
2455 .common.session_tv = &s->session->sessionstart_tv,
2456 .common.local_addr = {
2457 .addr = &s->tcptls_session->parent->local_address,
2458 .transport = mansession_get_transport(s),
2460 .common.remote_addr = {
2461 .addr = &s->session->addr,
2462 .transport = mansession_get_transport(s),
2464 .common.session_id = session_id,
2466 .request_type = request_type,
2469 snprintf(session_id, sizeof(session_id), "%p", s->session);
2470 snprintf(request_type, sizeof(request_type), "Action: %s", action);
2472 ast_security_event_report(AST_SEC_EVT(&req_not_allowed));
2475 static void report_req_bad_format(const struct mansession *s, const char *action)
2477 char session_id[32];
2478 char request_type[64];
2479 struct ast_security_event_req_bad_format req_bad_format = {
2480 .common.event_type = AST_SECURITY_EVENT_REQ_BAD_FORMAT,
2481 .common.version = AST_SECURITY_EVENT_REQ_BAD_FORMAT_VERSION,
2482 .common.service = "AMI",
2483 .common.account_id = s->session->username,
2484 .common.session_tv = &s->session->sessionstart_tv,
2485 .common.local_addr = {
2486 .addr = &s->tcptls_session->parent->local_address,
2487 .transport = mansession_get_transport(s),
2489 .common.remote_addr = {
2490 .addr = &s->session->addr,
2491 .transport = mansession_get_transport(s),
2493 .common.session_id = session_id,
2495 .request_type = request_type,
2498 snprintf(session_id, sizeof(session_id), "%p", s->session);
2499 snprintf(request_type, sizeof(request_type), "Action: %s", action);
2501 ast_security_event_report(AST_SEC_EVT(&req_bad_format));
2504 static void report_failed_challenge_response(const struct mansession *s,
2505 const char *response, const char *expected_response)
2507 char session_id[32];
2508 struct ast_security_event_chal_resp_failed chal_resp_failed = {
2509 .common.event_type = AST_SECURITY_EVENT_CHAL_RESP_FAILED,
2510 .common.version = AST_SECURITY_EVENT_CHAL_RESP_FAILED_VERSION,
2511 .common.service = "AMI",
2512 .common.account_id = s->session->username,
2513 .common.session_tv = &s->session->sessionstart_tv,
2514 .common.local_addr = {
2515 .addr = &s->tcptls_session->parent->local_address,
2516 .transport = mansession_get_transport(s),
2518 .common.remote_addr = {
2519 .addr = &s->session->addr,
2520 .transport = mansession_get_transport(s),
2522 .common.session_id = session_id,
2524 .challenge = s->session->challenge,
2525 .response = response,
2526 .expected_response = expected_response,
2529 snprintf(session_id, sizeof(session_id), "%p", s->session);
2531 ast_security_event_report(AST_SEC_EVT(&chal_resp_failed));
2534 static void report_session_limit(const struct mansession *s)
2536 char session_id[32];
2537 struct ast_security_event_session_limit session_limit = {
2538 .common.event_type = AST_SECURITY_EVENT_SESSION_LIMIT,
2539 .common.version = AST_SECURITY_EVENT_SESSION_LIMIT_VERSION,
2540 .common.service = "AMI",
2541 .common.account_id = s->session->username,
2542 .common.session_tv = &s->session->sessionstart_tv,
2543 .common.local_addr = {
2544 .addr = &s->tcptls_session->parent->local_address,
2545 .transport = mansession_get_transport(s),
2547 .common.remote_addr = {
2548 .addr = &s->session->addr,
2549 .transport = mansession_get_transport(s),
2551 .common.session_id = session_id,
2554 snprintf(session_id, sizeof(session_id), "%p", s->session);
2556 ast_security_event_report(AST_SEC_EVT(&session_limit));
2560 * Here we start with action_ handlers for AMI actions,
2561 * and the internal functions used by them.
2562 * Generally, the handlers are called action_foo()
2565 /* helper function for action_login() */
2566 static int authenticate(struct mansession *s, const struct message *m)
2568 const char *username = astman_get_header(m, "Username");
2569 const char *password = astman_get_header(m, "Secret");
2571 struct ast_manager_user *user = NULL;
2572 regex_t *regex_filter;
2573 struct ao2_iterator filter_iter;
2575 if (ast_strlen_zero(username)) { /* missing username */
2579 /* locate user in locked state */
2580 AST_RWLIST_WRLOCK(&users);
2582 if (!(user = get_manager_by_name_locked(username))) {
2583 report_invalid_user(s, username);
2584 ast_log(LOG_NOTICE, "%s tried to authenticate with nonexistent user '%s'\n", ast_sockaddr_stringify_addr(&s->session->addr), username);
2585 } else if (user->acl && (ast_apply_acl(user->acl, &s->session->addr, "Manager User ACL: ") == AST_SENSE_DENY)) {
2586 report_failed_acl(s, username);
2587 ast_log(LOG_NOTICE, "%s failed to pass IP ACL as '%s'\n", ast_sockaddr_stringify_addr(&s->session->addr), username);
2588 } else if (!strcasecmp(astman_get_header(m, "AuthType"), "MD5")) {
2589 const char *key = astman_get_header(m, "Key");
2590 if (!ast_strlen_zero(key) && !ast_strlen_zero(s->session->challenge) && user->secret) {
2593 char md5key[256] = "";
2594 struct MD5Context md5;
2595 unsigned char digest[16];
2598 MD5Update(&md5, (unsigned char *) s->session->challenge, strlen(s->session->challenge));
2599 MD5Update(&md5, (unsigned char *) user->secret, strlen(user->secret));
2600 MD5Final(digest, &md5);
2601 for (x = 0; x < 16; x++)
2602 len += sprintf(md5key + len, "%2.2x", digest[x]);
2603 if (!strcmp(md5key, key)) {
2606 report_failed_challenge_response(s, key, md5key);
2609 ast_debug(1, "MD5 authentication is not possible. challenge: '%s'\n",
2610 S_OR(s->session->challenge, ""));
2612 } else if (user->secret) {
2613 if (!strcmp(password, user->secret)) {
2616 report_inval_password(s, username);
2621 ast_log(LOG_NOTICE, "%s failed to authenticate as '%s'\n", ast_sockaddr_stringify_addr(&s->session->addr), username);
2622 AST_RWLIST_UNLOCK(&users);
2628 /* All of the user parameters are copied to the session so that in the event
2629 * of a reload and a configuration change, the session parameters are not
2631 ast_copy_string(s->session->username, username, sizeof(s->session->username));
2632 s->session->readperm = user->readperm;
2633 s->session->writeperm = user->writeperm;
2634 s->session->writetimeout = user->writetimeout;
2635 if (user->chanvars) {
2636 s->session->chanvars = ast_variables_dup(user->chanvars);
2639 filter_iter = ao2_iterator_init(user->whitefilters, 0);
2640 while ((regex_filter = ao2_iterator_next(&filter_iter))) {
2641 ao2_t_link(s->session->whitefilters, regex_filter, "add white user filter to session");
2642 ao2_t_ref(regex_filter, -1, "remove iterator ref");
2644 ao2_iterator_destroy(&filter_iter);
2646 filter_iter = ao2_iterator_init(user->blackfilters, 0);
2647 while ((regex_filter = ao2_iterator_next(&filter_iter))) {
2648 ao2_t_link(s->session->blackfilters, regex_filter, "add black user filter to session");
2649 ao2_t_ref(regex_filter, -1, "remove iterator ref");
2651 ao2_iterator_destroy(&filter_iter);
2653 s->session->sessionstart = time(NULL);
2654 s->session->sessionstart_tv = ast_tvnow();
2655 set_eventmask(s, astman_get_header(m, "Events"));
2657 report_auth_success(s);
2659 AST_RWLIST_UNLOCK(&users);
2663 static int action_ping(struct mansession *s, const struct message *m)
2665 const char *actionid = astman_get_header(m, "ActionID");
2666 struct timeval now = ast_tvnow();
2668 astman_append(s, "Response: Success\r\n");
2669 if (!ast_strlen_zero(actionid)){
2670 astman_append(s, "ActionID: %s\r\n", actionid);
2675 "Timestamp: %ld.%06lu\r\n"
2677 (long) now.tv_sec, (unsigned long) now.tv_usec);
2681 static int action_getconfig(struct mansession *s, const struct message *m)
2683 struct ast_config *cfg;
2684 const char *fn = astman_get_header(m, "Filename");
2685 const char *category = astman_get_header(m, "Category");
2688 char *cur_category = NULL;
2689 struct ast_variable *v;
2690 struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
2692 if (ast_strlen_zero(fn)) {
2693 astman_send_error(s, m, "Filename not specified");
2696 cfg = ast_config_load2(fn, "manager", config_flags);
2697 if (cfg == CONFIG_STATUS_FILEMISSING) {
2698 astman_send_error(s, m, "Config file not found");
2700 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
2701 astman_send_error(s, m, "Config file has invalid format");
2705 astman_start_ack(s, m);
2706 while ((cur_category = ast_category_browse(cfg, cur_category))) {
2707 if (ast_strlen_zero(category) || (!ast_strlen_zero(category) && !strcmp(category, cur_category))) {
2709 astman_append(s, "Category-%06d: %s\r\n", catcount, cur_category);
2710 for (v = ast_variable_browse(cfg, cur_category); v; v = v->next) {
2711 astman_append(s, "Line-%06d-%06d: %s=%s\r\n", catcount, lineno++, v->name, v->value);
2716 if (!ast_strlen_zero(category) && catcount == 0) { /* TODO: actually, a config with no categories doesn't even get loaded */
2717 astman_append(s, "No categories found\r\n");
2719 ast_config_destroy(cfg);
2720 astman_append(s, "\r\n");
2725 static int action_listcategories(struct mansession *s, const struct message *m)
2727 struct ast_config *cfg;
2728 const char *fn = astman_get_header(m, "Filename");
2729 char *category = NULL;
2730 struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
2733 if (ast_strlen_zero(fn)) {
2734 astman_send_error(s, m, "Filename not specified");
2737 if (!(cfg = ast_config_load2(fn, "manager", config_flags))) {
2738 astman_send_error(s, m, "Config file not found");
2740 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
2741 astman_send_error(s, m, "Config file has invalid format");
2744 astman_start_ack(s, m);
2745 while ((category = ast_category_browse(cfg, category))) {
2746 astman_append(s, "Category-%06d: %s\r\n", catcount, category);
2749 if (catcount == 0) { /* TODO: actually, a config with no categories doesn't even get loaded */
2750 astman_append(s, "Error: no categories found\r\n");
2752 ast_config_destroy(cfg);
2753 astman_append(s, "\r\n");
2761 /*! The amount of space in out must be at least ( 2 * strlen(in) + 1 ) */
2762 static void json_escape(char *out, const char *in)
2765 if (*in == '\\' || *in == '\"') {
2775 * \brief Append a JSON escaped string to the manager stream.
2777 * \param s AMI stream to append a string.
2778 * \param str String to append to the stream after JSON escaping it.
2782 static void astman_append_json(struct mansession *s, const char *str)
2786 buf = ast_alloca(2 * strlen(str) + 1);
2787 json_escape(buf, str);
2788 astman_append(s, "%s", buf);
2791 static int action_getconfigjson(struct mansession *s, const struct message *m)
2793 struct ast_config *cfg;
2794 const char *fn = astman_get_header(m, "Filename");
2795 char *category = NULL;
2796 struct ast_variable *v;
2798 struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
2800 if (ast_strlen_zero(fn)) {
2801 astman_send_error(s, m, "Filename not specified");
2805 if (!(cfg = ast_config_load2(fn, "manager", config_flags))) {
2806 astman_send_error(s, m, "Config file not found");
2808 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
2809 astman_send_error(s, m, "Config file has invalid format");
2813 astman_start_ack(s, m);
2814 astman_append(s, "JSON: {");
2815 while ((category = ast_category_browse(cfg, category))) {
2818 astman_append(s, "%s\"", comma1 ? "," : "");
2819 astman_append_json(s, category);
2820 astman_append(s, "\":[");
2822 for (v = ast_variable_browse(cfg, category); v; v = v->next) {
2823 astman_append(s, "%s\"", comma2 ? "," : "");
2824 astman_append_json(s, v->name);
2825 astman_append(s, "\":\"");
2826 astman_append_json(s, v->value);
2827 astman_append(s, "\"");
2830 astman_append(s, "]");
2832 astman_append(s, "}\r\n\r\n");
2834 ast_config_destroy(cfg);
2839 /*! \brief helper function for action_updateconfig */
2840 static enum error_type handle_updates(struct mansession *s, const struct message *m, struct ast_config *cfg, const char *dfn)
2844 const char *action, *cat, *var, *value, *match, *line;
2845 struct ast_category *category;
2846 struct ast_variable *v;
2847 struct ast_str *str1 = ast_str_create(16), *str2 = ast_str_create(16);
2848 enum error_type result = 0;
2850 for (x = 0; x < 100000; x++) { /* 100000 = the max number of allowed updates + 1 */
2851 unsigned int object = 0;
2853 snprintf(hdr, sizeof(hdr), "Action-%06d", x);
2854 action = astman_get_header(m, hdr);
2855 if (ast_strlen_zero(action)) /* breaks the for loop if no action header */
2856 break; /* this could cause problems if actions come in misnumbered */
2858 snprintf(hdr, sizeof(hdr), "Cat-%06d", x);
2859 cat = astman_get_header(m, hdr);
2860 if (ast_strlen_zero(cat)) { /* every action needs a category */
2861 result = UNSPECIFIED_CATEGORY;
2865 snprintf(hdr, sizeof(hdr), "Var-%06d", x);
2866 var = astman_get_header(m, hdr);
2868 snprintf(hdr, sizeof(hdr), "Value-%06d", x);
2869 value = astman_get_header(m, hdr);
2871 if (!ast_strlen_zero(value) && *value == '>') {
2876 snprintf(hdr, sizeof(hdr), "Match-%06d", x);
2877 match = astman_get_header(m, hdr);
2879 snprintf(hdr, sizeof(hdr), "Line-%06d", x);
2880 line = astman_get_header(m, hdr);
2882 if (!strcasecmp(action, "newcat")) {
2883 if (ast_category_get(cfg,cat)) { /* check to make sure the cat doesn't */
2884 result = FAILURE_NEWCAT; /* already exist */
2887 if (!(category = ast_category_new(cat, dfn, -1))) {
2888 result = FAILURE_ALLOCATION;
2891 if (ast_strlen_zero(match)) {
2892 ast_category_append(cfg, category);
2894 ast_category_insert(cfg, category, match);
2896 } else if (!strcasecmp(action, "renamecat")) {
2897 if (ast_strlen_zero(value)) {
2898 result = UNSPECIFIED_ARGUMENT;
2901 if (!(category = ast_category_get(cfg, cat))) {
2902 result = UNKNOWN_CATEGORY;
2905 ast_category_rename(category, value);
2906 } else if (!strcasecmp(action, "delcat")) {
2907 if (ast_category_delete(cfg, cat)) {
2908 result = FAILURE_DELCAT;
2911 } else if (!strcasecmp(action, "emptycat")) {
2912 if (ast_category_empty(cfg, cat)) {
2913 result = FAILURE_EMPTYCAT;
2916 } else if (!strcasecmp(action, "update")) {
2917 if (ast_strlen_zero(var)) {
2918 result = UNSPECIFIED_ARGUMENT;
2921 if (!(category = ast_category_get(cfg,cat))) {
2922 result = UNKNOWN_CATEGORY;
2925 if (ast_variable_update(category, var, value, match, object)) {
2926 result = FAILURE_UPDATE;
2929 } else if (!strcasecmp(action, "delete")) {
2930 if ((ast_strlen_zero(var) && ast_strlen_zero(line))) {
2931 result = UNSPECIFIED_ARGUMENT;
2934 if (!(category = ast_category_get(cfg, cat))) {
2935 result = UNKNOWN_CATEGORY;
2938 if (ast_variable_delete(category, var, match, line)) {
2939 result = FAILURE_DELETE;
2942 } else if (!strcasecmp(action, "append")) {
2943 if (ast_strlen_zero(var)) {
2944 result = UNSPECIFIED_ARGUMENT;
2947 if (!(category = ast_category_get(cfg, cat))) {
2948 result = UNKNOWN_CATEGORY;
2951 if (!(v = ast_variable_new(var, value, dfn))) {
2952 result = FAILURE_ALLOCATION;
2955 if (object || (match && !strcasecmp(match, "object"))) {
2958 ast_variable_append(category, v);
2959 } else if (!strcasecmp(action, "insert")) {
2960 if (ast_strlen_zero(var) || ast_strlen_zero(line)) {
2961 result = UNSPECIFIED_ARGUMENT;
2964 if (!(category = ast_category_get(cfg, cat))) {
2965 result = UNKNOWN_CATEGORY;
2968 if (!(v = ast_variable_new(var, value, dfn))) {
2969 result = FAILURE_ALLOCATION;
2972 ast_variable_insert(category, v, line);
2975 ast_log(LOG_WARNING, "Action-%06d: %s not handled\n", x, action);
2976 result = UNKNOWN_ACTION;
2985 static int action_updateconfig(struct mansession *s, const struct message *m)
2987 struct ast_config *cfg;
2988 const char *sfn = astman_get_header(m, "SrcFilename");
2989 const char *dfn = astman_get_header(m, "DstFilename");
2991 const char *rld = astman_get_header(m, "Reload");
2992 struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
2993 enum error_type result;
2995 if (ast_strlen_zero(sfn) || ast_strlen_zero(dfn)) {
2996 astman_send_error(s, m, "Filename not specified");
2999 if (!(cfg = ast_config_load2(sfn, "manager", config_flags))) {
3000 astman_send_error(s, m, "Config file not found");
3002 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
3003 astman_send_error(s, m, "Config file has invalid format");
3006 result = handle_updates(s, m, cfg, dfn);
3008 ast_include_rename(cfg, sfn, dfn); /* change the include references from dfn to sfn, so things match up */
3009 res = ast_config_text_file_save(dfn, cfg, "Manager");
3010 ast_config_destroy(cfg);
3012 astman_send_error(s, m, "Save of config failed");
3015 astman_send_ack(s, m, NULL);
3016 if (!ast_strlen_zero(rld)) {
3017 if (ast_true(rld)) {
3020 ast_module_reload(rld);
3023 ast_config_destroy(cfg);
3025 case UNKNOWN_ACTION:
3026 astman_send_error(s, m, "Unknown action command");
3028 case UNKNOWN_CATEGORY:
3029 astman_send_error(s, m, "Given category does not exist");
3031 case UNSPECIFIED_CATEGORY:
3032 astman_send_error(s, m, "Category not specified");
3034 case UNSPECIFIED_ARGUMENT:
3035 astman_send_error(s, m, "Problem with category, value, or line (if required)");
3037 case FAILURE_ALLOCATION:
3038 astman_send_error(s, m, "Memory allocation failure, this should not happen");
3040 case FAILURE_NEWCAT:
3041 astman_send_error(s, m, "Create category did not complete successfully");
3043 case FAILURE_DELCAT:
3044 astman_send_error(s, m, "Delete category did not complete successfully");
3046 case FAILURE_EMPTYCAT:
3047 astman_send_error(s, m, "Empty category did not complete successfully");
3049 case FAILURE_UPDATE:
3050 astman_send_error(s, m, "Update did not complete successfully");
3052 case FAILURE_DELETE:
3053 astman_send_error(s, m, "Delete did not complete successfully");
3055 case FAILURE_APPEND:
3056 astman_send_error(s, m, "Append did not complete successfully");
3063 static int action_createconfig(struct mansession *s, const struct message *m)
3066 const char *fn = astman_get_header(m, "Filename");
3067 struct ast_str *filepath = ast_str_alloca(PATH_MAX);
3068 ast_str_set(&filepath, 0, "%s/", ast_config_AST_CONFIG_DIR);
3069 ast_str_append(&filepath, 0, "%s", fn);
3071 if ((fd = open(ast_str_buffer(filepath), O_CREAT | O_EXCL, AST_FILE_MODE)) != -1) {
3073 astman_send_ack(s, m, "New configuration file created successfully");
3075 astman_send_error(s, m, strerror(errno));
3081 static int action_waitevent(struct mansession *s, const struct message *m)
3083 const char *timeouts = astman_get_header(m, "Timeout");
3087 const char *id = astman_get_header(m, "ActionID");
3090 if (!ast_strlen_zero(id)) {
3091 snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
3096 if (!ast_strlen_zero(timeouts)) {
3097 sscanf(timeouts, "%30i", &timeout);
3101 /* XXX maybe put an upper bound, or prevent the use of 0 ? */
3104 ao2_lock(s->session);
3105 if (s->session->waiting_thread != AST_PTHREADT_NULL) {
3106 pthread_kill(s->session->waiting_thread, SIGURG);
3109 if (s->session->managerid) { /* AMI-over-HTTP session */
3111 * Make sure the timeout is within the expire time of the session,
3112 * as the client will likely abort the request if it does not see
3113 * data coming after some amount of time.
3115 time_t now = time(NULL);
3116 int max = s->session->sessiontimeout - now - 10;
3118 if (max < 0) { /* We are already late. Strange but possible. */
3121 if (timeout < 0 || timeout > max) {
3124 if (!s->session->send_events) { /* make sure we record events */
3125 s->session->send_events = -1;
3128 ao2_unlock(s->session);
3130 /* XXX should this go inside the lock ? */
3131 s->session->waiting_thread = pthread_self(); /* let new events wake up this thread */
3132 ast_debug(1, "Starting waiting for an event!\n");
3134 for (x = 0; x < timeout || timeout < 0; x++) {
3135 ao2_lock(s->session);
3136 if (AST_RWLIST_NEXT(s->session->last_ev, eq_next)) {
3139 /* We can have multiple HTTP session point to the same mansession entry.
3140 * The way we deal with it is not very nice: newcomers kick out the previous
3141 * HTTP session. XXX this needs to be improved.
3143 if (s->session->waiting_thread != pthread_self()) {
3146 if (s->session->needdestroy) {
3149 ao2_unlock(s->session);
3153 if (s->session->managerid == 0) { /* AMI session */
3154 if (ast_wait_for_input(s->session->fd, 1000)) {
3157 } else { /* HTTP session */
3161 ast_debug(1, "Finished waiting for an event!\n");
3163 ao2_lock(s->session);
3164 if (s->session->waiting_thread == pthread_self()) {
3165 struct eventqent *eqe = s->session->last_ev;
3166 astman_send_response(s, m, "Success", "Waiting for Event completed.");
3167 while ((eqe = advance_event(eqe))) {
3168 if (((s->session->readperm & eqe->category) == eqe->category) &&
3169 ((s->session->send_events & eqe->category) == eqe->category)) {
3170 astman_append(s, "%s", eqe->eventdata);
3172 s->session->last_ev = eqe;
3175 "Event: WaitEventComplete\r\n"
3178 s->session->waiting_thread = AST_PTHREADT_NULL;
3180 ast_debug(1, "Abandoning event request!\n");
3182 ao2_unlock(s->session);
3187 static int action_listcommands(struct mansession *s, const struct message *m)
3189 struct manager_action *cur;
3190 struct ast_str *temp = ast_str_alloca(256);
3192 astman_start_ack(s, m);
3193 AST_RWLIST_RDLOCK(&actions);
3194 AST_RWLIST_TRAVERSE(&actions, cur, list) {
3195 if ((s->session->writeperm & cur->authority) || cur->authority == 0) {
3196 astman_append(s, "%s: %s (Priv: %s)\r\n",
3197 cur->action, cur->synopsis, authority_to_str(cur->authority, &temp));
3200 AST_RWLIST_UNLOCK(&actions);
3201 astman_append(s, "\r\n");
3206 static int action_events(struct mansession *s, const struct message *m)
3208 const char *mask = astman_get_header(m, "EventMask");
3210 const char *id = astman_get_header(m, "ActionID");
3213 if (!ast_strlen_zero(id)) {
3214 snprintf(id_text, sizeof(id_text), "ActionID: %s\r\n", id);
3219 res = set_eventmask(s, mask);
3220 if (broken_events_action) {
3221 /* if this option is set we should not return a response on
3222 * error, or when all events are set */
3225 for (x = 0; x < ARRAY_LEN(perms); x++) {
3226 if (!strcasecmp(perms[x].label, "all") && res == perms[x].num) {
3230 astman_append(s, "Response: Success\r\n%s"
3231 "Events: On\r\n\r\n", id_text);
3232 } else if (res == 0)
3233 astman_append(s, "Response: Success\r\n%s"
3234 "Events: Off\r\n\r\n", id_text);
3239 astman_append(s, "Response: Success\r\n%s"
3240 "Events: On\r\n\r\n", id_text);
3242 astman_append(s, "Response: Success\r\n%s"
3243 "Events: Off\r\n\r\n", id_text);
3245 astman_send_error(s, m, "Invalid event mask");
3250 static int action_logoff(struct mansession *s, const struct message *m)
3252 astman_send_response(s, m, "Goodbye", "Thanks for all the fish.");
3256 static int action_login(struct mansession *s, const struct message *m)
3259 /* still authenticated - don't process again */
3260 if (s->session->authenticated) {
3261 astman_send_ack(s, m, "Already authenticated");
3265 if (authenticate(s, m)) {
3267 astman_send_error(s, m, "Authentication failed");
3270 s->session->authenticated = 1;
3271 ast_atomic_fetchadd_int(&unauth_sessions, -1);
3272 if (manager_displayconnects(s->session)) {
3273 ast_verb(2, "%sManager '%s' logged on from %s\n", (s->session->managerid ? "HTTP " : ""), s->session->username, ast_sockaddr_stringify_addr(&s->session->addr));
3275 astman_send_ack(s, m, "Authentication accepted");
3276 if ((s->session->send_events & EVENT_FLAG_SYSTEM)
3277 && ast_test_flag(&ast_options, AST_OPT_FLAG_FULLY_BOOTED)) {
3278 struct ast_str *auth = ast_str_alloca(80);
3279 const char *cat_str = authority_to_str(EVENT_FLAG_SYSTEM, &auth);
3280 astman_append(s, "Event: FullyBooted\r\n"
3282 "Status: Fully Booted\r\n\r\n", cat_str);
3287 static int action_challenge(struct mansession *s, const struct message *m)
3289 const char *authtype = astman_get_header(m, "AuthType");
3291 if (!strcasecmp(authtype, "MD5")) {
3292 if (ast_strlen_zero(s->session->challenge)) {
3293 snprintf(s->session->challenge, sizeof(s->session->challenge), "%ld", ast_random());
3296 astman_start_ack(s, m);
3297 astman_append(s, "Challenge: %s\r\n\r\n", s->session->challenge);
3298 mansession_unlock(s);
3300 astman_send_error(s, m, "Must specify AuthType");
3305 static int action_hangup(struct mansession *s, const struct message *m)
3307 struct ast_channel *c = NULL;
3308 int causecode = 0; /* all values <= 0 mean 'do not set hangupcause in channel' */
3309 const char *id = astman_get_header(m, "ActionID");
3310 const char *name_or_regex = astman_get_header(m, "Channel");
3311 const char *cause = astman_get_header(m, "Cause");
3314 struct ast_channel_iterator *iter = NULL;
3315 struct ast_str *regex_string;
3316 int channels_matched = 0;
3318 if (ast_strlen_zero(name_or_regex)) {
3319 astman_send_error(s, m, "No channel specified");
3323 if (!ast_strlen_zero(id)) {
3324 snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
3329 if (!ast_strlen_zero(cause)) {
3331 causecode = strtol(cause, &endptr, 10);
3332 if (causecode < 0 || causecode > 127 || *endptr != '\0') {
3333 ast_log(LOG_NOTICE, "Invalid 'Cause: %s' in manager action Hangup\n", cause);
3334 /* keep going, better to hangup without cause than to not hang up at all */
3335 causecode = 0; /* do not set channel's hangupcause */
3339 /************************************************/
3340 /* Regular explicit match channel byname hangup */
3342 if (name_or_regex[0] != '/') {
3343 if (!(c = ast_channel_get_by_name(name_or_regex))) {
3344 ast_log(LOG_NOTICE, "!!!!!!!!!! Can't find channel to hang up!\n");
3345 astman_send_error(s, m, "No such channel");
3349 ast_verb(3, "%sManager '%s' from %s, hanging up channel: %s\n",
3350 (s->session->managerid ? "HTTP " : ""),
3351 s->session->username,
3352 ast_sockaddr_stringify_addr(&s->session->addr),
3353 ast_channel_name(c));
3355 ast_channel_softhangup_withcause_locked(c, causecode);
3356 c = ast_channel_unref(c);
3358 astman_send_ack(s, m, "Channel Hungup");
3363 /***********************************************/
3364 /* find and hangup any channels matching regex */
3366 regex_string = ast_str_create(strlen(name_or_regex));
3367 if (!regex_string) {
3368 astman_send_error(s, m, "Memory Allocation Failure");
3372 /* Make "/regex/" into "regex" */
3373 if (ast_regex_string_to_regex_pattern(name_or_regex, ®ex_string) != 0) {
3374 astman_send_error(s, m, "Regex format invalid, Channel param should be /regex/");
3375 ast_free(regex_string);
3379 /* if regex compilation fails, hangup fails */
3380 if (regcomp(®exbuf, ast_str_buffer(regex_string), REG_EXTENDED | REG_NOSUB)) {
3381 astman_send_error_va(s, m, "Regex compile failed on: %s\n", name_or_regex);
3382 ast_free(regex_string);
3386 astman_send_listack(s, m, "Channels hung up will follow", "start");
3388 iter = ast_channel_iterator_all_new();
3390 for (; (c = ast_channel_iterator_next(iter)); ast_channel_unref(c)) {
3391 if (regexec(®exbuf, ast_channel_name(c), 0, NULL, 0)) {
3395 ast_verb(3, "%sManager '%s' from %s, hanging up channel: %s\n",
3396 (s->session->managerid ? "HTTP " : ""),
3397 s->session->username,
3398 ast_sockaddr_stringify_addr(&s->session->addr),
3399 ast_channel_name(c));
3401 ast_channel_softhangup_withcause_locked(c, causecode);
3405 "Event: ChannelHungup\r\n"
3408 "\r\n", ast_channel_name(c), idText);
3410 ast_channel_iterator_destroy(iter);
3414 ast_free(regex_string);
3417 "Event: ChannelsHungupListComplete\r\n"
3418 "EventList: Complete\r\n"
3421 "\r\n", channels_matched, idText);
3426 static int action_setvar(struct mansession *s, const struct message *m)
3428 struct ast_channel *c = NULL;
3429 const char *name = astman_get_header(m, "Channel");
3430 const char *varname = astman_get_header(m, "Variable");
3431 const char *varval = astman_get_header(m, "Value");
3434 if (ast_strlen_zero(varname)) {
3435 astman_send_error(s, m, "No variable specified");
3439 if (!ast_strlen_zero(name)) {
3440 if (!(c = ast_channel_get_by_name(name))) {
3441 astman_send_error(s, m, "No such channel");
3446 res = pbx_builtin_setvar_helper(c, varname, S_OR(varval, ""));
3449 c = ast_channel_unref(c);
3452 astman_send_ack(s, m, "Variable Set");
3454 astman_send_error(s, m, "Variable not set");
3459 static int action_getvar(struct mansession *s, const struct message *m)
3461 struct ast_channel *c = NULL;
3462 const char *name = astman_get_header(m, "Channel");
3463 const char *varname = astman_get_header(m, "Variable");
3465 char workspace[1024];
3467 if (ast_strlen_zero(varname)) {
3468 astman_send_error(s, m, "No variable specified");
3472 /* We don't want users with insufficient permissions using certain functions. */
3473 if (!(function_capable_string_allowed_with_auths(varname, s->session->writeperm))) {
3474 astman_send_error(s, m, "GetVar Access Forbidden: Variable");
3478 if (!ast_strlen_zero(name)) {
3479 if (!(c = ast_channel_get_by_name(name))) {
3480 astman_send_error(s, m, "No such channel");
3485 workspace[0] = '\0';
3486 if (varname[strlen(varname) - 1] == ')') {