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 void ast_manager_publish_event(const char *type, int class_type, struct ast_json *obj)
1317 RAII_VAR(struct ast_json *, event_info, NULL, ast_json_unref);
1318 RAII_VAR(struct ast_json_payload *, payload, NULL, ao2_cleanup);
1319 RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
1326 event_info = ast_json_pack("{s: s, s: i, s: o}",
1328 "class_type", class_type,
1334 payload = ast_json_payload_create(event_info);
1338 message = stasis_message_create(ast_manager_get_generic_type(), payload);
1342 stasis_publish(ast_manager_get_topic(), message);
1345 /*! \brief Add a custom hook to be called when an event is fired */
1346 void ast_manager_register_hook(struct manager_custom_hook *hook)
1348 AST_RWLIST_WRLOCK(&manager_hooks);
1349 AST_RWLIST_INSERT_TAIL(&manager_hooks, hook, list);
1350 AST_RWLIST_UNLOCK(&manager_hooks);
1353 /*! \brief Delete a custom hook to be called when an event is fired */
1354 void ast_manager_unregister_hook(struct manager_custom_hook *hook)
1356 AST_RWLIST_WRLOCK(&manager_hooks);
1357 AST_RWLIST_REMOVE(&manager_hooks, hook, list);
1358 AST_RWLIST_UNLOCK(&manager_hooks);
1361 int check_manager_enabled(void)
1363 return manager_enabled;
1366 int check_webmanager_enabled(void)
1368 return (webmanager_enabled && manager_enabled);
1372 * Grab a reference to the last event, update usecount as needed.
1373 * Can handle a NULL pointer.
1375 static struct eventqent *grab_last(void)
1377 struct eventqent *ret;
1379 AST_RWLIST_WRLOCK(&all_events);
1380 ret = AST_RWLIST_LAST(&all_events);
1381 /* the list is never empty now, but may become so when
1382 * we optimize it in the future, so be prepared.
1385 ast_atomic_fetchadd_int(&ret->usecount, 1);
1387 AST_RWLIST_UNLOCK(&all_events);
1392 * Purge unused events. Remove elements from the head
1393 * as long as their usecount is 0 and there is a next element.
1395 static void purge_events(void)
1397 struct eventqent *ev;
1398 struct timeval now = ast_tvnow();
1400 AST_RWLIST_WRLOCK(&all_events);
1401 while ( (ev = AST_RWLIST_FIRST(&all_events)) &&
1402 ev->usecount == 0 && AST_RWLIST_NEXT(ev, eq_next)) {
1403 AST_RWLIST_REMOVE_HEAD(&all_events, eq_next);
1407 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&all_events, ev, eq_next) {
1408 /* Never release the last event */
1409 if (!AST_RWLIST_NEXT(ev, eq_next)) {
1413 /* 2.5 times whatever the HTTP timeout is (maximum 2.5 hours) is the maximum time that we will definitely cache an event */
1414 if (ev->usecount == 0 && ast_tvdiff_sec(now, ev->tv) > (httptimeout > 3600 ? 3600 : httptimeout) * 2.5) {
1415 AST_RWLIST_REMOVE_CURRENT(eq_next);
1419 AST_RWLIST_TRAVERSE_SAFE_END;
1420 AST_RWLIST_UNLOCK(&all_events);
1424 * helper functions to convert back and forth between
1425 * string and numeric representation of set of flags
1427 static const struct permalias {
1431 { EVENT_FLAG_SYSTEM, "system" },
1432 { EVENT_FLAG_CALL, "call" },
1433 { EVENT_FLAG_LOG, "log" },
1434 { EVENT_FLAG_VERBOSE, "verbose" },
1435 { EVENT_FLAG_COMMAND, "command" },
1436 { EVENT_FLAG_AGENT, "agent" },
1437 { EVENT_FLAG_USER, "user" },
1438 { EVENT_FLAG_CONFIG, "config" },
1439 { EVENT_FLAG_DTMF, "dtmf" },
1440 { EVENT_FLAG_REPORTING, "reporting" },
1441 { EVENT_FLAG_CDR, "cdr" },
1442 { EVENT_FLAG_DIALPLAN, "dialplan" },
1443 { EVENT_FLAG_ORIGINATE, "originate" },
1444 { EVENT_FLAG_AGI, "agi" },
1445 { EVENT_FLAG_CC, "cc" },
1446 { EVENT_FLAG_AOC, "aoc" },
1447 { EVENT_FLAG_TEST, "test" },
1448 { EVENT_FLAG_MESSAGE, "message" },
1453 /*! \brief Checks to see if a string which can be used to evaluate functions should be rejected */
1454 static int function_capable_string_allowed_with_auths(const char *evaluating, int writepermlist)
1456 if (!(writepermlist & EVENT_FLAG_SYSTEM)
1458 strstr(evaluating, "SHELL") || /* NoOp(${SHELL(rm -rf /)}) */
1459 strstr(evaluating, "EVAL") /* NoOp(${EVAL(${some_var_containing_SHELL})}) */
1466 /*! \brief Convert authority code to a list of options for a user. This will only
1467 * display those authority codes that have an explicit match on authority */
1468 static const char *user_authority_to_str(int authority, struct ast_str **res)
1473 ast_str_reset(*res);
1474 for (i = 0; i < ARRAY_LEN(perms) - 1; i++) {
1475 if ((authority & perms[i].num) == perms[i].num) {
1476 ast_str_append(res, 0, "%s%s", sep, perms[i].label);
1481 if (ast_str_strlen(*res) == 0) /* replace empty string with something sensible */
1482 ast_str_append(res, 0, "<none>");
1484 return ast_str_buffer(*res);
1488 /*! \brief Convert authority code to a list of options. Note that the EVENT_FLAG_ALL
1489 * authority will always be returned. */
1490 static const char *authority_to_str(int authority, struct ast_str **res)
1495 ast_str_reset(*res);
1496 for (i = 0; i < ARRAY_LEN(perms) - 1; i++) {
1497 if (authority & perms[i].num) {
1498 ast_str_append(res, 0, "%s%s", sep, perms[i].label);
1503 if (ast_str_strlen(*res) == 0) /* replace empty string with something sensible */
1504 ast_str_append(res, 0, "<none>");
1506 return ast_str_buffer(*res);
1509 /*! Tells you if smallstr exists inside bigstr
1510 which is delim by delim and uses no buf or stringsep
1511 ast_instring("this|that|more","this",'|') == 1;
1513 feel free to move this to app.c -anthm */
1514 static int ast_instring(const char *bigstr, const char *smallstr, const char delim)
1516 const char *val = bigstr, *next;
1519 if ((next = strchr(val, delim))) {
1520 if (!strncmp(val, smallstr, (next - val))) {
1526 return !strcmp(smallstr, val);
1528 } while (*(val = (next + 1)));
1533 static int get_perm(const char *instr)
1541 for (x = 0; x < ARRAY_LEN(perms); x++) {
1542 if (ast_instring(instr, perms[x].label, ',')) {
1543 ret |= perms[x].num;
1551 * A number returns itself, false returns 0, true returns all flags,
1552 * other strings return the flags that are set.
1554 static int strings_to_mask(const char *string)
1558 if (ast_strlen_zero(string)) {
1562 for (p = string; *p; p++) {
1563 if (*p < '0' || *p > '9') {
1567 if (!*p) { /* all digits */
1568 return atoi(string);
1570 if (ast_false(string)) {
1573 if (ast_true(string)) { /* all permissions */
1575 for (x = 0; x < ARRAY_LEN(perms); x++) {
1576 ret |= perms[x].num;
1580 return get_perm(string);
1583 /*! \brief Unreference manager session object.
1584 If no more references, then go ahead and delete it */
1585 static struct mansession_session *unref_mansession(struct mansession_session *s)
1587 int refcount = ao2_ref(s, -1);
1588 if (manager_debug) {
1589 ast_debug(1, "Mansession: %p refcount now %d\n", s, refcount - 1);
1594 static void event_filter_destructor(void *obj)
1596 regex_t *regex_filter = obj;
1597 regfree(regex_filter);
1600 static void session_destructor(void *obj)
1602 struct mansession_session *session = obj;
1603 struct eventqent *eqe = session->last_ev;
1604 struct ast_datastore *datastore;
1606 /* Get rid of each of the data stores on the session */
1607 while ((datastore = AST_LIST_REMOVE_HEAD(&session->datastores, entry))) {
1608 /* Free the data store */
1609 ast_datastore_free(datastore);
1612 if (session->f != NULL) {
1616 ast_atomic_fetchadd_int(&eqe->usecount, -1);
1618 if (session->chanvars) {
1619 ast_variables_destroy(session->chanvars);
1622 if (session->whitefilters) {
1623 ao2_t_callback(session->whitefilters, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL, "unlink all white filters");
1624 ao2_t_ref(session->whitefilters, -1 , "decrement ref for white container, should be last one");
1627 if (session->blackfilters) {
1628 ao2_t_callback(session->blackfilters, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL, "unlink all black filters");
1629 ao2_t_ref(session->blackfilters, -1 , "decrement ref for black container, should be last one");
1633 /*! \brief Allocate manager session structure and add it to the list of sessions */
1634 static struct mansession_session *build_mansession(const struct ast_sockaddr *addr)
1636 struct mansession_session *newsession;
1638 if (!(newsession = ao2_alloc(sizeof(*newsession), session_destructor))) {
1642 if (!(newsession->whitefilters = ao2_container_alloc(1, NULL, NULL))) {
1643 ao2_ref(newsession, -1);
1647 if (!(newsession->blackfilters = ao2_container_alloc(1, NULL, NULL))) {
1648 ao2_ref(newsession, -1); /* session_destructor will cleanup the other filter */
1652 newsession->fd = -1;
1653 newsession->waiting_thread = AST_PTHREADT_NULL;
1654 newsession->writetimeout = 100;
1655 newsession->send_events = -1;
1656 ast_sockaddr_copy(&newsession->addr, addr);
1658 ao2_link(sessions, newsession);
1663 static int mansession_cmp_fn(void *obj, void *arg, int flags)
1665 struct mansession_session *s = obj;
1667 return !strcasecmp(s->username, str) ? CMP_MATCH : 0;
1670 static void session_destroy(struct mansession_session *s)
1672 unref_mansession(s);
1673 ao2_unlink(sessions, s);
1677 static int check_manager_session_inuse(const char *name)
1679 struct mansession_session *session = ao2_find(sessions, (char *) name, 0);
1684 unref_mansession(session);
1691 * lookup an entry in the list of registered users.
1692 * must be called with the list lock held.
1694 static struct ast_manager_user *get_manager_by_name_locked(const char *name)
1696 struct ast_manager_user *user = NULL;
1698 AST_RWLIST_TRAVERSE(&users, user, list) {
1699 if (!strcasecmp(user->username, name)) {
1707 /*! \brief Get displayconnects config option.
1708 * \param session manager session to get parameter from.
1709 * \return displayconnects config option value.
1711 static int manager_displayconnects (struct mansession_session *session)
1713 struct ast_manager_user *user = NULL;
1716 AST_RWLIST_RDLOCK(&users);
1717 if ((user = get_manager_by_name_locked (session->username))) {
1718 ret = user->displayconnects;
1720 AST_RWLIST_UNLOCK(&users);
1725 static char *handle_showmancmd(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1727 struct manager_action *cur;
1728 struct ast_str *authority;
1732 char syntax_title[64], description_title[64], synopsis_title[64], seealso_title[64], arguments_title[64], privilege_title[64];
1737 e->command = "manager show command";
1739 "Usage: manager show command <actionname> [<actionname> [<actionname> [...]]]\n"
1740 " Shows the detailed description for a specific Asterisk manager interface command.\n";
1743 l = strlen(a->word);
1745 AST_RWLIST_RDLOCK(&actions);
1746 AST_RWLIST_TRAVERSE(&actions, cur, list) {
1747 if (!strncasecmp(a->word, cur->action, l) && ++which > a->n) {
1748 ret = ast_strdup(cur->action);
1749 break; /* make sure we exit even if ast_strdup() returns NULL */
1752 AST_RWLIST_UNLOCK(&actions);
1755 authority = ast_str_alloca(80);
1757 return CLI_SHOWUSAGE;
1761 /* setup the titles */
1762 term_color(synopsis_title, "[Synopsis]\n", COLOR_MAGENTA, 0, 40);
1763 term_color(description_title, "[Description]\n", COLOR_MAGENTA, 0, 40);
1764 term_color(syntax_title, "[Syntax]\n", COLOR_MAGENTA, 0, 40);
1765 term_color(seealso_title, "[See Also]\n", COLOR_MAGENTA, 0, 40);
1766 term_color(arguments_title, "[Arguments]\n", COLOR_MAGENTA, 0, 40);
1767 term_color(privilege_title, "[Privilege]\n", COLOR_MAGENTA, 0, 40);
1770 AST_RWLIST_RDLOCK(&actions);
1771 AST_RWLIST_TRAVERSE(&actions, cur, list) {
1772 for (num = 3; num < a->argc; num++) {
1773 if (!strcasecmp(cur->action, a->argv[num])) {
1774 authority_to_str(cur->authority, &authority);
1777 if (cur->docsrc == AST_XML_DOC) {
1778 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",
1780 ast_xmldoc_printable(S_OR(cur->syntax, "Not available"), 1),
1782 ast_xmldoc_printable(S_OR(cur->synopsis, "Not available"), 1),
1784 ast_xmldoc_printable(S_OR(cur->description, "Not available"), 1),
1786 ast_xmldoc_printable(S_OR(cur->arguments, "Not available"), 1),
1788 ast_xmldoc_printable(S_OR(cur->seealso, "Not available"), 1),
1790 ast_xmldoc_printable(S_OR(authority->str, "Not available"), 1));
1794 ast_cli(a->fd, "Action: %s\nSynopsis: %s\nPrivilege: %s\n%s\n",
1795 cur->action, cur->synopsis,
1797 S_OR(cur->description, ""));
1802 AST_RWLIST_UNLOCK(&actions);
1807 static char *handle_mandebug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1811 e->command = "manager set debug [on|off]";
1812 e->usage = "Usage: manager set debug [on|off]\n Show, enable, disable debugging of the manager code.\n";
1819 ast_cli(a->fd, "manager debug is %s\n", manager_debug? "on" : "off");
1820 } else if (a->argc == 4) {
1821 if (!strcasecmp(a->argv[3], "on")) {
1823 } else if (!strcasecmp(a->argv[3], "off")) {
1826 return CLI_SHOWUSAGE;
1832 static char *handle_showmanager(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1834 struct ast_manager_user *user = NULL;
1837 struct ast_str *rauthority = ast_str_alloca(128);
1838 struct ast_str *wauthority = ast_str_alloca(128);
1839 struct ast_variable *v;
1843 e->command = "manager show user";
1845 " Usage: manager show user <user>\n"
1846 " Display all information related to the manager user specified.\n";
1849 l = strlen(a->word);
1854 AST_RWLIST_RDLOCK(&users);
1855 AST_RWLIST_TRAVERSE(&users, user, list) {
1856 if ( !strncasecmp(a->word, user->username, l) && ++which > a->n ) {
1857 ret = ast_strdup(user->username);
1861 AST_RWLIST_UNLOCK(&users);
1866 return CLI_SHOWUSAGE;
1869 AST_RWLIST_RDLOCK(&users);
1871 if (!(user = get_manager_by_name_locked(a->argv[3]))) {
1872 ast_cli(a->fd, "There is no manager called %s\n", a->argv[3]);
1873 AST_RWLIST_UNLOCK(&users);
1877 ast_cli(a->fd, "\n");
1884 "displayconnects: %s\n",
1885 (user->username ? user->username : "(N/A)"),
1886 (user->secret ? "<Set>" : "(N/A)"),
1887 ((user->acl && !ast_acl_list_is_empty(user->acl)) ? "yes" : "no"),
1888 user_authority_to_str(user->readperm, &rauthority),
1889 user_authority_to_str(user->writeperm, &wauthority),
1890 (user->displayconnects ? "yes" : "no"));
1891 ast_cli(a->fd, " Variables: \n");
1892 for (v = user->chanvars ; v ; v = v->next) {
1893 ast_cli(a->fd, " %s = %s\n", v->name, v->value);
1896 AST_RWLIST_UNLOCK(&users);
1901 static char *handle_showmanagers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1903 struct ast_manager_user *user = NULL;
1907 e->command = "manager show users";
1909 "Usage: manager show users\n"
1910 " Prints a listing of all managers that are currently configured on that\n"
1917 return CLI_SHOWUSAGE;
1920 AST_RWLIST_RDLOCK(&users);
1922 /* If there are no users, print out something along those lines */
1923 if (AST_RWLIST_EMPTY(&users)) {
1924 ast_cli(a->fd, "There are no manager users.\n");
1925 AST_RWLIST_UNLOCK(&users);
1929 ast_cli(a->fd, "\nusername\n--------\n");
1931 AST_RWLIST_TRAVERSE(&users, user, list) {
1932 ast_cli(a->fd, "%s\n", user->username);
1936 AST_RWLIST_UNLOCK(&users);
1938 ast_cli(a->fd,"-------------------\n"
1939 "%d manager users configured.\n", count_amu);
1943 /*! \brief CLI command manager list commands */
1944 static char *handle_showmancmds(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1946 struct manager_action *cur;
1948 int space_remaining;
1949 #define HSMC_FORMAT " %-*.*s %-.*s\n"
1952 e->command = "manager show commands";
1954 "Usage: manager show commands\n"
1955 " Prints a listing of all the available Asterisk manager interface commands.\n";
1961 AST_RWLIST_RDLOCK(&actions);
1962 AST_RWLIST_TRAVERSE(&actions, cur, list) {
1963 int incoming_len = strlen(cur->action);
1964 if (incoming_len > name_len) {
1965 name_len = incoming_len;
1969 space_remaining = MGR_SHOW_TERMINAL_WIDTH - name_len - 4;
1970 if (space_remaining < 0) {
1971 space_remaining = 0;
1974 ast_cli(a->fd, HSMC_FORMAT, name_len, name_len, "Action", space_remaining, "Synopsis");
1975 ast_cli(a->fd, HSMC_FORMAT, name_len, name_len, "------", space_remaining, "--------");
1977 AST_RWLIST_TRAVERSE(&actions, cur, list) {
1978 ast_cli(a->fd, HSMC_FORMAT, name_len, name_len, cur->action, space_remaining, cur->synopsis);
1980 AST_RWLIST_UNLOCK(&actions);
1985 /*! \brief CLI command manager list connected */
1986 static char *handle_showmanconn(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1988 struct mansession_session *session;
1989 time_t now = time(NULL);
1990 #define HSMCONN_FORMAT1 " %-15.15s %-55.55s %-10.10s %-10.10s %-8.8s %-8.8s %-5.5s %-5.5s\n"
1991 #define HSMCONN_FORMAT2 " %-15.15s %-55.55s %-10d %-10d %-8d %-8d %-5.5d %-5.5d\n"
1993 struct ao2_iterator i;
1997 e->command = "manager show connected";
1999 "Usage: manager show connected\n"
2000 " Prints a listing of the users that are currently connected to the\n"
2001 "Asterisk manager interface.\n";
2007 ast_cli(a->fd, HSMCONN_FORMAT1, "Username", "IP Address", "Start", "Elapsed", "FileDes", "HttpCnt", "Read", "Write");
2009 i = ao2_iterator_init(sessions, 0);
2010 while ((session = ao2_iterator_next(&i))) {
2012 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);
2014 ao2_unlock(session);
2015 unref_mansession(session);
2017 ao2_iterator_destroy(&i);
2018 ast_cli(a->fd, "%d users connected.\n", count);
2023 /*! \brief CLI command manager list eventq */
2024 /* Should change to "manager show connected" */
2025 static char *handle_showmaneventq(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2027 struct eventqent *s;
2030 e->command = "manager show eventq";
2032 "Usage: manager show eventq\n"
2033 " Prints a listing of all events pending in the Asterisk manger\n"
2039 AST_RWLIST_RDLOCK(&all_events);
2040 AST_RWLIST_TRAVERSE(&all_events, s, eq_next) {
2041 ast_cli(a->fd, "Usecount: %d\n", s->usecount);
2042 ast_cli(a->fd, "Category: %d\n", s->category);
2043 ast_cli(a->fd, "Event:\n%s", s->eventdata);
2045 AST_RWLIST_UNLOCK(&all_events);
2050 /*! \brief CLI command manager reload */
2051 static char *handle_manager_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2055 e->command = "manager reload";
2057 "Usage: manager reload\n"
2058 " Reloads the manager configuration.\n";
2064 return CLI_SHOWUSAGE;
2070 static struct eventqent *advance_event(struct eventqent *e)
2072 struct eventqent *next;
2074 AST_RWLIST_RDLOCK(&all_events);
2075 if ((next = AST_RWLIST_NEXT(e, eq_next))) {
2076 ast_atomic_fetchadd_int(&next->usecount, 1);
2077 ast_atomic_fetchadd_int(&e->usecount, -1);
2079 AST_RWLIST_UNLOCK(&all_events);
2083 #define GET_HEADER_FIRST_MATCH 0
2084 #define GET_HEADER_LAST_MATCH 1
2085 #define GET_HEADER_SKIP_EMPTY 2
2088 * \brief Return a matching header value.
2091 * Generic function to return either the first or the last
2092 * matching header from a list of variables, possibly skipping
2095 * \note At the moment there is only one use of this function in
2096 * this file, so we make it static.
2098 * \note Never returns NULL.
2100 static const char *__astman_get_header(const struct message *m, char *var, int mode)
2102 int x, l = strlen(var);
2103 const char *result = "";
2109 for (x = 0; x < m->hdrcount; x++) {
2110 const char *h = m->headers[x];
2111 if (!strncasecmp(var, h, l) && h[l] == ':') {
2112 const char *value = h + l + 1;
2113 value = ast_skip_blanks(value); /* ignore leading spaces in the value */
2114 /* found a potential candidate */
2115 if ((mode & GET_HEADER_SKIP_EMPTY) && ast_strlen_zero(value)) {
2116 continue; /* not interesting */
2118 if (mode & GET_HEADER_LAST_MATCH) {
2119 result = value; /* record the last match so far */
2130 * \brief Return the first matching variable from an array.
2132 * \note This is the legacy function and is implemented in
2133 * therms of __astman_get_header().
2135 * \note Never returns NULL.
2137 const char *astman_get_header(const struct message *m, char *var)
2139 return __astman_get_header(m, var, GET_HEADER_FIRST_MATCH);
2144 * \brief Process one "Variable:" header value string.
2146 * \param head Current list of AMI variables to get new values added.
2147 * \param hdr_val Header value string to process.
2149 * \return New variable list head.
2151 static struct ast_variable *man_do_variable_value(struct ast_variable *head, const char *hdr_val)
2154 AST_DECLARE_APP_ARGS(args,
2155 AST_APP_ARG(vars)[64];
2158 hdr_val = ast_skip_blanks(hdr_val); /* ignore leading spaces in the value */
2159 parse = ast_strdupa(hdr_val);
2161 /* Break the header value string into name=val pair items. */
2162 AST_STANDARD_APP_ARGS(args, parse);
2166 /* Process each name=val pair item. */
2167 for (y = 0; y < args.argc; y++) {
2168 struct ast_variable *cur;
2172 if (!args.vars[y]) {
2175 var = val = args.vars[y];
2178 /* XXX We may wish to trim whitespace from the strings. */
2179 if (!val || ast_strlen_zero(var)) {
2183 /* Create new variable list node and prepend it to the list. */
2184 cur = ast_variable_new(var, val, "");
2195 struct ast_variable *astman_get_variables(const struct message *m)
2199 struct ast_variable *head = NULL;
2201 static const char var_hdr[] = "Variable:";
2203 /* Process all "Variable:" headers. */
2204 varlen = strlen(var_hdr);
2205 for (x = 0; x < m->hdrcount; x++) {
2206 if (strncasecmp(var_hdr, m->headers[x], varlen)) {
2209 head = man_do_variable_value(head, m->headers[x] + varlen);
2215 /*! \brief access for hooks to send action messages to ami */
2216 int ast_hook_send_action(struct manager_custom_hook *hook, const char *msg)
2220 struct manager_action *act_found;
2221 struct mansession s = {.session = NULL, };
2222 struct message m = { 0 };
2232 /* Create our own copy of the AMI action msg string. */
2233 src = dup_str = ast_strdup(msg);
2238 /* convert msg string to message struct */
2239 curlen = strlen(src);
2240 for (x = 0; x < curlen; x++) {
2241 int cr; /* set if we have \r */
2242 if (src[x] == '\r' && x+1 < curlen && src[x+1] == '\n')
2243 cr = 2; /* Found. Update length to include \r\n */
2244 else if (src[x] == '\n')
2245 cr = 1; /* also accept \n only */
2248 /* don't keep empty lines */
2249 if (x && m.hdrcount < ARRAY_LEN(m.headers)) {
2250 /* ... but trim \r\n and terminate the header string */
2252 m.headers[m.hdrcount++] = src;
2255 curlen -= x; /* remaining size */
2256 src += x; /* update pointer */
2257 x = -1; /* reset loop */
2260 action = astman_get_header(&m, "Action");
2261 if (strcasecmp(action, "login")) {
2262 act_found = action_find(action);
2265 * we have to simulate a session for this action request
2266 * to be able to pass it down for processing
2267 * This is necessary to meet the previous design of manager.c
2270 s.f = (void*)1; /* set this to something so our request will make it through all functions that test it*/
2272 ao2_lock(act_found);
2273 if (act_found->registered && act_found->func) {
2274 if (act_found->module) {
2275 ast_module_ref(act_found->module);
2277 ao2_unlock(act_found);
2278 ret = act_found->func(&s, &m);
2279 ao2_lock(act_found);
2280 if (act_found->module) {
2281 ast_module_unref(act_found->module);
2286 ao2_unlock(act_found);
2287 ao2_t_ref(act_found, -1, "done with found action object");
2296 * helper function to send a string to the socket.
2297 * Return -1 on error (e.g. buffer full).
2299 static int send_string(struct mansession *s, char *string)
2302 FILE *f = s->f ? s->f : s->session->f;
2303 int fd = s->f ? s->fd : s->session->fd;
2305 /* It's a result from one of the hook's action invocation */
2308 * to send responses, we're using the same function
2309 * as for receiving events. We call the event "HookResponse"
2311 s->hook->helper(EVENT_FLAG_HOOKRESPONSE, "HookResponse", string);
2315 if ((res = ast_careful_fwrite(f, fd, string, strlen(string), s->session->writetimeout))) {
2323 * \brief thread local buffer for astman_append
2325 * \note This can not be defined within the astman_append() function
2326 * because it declares a couple of functions that get used to
2327 * initialize the thread local storage key.
2329 AST_THREADSTORAGE(astman_append_buf);
2331 AST_THREADSTORAGE(userevent_buf);
2333 /*! \brief initial allocated size for the astman_append_buf and astman_send_*_va */
2334 #define ASTMAN_APPEND_BUF_INITSIZE 256
2337 * utility functions for creating AMI replies
2339 void astman_append(struct mansession *s, const char *fmt, ...)
2342 struct ast_str *buf;
2344 if (!(buf = ast_str_thread_get(&astman_append_buf, ASTMAN_APPEND_BUF_INITSIZE))) {
2349 ast_str_set_va(&buf, 0, fmt, ap);
2352 if (s->f != NULL || s->session->f != NULL) {
2353 send_string(s, ast_str_buffer(buf));
2355 ast_verbose("fd == -1 in astman_append, should not happen\n");
2359 /*! \note NOTE: XXX this comment is unclear and possibly wrong.
2360 Callers of astman_send_error(), astman_send_response() or astman_send_ack() must EITHER
2361 hold the session lock _or_ be running in an action callback (in which case s->session->busy will
2362 be non-zero). In either of these cases, there is no need to lock-protect the session's
2363 fd, since no other output will be sent (events will be queued), and no input will
2364 be read until either the current action finishes or get_input() obtains the session
2368 /*! \todo XXX MSG_MOREDATA should go to a header file. */
2369 #define MSG_MOREDATA ((char *)astman_send_response)
2371 /*! \brief send a response with an optional message,
2372 * and terminate it with an empty line.
2373 * m is used only to grab the 'ActionID' field.
2375 * Use the explicit constant MSG_MOREDATA to remove the empty line.
2376 * XXX MSG_MOREDATA should go to a header file.
2378 static void astman_send_response_full(struct mansession *s, const struct message *m, char *resp, char *msg, char *listflag)
2380 const char *id = astman_get_header(m, "ActionID");
2382 astman_append(s, "Response: %s\r\n", resp);
2383 if (!ast_strlen_zero(id)) {
2384 astman_append(s, "ActionID: %s\r\n", id);
2387 astman_append(s, "EventList: %s\r\n", listflag); /* Start, complete, cancelled */
2389 if (msg == MSG_MOREDATA) {
2392 astman_append(s, "Message: %s\r\n\r\n", msg);
2394 astman_append(s, "\r\n");
2398 void astman_send_response(struct mansession *s, const struct message *m, char *resp, char *msg)
2400 astman_send_response_full(s, m, resp, msg, NULL);
2403 void astman_send_error(struct mansession *s, const struct message *m, char *error)
2405 astman_send_response_full(s, m, "Error", error, NULL);
2408 void astman_send_error_va(struct mansession *s, const struct message *m, const char *fmt, ...)
2411 struct ast_str *buf;
2414 if (!(buf = ast_str_thread_get(&astman_append_buf, ASTMAN_APPEND_BUF_INITSIZE))) {
2419 ast_str_set_va(&buf, 0, fmt, ap);
2422 /* astman_append will use the same underlying buffer, so copy the message out
2423 * before sending the response */
2424 msg = ast_str_buffer(buf);
2426 msg = ast_strdupa(msg);
2428 astman_send_response_full(s, m, "Error", msg, NULL);
2431 void astman_send_ack(struct mansession *s, const struct message *m, char *msg)
2433 astman_send_response_full(s, m, "Success", msg, NULL);
2436 static void astman_start_ack(struct mansession *s, const struct message *m)
2438 astman_send_response_full(s, m, "Success", MSG_MOREDATA, NULL);
2441 void astman_send_listack(struct mansession *s, const struct message *m, char *msg, char *listflag)
2443 astman_send_response_full(s, m, "Success", msg, listflag);
2446 /*! \brief Lock the 'mansession' structure. */
2447 static void mansession_lock(struct mansession *s)
2449 ast_mutex_lock(&s->lock);
2452 /*! \brief Unlock the 'mansession' structure. */
2453 static void mansession_unlock(struct mansession *s)
2455 ast_mutex_unlock(&s->lock);
2459 Rather than braindead on,off this now can also accept a specific int mask value
2460 or a ',' delim list of mask strings (the same as manager.conf) -anthm
2462 static int set_eventmask(struct mansession *s, const char *eventmask)
2464 int maskint = strings_to_mask(eventmask);
2466 ao2_lock(s->session);
2468 s->session->send_events = maskint;
2470 ao2_unlock(s->session);
2475 static enum ast_transport mansession_get_transport(const struct mansession *s)
2477 return s->tcptls_session->parent->tls_cfg ? AST_TRANSPORT_TLS :
2481 static void report_invalid_user(const struct mansession *s, const char *username)
2483 char session_id[32];
2484 struct ast_security_event_inval_acct_id inval_acct_id = {
2485 .common.event_type = AST_SECURITY_EVENT_INVAL_ACCT_ID,
2486 .common.version = AST_SECURITY_EVENT_INVAL_ACCT_ID_VERSION,
2487 .common.service = "AMI",
2488 .common.account_id = username,
2489 .common.session_tv = &s->session->sessionstart_tv,
2490 .common.local_addr = {
2491 .addr = &s->tcptls_session->parent->local_address,
2492 .transport = mansession_get_transport(s),
2494 .common.remote_addr = {
2495 .addr = &s->session->addr,
2496 .transport = mansession_get_transport(s),
2498 .common.session_id = session_id,
2501 snprintf(session_id, sizeof(session_id), "%p", s);
2503 ast_security_event_report(AST_SEC_EVT(&inval_acct_id));
2506 static void report_failed_acl(const struct mansession *s, const char *username)
2508 char session_id[32];
2509 struct ast_security_event_failed_acl failed_acl_event = {
2510 .common.event_type = AST_SECURITY_EVENT_FAILED_ACL,
2511 .common.version = AST_SECURITY_EVENT_FAILED_ACL_VERSION,
2512 .common.service = "AMI",
2513 .common.account_id = username,
2514 .common.session_tv = &s->session->sessionstart_tv,
2515 .common.local_addr = {
2516 .addr = &s->tcptls_session->parent->local_address,
2517 .transport = mansession_get_transport(s),
2519 .common.remote_addr = {
2520 .addr = &s->session->addr,
2521 .transport = mansession_get_transport(s),
2523 .common.session_id = session_id,
2526 snprintf(session_id, sizeof(session_id), "%p", s->session);
2528 ast_security_event_report(AST_SEC_EVT(&failed_acl_event));
2531 static void report_inval_password(const struct mansession *s, const char *username)
2533 char session_id[32];
2534 struct ast_security_event_inval_password inval_password = {
2535 .common.event_type = AST_SECURITY_EVENT_INVAL_PASSWORD,
2536 .common.version = AST_SECURITY_EVENT_INVAL_PASSWORD_VERSION,
2537 .common.service = "AMI",
2538 .common.account_id = username,
2539 .common.session_tv = &s->session->sessionstart_tv,
2540 .common.local_addr = {
2541 .addr = &s->tcptls_session->parent->local_address,
2542 .transport = mansession_get_transport(s),
2544 .common.remote_addr = {
2545 .addr = &s->session->addr,
2546 .transport = mansession_get_transport(s),
2548 .common.session_id = session_id,
2551 snprintf(session_id, sizeof(session_id), "%p", s->session);
2553 ast_security_event_report(AST_SEC_EVT(&inval_password));
2556 static void report_auth_success(const struct mansession *s)
2558 char session_id[32];
2559 struct ast_security_event_successful_auth successful_auth = {
2560 .common.event_type = AST_SECURITY_EVENT_SUCCESSFUL_AUTH,
2561 .common.version = AST_SECURITY_EVENT_SUCCESSFUL_AUTH_VERSION,
2562 .common.service = "AMI",
2563 .common.account_id = s->session->username,
2564 .common.session_tv = &s->session->sessionstart_tv,
2565 .common.local_addr = {
2566 .addr = &s->tcptls_session->parent->local_address,
2567 .transport = mansession_get_transport(s),
2569 .common.remote_addr = {
2570 .addr = &s->session->addr,
2571 .transport = mansession_get_transport(s),
2573 .common.session_id = session_id,
2576 snprintf(session_id, sizeof(session_id), "%p", s->session);
2578 ast_security_event_report(AST_SEC_EVT(&successful_auth));
2581 static void report_req_not_allowed(const struct mansession *s, const char *action)
2583 char session_id[32];
2584 char request_type[64];
2585 struct ast_security_event_req_not_allowed req_not_allowed = {
2586 .common.event_type = AST_SECURITY_EVENT_REQ_NOT_ALLOWED,
2587 .common.version = AST_SECURITY_EVENT_REQ_NOT_ALLOWED_VERSION,
2588 .common.service = "AMI",
2589 .common.account_id = s->session->username,
2590 .common.session_tv = &s->session->sessionstart_tv,
2591 .common.local_addr = {
2592 .addr = &s->tcptls_session->parent->local_address,
2593 .transport = mansession_get_transport(s),
2595 .common.remote_addr = {
2596 .addr = &s->session->addr,
2597 .transport = mansession_get_transport(s),
2599 .common.session_id = session_id,
2601 .request_type = request_type,
2604 snprintf(session_id, sizeof(session_id), "%p", s->session);
2605 snprintf(request_type, sizeof(request_type), "Action: %s", action);
2607 ast_security_event_report(AST_SEC_EVT(&req_not_allowed));
2610 static void report_req_bad_format(const struct mansession *s, const char *action)
2612 char session_id[32];
2613 char request_type[64];
2614 struct ast_security_event_req_bad_format req_bad_format = {
2615 .common.event_type = AST_SECURITY_EVENT_REQ_BAD_FORMAT,
2616 .common.version = AST_SECURITY_EVENT_REQ_BAD_FORMAT_VERSION,
2617 .common.service = "AMI",
2618 .common.account_id = s->session->username,
2619 .common.session_tv = &s->session->sessionstart_tv,
2620 .common.local_addr = {
2621 .addr = &s->tcptls_session->parent->local_address,
2622 .transport = mansession_get_transport(s),
2624 .common.remote_addr = {
2625 .addr = &s->session->addr,
2626 .transport = mansession_get_transport(s),
2628 .common.session_id = session_id,
2630 .request_type = request_type,
2633 snprintf(session_id, sizeof(session_id), "%p", s->session);
2634 snprintf(request_type, sizeof(request_type), "Action: %s", action);
2636 ast_security_event_report(AST_SEC_EVT(&req_bad_format));
2639 static void report_failed_challenge_response(const struct mansession *s,
2640 const char *response, const char *expected_response)
2642 char session_id[32];
2643 struct ast_security_event_chal_resp_failed chal_resp_failed = {
2644 .common.event_type = AST_SECURITY_EVENT_CHAL_RESP_FAILED,
2645 .common.version = AST_SECURITY_EVENT_CHAL_RESP_FAILED_VERSION,
2646 .common.service = "AMI",
2647 .common.account_id = s->session->username,
2648 .common.session_tv = &s->session->sessionstart_tv,
2649 .common.local_addr = {
2650 .addr = &s->tcptls_session->parent->local_address,
2651 .transport = mansession_get_transport(s),
2653 .common.remote_addr = {
2654 .addr = &s->session->addr,
2655 .transport = mansession_get_transport(s),
2657 .common.session_id = session_id,
2659 .challenge = s->session->challenge,
2660 .response = response,
2661 .expected_response = expected_response,
2664 snprintf(session_id, sizeof(session_id), "%p", s->session);
2666 ast_security_event_report(AST_SEC_EVT(&chal_resp_failed));
2669 static void report_session_limit(const struct mansession *s)
2671 char session_id[32];
2672 struct ast_security_event_session_limit session_limit = {
2673 .common.event_type = AST_SECURITY_EVENT_SESSION_LIMIT,
2674 .common.version = AST_SECURITY_EVENT_SESSION_LIMIT_VERSION,
2675 .common.service = "AMI",
2676 .common.account_id = s->session->username,
2677 .common.session_tv = &s->session->sessionstart_tv,
2678 .common.local_addr = {
2679 .addr = &s->tcptls_session->parent->local_address,
2680 .transport = mansession_get_transport(s),
2682 .common.remote_addr = {
2683 .addr = &s->session->addr,
2684 .transport = mansession_get_transport(s),
2686 .common.session_id = session_id,
2689 snprintf(session_id, sizeof(session_id), "%p", s->session);
2691 ast_security_event_report(AST_SEC_EVT(&session_limit));
2695 * Here we start with action_ handlers for AMI actions,
2696 * and the internal functions used by them.
2697 * Generally, the handlers are called action_foo()
2700 /* helper function for action_login() */
2701 static int authenticate(struct mansession *s, const struct message *m)
2703 const char *username = astman_get_header(m, "Username");
2704 const char *password = astman_get_header(m, "Secret");
2706 struct ast_manager_user *user = NULL;
2707 regex_t *regex_filter;
2708 struct ao2_iterator filter_iter;
2710 if (ast_strlen_zero(username)) { /* missing username */
2714 /* locate user in locked state */
2715 AST_RWLIST_WRLOCK(&users);
2717 if (!(user = get_manager_by_name_locked(username))) {
2718 report_invalid_user(s, username);
2719 ast_log(LOG_NOTICE, "%s tried to authenticate with nonexistent user '%s'\n", ast_sockaddr_stringify_addr(&s->session->addr), username);
2720 } else if (user->acl && (ast_apply_acl(user->acl, &s->session->addr, "Manager User ACL: ") == AST_SENSE_DENY)) {
2721 report_failed_acl(s, username);
2722 ast_log(LOG_NOTICE, "%s failed to pass IP ACL as '%s'\n", ast_sockaddr_stringify_addr(&s->session->addr), username);
2723 } else if (!strcasecmp(astman_get_header(m, "AuthType"), "MD5")) {
2724 const char *key = astman_get_header(m, "Key");
2725 if (!ast_strlen_zero(key) && !ast_strlen_zero(s->session->challenge) && user->secret) {
2728 char md5key[256] = "";
2729 struct MD5Context md5;
2730 unsigned char digest[16];
2733 MD5Update(&md5, (unsigned char *) s->session->challenge, strlen(s->session->challenge));
2734 MD5Update(&md5, (unsigned char *) user->secret, strlen(user->secret));
2735 MD5Final(digest, &md5);
2736 for (x = 0; x < 16; x++)
2737 len += sprintf(md5key + len, "%2.2x", digest[x]);
2738 if (!strcmp(md5key, key)) {
2741 report_failed_challenge_response(s, key, md5key);
2744 ast_debug(1, "MD5 authentication is not possible. challenge: '%s'\n",
2745 S_OR(s->session->challenge, ""));
2747 } else if (user->secret) {
2748 if (!strcmp(password, user->secret)) {
2751 report_inval_password(s, username);
2756 ast_log(LOG_NOTICE, "%s failed to authenticate as '%s'\n", ast_sockaddr_stringify_addr(&s->session->addr), username);
2757 AST_RWLIST_UNLOCK(&users);
2763 /* All of the user parameters are copied to the session so that in the event
2764 * of a reload and a configuration change, the session parameters are not
2766 ast_copy_string(s->session->username, username, sizeof(s->session->username));
2767 s->session->readperm = user->readperm;
2768 s->session->writeperm = user->writeperm;
2769 s->session->writetimeout = user->writetimeout;
2770 if (user->chanvars) {
2771 s->session->chanvars = ast_variables_dup(user->chanvars);
2774 filter_iter = ao2_iterator_init(user->whitefilters, 0);
2775 while ((regex_filter = ao2_iterator_next(&filter_iter))) {
2776 ao2_t_link(s->session->whitefilters, regex_filter, "add white user filter to session");
2777 ao2_t_ref(regex_filter, -1, "remove iterator ref");
2779 ao2_iterator_destroy(&filter_iter);
2781 filter_iter = ao2_iterator_init(user->blackfilters, 0);
2782 while ((regex_filter = ao2_iterator_next(&filter_iter))) {
2783 ao2_t_link(s->session->blackfilters, regex_filter, "add black user filter to session");
2784 ao2_t_ref(regex_filter, -1, "remove iterator ref");
2786 ao2_iterator_destroy(&filter_iter);
2788 s->session->sessionstart = time(NULL);
2789 s->session->sessionstart_tv = ast_tvnow();
2790 set_eventmask(s, astman_get_header(m, "Events"));
2792 report_auth_success(s);
2794 AST_RWLIST_UNLOCK(&users);
2798 static int action_ping(struct mansession *s, const struct message *m)
2800 const char *actionid = astman_get_header(m, "ActionID");
2801 struct timeval now = ast_tvnow();
2803 astman_append(s, "Response: Success\r\n");
2804 if (!ast_strlen_zero(actionid)){
2805 astman_append(s, "ActionID: %s\r\n", actionid);
2810 "Timestamp: %ld.%06lu\r\n"
2812 (long) now.tv_sec, (unsigned long) now.tv_usec);
2816 static int action_getconfig(struct mansession *s, const struct message *m)
2818 struct ast_config *cfg;
2819 const char *fn = astman_get_header(m, "Filename");
2820 const char *category = astman_get_header(m, "Category");
2823 char *cur_category = NULL;
2824 struct ast_variable *v;
2825 struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
2827 if (ast_strlen_zero(fn)) {
2828 astman_send_error(s, m, "Filename not specified");
2831 cfg = ast_config_load2(fn, "manager", config_flags);
2832 if (cfg == CONFIG_STATUS_FILEMISSING) {
2833 astman_send_error(s, m, "Config file not found");
2835 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
2836 astman_send_error(s, m, "Config file has invalid format");
2840 astman_start_ack(s, m);
2841 while ((cur_category = ast_category_browse(cfg, cur_category))) {
2842 if (ast_strlen_zero(category) || (!ast_strlen_zero(category) && !strcmp(category, cur_category))) {
2844 astman_append(s, "Category-%06d: %s\r\n", catcount, cur_category);
2845 for (v = ast_variable_browse(cfg, cur_category); v; v = v->next) {
2846 astman_append(s, "Line-%06d-%06d: %s=%s\r\n", catcount, lineno++, v->name, v->value);
2851 if (!ast_strlen_zero(category) && catcount == 0) { /* TODO: actually, a config with no categories doesn't even get loaded */
2852 astman_append(s, "No categories found\r\n");
2854 ast_config_destroy(cfg);
2855 astman_append(s, "\r\n");
2860 static int action_listcategories(struct mansession *s, const struct message *m)
2862 struct ast_config *cfg;
2863 const char *fn = astman_get_header(m, "Filename");
2864 char *category = NULL;
2865 struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
2868 if (ast_strlen_zero(fn)) {
2869 astman_send_error(s, m, "Filename not specified");
2872 if (!(cfg = ast_config_load2(fn, "manager", config_flags))) {
2873 astman_send_error(s, m, "Config file not found");
2875 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
2876 astman_send_error(s, m, "Config file has invalid format");
2879 astman_start_ack(s, m);
2880 while ((category = ast_category_browse(cfg, category))) {
2881 astman_append(s, "Category-%06d: %s\r\n", catcount, category);
2884 if (catcount == 0) { /* TODO: actually, a config with no categories doesn't even get loaded */
2885 astman_append(s, "Error: no categories found\r\n");
2887 ast_config_destroy(cfg);
2888 astman_append(s, "\r\n");
2896 /*! The amount of space in out must be at least ( 2 * strlen(in) + 1 ) */
2897 static void json_escape(char *out, const char *in)
2900 if (*in == '\\' || *in == '\"') {
2910 * \brief Append a JSON escaped string to the manager stream.
2912 * \param s AMI stream to append a string.
2913 * \param str String to append to the stream after JSON escaping it.
2917 static void astman_append_json(struct mansession *s, const char *str)
2921 buf = ast_alloca(2 * strlen(str) + 1);
2922 json_escape(buf, str);
2923 astman_append(s, "%s", buf);
2926 static int action_getconfigjson(struct mansession *s, const struct message *m)
2928 struct ast_config *cfg;
2929 const char *fn = astman_get_header(m, "Filename");
2930 char *category = NULL;
2931 struct ast_variable *v;
2933 struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
2935 if (ast_strlen_zero(fn)) {
2936 astman_send_error(s, m, "Filename not specified");
2940 if (!(cfg = ast_config_load2(fn, "manager", config_flags))) {
2941 astman_send_error(s, m, "Config file not found");
2943 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
2944 astman_send_error(s, m, "Config file has invalid format");
2948 astman_start_ack(s, m);
2949 astman_append(s, "JSON: {");
2950 while ((category = ast_category_browse(cfg, category))) {
2953 astman_append(s, "%s\"", comma1 ? "," : "");
2954 astman_append_json(s, category);
2955 astman_append(s, "\":[");
2957 for (v = ast_variable_browse(cfg, category); v; v = v->next) {
2958 astman_append(s, "%s\"", comma2 ? "," : "");
2959 astman_append_json(s, v->name);
2960 astman_append(s, "\":\"");
2961 astman_append_json(s, v->value);
2962 astman_append(s, "\"");
2965 astman_append(s, "]");
2967 astman_append(s, "}\r\n\r\n");
2969 ast_config_destroy(cfg);
2974 /*! \brief helper function for action_updateconfig */
2975 static enum error_type handle_updates(struct mansession *s, const struct message *m, struct ast_config *cfg, const char *dfn)
2979 const char *action, *cat, *var, *value, *match, *line;
2980 struct ast_category *category;
2981 struct ast_variable *v;
2982 struct ast_str *str1 = ast_str_create(16), *str2 = ast_str_create(16);
2983 enum error_type result = 0;
2985 for (x = 0; x < 100000; x++) { /* 100000 = the max number of allowed updates + 1 */
2986 unsigned int object = 0;
2988 snprintf(hdr, sizeof(hdr), "Action-%06d", x);
2989 action = astman_get_header(m, hdr);
2990 if (ast_strlen_zero(action)) /* breaks the for loop if no action header */
2991 break; /* this could cause problems if actions come in misnumbered */
2993 snprintf(hdr, sizeof(hdr), "Cat-%06d", x);
2994 cat = astman_get_header(m, hdr);
2995 if (ast_strlen_zero(cat)) { /* every action needs a category */
2996 result = UNSPECIFIED_CATEGORY;
3000 snprintf(hdr, sizeof(hdr), "Var-%06d", x);
3001 var = astman_get_header(m, hdr);
3003 snprintf(hdr, sizeof(hdr), "Value-%06d", x);
3004 value = astman_get_header(m, hdr);
3006 if (!ast_strlen_zero(value) && *value == '>') {
3011 snprintf(hdr, sizeof(hdr), "Match-%06d", x);
3012 match = astman_get_header(m, hdr);
3014 snprintf(hdr, sizeof(hdr), "Line-%06d", x);
3015 line = astman_get_header(m, hdr);
3017 if (!strcasecmp(action, "newcat")) {
3018 if (ast_category_get(cfg,cat)) { /* check to make sure the cat doesn't */
3019 result = FAILURE_NEWCAT; /* already exist */
3022 if (!(category = ast_category_new(cat, dfn, -1))) {
3023 result = FAILURE_ALLOCATION;
3026 if (ast_strlen_zero(match)) {
3027 ast_category_append(cfg, category);
3029 ast_category_insert(cfg, category, match);
3031 } else if (!strcasecmp(action, "renamecat")) {
3032 if (ast_strlen_zero(value)) {
3033 result = UNSPECIFIED_ARGUMENT;
3036 if (!(category = ast_category_get(cfg, cat))) {
3037 result = UNKNOWN_CATEGORY;
3040 ast_category_rename(category, value);
3041 } else if (!strcasecmp(action, "delcat")) {
3042 if (ast_category_delete(cfg, cat)) {
3043 result = FAILURE_DELCAT;
3046 } else if (!strcasecmp(action, "emptycat")) {
3047 if (ast_category_empty(cfg, cat)) {
3048 result = FAILURE_EMPTYCAT;