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"
94 #include "asterisk/stasis.h"
95 #include "asterisk/stasis_message_router.h"
96 #include "asterisk/test.h"
97 #include "asterisk/json.h"
98 #include "asterisk/bridging.h"
101 <manager name="Ping" language="en_US">
106 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
109 <para>A 'Ping' action will ellicit a 'Pong' response. Used to keep the
110 manager connection open.</para>
113 <manager name="Events" language="en_US">
118 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
119 <parameter name="EventMask" required="true">
122 <para>If all events should be sent.</para>
125 <para>If no events should be sent.</para>
127 <enum name="system,call,log,...">
128 <para>To select which flags events should have to be sent.</para>
134 <para>Enable/Disable sending of events to this manager client.</para>
137 <manager name="Logoff" language="en_US">
142 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
145 <para>Logoff the current manager session.</para>
148 <manager name="Login" language="en_US">
153 <parameter name="ActionID">
154 <para>ActionID for this transaction. Will be returned.</para>
156 <parameter name="Username" required="true">
157 <para>Username to login with as specified in manager.conf.</para>
159 <parameter name="Secret">
160 <para>Secret to login with as specified in manager.conf.</para>
164 <para>Login Manager.</para>
167 <manager name="Challenge" language="en_US">
169 Generate Challenge for MD5 Auth.
172 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
173 <parameter name="AuthType" required="true">
174 <para>Digest algorithm to use in the challenge. Valid values are:</para>
181 <para>Generate a challenge for MD5 authentication.</para>
184 <manager name="Hangup" language="en_US">
189 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
190 <parameter name="Channel" required="true">
191 <para>The exact channel name to be hungup, or to use a regular expression, set this parameter to: /regex/</para>
192 <para>Example exact channel: SIP/provider-0000012a</para>
193 <para>Example regular expression: /^SIP/provider-.*$/</para>
195 <parameter name="Cause">
196 <para>Numeric hangup cause.</para>
200 <para>Hangup a channel.</para>
203 <manager name="Status" language="en_US">
208 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
209 <parameter name="Channel" required="true">
210 <para>The name of the channel to query for status.</para>
212 <parameter name="Variables">
213 <para>Comma <literal>,</literal> separated list of variable to include.</para>
217 <para>Will return the status information of each channel along with the
218 value for the specified channel variables.</para>
221 <manager name="Setvar" language="en_US">
223 Set a channel variable.
226 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
227 <parameter name="Channel">
228 <para>Channel to set variable for.</para>
230 <parameter name="Variable" required="true">
231 <para>Variable name.</para>
233 <parameter name="Value" required="true">
234 <para>Variable value.</para>
238 <para>Set a global or local channel variable.</para>
240 <para>If a channel name is not provided then the variable is global.</para>
244 <manager name="Getvar" language="en_US">
246 Gets a channel variable.
249 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
250 <parameter name="Channel">
251 <para>Channel to read variable from.</para>
253 <parameter name="Variable" required="true">
254 <para>Variable name.</para>
258 <para>Get the value of a global or local channel variable.</para>
260 <para>If a channel name is not provided then the variable is global.</para>
264 <manager name="GetConfig" language="en_US">
266 Retrieve configuration.
269 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
270 <parameter name="Filename" required="true">
271 <para>Configuration filename (e.g. <filename>foo.conf</filename>).</para>
273 <parameter name="Category">
274 <para>Category in configuration file.</para>
278 <para>This action will dump the contents of a configuration
279 file by category and contents or optionally by specified category only.</para>
282 <manager name="GetConfigJSON" language="en_US">
284 Retrieve configuration (JSON format).
287 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
288 <parameter name="Filename" required="true">
289 <para>Configuration filename (e.g. <filename>foo.conf</filename>).</para>
293 <para>This action will dump the contents of a configuration file by category
294 and contents in JSON format. This only makes sense to be used using rawman over
295 the HTTP interface.</para>
298 <manager name="UpdateConfig" language="en_US">
300 Update basic configuration.
303 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
304 <parameter name="SrcFilename" required="true">
305 <para>Configuration filename to read (e.g. <filename>foo.conf</filename>).</para>
307 <parameter name="DstFilename" required="true">
308 <para>Configuration filename to write (e.g. <filename>foo.conf</filename>)</para>
310 <parameter name="Reload">
311 <para>Whether or not a reload should take place (or name of specific module).</para>
313 <parameter name="Action-XXXXXX">
314 <para>Action to take.</para>
315 <para>X's represent 6 digit number beginning with 000000.</para>
317 <enum name="NewCat" />
318 <enum name="RenameCat" />
319 <enum name="DelCat" />
320 <enum name="EmptyCat" />
321 <enum name="Update" />
322 <enum name="Delete" />
323 <enum name="Append" />
324 <enum name="Insert" />
327 <parameter name="Cat-XXXXXX">
328 <para>Category to operate on.</para>
329 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-XXXXXX']/para[2])" />
331 <parameter name="Var-XXXXXX">
332 <para>Variable to work on.</para>
333 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-XXXXXX']/para[2])" />
335 <parameter name="Value-XXXXXX">
336 <para>Value to work on.</para>
337 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-XXXXXX']/para[2])" />
339 <parameter name="Match-XXXXXX">
340 <para>Extra match required to match line.</para>
341 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-XXXXXX']/para[2])" />
343 <parameter name="Line-XXXXXX">
344 <para>Line in category to operate on (used with delete and insert actions).</para>
345 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-XXXXXX']/para[2])" />
349 <para>This action will modify, create, or delete configuration elements
350 in Asterisk configuration files.</para>
353 <manager name="CreateConfig" language="en_US">
355 Creates an empty file in the configuration directory.
358 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
359 <parameter name="Filename" required="true">
360 <para>The configuration filename to create (e.g. <filename>foo.conf</filename>).</para>
364 <para>This action will create an empty file in the configuration
365 directory. This action is intended to be used before an UpdateConfig
369 <manager name="ListCategories" language="en_US">
371 List categories in configuration file.
374 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
375 <parameter name="Filename" required="true">
376 <para>Configuration filename (e.g. <filename>foo.conf</filename>).</para>
380 <para>This action will dump the categories in a given file.</para>
383 <manager name="Redirect" language="en_US">
385 Redirect (transfer) a call.
388 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
389 <parameter name="Channel" required="true">
390 <para>Channel to redirect.</para>
392 <parameter name="ExtraChannel">
393 <para>Second call leg to transfer (optional).</para>
395 <parameter name="Exten" required="true">
396 <para>Extension to transfer to.</para>
398 <parameter name="ExtraExten">
399 <para>Extension to transfer extrachannel to (optional).</para>
401 <parameter name="Context" required="true">
402 <para>Context to transfer to.</para>
404 <parameter name="ExtraContext">
405 <para>Context to transfer extrachannel to (optional).</para>
407 <parameter name="Priority" required="true">
408 <para>Priority to transfer to.</para>
410 <parameter name="ExtraPriority">
411 <para>Priority to transfer extrachannel to (optional).</para>
415 <para>Redirect (transfer) a call.</para>
418 <manager name="Atxfer" language="en_US">
423 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
424 <parameter name="Channel" required="true">
425 <para>Transferer's channel.</para>
427 <parameter name="Exten" required="true">
428 <para>Extension to transfer to.</para>
430 <parameter name="Context" required="true">
431 <para>Context to transfer to.</para>
433 <parameter name="Priority" required="true">
434 <para>Priority to transfer to.</para>
438 <para>Attended transfer.</para>
441 <manager name="Originate" language="en_US">
446 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
447 <parameter name="Channel" required="true">
448 <para>Channel name to call.</para>
450 <parameter name="Exten">
451 <para>Extension to use (requires <literal>Context</literal> and
452 <literal>Priority</literal>)</para>
454 <parameter name="Context">
455 <para>Context to use (requires <literal>Exten</literal> and
456 <literal>Priority</literal>)</para>
458 <parameter name="Priority">
459 <para>Priority to use (requires <literal>Exten</literal> and
460 <literal>Context</literal>)</para>
462 <parameter name="Application">
463 <para>Application to execute.</para>
465 <parameter name="Data">
466 <para>Data to use (requires <literal>Application</literal>).</para>
468 <parameter name="Timeout" default="30000">
469 <para>How long to wait for call to be answered (in ms.).</para>
471 <parameter name="CallerID">
472 <para>Caller ID to be set on the outgoing channel.</para>
474 <parameter name="Variable">
475 <para>Channel variable to set, multiple Variable: headers are allowed.</para>
477 <parameter name="Account">
478 <para>Account code.</para>
480 <parameter name="EarlyMedia">
481 <para>Set to <literal>true</literal> to force call bridge on early media..</para>
483 <parameter name="Async">
484 <para>Set to <literal>true</literal> for fast origination.</para>
486 <parameter name="Codecs">
487 <para>Comma-separated list of codecs to use for this call.</para>
491 <para>Generates an outgoing call to a
492 <replaceable>Extension</replaceable>/<replaceable>Context</replaceable>/<replaceable>Priority</replaceable>
493 or <replaceable>Application</replaceable>/<replaceable>Data</replaceable></para>
496 <ref type="managerEvent">OriginateResponse</ref>
499 <managerEvent language="en_US" name="OriginateResponse">
500 <managerEventInstance class="EVENT_FLAG_CALL">
501 <synopsis>Raised in response to an Originate command.</synopsis>
503 <parameter name="ActionID" required="false"/>
504 <parameter name="Resonse">
506 <enum name="Failure"/>
507 <enum name="Success"/>
510 <parameter name="Channel"/>
511 <parameter name="Context"/>
512 <parameter name="Exten"/>
513 <parameter name="Reason"/>
514 <parameter name="Uniqueid"/>
515 <parameter name="CallerIDNum"/>
516 <parameter name="CallerIDName"/>
519 <ref type="manager">Originate</ref>
521 </managerEventInstance>
523 <manager name="Command" language="en_US">
525 Execute Asterisk CLI Command.
528 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
529 <parameter name="Command" required="true">
530 <para>Asterisk CLI command to run.</para>
534 <para>Run a CLI command.</para>
537 <manager name="ExtensionState" language="en_US">
539 Check Extension Status.
542 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
543 <parameter name="Exten" required="true">
544 <para>Extension to check state on.</para>
546 <parameter name="Context" required="true">
547 <para>Context for extension.</para>
551 <para>Report the extension state for given extension. If the extension has a hint,
552 will use devicestate to check the status of the device connected to the extension.</para>
553 <para>Will return an <literal>Extension Status</literal> message. The response will include
554 the hint for the extension and the status.</para>
557 <manager name="PresenceState" language="en_US">
562 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
563 <parameter name="Provider" required="true">
564 <para>Presence Provider to check the state of</para>
568 <para>Report the presence state for the given presence provider.</para>
569 <para>Will return a <literal>Presence State</literal> message. The response will include the
570 presence state and, if set, a presence subtype and custom message.</para>
573 <manager name="AbsoluteTimeout" language="en_US">
575 Set absolute timeout.
578 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
579 <parameter name="Channel" required="true">
580 <para>Channel name to hangup.</para>
582 <parameter name="Timeout" required="true">
583 <para>Maximum duration of the call (sec).</para>
587 <para>Hangup a channel after a certain time. Acknowledges set time with
588 <literal>Timeout Set</literal> message.</para>
591 <manager name="MailboxStatus" language="en_US">
596 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
597 <parameter name="Mailbox" required="true">
598 <para>Full mailbox ID <replaceable>mailbox</replaceable>@<replaceable>vm-context</replaceable>.</para>
602 <para>Checks a voicemail account for status.</para>
603 <para>Returns whether there are messages waiting.</para>
604 <para>Message: Mailbox Status.</para>
605 <para>Mailbox: <replaceable>mailboxid</replaceable>.</para>
606 <para>Waiting: <literal>0</literal> if messages waiting, <literal>1</literal>
607 if no messages waiting.</para>
610 <manager name="MailboxCount" language="en_US">
612 Check Mailbox Message Count.
615 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
616 <parameter name="Mailbox" required="true">
617 <para>Full mailbox ID <replaceable>mailbox</replaceable>@<replaceable>vm-context</replaceable>.</para>
621 <para>Checks a voicemail account for new messages.</para>
622 <para>Returns number of urgent, new and old messages.</para>
623 <para>Message: Mailbox Message Count</para>
624 <para>Mailbox: <replaceable>mailboxid</replaceable></para>
625 <para>UrgentMessages: <replaceable>count</replaceable></para>
626 <para>NewMessages: <replaceable>count</replaceable></para>
627 <para>OldMessages: <replaceable>count</replaceable></para>
630 <manager name="ListCommands" language="en_US">
632 List available manager commands.
635 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
638 <para>Returns the action name and synopsis for every action that
639 is available to the user.</para>
642 <manager name="SendText" language="en_US">
644 Send text message to channel.
647 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
648 <parameter name="Channel" required="true">
649 <para>Channel to send message to.</para>
651 <parameter name="Message" required="true">
652 <para>Message to send.</para>
656 <para>Sends A Text Message to a channel while in a call.</para>
659 <manager name="UserEvent" language="en_US">
661 Send an arbitrary event.
664 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
665 <parameter name="UserEvent" required="true">
666 <para>Event string to send.</para>
668 <parameter name="Header1">
669 <para>Content1.</para>
671 <parameter name="HeaderN">
672 <para>ContentN.</para>
676 <para>Send an event to manager sessions.</para>
679 <manager name="WaitEvent" language="en_US">
681 Wait for an event to occur.
684 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
685 <parameter name="Timeout" required="true">
686 <para>Maximum time (in seconds) to wait for events, <literal>-1</literal> means forever.</para>
690 <para>This action will ellicit a <literal>Success</literal> response. Whenever
691 a manager event is queued. Once WaitEvent has been called on an HTTP manager
692 session, events will be generated and queued.</para>
695 <manager name="CoreSettings" language="en_US">
697 Show PBX core settings (version etc).
700 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
703 <para>Query for Core PBX settings.</para>
706 <manager name="CoreStatus" language="en_US">
708 Show PBX core status variables.
711 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
714 <para>Query for Core PBX status.</para>
717 <manager name="Reload" language="en_US">
722 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
723 <parameter name="Module">
724 <para>Name of the module to reload.</para>
728 <para>Send a reload event.</para>
731 <manager name="CoreShowChannels" language="en_US">
733 List currently active channels.
736 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
739 <para>List currently defined channels and some information about them.</para>
742 <manager name="ModuleLoad" language="en_US">
747 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
748 <parameter name="Module">
749 <para>Asterisk module name (including .so extension) or subsystem identifier:</para>
752 <enum name="dnsmgr" />
753 <enum name="extconfig" />
756 <enum name="manager" />
758 <enum name="logger" />
759 <enum name="features" />
761 <enum name="udptl" />
762 <enum name="indications" />
767 <parameter name="LoadType" required="true">
768 <para>The operation to be done on module. Subsystem identifiers may only
772 <enum name="unload" />
773 <enum name="reload" />
775 <para>If no module is specified for a <literal>reload</literal> loadtype,
776 all modules are reloaded.</para>
780 <para>Loads, unloads or reloads an Asterisk module in a running system.</para>
783 <manager name="ModuleCheck" language="en_US">
785 Check if module is loaded.
788 <parameter name="Module" required="true">
789 <para>Asterisk module name (not including extension).</para>
793 <para>Checks if Asterisk module is loaded. Will return Success/Failure.
794 For success returns, the module revision number is included.</para>
797 <manager name="AOCMessage" language="en_US">
799 Generate an Advice of Charge message on a channel.
802 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
803 <parameter name="Channel" required="true">
804 <para>Channel name to generate the AOC message on.</para>
806 <parameter name="ChannelPrefix">
807 <para>Partial channel prefix. By using this option one can match the beginning part
808 of a channel name without having to put the entire name in. For example
809 if a channel name is SIP/snom-00000001 and this value is set to SIP/snom, then
810 that channel matches and the message will be sent. Note however that only
811 the first matched channel has the message sent on it. </para>
813 <parameter name="MsgType" required="true">
814 <para>Defines what type of AOC message to create, AOC-D or AOC-E</para>
820 <parameter name="ChargeType" required="true">
821 <para>Defines what kind of charge this message represents.</para>
825 <enum name="Currency" />
829 <parameter name="UnitAmount(0)">
830 <para>This represents the amount of units charged. The ETSI AOC standard specifies that
831 this value along with the optional UnitType value are entries in a list. To accommodate this
832 these values take an index value starting at 0 which can be used to generate this list of
833 unit entries. For Example, If two unit entires were required this could be achieved by setting the
834 paramter UnitAmount(0)=1234 and UnitAmount(1)=5678. Note that UnitAmount at index 0 is
835 required when ChargeType=Unit, all other entries in the list are optional.
838 <parameter name="UnitType(0)">
839 <para>Defines the type of unit. ETSI AOC standard specifies this as an integer
840 value between 1 and 16, but this value is left open to accept any positive
841 integer. Like the UnitAmount parameter, this value represents a list entry
842 and has an index parameter that starts at 0.
845 <parameter name="CurrencyName">
846 <para>Specifies the currency's name. Note that this value is truncated after 10 characters.</para>
848 <parameter name="CurrencyAmount">
849 <para>Specifies the charge unit amount as a positive integer. This value is required
850 when ChargeType==Currency.</para>
852 <parameter name="CurrencyMultiplier">
853 <para>Specifies the currency multiplier. This value is required when ChargeType==Currency.</para>
855 <enum name="OneThousandth" />
856 <enum name="OneHundredth" />
857 <enum name="OneTenth" />
860 <enum name="Hundred" />
861 <enum name="Thousand" />
864 <parameter name="TotalType" default="Total">
865 <para>Defines what kind of AOC-D total is represented.</para>
867 <enum name="Total" />
868 <enum name="SubTotal" />
871 <parameter name="AOCBillingId">
872 <para>Represents a billing ID associated with an AOC-D or AOC-E message. Note
873 that only the first 3 items of the enum are valid AOC-D billing IDs</para>
875 <enum name="Normal" />
876 <enum name="ReverseCharge" />
877 <enum name="CreditCard" />
878 <enum name="CallFwdUnconditional" />
879 <enum name="CallFwdBusy" />
880 <enum name="CallFwdNoReply" />
881 <enum name="CallDeflection" />
882 <enum name="CallTransfer" />
885 <parameter name="ChargingAssociationId">
886 <para>Charging association identifier. This is optional for AOC-E and can be
887 set to any value between -32768 and 32767</para>
889 <parameter name="ChargingAssociationNumber">
890 <para>Represents the charging association party number. This value is optional
893 <parameter name="ChargingAssociationPlan">
894 <para>Integer representing the charging plan associated with the ChargingAssociationNumber.
895 The value is bits 7 through 1 of the Q.931 octet containing the type-of-number and
896 numbering-plan-identification fields.</para>
900 <para>Generates an AOC-D or AOC-E message on a channel.</para>
903 <function name="AMI_CLIENT" language="en_US">
905 Checks attributes of manager accounts
908 <parameter name="loginname" required="true">
909 <para>Login name, specified in manager.conf</para>
911 <parameter name="field" required="true">
912 <para>The manager account attribute to return</para>
914 <enum name="sessions"><para>The number of sessions for this AMI account</para></enum>
920 Currently, the only supported parameter is "sessions" which will return the current number of
921 active sessions for this AMI account.
925 <manager name="Filter" language="en_US">
927 Dynamically add filters for the current manager session.
930 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
931 <parameter name="Operation">
934 <para>Add a filter.</para>
938 <parameter name="Filter">
939 <para>Filters can be whitelist or blacklist</para>
940 <para>Example whitelist filter: "Event: Newchannel"</para>
941 <para>Example blacklist filter: "!Channel: DAHDI.*"</para>
942 <para>This filter option is used to whitelist or blacklist events per user to be
943 reported with regular expressions and are allowed if both the regex matches
944 and the user has read access as defined in manager.conf. Filters are assumed to be for whitelisting
945 unless preceeded by an exclamation point, which marks it as being black.
946 Evaluation of the filters is as follows:</para>
947 <para>- If no filters are configured all events are reported as normal.</para>
948 <para>- If there are white filters only: implied black all filter processed first, then white filters.</para>
949 <para>- If there are black filters only: implied white all filter processed first, then black filters.</para>
950 <para>- If there are both white and black filters: implied black all filter processed first, then white
951 filters, and lastly black filters.</para>
955 <para>The filters added are only used for the current session.
956 Once the connection is closed the filters are removed.</para>
957 <para>This comand requires the system permission because
958 this command can be used to create filters that may bypass
959 filters defined in manager.conf</para>
962 <manager name="FilterList" language="en_US">
964 Show current event filters for this session
967 <para>The filters displayed are for the current session. Only those filters defined in
968 manager.conf will be present upon starting a new session.</para>
971 <manager name="BlindTransfer" language="en_US">
973 Blind transfer channel(s) to the given destination
976 <parameter name="Channel" required="true">
978 <parameter name="Context">
980 <parameter name="Exten">
984 <para>Redirect all channels currently bridged to the specified channel to the specified destination.</para>
987 <ref type="manager">Redirect</ref>
992 /*! \addtogroup Group_AMI AMI functions
1000 UNSPECIFIED_CATEGORY,
1001 UNSPECIFIED_ARGUMENT,
1011 enum add_filter_result {
1013 FILTER_ALLOC_FAILED,
1014 FILTER_COMPILE_FAIL,
1018 * Linked list of events.
1019 * Global events are appended to the list by append_event().
1020 * The usecount is the number of stored pointers to the element,
1021 * excluding the list pointers. So an element that is only in
1022 * the list has a usecount of 0, not 1.
1024 * Clients have a pointer to the last event processed, and for each
1025 * of these clients we track the usecount of the elements.
1026 * If we have a pointer to an entry in the list, it is safe to navigate
1027 * it forward because elements will not be deleted, but only appended.
1028 * The worst that can happen is seeing the pointer still NULL.
1030 * When the usecount of an element drops to 0, and the element is the
1031 * first in the list, we can remove it. Removal is done within the
1032 * main thread, which is woken up for the purpose.
1034 * For simplicity of implementation, we make sure the list is never empty.
1037 int usecount; /*!< # of clients who still need the event */
1039 unsigned int seq; /*!< sequence number */
1040 struct timeval tv; /*!< When event was allocated */
1041 AST_RWLIST_ENTRY(eventqent) eq_next;
1042 char eventdata[1]; /*!< really variable size, allocated by append_event() */
1045 static AST_RWLIST_HEAD_STATIC(all_events, eventqent);
1047 static int displayconnects = 1;
1048 static int allowmultiplelogin = 1;
1049 static int timestampevents;
1050 static int httptimeout = 60;
1051 static int broken_events_action = 0;
1052 static int manager_enabled = 0;
1053 static int webmanager_enabled = 0;
1054 static int manager_debug = 0; /*!< enable some debugging code in the manager */
1055 static int authtimeout;
1056 static int authlimit;
1057 static char *manager_channelvars;
1059 #define DEFAULT_REALM "asterisk"
1060 static char global_realm[MAXHOSTNAMELEN]; /*!< Default realm */
1062 static int block_sockets;
1063 static int unauth_sessions = 0;
1064 static struct stasis_subscription *acl_change_sub;
1066 /*! \brief A \ref stasis_topic that all topics AMI cares about will be forwarded to */
1067 static struct stasis_topic *manager_topic;
1069 /*! \brief The \ref stasis_message_router for all \ref stasis messages */
1070 static struct stasis_message_router *stasis_router;
1072 #define MGR_SHOW_TERMINAL_WIDTH 80
1074 #define MAX_VARS 128
1077 * Descriptor for a manager session, either on the AMI socket or over HTTP.
1080 * AMI session have managerid == 0; the entry is created upon a connect,
1081 * and destroyed with the socket.
1082 * HTTP sessions have managerid != 0, the value is used as a search key
1083 * to lookup sessions (using the mansession_id cookie, or nonce key from
1084 * Digest Authentication http header).
1086 #define MAX_BLACKLIST_CMD_LEN 2
1087 static const struct {
1088 const char *words[AST_MAX_CMD_LEN];
1089 } command_blacklist[] = {
1090 {{ "module", "load", NULL }},
1091 {{ "module", "unload", NULL }},
1092 {{ "restart", "gracefully", NULL }},
1095 static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_topic *topic, struct stasis_message *message);
1097 static void acl_change_stasis_subscribe(void)
1099 if (!acl_change_sub) {
1100 acl_change_sub = stasis_subscribe(ast_security_topic(),
1101 acl_change_stasis_cb, NULL);
1105 static void acl_change_stasis_unsubscribe(void)
1107 acl_change_sub = stasis_unsubscribe_and_join(acl_change_sub);
1110 /* In order to understand what the heck is going on with the
1111 * mansession_session and mansession structs, we need to have a bit of a history
1114 * In the beginning, there was the mansession. The mansession contained data that was
1115 * intrinsic to a manager session, such as the time that it started, the name of the logged-in
1116 * user, etc. In addition to these parameters were the f and fd parameters. For typical manager
1117 * sessions, these were used to represent the TCP socket over which the AMI session was taking
1118 * place. It makes perfect sense for these fields to be a part of the session-specific data since
1119 * the session actually defines this information.
1121 * Then came the HTTP AMI sessions. With these, the f and fd fields need to be opened and closed
1122 * for every single action that occurs. Thus the f and fd fields aren't really specific to the session
1123 * but rather to the action that is being executed. Because a single session may execute many commands
1124 * at once, some sort of safety needed to be added in order to be sure that we did not end up with fd
1125 * leaks from one action overwriting the f and fd fields used by a previous action before the previous action
1126 * has had a chance to properly close its handles.
1128 * The initial idea to solve this was to use thread synchronization, but this prevented multiple actions
1129 * from being run at the same time in a single session. Some manager actions may block for a long time, thus
1130 * creating a large queue of actions to execute. In addition, this fix did not address the basic architectural
1131 * issue that for HTTP manager sessions, the f and fd variables are not really a part of the session, but are
1132 * part of the action instead.
1134 * The new idea was to create a structure on the stack for each HTTP Manager action. This structure would
1135 * contain the action-specific information, such as which file to write to. In order to maintain expectations
1136 * of action handlers and not have to change the public API of the manager code, we would need to name this
1137 * new stacked structure 'mansession' and contain within it the old mansession struct that we used to use.
1138 * We renamed the old mansession struct 'mansession_session' to hopefully convey that what is in this structure
1139 * is session-specific data. The structure that it is wrapped in, called a 'mansession' really contains action-specific
1142 struct mansession_session {
1143 /*! \todo XXX need to document which fields it is protecting */
1144 struct ast_sockaddr addr; /*!< address we are connecting from */
1145 FILE *f; /*!< fdopen() on the underlying fd */
1146 int fd; /*!< descriptor used for output. Either the socket (AMI) or a temporary file (HTTP) */
1147 int inuse; /*!< number of HTTP sessions using this entry */
1148 int needdestroy; /*!< Whether an HTTP session should be destroyed */
1149 pthread_t waiting_thread; /*!< Sleeping thread using this descriptor */
1150 uint32_t managerid; /*!< Unique manager identifier, 0 for AMI sessions */
1151 time_t sessionstart; /*!< Session start time */
1152 struct timeval sessionstart_tv; /*!< Session start time */
1153 time_t sessiontimeout; /*!< Session timeout if HTTP */
1154 char username[80]; /*!< Logged in username */
1155 char challenge[10]; /*!< Authentication challenge */
1156 int authenticated; /*!< Authentication status */
1157 int readperm; /*!< Authorization for reading */
1158 int writeperm; /*!< Authorization for writing */
1159 char inbuf[1025]; /*!< Buffer - we use the extra byte to add a '\\0' and simplify parsing */
1160 int inlen; /*!< number of buffered bytes */
1161 struct ao2_container *whitefilters; /*!< Manager event filters - white list */
1162 struct ao2_container *blackfilters; /*!< Manager event filters - black list */
1163 struct ast_variable *chanvars; /*!< Channel variables to set for originate */
1164 int send_events; /*!< XXX what ? */
1165 struct eventqent *last_ev; /*!< last event processed. */
1166 int writetimeout; /*!< Timeout for ast_carefulwrite() */
1168 int pending_event; /*!< Pending events indicator in case when waiting_thread is NULL */
1169 time_t noncetime; /*!< Timer for nonce value expiration */
1170 unsigned long oldnonce; /*!< Stale nonce value */
1171 unsigned long nc; /*!< incremental nonce counter */
1172 AST_LIST_HEAD_NOLOCK(mansession_datastores, ast_datastore) datastores; /*!< Data stores on the session */
1173 AST_LIST_ENTRY(mansession_session) list;
1176 enum mansession_message_parsing {
1178 MESSAGE_LINE_TOO_LONG
1181 /*! \brief In case you didn't read that giant block of text above the mansession_session struct, the
1182 * \ref struct mansession is named this solely to keep the API the same in Asterisk. This structure really
1183 * represents data that is different from Manager action to Manager action. The mansession_session pointer
1184 * contained within points to session-specific data.
1187 struct mansession_session *session;
1188 struct ast_tcptls_session_instance *tcptls_session;
1191 enum mansession_message_parsing parsing;
1193 struct manager_custom_hook *hook;
1197 static struct ao2_container *sessions = NULL;
1199 /*! \brief user descriptor, as read from the config file.
1201 * \note It is still missing some fields -- e.g. we can have multiple permit and deny
1202 * lines which are not supported here, and readperm/writeperm/writetimeout
1205 struct ast_manager_user {
1207 char *secret; /*!< Secret for logging in */
1208 int readperm; /*!< Authorization for reading */
1209 int writeperm; /*!< Authorization for writing */
1210 int writetimeout; /*!< Per user Timeout for ast_carefulwrite() */
1211 int displayconnects; /*!< XXX unused */
1212 int keep; /*!< mark entries created on a reload */
1213 struct ao2_container *whitefilters; /*!< Manager event filters - white list */
1214 struct ao2_container *blackfilters; /*!< Manager event filters - black list */
1215 struct ast_acl_list *acl; /*!< ACL setting */
1216 char *a1_hash; /*!< precalculated A1 for Digest auth */
1217 struct ast_variable *chanvars; /*!< Channel variables to set for originate */
1218 AST_RWLIST_ENTRY(ast_manager_user) list;
1221 /*! \brief list of users found in the config file */
1222 static AST_RWLIST_HEAD_STATIC(users, ast_manager_user);
1224 /*! \brief list of actions registered */
1225 static AST_RWLIST_HEAD_STATIC(actions, manager_action);
1227 /*! \brief list of hooks registered */
1228 static AST_RWLIST_HEAD_STATIC(manager_hooks, manager_custom_hook);
1230 /*! \brief A container of event documentation nodes */
1231 AO2_GLOBAL_OBJ_STATIC(event_docs);
1233 static enum add_filter_result manager_add_filter(const char *filter_pattern, struct ao2_container *whitefilters, struct ao2_container *blackfilters);
1236 * @{ \brief Define AMI message types.
1238 STASIS_MESSAGE_TYPE_DEFN(ast_manager_get_generic_type);
1243 * \brief Find a registered action object.
1245 * \param name Name of AMI action to find.
1247 * \return Reffed action found or NULL
1249 static struct manager_action *action_find(const char *name)
1251 struct manager_action *act;
1253 AST_RWLIST_RDLOCK(&actions);
1254 AST_RWLIST_TRAVERSE(&actions, act, list) {
1255 if (!strcasecmp(name, act->action)) {
1256 ao2_t_ref(act, +1, "found action object");
1260 AST_RWLIST_UNLOCK(&actions);
1265 struct stasis_topic *ast_manager_get_topic(void)
1267 return manager_topic;
1270 struct stasis_message_router *ast_manager_get_message_router(void)
1272 return stasis_router;
1275 struct ast_str *ast_manager_str_from_json_object(struct ast_json *blob, key_exclusion_cb exclusion_cb)
1277 struct ast_str *output_str = ast_str_create(32);
1278 struct ast_json *value;
1284 ast_json_object_foreach(blob, key, value) {
1285 if (exclusion_cb && exclusion_cb(key)) {
1288 ast_str_append(&output_str, 0, "%s: %s\r\n", key, ast_json_string_get(value));
1297 static void manager_generic_msg_cb(void *data, struct stasis_subscription *sub,
1298 struct stasis_topic *topic,
1299 struct stasis_message *message)
1301 struct ast_json_payload *payload = stasis_message_data(message);
1302 int class_type = ast_json_integer_get(ast_json_object_get(payload->json, "class_type"));
1303 const char *type = ast_json_string_get(ast_json_object_get(payload->json, "type"));
1304 struct ast_json *event = ast_json_object_get(payload->json, "event");
1305 RAII_VAR(struct ast_str *, event_buffer, NULL, ast_free);
1307 event_buffer = ast_manager_str_from_json_object(event, NULL);
1308 if (!event_buffer) {
1309 ast_log(AST_LOG_WARNING, "Error while creating payload for event %s\n", type);
1312 manager_event(class_type, type, "%s", ast_str_buffer(event_buffer));
1315 int ast_manager_publish_message(struct ast_json *obj)
1317 RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
1318 RAII_VAR(struct ast_json_payload *, payload, NULL, ao2_cleanup);
1319 struct ast_json *type = ast_json_object_get(obj, "type");
1320 struct ast_json *class_type = ast_json_object_get(obj, "class_type");
1321 struct ast_json *event = ast_json_object_get(obj, "event");
1324 ast_log(AST_LOG_ERROR, "Attempt to send generic manager event without type field\n");
1328 ast_log(AST_LOG_ERROR, "Attempt to send generic manager event without class type field\n");
1332 ast_log(AST_LOG_ERROR, "Attempt to send generic manager event without event payload\n");
1336 payload = ast_json_payload_create(obj);
1340 message = stasis_message_create(ast_manager_get_generic_type(), payload);
1344 stasis_publish(ast_manager_get_topic(), message);
1348 /*! \brief Add a custom hook to be called when an event is fired */
1349 void ast_manager_register_hook(struct manager_custom_hook *hook)
1351 AST_RWLIST_WRLOCK(&manager_hooks);
1352 AST_RWLIST_INSERT_TAIL(&manager_hooks, hook, list);
1353 AST_RWLIST_UNLOCK(&manager_hooks);
1356 /*! \brief Delete a custom hook to be called when an event is fired */
1357 void ast_manager_unregister_hook(struct manager_custom_hook *hook)
1359 AST_RWLIST_WRLOCK(&manager_hooks);
1360 AST_RWLIST_REMOVE(&manager_hooks, hook, list);
1361 AST_RWLIST_UNLOCK(&manager_hooks);
1364 int check_manager_enabled(void)
1366 return manager_enabled;
1369 int check_webmanager_enabled(void)
1371 return (webmanager_enabled && manager_enabled);
1375 * Grab a reference to the last event, update usecount as needed.
1376 * Can handle a NULL pointer.
1378 static struct eventqent *grab_last(void)
1380 struct eventqent *ret;
1382 AST_RWLIST_WRLOCK(&all_events);
1383 ret = AST_RWLIST_LAST(&all_events);
1384 /* the list is never empty now, but may become so when
1385 * we optimize it in the future, so be prepared.
1388 ast_atomic_fetchadd_int(&ret->usecount, 1);
1390 AST_RWLIST_UNLOCK(&all_events);
1395 * Purge unused events. Remove elements from the head
1396 * as long as their usecount is 0 and there is a next element.
1398 static void purge_events(void)
1400 struct eventqent *ev;
1401 struct timeval now = ast_tvnow();
1403 AST_RWLIST_WRLOCK(&all_events);
1404 while ( (ev = AST_RWLIST_FIRST(&all_events)) &&
1405 ev->usecount == 0 && AST_RWLIST_NEXT(ev, eq_next)) {
1406 AST_RWLIST_REMOVE_HEAD(&all_events, eq_next);
1410 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&all_events, ev, eq_next) {
1411 /* Never release the last event */
1412 if (!AST_RWLIST_NEXT(ev, eq_next)) {
1416 /* 2.5 times whatever the HTTP timeout is (maximum 2.5 hours) is the maximum time that we will definitely cache an event */
1417 if (ev->usecount == 0 && ast_tvdiff_sec(now, ev->tv) > (httptimeout > 3600 ? 3600 : httptimeout) * 2.5) {
1418 AST_RWLIST_REMOVE_CURRENT(eq_next);
1422 AST_RWLIST_TRAVERSE_SAFE_END;
1423 AST_RWLIST_UNLOCK(&all_events);
1427 * helper functions to convert back and forth between
1428 * string and numeric representation of set of flags
1430 static const struct permalias {
1434 { EVENT_FLAG_SYSTEM, "system" },
1435 { EVENT_FLAG_CALL, "call" },
1436 { EVENT_FLAG_LOG, "log" },
1437 { EVENT_FLAG_VERBOSE, "verbose" },
1438 { EVENT_FLAG_COMMAND, "command" },
1439 { EVENT_FLAG_AGENT, "agent" },
1440 { EVENT_FLAG_USER, "user" },
1441 { EVENT_FLAG_CONFIG, "config" },
1442 { EVENT_FLAG_DTMF, "dtmf" },
1443 { EVENT_FLAG_REPORTING, "reporting" },
1444 { EVENT_FLAG_CDR, "cdr" },
1445 { EVENT_FLAG_DIALPLAN, "dialplan" },
1446 { EVENT_FLAG_ORIGINATE, "originate" },
1447 { EVENT_FLAG_AGI, "agi" },
1448 { EVENT_FLAG_CC, "cc" },
1449 { EVENT_FLAG_AOC, "aoc" },
1450 { EVENT_FLAG_TEST, "test" },
1451 { EVENT_FLAG_MESSAGE, "message" },
1456 /*! \brief Checks to see if a string which can be used to evaluate functions should be rejected */
1457 static int function_capable_string_allowed_with_auths(const char *evaluating, int writepermlist)
1459 if (!(writepermlist & EVENT_FLAG_SYSTEM)
1461 strstr(evaluating, "SHELL") || /* NoOp(${SHELL(rm -rf /)}) */
1462 strstr(evaluating, "EVAL") /* NoOp(${EVAL(${some_var_containing_SHELL})}) */
1469 /*! \brief Convert authority code to a list of options for a user. This will only
1470 * display those authority codes that have an explicit match on authority */
1471 static const char *user_authority_to_str(int authority, struct ast_str **res)
1476 ast_str_reset(*res);
1477 for (i = 0; i < ARRAY_LEN(perms) - 1; i++) {
1478 if ((authority & perms[i].num) == perms[i].num) {
1479 ast_str_append(res, 0, "%s%s", sep, perms[i].label);
1484 if (ast_str_strlen(*res) == 0) /* replace empty string with something sensible */
1485 ast_str_append(res, 0, "<none>");
1487 return ast_str_buffer(*res);
1491 /*! \brief Convert authority code to a list of options. Note that the EVENT_FLAG_ALL
1492 * authority will always be returned. */
1493 static const char *authority_to_str(int authority, struct ast_str **res)
1498 ast_str_reset(*res);
1499 for (i = 0; i < ARRAY_LEN(perms) - 1; i++) {
1500 if (authority & perms[i].num) {
1501 ast_str_append(res, 0, "%s%s", sep, perms[i].label);
1506 if (ast_str_strlen(*res) == 0) /* replace empty string with something sensible */
1507 ast_str_append(res, 0, "<none>");
1509 return ast_str_buffer(*res);
1512 /*! Tells you if smallstr exists inside bigstr
1513 which is delim by delim and uses no buf or stringsep
1514 ast_instring("this|that|more","this",'|') == 1;
1516 feel free to move this to app.c -anthm */
1517 static int ast_instring(const char *bigstr, const char *smallstr, const char delim)
1519 const char *val = bigstr, *next;
1522 if ((next = strchr(val, delim))) {
1523 if (!strncmp(val, smallstr, (next - val))) {
1529 return !strcmp(smallstr, val);
1531 } while (*(val = (next + 1)));
1536 static int get_perm(const char *instr)
1544 for (x = 0; x < ARRAY_LEN(perms); x++) {
1545 if (ast_instring(instr, perms[x].label, ',')) {
1546 ret |= perms[x].num;
1554 * A number returns itself, false returns 0, true returns all flags,
1555 * other strings return the flags that are set.
1557 static int strings_to_mask(const char *string)
1561 if (ast_strlen_zero(string)) {
1565 for (p = string; *p; p++) {
1566 if (*p < '0' || *p > '9') {
1570 if (!*p) { /* all digits */
1571 return atoi(string);
1573 if (ast_false(string)) {
1576 if (ast_true(string)) { /* all permissions */
1578 for (x = 0; x < ARRAY_LEN(perms); x++) {
1579 ret |= perms[x].num;
1583 return get_perm(string);
1586 /*! \brief Unreference manager session object.
1587 If no more references, then go ahead and delete it */
1588 static struct mansession_session *unref_mansession(struct mansession_session *s)
1590 int refcount = ao2_ref(s, -1);
1591 if (manager_debug) {
1592 ast_debug(1, "Mansession: %p refcount now %d\n", s, refcount - 1);
1597 static void event_filter_destructor(void *obj)
1599 regex_t *regex_filter = obj;
1600 regfree(regex_filter);
1603 static void session_destructor(void *obj)
1605 struct mansession_session *session = obj;
1606 struct eventqent *eqe = session->last_ev;
1607 struct ast_datastore *datastore;
1609 /* Get rid of each of the data stores on the session */
1610 while ((datastore = AST_LIST_REMOVE_HEAD(&session->datastores, entry))) {
1611 /* Free the data store */
1612 ast_datastore_free(datastore);
1615 if (session->f != NULL) {
1619 ast_atomic_fetchadd_int(&eqe->usecount, -1);
1621 if (session->chanvars) {
1622 ast_variables_destroy(session->chanvars);
1625 if (session->whitefilters) {
1626 ao2_t_callback(session->whitefilters, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL, "unlink all white filters");
1627 ao2_t_ref(session->whitefilters, -1 , "decrement ref for white container, should be last one");
1630 if (session->blackfilters) {
1631 ao2_t_callback(session->blackfilters, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL, "unlink all black filters");
1632 ao2_t_ref(session->blackfilters, -1 , "decrement ref for black container, should be last one");
1636 /*! \brief Allocate manager session structure and add it to the list of sessions */
1637 static struct mansession_session *build_mansession(const struct ast_sockaddr *addr)
1639 struct mansession_session *newsession;
1641 if (!(newsession = ao2_alloc(sizeof(*newsession), session_destructor))) {
1645 if (!(newsession->whitefilters = ao2_container_alloc(1, NULL, NULL))) {
1646 ao2_ref(newsession, -1);
1650 if (!(newsession->blackfilters = ao2_container_alloc(1, NULL, NULL))) {
1651 ao2_ref(newsession, -1); /* session_destructor will cleanup the other filter */
1655 newsession->fd = -1;
1656 newsession->waiting_thread = AST_PTHREADT_NULL;
1657 newsession->writetimeout = 100;
1658 newsession->send_events = -1;
1659 ast_sockaddr_copy(&newsession->addr, addr);
1661 ao2_link(sessions, newsession);
1666 static int mansession_cmp_fn(void *obj, void *arg, int flags)
1668 struct mansession_session *s = obj;
1670 return !strcasecmp(s->username, str) ? CMP_MATCH : 0;
1673 static void session_destroy(struct mansession_session *s)
1675 unref_mansession(s);
1676 ao2_unlink(sessions, s);
1680 static int check_manager_session_inuse(const char *name)
1682 struct mansession_session *session = ao2_find(sessions, (char *) name, 0);
1687 unref_mansession(session);
1694 * lookup an entry in the list of registered users.
1695 * must be called with the list lock held.
1697 static struct ast_manager_user *get_manager_by_name_locked(const char *name)
1699 struct ast_manager_user *user = NULL;
1701 AST_RWLIST_TRAVERSE(&users, user, list) {
1702 if (!strcasecmp(user->username, name)) {
1710 /*! \brief Get displayconnects config option.
1711 * \param session manager session to get parameter from.
1712 * \return displayconnects config option value.
1714 static int manager_displayconnects (struct mansession_session *session)
1716 struct ast_manager_user *user = NULL;
1719 AST_RWLIST_RDLOCK(&users);
1720 if ((user = get_manager_by_name_locked (session->username))) {
1721 ret = user->displayconnects;
1723 AST_RWLIST_UNLOCK(&users);
1728 static char *handle_showmancmd(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1730 struct manager_action *cur;
1731 struct ast_str *authority;
1735 char syntax_title[64], description_title[64], synopsis_title[64], seealso_title[64], arguments_title[64], privilege_title[64];
1740 e->command = "manager show command";
1742 "Usage: manager show command <actionname> [<actionname> [<actionname> [...]]]\n"
1743 " Shows the detailed description for a specific Asterisk manager interface command.\n";
1746 l = strlen(a->word);
1748 AST_RWLIST_RDLOCK(&actions);
1749 AST_RWLIST_TRAVERSE(&actions, cur, list) {
1750 if (!strncasecmp(a->word, cur->action, l) && ++which > a->n) {
1751 ret = ast_strdup(cur->action);
1752 break; /* make sure we exit even if ast_strdup() returns NULL */
1755 AST_RWLIST_UNLOCK(&actions);
1758 authority = ast_str_alloca(80);
1760 return CLI_SHOWUSAGE;
1764 /* setup the titles */
1765 term_color(synopsis_title, "[Synopsis]\n", COLOR_MAGENTA, 0, 40);
1766 term_color(description_title, "[Description]\n", COLOR_MAGENTA, 0, 40);
1767 term_color(syntax_title, "[Syntax]\n", COLOR_MAGENTA, 0, 40);
1768 term_color(seealso_title, "[See Also]\n", COLOR_MAGENTA, 0, 40);
1769 term_color(arguments_title, "[Arguments]\n", COLOR_MAGENTA, 0, 40);
1770 term_color(privilege_title, "[Privilege]\n", COLOR_MAGENTA, 0, 40);
1773 AST_RWLIST_RDLOCK(&actions);
1774 AST_RWLIST_TRAVERSE(&actions, cur, list) {
1775 for (num = 3; num < a->argc; num++) {
1776 if (!strcasecmp(cur->action, a->argv[num])) {
1777 authority_to_str(cur->authority, &authority);
1780 if (cur->docsrc == AST_XML_DOC) {
1781 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",
1783 ast_xmldoc_printable(S_OR(cur->syntax, "Not available"), 1),
1785 ast_xmldoc_printable(S_OR(cur->synopsis, "Not available"), 1),
1787 ast_xmldoc_printable(S_OR(cur->description, "Not available"), 1),
1789 ast_xmldoc_printable(S_OR(cur->arguments, "Not available"), 1),
1791 ast_xmldoc_printable(S_OR(cur->seealso, "Not available"), 1),
1793 ast_xmldoc_printable(S_OR(authority->str, "Not available"), 1));
1797 ast_cli(a->fd, "Action: %s\nSynopsis: %s\nPrivilege: %s\n%s\n",
1798 cur->action, cur->synopsis,
1800 S_OR(cur->description, ""));
1805 AST_RWLIST_UNLOCK(&actions);
1810 static char *handle_mandebug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1814 e->command = "manager set debug [on|off]";
1815 e->usage = "Usage: manager set debug [on|off]\n Show, enable, disable debugging of the manager code.\n";
1822 ast_cli(a->fd, "manager debug is %s\n", manager_debug? "on" : "off");
1823 } else if (a->argc == 4) {
1824 if (!strcasecmp(a->argv[3], "on")) {
1826 } else if (!strcasecmp(a->argv[3], "off")) {
1829 return CLI_SHOWUSAGE;
1835 static char *handle_showmanager(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1837 struct ast_manager_user *user = NULL;
1840 struct ast_str *rauthority = ast_str_alloca(128);
1841 struct ast_str *wauthority = ast_str_alloca(128);
1842 struct ast_variable *v;
1846 e->command = "manager show user";
1848 " Usage: manager show user <user>\n"
1849 " Display all information related to the manager user specified.\n";
1852 l = strlen(a->word);
1857 AST_RWLIST_RDLOCK(&users);
1858 AST_RWLIST_TRAVERSE(&users, user, list) {
1859 if ( !strncasecmp(a->word, user->username, l) && ++which > a->n ) {
1860 ret = ast_strdup(user->username);
1864 AST_RWLIST_UNLOCK(&users);
1869 return CLI_SHOWUSAGE;
1872 AST_RWLIST_RDLOCK(&users);
1874 if (!(user = get_manager_by_name_locked(a->argv[3]))) {
1875 ast_cli(a->fd, "There is no manager called %s\n", a->argv[3]);
1876 AST_RWLIST_UNLOCK(&users);
1880 ast_cli(a->fd, "\n");
1887 "displayconnects: %s\n",
1888 (user->username ? user->username : "(N/A)"),
1889 (user->secret ? "<Set>" : "(N/A)"),
1890 ((user->acl && !ast_acl_list_is_empty(user->acl)) ? "yes" : "no"),
1891 user_authority_to_str(user->readperm, &rauthority),
1892 user_authority_to_str(user->writeperm, &wauthority),
1893 (user->displayconnects ? "yes" : "no"));
1894 ast_cli(a->fd, " Variables: \n");
1895 for (v = user->chanvars ; v ; v = v->next) {
1896 ast_cli(a->fd, " %s = %s\n", v->name, v->value);
1899 AST_RWLIST_UNLOCK(&users);
1904 static char *handle_showmanagers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1906 struct ast_manager_user *user = NULL;
1910 e->command = "manager show users";
1912 "Usage: manager show users\n"
1913 " Prints a listing of all managers that are currently configured on that\n"
1920 return CLI_SHOWUSAGE;
1923 AST_RWLIST_RDLOCK(&users);
1925 /* If there are no users, print out something along those lines */
1926 if (AST_RWLIST_EMPTY(&users)) {
1927 ast_cli(a->fd, "There are no manager users.\n");
1928 AST_RWLIST_UNLOCK(&users);
1932 ast_cli(a->fd, "\nusername\n--------\n");
1934 AST_RWLIST_TRAVERSE(&users, user, list) {
1935 ast_cli(a->fd, "%s\n", user->username);
1939 AST_RWLIST_UNLOCK(&users);
1941 ast_cli(a->fd,"-------------------\n"
1942 "%d manager users configured.\n", count_amu);
1946 /*! \brief CLI command manager list commands */
1947 static char *handle_showmancmds(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1949 struct manager_action *cur;
1951 int space_remaining;
1952 #define HSMC_FORMAT " %-*.*s %-.*s\n"
1955 e->command = "manager show commands";
1957 "Usage: manager show commands\n"
1958 " Prints a listing of all the available Asterisk manager interface commands.\n";
1964 AST_RWLIST_RDLOCK(&actions);
1965 AST_RWLIST_TRAVERSE(&actions, cur, list) {
1966 int incoming_len = strlen(cur->action);
1967 if (incoming_len > name_len) {
1968 name_len = incoming_len;
1972 space_remaining = MGR_SHOW_TERMINAL_WIDTH - name_len - 4;
1973 if (space_remaining < 0) {
1974 space_remaining = 0;
1977 ast_cli(a->fd, HSMC_FORMAT, name_len, name_len, "Action", space_remaining, "Synopsis");
1978 ast_cli(a->fd, HSMC_FORMAT, name_len, name_len, "------", space_remaining, "--------");
1980 AST_RWLIST_TRAVERSE(&actions, cur, list) {
1981 ast_cli(a->fd, HSMC_FORMAT, name_len, name_len, cur->action, space_remaining, cur->synopsis);
1983 AST_RWLIST_UNLOCK(&actions);
1988 /*! \brief CLI command manager list connected */
1989 static char *handle_showmanconn(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1991 struct mansession_session *session;
1992 time_t now = time(NULL);
1993 #define HSMCONN_FORMAT1 " %-15.15s %-55.55s %-10.10s %-10.10s %-8.8s %-8.8s %-5.5s %-5.5s\n"
1994 #define HSMCONN_FORMAT2 " %-15.15s %-55.55s %-10d %-10d %-8d %-8d %-5.5d %-5.5d\n"
1996 struct ao2_iterator i;
2000 e->command = "manager show connected";
2002 "Usage: manager show connected\n"
2003 " Prints a listing of the users that are currently connected to the\n"
2004 "Asterisk manager interface.\n";
2010 ast_cli(a->fd, HSMCONN_FORMAT1, "Username", "IP Address", "Start", "Elapsed", "FileDes", "HttpCnt", "Read", "Write");
2012 i = ao2_iterator_init(sessions, 0);
2013 while ((session = ao2_iterator_next(&i))) {
2015 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);
2017 ao2_unlock(session);
2018 unref_mansession(session);
2020 ao2_iterator_destroy(&i);
2021 ast_cli(a->fd, "%d users connected.\n", count);
2026 /*! \brief CLI command manager list eventq */
2027 /* Should change to "manager show connected" */
2028 static char *handle_showmaneventq(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2030 struct eventqent *s;
2033 e->command = "manager show eventq";
2035 "Usage: manager show eventq\n"
2036 " Prints a listing of all events pending in the Asterisk manger\n"
2042 AST_RWLIST_RDLOCK(&all_events);
2043 AST_RWLIST_TRAVERSE(&all_events, s, eq_next) {
2044 ast_cli(a->fd, "Usecount: %d\n", s->usecount);
2045 ast_cli(a->fd, "Category: %d\n", s->category);
2046 ast_cli(a->fd, "Event:\n%s", s->eventdata);
2048 AST_RWLIST_UNLOCK(&all_events);
2053 /*! \brief CLI command manager reload */
2054 static char *handle_manager_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2058 e->command = "manager reload";
2060 "Usage: manager reload\n"
2061 " Reloads the manager configuration.\n";
2067 return CLI_SHOWUSAGE;
2073 static struct eventqent *advance_event(struct eventqent *e)
2075 struct eventqent *next;
2077 AST_RWLIST_RDLOCK(&all_events);
2078 if ((next = AST_RWLIST_NEXT(e, eq_next))) {
2079 ast_atomic_fetchadd_int(&next->usecount, 1);
2080 ast_atomic_fetchadd_int(&e->usecount, -1);
2082 AST_RWLIST_UNLOCK(&all_events);
2086 #define GET_HEADER_FIRST_MATCH 0
2087 #define GET_HEADER_LAST_MATCH 1
2088 #define GET_HEADER_SKIP_EMPTY 2
2091 * \brief Return a matching header value.
2094 * Generic function to return either the first or the last
2095 * matching header from a list of variables, possibly skipping
2098 * \note At the moment there is only one use of this function in
2099 * this file, so we make it static.
2101 * \note Never returns NULL.
2103 static const char *__astman_get_header(const struct message *m, char *var, int mode)
2105 int x, l = strlen(var);
2106 const char *result = "";
2112 for (x = 0; x < m->hdrcount; x++) {
2113 const char *h = m->headers[x];
2114 if (!strncasecmp(var, h, l) && h[l] == ':') {
2115 const char *value = h + l + 1;
2116 value = ast_skip_blanks(value); /* ignore leading spaces in the value */
2117 /* found a potential candidate */
2118 if ((mode & GET_HEADER_SKIP_EMPTY) && ast_strlen_zero(value)) {
2119 continue; /* not interesting */
2121 if (mode & GET_HEADER_LAST_MATCH) {
2122 result = value; /* record the last match so far */
2133 * \brief Return the first matching variable from an array.
2135 * \note This is the legacy function and is implemented in
2136 * therms of __astman_get_header().
2138 * \note Never returns NULL.
2140 const char *astman_get_header(const struct message *m, char *var)
2142 return __astman_get_header(m, var, GET_HEADER_FIRST_MATCH);
2147 * \brief Process one "Variable:" header value string.
2149 * \param head Current list of AMI variables to get new values added.
2150 * \param hdr_val Header value string to process.
2152 * \return New variable list head.
2154 static struct ast_variable *man_do_variable_value(struct ast_variable *head, const char *hdr_val)
2157 AST_DECLARE_APP_ARGS(args,
2158 AST_APP_ARG(vars)[64];
2161 hdr_val = ast_skip_blanks(hdr_val); /* ignore leading spaces in the value */
2162 parse = ast_strdupa(hdr_val);
2164 /* Break the header value string into name=val pair items. */
2165 AST_STANDARD_APP_ARGS(args, parse);
2169 /* Process each name=val pair item. */
2170 for (y = 0; y < args.argc; y++) {
2171 struct ast_variable *cur;
2175 if (!args.vars[y]) {
2178 var = val = args.vars[y];
2181 /* XXX We may wish to trim whitespace from the strings. */
2182 if (!val || ast_strlen_zero(var)) {
2186 /* Create new variable list node and prepend it to the list. */
2187 cur = ast_variable_new(var, val, "");
2198 struct ast_variable *astman_get_variables(const struct message *m)
2202 struct ast_variable *head = NULL;
2204 static const char var_hdr[] = "Variable:";
2206 /* Process all "Variable:" headers. */
2207 varlen = strlen(var_hdr);
2208 for (x = 0; x < m->hdrcount; x++) {
2209 if (strncasecmp(var_hdr, m->headers[x], varlen)) {
2212 head = man_do_variable_value(head, m->headers[x] + varlen);
2218 /*! \brief access for hooks to send action messages to ami */
2219 int ast_hook_send_action(struct manager_custom_hook *hook, const char *msg)
2223 struct manager_action *act_found;
2224 struct mansession s = {.session = NULL, };
2225 struct message m = { 0 };
2235 /* Create our own copy of the AMI action msg string. */
2236 src = dup_str = ast_strdup(msg);
2241 /* convert msg string to message struct */
2242 curlen = strlen(src);
2243 for (x = 0; x < curlen; x++) {
2244 int cr; /* set if we have \r */
2245 if (src[x] == '\r' && x+1 < curlen && src[x+1] == '\n')
2246 cr = 2; /* Found. Update length to include \r\n */
2247 else if (src[x] == '\n')
2248 cr = 1; /* also accept \n only */
2251 /* don't keep empty lines */
2252 if (x && m.hdrcount < ARRAY_LEN(m.headers)) {
2253 /* ... but trim \r\n and terminate the header string */
2255 m.headers[m.hdrcount++] = src;
2258 curlen -= x; /* remaining size */
2259 src += x; /* update pointer */
2260 x = -1; /* reset loop */
2263 action = astman_get_header(&m, "Action");
2264 if (strcasecmp(action, "login")) {
2265 act_found = action_find(action);
2268 * we have to simulate a session for this action request
2269 * to be able to pass it down for processing
2270 * This is necessary to meet the previous design of manager.c
2273 s.f = (void*)1; /* set this to something so our request will make it through all functions that test it*/
2275 ao2_lock(act_found);
2276 if (act_found->registered && act_found->func) {
2277 if (act_found->module) {
2278 ast_module_ref(act_found->module);
2280 ao2_unlock(act_found);
2281 ret = act_found->func(&s, &m);
2282 ao2_lock(act_found);
2283 if (act_found->module) {
2284 ast_module_unref(act_found->module);
2289 ao2_unlock(act_found);
2290 ao2_t_ref(act_found, -1, "done with found action object");
2299 * helper function to send a string to the socket.
2300 * Return -1 on error (e.g. buffer full).
2302 static int send_string(struct mansession *s, char *string)
2305 FILE *f = s->f ? s->f : s->session->f;
2306 int fd = s->f ? s->fd : s->session->fd;
2308 /* It's a result from one of the hook's action invocation */
2311 * to send responses, we're using the same function
2312 * as for receiving events. We call the event "HookResponse"
2314 s->hook->helper(EVENT_FLAG_HOOKRESPONSE, "HookResponse", string);
2318 if ((res = ast_careful_fwrite(f, fd, string, strlen(string), s->session->writetimeout))) {
2326 * \brief thread local buffer for astman_append
2328 * \note This can not be defined within the astman_append() function
2329 * because it declares a couple of functions that get used to
2330 * initialize the thread local storage key.
2332 AST_THREADSTORAGE(astman_append_buf);
2334 AST_THREADSTORAGE(userevent_buf);
2336 /*! \brief initial allocated size for the astman_append_buf and astman_send_*_va */
2337 #define ASTMAN_APPEND_BUF_INITSIZE 256
2340 * utility functions for creating AMI replies
2342 void astman_append(struct mansession *s, const char *fmt, ...)
2345 struct ast_str *buf;
2347 if (!(buf = ast_str_thread_get(&astman_append_buf, ASTMAN_APPEND_BUF_INITSIZE))) {
2352 ast_str_set_va(&buf, 0, fmt, ap);
2355 if (s->f != NULL || s->session->f != NULL) {
2356 send_string(s, ast_str_buffer(buf));
2358 ast_verbose("fd == -1 in astman_append, should not happen\n");
2362 /*! \note NOTE: XXX this comment is unclear and possibly wrong.
2363 Callers of astman_send_error(), astman_send_response() or astman_send_ack() must EITHER
2364 hold the session lock _or_ be running in an action callback (in which case s->session->busy will
2365 be non-zero). In either of these cases, there is no need to lock-protect the session's
2366 fd, since no other output will be sent (events will be queued), and no input will
2367 be read until either the current action finishes or get_input() obtains the session
2371 /*! \todo XXX MSG_MOREDATA should go to a header file. */
2372 #define MSG_MOREDATA ((char *)astman_send_response)
2374 /*! \brief send a response with an optional message,
2375 * and terminate it with an empty line.
2376 * m is used only to grab the 'ActionID' field.
2378 * Use the explicit constant MSG_MOREDATA to remove the empty line.
2379 * XXX MSG_MOREDATA should go to a header file.
2381 static void astman_send_response_full(struct mansession *s, const struct message *m, char *resp, char *msg, char *listflag)
2383 const char *id = astman_get_header(m, "ActionID");
2385 astman_append(s, "Response: %s\r\n", resp);
2386 if (!ast_strlen_zero(id)) {
2387 astman_append(s, "ActionID: %s\r\n", id);
2390 astman_append(s, "EventList: %s\r\n", listflag); /* Start, complete, cancelled */
2392 if (msg == MSG_MOREDATA) {
2395 astman_append(s, "Message: %s\r\n\r\n", msg);
2397 astman_append(s, "\r\n");
2401 void astman_send_response(struct mansession *s, const struct message *m, char *resp, char *msg)
2403 astman_send_response_full(s, m, resp, msg, NULL);
2406 void astman_send_error(struct mansession *s, const struct message *m, char *error)
2408 astman_send_response_full(s, m, "Error", error, NULL);
2411 void astman_send_error_va(struct mansession *s, const struct message *m, const char *fmt, ...)
2414 struct ast_str *buf;
2417 if (!(buf = ast_str_thread_get(&astman_append_buf, ASTMAN_APPEND_BUF_INITSIZE))) {
2422 ast_str_set_va(&buf, 0, fmt, ap);
2425 /* astman_append will use the same underlying buffer, so copy the message out
2426 * before sending the response */
2427 msg = ast_str_buffer(buf);
2429 msg = ast_strdupa(msg);
2431 astman_send_response_full(s, m, "Error", msg, NULL);
2434 void astman_send_ack(struct mansession *s, const struct message *m, char *msg)
2436 astman_send_response_full(s, m, "Success", msg, NULL);
2439 static void astman_start_ack(struct mansession *s, const struct message *m)
2441 astman_send_response_full(s, m, "Success", MSG_MOREDATA, NULL);
2444 void astman_send_listack(struct mansession *s, const struct message *m, char *msg, char *listflag)
2446 astman_send_response_full(s, m, "Success", msg, listflag);
2449 /*! \brief Lock the 'mansession' structure. */
2450 static void mansession_lock(struct mansession *s)
2452 ast_mutex_lock(&s->lock);
2455 /*! \brief Unlock the 'mansession' structure. */
2456 static void mansession_unlock(struct mansession *s)
2458 ast_mutex_unlock(&s->lock);
2462 Rather than braindead on,off this now can also accept a specific int mask value
2463 or a ',' delim list of mask strings (the same as manager.conf) -anthm
2465 static int set_eventmask(struct mansession *s, const char *eventmask)
2467 int maskint = strings_to_mask(eventmask);
2469 ao2_lock(s->session);
2471 s->session->send_events = maskint;
2473 ao2_unlock(s->session);
2478 static enum ast_transport mansession_get_transport(const struct mansession *s)
2480 return s->tcptls_session->parent->tls_cfg ? AST_TRANSPORT_TLS :
2484 static void report_invalid_user(const struct mansession *s, const char *username)
2486 char session_id[32];
2487 struct ast_security_event_inval_acct_id inval_acct_id = {
2488 .common.event_type = AST_SECURITY_EVENT_INVAL_ACCT_ID,
2489 .common.version = AST_SECURITY_EVENT_INVAL_ACCT_ID_VERSION,
2490 .common.service = "AMI",
2491 .common.account_id = username,
2492 .common.session_tv = &s->session->sessionstart_tv,
2493 .common.local_addr = {
2494 .addr = &s->tcptls_session->parent->local_address,
2495 .transport = mansession_get_transport(s),
2497 .common.remote_addr = {
2498 .addr = &s->session->addr,
2499 .transport = mansession_get_transport(s),
2501 .common.session_id = session_id,
2504 snprintf(session_id, sizeof(session_id), "%p", s);
2506 ast_security_event_report(AST_SEC_EVT(&inval_acct_id));
2509 static void report_failed_acl(const struct mansession *s, const char *username)
2511 char session_id[32];
2512 struct ast_security_event_failed_acl failed_acl_event = {
2513 .common.event_type = AST_SECURITY_EVENT_FAILED_ACL,
2514 .common.version = AST_SECURITY_EVENT_FAILED_ACL_VERSION,
2515 .common.service = "AMI",
2516 .common.account_id = username,
2517 .common.session_tv = &s->session->sessionstart_tv,
2518 .common.local_addr = {
2519 .addr = &s->tcptls_session->parent->local_address,
2520 .transport = mansession_get_transport(s),
2522 .common.remote_addr = {
2523 .addr = &s->session->addr,
2524 .transport = mansession_get_transport(s),
2526 .common.session_id = session_id,
2529 snprintf(session_id, sizeof(session_id), "%p", s->session);
2531 ast_security_event_report(AST_SEC_EVT(&failed_acl_event));
2534 static void report_inval_password(const struct mansession *s, const char *username)
2536 char session_id[32];
2537 struct ast_security_event_inval_password inval_password = {
2538 .common.event_type = AST_SECURITY_EVENT_INVAL_PASSWORD,
2539 .common.version = AST_SECURITY_EVENT_INVAL_PASSWORD_VERSION,
2540 .common.service = "AMI",
2541 .common.account_id = 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(&inval_password));
2559 static void report_auth_success(const struct mansession *s)
2561 char session_id[32];
2562 struct ast_security_event_successful_auth successful_auth = {
2563 .common.event_type = AST_SECURITY_EVENT_SUCCESSFUL_AUTH,
2564 .common.version = AST_SECURITY_EVENT_SUCCESSFUL_AUTH_VERSION,
2565 .common.service = "AMI",
2566 .common.account_id = s->session->username,
2567 .common.session_tv = &s->session->sessionstart_tv,
2568 .common.local_addr = {
2569 .addr = &s->tcptls_session->parent->local_address,
2570 .transport = mansession_get_transport(s),
2572 .common.remote_addr = {
2573 .addr = &s->session->addr,
2574 .transport = mansession_get_transport(s),
2576 .common.session_id = session_id,
2579 snprintf(session_id, sizeof(session_id), "%p", s->session);
2581 ast_security_event_report(AST_SEC_EVT(&successful_auth));
2584 static void report_req_not_allowed(const struct mansession *s, const char *action)
2586 char session_id[32];
2587 char request_type[64];
2588 struct ast_security_event_req_not_allowed req_not_allowed = {
2589 .common.event_type = AST_SECURITY_EVENT_REQ_NOT_ALLOWED,
2590 .common.version = AST_SECURITY_EVENT_REQ_NOT_ALLOWED_VERSION,
2591 .common.service = "AMI",
2592 .common.account_id = s->session->username,
2593 .common.session_tv = &s->session->sessionstart_tv,
2594 .common.local_addr = {
2595 .addr = &s->tcptls_session->parent->local_address,
2596 .transport = mansession_get_transport(s),
2598 .common.remote_addr = {
2599 .addr = &s->session->addr,
2600 .transport = mansession_get_transport(s),
2602 .common.session_id = session_id,
2604 .request_type = request_type,
2607 snprintf(session_id, sizeof(session_id), "%p", s->session);
2608 snprintf(request_type, sizeof(request_type), "Action: %s", action);
2610 ast_security_event_report(AST_SEC_EVT(&req_not_allowed));
2613 static void report_req_bad_format(const struct mansession *s, const char *action)
2615 char session_id[32];
2616 char request_type[64];
2617 struct ast_security_event_req_bad_format req_bad_format = {
2618 .common.event_type = AST_SECURITY_EVENT_REQ_BAD_FORMAT,
2619 .common.version = AST_SECURITY_EVENT_REQ_BAD_FORMAT_VERSION,
2620 .common.service = "AMI",
2621 .common.account_id = s->session->username,
2622 .common.session_tv = &s->session->sessionstart_tv,
2623 .common.local_addr = {
2624 .addr = &s->tcptls_session->parent->local_address,
2625 .transport = mansession_get_transport(s),
2627 .common.remote_addr = {
2628 .addr = &s->session->addr,
2629 .transport = mansession_get_transport(s),
2631 .common.session_id = session_id,
2633 .request_type = request_type,
2636 snprintf(session_id, sizeof(session_id), "%p", s->session);
2637 snprintf(request_type, sizeof(request_type), "Action: %s", action);
2639 ast_security_event_report(AST_SEC_EVT(&req_bad_format));
2642 static void report_failed_challenge_response(const struct mansession *s,
2643 const char *response, const char *expected_response)
2645 char session_id[32];
2646 struct ast_security_event_chal_resp_failed chal_resp_failed = {
2647 .common.event_type = AST_SECURITY_EVENT_CHAL_RESP_FAILED,
2648 .common.version = AST_SECURITY_EVENT_CHAL_RESP_FAILED_VERSION,
2649 .common.service = "AMI",
2650 .common.account_id = s->session->username,
2651 .common.session_tv = &s->session->sessionstart_tv,
2652 .common.local_addr = {
2653 .addr = &s->tcptls_session->parent->local_address,
2654 .transport = mansession_get_transport(s),
2656 .common.remote_addr = {
2657 .addr = &s->session->addr,
2658 .transport = mansession_get_transport(s),
2660 .common.session_id = session_id,
2662 .challenge = s->session->challenge,
2663 .response = response,
2664 .expected_response = expected_response,
2667 snprintf(session_id, sizeof(session_id), "%p", s->session);
2669 ast_security_event_report(AST_SEC_EVT(&chal_resp_failed));
2672 static void report_session_limit(const struct mansession *s)
2674 char session_id[32];
2675 struct ast_security_event_session_limit session_limit = {
2676 .common.event_type = AST_SECURITY_EVENT_SESSION_LIMIT,
2677 .common.version = AST_SECURITY_EVENT_SESSION_LIMIT_VERSION,
2678 .common.service = "AMI",
2679 .common.account_id = s->session->username,
2680 .common.session_tv = &s->session->sessionstart_tv,
2681 .common.local_addr = {
2682 .addr = &s->tcptls_session->parent->local_address,
2683 .transport = mansession_get_transport(s),
2685 .common.remote_addr = {
2686 .addr = &s->session->addr,
2687 .transport = mansession_get_transport(s),
2689 .common.session_id = session_id,
2692 snprintf(session_id, sizeof(session_id), "%p", s->session);
2694 ast_security_event_report(AST_SEC_EVT(&session_limit));
2698 * Here we start with action_ handlers for AMI actions,
2699 * and the internal functions used by them.
2700 * Generally, the handlers are called action_foo()
2703 /* helper function for action_login() */
2704 static int authenticate(struct mansession *s, const struct message *m)
2706 const char *username = astman_get_header(m, "Username");
2707 const char *password = astman_get_header(m, "Secret");
2709 struct ast_manager_user *user = NULL;
2710 regex_t *regex_filter;
2711 struct ao2_iterator filter_iter;
2713 if (ast_strlen_zero(username)) { /* missing username */
2717 /* locate user in locked state */
2718 AST_RWLIST_WRLOCK(&users);
2720 if (!(user = get_manager_by_name_locked(username))) {
2721 report_invalid_user(s, username);
2722 ast_log(LOG_NOTICE, "%s tried to authenticate with nonexistent user '%s'\n", ast_sockaddr_stringify_addr(&s->session->addr), username);
2723 } else if (user->acl && (ast_apply_acl(user->acl, &s->session->addr, "Manager User ACL: ") == AST_SENSE_DENY)) {
2724 report_failed_acl(s, username);
2725 ast_log(LOG_NOTICE, "%s failed to pass IP ACL as '%s'\n", ast_sockaddr_stringify_addr(&s->session->addr), username);
2726 } else if (!strcasecmp(astman_get_header(m, "AuthType"), "MD5")) {
2727 const char *key = astman_get_header(m, "Key");
2728 if (!ast_strlen_zero(key) && !ast_strlen_zero(s->session->challenge) && user->secret) {
2731 char md5key[256] = "";
2732 struct MD5Context md5;
2733 unsigned char digest[16];
2736 MD5Update(&md5, (unsigned char *) s->session->challenge, strlen(s->session->challenge));
2737 MD5Update(&md5, (unsigned char *) user->secret, strlen(user->secret));
2738 MD5Final(digest, &md5);
2739 for (x = 0; x < 16; x++)
2740 len += sprintf(md5key + len, "%2.2x", digest[x]);
2741 if (!strcmp(md5key, key)) {
2744 report_failed_challenge_response(s, key, md5key);
2747 ast_debug(1, "MD5 authentication is not possible. challenge: '%s'\n",
2748 S_OR(s->session->challenge, ""));
2750 } else if (user->secret) {
2751 if (!strcmp(password, user->secret)) {
2754 report_inval_password(s, username);
2759 ast_log(LOG_NOTICE, "%s failed to authenticate as '%s'\n", ast_sockaddr_stringify_addr(&s->session->addr), username);
2760 AST_RWLIST_UNLOCK(&users);
2766 /* All of the user parameters are copied to the session so that in the event
2767 * of a reload and a configuration change, the session parameters are not
2769 ast_copy_string(s->session->username, username, sizeof(s->session->username));
2770 s->session->readperm = user->readperm;
2771 s->session->writeperm = user->writeperm;
2772 s->session->writetimeout = user->writetimeout;
2773 if (user->chanvars) {
2774 s->session->chanvars = ast_variables_dup(user->chanvars);
2777 filter_iter = ao2_iterator_init(user->whitefilters, 0);
2778 while ((regex_filter = ao2_iterator_next(&filter_iter))) {
2779 ao2_t_link(s->session->whitefilters, regex_filter, "add white user filter to session");
2780 ao2_t_ref(regex_filter, -1, "remove iterator ref");
2782 ao2_iterator_destroy(&filter_iter);
2784 filter_iter = ao2_iterator_init(user->blackfilters, 0);
2785 while ((regex_filter = ao2_iterator_next(&filter_iter))) {
2786 ao2_t_link(s->session->blackfilters, regex_filter, "add black user filter to session");
2787 ao2_t_ref(regex_filter, -1, "remove iterator ref");
2789 ao2_iterator_destroy(&filter_iter);
2791 s->session->sessionstart = time(NULL);
2792 s->session->sessionstart_tv = ast_tvnow();
2793 set_eventmask(s, astman_get_header(m, "Events"));
2795 report_auth_success(s);
2797 AST_RWLIST_UNLOCK(&users);
2801 static int action_ping(struct mansession *s, const struct message *m)
2803 const char *actionid = astman_get_header(m, "ActionID");
2804 struct timeval now = ast_tvnow();
2806 astman_append(s, "Response: Success\r\n");
2807 if (!ast_strlen_zero(actionid)){
2808 astman_append(s, "ActionID: %s\r\n", actionid);
2813 "Timestamp: %ld.%06lu\r\n"
2815 (long) now.tv_sec, (unsigned long) now.tv_usec);
2819 static int action_getconfig(struct mansession *s, const struct message *m)
2821 struct ast_config *cfg;
2822 const char *fn = astman_get_header(m, "Filename");
2823 const char *category = astman_get_header(m, "Category");
2826 char *cur_category = NULL;
2827 struct ast_variable *v;
2828 struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
2830 if (ast_strlen_zero(fn)) {
2831 astman_send_error(s, m, "Filename not specified");
2834 cfg = ast_config_load2(fn, "manager", config_flags);
2835 if (cfg == CONFIG_STATUS_FILEMISSING) {
2836 astman_send_error(s, m, "Config file not found");
2838 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
2839 astman_send_error(s, m, "Config file has invalid format");
2843 astman_start_ack(s, m);
2844 while ((cur_category = ast_category_browse(cfg, cur_category))) {
2845 if (ast_strlen_zero(category) || (!ast_strlen_zero(category) && !strcmp(category, cur_category))) {
2847 astman_append(s, "Category-%06d: %s\r\n", catcount, cur_category);
2848 for (v = ast_variable_browse(cfg, cur_category); v; v = v->next) {
2849 astman_append(s, "Line-%06d-%06d: %s=%s\r\n", catcount, lineno++, v->name, v->value);
2854 if (!ast_strlen_zero(category) && catcount == 0) { /* TODO: actually, a config with no categories doesn't even get loaded */
2855 astman_append(s, "No categories found\r\n");
2857 ast_config_destroy(cfg);
2858 astman_append(s, "\r\n");
2863 static int action_listcategories(struct mansession *s, const struct message *m)
2865 struct ast_config *cfg;
2866 const char *fn = astman_get_header(m, "Filename");
2867 char *category = NULL;
2868 struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
2871 if (ast_strlen_zero(fn)) {
2872 astman_send_error(s, m, "Filename not specified");
2875 if (!(cfg = ast_config_load2(fn, "manager", config_flags))) {
2876 astman_send_error(s, m, "Config file not found");
2878 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
2879 astman_send_error(s, m, "Config file has invalid format");
2882 astman_start_ack(s, m);
2883 while ((category = ast_category_browse(cfg, category))) {
2884 astman_append(s, "Category-%06d: %s\r\n", catcount, category);
2887 if (catcount == 0) { /* TODO: actually, a config with no categories doesn't even get loaded */
2888 astman_append(s, "Error: no categories found\r\n");
2890 ast_config_destroy(cfg);
2891 astman_append(s, "\r\n");
2899 /*! The amount of space in out must be at least ( 2 * strlen(in) + 1 ) */
2900 static void json_escape(char *out, const char *in)
2903 if (*in == '\\' || *in == '\"') {
2913 * \brief Append a JSON escaped string to the manager stream.
2915 * \param s AMI stream to append a string.
2916 * \param str String to append to the stream after JSON escaping it.
2920 static void astman_append_json(struct mansession *s, const char *str)
2924 buf = ast_alloca(2 * strlen(str) + 1);
2925 json_escape(buf, str);
2926 astman_append(s, "%s", buf);
2929 static int action_getconfigjson(struct mansession *s, const struct message *m)
2931 struct ast_config *cfg;
2932 const char *fn = astman_get_header(m, "Filename");
2933 char *category = NULL;
2934 struct ast_variable *v;
2936 struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
2938 if (ast_strlen_zero(fn)) {
2939 astman_send_error(s, m, "Filename not specified");
2943 if (!(cfg = ast_config_load2(fn, "manager", config_flags))) {
2944 astman_send_error(s, m, "Config file not found");
2946 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
2947 astman_send_error(s, m, "Config file has invalid format");
2951 astman_start_ack(s, m);
2952 astman_append(s, "JSON: {");
2953 while ((category = ast_category_browse(cfg, category))) {
2956 astman_append(s, "%s\"", comma1 ? "," : "");
2957 astman_append_json(s, category);
2958 astman_append(s, "\":[");
2960 for (v = ast_variable_browse(cfg, category); v; v = v->next) {
2961 astman_append(s, "%s\"", comma2 ? "," : "");
2962 astman_append_json(s, v->name);
2963 astman_append(s, "\":\"");
2964 astman_append_json(s, v->value);
2965 astman_append(s, "\"");
2968 astman_append(s, "]");
2970 astman_append(s, "}\r\n\r\n");
2972 ast_config_destroy(cfg);
2977 /*! \brief helper function for action_updateconfig */
2978 static enum error_type handle_updates(struct mansession *s, const struct message *m, struct ast_config *cfg, const char *dfn)
2982 const char *action, *cat, *var, *value, *match, *line;
2983 struct ast_category *category;
2984 struct ast_variable *v;
2985 struct ast_str *str1 = ast_str_create(16), *str2 = ast_str_create(16);
2986 enum error_type result = 0;
2988 for (x = 0; x < 100000; x++) { /* 100000 = the max number of allowed updates + 1 */
2989 unsigned int object = 0;
2991 snprintf(hdr, sizeof(hdr), "Action-%06d", x);
2992 action = astman_get_header(m, hdr);
2993 if (ast_strlen_zero(action)) /* breaks the for loop if no action header */
2994 break; /* this could cause problems if actions come in misnumbered */
2996 snprintf(hdr, sizeof(hdr), "Cat-%06d", x);
2997 cat = astman_get_header(m, hdr);
2998 if (ast_strlen_zero(cat)) { /* every action needs a category */
2999 result = UNSPECIFIED_CATEGORY;
3003 snprintf(hdr, sizeof(hdr), "Var-%06d", x);
3004 var = astman_get_header(m, hdr);
3006 snprintf(hdr, sizeof(hdr), "Value-%06d", x);
3007 value = astman_get_header(m, hdr);
3009 if (!ast_strlen_zero(value) && *value == '>') {
3014 snprintf(hdr, sizeof(hdr), "Match-%06d", x);
3015 match = astman_get_header(m, hdr);
3017 snprintf(hdr, sizeof(hdr), "Line-%06d", x);
3018 line = astman_get_header(m, hdr);
3020 if (!strcasecmp(action, "newcat")) {
3021 if (ast_category_get(cfg,cat)) { /* check to make sure the cat doesn't */
3022 result = FAILURE_NEWCAT; /* already exist */
3025 if (!(category = ast_category_new(cat, dfn, -1))) {
3026 result = FAILURE_ALLOCATION;
3029 if (ast_strlen_zero(match)) {
3030 ast_category_append(cfg, category);
3032 ast_category_insert(cfg, category, match);
3034 } else if (!strcasecmp(action, "renamecat")) {
3035 if (ast_strlen_zero(value)) {
3036 result = UNSPECIFIED_ARGUMENT;
3039 if (!(category = ast_category_get(cfg, cat))) {
3040 result = UNKNOWN_CATEGORY;
3043 ast_category_rename(category, value);
3044 } else if (!strcasecmp(action, "delcat")) {
3045 if (ast_category_delete(cfg, cat)) {
3046 result = FAILURE_DELCAT;
3049 } else if (!strcasecmp(action, "emptycat")) {
3050 if (ast_category_empty(cfg, cat)) {