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/aoc.h"
91 #include "asterisk/strings.h"
92 #include "asterisk/stringfields.h"
93 #include "asterisk/presencestate.h"
94 #include "asterisk/stasis_message_router.h"
95 #include "asterisk/stasis_channels.h"
96 #include "asterisk/stasis_bridges.h"
97 #include "asterisk/test.h"
98 #include "asterisk/json.h"
99 #include "asterisk/bridge.h"
100 #include "asterisk/features_config.h"
101 #include "asterisk/rtp_engine.h"
102 #include "asterisk/format_cache.h"
103 #include "asterisk/translate.h"
106 <manager name="Ping" language="en_US">
111 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
114 <para>A 'Ping' action will ellicit a 'Pong' response. Used to keep the
115 manager connection open.</para>
118 <manager name="Events" language="en_US">
123 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
124 <parameter name="EventMask" required="true">
127 <para>If all events should be sent.</para>
130 <para>If no events should be sent.</para>
132 <enum name="system,call,log,...">
133 <para>To select which flags events should have to be sent.</para>
139 <para>Enable/Disable sending of events to this manager client.</para>
142 <manager name="Logoff" language="en_US">
147 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
150 <para>Logoff the current manager session.</para>
153 <manager name="Login" language="en_US">
158 <parameter name="ActionID">
159 <para>ActionID for this transaction. Will be returned.</para>
161 <parameter name="Username" required="true">
162 <para>Username to login with as specified in manager.conf.</para>
164 <parameter name="Secret">
165 <para>Secret to login with as specified in manager.conf.</para>
169 <para>Login Manager.</para>
172 <manager name="Challenge" language="en_US">
174 Generate Challenge for MD5 Auth.
177 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
178 <parameter name="AuthType" required="true">
179 <para>Digest algorithm to use in the challenge. Valid values are:</para>
186 <para>Generate a challenge for MD5 authentication.</para>
189 <manager name="Hangup" language="en_US">
194 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
195 <parameter name="Channel" required="true">
196 <para>The exact channel name to be hungup, or to use a regular expression, set this parameter to: /regex/</para>
197 <para>Example exact channel: SIP/provider-0000012a</para>
198 <para>Example regular expression: /^SIP/provider-.*$/</para>
200 <parameter name="Cause">
201 <para>Numeric hangup cause.</para>
205 <para>Hangup a channel.</para>
208 <manager name="Status" language="en_US">
213 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
214 <parameter name="Channel" required="true">
215 <para>The name of the channel to query for status.</para>
217 <parameter name="Variables">
218 <para>Comma <literal>,</literal> separated list of variable to include.</para>
222 <para>Will return the status information of each channel along with the
223 value for the specified channel variables.</para>
226 <managerEvent language="en_US" name="Status">
227 <managerEventInstance class="EVENT_FLAG_CALL">
228 <synopsis>Raised in response to a Status command.</synopsis>
230 <parameter name="ActionID" required="false"/>
232 <parameter name="Type">
233 <para>Type of channel</para>
235 <parameter name="DNID">
236 <para>Dialed number identifier</para>
238 <parameter name="TimeToHangup">
239 <para>Absolute lifetime of the channel</para>
241 <parameter name="BridgeID">
242 <para>Identifier of the bridge the channel is in, may be empty if not in one</para>
244 <parameter name="Linkedid">
246 <parameter name="Application">
247 <para>Application currently executing on the channel</para>
249 <parameter name="Data">
250 <para>Data given to the currently executing channel</para>
252 <parameter name="Nativeformats">
253 <para>Media formats the connected party is willing to send or receive</para>
255 <parameter name="Readformat">
256 <para>Media formats that frames from the channel are received in</para>
258 <parameter name="Readtrans">
259 <para>Translation path for media received in native formats</para>
261 <parameter name="Writeformat">
262 <para>Media formats that frames to the channel are accepted in</para>
264 <parameter name="Writetrans">
265 <para>Translation path for media sent to the connected party</para>
267 <parameter name="Callgroup">
268 <para>Configured call group on the channel</para>
270 <parameter name="Pickupgroup">
271 <para>Configured pickup group on the channel</para>
273 <parameter name="Seconds">
274 <para>Number of seconds the channel has been active</para>
278 <ref type="manager">Status</ref>
280 </managerEventInstance>
282 <manager name="Setvar" language="en_US">
284 Set a channel variable.
287 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
288 <parameter name="Channel">
289 <para>Channel to set variable for.</para>
291 <parameter name="Variable" required="true">
292 <para>Variable name.</para>
294 <parameter name="Value" required="true">
295 <para>Variable value.</para>
299 <para>Set a global or local channel variable.</para>
301 <para>If a channel name is not provided then the variable is global.</para>
305 <manager name="Getvar" language="en_US">
307 Gets a channel variable.
310 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
311 <parameter name="Channel">
312 <para>Channel to read variable from.</para>
314 <parameter name="Variable" required="true">
315 <para>Variable name.</para>
319 <para>Get the value of a global or local channel variable.</para>
321 <para>If a channel name is not provided then the variable is global.</para>
325 <manager name="GetConfig" language="en_US">
327 Retrieve configuration.
330 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
331 <parameter name="Filename" required="true">
332 <para>Configuration filename (e.g. <filename>foo.conf</filename>).</para>
334 <parameter name="Category">
335 <para>Category in configuration file.</para>
339 <para>This action will dump the contents of a configuration
340 file by category and contents or optionally by specified category only.</para>
343 <manager name="GetConfigJSON" language="en_US">
345 Retrieve configuration (JSON format).
348 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
349 <parameter name="Filename" required="true">
350 <para>Configuration filename (e.g. <filename>foo.conf</filename>).</para>
354 <para>This action will dump the contents of a configuration file by category
355 and contents in JSON format. This only makes sense to be used using rawman over
356 the HTTP interface.</para>
359 <manager name="UpdateConfig" language="en_US">
361 Update basic configuration.
364 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
365 <parameter name="SrcFilename" required="true">
366 <para>Configuration filename to read (e.g. <filename>foo.conf</filename>).</para>
368 <parameter name="DstFilename" required="true">
369 <para>Configuration filename to write (e.g. <filename>foo.conf</filename>)</para>
371 <parameter name="Reload">
372 <para>Whether or not a reload should take place (or name of specific module).</para>
374 <parameter name="Action-XXXXXX">
375 <para>Action to take.</para>
376 <para>X's represent 6 digit number beginning with 000000.</para>
378 <enum name="NewCat" />
379 <enum name="RenameCat" />
380 <enum name="DelCat" />
381 <enum name="EmptyCat" />
382 <enum name="Update" />
383 <enum name="Delete" />
384 <enum name="Append" />
385 <enum name="Insert" />
388 <parameter name="Cat-XXXXXX">
389 <para>Category to operate on.</para>
390 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-XXXXXX']/para[2])" />
392 <parameter name="Var-XXXXXX">
393 <para>Variable to work on.</para>
394 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-XXXXXX']/para[2])" />
396 <parameter name="Value-XXXXXX">
397 <para>Value to work on.</para>
398 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-XXXXXX']/para[2])" />
400 <parameter name="Match-XXXXXX">
401 <para>Extra match required to match line.</para>
402 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-XXXXXX']/para[2])" />
404 <parameter name="Line-XXXXXX">
405 <para>Line in category to operate on (used with delete and insert actions).</para>
406 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-XXXXXX']/para[2])" />
410 <para>This action will modify, create, or delete configuration elements
411 in Asterisk configuration files.</para>
414 <manager name="CreateConfig" language="en_US">
416 Creates an empty file in the configuration directory.
419 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
420 <parameter name="Filename" required="true">
421 <para>The configuration filename to create (e.g. <filename>foo.conf</filename>).</para>
425 <para>This action will create an empty file in the configuration
426 directory. This action is intended to be used before an UpdateConfig
430 <manager name="ListCategories" language="en_US">
432 List categories in configuration file.
435 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
436 <parameter name="Filename" required="true">
437 <para>Configuration filename (e.g. <filename>foo.conf</filename>).</para>
441 <para>This action will dump the categories in a given file.</para>
444 <manager name="Redirect" language="en_US">
446 Redirect (transfer) a call.
449 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
450 <parameter name="Channel" required="true">
451 <para>Channel to redirect.</para>
453 <parameter name="ExtraChannel">
454 <para>Second call leg to transfer (optional).</para>
456 <parameter name="Exten" required="true">
457 <para>Extension to transfer to.</para>
459 <parameter name="ExtraExten">
460 <para>Extension to transfer extrachannel to (optional).</para>
462 <parameter name="Context" required="true">
463 <para>Context to transfer to.</para>
465 <parameter name="ExtraContext">
466 <para>Context to transfer extrachannel to (optional).</para>
468 <parameter name="Priority" required="true">
469 <para>Priority to transfer to.</para>
471 <parameter name="ExtraPriority">
472 <para>Priority to transfer extrachannel to (optional).</para>
476 <para>Redirect (transfer) a call.</para>
479 <manager name="Atxfer" language="en_US">
484 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
485 <parameter name="Channel" required="true">
486 <para>Transferer's channel.</para>
488 <parameter name="Exten" required="true">
489 <para>Extension to transfer to.</para>
491 <parameter name="Context">
492 <para>Context to transfer to.</para>
496 <para>Attended transfer.</para>
499 <manager name="Originate" language="en_US">
504 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
505 <parameter name="Channel" required="true">
506 <para>Channel name to call.</para>
508 <parameter name="Exten">
509 <para>Extension to use (requires <literal>Context</literal> and
510 <literal>Priority</literal>)</para>
512 <parameter name="Context">
513 <para>Context to use (requires <literal>Exten</literal> and
514 <literal>Priority</literal>)</para>
516 <parameter name="Priority">
517 <para>Priority to use (requires <literal>Exten</literal> and
518 <literal>Context</literal>)</para>
520 <parameter name="Application">
521 <para>Application to execute.</para>
523 <parameter name="Data">
524 <para>Data to use (requires <literal>Application</literal>).</para>
526 <parameter name="Timeout" default="30000">
527 <para>How long to wait for call to be answered (in ms.).</para>
529 <parameter name="CallerID">
530 <para>Caller ID to be set on the outgoing channel.</para>
532 <parameter name="Variable">
533 <para>Channel variable to set, multiple Variable: headers are allowed.</para>
535 <parameter name="Account">
536 <para>Account code.</para>
538 <parameter name="EarlyMedia">
539 <para>Set to <literal>true</literal> to force call bridge on early media..</para>
541 <parameter name="Async">
542 <para>Set to <literal>true</literal> for fast origination.</para>
544 <parameter name="Codecs">
545 <para>Comma-separated list of codecs to use for this call.</para>
547 <parameter name="ChannelId">
548 <para>Channel UniqueId to be set on the channel.</para>
550 <parameter name="OtherChannelId">
551 <para>Channel UniqueId to be set on the second local channel.</para>
555 <para>Generates an outgoing call to a
556 <replaceable>Extension</replaceable>/<replaceable>Context</replaceable>/<replaceable>Priority</replaceable>
557 or <replaceable>Application</replaceable>/<replaceable>Data</replaceable></para>
560 <ref type="managerEvent">OriginateResponse</ref>
563 <managerEvent language="en_US" name="OriginateResponse">
564 <managerEventInstance class="EVENT_FLAG_CALL">
565 <synopsis>Raised in response to an Originate command.</synopsis>
567 <parameter name="ActionID" required="false"/>
568 <parameter name="Resonse">
570 <enum name="Failure"/>
571 <enum name="Success"/>
574 <parameter name="Channel"/>
575 <parameter name="Context"/>
576 <parameter name="Exten"/>
577 <parameter name="Reason"/>
578 <parameter name="Uniqueid"/>
579 <parameter name="CallerIDNum"/>
580 <parameter name="CallerIDName"/>
583 <ref type="manager">Originate</ref>
585 </managerEventInstance>
587 <manager name="Command" language="en_US">
589 Execute Asterisk CLI Command.
592 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
593 <parameter name="Command" required="true">
594 <para>Asterisk CLI command to run.</para>
598 <para>Run a CLI command.</para>
601 <manager name="ExtensionState" language="en_US">
603 Check Extension Status.
606 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
607 <parameter name="Exten" required="true">
608 <para>Extension to check state on.</para>
610 <parameter name="Context" required="true">
611 <para>Context for extension.</para>
615 <para>Report the extension state for given extension. If the extension has a hint,
616 will use devicestate to check the status of the device connected to the extension.</para>
617 <para>Will return an <literal>Extension Status</literal> message. The response will include
618 the hint for the extension and the status.</para>
621 <manager name="PresenceState" language="en_US">
626 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
627 <parameter name="Provider" required="true">
628 <para>Presence Provider to check the state of</para>
632 <para>Report the presence state for the given presence provider.</para>
633 <para>Will return a <literal>Presence State</literal> message. The response will include the
634 presence state and, if set, a presence subtype and custom message.</para>
637 <manager name="AbsoluteTimeout" language="en_US">
639 Set absolute timeout.
642 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
643 <parameter name="Channel" required="true">
644 <para>Channel name to hangup.</para>
646 <parameter name="Timeout" required="true">
647 <para>Maximum duration of the call (sec).</para>
651 <para>Hangup a channel after a certain time. Acknowledges set time with
652 <literal>Timeout Set</literal> message.</para>
655 <manager name="MailboxStatus" language="en_US">
660 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
661 <parameter name="Mailbox" required="true">
662 <para>Full mailbox ID <replaceable>mailbox</replaceable>@<replaceable>vm-context</replaceable>.</para>
666 <para>Checks a voicemail account for status.</para>
667 <para>Returns whether there are messages waiting.</para>
668 <para>Message: Mailbox Status.</para>
669 <para>Mailbox: <replaceable>mailboxid</replaceable>.</para>
670 <para>Waiting: <literal>0</literal> if messages waiting, <literal>1</literal>
671 if no messages waiting.</para>
674 <manager name="MailboxCount" language="en_US">
676 Check Mailbox Message Count.
679 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
680 <parameter name="Mailbox" required="true">
681 <para>Full mailbox ID <replaceable>mailbox</replaceable>@<replaceable>vm-context</replaceable>.</para>
685 <para>Checks a voicemail account for new messages.</para>
686 <para>Returns number of urgent, new and old messages.</para>
687 <para>Message: Mailbox Message Count</para>
688 <para>Mailbox: <replaceable>mailboxid</replaceable></para>
689 <para>UrgentMessages: <replaceable>count</replaceable></para>
690 <para>NewMessages: <replaceable>count</replaceable></para>
691 <para>OldMessages: <replaceable>count</replaceable></para>
694 <manager name="ListCommands" language="en_US">
696 List available manager commands.
699 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
702 <para>Returns the action name and synopsis for every action that
703 is available to the user.</para>
706 <manager name="SendText" language="en_US">
708 Send text message to channel.
711 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
712 <parameter name="Channel" required="true">
713 <para>Channel to send message to.</para>
715 <parameter name="Message" required="true">
716 <para>Message to send.</para>
720 <para>Sends A Text Message to a channel while in a call.</para>
723 <manager name="UserEvent" language="en_US">
725 Send an arbitrary event.
728 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
729 <parameter name="UserEvent" required="true">
730 <para>Event string to send.</para>
732 <parameter name="Header1">
733 <para>Content1.</para>
735 <parameter name="HeaderN">
736 <para>ContentN.</para>
740 <para>Send an event to manager sessions.</para>
743 <manager name="WaitEvent" language="en_US">
745 Wait for an event to occur.
748 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
749 <parameter name="Timeout" required="true">
750 <para>Maximum time (in seconds) to wait for events, <literal>-1</literal> means forever.</para>
754 <para>This action will ellicit a <literal>Success</literal> response. Whenever
755 a manager event is queued. Once WaitEvent has been called on an HTTP manager
756 session, events will be generated and queued.</para>
759 <manager name="CoreSettings" language="en_US">
761 Show PBX core settings (version etc).
764 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
767 <para>Query for Core PBX settings.</para>
770 <manager name="CoreStatus" language="en_US">
772 Show PBX core status variables.
775 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
778 <para>Query for Core PBX status.</para>
781 <manager name="Reload" language="en_US">
786 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
787 <parameter name="Module">
788 <para>Name of the module to reload.</para>
792 <para>Send a reload event.</para>
795 <manager name="CoreShowChannels" language="en_US">
797 List currently active channels.
800 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
803 <para>List currently defined channels and some information about them.</para>
806 <manager name="LoggerRotate" language="en_US">
808 Reload and rotate the Asterisk logger.
811 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
814 <para>Reload and rotate the logger. Analogous to the CLI command 'logger rotate'.</para>
817 <manager name="ModuleLoad" language="en_US">
822 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
823 <parameter name="Module">
824 <para>Asterisk module name (including .so extension) or subsystem identifier:</para>
827 <enum name="dnsmgr" />
828 <enum name="extconfig" />
831 <enum name="manager" />
833 <enum name="logger" />
834 <enum name="features" />
836 <enum name="udptl" />
837 <enum name="indications" />
842 <parameter name="LoadType" required="true">
843 <para>The operation to be done on module. Subsystem identifiers may only
847 <enum name="unload" />
848 <enum name="reload" />
850 <para>If no module is specified for a <literal>reload</literal> loadtype,
851 all modules are reloaded.</para>
855 <para>Loads, unloads or reloads an Asterisk module in a running system.</para>
858 <manager name="ModuleCheck" language="en_US">
860 Check if module is loaded.
863 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
864 <parameter name="Module" required="true">
865 <para>Asterisk module name (not including extension).</para>
869 <para>Checks if Asterisk module is loaded. Will return Success/Failure.
870 For success returns, the module revision number is included.</para>
873 <manager name="AOCMessage" language="en_US">
875 Generate an Advice of Charge message on a channel.
878 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
879 <parameter name="Channel" required="true">
880 <para>Channel name to generate the AOC message on.</para>
882 <parameter name="ChannelPrefix">
883 <para>Partial channel prefix. By using this option one can match the beginning part
884 of a channel name without having to put the entire name in. For example
885 if a channel name is SIP/snom-00000001 and this value is set to SIP/snom, then
886 that channel matches and the message will be sent. Note however that only
887 the first matched channel has the message sent on it. </para>
889 <parameter name="MsgType" required="true">
890 <para>Defines what type of AOC message to create, AOC-D or AOC-E</para>
896 <parameter name="ChargeType" required="true">
897 <para>Defines what kind of charge this message represents.</para>
901 <enum name="Currency" />
905 <parameter name="UnitAmount(0)">
906 <para>This represents the amount of units charged. The ETSI AOC standard specifies that
907 this value along with the optional UnitType value are entries in a list. To accommodate this
908 these values take an index value starting at 0 which can be used to generate this list of
909 unit entries. For Example, If two unit entires were required this could be achieved by setting the
910 paramter UnitAmount(0)=1234 and UnitAmount(1)=5678. Note that UnitAmount at index 0 is
911 required when ChargeType=Unit, all other entries in the list are optional.
914 <parameter name="UnitType(0)">
915 <para>Defines the type of unit. ETSI AOC standard specifies this as an integer
916 value between 1 and 16, but this value is left open to accept any positive
917 integer. Like the UnitAmount parameter, this value represents a list entry
918 and has an index parameter that starts at 0.
921 <parameter name="CurrencyName">
922 <para>Specifies the currency's name. Note that this value is truncated after 10 characters.</para>
924 <parameter name="CurrencyAmount">
925 <para>Specifies the charge unit amount as a positive integer. This value is required
926 when ChargeType==Currency.</para>
928 <parameter name="CurrencyMultiplier">
929 <para>Specifies the currency multiplier. This value is required when ChargeType==Currency.</para>
931 <enum name="OneThousandth" />
932 <enum name="OneHundredth" />
933 <enum name="OneTenth" />
936 <enum name="Hundred" />
937 <enum name="Thousand" />
940 <parameter name="TotalType" default="Total">
941 <para>Defines what kind of AOC-D total is represented.</para>
943 <enum name="Total" />
944 <enum name="SubTotal" />
947 <parameter name="AOCBillingId">
948 <para>Represents a billing ID associated with an AOC-D or AOC-E message. Note
949 that only the first 3 items of the enum are valid AOC-D billing IDs</para>
951 <enum name="Normal" />
952 <enum name="ReverseCharge" />
953 <enum name="CreditCard" />
954 <enum name="CallFwdUnconditional" />
955 <enum name="CallFwdBusy" />
956 <enum name="CallFwdNoReply" />
957 <enum name="CallDeflection" />
958 <enum name="CallTransfer" />
961 <parameter name="ChargingAssociationId">
962 <para>Charging association identifier. This is optional for AOC-E and can be
963 set to any value between -32768 and 32767</para>
965 <parameter name="ChargingAssociationNumber">
966 <para>Represents the charging association party number. This value is optional
969 <parameter name="ChargingAssociationPlan">
970 <para>Integer representing the charging plan associated with the ChargingAssociationNumber.
971 The value is bits 7 through 1 of the Q.931 octet containing the type-of-number and
972 numbering-plan-identification fields.</para>
976 <para>Generates an AOC-D or AOC-E message on a channel.</para>
979 <function name="AMI_CLIENT" language="en_US">
981 Checks attributes of manager accounts
984 <parameter name="loginname" required="true">
985 <para>Login name, specified in manager.conf</para>
987 <parameter name="field" required="true">
988 <para>The manager account attribute to return</para>
990 <enum name="sessions"><para>The number of sessions for this AMI account</para></enum>
996 Currently, the only supported parameter is "sessions" which will return the current number of
997 active sessions for this AMI account.
1001 <manager name="Filter" language="en_US">
1003 Dynamically add filters for the current manager session.
1006 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
1007 <parameter name="Operation">
1010 <para>Add a filter.</para>
1014 <parameter name="Filter">
1015 <para>Filters can be whitelist or blacklist</para>
1016 <para>Example whitelist filter: "Event: Newchannel"</para>
1017 <para>Example blacklist filter: "!Channel: DAHDI.*"</para>
1018 <para>This filter option is used to whitelist or blacklist events per user to be
1019 reported with regular expressions and are allowed if both the regex matches
1020 and the user has read access as defined in manager.conf. Filters are assumed to be for whitelisting
1021 unless preceeded by an exclamation point, which marks it as being black.
1022 Evaluation of the filters is as follows:</para>
1023 <para>- If no filters are configured all events are reported as normal.</para>
1024 <para>- If there are white filters only: implied black all filter processed first, then white filters.</para>
1025 <para>- If there are black filters only: implied white all filter processed first, then black filters.</para>
1026 <para>- If there are both white and black filters: implied black all filter processed first, then white
1027 filters, and lastly black filters.</para>
1031 <para>The filters added are only used for the current session.
1032 Once the connection is closed the filters are removed.</para>
1033 <para>This comand requires the system permission because
1034 this command can be used to create filters that may bypass
1035 filters defined in manager.conf</para>
1038 <manager name="FilterList" language="en_US">
1040 Show current event filters for this session
1043 <para>The filters displayed are for the current session. Only those filters defined in
1044 manager.conf will be present upon starting a new session.</para>
1047 <manager name="BlindTransfer" language="en_US">
1049 Blind transfer channel(s) to the given destination
1052 <parameter name="Channel" required="true">
1054 <parameter name="Context">
1056 <parameter name="Exten">
1060 <para>Redirect all channels currently bridged to the specified channel to the specified destination.</para>
1063 <ref type="manager">Redirect</ref>
1066 <managerEvent name="ExtensionStatus" language="en_US">
1067 <managerEventInstance class="EVENT_FLAG_CALL">
1068 <synopsis>Raised when a hint changes due to a device state change.</synopsis>
1070 <parameter name="Exten" />
1071 <parameter name="Context" />
1072 <parameter name="Hint" />
1073 <parameter name="Status" />
1074 <parameter name="StatusText" />
1076 </managerEventInstance>
1078 <managerEvent name="PresenceStatus" language="en_US">
1079 <managerEventInstance class="EVENT_FLAG_CALL">
1080 <synopsis>Raised when a hint changes due to a presence state change.</synopsis>
1082 <parameter name="Exten" />
1083 <parameter name="Context" />
1084 <parameter name="Hint" />
1085 <parameter name="Status" />
1086 <parameter name="Subtype" />
1087 <parameter name="Message" />
1089 </managerEventInstance>
1093 /*! \addtogroup Group_AMI AMI functions
1101 UNSPECIFIED_CATEGORY,
1102 UNSPECIFIED_ARGUMENT,
1112 enum add_filter_result {
1114 FILTER_ALLOC_FAILED,
1115 FILTER_COMPILE_FAIL,
1119 * Linked list of events.
1120 * Global events are appended to the list by append_event().
1121 * The usecount is the number of stored pointers to the element,
1122 * excluding the list pointers. So an element that is only in
1123 * the list has a usecount of 0, not 1.
1125 * Clients have a pointer to the last event processed, and for each
1126 * of these clients we track the usecount of the elements.
1127 * If we have a pointer to an entry in the list, it is safe to navigate
1128 * it forward because elements will not be deleted, but only appended.
1129 * The worst that can happen is seeing the pointer still NULL.
1131 * When the usecount of an element drops to 0, and the element is the
1132 * first in the list, we can remove it. Removal is done within the
1133 * main thread, which is woken up for the purpose.
1135 * For simplicity of implementation, we make sure the list is never empty.
1138 int usecount; /*!< # of clients who still need the event */
1140 unsigned int seq; /*!< sequence number */
1141 struct timeval tv; /*!< When event was allocated */
1142 AST_RWLIST_ENTRY(eventqent) eq_next;
1143 char eventdata[1]; /*!< really variable size, allocated by append_event() */
1146 static AST_RWLIST_HEAD_STATIC(all_events, eventqent);
1148 static int displayconnects = 1;
1149 static int allowmultiplelogin = 1;
1150 static int timestampevents;
1151 static int httptimeout = 60;
1152 static int broken_events_action = 0;
1153 static int manager_enabled = 0;
1154 static int subscribed = 0;
1155 static int webmanager_enabled = 0;
1156 static int manager_debug = 0; /*!< enable some debugging code in the manager */
1157 static int authtimeout;
1158 static int authlimit;
1159 static char *manager_channelvars;
1161 #define DEFAULT_REALM "asterisk"
1162 static char global_realm[MAXHOSTNAMELEN]; /*!< Default realm */
1164 static int unauth_sessions = 0;
1165 static struct stasis_subscription *acl_change_sub;
1167 /*! \brief A \ref stasis_topic that all topics AMI cares about will be forwarded to */
1168 static struct stasis_topic *manager_topic;
1170 /*! \brief The \ref stasis_message_router for all \ref stasis messages */
1171 static struct stasis_message_router *stasis_router;
1173 /*! \brief The \ref stasis_subscription for forwarding the RTP topic to the AMI topic */
1174 static struct stasis_forward *rtp_topic_forwarder;
1176 /*! \brief The \ref stasis_subscription for forwarding the Security topic to the AMI topic */
1177 static struct stasis_forward *security_topic_forwarder;
1179 #ifdef TEST_FRAMEWORK
1180 struct stasis_subscription *test_suite_sub;
1183 #define MGR_SHOW_TERMINAL_WIDTH 80
1185 #define MAX_VARS 128
1188 * Descriptor for a manager session, either on the AMI socket or over HTTP.
1191 * AMI session have managerid == 0; the entry is created upon a connect,
1192 * and destroyed with the socket.
1193 * HTTP sessions have managerid != 0, the value is used as a search key
1194 * to lookup sessions (using the mansession_id cookie, or nonce key from
1195 * Digest Authentication http header).
1197 #define MAX_BLACKLIST_CMD_LEN 2
1198 static const struct {
1199 const char *words[AST_MAX_CMD_LEN];
1200 } command_blacklist[] = {
1201 {{ "module", "load", NULL }},
1202 {{ "module", "unload", NULL }},
1203 {{ "restart", "gracefully", NULL }},
1206 static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message);
1208 static void acl_change_stasis_subscribe(void)
1210 if (!acl_change_sub) {
1211 acl_change_sub = stasis_subscribe(ast_security_topic(),
1212 acl_change_stasis_cb, NULL);
1216 static void acl_change_stasis_unsubscribe(void)
1218 acl_change_sub = stasis_unsubscribe_and_join(acl_change_sub);
1221 /* In order to understand what the heck is going on with the
1222 * mansession_session and mansession structs, we need to have a bit of a history
1225 * In the beginning, there was the mansession. The mansession contained data that was
1226 * intrinsic to a manager session, such as the time that it started, the name of the logged-in
1227 * user, etc. In addition to these parameters were the f and fd parameters. For typical manager
1228 * sessions, these were used to represent the TCP socket over which the AMI session was taking
1229 * place. It makes perfect sense for these fields to be a part of the session-specific data since
1230 * the session actually defines this information.
1232 * Then came the HTTP AMI sessions. With these, the f and fd fields need to be opened and closed
1233 * for every single action that occurs. Thus the f and fd fields aren't really specific to the session
1234 * but rather to the action that is being executed. Because a single session may execute many commands
1235 * at once, some sort of safety needed to be added in order to be sure that we did not end up with fd
1236 * leaks from one action overwriting the f and fd fields used by a previous action before the previous action
1237 * has had a chance to properly close its handles.
1239 * The initial idea to solve this was to use thread synchronization, but this prevented multiple actions
1240 * from being run at the same time in a single session. Some manager actions may block for a long time, thus
1241 * creating a large queue of actions to execute. In addition, this fix did not address the basic architectural
1242 * issue that for HTTP manager sessions, the f and fd variables are not really a part of the session, but are
1243 * part of the action instead.
1245 * The new idea was to create a structure on the stack for each HTTP Manager action. This structure would
1246 * contain the action-specific information, such as which file to write to. In order to maintain expectations
1247 * of action handlers and not have to change the public API of the manager code, we would need to name this
1248 * new stacked structure 'mansession' and contain within it the old mansession struct that we used to use.
1249 * We renamed the old mansession struct 'mansession_session' to hopefully convey that what is in this structure
1250 * is session-specific data. The structure that it is wrapped in, called a 'mansession' really contains action-specific
1253 struct mansession_session {
1254 /*! \todo XXX need to document which fields it is protecting */
1255 struct ast_sockaddr addr; /*!< address we are connecting from */
1256 FILE *f; /*!< fdopen() on the underlying fd */
1257 int fd; /*!< descriptor used for output. Either the socket (AMI) or a temporary file (HTTP) */
1258 int inuse; /*!< number of HTTP sessions using this entry */
1259 int needdestroy; /*!< Whether an HTTP session should be destroyed */
1260 pthread_t waiting_thread; /*!< Sleeping thread using this descriptor */
1261 uint32_t managerid; /*!< Unique manager identifier, 0 for AMI sessions */
1262 time_t sessionstart; /*!< Session start time */
1263 struct timeval sessionstart_tv; /*!< Session start time */
1264 time_t sessiontimeout; /*!< Session timeout if HTTP */
1265 char username[80]; /*!< Logged in username */
1266 char challenge[10]; /*!< Authentication challenge */
1267 int authenticated; /*!< Authentication status */
1268 int readperm; /*!< Authorization for reading */
1269 int writeperm; /*!< Authorization for writing */
1270 char inbuf[1025]; /*!< Buffer - we use the extra byte to add a '\\0' and simplify parsing */
1271 int inlen; /*!< number of buffered bytes */
1272 struct ao2_container *whitefilters; /*!< Manager event filters - white list */
1273 struct ao2_container *blackfilters; /*!< Manager event filters - black list */
1274 struct ast_variable *chanvars; /*!< Channel variables to set for originate */
1275 int send_events; /*!< XXX what ? */
1276 struct eventqent *last_ev; /*!< last event processed. */
1277 int writetimeout; /*!< Timeout for ast_carefulwrite() */
1279 int pending_event; /*!< Pending events indicator in case when waiting_thread is NULL */
1280 time_t noncetime; /*!< Timer for nonce value expiration */
1281 unsigned long oldnonce; /*!< Stale nonce value */
1282 unsigned long nc; /*!< incremental nonce counter */
1283 AST_LIST_HEAD_NOLOCK(mansession_datastores, ast_datastore) datastores; /*!< Data stores on the session */
1284 AST_LIST_ENTRY(mansession_session) list;
1287 enum mansession_message_parsing {
1289 MESSAGE_LINE_TOO_LONG
1292 /*! \brief In case you didn't read that giant block of text above the mansession_session struct, the
1293 * \ref struct mansession is named this solely to keep the API the same in Asterisk. This structure really
1294 * represents data that is different from Manager action to Manager action. The mansession_session pointer
1295 * contained within points to session-specific data.
1298 struct mansession_session *session;
1299 struct ast_tcptls_session_instance *tcptls_session;
1302 enum mansession_message_parsing parsing;
1304 struct manager_custom_hook *hook;
1308 /*! Active manager connection sessions container. */
1309 static AO2_GLOBAL_OBJ_STATIC(mgr_sessions);
1311 /*! \brief user descriptor, as read from the config file.
1313 * \note It is still missing some fields -- e.g. we can have multiple permit and deny
1314 * lines which are not supported here, and readperm/writeperm/writetimeout
1317 struct ast_manager_user {
1319 char *secret; /*!< Secret for logging in */
1320 int readperm; /*!< Authorization for reading */
1321 int writeperm; /*!< Authorization for writing */
1322 int writetimeout; /*!< Per user Timeout for ast_carefulwrite() */
1323 int displayconnects; /*!< XXX unused */
1324 int allowmultiplelogin; /*!< Per user option*/
1325 int keep; /*!< mark entries created on a reload */
1326 struct ao2_container *whitefilters; /*!< Manager event filters - white list */
1327 struct ao2_container *blackfilters; /*!< Manager event filters - black list */
1328 struct ast_acl_list *acl; /*!< ACL setting */
1329 char *a1_hash; /*!< precalculated A1 for Digest auth */
1330 struct ast_variable *chanvars; /*!< Channel variables to set for originate */
1331 AST_RWLIST_ENTRY(ast_manager_user) list;
1334 /*! \brief list of users found in the config file */
1335 static AST_RWLIST_HEAD_STATIC(users, ast_manager_user);
1337 /*! \brief list of actions registered */
1338 static AST_RWLIST_HEAD_STATIC(actions, manager_action);
1340 /*! \brief list of hooks registered */
1341 static AST_RWLIST_HEAD_STATIC(manager_hooks, manager_custom_hook);
1343 /*! \brief A container of event documentation nodes */
1344 static AO2_GLOBAL_OBJ_STATIC(event_docs);
1346 static enum add_filter_result manager_add_filter(const char *filter_pattern, struct ao2_container *whitefilters, struct ao2_container *blackfilters);
1349 * @{ \brief Define AMI message types.
1351 STASIS_MESSAGE_TYPE_DEFN(ast_manager_get_generic_type);
1356 * \brief Find a registered action object.
1358 * \param name Name of AMI action to find.
1360 * \return Reffed action found or NULL
1362 static struct manager_action *action_find(const char *name)
1364 struct manager_action *act;
1366 AST_RWLIST_RDLOCK(&actions);
1367 AST_RWLIST_TRAVERSE(&actions, act, list) {
1368 if (!strcasecmp(name, act->action)) {
1369 ao2_t_ref(act, +1, "found action object");
1373 AST_RWLIST_UNLOCK(&actions);
1378 struct stasis_topic *ast_manager_get_topic(void)
1380 return manager_topic;
1383 struct stasis_message_router *ast_manager_get_message_router(void)
1385 return stasis_router;
1388 static void manager_json_value_str_append(struct ast_json *value, const char *key,
1389 struct ast_str **res)
1391 switch (ast_json_typeof(value)) {
1392 case AST_JSON_STRING:
1393 ast_str_append(res, 0, "%s: %s\r\n", key, ast_json_string_get(value));
1395 case AST_JSON_INTEGER:
1396 ast_str_append(res, 0, "%s: %jd\r\n", key, ast_json_integer_get(value));
1399 ast_str_append(res, 0, "%s: True\r\n", key);
1401 case AST_JSON_FALSE:
1402 ast_str_append(res, 0, "%s: False\r\n", key);
1405 ast_str_append(res, 0, "%s: \r\n", key);
1410 static void manager_json_to_ast_str(struct ast_json *obj, const char *key,
1411 struct ast_str **res, key_exclusion_cb exclusion_cb);
1413 static void manager_json_array_with_key(struct ast_json *obj, const char* key,
1414 size_t index, struct ast_str **res,
1415 key_exclusion_cb exclusion_cb)
1417 struct ast_str *key_str = ast_str_alloca(64);
1418 ast_str_set(&key_str, 0, "%s(%zu)", key, index);
1419 manager_json_to_ast_str(obj, ast_str_buffer(key_str),
1423 static void manager_json_obj_with_key(struct ast_json *obj, const char* key,
1424 const char *parent_key, struct ast_str **res,
1425 key_exclusion_cb exclusion_cb)
1428 struct ast_str *key_str = ast_str_alloca(64);
1429 ast_str_set(&key_str, 0, "%s/%s", parent_key, key);
1430 manager_json_to_ast_str(obj, ast_str_buffer(key_str),
1435 manager_json_to_ast_str(obj, key, res, exclusion_cb);
1438 void manager_json_to_ast_str(struct ast_json *obj, const char *key,
1439 struct ast_str **res, key_exclusion_cb exclusion_cb)
1441 struct ast_json_iter *i;
1443 if (!obj || (!res && !(*res) && (!(*res = ast_str_create(1024))))) {
1447 if (exclusion_cb && key && exclusion_cb(key)) {
1451 if (ast_json_typeof(obj) != AST_JSON_OBJECT &&
1452 ast_json_typeof(obj) != AST_JSON_ARRAY) {
1453 manager_json_value_str_append(obj, key, res);
1457 if (ast_json_typeof(obj) == AST_JSON_ARRAY) {
1459 for (j = 0; j < ast_json_array_size(obj); ++j) {
1460 manager_json_array_with_key(ast_json_array_get(obj, j),
1461 key, j, res, exclusion_cb);
1466 for (i = ast_json_object_iter(obj); i;
1467 i = ast_json_object_iter_next(obj, i)) {
1468 manager_json_obj_with_key(ast_json_object_iter_value(i),
1469 ast_json_object_iter_key(i),
1470 key, res, exclusion_cb);
1475 struct ast_str *ast_manager_str_from_json_object(struct ast_json *blob, key_exclusion_cb exclusion_cb)
1477 struct ast_str *res = ast_str_create(1024);
1478 manager_json_to_ast_str(blob, NULL, &res, exclusion_cb);
1482 static void manager_default_msg_cb(void *data, struct stasis_subscription *sub,
1483 struct stasis_message *message)
1485 RAII_VAR(struct ast_manager_event_blob *, ev, NULL, ao2_cleanup);
1487 ev = stasis_message_to_ami(message);
1490 /* Not and AMI message; disregard */
1494 manager_event(ev->event_flags, ev->manager_event, "%s",
1498 static void manager_generic_msg_cb(void *data, struct stasis_subscription *sub,
1499 struct stasis_message *message)
1501 struct ast_json_payload *payload = stasis_message_data(message);
1502 int class_type = ast_json_integer_get(ast_json_object_get(payload->json, "class_type"));
1503 const char *type = ast_json_string_get(ast_json_object_get(payload->json, "type"));
1504 struct ast_json *event = ast_json_object_get(payload->json, "event");
1505 RAII_VAR(struct ast_str *, event_buffer, NULL, ast_free);
1507 event_buffer = ast_manager_str_from_json_object(event, NULL);
1508 if (!event_buffer) {
1509 ast_log(AST_LOG_WARNING, "Error while creating payload for event %s\n", type);
1512 manager_event(class_type, type, "%s", ast_str_buffer(event_buffer));
1515 void ast_manager_publish_event(const char *type, int class_type, struct ast_json *obj)
1517 RAII_VAR(struct ast_json *, event_info, NULL, ast_json_unref);
1518 RAII_VAR(struct ast_json_payload *, payload, NULL, ao2_cleanup);
1519 RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
1526 event_info = ast_json_pack("{s: s, s: i, s: o}",
1528 "class_type", class_type,
1534 payload = ast_json_payload_create(event_info);
1538 message = stasis_message_create(ast_manager_get_generic_type(), payload);
1542 stasis_publish(ast_manager_get_topic(), message);
1545 /*! \brief Add a custom hook to be called when an event is fired */
1546 void ast_manager_register_hook(struct manager_custom_hook *hook)
1548 AST_RWLIST_WRLOCK(&manager_hooks);
1549 AST_RWLIST_INSERT_TAIL(&manager_hooks, hook, list);
1550 AST_RWLIST_UNLOCK(&manager_hooks);
1553 /*! \brief Delete a custom hook to be called when an event is fired */
1554 void ast_manager_unregister_hook(struct manager_custom_hook *hook)
1556 AST_RWLIST_WRLOCK(&manager_hooks);
1557 AST_RWLIST_REMOVE(&manager_hooks, hook, list);
1558 AST_RWLIST_UNLOCK(&manager_hooks);
1561 int check_manager_enabled(void)
1563 return manager_enabled;
1566 int check_webmanager_enabled(void)
1568 return (webmanager_enabled && manager_enabled);
1572 * Grab a reference to the last event, update usecount as needed.
1573 * Can handle a NULL pointer.
1575 static struct eventqent *grab_last(void)
1577 struct eventqent *ret;
1579 AST_RWLIST_WRLOCK(&all_events);
1580 ret = AST_RWLIST_LAST(&all_events);
1581 /* the list is never empty now, but may become so when
1582 * we optimize it in the future, so be prepared.
1585 ast_atomic_fetchadd_int(&ret->usecount, 1);
1587 AST_RWLIST_UNLOCK(&all_events);
1592 * Purge unused events. Remove elements from the head
1593 * as long as their usecount is 0 and there is a next element.
1595 static void purge_events(void)
1597 struct eventqent *ev;
1598 struct timeval now = ast_tvnow();
1600 AST_RWLIST_WRLOCK(&all_events);
1601 while ( (ev = AST_RWLIST_FIRST(&all_events)) &&
1602 ev->usecount == 0 && AST_RWLIST_NEXT(ev, eq_next)) {
1603 AST_RWLIST_REMOVE_HEAD(&all_events, eq_next);
1607 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&all_events, ev, eq_next) {
1608 /* Never release the last event */
1609 if (!AST_RWLIST_NEXT(ev, eq_next)) {
1613 /* 2.5 times whatever the HTTP timeout is (maximum 2.5 hours) is the maximum time that we will definitely cache an event */
1614 if (ev->usecount == 0 && ast_tvdiff_sec(now, ev->tv) > (httptimeout > 3600 ? 3600 : httptimeout) * 2.5) {
1615 AST_RWLIST_REMOVE_CURRENT(eq_next);
1619 AST_RWLIST_TRAVERSE_SAFE_END;
1620 AST_RWLIST_UNLOCK(&all_events);
1624 * helper functions to convert back and forth between
1625 * string and numeric representation of set of flags
1627 static const struct permalias {
1631 { EVENT_FLAG_SYSTEM, "system" },
1632 { EVENT_FLAG_CALL, "call" },
1633 { EVENT_FLAG_LOG, "log" },
1634 { EVENT_FLAG_VERBOSE, "verbose" },
1635 { EVENT_FLAG_COMMAND, "command" },
1636 { EVENT_FLAG_AGENT, "agent" },
1637 { EVENT_FLAG_USER, "user" },
1638 { EVENT_FLAG_CONFIG, "config" },
1639 { EVENT_FLAG_DTMF, "dtmf" },
1640 { EVENT_FLAG_REPORTING, "reporting" },
1641 { EVENT_FLAG_CDR, "cdr" },
1642 { EVENT_FLAG_DIALPLAN, "dialplan" },
1643 { EVENT_FLAG_ORIGINATE, "originate" },
1644 { EVENT_FLAG_AGI, "agi" },
1645 { EVENT_FLAG_CC, "cc" },
1646 { EVENT_FLAG_AOC, "aoc" },
1647 { EVENT_FLAG_TEST, "test" },
1648 { EVENT_FLAG_SECURITY, "security" },
1649 { EVENT_FLAG_MESSAGE, "message" },
1654 /*! \brief Checks to see if a string which can be used to evaluate functions should be rejected */
1655 static int function_capable_string_allowed_with_auths(const char *evaluating, int writepermlist)
1657 if (!(writepermlist & EVENT_FLAG_SYSTEM)
1659 strstr(evaluating, "SHELL") || /* NoOp(${SHELL(rm -rf /)}) */
1660 strstr(evaluating, "EVAL") /* NoOp(${EVAL(${some_var_containing_SHELL})}) */
1667 /*! \brief Convert authority code to a list of options for a user. This will only
1668 * display those authority codes that have an explicit match on authority */
1669 static const char *user_authority_to_str(int authority, struct ast_str **res)
1674 ast_str_reset(*res);
1675 for (i = 0; i < ARRAY_LEN(perms) - 1; i++) {
1676 if ((authority & perms[i].num) == perms[i].num) {
1677 ast_str_append(res, 0, "%s%s", sep, perms[i].label);
1682 if (ast_str_strlen(*res) == 0) /* replace empty string with something sensible */
1683 ast_str_append(res, 0, "<none>");
1685 return ast_str_buffer(*res);
1689 /*! \brief Convert authority code to a list of options. Note that the EVENT_FLAG_ALL
1690 * authority will always be returned. */
1691 static const char *authority_to_str(int authority, struct ast_str **res)
1696 ast_str_reset(*res);
1697 for (i = 0; i < ARRAY_LEN(perms) - 1; i++) {
1698 if (authority & perms[i].num) {
1699 ast_str_append(res, 0, "%s%s", sep, perms[i].label);
1704 if (ast_str_strlen(*res) == 0) /* replace empty string with something sensible */
1705 ast_str_append(res, 0, "<none>");
1707 return ast_str_buffer(*res);
1710 /*! Tells you if smallstr exists inside bigstr
1711 which is delim by delim and uses no buf or stringsep
1712 ast_instring("this|that|more","this",'|') == 1;
1714 feel free to move this to app.c -anthm */
1715 static int ast_instring(const char *bigstr, const char *smallstr, const char delim)
1717 const char *val = bigstr, *next;
1720 if ((next = strchr(val, delim))) {
1721 if (!strncmp(val, smallstr, (next - val))) {
1727 return !strcmp(smallstr, val);
1729 } while (*(val = (next + 1)));
1734 static int get_perm(const char *instr)
1742 for (x = 0; x < ARRAY_LEN(perms); x++) {
1743 if (ast_instring(instr, perms[x].label, ',')) {
1744 ret |= perms[x].num;
1752 * A number returns itself, false returns 0, true returns all flags,
1753 * other strings return the flags that are set.
1755 static int strings_to_mask(const char *string)
1759 if (ast_strlen_zero(string)) {
1763 for (p = string; *p; p++) {
1764 if (*p < '0' || *p > '9') {
1768 if (!*p) { /* all digits */
1769 return atoi(string);
1771 if (ast_false(string)) {
1774 if (ast_true(string)) { /* all permissions */
1776 for (x = 0; x < ARRAY_LEN(perms); x++) {
1777 ret |= perms[x].num;
1781 return get_perm(string);
1784 /*! \brief Unreference manager session object.
1785 If no more references, then go ahead and delete it */
1786 static struct mansession_session *unref_mansession(struct mansession_session *s)
1788 int refcount = ao2_ref(s, -1);
1789 if (manager_debug) {
1790 ast_debug(1, "Mansession: %p refcount now %d\n", s, refcount - 1);
1795 static void event_filter_destructor(void *obj)
1797 regex_t *regex_filter = obj;
1798 regfree(regex_filter);
1801 static void session_destructor(void *obj)
1803 struct mansession_session *session = obj;
1804 struct eventqent *eqe = session->last_ev;
1805 struct ast_datastore *datastore;
1807 /* Get rid of each of the data stores on the session */
1808 while ((datastore = AST_LIST_REMOVE_HEAD(&session->datastores, entry))) {
1809 /* Free the data store */
1810 ast_datastore_free(datastore);
1813 if (session->f != NULL) {
1818 ast_atomic_fetchadd_int(&eqe->usecount, -1);
1820 if (session->chanvars) {
1821 ast_variables_destroy(session->chanvars);
1824 if (session->whitefilters) {
1825 ao2_t_ref(session->whitefilters, -1, "decrement ref for white container, should be last one");
1828 if (session->blackfilters) {
1829 ao2_t_ref(session->blackfilters, -1, "decrement ref for black container, should be last one");
1833 /*! \brief Allocate manager session structure and add it to the list of sessions */
1834 static struct mansession_session *build_mansession(const struct ast_sockaddr *addr)
1836 struct ao2_container *sessions;
1837 struct mansession_session *newsession;
1839 newsession = ao2_alloc(sizeof(*newsession), session_destructor);
1844 newsession->whitefilters = ao2_container_alloc(1, NULL, NULL);
1845 newsession->blackfilters = ao2_container_alloc(1, NULL, NULL);
1846 if (!newsession->whitefilters || !newsession->blackfilters) {
1847 ao2_ref(newsession, -1);
1851 newsession->fd = -1;
1852 newsession->waiting_thread = AST_PTHREADT_NULL;
1853 newsession->writetimeout = 100;
1854 newsession->send_events = -1;
1855 ast_sockaddr_copy(&newsession->addr, addr);
1857 sessions = ao2_global_obj_ref(mgr_sessions);
1859 ao2_link(sessions, newsession);
1860 ao2_ref(sessions, -1);
1866 static int mansession_cmp_fn(void *obj, void *arg, int flags)
1868 struct mansession_session *s = obj;
1870 return !strcasecmp(s->username, str) ? CMP_MATCH : 0;
1873 static void session_destroy(struct mansession_session *s)
1875 struct ao2_container *sessions;
1877 sessions = ao2_global_obj_ref(mgr_sessions);
1879 ao2_unlink(sessions, s);
1880 ao2_ref(sessions, -1);
1882 unref_mansession(s);
1886 static int check_manager_session_inuse(const char *name)
1888 struct ao2_container *sessions;
1889 struct mansession_session *session;
1892 sessions = ao2_global_obj_ref(mgr_sessions);
1894 session = ao2_find(sessions, (char *) name, 0);
1895 ao2_ref(sessions, -1);
1897 unref_mansession(session);
1906 * lookup an entry in the list of registered users.
1907 * must be called with the list lock held.
1909 static struct ast_manager_user *get_manager_by_name_locked(const char *name)
1911 struct ast_manager_user *user = NULL;
1913 AST_RWLIST_TRAVERSE(&users, user, list) {
1914 if (!strcasecmp(user->username, name)) {
1922 /*! \brief Get displayconnects config option.
1923 * \param session manager session to get parameter from.
1924 * \return displayconnects config option value.
1926 static int manager_displayconnects(struct mansession_session *session)
1928 struct ast_manager_user *user = NULL;
1931 AST_RWLIST_RDLOCK(&users);
1932 if ((user = get_manager_by_name_locked(session->username))) {
1933 ret = user->displayconnects;
1935 AST_RWLIST_UNLOCK(&users);
1940 static void print_event_instance(struct ast_cli_args *a, struct ast_xml_doc_item *instance);
1942 static char *handle_showmancmd(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1944 struct manager_action *cur;
1945 struct ast_str *authority;
1949 char syntax_title[64], description_title[64], synopsis_title[64], seealso_title[64];
1950 char arguments_title[64], privilege_title[64], final_response_title[64], list_responses_title[64];
1955 e->command = "manager show command";
1957 "Usage: manager show command <actionname> [<actionname> [<actionname> [...]]]\n"
1958 " Shows the detailed description for a specific Asterisk manager interface command.\n";
1961 l = strlen(a->word);
1963 AST_RWLIST_RDLOCK(&actions);
1964 AST_RWLIST_TRAVERSE(&actions, cur, list) {
1965 if (!strncasecmp(a->word, cur->action, l) && ++which > a->n) {
1966 ret = ast_strdup(cur->action);
1967 break; /* make sure we exit even if ast_strdup() returns NULL */
1970 AST_RWLIST_UNLOCK(&actions);
1973 authority = ast_str_alloca(80);
1975 return CLI_SHOWUSAGE;
1979 /* setup the titles */
1980 term_color(synopsis_title, "[Synopsis]\n", COLOR_MAGENTA, 0, 40);
1981 term_color(description_title, "[Description]\n", COLOR_MAGENTA, 0, 40);
1982 term_color(syntax_title, "[Syntax]\n", COLOR_MAGENTA, 0, 40);
1983 term_color(seealso_title, "[See Also]\n", COLOR_MAGENTA, 0, 40);
1984 term_color(arguments_title, "[Arguments]\n", COLOR_MAGENTA, 0, 40);
1985 term_color(privilege_title, "[Privilege]\n", COLOR_MAGENTA, 0, 40);
1986 term_color(final_response_title, "[Final Response]\n", COLOR_MAGENTA, 0, 40);
1987 term_color(list_responses_title, "[List Responses]\n", COLOR_MAGENTA, 0, 40);
1990 AST_RWLIST_RDLOCK(&actions);
1991 AST_RWLIST_TRAVERSE(&actions, cur, list) {
1992 for (num = 3; num < a->argc; num++) {
1993 if (!strcasecmp(cur->action, a->argv[num])) {
1994 authority_to_str(cur->authority, &authority);
1997 if (cur->docsrc == AST_XML_DOC) {
1998 char *syntax = ast_xmldoc_printable(S_OR(cur->syntax, "Not available"), 1);
1999 char *synopsis = ast_xmldoc_printable(S_OR(cur->synopsis, "Not available"), 1);
2000 char *description = ast_xmldoc_printable(S_OR(cur->description, "Not available"), 1);
2001 char *arguments = ast_xmldoc_printable(S_OR(cur->arguments, "Not available"), 1);
2002 char *seealso = ast_xmldoc_printable(S_OR(cur->seealso, "Not available"), 1);
2003 char *privilege = ast_xmldoc_printable(S_OR(authority->str, "Not available"), 1);
2004 char *responses = ast_xmldoc_printable("None", 1);
2005 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%s",
2006 syntax_title, syntax,
2007 synopsis_title, synopsis,
2008 description_title, description,
2009 arguments_title, arguments,
2010 seealso_title, seealso,
2011 privilege_title, privilege,
2012 list_responses_title);
2014 if (!cur->list_responses) {
2015 ast_cli(a->fd, "%s\n\n", responses);
2017 struct ast_xml_doc_item *temp;
2018 for (temp = cur->list_responses; temp; temp = AST_LIST_NEXT(temp, next)) {
2019 ast_cli(a->fd, "Event: %s\n", temp->name);
2020 print_event_instance(a, temp);
2024 ast_cli(a->fd, "%s", final_response_title);
2026 if (!cur->final_response) {
2027 ast_cli(a->fd, "%s\n\n", responses);
2029 ast_cli(a->fd, "Event: %s\n", cur->final_response->name);
2030 print_event_instance(a, cur->final_response);
2035 ast_cli(a->fd, "Action: %s\nSynopsis: %s\nPrivilege: %s\n%s\n",
2036 cur->action, cur->synopsis,
2038 S_OR(cur->description, ""));
2043 AST_RWLIST_UNLOCK(&actions);
2048 static char *handle_mandebug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2052 e->command = "manager set debug [on|off]";
2053 e->usage = "Usage: manager set debug [on|off]\n Show, enable, disable debugging of the manager code.\n";
2060 ast_cli(a->fd, "manager debug is %s\n", manager_debug? "on" : "off");
2061 } else if (a->argc == 4) {
2062 if (!strcasecmp(a->argv[3], "on")) {
2064 } else if (!strcasecmp(a->argv[3], "off")) {
2067 return CLI_SHOWUSAGE;
2073 static char *handle_showmanager(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2075 struct ast_manager_user *user = NULL;
2078 struct ast_str *rauthority = ast_str_alloca(128);
2079 struct ast_str *wauthority = ast_str_alloca(128);
2080 struct ast_variable *v;
2084 e->command = "manager show user";
2086 " Usage: manager show user <user>\n"
2087 " Display all information related to the manager user specified.\n";
2090 l = strlen(a->word);
2095 AST_RWLIST_RDLOCK(&users);
2096 AST_RWLIST_TRAVERSE(&users, user, list) {
2097 if ( !strncasecmp(a->word, user->username, l) && ++which > a->n ) {
2098 ret = ast_strdup(user->username);
2102 AST_RWLIST_UNLOCK(&users);
2107 return CLI_SHOWUSAGE;
2110 AST_RWLIST_RDLOCK(&users);
2112 if (!(user = get_manager_by_name_locked(a->argv[3]))) {
2113 ast_cli(a->fd, "There is no manager called %s\n", a->argv[3]);
2114 AST_RWLIST_UNLOCK(&users);
2118 ast_cli(a->fd, "\n");
2125 " displayconnects: %s\n"
2126 "allowmultiplelogin: %s\n",
2127 (user->username ? user->username : "(N/A)"),
2128 (user->secret ? "<Set>" : "(N/A)"),
2129 ((user->acl && !ast_acl_list_is_empty(user->acl)) ? "yes" : "no"),
2130 user_authority_to_str(user->readperm, &rauthority),
2131 user_authority_to_str(user->writeperm, &wauthority),
2132 (user->displayconnects ? "yes" : "no"),
2133 (user->allowmultiplelogin ? "yes" : "no"));
2134 ast_cli(a->fd, " Variables: \n");
2135 for (v = user->chanvars ; v ; v = v->next) {
2136 ast_cli(a->fd, " %s = %s\n", v->name, v->value);
2139 AST_RWLIST_UNLOCK(&users);
2144 static char *handle_showmanagers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2146 struct ast_manager_user *user = NULL;
2150 e->command = "manager show users";
2152 "Usage: manager show users\n"
2153 " Prints a listing of all managers that are currently configured on that\n"
2160 return CLI_SHOWUSAGE;
2163 AST_RWLIST_RDLOCK(&users);
2165 /* If there are no users, print out something along those lines */
2166 if (AST_RWLIST_EMPTY(&users)) {
2167 ast_cli(a->fd, "There are no manager users.\n");
2168 AST_RWLIST_UNLOCK(&users);
2172 ast_cli(a->fd, "\nusername\n--------\n");
2174 AST_RWLIST_TRAVERSE(&users, user, list) {
2175 ast_cli(a->fd, "%s\n", user->username);
2179 AST_RWLIST_UNLOCK(&users);
2181 ast_cli(a->fd,"-------------------\n"
2182 "%d manager users configured.\n", count_amu);
2186 /*! \brief CLI command manager list commands */
2187 static char *handle_showmancmds(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2189 struct manager_action *cur;
2191 int space_remaining;
2192 #define HSMC_FORMAT " %-*.*s %-.*s\n"
2195 e->command = "manager show commands";
2197 "Usage: manager show commands\n"
2198 " Prints a listing of all the available Asterisk manager interface commands.\n";
2204 AST_RWLIST_RDLOCK(&actions);
2205 AST_RWLIST_TRAVERSE(&actions, cur, list) {
2206 int incoming_len = strlen(cur->action);
2207 if (incoming_len > name_len) {
2208 name_len = incoming_len;
2212 space_remaining = MGR_SHOW_TERMINAL_WIDTH - name_len - 4;
2213 if (space_remaining < 0) {
2214 space_remaining = 0;
2217 ast_cli(a->fd, HSMC_FORMAT, name_len, name_len, "Action", space_remaining, "Synopsis");
2218 ast_cli(a->fd, HSMC_FORMAT, name_len, name_len, "------", space_remaining, "--------");
2220 AST_RWLIST_TRAVERSE(&actions, cur, list) {
2221 ast_cli(a->fd, HSMC_FORMAT, name_len, name_len, cur->action, space_remaining, cur->synopsis);
2223 AST_RWLIST_UNLOCK(&actions);
2228 /*! \brief CLI command manager list connected */
2229 static char *handle_showmanconn(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2231 struct ao2_container *sessions;
2232 struct mansession_session *session;
2233 time_t now = time(NULL);
2234 #define HSMCONN_FORMAT1 " %-15.15s %-55.55s %-10.10s %-10.10s %-8.8s %-8.8s %-5.5s %-5.5s\n"
2235 #define HSMCONN_FORMAT2 " %-15.15s %-55.55s %-10d %-10d %-8d %-8d %-5.5d %-5.5d\n"
2237 struct ao2_iterator i;
2241 e->command = "manager show connected";
2243 "Usage: manager show connected\n"
2244 " Prints a listing of the users that are currently connected to the\n"
2245 "Asterisk manager interface.\n";
2251 ast_cli(a->fd, HSMCONN_FORMAT1, "Username", "IP Address", "Start", "Elapsed", "FileDes", "HttpCnt", "Read", "Write");
2253 sessions = ao2_global_obj_ref(mgr_sessions);
2255 i = ao2_iterator_init(sessions, 0);
2256 ao2_ref(sessions, -1);
2257 while ((session = ao2_iterator_next(&i))) {
2259 ast_cli(a->fd, HSMCONN_FORMAT2, session->username,
2260 ast_sockaddr_stringify_addr(&session->addr),
2261 (int) (session->sessionstart),
2262 (int) (now - session->sessionstart),
2266 session->writeperm);
2268 ao2_unlock(session);
2269 unref_mansession(session);
2271 ao2_iterator_destroy(&i);
2273 ast_cli(a->fd, "%d users connected.\n", count);
2278 /*! \brief CLI command manager list eventq */
2279 /* Should change to "manager show connected" */
2280 static char *handle_showmaneventq(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2282 struct eventqent *s;
2285 e->command = "manager show eventq";
2287 "Usage: manager show eventq\n"
2288 " Prints a listing of all events pending in the Asterisk manger\n"
2294 AST_RWLIST_RDLOCK(&all_events);
2295 AST_RWLIST_TRAVERSE(&all_events, s, eq_next) {
2296 ast_cli(a->fd, "Usecount: %d\n", s->usecount);
2297 ast_cli(a->fd, "Category: %d\n", s->category);
2298 ast_cli(a->fd, "Event:\n%s", s->eventdata);
2300 AST_RWLIST_UNLOCK(&all_events);
2305 /*! \brief CLI command manager reload */
2306 static char *handle_manager_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2310 e->command = "manager reload";
2312 "Usage: manager reload\n"
2313 " Reloads the manager configuration.\n";
2319 return CLI_SHOWUSAGE;
2325 static struct eventqent *advance_event(struct eventqent *e)
2327 struct eventqent *next;
2329 AST_RWLIST_RDLOCK(&all_events);
2330 if ((next = AST_RWLIST_NEXT(e, eq_next))) {
2331 ast_atomic_fetchadd_int(&next->usecount, 1);
2332 ast_atomic_fetchadd_int(&e->usecount, -1);
2334 AST_RWLIST_UNLOCK(&all_events);
2338 #define GET_HEADER_FIRST_MATCH 0
2339 #define GET_HEADER_LAST_MATCH 1
2340 #define GET_HEADER_SKIP_EMPTY 2
2343 * \brief Return a matching header value.
2346 * Generic function to return either the first or the last
2347 * matching header from a list of variables, possibly skipping
2350 * \note At the moment there is only one use of this function in
2351 * this file, so we make it static.
2353 * \note Never returns NULL.
2355 static const char *__astman_get_header(const struct message *m, char *var, int mode)
2357 int x, l = strlen(var);
2358 const char *result = "";
2364 for (x = 0; x < m->hdrcount; x++) {
2365 const char *h = m->headers[x];
2366 if (!strncasecmp(var, h, l) && h[l] == ':') {
2367 const char *value = h + l + 1;
2368 value = ast_skip_blanks(value); /* ignore leading spaces in the value */
2369 /* found a potential candidate */
2370 if ((mode & GET_HEADER_SKIP_EMPTY) && ast_strlen_zero(value)) {
2371 continue; /* not interesting */
2373 if (mode & GET_HEADER_LAST_MATCH) {
2374 result = value; /* record the last match so far */
2385 * \brief Return the first matching variable from an array.
2387 * \note This is the legacy function and is implemented in
2388 * therms of __astman_get_header().
2390 * \note Never returns NULL.
2392 const char *astman_get_header(const struct message *m, char *var)
2394 return __astman_get_header(m, var, GET_HEADER_FIRST_MATCH);
2399 * \brief Process one "Variable:" header value string.
2401 * \param head Current list of AMI variables to get new values added.
2402 * \param hdr_val Header value string to process.
2404 * \return New variable list head.
2406 static struct ast_variable *man_do_variable_value(struct ast_variable *head, const char *hdr_val)
2409 AST_DECLARE_APP_ARGS(args,
2410 AST_APP_ARG(vars)[64];
2413 hdr_val = ast_skip_blanks(hdr_val); /* ignore leading spaces in the value */
2414 parse = ast_strdupa(hdr_val);
2416 /* Break the header value string into name=val pair items. */
2417 AST_STANDARD_APP_ARGS(args, parse);
2421 /* Process each name=val pair item. */
2422 for (y = 0; y < args.argc; y++) {
2423 struct ast_variable *cur;
2427 if (!args.vars[y]) {
2430 var = val = args.vars[y];
2433 /* XXX We may wish to trim whitespace from the strings. */
2434 if (!val || ast_strlen_zero(var)) {
2438 /* Create new variable list node and prepend it to the list. */
2439 cur = ast_variable_new(var, val, "");
2450 struct ast_variable *astman_get_variables(const struct message *m)
2452 return astman_get_variables_order(m, ORDER_REVERSE);
2455 struct ast_variable *astman_get_variables_order(const struct message *m,
2456 enum variable_orders order)
2460 struct ast_variable *head = NULL;
2462 static const char var_hdr[] = "Variable:";
2464 /* Process all "Variable:" headers. */
2465 varlen = strlen(var_hdr);
2466 for (x = 0; x < m->hdrcount; x++) {
2467 if (strncasecmp(var_hdr, m->headers[x], varlen)) {
2470 head = man_do_variable_value(head, m->headers[x] + varlen);
2473 if (order == ORDER_NATURAL) {
2474 head = ast_variables_reverse(head);
2480 /*! \brief access for hooks to send action messages to ami */
2481 int ast_hook_send_action(struct manager_custom_hook *hook, const char *msg)
2485 struct manager_action *act_found;
2486 struct mansession s = {.session = NULL, };
2487 struct message m = { 0 };
2497 /* Create our own copy of the AMI action msg string. */
2498 src = dup_str = ast_strdup(msg);
2503 /* convert msg string to message struct */
2504 curlen = strlen(src);
2505 for (x = 0; x < curlen; x++) {
2506 int cr; /* set if we have \r */
2507 if (src[x] == '\r' && x+1 < curlen && src[x+1] == '\n')
2508 cr = 2; /* Found. Update length to include \r\n */
2509 else if (src[x] == '\n')
2510 cr = 1; /* also accept \n only */
2513 /* don't keep empty lines */
2514 if (x && m.hdrcount < ARRAY_LEN(m.headers)) {
2515 /* ... but trim \r\n and terminate the header string */
2517 m.headers[m.hdrcount++] = src;
2520 curlen -= x; /* remaining size */
2521 src += x; /* update pointer */
2522 x = -1; /* reset loop */
2525 action = astman_get_header(&m, "Action");
2526 if (strcasecmp(action, "login")) {
2527 act_found = action_find(action);
2530 * we have to simulate a session for this action request
2531 * to be able to pass it down for processing
2532 * This is necessary to meet the previous design of manager.c
2535 s.f = (void*)1; /* set this to something so our request will make it through all functions that test it*/
2537 ao2_lock(act_found);
2538 if (act_found->registered && act_found->func) {
2539 if (act_found->module) {
2540 ast_module_ref(act_found->module);
2542 ao2_unlock(act_found);
2543 ret = act_found->func(&s, &m);
2544 ao2_lock(act_found);
2545 if (act_found->module) {
2546 ast_module_unref(act_found->module);
2551 ao2_unlock(act_found);
2552 ao2_t_ref(act_found, -1, "done with found action object");
2561 * helper function to send a string to the socket.
2562 * Return -1 on error (e.g. buffer full).
2564 static int send_string(struct mansession *s, char *string)
2567 FILE *f = s->f ? s->f : s->session->f;
2568 int fd = s->f ? s->fd : s->session->fd;
2570 /* It's a result from one of the hook's action invocation */
2573 * to send responses, we're using the same function
2574 * as for receiving events. We call the event "HookResponse"
2576 s->hook->helper(EVENT_FLAG_HOOKRESPONSE, "HookResponse", string);
2580 if ((res = ast_careful_fwrite(f, fd, string, strlen(string), s->session->writetimeout))) {
2588 * \brief thread local buffer for astman_append
2590 * \note This can not be defined within the astman_append() function
2591 * because it declares a couple of functions that get used to
2592 * initialize the thread local storage key.
2594 AST_THREADSTORAGE(astman_append_buf);
2596 AST_THREADSTORAGE(userevent_buf);
2598 /*! \brief initial allocated size for the astman_append_buf and astman_send_*_va */
2599 #define ASTMAN_APPEND_BUF_INITSIZE 256
2602 * utility functions for creating AMI replies
2604 void astman_append(struct mansession *s, const char *fmt, ...)
2607 struct ast_str *buf;
2609 if (!(buf = ast_str_thread_get(&astman_append_buf, ASTMAN_APPEND_BUF_INITSIZE))) {
2614 ast_str_set_va(&buf, 0, fmt, ap);
2617 if (s->f != NULL || s->session->f != NULL) {
2618 send_string(s, ast_str_buffer(buf));
2620 ast_verbose("fd == -1 in astman_append, should not happen\n");
2624 /*! \note NOTE: XXX this comment is unclear and possibly wrong.
2625 Callers of astman_send_error(), astman_send_response() or astman_send_ack() must EITHER
2626 hold the session lock _or_ be running in an action callback (in which case s->session->busy will
2627 be non-zero). In either of these cases, there is no need to lock-protect the session's
2628 fd, since no other output will be sent (events will be queued), and no input will
2629 be read until either the current action finishes or get_input() obtains the session
2633 /*! \todo XXX MSG_MOREDATA should go to a header file. */
2634 #define MSG_MOREDATA ((char *)astman_send_response)
2636 /*! \brief send a response with an optional message,
2637 * and terminate it with an empty line.
2638 * m is used only to grab the 'ActionID' field.
2640 * Use the explicit constant MSG_MOREDATA to remove the empty line.
2641 * XXX MSG_MOREDATA should go to a header file.
2643 static void astman_send_response_full(struct mansession *s, const struct message *m, char *resp, char *msg, char *listflag)
2645 const char *id = astman_get_header(m, "ActionID");
2647 astman_append(s, "Response: %s\r\n", resp);
2648 if (!ast_strlen_zero(id)) {
2649 astman_append(s, "ActionID: %s\r\n", id);
2652 astman_append(s, "EventList: %s\r\n", listflag); /* Start, complete, cancelled */
2654 if (msg == MSG_MOREDATA) {
2657 astman_append(s, "Message: %s\r\n\r\n", msg);
2659 astman_append(s, "\r\n");
2663 void astman_send_response(struct mansession *s, const struct message *m, char *resp, char *msg)
2665 astman_send_response_full(s, m, resp, msg, NULL);
2668 void astman_send_error(struct mansession *s, const struct message *m, char *error)
2670 astman_send_response_full(s, m, "Error", error, NULL);
2673 void astman_send_error_va(struct mansession *s, const struct message *m, const char *fmt, ...)
2676 struct ast_str *buf;
2679 if (!(buf = ast_str_thread_get(&astman_append_buf, ASTMAN_APPEND_BUF_INITSIZE))) {
2684 ast_str_set_va(&buf, 0, fmt, ap);
2687 /* astman_append will use the same underlying buffer, so copy the message out
2688 * before sending the response */
2689 msg = ast_str_buffer(buf);
2691 msg = ast_strdupa(msg);
2693 astman_send_response_full(s, m, "Error", msg, NULL);
2696 void astman_send_ack(struct mansession *s, const struct message *m, char *msg)
2698 astman_send_response_full(s, m, "Success", msg, NULL);
2701 static void astman_start_ack(struct mansession *s, const struct message *m)
2703 astman_send_response_full(s, m, "Success", MSG_MOREDATA, NULL);
2706 void astman_send_listack(struct mansession *s, const struct message *m, char *msg, char *listflag)
2708 astman_send_response_full(s, m, "Success", msg, listflag);
2711 /*! \brief Lock the 'mansession' structure. */
2712 static void mansession_lock(struct mansession *s)
2714 ast_mutex_lock(&s->lock);
2717 /*! \brief Unlock the 'mansession' structure. */
2718 static void mansession_unlock(struct mansession *s)
2720 ast_mutex_unlock(&s->lock);
2724 Rather than braindead on,off this now can also accept a specific int mask value
2725 or a ',' delim list of mask strings (the same as manager.conf) -anthm
2727 static int set_eventmask(struct mansession *s, const char *eventmask)
2729 int maskint = strings_to_mask(eventmask);
2731 ao2_lock(s->session);
2733 s->session->send_events = maskint;
2735 ao2_unlock(s->session);
2740 static enum ast_transport mansession_get_transport(const struct mansession *s)
2742 return s->tcptls_session->parent->tls_cfg ? AST_TRANSPORT_TLS :
2746 static void report_invalid_user(const struct mansession *s, const char *username)
2748 char session_id[32];
2749 struct ast_security_event_inval_acct_id inval_acct_id = {
2750 .common.event_type = AST_SECURITY_EVENT_INVAL_ACCT_ID,
2751 .common.version = AST_SECURITY_EVENT_INVAL_ACCT_ID_VERSION,
2752 .common.service = "AMI",
2753 .common.account_id = username,
2754 .common.session_tv = &s->session->sessionstart_tv,
2755 .common.local_addr = {
2756 .addr = &s->tcptls_session->parent->local_address,
2757 .transport = mansession_get_transport(s),
2759 .common.remote_addr = {
2760 .addr = &s->session->addr,
2761 .transport = mansession_get_transport(s),
2763 .common.session_id = session_id,
2766 snprintf(session_id, sizeof(session_id), "%p", s);
2768 ast_security_event_report(AST_SEC_EVT(&inval_acct_id));
2771 static void report_failed_acl(const struct mansession *s, const char *username)
2773 char session_id[32];
2774 struct ast_security_event_failed_acl failed_acl_event = {
2775 .common.event_type = AST_SECURITY_EVENT_FAILED_ACL,
2776 .common.version = AST_SECURITY_EVENT_FAILED_ACL_VERSION,
2777 .common.service = "AMI",
2778 .common.account_id = username,
2779 .common.session_tv = &s->session->sessionstart_tv,
2780 .common.local_addr = {
2781 .addr = &s->tcptls_session->parent->local_address,
2782 .transport = mansession_get_transport(s),
2784 .common.remote_addr = {
2785 .addr = &s->session->addr,
2786 .transport = mansession_get_transport(s),
2788 .common.session_id = session_id,
2791 snprintf(session_id, sizeof(session_id), "%p", s->session);
2793 ast_security_event_report(AST_SEC_EVT(&failed_acl_event));
2796 static void report_inval_password(const struct mansession *s, const char *username)
2798 char session_id[32];
2799 struct ast_security_event_inval_password inval_password = {
2800 .common.event_type = AST_SECURITY_EVENT_INVAL_PASSWORD,
2801 .common.version = AST_SECURITY_EVENT_INVAL_PASSWORD_VERSION,
2802 .common.service = "AMI",
2803 .common.account_id = username,
2804 .common.session_tv = &s->session->sessionstart_tv,
2805 .common.local_addr = {
2806 .addr = &s->tcptls_session->parent->local_address,
2807 .transport = mansession_get_transport(s),
2809 .common.remote_addr = {
2810 .addr = &s->session->addr,
2811 .transport = mansession_get_transport(s),
2813 .common.session_id = session_id,
2816 snprintf(session_id, sizeof(session_id), "%p", s->session);
2818 ast_security_event_report(AST_SEC_EVT(&inval_password));
2821 static void report_auth_success(const struct mansession *s)
2823 char session_id[32];
2824 struct ast_security_event_successful_auth successful_auth = {
2825 .common.event_type = AST_SECURITY_EVENT_SUCCESSFUL_AUTH,
2826 .common.version = AST_SECURITY_EVENT_SUCCESSFUL_AUTH_VERSION,
2827 .common.service = "AMI",
2828 .common.account_id = s->session->username,
2829 .common.session_tv = &s->session->sessionstart_tv,
2830 .common.local_addr = {
2831 .addr = &s->tcptls_session->parent->local_address,
2832 .transport = mansession_get_transport(s),
2834 .common.remote_addr = {
2835 .addr = &s->session->addr,
2836 .transport = mansession_get_transport(s),
2838 .common.session_id = session_id,
2841 snprintf(session_id, sizeof(session_id), "%p", s->session);
2843 ast_security_event_report(AST_SEC_EVT(&successful_auth));
2846 static void report_req_not_allowed(const struct mansession *s, const char *action)
2848 char session_id[32];
2849 char request_type[64];
2850 struct ast_security_event_req_not_allowed req_not_allowed = {
2851 .common.event_type = AST_SECURITY_EVENT_REQ_NOT_ALLOWED,
2852 .common.version = AST_SECURITY_EVENT_REQ_NOT_ALLOWED_VERSION,
2853 .common.service = "AMI",
2854 .common.account_id = s->session->username,
2855 .common.session_tv = &s->session->sessionstart_tv,
2856 .common.local_addr = {
2857 .addr = &s->tcptls_session->parent->local_address,
2858 .transport = mansession_get_transport(s),
2860 .common.remote_addr = {
2861 .addr = &s->session->addr,
2862 .transport = mansession_get_transport(s),
2864 .common.session_id = session_id,
2866 .request_type = request_type,
2869 snprintf(session_id, sizeof(session_id), "%p", s->session);
2870 snprintf(request_type, sizeof(request_type), "Action: %s", action);
2872 ast_security_event_report(AST_SEC_EVT(&req_not_allowed));
2875 static void report_req_bad_format(const struct mansession *s, const char *action)
2877 char session_id[32];
2878 char request_type[64];
2879 struct ast_security_event_req_bad_format req_bad_format = {
2880 .common.event_type = AST_SECURITY_EVENT_REQ_BAD_FORMAT,
2881 .common.version = AST_SECURITY_EVENT_REQ_BAD_FORMAT_VERSION,
2882 .common.service = "AMI",
2883 .common.account_id = s->session->username,
2884 .common.session_tv = &s->session->sessionstart_tv,
2885 .common.local_addr = {
2886 .addr = &s->tcptls_session->parent->local_address,
2887 .transport = mansession_get_transport(s),
2889 .common.remote_addr = {
2890 .addr = &s->session->addr,
2891 .transport = mansession_get_transport(s),
2893 .common.session_id = session_id,
2895 .request_type = request_type,
2898 snprintf(session_id, sizeof(session_id), "%p", s->session);
2899 snprintf(request_type, sizeof(request_type), "Action: %s", action);
2901 ast_security_event_report(AST_SEC_EVT(&req_bad_format));
2904 static void report_failed_challenge_response(const struct mansession *s,
2905 const char *response, const char *expected_response)
2907 char session_id[32];
2908 struct ast_security_event_chal_resp_failed chal_resp_failed = {
2909 .common.event_type = AST_SECURITY_EVENT_CHAL_RESP_FAILED,
2910 .common.version = AST_SECURITY_EVENT_CHAL_RESP_FAILED_VERSION,
2911 .common.service = "AMI",
2912 .common.account_id = s->session->username,
2913 .common.session_tv = &s->session->sessionstart_tv,
2914 .common.local_addr = {
2915 .addr = &s->tcptls_session->parent->local_address,
2916 .transport = mansession_get_transport(s),
2918 .common.remote_addr = {
2919 .addr = &s->session->addr,
2920 .transport = mansession_get_transport(s),
2922 .common.session_id = session_id,
2924 .challenge = s->session->challenge,
2925 .response = response,
2926 .expected_response = expected_response,
2929 snprintf(session_id, sizeof(session_id), "%p", s->session);
2931 ast_security_event_report(AST_SEC_EVT(&chal_resp_failed));
2934 static void report_session_limit(const struct mansession *s)
2936 char session_id[32];
2937 struct ast_security_event_session_limit session_limit = {
2938 .common.event_type = AST_SECURITY_EVENT_SESSION_LIMIT,
2939 .common.version = AST_SECURITY_EVENT_SESSION_LIMIT_VERSION,
2940 .common.service = "AMI",
2941 .common.account_id = s->session->username,
2942 .common.session_tv = &s->session->sessionstart_tv,
2943 .common.local_addr = {
2944 .addr = &s->tcptls_session->parent->local_address,
2945 .transport = mansession_get_transport(s),
2947 .common.remote_addr = {
2948 .addr = &s->session->addr,
2949 .transport = mansession_get_transport(s),
2951 .common.session_id = session_id,
2954 snprintf(session_id, sizeof(session_id), "%p", s->session);
2956 ast_security_event_report(AST_SEC_EVT(&session_limit));
2960 * Here we start with action_ handlers for AMI actions,
2961 * and the internal functions used by them.
2962 * Generally, the handlers are called action_foo()
2965 /* helper function for action_login() */
2966 static int authenticate(struct mansession *s, const struct message *m)
2968 const char *username = astman_get_header(m, "Username");
2969 const char *password = astman_get_header(m, "Secret");
2971 struct ast_manager_user *user = NULL;
2972 regex_t *regex_filter;
2973 struct ao2_iterator filter_iter;
2975 if (ast_strlen_zero(username)) { /* missing username */
2979 /* locate user in locked state */
2980 AST_RWLIST_WRLOCK(&users);
2982 if (!(user = get_manager_by_name_locked(username))) {
2983 report_invalid_user(s, username);
2984 ast_log(LOG_NOTICE, "%s tried to authenticate with nonexistent user '%s'\n", ast_sockaddr_stringify_addr(&s->session->addr), username);
2985 } else if (user->acl && (ast_apply_acl(user->acl, &s->session->addr, "Manager User ACL: ") == AST_SENSE_DENY)) {
2986 report_failed_acl(s, username);
2987 ast_log(LOG_NOTICE, "%s failed to pass IP ACL as '%s'\n", ast_sockaddr_stringify_addr(&s->session->addr), username);
2988 } else if (!strcasecmp(astman_get_header(m, "AuthType"), "MD5")) {
2989 const char *key = astman_get_header(m, "Key");
2990 if (!ast_strlen_zero(key) && !ast_strlen_zero(s->session->challenge) && user->secret) {
2993 char md5key[256] = "";
2994 struct MD5Context md5;
2995 unsigned char digest[16];
2998 MD5Update(&md5, (unsigned char *) s->session->challenge, strlen(s->session->challenge));
2999 MD5Update(&md5, (unsigned char *) user->secret, strlen(user->secret));
3000 MD5Final(digest, &md5);
3001 for (x = 0; x < 16; x++)
3002 len += sprintf(md5key + len, "%2.2x", (unsigned)digest[x]);
3003 if (!strcmp(md5key, key)) {
3006 report_failed_challenge_response(s, key, md5key);
3009 ast_debug(1, "MD5 authentication is