7accaa15f7f88aa4f60d3114f576fccd0a6c307e
[asterisk/asterisk.git] / main / manager.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2006, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
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.
13  *
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.
17  */
18
19 /*! \file
20  *
21  * \brief The Asterisk Management Interface - AMI
22  *
23  * \author Mark Spencer <markster@digium.com>
24  *
25  * OpenSSL http://www.openssl.org - for AMI/SSL
26  *
27  * At the moment this file contains a number of functions, namely:
28  *
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
35  *
36  * \ref amiconf
37  */
38
39 /*! \li \ref manager.c uses the configuration file \ref manager.conf and \ref users.conf
40  * \addtogroup configuration_file
41  */
42
43 /*! \page manager.conf manager.conf
44  * \verbinclude manager.conf.sample
45  */
46
47 /*! \page users.conf users.conf
48  * \verbinclude users.conf.sample
49  */
50
51 /*** MODULEINFO
52         <support_level>core</support_level>
53  ***/
54
55 #include "asterisk.h"
56
57 #include "asterisk/paths.h"     /* use various ast_config_AST_* */
58 #include <ctype.h>
59 #include <sys/time.h>
60 #include <signal.h>
61 #include <sys/mman.h>
62 #include <sys/types.h>
63 #include <regex.h>
64
65 #include "asterisk/channel.h"
66 #include "asterisk/file.h"
67 #include "asterisk/manager.h"
68 #include "asterisk/module.h"
69 #include "asterisk/config.h"
70 #include "asterisk/callerid.h"
71 #include "asterisk/lock.h"
72 #include "asterisk/cli.h"
73 #include "asterisk/app.h"
74 #include "asterisk/pbx.h"
75 #include "asterisk/md5.h"
76 #include "asterisk/acl.h"
77 #include "asterisk/utils.h"
78 #include "asterisk/tcptls.h"
79 #include "asterisk/http.h"
80 #include "asterisk/ast_version.h"
81 #include "asterisk/threadstorage.h"
82 #include "asterisk/linkedlists.h"
83 #include "asterisk/term.h"
84 #include "asterisk/astobj2.h"
85 #include "asterisk/features.h"
86 #include "asterisk/security_events.h"
87 #include "asterisk/aoc.h"
88 #include "asterisk/strings.h"
89 #include "asterisk/stringfields.h"
90 #include "asterisk/presencestate.h"
91 #include "asterisk/stasis_message_router.h"
92 #include "asterisk/stasis_channels.h"
93 #include "asterisk/stasis_bridges.h"
94 #include "asterisk/test.h"
95 #include "asterisk/json.h"
96 #include "asterisk/bridge.h"
97 #include "asterisk/features_config.h"
98 #include "asterisk/rtp_engine.h"
99 #include "asterisk/format_cache.h"
100 #include "asterisk/translate.h"
101 #include "asterisk/taskprocessor.h"
102
103 /*** DOCUMENTATION
104         <manager name="Ping" language="en_US">
105                 <synopsis>
106                         Keepalive command.
107                 </synopsis>
108                 <syntax>
109                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
110                 </syntax>
111                 <description>
112                         <para>A 'Ping' action will ellicit a 'Pong' response. Used to keep the
113                         manager connection open.</para>
114                 </description>
115         </manager>
116         <manager name="Events" language="en_US">
117                 <synopsis>
118                         Control Event Flow.
119                 </synopsis>
120                 <syntax>
121                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
122                         <parameter name="EventMask" required="true">
123                                 <enumlist>
124                                         <enum name="on">
125                                                 <para>If all events should be sent.</para>
126                                         </enum>
127                                         <enum name="off">
128                                                 <para>If no events should be sent.</para>
129                                         </enum>
130                                         <enum name="system,call,log,...">
131                                                 <para>To select which flags events should have to be sent.</para>
132                                         </enum>
133                                 </enumlist>
134                         </parameter>
135                 </syntax>
136                 <description>
137                         <para>Enable/Disable sending of events to this manager client.</para>
138                 </description>
139         </manager>
140         <manager name="Logoff" language="en_US">
141                 <synopsis>
142                         Logoff Manager.
143                 </synopsis>
144                 <syntax>
145                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
146                 </syntax>
147                 <description>
148                         <para>Logoff the current manager session.</para>
149                 </description>
150                 <see-also>
151                         <ref type="manager">Login</ref>
152                 </see-also>
153         </manager>
154         <manager name="Login" language="en_US">
155                 <synopsis>
156                         Login Manager.
157                 </synopsis>
158                 <syntax>
159                         <parameter name="ActionID">
160                                 <para>ActionID for this transaction. Will be returned.</para>
161                         </parameter>
162                         <parameter name="Username" required="true">
163                                 <para>Username to login with as specified in manager.conf.</para>
164                         </parameter>
165                         <parameter name="Secret">
166                                 <para>Secret to login with as specified in manager.conf.</para>
167                         </parameter>
168                 </syntax>
169                 <description>
170                         <para>Login Manager.</para>
171                 </description>
172                 <see-also>
173                         <ref type="manager">Logoff</ref>
174                 </see-also>
175         </manager>
176         <manager name="Challenge" language="en_US">
177                 <synopsis>
178                         Generate Challenge for MD5 Auth.
179                 </synopsis>
180                 <syntax>
181                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
182                         <parameter name="AuthType" required="true">
183                                 <para>Digest algorithm to use in the challenge. Valid values are:</para>
184                                 <enumlist>
185                                         <enum name="MD5" />
186                                 </enumlist>
187                         </parameter>
188                 </syntax>
189                 <description>
190                         <para>Generate a challenge for MD5 authentication.</para>
191                 </description>
192         </manager>
193         <manager name="Hangup" language="en_US">
194                 <synopsis>
195                         Hangup channel.
196                 </synopsis>
197                 <syntax>
198                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
199                         <parameter name="Channel" required="true">
200                                 <para>The exact channel name to be hungup, or to use a regular expression, set this parameter to: /regex/</para>
201                                 <para>Example exact channel: SIP/provider-0000012a</para>
202                                 <para>Example regular expression: /^SIP/provider-.*$/</para>
203                         </parameter>
204                         <parameter name="Cause">
205                                 <para>Numeric hangup cause.</para>
206                         </parameter>
207                 </syntax>
208                 <description>
209                         <para>Hangup a channel.</para>
210                 </description>
211         </manager>
212         <manager name="Status" language="en_US">
213                 <synopsis>
214                         List channel status.
215                 </synopsis>
216                 <syntax>
217                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
218                         <parameter name="Channel" required="false">
219                                 <para>The name of the channel to query for status.</para>
220                         </parameter>
221                         <parameter name="Variables">
222                                 <para>Comma <literal>,</literal> separated list of variable to include.</para>
223                         </parameter>
224                         <parameter name="AllVariables">
225                                 <para>If set to "true", the Status event will include all channel variables for
226                                 the requested channel(s).</para>
227                                 <enumlist>
228                                         <enum name="true"/>
229                                         <enum name="false"/>
230                                 </enumlist>
231                         </parameter>
232                 </syntax>
233                 <description>
234                         <para>Will return the status information of each channel along with the
235                         value for the specified channel variables.</para>
236                 </description>
237                 <responses>
238                         <list-elements>
239                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='Status'])" />
240                         </list-elements>
241                         <xi:include xpointer="xpointer(/docs/managerEvent[@name='StatusComplete'])" />
242                 </responses>
243         </manager>
244         <managerEvent language="en_US" name="Status">
245                 <managerEventInstance class="EVENT_FLAG_CALL">
246                         <synopsis>Raised in response to a Status command.</synopsis>
247                         <syntax>
248                                 <parameter name="ActionID" required="false"/>
249                                 <channel_snapshot/>
250                                 <parameter name="Type">
251                                         <para>Type of channel</para>
252                                 </parameter>
253                                 <parameter name="DNID">
254                                         <para>Dialed number identifier</para>
255                                 </parameter>
256                                 <parameter name="EffectiveConnectedLineNum">
257                                 </parameter>
258                                 <parameter name="EffectiveConnectedLineName">
259                                 </parameter>
260                                 <parameter name="TimeToHangup">
261                                         <para>Absolute lifetime of the channel</para>
262                                 </parameter>
263                                 <parameter name="BridgeID">
264                                         <para>Identifier of the bridge the channel is in, may be empty if not in one</para>
265                                 </parameter>
266                                 <parameter name="Application">
267                                         <para>Application currently executing on the channel</para>
268                                 </parameter>
269                                 <parameter name="Data">
270                                         <para>Data given to the currently executing channel</para>
271                                 </parameter>
272                                 <parameter name="Nativeformats">
273                                         <para>Media formats the connected party is willing to send or receive</para>
274                                 </parameter>
275                                 <parameter name="Readformat">
276                                         <para>Media formats that frames from the channel are received in</para>
277                                 </parameter>
278                                 <parameter name="Readtrans">
279                                         <para>Translation path for media received in native formats</para>
280                                 </parameter>
281                                 <parameter name="Writeformat">
282                                         <para>Media formats that frames to the channel are accepted in</para>
283                                 </parameter>
284                                 <parameter name="Writetrans">
285                                         <para>Translation path for media sent to the connected party</para>
286                                 </parameter>
287                                 <parameter name="Callgroup">
288                                         <para>Configured call group on the channel</para>
289                                 </parameter>
290                                 <parameter name="Pickupgroup">
291                                         <para>Configured pickup group on the channel</para>
292                                 </parameter>
293                                 <parameter name="Seconds">
294                                         <para>Number of seconds the channel has been active</para>
295                                 </parameter>
296                         </syntax>
297                         <see-also>
298                                 <ref type="manager">Status</ref>
299                         </see-also>
300                 </managerEventInstance>
301         </managerEvent>
302         <managerEvent language="en_US" name="StatusComplete">
303                 <managerEventInstance class="EVENT_FLAG_CALL">
304                         <synopsis>Raised in response to a Status command.</synopsis>
305                         <syntax>
306                                 <parameter name="Items">
307                                         <para>Number of Status events returned</para>
308                                 </parameter>
309                         </syntax>
310                         <see-also>
311                                 <ref type="manager">Status</ref>
312                         </see-also>
313                 </managerEventInstance>
314         </managerEvent>
315         <manager name="Setvar" language="en_US">
316                 <synopsis>
317                         Sets a channel variable or function value.
318                 </synopsis>
319                 <syntax>
320                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
321                         <parameter name="Channel">
322                                 <para>Channel to set variable for.</para>
323                         </parameter>
324                         <parameter name="Variable" required="true">
325                                 <para>Variable name, function or expression.</para>
326                         </parameter>
327                         <parameter name="Value" required="true">
328                                 <para>Variable or function value.</para>
329                         </parameter>
330                 </syntax>
331                 <description>
332                         <para>This command can be used to set the value of channel variables or dialplan
333                         functions.</para>
334                         <note>
335                                 <para>If a channel name is not provided then the variable is considered global.</para>
336                         </note>
337                 </description>
338                 <see-also>
339                         <ref type="manager">Getvar</ref>
340                 </see-also>
341         </manager>
342         <manager name="Getvar" language="en_US">
343                 <synopsis>
344                         Gets a channel variable or function value.
345                 </synopsis>
346                 <syntax>
347                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
348                         <parameter name="Channel">
349                                 <para>Channel to read variable from.</para>
350                         </parameter>
351                         <parameter name="Variable" required="true">
352                                 <para>Variable name, function or expression.</para>
353                         </parameter>
354                 </syntax>
355                 <description>
356                         <para>Get the value of a channel variable or function return.</para>
357                         <note>
358                                 <para>If a channel name is not provided then the variable is considered global.</para>
359                         </note>
360                 </description>
361                 <see-also>
362                         <ref type="manager">Setvar</ref>
363                 </see-also>
364         </manager>
365         <manager name="GetConfig" language="en_US">
366                 <synopsis>
367                         Retrieve configuration.
368                 </synopsis>
369                 <syntax>
370                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
371                         <parameter name="Filename" required="true">
372                                 <para>Configuration filename (e.g. <filename>foo.conf</filename>).</para>
373                         </parameter>
374                         <parameter name="Category">
375                                 <para>Category in configuration file.</para>
376                         </parameter>
377                         <parameter name="Filter">
378                                 <para>A comma separated list of
379                                 <replaceable>name_regex</replaceable>=<replaceable>value_regex</replaceable>
380                                 expressions which will cause only categories whose variables match all expressions
381                                 to be considered.  The special variable name <literal>TEMPLATES</literal>
382                                 can be used to control whether templates are included.  Passing
383                                 <literal>include</literal> as the value will include templates
384                                 along with normal categories. Passing
385                                 <literal>restrict</literal> as the value will restrict the operation to
386                                 ONLY templates.  Not specifying a <literal>TEMPLATES</literal> expression
387                                 results in the default behavior which is to not include templates.</para>
388                         </parameter>
389                 </syntax>
390                 <description>
391                         <para>This action will dump the contents of a configuration
392                         file by category and contents or optionally by specified category only.
393                         In the case where a category name is non-unique, a filter may be specified
394                         to match only categories with matching variable values.</para>
395                 </description>
396                 <see-also>
397                         <ref type="manager">GetConfigJSON</ref>
398                         <ref type="manager">UpdateConfig</ref>
399                         <ref type="manager">CreateConfig</ref>
400                         <ref type="manager">ListCategories</ref>
401                 </see-also>
402         </manager>
403         <manager name="GetConfigJSON" language="en_US">
404                 <synopsis>
405                         Retrieve configuration (JSON format).
406                 </synopsis>
407                 <syntax>
408                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
409                         <parameter name="Filename" required="true">
410                                 <para>Configuration filename (e.g. <filename>foo.conf</filename>).</para>
411                         </parameter>
412                         <parameter name="Category">
413                                 <para>Category in configuration file.</para>
414                         </parameter>
415                         <parameter name="Filter">
416                                 <xi:include xpointer="xpointer(/docs/manager[@name='GetConfig']/syntax/parameter[@name='Filter']/para[1])" />
417                         </parameter>
418                 </syntax>
419                 <description>
420                         <para>This action will dump the contents of a configuration file by category
421                         and contents in JSON format or optionally by specified category only.
422                         This only makes sense to be used using rawman over the HTTP interface.
423                         In the case where a category name is non-unique, a filter may be specified
424                         to match only categories with matching variable values.</para>
425                 </description>
426                 <see-also>
427                         <ref type="manager">GetConfig</ref>
428                         <ref type="manager">UpdateConfig</ref>
429                         <ref type="manager">CreateConfig</ref>
430                         <ref type="manager">ListCategories</ref>
431                 </see-also>
432         </manager>
433         <manager name="UpdateConfig" language="en_US">
434                 <synopsis>
435                         Update basic configuration.
436                 </synopsis>
437                 <syntax>
438                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
439                         <parameter name="SrcFilename" required="true">
440                                 <para>Configuration filename to read (e.g. <filename>foo.conf</filename>).</para>
441                         </parameter>
442                         <parameter name="DstFilename" required="true">
443                                 <para>Configuration filename to write (e.g. <filename>foo.conf</filename>)</para>
444                         </parameter>
445                         <parameter name="Reload">
446                                 <para>Whether or not a reload should take place (or name of specific module).</para>
447                         </parameter>
448                         <parameter name="PreserveEffectiveContext">
449                                 <para>Whether the effective category contents should be preserved on template change. Default is true (pre 13.2 behavior).</para>
450                         </parameter>
451                         <parameter name="Action-000000">
452                                 <para>Action to take.</para>
453                                 <para>0's represent 6 digit number beginning with 000000.</para>
454                                 <enumlist>
455                                         <enum name="NewCat" />
456                                         <enum name="RenameCat" />
457                                         <enum name="DelCat" />
458                                         <enum name="EmptyCat" />
459                                         <enum name="Update" />
460                                         <enum name="Delete" />
461                                         <enum name="Append" />
462                                         <enum name="Insert" />
463                                 </enumlist>
464                         </parameter>
465                         <parameter name="Cat-000000">
466                                 <para>Category to operate on.</para>
467                                 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-000000']/para[2])" />
468                         </parameter>
469                         <parameter name="Var-000000">
470                                 <para>Variable to work on.</para>
471                                 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-000000']/para[2])" />
472                         </parameter>
473                         <parameter name="Value-000000">
474                                 <para>Value to work on.</para>
475                                 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-000000']/para[2])" />
476                         </parameter>
477                         <parameter name="Match-000000">
478                                 <para>Extra match required to match line.</para>
479                                 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-000000']/para[2])" />
480                         </parameter>
481                         <parameter name="Line-000000">
482                                 <para>Line in category to operate on (used with delete and insert actions).</para>
483                                 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-000000']/para[2])" />
484                         </parameter>
485                         <parameter name="Options-000000">
486                                 <para>A comma separated list of action-specific options.</para>
487                                         <enumlist>
488                                                 <enum name="NewCat"><para>One or more of the following... </para>
489                                                         <enumlist>
490                                                                 <enum name="allowdups"><para>Allow duplicate category names.</para></enum>
491                                                                 <enum name="template"><para>This category is a template.</para></enum>
492                                                                 <enum name="inherit=&quot;template[,...]&quot;"><para>Templates from which to inherit.</para></enum>
493                                                         </enumlist>
494                                                 </enum>
495                                         </enumlist>
496                                         <para> </para>
497                                                 <para>The following actions share the same options...</para>
498                                         <enumlist>
499                                                 <enum name="RenameCat"/>
500                                                 <enum name="DelCat"/>
501                                                 <enum name="EmptyCat"/>
502                                                 <enum name="Update"/>
503                                                 <enum name="Delete"/>
504                                                 <enum name="Append"/>
505                                                 <enum name="Insert"><para> </para>
506                                                         <enumlist>
507                                                                 <enum name="catfilter=&quot;&lt;expression&gt;[,...]&quot;"><para> </para>
508                                                                         <xi:include xpointer="xpointer(/docs/manager[@name='GetConfig']/syntax/parameter[@name='Filter']/para[1])" />
509                                                                         <para><literal>catfilter</literal> is most useful when a file
510                                                                         contains multiple categories with the same name and you wish to
511                                                                         operate on specific ones instead of all of them.</para>
512                                                                 </enum>
513                                                         </enumlist>
514                                                 </enum>
515                                         </enumlist>
516                                 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-000000']/para[2])" />
517                         </parameter>
518                 </syntax>
519                 <description>
520                         <para>This action will modify, create, or delete configuration elements
521                         in Asterisk configuration files.</para>
522                 </description>
523                 <see-also>
524                         <ref type="manager">GetConfig</ref>
525                         <ref type="manager">GetConfigJSON</ref>
526                         <ref type="manager">CreateConfig</ref>
527                         <ref type="manager">ListCategories</ref>
528                 </see-also>
529         </manager>
530         <manager name="CreateConfig" language="en_US">
531                 <synopsis>
532                         Creates an empty file in the configuration directory.
533                 </synopsis>
534                 <syntax>
535                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
536                         <parameter name="Filename" required="true">
537                                 <para>The configuration filename to create (e.g. <filename>foo.conf</filename>).</para>
538                         </parameter>
539                 </syntax>
540                 <description>
541                         <para>This action will create an empty file in the configuration
542                         directory. This action is intended to be used before an UpdateConfig
543                         action.</para>
544                 </description>
545                 <see-also>
546                         <ref type="manager">GetConfig</ref>
547                         <ref type="manager">GetConfigJSON</ref>
548                         <ref type="manager">UpdateConfig</ref>
549                         <ref type="manager">ListCategories</ref>
550                 </see-also>
551         </manager>
552         <manager name="ListCategories" language="en_US">
553                 <synopsis>
554                         List categories in configuration file.
555                 </synopsis>
556                 <syntax>
557                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
558                         <parameter name="Filename" required="true">
559                                 <para>Configuration filename (e.g. <filename>foo.conf</filename>).</para>
560                         </parameter>
561                 </syntax>
562                 <description>
563                         <para>This action will dump the categories in a given file.</para>
564                 </description>
565                 <see-also>
566                         <ref type="manager">GetConfig</ref>
567                         <ref type="manager">GetConfigJSON</ref>
568                         <ref type="manager">UpdateConfig</ref>
569                         <ref type="manager">CreateConfig</ref>
570                 </see-also>
571         </manager>
572         <manager name="Redirect" language="en_US">
573                 <synopsis>
574                         Redirect (transfer) a call.
575                 </synopsis>
576                 <syntax>
577                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
578                         <parameter name="Channel" required="true">
579                                 <para>Channel to redirect.</para>
580                         </parameter>
581                         <parameter name="ExtraChannel">
582                                 <para>Second call leg to transfer (optional).</para>
583                         </parameter>
584                         <parameter name="Exten" required="true">
585                                 <para>Extension to transfer to.</para>
586                         </parameter>
587                         <parameter name="ExtraExten">
588                                 <para>Extension to transfer extrachannel to (optional).</para>
589                         </parameter>
590                         <parameter name="Context" required="true">
591                                 <para>Context to transfer to.</para>
592                         </parameter>
593                         <parameter name="ExtraContext">
594                                 <para>Context to transfer extrachannel to (optional).</para>
595                         </parameter>
596                         <parameter name="Priority" required="true">
597                                 <para>Priority to transfer to.</para>
598                         </parameter>
599                         <parameter name="ExtraPriority">
600                                 <para>Priority to transfer extrachannel to (optional).</para>
601                         </parameter>
602                 </syntax>
603                 <description>
604                         <para>Redirect (transfer) a call.</para>
605                 </description>
606                 <see-also>
607                         <ref type="manager">BlindTransfer</ref>
608                 </see-also>
609         </manager>
610         <manager name="Atxfer" language="en_US">
611                 <synopsis>
612                         Attended transfer.
613                 </synopsis>
614                 <syntax>
615                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
616                         <parameter name="Channel" required="true">
617                                 <para>Transferer's channel.</para>
618                         </parameter>
619                         <parameter name="Exten" required="true">
620                                 <para>Extension to transfer to.</para>
621                         </parameter>
622                         <parameter name="Context">
623                                 <para>Context to transfer to.</para>
624                         </parameter>
625                 </syntax>
626                 <description>
627                         <para>Attended transfer.</para>
628                 </description>
629                 <see-also>
630                         <ref type="managerEvent">AttendedTransfer</ref>
631                 </see-also>
632         </manager>
633         <manager name="CancelAtxfer" language="en_US">
634                 <synopsis>
635                         Cancel an attended transfer.
636                 </synopsis>
637                 <syntax>
638                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
639                         <parameter name="Channel" required="true">
640                                 <para>The transferer channel.</para>
641                         </parameter>
642                 </syntax>
643                 <description>
644                         <para>Cancel an attended transfer. Note, this uses the configured cancel attended transfer
645                         feature option (atxferabort) to cancel the transfer. If not available this action will fail.
646                         </para>
647                 </description>
648                 <see-also>
649                         <ref type="managerEvent">AttendedTransfer</ref>
650                 </see-also>
651         </manager>
652         <manager name="Originate" language="en_US">
653                 <synopsis>
654                         Originate a call.
655                 </synopsis>
656                 <syntax>
657                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
658                         <parameter name="Channel" required="true">
659                                 <para>Channel name to call.</para>
660                         </parameter>
661                         <parameter name="Exten">
662                                 <para>Extension to use (requires <literal>Context</literal> and
663                                 <literal>Priority</literal>)</para>
664                         </parameter>
665                         <parameter name="Context">
666                                 <para>Context to use (requires <literal>Exten</literal> and
667                                 <literal>Priority</literal>)</para>
668                         </parameter>
669                         <parameter name="Priority">
670                                 <para>Priority to use (requires <literal>Exten</literal> and
671                                 <literal>Context</literal>)</para>
672                         </parameter>
673                         <parameter name="Application">
674                                 <para>Application to execute.</para>
675                         </parameter>
676                         <parameter name="Data">
677                                 <para>Data to use (requires <literal>Application</literal>).</para>
678                         </parameter>
679                         <parameter name="Timeout" default="30000">
680                                 <para>How long to wait for call to be answered (in ms.).</para>
681                         </parameter>
682                         <parameter name="CallerID">
683                                 <para>Caller ID to be set on the outgoing channel.</para>
684                         </parameter>
685                         <parameter name="Variable">
686                                 <para>Channel variable to set, multiple Variable: headers are allowed.</para>
687                         </parameter>
688                         <parameter name="Account">
689                                 <para>Account code.</para>
690                         </parameter>
691                         <parameter name="EarlyMedia">
692                                 <para>Set to <literal>true</literal> to force call bridge on early media..</para>
693                         </parameter>
694                         <parameter name="Async">
695                                 <para>Set to <literal>true</literal> for fast origination.</para>
696                         </parameter>
697                         <parameter name="Codecs">
698                                 <para>Comma-separated list of codecs to use for this call.</para>
699                         </parameter>
700                         <parameter name="ChannelId">
701                                 <para>Channel UniqueId to be set on the channel.</para>
702                         </parameter>
703                         <parameter name="OtherChannelId">
704                                 <para>Channel UniqueId to be set on the second local channel.</para>
705                         </parameter>
706                 </syntax>
707                 <description>
708                         <para>Generates an outgoing call to a
709                         <replaceable>Extension</replaceable>/<replaceable>Context</replaceable>/<replaceable>Priority</replaceable>
710                         or <replaceable>Application</replaceable>/<replaceable>Data</replaceable></para>
711                 </description>
712                 <see-also>
713                         <ref type="managerEvent">OriginateResponse</ref>
714                 </see-also>
715         </manager>
716         <managerEvent language="en_US" name="OriginateResponse">
717                 <managerEventInstance class="EVENT_FLAG_CALL">
718                         <synopsis>Raised in response to an Originate command.</synopsis>
719                         <syntax>
720                                 <parameter name="ActionID" required="false"/>
721                                 <parameter name="Response">
722                                         <enumlist>
723                                                 <enum name="Failure"/>
724                                                 <enum name="Success"/>
725                                         </enumlist>
726                                 </parameter>
727                                 <parameter name="Channel"/>
728                                 <parameter name="Context"/>
729                                 <parameter name="Exten"/>
730                                 <parameter name="Application"/>
731                                 <parameter name="Data"/>
732                                 <parameter name="Reason"/>
733                                 <parameter name="Uniqueid"/>
734                                 <parameter name="CallerIDNum"/>
735                                 <parameter name="CallerIDName"/>
736                         </syntax>
737                         <see-also>
738                                 <ref type="manager">Originate</ref>
739                         </see-also>
740                 </managerEventInstance>
741         </managerEvent>
742         <manager name="Command" language="en_US">
743                 <synopsis>
744                         Execute Asterisk CLI Command.
745                 </synopsis>
746                 <syntax>
747                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
748                         <parameter name="Command" required="true">
749                                 <para>Asterisk CLI command to run.</para>
750                         </parameter>
751                 </syntax>
752                 <description>
753                         <para>Run a CLI command.</para>
754                 </description>
755         </manager>
756         <manager name="ExtensionState" language="en_US">
757                 <synopsis>
758                         Check Extension Status.
759                 </synopsis>
760                 <syntax>
761                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
762                         <parameter name="Exten" required="true">
763                                 <para>Extension to check state on.</para>
764                         </parameter>
765                         <parameter name="Context" required="true">
766                                 <para>Context for extension.</para>
767                         </parameter>
768                 </syntax>
769                 <description>
770                         <para>Report the extension state for given extension. If the extension has a hint,
771                         will use devicestate to check the status of the device connected to the extension.</para>
772                         <para>Will return an <literal>Extension Status</literal> message. The response will include
773                         the hint for the extension and the status.</para>
774                 </description>
775                 <see-also>
776                         <ref type="managerEvent">ExtensionStatus</ref>
777                 </see-also>
778         </manager>
779         <manager name="PresenceState" language="en_US">
780                 <synopsis>
781                         Check Presence State
782                 </synopsis>
783                 <syntax>
784                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
785                         <parameter name="Provider" required="true">
786                                 <para>Presence Provider to check the state of</para>
787                         </parameter>
788                 </syntax>
789                 <description>
790                         <para>Report the presence state for the given presence provider.</para>
791                         <para>Will return a <literal>Presence State</literal> message. The response will include the
792                         presence state and, if set, a presence subtype and custom message.</para>
793                 </description>
794                 <see-also>
795                         <ref type="managerEvent">PresenceStatus</ref>
796                 </see-also>
797         </manager>
798         <manager name="AbsoluteTimeout" language="en_US">
799                 <synopsis>
800                         Set absolute timeout.
801                 </synopsis>
802                 <syntax>
803                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
804                         <parameter name="Channel" required="true">
805                                 <para>Channel name to hangup.</para>
806                         </parameter>
807                         <parameter name="Timeout" required="true">
808                                 <para>Maximum duration of the call (sec).</para>
809                         </parameter>
810                 </syntax>
811                 <description>
812                         <para>Hangup a channel after a certain time. Acknowledges set time with
813                         <literal>Timeout Set</literal> message.</para>
814                 </description>
815         </manager>
816         <manager name="MailboxStatus" language="en_US">
817                 <synopsis>
818                         Check mailbox.
819                 </synopsis>
820                 <syntax>
821                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
822                         <parameter name="Mailbox" required="true">
823                                 <para>Full mailbox ID <replaceable>mailbox</replaceable>@<replaceable>vm-context</replaceable>.</para>
824                         </parameter>
825                 </syntax>
826                 <description>
827                         <para>Checks a voicemail account for status.</para>
828                         <para>Returns whether there are messages waiting.</para>
829                         <para>Message: Mailbox Status.</para>
830                         <para>Mailbox: <replaceable>mailboxid</replaceable>.</para>
831                         <para>Waiting: <literal>0</literal> if messages waiting, <literal>1</literal>
832                         if no messages waiting.</para>
833                 </description>
834                 <see-also>
835                         <ref type="manager">MailboxCount</ref>
836                 </see-also>
837         </manager>
838         <manager name="MailboxCount" language="en_US">
839                 <synopsis>
840                         Check Mailbox Message Count.
841                 </synopsis>
842                 <syntax>
843                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
844                         <parameter name="Mailbox" required="true">
845                                 <para>Full mailbox ID <replaceable>mailbox</replaceable>@<replaceable>vm-context</replaceable>.</para>
846                         </parameter>
847                 </syntax>
848                 <description>
849                         <para>Checks a voicemail account for new messages.</para>
850                         <para>Returns number of urgent, new and old messages.</para>
851                         <para>Message: Mailbox Message Count</para>
852                         <para>Mailbox: <replaceable>mailboxid</replaceable></para>
853                         <para>UrgentMessages: <replaceable>count</replaceable></para>
854                         <para>NewMessages: <replaceable>count</replaceable></para>
855                         <para>OldMessages: <replaceable>count</replaceable></para>
856                 </description>
857                 <see-also>
858                         <ref type="manager">MailboxStatus</ref>
859                 </see-also>
860         </manager>
861         <manager name="ListCommands" language="en_US">
862                 <synopsis>
863                         List available manager commands.
864                 </synopsis>
865                 <syntax>
866                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
867                 </syntax>
868                 <description>
869                         <para>Returns the action name and synopsis for every action that
870                         is available to the user.</para>
871                 </description>
872         </manager>
873         <manager name="SendText" language="en_US">
874                 <synopsis>
875                         Send text message to channel.
876                 </synopsis>
877                 <syntax>
878                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
879                         <parameter name="Channel" required="true">
880                                 <para>Channel to send message to.</para>
881                         </parameter>
882                         <parameter name="Message" required="true">
883                                 <para>Message to send.</para>
884                         </parameter>
885                 </syntax>
886                 <description>
887                         <para>Sends A Text Message to a channel while in a call.</para>
888                 </description>
889         </manager>
890         <manager name="UserEvent" language="en_US">
891                 <synopsis>
892                         Send an arbitrary event.
893                 </synopsis>
894                 <syntax>
895                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
896                         <parameter name="UserEvent" required="true">
897                                 <para>Event string to send.</para>
898                         </parameter>
899                         <parameter name="Header1">
900                                 <para>Content1.</para>
901                         </parameter>
902                         <parameter name="HeaderN">
903                                 <para>ContentN.</para>
904                         </parameter>
905                 </syntax>
906                 <description>
907                         <para>Send an event to manager sessions.</para>
908                 </description>
909                 <see-also>
910                         <ref type="managerEvent">UserEvent</ref>
911                         <ref type="application">UserEvent</ref>
912                 </see-also>
913         </manager>
914         <manager name="WaitEvent" language="en_US">
915                 <synopsis>
916                         Wait for an event to occur.
917                 </synopsis>
918                 <syntax>
919                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
920                         <parameter name="Timeout" required="true">
921                                 <para>Maximum time (in seconds) to wait for events, <literal>-1</literal> means forever.</para>
922                         </parameter>
923                 </syntax>
924                 <description>
925                         <para>This action will ellicit a <literal>Success</literal> response. Whenever
926                         a manager event is queued. Once WaitEvent has been called on an HTTP manager
927                         session, events will be generated and queued.</para>
928                 </description>
929         </manager>
930         <manager name="CoreSettings" language="en_US">
931                 <synopsis>
932                         Show PBX core settings (version etc).
933                 </synopsis>
934                 <syntax>
935                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
936                 </syntax>
937                 <description>
938                         <para>Query for Core PBX settings.</para>
939                 </description>
940         </manager>
941         <manager name="CoreStatus" language="en_US">
942                 <synopsis>
943                         Show PBX core status variables.
944                 </synopsis>
945                 <syntax>
946                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
947                 </syntax>
948                 <description>
949                         <para>Query for Core PBX status.</para>
950                 </description>
951         </manager>
952         <manager name="Reload" language="en_US">
953                 <synopsis>
954                         Send a reload event.
955                 </synopsis>
956                 <syntax>
957                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
958                         <parameter name="Module">
959                                 <para>Name of the module to reload.</para>
960                         </parameter>
961                 </syntax>
962                 <description>
963                         <para>Send a reload event.</para>
964                 </description>
965                 <see-also>
966                         <ref type="manager">ModuleLoad</ref>
967                 </see-also>
968         </manager>
969         <managerEvent language="en_US" name="CoreShowChannel">
970                 <managerEventInstance class="EVENT_FLAG_CALL">
971                         <synopsis>Raised in response to a CoreShowChannels command.</synopsis>
972                         <syntax>
973                                 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
974                                 <channel_snapshot/>
975                                 <parameter name="BridgeId">
976                                         <para>Identifier of the bridge the channel is in, may be empty if not in one</para>
977                                 </parameter>
978                                 <parameter name="Application">
979                                         <para>Application currently executing on the channel</para>
980                                 </parameter>
981                                 <parameter name="ApplicationData">
982                                         <para>Data given to the currently executing application</para>
983                                 </parameter>
984                                 <parameter name="Duration">
985                                         <para>The amount of time the channel has existed</para>
986                                 </parameter>
987                         </syntax>
988                         <see-also>
989                                 <ref type="manager">CoreShowChannels</ref>
990                                 <ref type="managerEvent">CoreShowChannelsComplete</ref>
991                         </see-also>
992                 </managerEventInstance>
993         </managerEvent>
994         <managerEvent language="en_US" name="CoreShowChannelsComplete">
995                 <managerEventInstance class="EVENT_FLAG_CALL">
996                         <synopsis>Raised at the end of the CoreShowChannel list produced by the CoreShowChannels command.</synopsis>
997                         <syntax>
998                                 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
999                                 <parameter name="EventList">
1000                                         <para>Conveys the status of the command reponse list</para>
1001                                 </parameter>
1002                                 <parameter name="ListItems">
1003                                         <para>The total number of list items produced</para>
1004                                 </parameter>
1005                         </syntax>
1006                         <see-also>
1007                                 <ref type="manager">CoreShowChannels</ref>
1008                                 <ref type="managerEvent">CoreShowChannel</ref>
1009                         </see-also>
1010                 </managerEventInstance>
1011         </managerEvent>
1012         <manager name="CoreShowChannels" language="en_US">
1013                 <synopsis>
1014                         List currently active channels.
1015                 </synopsis>
1016                 <syntax>
1017                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
1018                 </syntax>
1019                 <description>
1020                         <para>List currently defined channels and some information about them.</para>
1021                 </description>
1022                 <responses>
1023                         <list-elements>
1024                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='CoreShowChannel'])" />
1025                         </list-elements>
1026                         <xi:include xpointer="xpointer(/docs/managerEvent[@name='CoreShowChannelsComplete'])" />
1027                 </responses>
1028         </manager>
1029         <manager name="LoggerRotate" language="en_US">
1030                 <synopsis>
1031                         Reload and rotate the Asterisk logger.
1032                 </synopsis>
1033                 <syntax>
1034                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
1035                 </syntax>
1036                 <description>
1037                         <para>Reload and rotate the logger. Analogous to the CLI command 'logger rotate'.</para>
1038                 </description>
1039         </manager>
1040         <manager name="ModuleLoad" language="en_US">
1041                 <synopsis>
1042                         Module management.
1043                 </synopsis>
1044                 <syntax>
1045                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
1046                         <parameter name="Module">
1047                                 <para>Asterisk module name (including .so extension) or subsystem identifier:</para>
1048                                 <enumlist>
1049                                         <enum name="cdr" />
1050                                         <enum name="dnsmgr" />
1051                                         <enum name="extconfig" />
1052                                         <enum name="enum" />
1053                                         <enum name="acl" />
1054                                         <enum name="manager" />
1055                                         <enum name="http" />
1056                                         <enum name="logger" />
1057                                         <enum name="features" />
1058                                         <enum name="dsp" />
1059                                         <enum name="udptl" />
1060                                         <enum name="indications" />
1061                                         <enum name="cel" />
1062                                         <enum name="plc" />
1063                                 </enumlist>
1064                         </parameter>
1065                         <parameter name="LoadType" required="true">
1066                                 <para>The operation to be done on module. Subsystem identifiers may only
1067                                 be reloaded.</para>
1068                                 <enumlist>
1069                                         <enum name="load" />
1070                                         <enum name="unload" />
1071                                         <enum name="reload" />
1072                                 </enumlist>
1073                                 <para>If no module is specified for a <literal>reload</literal> loadtype,
1074                                 all modules are reloaded.</para>
1075                         </parameter>
1076                 </syntax>
1077                 <description>
1078                         <para>Loads, unloads or reloads an Asterisk module in a running system.</para>
1079                 </description>
1080                 <see-also>
1081                         <ref type="manager">Reload</ref>
1082                         <ref type="manager">ModuleCheck</ref>
1083                 </see-also>
1084         </manager>
1085         <manager name="ModuleCheck" language="en_US">
1086                 <synopsis>
1087                         Check if module is loaded.
1088                 </synopsis>
1089                 <syntax>
1090                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
1091                         <parameter name="Module" required="true">
1092                                 <para>Asterisk module name (not including extension).</para>
1093                         </parameter>
1094                 </syntax>
1095                 <description>
1096                         <para>Checks if Asterisk module is loaded. Will return Success/Failure.
1097                         For success returns, the module revision number is included.</para>
1098                 </description>
1099                 <see-also>
1100                         <ref type="manager">ModuleLoad</ref>
1101                 </see-also>
1102         </manager>
1103         <manager name="AOCMessage" language="en_US">
1104                 <synopsis>
1105                         Generate an Advice of Charge message on a channel.
1106                 </synopsis>
1107                 <syntax>
1108                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
1109                         <parameter name="Channel" required="true">
1110                                 <para>Channel name to generate the AOC message on.</para>
1111                         </parameter>
1112                         <parameter name="ChannelPrefix">
1113                                 <para>Partial channel prefix.  By using this option one can match the beginning part
1114                                 of a channel name without having to put the entire name in.  For example
1115                                 if a channel name is SIP/snom-00000001 and this value is set to SIP/snom, then
1116                                 that channel matches and the message will be sent.  Note however that only
1117                                 the first matched channel has the message sent on it. </para>
1118                         </parameter>
1119                         <parameter name="MsgType" required="true">
1120                                 <para>Defines what type of AOC message to create, AOC-D or AOC-E</para>
1121                                 <enumlist>
1122                                         <enum name="D" />
1123                                         <enum name="E" />
1124                                 </enumlist>
1125                         </parameter>
1126                         <parameter name="ChargeType" required="true">
1127                                 <para>Defines what kind of charge this message represents.</para>
1128                                 <enumlist>
1129                                         <enum name="NA" />
1130                                         <enum name="FREE" />
1131                                         <enum name="Currency" />
1132                                         <enum name="Unit" />
1133                                 </enumlist>
1134                         </parameter>
1135                         <parameter name="UnitAmount(0)">
1136                                 <para>This represents the amount of units charged. The ETSI AOC standard specifies that
1137                                 this value along with the optional UnitType value are entries in a list.  To accommodate this
1138                                 these values take an index value starting at 0 which can be used to generate this list of
1139                                 unit entries.  For Example, If two unit entires were required this could be achieved by setting the
1140                                 paramter UnitAmount(0)=1234 and UnitAmount(1)=5678.  Note that UnitAmount at index 0 is
1141                                 required when ChargeType=Unit, all other entries in the list are optional.
1142                                 </para>
1143                         </parameter>
1144                         <parameter name="UnitType(0)">
1145                                 <para>Defines the type of unit.  ETSI AOC standard specifies this as an integer
1146                                 value between 1 and 16, but this value is left open to accept any positive
1147                                 integer.  Like the UnitAmount parameter, this value represents a list entry
1148                                 and has an index parameter that starts at 0.
1149                                 </para>
1150                         </parameter>
1151                         <parameter name="CurrencyName">
1152                                 <para>Specifies the currency's name.  Note that this value is truncated after 10 characters.</para>
1153                         </parameter>
1154                         <parameter name="CurrencyAmount">
1155                                 <para>Specifies the charge unit amount as a positive integer.  This value is required
1156                                 when ChargeType==Currency.</para>
1157                         </parameter>
1158                         <parameter name="CurrencyMultiplier">
1159                                 <para>Specifies the currency multiplier.  This value is required when ChargeType==Currency.</para>
1160                                 <enumlist>
1161                                         <enum name="OneThousandth" />
1162                                         <enum name="OneHundredth" />
1163                                         <enum name="OneTenth" />
1164                                         <enum name="One" />
1165                                         <enum name="Ten" />
1166                                         <enum name="Hundred" />
1167                                         <enum name="Thousand" />
1168                                 </enumlist>
1169                         </parameter>
1170                         <parameter name="TotalType" default="Total">
1171                                 <para>Defines what kind of AOC-D total is represented.</para>
1172                                 <enumlist>
1173                                         <enum name="Total" />
1174                                         <enum name="SubTotal" />
1175                                 </enumlist>
1176                         </parameter>
1177                         <parameter name="AOCBillingId">
1178                                 <para>Represents a billing ID associated with an AOC-D or AOC-E message. Note
1179                                 that only the first 3 items of the enum are valid AOC-D billing IDs</para>
1180                                 <enumlist>
1181                                         <enum name="Normal" />
1182                                         <enum name="ReverseCharge" />
1183                                         <enum name="CreditCard" />
1184                                         <enum name="CallFwdUnconditional" />
1185                                         <enum name="CallFwdBusy" />
1186                                         <enum name="CallFwdNoReply" />
1187                                         <enum name="CallDeflection" />
1188                                         <enum name="CallTransfer" />
1189                                 </enumlist>
1190                         </parameter>
1191                         <parameter name="ChargingAssociationId">
1192                                 <para>Charging association identifier.  This is optional for AOC-E and can be
1193                                 set to any value between -32768 and 32767</para>
1194                         </parameter>
1195                         <parameter name="ChargingAssociationNumber">
1196                                 <para>Represents the charging association party number.  This value is optional
1197                                 for AOC-E.</para>
1198                         </parameter>
1199                         <parameter name="ChargingAssociationPlan">
1200                                 <para>Integer representing the charging plan associated with the ChargingAssociationNumber.
1201                                 The value is bits 7 through 1 of the Q.931 octet containing the type-of-number and
1202                                 numbering-plan-identification fields.</para>
1203                         </parameter>
1204                 </syntax>
1205                 <description>
1206                         <para>Generates an AOC-D or AOC-E message on a channel.</para>
1207                 </description>
1208                 <see-also>
1209                         <ref type="managerEvent">AOC-D</ref>
1210                         <ref type="managerEvent">AOC-E</ref>
1211                 </see-also>
1212         </manager>
1213         <function name="AMI_CLIENT" language="en_US">
1214                 <synopsis>
1215                         Checks attributes of manager accounts
1216                 </synopsis>
1217                 <syntax>
1218                         <parameter name="loginname" required="true">
1219                                 <para>Login name, specified in manager.conf</para>
1220                         </parameter>
1221                         <parameter name="field" required="true">
1222                                 <para>The manager account attribute to return</para>
1223                                 <enumlist>
1224                                         <enum name="sessions"><para>The number of sessions for this AMI account</para></enum>
1225                                 </enumlist>
1226                         </parameter>
1227                 </syntax>
1228                 <description>
1229                         <para>
1230                                 Currently, the only supported  parameter is "sessions" which will return the current number of
1231                                 active sessions for this AMI account.
1232                         </para>
1233                 </description>
1234         </function>
1235         <manager name="Filter" language="en_US">
1236                 <synopsis>
1237                         Dynamically add filters for the current manager session.
1238                 </synopsis>
1239                 <syntax>
1240                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
1241                         <parameter name="Operation">
1242                                 <enumlist>
1243                                         <enum name="Add">
1244                                                 <para>Add a filter.</para>
1245                                         </enum>
1246                                 </enumlist>
1247                         </parameter>
1248                         <parameter name="Filter">
1249                                 <para>Filters can be whitelist or blacklist</para>
1250                                 <para>Example whitelist filter: "Event: Newchannel"</para>
1251                                 <para>Example blacklist filter: "!Channel: DAHDI.*"</para>
1252                                 <para>This filter option is used to whitelist or blacklist events per user to be
1253                                 reported with regular expressions and are allowed if both the regex matches
1254                                 and the user has read access as defined in manager.conf. Filters are assumed to be for whitelisting
1255                                 unless preceeded by an exclamation point, which marks it as being black.
1256                                 Evaluation of the filters is as follows:</para>
1257                                 <para>- If no filters are configured all events are reported as normal.</para>
1258                                 <para>- If there are white filters only: implied black all filter processed first, then white filters.</para>
1259                                 <para>- If there are black filters only: implied white all filter processed first, then black filters.</para>
1260                                 <para>- If there are both white and black filters: implied black all filter processed first, then white
1261                                 filters, and lastly black filters.</para>
1262                         </parameter>
1263                 </syntax>
1264                 <description>
1265                         <para>The filters added are only used for the current session.
1266                         Once the connection is closed the filters are removed.</para>
1267                         <para>This comand requires the system permission because
1268                         this command can be used to create filters that may bypass
1269                         filters defined in manager.conf</para>
1270                 </description>
1271                 <see-also>
1272                         <ref type="manager">FilterList</ref>
1273                 </see-also>
1274         </manager>
1275         <manager name="FilterList" language="en_US">
1276                 <synopsis>
1277                         Show current event filters for this session
1278                 </synopsis>
1279                 <description>
1280                         <para>The filters displayed are for the current session.  Only those filters defined in
1281                         manager.conf will be present upon starting a new session.</para>
1282                 </description>
1283                 <see-also>
1284                         <ref type="manager">Filter</ref>
1285                 </see-also>
1286         </manager>
1287         <manager name="BlindTransfer" language="en_US">
1288                 <synopsis>
1289                         Blind transfer channel(s) to the given destination
1290                 </synopsis>
1291                 <syntax>
1292                         <parameter name="Channel" required="true">
1293                         </parameter>
1294                         <parameter name="Context">
1295                         </parameter>
1296                         <parameter name="Exten">
1297                         </parameter>
1298                 </syntax>
1299                 <description>
1300                         <para>Redirect all channels currently bridged to the specified channel to the specified destination.</para>
1301                 </description>
1302                 <see-also>
1303                         <ref type="manager">Redirect</ref>
1304                         <ref type="managerEvent">BlindTransfer</ref>
1305                 </see-also>
1306         </manager>
1307         <managerEvent name="ExtensionStatus" language="en_US">
1308                 <managerEventInstance class="EVENT_FLAG_CALL">
1309                         <synopsis>Raised when a hint changes due to a device state change.</synopsis>
1310                         <syntax>
1311                                 <parameter name="Exten">
1312                                         <para>Name of the extension.</para>
1313                                 </parameter>
1314                                 <parameter name="Context">
1315                                         <para>Context that owns the extension.</para>
1316                                 </parameter>
1317                                 <parameter name="Hint">
1318                                         <para>Hint set for the extension</para>
1319                                 </parameter>
1320                                 <parameter name="Status">
1321                                         <para>Numerical value of the extension status. Extension
1322                                         status is determined by the combined device state of all items
1323                                         contained in the hint.</para>
1324                                         <enumlist>
1325                                                 <enum name="-2">
1326                                                         <para>The extension was removed from the dialplan.</para>
1327                                                 </enum>
1328                                                 <enum name="-1">
1329                                                         <para>The extension's hint was removed from the dialplan.</para>
1330                                                 </enum>
1331                                                 <enum name="0">
1332                                                         <para><literal>Idle</literal> - Related device(s) are in an idle
1333                                                         state.</para>
1334                                                 </enum>
1335                                                 <enum name="1">
1336                                                         <para><literal>InUse</literal> - Related device(s) are in active
1337                                                         calls but may take more calls.</para>
1338                                                 </enum>
1339                                                 <enum name="2">
1340                                                         <para><literal>Busy</literal> - Related device(s) are in active
1341                                                         calls and may not take any more calls.</para>
1342                                                 </enum>
1343                                                 <enum name="4">
1344                                                         <para><literal>Unavailable</literal> - Related device(s) are
1345                                                         not reachable.</para>
1346                                                 </enum>
1347                                                 <enum name="8">
1348                                                         <para><literal>Ringing</literal> - Related device(s) are
1349                                                         currently ringing.</para>
1350                                                 </enum>
1351                                                 <enum name="9">
1352                                                         <para><literal>InUse&amp;Ringing</literal> - Related device(s)
1353                                                         are currently ringing and in active calls.</para>
1354                                                 </enum>
1355                                                 <enum name="16">
1356                                                         <para><literal>Hold</literal> - Related device(s) are
1357                                                         currently on hold.</para>
1358                                                 </enum>
1359                                                 <enum name="17">
1360                                                         <para><literal>InUse&amp;Hold</literal> - Related device(s)
1361                                                         are currently on hold and in active calls.</para>
1362                                                 </enum>
1363                                         </enumlist>
1364                                 </parameter>
1365                                 <parameter name="StatusText">
1366                                         <para>Text representation of <literal>Status</literal>.</para>
1367                                         <enumlist>
1368                                                 <enum name="Idle" />
1369                                                 <enum name="InUse" />
1370                                                 <enum name="Busy" />
1371                                                 <enum name="Unavailable" />
1372                                                 <enum name="Ringing" />
1373                                                 <enum name="InUse&amp;Ringing" />
1374                                                 <enum name="Hold" />
1375                                                 <enum name="InUse&amp;Hold" />
1376                                                 <enum name="Unknown">
1377                                                         <para>Status does not match any of the above values.</para>
1378                                                 </enum>
1379                                         </enumlist>
1380                                 </parameter>
1381                         </syntax>
1382                         <see-also>
1383                                 <ref type="manager">ExtensionState</ref>
1384                         </see-also>
1385                 </managerEventInstance>
1386         </managerEvent>
1387         <managerEvent name="PresenceStatus" language="en_US">
1388                 <managerEventInstance class="EVENT_FLAG_CALL">
1389                         <synopsis>Raised when a hint changes due to a presence state change.</synopsis>
1390                         <syntax>
1391                                 <parameter name="Exten" />
1392                                 <parameter name="Context" />
1393                                 <parameter name="Hint" />
1394                                 <parameter name="Status" />
1395                                 <parameter name="Subtype" />
1396                                 <parameter name="Message" />
1397                         </syntax>
1398                         <see-also>
1399                                 <ref type="manager">PresenceState</ref>
1400                         </see-also>
1401                 </managerEventInstance>
1402         </managerEvent>
1403  ***/
1404
1405 /*! \addtogroup Group_AMI AMI functions
1406 */
1407 /*! @{
1408  Doxygen group */
1409
1410 enum error_type {
1411         UNKNOWN_ACTION = 1,
1412         UNKNOWN_CATEGORY,
1413         UNSPECIFIED_CATEGORY,
1414         UNSPECIFIED_ARGUMENT,
1415         FAILURE_ALLOCATION,
1416         FAILURE_NEWCAT,
1417         FAILURE_DELCAT,
1418         FAILURE_EMPTYCAT,
1419         FAILURE_UPDATE,
1420         FAILURE_DELETE,
1421         FAILURE_APPEND,
1422         FAILURE_TEMPLATE
1423 };
1424
1425 enum add_filter_result {
1426         FILTER_SUCCESS,
1427         FILTER_ALLOC_FAILED,
1428         FILTER_COMPILE_FAIL,
1429 };
1430
1431 /*!
1432  * Linked list of events.
1433  * Global events are appended to the list by append_event().
1434  * The usecount is the number of stored pointers to the element,
1435  * excluding the list pointers. So an element that is only in
1436  * the list has a usecount of 0, not 1.
1437  *
1438  * Clients have a pointer to the last event processed, and for each
1439  * of these clients we track the usecount of the elements.
1440  * If we have a pointer to an entry in the list, it is safe to navigate
1441  * it forward because elements will not be deleted, but only appended.
1442  * The worst that can happen is seeing the pointer still NULL.
1443  *
1444  * When the usecount of an element drops to 0, and the element is the
1445  * first in the list, we can remove it. Removal is done within the
1446  * main thread, which is woken up for the purpose.
1447  *
1448  * For simplicity of implementation, we make sure the list is never empty.
1449  */
1450 struct eventqent {
1451         int usecount;           /*!< # of clients who still need the event */
1452         int category;
1453         unsigned int seq;       /*!< sequence number */
1454         struct timeval tv;  /*!< When event was allocated */
1455         AST_RWLIST_ENTRY(eventqent) eq_next;
1456         char eventdata[1];      /*!< really variable size, allocated by append_event() */
1457 };
1458
1459 static AST_RWLIST_HEAD_STATIC(all_events, eventqent);
1460
1461 static int displayconnects = 1;
1462 static int allowmultiplelogin = 1;
1463 static int timestampevents;
1464 static int httptimeout = 60;
1465 static int broken_events_action = 0;
1466 static int manager_enabled = 0;
1467 static int subscribed = 0;
1468 static int webmanager_enabled = 0;
1469 static int manager_debug = 0;   /*!< enable some debugging code in the manager */
1470 static int authtimeout;
1471 static int authlimit;
1472 static char *manager_channelvars;
1473
1474 #define DEFAULT_REALM           "asterisk"
1475 static char global_realm[MAXHOSTNAMELEN];       /*!< Default realm */
1476
1477 static int unauth_sessions = 0;
1478 static struct stasis_subscription *acl_change_sub;
1479
1480 /*! \brief A \ref stasis_topic that all topics AMI cares about will be forwarded to */
1481 static struct stasis_topic *manager_topic;
1482
1483 /*! \brief The \ref stasis_message_router for all \ref stasis messages */
1484 static struct stasis_message_router *stasis_router;
1485
1486 /*! \brief The \ref stasis_subscription for forwarding the RTP topic to the AMI topic */
1487 static struct stasis_forward *rtp_topic_forwarder;
1488
1489 /*! \brief The \ref stasis_subscription for forwarding the Security topic to the AMI topic */
1490 static struct stasis_forward *security_topic_forwarder;
1491
1492 #ifdef TEST_FRAMEWORK
1493 /*! \brief The \ref stasis_subscription for forwarding the Test topic to the AMI topic */
1494 static struct stasis_forward *test_suite_forwarder;
1495 #endif
1496
1497 #define MGR_SHOW_TERMINAL_WIDTH 80
1498
1499 #define MAX_VARS 128
1500
1501 /*! \brief Fake event class used to end sessions at shutdown */
1502 #define EVENT_FLAG_SHUTDOWN -1
1503
1504 /*! \brief
1505  * Descriptor for a manager session, either on the AMI socket or over HTTP.
1506  *
1507  * \note
1508  * AMI session have managerid == 0; the entry is created upon a connect,
1509  * and destroyed with the socket.
1510  * HTTP sessions have managerid != 0, the value is used as a search key
1511  * to lookup sessions (using the mansession_id cookie, or nonce key from
1512  * Digest Authentication http header).
1513  */
1514 #define MAX_BLACKLIST_CMD_LEN 2
1515 static const struct {
1516         const char *words[AST_MAX_CMD_LEN];
1517 } command_blacklist[] = {
1518         {{ "module", "load", NULL }},
1519         {{ "module", "unload", NULL }},
1520         {{ "restart", "gracefully", NULL }},
1521 };
1522
1523 static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message);
1524
1525 static void acl_change_stasis_subscribe(void)
1526 {
1527         if (!acl_change_sub) {
1528                 acl_change_sub = stasis_subscribe(ast_security_topic(),
1529                         acl_change_stasis_cb, NULL);
1530         }
1531 }
1532
1533 static void acl_change_stasis_unsubscribe(void)
1534 {
1535         acl_change_sub = stasis_unsubscribe_and_join(acl_change_sub);
1536 }
1537
1538 /* In order to understand what the heck is going on with the
1539  * mansession_session and mansession structs, we need to have a bit of a history
1540  * lesson.
1541  *
1542  * In the beginning, there was the mansession. The mansession contained data that was
1543  * intrinsic to a manager session, such as the time that it started, the name of the logged-in
1544  * user, etc. In addition to these parameters were the f and fd parameters. For typical manager
1545  * sessions, these were used to represent the TCP socket over which the AMI session was taking
1546  * place. It makes perfect sense for these fields to be a part of the session-specific data since
1547  * the session actually defines this information.
1548  *
1549  * Then came the HTTP AMI sessions. With these, the f and fd fields need to be opened and closed
1550  * for every single action that occurs. Thus the f and fd fields aren't really specific to the session
1551  * but rather to the action that is being executed. Because a single session may execute many commands
1552  * at once, some sort of safety needed to be added in order to be sure that we did not end up with fd
1553  * leaks from one action overwriting the f and fd fields used by a previous action before the previous action
1554  * has had a chance to properly close its handles.
1555  *
1556  * The initial idea to solve this was to use thread synchronization, but this prevented multiple actions
1557  * from being run at the same time in a single session. Some manager actions may block for a long time, thus
1558  * creating a large queue of actions to execute. In addition, this fix did not address the basic architectural
1559  * issue that for HTTP manager sessions, the f and fd variables are not really a part of the session, but are
1560  * part of the action instead.
1561  *
1562  * The new idea was to create a structure on the stack for each HTTP Manager action. This structure would
1563  * contain the action-specific information, such as which file to write to. In order to maintain expectations
1564  * of action handlers and not have to change the public API of the manager code, we would need to name this
1565  * new stacked structure 'mansession' and contain within it the old mansession struct that we used to use.
1566  * We renamed the old mansession struct 'mansession_session' to hopefully convey that what is in this structure
1567  * is session-specific data. The structure that it is wrapped in, called a 'mansession' really contains action-specific
1568  * data.
1569  */
1570 struct mansession_session {
1571                                 /*! \todo XXX need to document which fields it is protecting */
1572         struct ast_sockaddr addr;       /*!< address we are connecting from */
1573         struct ast_iostream *stream;    /*!< AMI stream */
1574         int inuse;              /*!< number of HTTP sessions using this entry */
1575         int needdestroy;        /*!< Whether an HTTP session should be destroyed */
1576         pthread_t waiting_thread;       /*!< Sleeping thread using this descriptor */
1577         uint32_t managerid;     /*!< Unique manager identifier, 0 for AMI sessions */
1578         time_t sessionstart;    /*!< Session start time */
1579         struct timeval sessionstart_tv; /*!< Session start time */
1580         time_t sessiontimeout;  /*!< Session timeout if HTTP */
1581         char username[80];      /*!< Logged in username */
1582         char challenge[10];     /*!< Authentication challenge */
1583         int authenticated;      /*!< Authentication status */
1584         int readperm;           /*!< Authorization for reading */
1585         int writeperm;          /*!< Authorization for writing */
1586         char inbuf[1025];       /*!< Buffer -  we use the extra byte to add a '\\0' and simplify parsing */
1587         int inlen;              /*!< number of buffered bytes */
1588         struct ao2_container *whitefilters;     /*!< Manager event filters - white list */
1589         struct ao2_container *blackfilters;     /*!< Manager event filters - black list */
1590         struct ast_variable *chanvars;  /*!< Channel variables to set for originate */
1591         int send_events;        /*!<  XXX what ? */
1592         struct eventqent *last_ev;      /*!< last event processed. */
1593         int writetimeout;       /*!< Timeout for ast_carefulwrite() */
1594         time_t authstart;
1595         int pending_event;         /*!< Pending events indicator in case when waiting_thread is NULL */
1596         time_t noncetime;       /*!< Timer for nonce value expiration */
1597         unsigned long oldnonce; /*!< Stale nonce value */
1598         unsigned long nc;       /*!< incremental  nonce counter */
1599         AST_LIST_HEAD_NOLOCK(mansession_datastores, ast_datastore) datastores; /*!< Data stores on the session */
1600         AST_LIST_ENTRY(mansession_session) list;
1601 };
1602
1603 enum mansession_message_parsing {
1604         MESSAGE_OKAY,
1605         MESSAGE_LINE_TOO_LONG
1606 };
1607
1608 /*! \brief In case you didn't read that giant block of text above the mansession_session struct, the
1609  * \ref struct mansession is named this solely to keep the API the same in Asterisk. This structure really
1610  * represents data that is different from Manager action to Manager action. The mansession_session pointer
1611  * contained within points to session-specific data.
1612  */
1613 struct mansession {
1614         struct mansession_session *session;
1615         struct ast_iostream *stream;
1616         struct ast_tcptls_session_instance *tcptls_session;
1617         enum mansession_message_parsing parsing;
1618         int write_error:1;
1619         struct manager_custom_hook *hook;
1620         ast_mutex_t lock;
1621 };
1622
1623 /*! Active manager connection sessions container. */
1624 static AO2_GLOBAL_OBJ_STATIC(mgr_sessions);
1625
1626 /*! \brief user descriptor, as read from the config file.
1627  *
1628  * \note It is still missing some fields -- e.g. we can have multiple permit and deny
1629  * lines which are not supported here, and readperm/writeperm/writetimeout
1630  * are not stored.
1631  */
1632 struct ast_manager_user {
1633         char username[80];
1634         char *secret;                   /*!< Secret for logging in */
1635         int readperm;                   /*!< Authorization for reading */
1636         int writeperm;                  /*!< Authorization for writing */
1637         int writetimeout;               /*!< Per user Timeout for ast_carefulwrite() */
1638         int displayconnects;            /*!< XXX unused */
1639         int allowmultiplelogin; /*!< Per user option*/
1640         int keep;                       /*!< mark entries created on a reload */
1641         struct ao2_container *whitefilters; /*!< Manager event filters - white list */
1642         struct ao2_container *blackfilters; /*!< Manager event filters - black list */
1643         struct ast_acl_list *acl;       /*!< ACL setting */
1644         char *a1_hash;                  /*!< precalculated A1 for Digest auth */
1645         struct ast_variable *chanvars;  /*!< Channel variables to set for originate */
1646         AST_RWLIST_ENTRY(ast_manager_user) list;
1647 };
1648
1649 /*! \brief list of users found in the config file */
1650 static AST_RWLIST_HEAD_STATIC(users, ast_manager_user);
1651
1652 /*! \brief list of actions registered */
1653 static AST_RWLIST_HEAD_STATIC(actions, manager_action);
1654
1655 /*! \brief list of hooks registered */
1656 static AST_RWLIST_HEAD_STATIC(manager_hooks, manager_custom_hook);
1657
1658 #ifdef AST_XML_DOCS
1659 /*! \brief A container of event documentation nodes */
1660 static AO2_GLOBAL_OBJ_STATIC(event_docs);
1661 #endif
1662
1663 static int __attribute__((format(printf, 9, 0))) __manager_event_sessions(
1664         struct ao2_container *sessions,
1665         int category,
1666         const char *event,
1667         int chancount,
1668         struct ast_channel **chans,
1669         const char *file,
1670         int line,
1671         const char *func,
1672         const char *fmt,
1673         ...);
1674 static enum add_filter_result manager_add_filter(const char *filter_pattern, struct ao2_container *whitefilters, struct ao2_container *blackfilters);
1675
1676 static int match_filter(struct mansession *s, char *eventdata);
1677
1678 /*!
1679  * @{ \brief Define AMI message types.
1680  */
1681 STASIS_MESSAGE_TYPE_DEFN(ast_manager_get_generic_type);
1682 /*! @} */
1683
1684 /*!
1685  * \internal
1686  * \brief Find a registered action object.
1687  *
1688  * \param name Name of AMI action to find.
1689  *
1690  * \return Reffed action found or NULL
1691  */
1692 static struct manager_action *action_find(const char *name)
1693 {
1694         struct manager_action *act;
1695
1696         AST_RWLIST_RDLOCK(&actions);
1697         AST_RWLIST_TRAVERSE(&actions, act, list) {
1698                 if (!strcasecmp(name, act->action)) {
1699                         ao2_t_ref(act, +1, "found action object");
1700                         break;
1701                 }
1702         }
1703         AST_RWLIST_UNLOCK(&actions);
1704
1705         return act;
1706 }
1707
1708 struct stasis_topic *ast_manager_get_topic(void)
1709 {
1710         return manager_topic;
1711 }
1712
1713 struct stasis_message_router *ast_manager_get_message_router(void)
1714 {
1715         return stasis_router;
1716 }
1717
1718 static void manager_json_value_str_append(struct ast_json *value, const char *key,
1719                                           struct ast_str **res)
1720 {
1721         switch (ast_json_typeof(value)) {
1722         case AST_JSON_STRING:
1723                 ast_str_append(res, 0, "%s: %s\r\n", key, ast_json_string_get(value));
1724                 break;
1725         case AST_JSON_INTEGER:
1726                 ast_str_append(res, 0, "%s: %jd\r\n", key, ast_json_integer_get(value));
1727                 break;
1728         case AST_JSON_TRUE:
1729                 ast_str_append(res, 0, "%s: True\r\n", key);
1730                 break;
1731         case AST_JSON_FALSE:
1732                 ast_str_append(res, 0, "%s: False\r\n", key);
1733                 break;
1734         default:
1735                 ast_str_append(res, 0, "%s: \r\n", key);
1736                 break;
1737         }
1738 }
1739
1740 static void manager_json_to_ast_str(struct ast_json *obj, const char *key,
1741                                     struct ast_str **res, key_exclusion_cb exclusion_cb);
1742
1743 static void manager_json_array_with_key(struct ast_json *obj, const char* key,
1744                                         size_t index, struct ast_str **res,
1745                                         key_exclusion_cb exclusion_cb)
1746 {
1747         struct ast_str *key_str = ast_str_alloca(64);
1748         ast_str_set(&key_str, 0, "%s(%zu)", key, index);
1749         manager_json_to_ast_str(obj, ast_str_buffer(key_str),
1750                                 res, exclusion_cb);
1751 }
1752
1753 static void manager_json_obj_with_key(struct ast_json *obj, const char* key,
1754                                       const char *parent_key, struct ast_str **res,
1755                                       key_exclusion_cb exclusion_cb)
1756 {
1757         if (parent_key) {
1758                 struct ast_str *key_str = ast_str_alloca(64);
1759                 ast_str_set(&key_str, 0, "%s/%s", parent_key, key);
1760                 manager_json_to_ast_str(obj, ast_str_buffer(key_str),
1761                                         res, exclusion_cb);
1762                 return;
1763         }
1764
1765         manager_json_to_ast_str(obj, key, res, exclusion_cb);
1766 }
1767
1768 void manager_json_to_ast_str(struct ast_json *obj, const char *key,
1769                              struct ast_str **res, key_exclusion_cb exclusion_cb)
1770 {
1771         struct ast_json_iter *i;
1772
1773         /* If obj or res is not given, just return */
1774         if (!obj || !res) {
1775                 return;
1776         }
1777
1778         if (!*res && !(*res = ast_str_create(1024))) {
1779                 return;
1780         }
1781
1782         if (exclusion_cb && key && exclusion_cb(key)) {
1783                 return;
1784         }
1785
1786         if (ast_json_typeof(obj) != AST_JSON_OBJECT &&
1787             ast_json_typeof(obj) != AST_JSON_ARRAY) {
1788                 manager_json_value_str_append(obj, key, res);
1789                 return;
1790         }
1791
1792         if (ast_json_typeof(obj) == AST_JSON_ARRAY) {
1793                 size_t j;
1794                 for (j = 0; j < ast_json_array_size(obj); ++j) {
1795                         manager_json_array_with_key(ast_json_array_get(obj, j),
1796                                                     key, j, res, exclusion_cb);
1797                 }
1798                 return;
1799         }
1800
1801         for (i = ast_json_object_iter(obj); i;
1802              i = ast_json_object_iter_next(obj, i)) {
1803                 manager_json_obj_with_key(ast_json_object_iter_value(i),
1804                                           ast_json_object_iter_key(i),
1805                                           key, res, exclusion_cb);
1806         }
1807 }
1808
1809 struct ast_str *ast_manager_str_from_json_object(struct ast_json *blob, key_exclusion_cb exclusion_cb)
1810 {
1811         struct ast_str *res = ast_str_create(1024);
1812
1813         if (!ast_json_is_null(blob)) {
1814            manager_json_to_ast_str(blob, NULL, &res, exclusion_cb);
1815         }
1816
1817         return res;
1818 }
1819
1820 #define manager_event_sessions(sessions, category, event, contents , ...)       \
1821         __manager_event_sessions(sessions, category, event, 0, NULL, __FILE__, __LINE__, __PRETTY_FUNCTION__, contents , ## __VA_ARGS__)
1822
1823 #define any_manager_listeners(sessions) \
1824         ((sessions && ao2_container_count(sessions)) || !AST_RWLIST_EMPTY(&manager_hooks))
1825
1826 static void manager_default_msg_cb(void *data, struct stasis_subscription *sub,
1827                                     struct stasis_message *message)
1828 {
1829         struct ao2_container *sessions;
1830         struct ast_manager_event_blob *ev;
1831
1832         if (!stasis_message_can_be_ami(message)) {
1833                 /* Not an AMI message; disregard */
1834                 return;
1835         }
1836
1837         sessions = ao2_global_obj_ref(mgr_sessions);
1838         if (!any_manager_listeners(sessions)) {
1839                 /* Nobody is listening */
1840                 ao2_cleanup(sessions);
1841                 return;
1842         }
1843
1844         ev = stasis_message_to_ami(message);
1845         if (!ev) {
1846                 /* Conversion failure */
1847                 ao2_cleanup(sessions);
1848                 return;
1849         }
1850
1851         manager_event_sessions(sessions, ev->event_flags, ev->manager_event,
1852                 "%s", ev->extra_fields);
1853         ao2_ref(ev, -1);
1854         ao2_cleanup(sessions);
1855 }
1856
1857 static void manager_generic_msg_cb(void *data, struct stasis_subscription *sub,
1858                                     struct stasis_message *message)
1859 {
1860         struct ast_json_payload *payload;
1861         int class_type;
1862         const char *type;
1863         struct ast_json *event;
1864         struct ast_str *event_buffer;
1865         struct ao2_container *sessions;
1866
1867         sessions = ao2_global_obj_ref(mgr_sessions);
1868         if (!any_manager_listeners(sessions)) {
1869                 /* Nobody is listening */
1870                 ao2_cleanup(sessions);
1871                 return;
1872         }
1873
1874         payload = stasis_message_data(message);
1875         class_type = ast_json_integer_get(ast_json_object_get(payload->json, "class_type"));
1876         type = ast_json_string_get(ast_json_object_get(payload->json, "type"));
1877         event = ast_json_object_get(payload->json, "event");
1878
1879         event_buffer = ast_manager_str_from_json_object(event, NULL);
1880         if (!event_buffer) {
1881                 ast_log(AST_LOG_WARNING, "Error while creating payload for event %s\n", type);
1882                 ao2_cleanup(sessions);
1883                 return;
1884         }
1885         manager_event_sessions(sessions, class_type, type,
1886                 "%s", ast_str_buffer(event_buffer));
1887         ast_free(event_buffer);
1888         ao2_cleanup(sessions);
1889 }
1890
1891 void ast_manager_publish_event(const char *type, int class_type, struct ast_json *obj)
1892 {
1893         RAII_VAR(struct ast_json *, event_info, NULL, ast_json_unref);
1894         RAII_VAR(struct ast_json_payload *, payload, NULL, ao2_cleanup);
1895         RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
1896
1897         if (!obj || !ast_manager_get_generic_type()) {
1898                 return;
1899         }
1900
1901         ast_json_ref(obj);
1902         event_info = ast_json_pack("{s: s, s: i, s: o}",
1903                         "type", type,
1904                         "class_type", class_type,
1905                         "event", obj);
1906         if (!event_info) {
1907                 return;
1908         }
1909
1910         payload = ast_json_payload_create(event_info);
1911         if (!payload) {
1912                 return;
1913         }
1914         message = stasis_message_create(ast_manager_get_generic_type(), payload);
1915         if (!message) {
1916                 return;
1917         }
1918         stasis_publish(ast_manager_get_topic(), message);
1919 }
1920
1921 /*! \brief Add a custom hook to be called when an event is fired */
1922 void ast_manager_register_hook(struct manager_custom_hook *hook)
1923 {
1924         AST_RWLIST_WRLOCK(&manager_hooks);
1925         AST_RWLIST_INSERT_TAIL(&manager_hooks, hook, list);
1926         AST_RWLIST_UNLOCK(&manager_hooks);
1927 }
1928
1929 /*! \brief Delete a custom hook to be called when an event is fired */
1930 void ast_manager_unregister_hook(struct manager_custom_hook *hook)
1931 {
1932         AST_RWLIST_WRLOCK(&manager_hooks);
1933         AST_RWLIST_REMOVE(&manager_hooks, hook, list);
1934         AST_RWLIST_UNLOCK(&manager_hooks);
1935 }
1936
1937 int check_manager_enabled(void)
1938 {
1939         return manager_enabled;
1940 }
1941
1942 int check_webmanager_enabled(void)
1943 {
1944         return (webmanager_enabled && manager_enabled);
1945 }
1946
1947 /*!
1948  * Grab a reference to the last event, update usecount as needed.
1949  * Can handle a NULL pointer.
1950  */
1951 static struct eventqent *grab_last(void)
1952 {
1953         struct eventqent *ret;
1954
1955         AST_RWLIST_WRLOCK(&all_events);
1956         ret = AST_RWLIST_LAST(&all_events);
1957         /* the list is never empty now, but may become so when
1958          * we optimize it in the future, so be prepared.
1959          */
1960         if (ret) {
1961                 ast_atomic_fetchadd_int(&ret->usecount, 1);
1962         }
1963         AST_RWLIST_UNLOCK(&all_events);
1964         return ret;
1965 }
1966
1967 /*!
1968  * Purge unused events. Remove elements from the head
1969  * as long as their usecount is 0 and there is a next element.
1970  */
1971 static void purge_events(void)
1972 {
1973         struct eventqent *ev;
1974         struct timeval now = ast_tvnow();
1975
1976         AST_RWLIST_WRLOCK(&all_events);
1977         while ( (ev = AST_RWLIST_FIRST(&all_events)) &&
1978             ev->usecount == 0 && AST_RWLIST_NEXT(ev, eq_next)) {
1979                 AST_RWLIST_REMOVE_HEAD(&all_events, eq_next);
1980                 ast_free(ev);
1981         }
1982
1983         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&all_events, ev, eq_next) {
1984                 /* Never release the last event */
1985                 if (!AST_RWLIST_NEXT(ev, eq_next)) {
1986                         break;
1987                 }
1988
1989                 /* 2.5 times whatever the HTTP timeout is (maximum 2.5 hours) is the maximum time that we will definitely cache an event */
1990                 if (ev->usecount == 0 && ast_tvdiff_sec(now, ev->tv) > (httptimeout > 3600 ? 3600 : httptimeout) * 2.5) {
1991                         AST_RWLIST_REMOVE_CURRENT(eq_next);
1992                         ast_free(ev);
1993                 }
1994         }
1995         AST_RWLIST_TRAVERSE_SAFE_END;
1996         AST_RWLIST_UNLOCK(&all_events);
1997 }
1998
1999 /*!
2000  * helper functions to convert back and forth between
2001  * string and numeric representation of set of flags
2002  */
2003 static const struct permalias {
2004         int num;
2005         const char *label;
2006 } perms[] = {
2007         { EVENT_FLAG_SYSTEM, "system" },
2008         { EVENT_FLAG_CALL, "call" },
2009         { EVENT_FLAG_LOG, "log" },
2010         { EVENT_FLAG_VERBOSE, "verbose" },
2011         { EVENT_FLAG_COMMAND, "command" },
2012         { EVENT_FLAG_AGENT, "agent" },
2013         { EVENT_FLAG_USER, "user" },
2014         { EVENT_FLAG_CONFIG, "config" },
2015         { EVENT_FLAG_DTMF, "dtmf" },
2016         { EVENT_FLAG_REPORTING, "reporting" },
2017         { EVENT_FLAG_CDR, "cdr" },
2018         { EVENT_FLAG_DIALPLAN, "dialplan" },
2019         { EVENT_FLAG_ORIGINATE, "originate" },
2020         { EVENT_FLAG_AGI, "agi" },
2021         { EVENT_FLAG_CC, "cc" },
2022         { EVENT_FLAG_AOC, "aoc" },
2023         { EVENT_FLAG_TEST, "test" },
2024         { EVENT_FLAG_SECURITY, "security" },
2025         { EVENT_FLAG_MESSAGE, "message" },
2026         { INT_MAX, "all" },
2027         { 0, "none" },
2028 };
2029
2030 /*! Maximum string length of the AMI authority permission string buildable from perms[]. */
2031 #define MAX_AUTH_PERM_STRING    150
2032
2033 /*! \brief Checks to see if a string which can be used to evaluate functions should be rejected */
2034 static int function_capable_string_allowed_with_auths(const char *evaluating, int writepermlist)
2035 {
2036         if (!(writepermlist & EVENT_FLAG_SYSTEM)
2037                 && (
2038                         strstr(evaluating, "SHELL") ||       /* NoOp(${SHELL(rm -rf /)})  */
2039                         strstr(evaluating, "EVAL")           /* NoOp(${EVAL(${some_var_containing_SHELL})}) */
2040                 )) {
2041                 return 0;
2042         }
2043         return 1;
2044 }
2045
2046 /*! \brief Convert authority code to a list of options for a user. This will only
2047  * display those authority codes that have an explicit match on authority */
2048 static const char *user_authority_to_str(int authority, struct ast_str **res)
2049 {
2050         int i;
2051         char *sep = "";
2052
2053         ast_str_reset(*res);
2054         for (i = 0; i < ARRAY_LEN(perms) - 1; i++) {
2055                 if ((authority & perms[i].num) == perms[i].num) {
2056                         ast_str_append(res, 0, "%s%s", sep, perms[i].label);
2057                         sep = ",";
2058                 }
2059         }
2060
2061         if (ast_str_strlen(*res) == 0) {
2062                 /* replace empty string with something sensible */
2063                 ast_str_append(res, 0, "<none>");
2064         }
2065
2066         return ast_str_buffer(*res);
2067 }
2068
2069
2070 /*! \brief Convert authority code to a list of options. Note that the EVENT_FLAG_ALL
2071  * authority will always be returned. */
2072 static const char *authority_to_str(int authority, struct ast_str **res)
2073 {
2074         int i;
2075         char *sep = "";
2076
2077         ast_str_reset(*res);
2078         if (authority != EVENT_FLAG_SHUTDOWN) {
2079                 for (i = 0; i < ARRAY_LEN(perms) - 1; i++) {
2080                         if (authority & perms[i].num) {
2081                                 ast_str_append(res, 0, "%s%s", sep, perms[i].label);
2082                                 sep = ",";
2083                         }
2084                 }
2085         }
2086
2087         if (ast_str_strlen(*res) == 0) {
2088                 /* replace empty string with something sensible */
2089                 ast_str_append(res, 0, "<none>");
2090         }
2091
2092         return ast_str_buffer(*res);
2093 }
2094
2095 /*! Tells you if smallstr exists inside bigstr
2096    which is delim by delim and uses no buf or stringsep
2097    ast_instring("this|that|more","this",'|') == 1;
2098
2099    feel free to move this to app.c -anthm */
2100 static int ast_instring(const char *bigstr, const char *smallstr, const char delim)
2101 {
2102         const char *val = bigstr, *next;
2103
2104         do {
2105                 if ((next = strchr(val, delim))) {
2106                         if (!strncmp(val, smallstr, (next - val))) {
2107                                 return 1;
2108                         } else {
2109                                 continue;
2110                         }
2111                 } else {
2112                         return !strcmp(smallstr, val);
2113                 }
2114         } while (*(val = (next + 1)));
2115
2116         return 0;
2117 }
2118
2119 static int get_perm(const char *instr)
2120 {
2121         int x = 0, ret = 0;
2122
2123         if (!instr) {
2124                 return 0;
2125         }
2126
2127         for (x = 0; x < ARRAY_LEN(perms); x++) {
2128                 if (ast_instring(instr, perms[x].label, ',')) {
2129                         ret |= perms[x].num;
2130                 }
2131         }
2132
2133         return ret;
2134 }
2135
2136 /*!
2137  * A number returns itself, false returns 0, true returns all flags,
2138  * other strings return the flags that are set.
2139  */
2140 static int strings_to_mask(const char *string)
2141 {
2142         const char *p;
2143
2144         if (ast_strlen_zero(string)) {
2145                 return -1;
2146         }
2147
2148         for (p = string; *p; p++) {
2149                 if (*p < '0' || *p > '9') {
2150                         break;
2151                 }
2152         }
2153         if (!*p) { /* all digits */
2154                 return atoi(string);
2155         }
2156         if (ast_false(string)) {
2157                 return 0;
2158         }
2159         if (ast_true(string)) { /* all permissions */
2160                 int x, ret = 0;
2161                 for (x = 0; x < ARRAY_LEN(perms); x++) {
2162                         ret |= perms[x].num;
2163                 }
2164                 return ret;
2165         }
2166         return get_perm(string);
2167 }
2168
2169 /*! \brief Unreference manager session object.
2170      If no more references, then go ahead and delete it */
2171 static struct mansession_session *unref_mansession(struct mansession_session *s)
2172 {
2173         int refcount = ao2_ref(s, -1);
2174         if (manager_debug) {
2175                 ast_debug(1, "Mansession: %p refcount now %d\n", s, refcount - 1);
2176         }
2177         return NULL;
2178 }
2179
2180 static void event_filter_destructor(void *obj)
2181 {
2182         regex_t *regex_filter = obj;
2183         regfree(regex_filter);
2184 }
2185
2186 static void session_destructor(void *obj)
2187 {
2188         struct mansession_session *session = obj;
2189         struct eventqent *eqe = session->last_ev;
2190         struct ast_datastore *datastore;
2191
2192         /* Get rid of each of the data stores on the session */
2193         while ((datastore = AST_LIST_REMOVE_HEAD(&session->datastores, entry))) {
2194                 /* Free the data store */
2195                 ast_datastore_free(datastore);
2196         }
2197
2198         if (eqe) {
2199                 ast_atomic_fetchadd_int(&eqe->usecount, -1);
2200         }
2201         if (session->chanvars) {
2202                 ast_variables_destroy(session->chanvars);
2203         }
2204
2205         if (session->whitefilters) {
2206                 ao2_t_ref(session->whitefilters, -1, "decrement ref for white container, should be last one");
2207         }
2208
2209         if (session->blackfilters) {
2210                 ao2_t_ref(session->blackfilters, -1, "decrement ref for black container, should be last one");
2211         }
2212 }
2213
2214 /*! \brief Allocate manager session structure and add it to the list of sessions */
2215 static struct mansession_session *build_mansession(const struct ast_sockaddr *addr)
2216 {
2217         struct ao2_container *sessions;
2218         struct mansession_session *newsession;
2219
2220         newsession = ao2_alloc(sizeof(*newsession), session_destructor);
2221         if (!newsession) {
2222                 return NULL;
2223         }
2224
2225         newsession->whitefilters = ao2_container_alloc(1, NULL, NULL);
2226         newsession->blackfilters = ao2_container_alloc(1, NULL, NULL);
2227         if (!newsession->whitefilters || !newsession->blackfilters) {
2228                 ao2_ref(newsession, -1);
2229                 return NULL;
2230         }
2231
2232         newsession->waiting_thread = AST_PTHREADT_NULL;
2233         newsession->writetimeout = 100;
2234         newsession->send_events = -1;
2235         ast_sockaddr_copy(&newsession->addr, addr);
2236
2237         sessions = ao2_global_obj_ref(mgr_sessions);
2238         if (sessions) {
2239                 ao2_link(sessions, newsession);
2240                 ao2_ref(sessions, -1);
2241         }
2242
2243         return newsession;
2244 }
2245
2246 static int mansession_cmp_fn(void *obj, void *arg, int flags)
2247 {
2248         struct mansession_session *s = obj;
2249         char *str = arg;
2250         return !strcasecmp(s->username, str) ? CMP_MATCH : 0;
2251 }
2252
2253 static void session_destroy(struct mansession_session *s)
2254 {
2255         struct ao2_container *sessions;
2256
2257         sessions = ao2_global_obj_ref(mgr_sessions);
2258         if (sessions) {
2259                 ao2_unlink(sessions, s);
2260                 ao2_ref(sessions, -1);
2261         }
2262         unref_mansession(s);
2263 }
2264
2265
2266 static int check_manager_session_inuse(const char *name)
2267 {
2268         struct ao2_container *sessions;
2269         struct mansession_session *session;
2270         int inuse = 0;
2271
2272         sessions = ao2_global_obj_ref(mgr_sessions);
2273         if (sessions) {
2274                 session = ao2_find(sessions, (char *) name, 0);
2275                 ao2_ref(sessions, -1);
2276                 if (session) {
2277                         unref_mansession(session);
2278                         inuse = 1;
2279                 }
2280         }
2281         return inuse;
2282 }
2283
2284
2285 /*!
2286  * lookup an entry in the list of registered users.
2287  * must be called with the list lock held.
2288  */
2289 static struct ast_manager_user *get_manager_by_name_locked(const char *name)
2290 {
2291         struct ast_manager_user *user = NULL;
2292
2293         AST_RWLIST_TRAVERSE(&users, user, list) {
2294                 if (!strcasecmp(user->username, name)) {
2295                         break;
2296                 }
2297         }
2298
2299         return user;
2300 }
2301
2302 /*! \brief Get displayconnects config option.
2303  *  \param session manager session to get parameter from.
2304  *  \return displayconnects config option value.
2305  */
2306 static int manager_displayconnects(struct mansession_session *session)
2307 {
2308         struct ast_manager_user *user = NULL;
2309         int ret = 0;
2310
2311         AST_RWLIST_RDLOCK(&users);
2312         if ((user = get_manager_by_name_locked(session->username))) {
2313                 ret = user->displayconnects;
2314         }
2315         AST_RWLIST_UNLOCK(&users);
2316
2317         return ret;
2318 }
2319
2320 #ifdef AST_XML_DOCS
2321 static void print_event_instance(struct ast_cli_args *a, struct ast_xml_doc_item *instance);
2322 #endif
2323
2324 static char *handle_showmancmd(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2325 {
2326         struct manager_action *cur;
2327         struct ast_str *authority;
2328         int num;
2329         int l;
2330         const char *auth_str;
2331 #ifdef AST_XML_DOCS
2332         char syntax_title[64], description_title[64], synopsis_title[64], seealso_title[64];
2333         char arguments_title[64], privilege_title[64], final_response_title[64], list_responses_title[64];
2334 #endif
2335
2336         switch (cmd) {
2337         case CLI_INIT:
2338                 e->command = "manager show command";
2339                 e->usage =
2340                         "Usage: manager show command <actionname> [<actionname> [<actionname> [...]]]\n"
2341                         "       Shows the detailed description for a specific Asterisk manager interface command.\n";
2342                 return NULL;
2343         case CLI_GENERATE:
2344                 l = strlen(a->word);
2345                 AST_RWLIST_RDLOCK(&actions);
2346                 AST_RWLIST_TRAVERSE(&actions, cur, list) {
2347                         if (!strncasecmp(a->word, cur->action, l)) {
2348                                 if (ast_cli_completion_add(ast_strdup(cur->action))) {
2349                                         break;
2350                                 }
2351                         }
2352                 }
2353                 AST_RWLIST_UNLOCK(&actions);
2354                 return NULL;
2355         }
2356         if (a->argc < 4) {
2357                 return CLI_SHOWUSAGE;
2358         }
2359
2360         authority = ast_str_alloca(MAX_AUTH_PERM_STRING);
2361
2362 #ifdef AST_XML_DOCS
2363         /* setup the titles */
2364         term_color(synopsis_title, "[Synopsis]\n", COLOR_MAGENTA, 0, 40);
2365         term_color(description_title, "[Description]\n", COLOR_MAGENTA, 0, 40);
2366         term_color(syntax_title, "[Syntax]\n", COLOR_MAGENTA, 0, 40);
2367         term_color(seealso_title, "[See Also]\n", COLOR_MAGENTA, 0, 40);
2368         term_color(arguments_title, "[Arguments]\n", COLOR_MAGENTA, 0, 40);
2369         term_color(privilege_title, "[Privilege]\n", COLOR_MAGENTA, 0, 40);
2370         term_color(final_response_title, "[Final Response]\n", COLOR_MAGENTA, 0, 40);
2371         term_color(list_responses_title, "[List Responses]\n", COLOR_MAGENTA, 0, 40);
2372 #endif
2373
2374         AST_RWLIST_RDLOCK(&actions);
2375         AST_RWLIST_TRAVERSE(&actions, cur, list) {
2376                 for (num = 3; num < a->argc; num++) {
2377                         if (!strcasecmp(cur->action, a->argv[num])) {
2378                                 auth_str = authority_to_str(cur->authority, &authority);
2379
2380 #ifdef AST_XML_DOCS
2381                                 if (cur->docsrc == AST_XML_DOC) {
2382                                         char *syntax = ast_xmldoc_printable(S_OR(cur->syntax, "Not available"), 1);
2383                                         char *synopsis = ast_xmldoc_printable(S_OR(cur->synopsis, "Not available"), 1);
2384                                         char *description = ast_xmldoc_printable(S_OR(cur->description, "Not available"), 1);
2385                                         char *arguments = ast_xmldoc_printable(S_OR(cur->arguments, "Not available"), 1);
2386                                         char *seealso = ast_xmldoc_printable(S_OR(cur->seealso, "Not available"), 1);
2387                                         char *privilege = ast_xmldoc_printable(S_OR(auth_str, "Not available"), 1);
2388                                         char *responses = ast_xmldoc_printable("None", 1);
2389
2390                                         if (!syntax || !synopsis || !description || !arguments
2391                                                         || !seealso || !privilege || !responses) {
2392                                                 ast_free(syntax);
2393                                                 ast_free(synopsis);
2394                                                 ast_free(description);
2395                                                 ast_free(arguments);
2396                                                 ast_free(seealso);
2397                                                 ast_free(privilege);
2398                                                 ast_free(responses);
2399                                                 ast_cli(a->fd, "Allocation failure.\n");
2400                                                 AST_RWLIST_UNLOCK(&actions);
2401
2402                                                 return CLI_FAILURE;
2403                                         }
2404
2405                                         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",
2406                                                 syntax_title, syntax,
2407                                                 synopsis_title, synopsis,
2408                                                 description_title, description,
2409                                                 arguments_title, arguments,
2410                                                 seealso_title, seealso,
2411                                                 privilege_title, privilege,
2412                                                 list_responses_title);
2413
2414                                         if (!cur->list_responses) {
2415                                                 ast_cli(a->fd, "%s\n\n", responses);
2416                                         } else {
2417                                                 struct ast_xml_doc_item *temp;
2418                                                 for (temp = cur->list_responses; temp; temp = AST_LIST_NEXT(temp, next)) {
2419                                                         ast_cli(a->fd, "Event: %s\n", temp->name);
2420                                                         print_event_instance(a, temp);
2421                                                 }
2422                                         }
2423
2424                                         ast_cli(a->fd, "%s", final_response_title);
2425
2426                                         if (!cur->final_response) {
2427                                                 ast_cli(a->fd, "%s\n\n", responses);
2428                                         } else {
2429                                                 ast_cli(a->fd, "Event: %s\n", cur->final_response->name);
2430                                                 print_event_instance(a, cur->final_response);
2431                                         }
2432
2433                                         ast_free(syntax);
2434                                         ast_free(synopsis);
2435                                         ast_free(description);
2436                                         ast_free(arguments);
2437                                         ast_free(seealso);
2438                                         ast_free(privilege);
2439                                         ast_free(responses);
2440                                 } else
2441 #endif
2442                                 {
2443                                         ast_cli(a->fd, "Action: %s\nSynopsis: %s\nPrivilege: %s\n%s\n",
2444                                                 cur->action, cur->synopsis,
2445                                                 auth_str,
2446                                                 S_OR(cur->description, ""));
2447                                 }
2448                         }
2449                 }
2450         }
2451         AST_RWLIST_UNLOCK(&actions);
2452
2453         return CLI_SUCCESS;
2454 }
2455
2456 static char *handle_mandebug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2457 {
2458         switch (cmd) {
2459         case CLI_INIT:
2460                 e->command = "manager set debug [on|off]";
2461                 e->usage = "Usage: manager set debug [on|off]\n Show, enable, disable debugging of the manager code.\n";
2462                 return NULL;
2463         case CLI_GENERATE:
2464                 return NULL;
2465         }
2466
2467         if (a->argc == 3) {
2468                 ast_cli(a->fd, "manager debug is %s\n", manager_debug? "on" : "off");
2469         } else if (a->argc == 4) {
2470                 if (!strcasecmp(a->argv[3], "on")) {
2471                         manager_debug = 1;
2472                 } else if (!strcasecmp(a->argv[3], "off")) {
2473                         manager_debug = 0;
2474                 } else {
2475                         return CLI_SHOWUSAGE;
2476                 }
2477         }
2478         return CLI_SUCCESS;
2479 }
2480
2481 static char *handle_showmanager(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2482 {
2483         struct ast_manager_user *user = NULL;
2484         int l;
2485         struct ast_str *rauthority = ast_str_alloca(MAX_AUTH_PERM_STRING);
2486         struct ast_str *wauthority = ast_str_alloca(MAX_AUTH_PERM_STRING);
2487         struct ast_variable *v;
2488
2489         switch (cmd) {
2490         case CLI_INIT:
2491                 e->command = "manager show user";
2492                 e->usage =
2493                         " Usage: manager show user <user>\n"
2494                         "        Display all information related to the manager user specified.\n";
2495                 return NULL;
2496         case CLI_GENERATE:
2497                 l = strlen(a->word);
2498                 if (a->pos != 3) {
2499                         return NULL;
2500                 }
2501                 AST_RWLIST_RDLOCK(&users);
2502                 AST_RWLIST_TRAVERSE(&users, user, list) {
2503                         if (!strncasecmp(a->word, user->username, l)) {
2504                                 if (ast_cli_completion_add(ast_strdup(user->username))) {
2505                                         break;
2506                                 }
2507                         }
2508                 }
2509                 AST_RWLIST_UNLOCK(&users);
2510                 return NULL;
2511         }
2512
2513         if (a->argc != 4) {
2514                 return CLI_SHOWUSAGE;
2515         }
2516
2517         AST_RWLIST_RDLOCK(&users);
2518
2519         if (!(user = get_manager_by_name_locked(a->argv[3]))) {
2520                 ast_cli(a->fd, "There is no manager called %s\n", a->argv[3]);
2521                 AST_RWLIST_UNLOCK(&users);
2522                 return CLI_SUCCESS;
2523         }
2524
2525         ast_cli(a->fd, "\n");
2526         ast_cli(a->fd,
2527                 "          username: %s\n"
2528                 "            secret: %s\n"
2529                 "               ACL: %s\n"
2530                 "         read perm: %s\n"
2531                 "        write perm: %s\n"
2532                 "   displayconnects: %s\n"
2533                 "allowmultiplelogin: %s\n",
2534                 S_OR(user->username, "(N/A)"),
2535                 (user->secret ? "<Set>" : "(N/A)"),
2536                 ((user->acl && !ast_acl_list_is_empty(user->acl)) ? "yes" : "no"),
2537                 user_authority_to_str(user->readperm, &rauthority),
2538                 user_authority_to_str(user->writeperm, &wauthority),
2539                 (user->displayconnects ? "yes" : "no"),
2540                 (user->allowmultiplelogin ? "yes" : "no"));
2541         ast_cli(a->fd, "         Variables: \n");
2542                 for (v = user->chanvars ; v ; v = v->next) {
2543                         ast_cli(a->fd, "                 %s = %s\n", v->name, v->value);
2544                 }
2545
2546         AST_RWLIST_UNLOCK(&users);
2547
2548         return CLI_SUCCESS;
2549 }
2550
2551 static char *handle_showmanagers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2552 {
2553         struct ast_manager_user *user = NULL;
2554         int count_amu = 0;
2555         switch (cmd) {
2556         case CLI_INIT:
2557                 e->command = "manager show users";
2558                 e->usage =
2559                         "Usage: manager show users\n"
2560                         "       Prints a listing of all managers that are currently configured on that\n"
2561                         " system.\n";
2562                 return NULL;
2563         case CLI_GENERATE:
2564                 return NULL;
2565         }
2566         if (a->argc != 3) {
2567                 return CLI_SHOWUSAGE;
2568         }
2569
2570         AST_RWLIST_RDLOCK(&users);
2571
2572         /* If there are no users, print out something along those lines */
2573         if (AST_RWLIST_EMPTY(&users)) {
2574                 ast_cli(a->fd, "There are no manager users.\n");
2575                 AST_RWLIST_UNLOCK(&users);
2576                 return CLI_SUCCESS;
2577         }
2578
2579         ast_cli(a->fd, "\nusername\n--------\n");
2580
2581         AST_RWLIST_TRAVERSE(&users, user, list) {
2582                 ast_cli(a->fd, "%s\n", user->username);
2583                 count_amu++;
2584         }
2585
2586         AST_RWLIST_UNLOCK(&users);
2587
2588         ast_cli(a->fd,"-------------------\n"
2589                       "%d manager users configured.\n", count_amu);
2590         return CLI_SUCCESS;
2591 }
2592
2593 /*! \brief  CLI command  manager list commands */
2594 static char *handle_showmancmds(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2595 {
2596         struct manager_action *cur;
2597         int name_len = 1;
2598         int space_remaining;
2599 #define HSMC_FORMAT "  %-*.*s  %-.*s\n"
2600         switch (cmd) {
2601         case CLI_INIT:
2602                 e->command = "manager show commands";
2603                 e->usage =
2604                         "Usage: manager show commands\n"
2605                         "       Prints a listing of all the available Asterisk manager interface commands.\n";
2606                 return NULL;
2607         case CLI_GENERATE:
2608                 return NULL;
2609         }
2610
2611         AST_RWLIST_RDLOCK(&actions);
2612         AST_RWLIST_TRAVERSE(&actions, cur, list) {
2613                 int incoming_len = strlen(cur->action);
2614                 if (incoming_len > name_len) {
2615                         name_len = incoming_len;
2616                 }
2617         }
2618
2619         space_remaining = MGR_SHOW_TERMINAL_WIDTH - name_len - 4;
2620         if (space_remaining < 0) {
2621                 space_remaining = 0;
2622         }
2623
2624         ast_cli(a->fd, HSMC_FORMAT, name_len, name_len, "Action", space_remaining, "Synopsis");
2625         ast_cli(a->fd, HSMC_FORMAT, name_len, name_len, "------", space_remaining, "--------");
2626
2627         AST_RWLIST_TRAVERSE(&actions, cur, list) {
2628                 ast_cli(a->fd, HSMC_FORMAT, name_len, name_len, cur->action, space_remaining, cur->synopsis);
2629         }
2630         AST_RWLIST_UNLOCK(&actions);
2631
2632         return CLI_SUCCESS;
2633 }
2634
2635 /*! \brief CLI command manager list connected */
2636 static char *handle_showmanconn(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2637 {
2638         struct ao2_container *sessions;
2639         struct mansession_session *session;
2640         time_t now = time(NULL);
2641 #define HSMCONN_FORMAT1 "  %-15.15s  %-55.55s  %-10.10s  %-10.10s  %-8.8s  %-8.8s  %-5.5s  %-5.5s\n"
2642 #define HSMCONN_FORMAT2 "  %-15.15s  %-55.55s  %-10d  %-10d  %-8d  %-8d  %-5.5d  %-5.5d\n"
2643         int count = 0;
2644         struct ao2_iterator i;
2645
2646         switch (cmd) {
2647         case CLI_INIT:
2648                 e->command = "manager show connected";
2649                 e->usage =
2650                         "Usage: manager show connected\n"
2651                         "       Prints a listing of the users that are currently connected to the\n"
2652                         "Asterisk manager interface.\n";
2653                 return NULL;
2654         case CLI_GENERATE:
2655                 return NULL;
2656         }
2657
2658         ast_cli(a->fd, HSMCONN_FORMAT1, "Username", "IP Address", "Start", "Elapsed", "FileDes", "HttpCnt", "Read", "Write");
2659
2660         sessions = ao2_global_obj_ref(mgr_sessions);
2661         if (sessions) {
2662                 i = ao2_iterator_init(sessions, 0);
2663                 ao2_ref(sessions, -1);
2664                 while ((session = ao2_iterator_next(&i))) {
2665                         ao2_lock(session);
2666                         ast_cli(a->fd, HSMCONN_FORMAT2, session->username,
2667                                 ast_sockaddr_stringify_addr(&session->addr),
2668                                 (int) (session->sessionstart),
2669                                 (int) (now - session->sessionstart),
2670                                 session->stream ? ast_iostream_get_fd(session->stream) : -1,
2671                                 session->inuse,
2672                                 session->readperm,
2673                                 session->writeperm);
2674                         count++;
2675                         ao2_unlock(session);
2676                         unref_mansession(session);
2677                 }
2678                 ao2_iterator_destroy(&i);
2679         }
2680         ast_cli(a->fd, "%d users connected.\n", count);
2681
2682         return CLI_SUCCESS;
2683 }
2684
2685 /*! \brief CLI command manager list eventq */
2686 /* Should change to "manager show connected" */
2687 static char *handle_showmaneventq(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2688 {
2689         struct eventqent *s;
2690         switch (cmd) {
2691         case CLI_INIT:
2692                 e->command = "manager show eventq";
2693                 e->usage =
2694                         "Usage: manager show eventq\n"
2695                         "       Prints a listing of all events pending in the Asterisk manger\n"
2696                         "event queue.\n";
2697                 return NULL;
2698         case CLI_GENERATE:
2699                 return NULL;
2700         }
2701         AST_RWLIST_RDLOCK(&all_events);
2702         AST_RWLIST_TRAVERSE(&all_events, s, eq_next) {
2703                 ast_cli(a->fd, "Usecount: %d\n", s->usecount);
2704                 ast_cli(a->fd, "Category: %d\n", s->category);
2705                 ast_cli(a->fd, "Event:\n%s", s->eventdata);
2706         }
2707         AST_RWLIST_UNLOCK(&all_events);
2708
2709         return CLI_SUCCESS;
2710 }
2711
2712 static int reload_module(void);
2713
2714 /*! \brief CLI command manager reload */
2715 static char *handle_manager_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2716 {
2717         switch (cmd) {
2718         case CLI_INIT:
2719                 e->command = "manager reload";
2720                 e->usage =
2721                         "Usage: manager reload\n"
2722                         "       Reloads the manager configuration.\n";
2723                 return NULL;
2724         case CLI_GENERATE:
2725                 return NULL;
2726         }
2727         if (a->argc > 2) {
2728                 return CLI_SHOWUSAGE;
2729         }
2730         reload_module();
2731         return CLI_SUCCESS;
2732 }
2733
2734 static struct eventqent *advance_event(struct eventqent *e)
2735 {
2736         struct eventqent *next;
2737
2738         AST_RWLIST_RDLOCK(&all_events);
2739         if ((next = AST_RWLIST_NEXT(e, eq_next))) {
2740                 ast_atomic_fetchadd_int(&next->usecount, 1);
2741                 ast_atomic_fetchadd_int(&e->usecount, -1);
2742         }
2743         AST_RWLIST_UNLOCK(&all_events);
2744         return next;
2745 }
2746
2747 #define GET_HEADER_FIRST_MATCH  0
2748 #define GET_HEADER_LAST_MATCH   1
2749 #define GET_HEADER_SKIP_EMPTY   2
2750
2751 /*!
2752  * \brief Return a matching header value.
2753  *
2754  * \details
2755  * Generic function to return either the first or the last
2756  * matching header from a list of variables, possibly skipping
2757  * empty strings.
2758  *
2759  * \note At the moment there is only one use of this function in
2760  * this file, so we make it static.
2761  *
2762  * \note Never returns NULL.
2763  */
2764 static const char *__astman_get_header(const struct message *m, char *var, int mode)
2765 {
2766         int x, l = strlen(var);
2767         const char *result = "";
2768
2769         if (!m) {
2770                 return result;
2771         }
2772
2773         for (x = 0; x < m->hdrcount; x++) {
2774                 const char *h = m->headers[x];
2775                 if (!strncasecmp(var, h, l) && h[l] == ':') {
2776                         const char *value = h + l + 1;
2777                         value = ast_skip_blanks(value); /* ignore leading spaces in the value */
2778                         /* found a potential candidate */
2779                         if ((mode & GET_HEADER_SKIP_EMPTY) && ast_strlen_zero(value)) {
2780                                 continue;       /* not interesting */
2781                         }
2782                         if (mode & GET_HEADER_LAST_MATCH) {
2783                                 result = value; /* record the last match so far */
2784                         } else {
2785                                 return value;
2786                         }
2787                 }
2788         }
2789
2790         return result;
2791 }
2792
2793 /*!
2794  * \brief Return the first matching variable from an array.
2795  *
2796  * \note This is the legacy function and is implemented in
2797  * therms of __astman_get_header().
2798  *
2799  * \note Never returns NULL.
2800  */
2801 const char *astman_get_header(const struct message *m, char *var)
2802 {
2803         return __astman_get_header(m, var, GET_HEADER_FIRST_MATCH);
2804 }
2805
2806 /*!
2807  * \brief Append additional headers into the message structure from params.
2808  *
2809  * \note You likely want to initialize m->hdrcount to 0 before calling this.
2810  */
2811 static void astman_append_headers(struct message *m, const struct ast_variable *params)
2812 {
2813         const struct ast_variable *v;
2814
2815         for (v = params; v && m->hdrcount < ARRAY_LEN(m->headers); v = v->next) {
2816                 if (ast_asprintf((char**)&m->headers[m->hdrcount], "%s: %s", v->name, v->value) > -1) {
2817                         ++m->hdrcount;
2818                 }
2819         }
2820 }
2821
2822 /*!
2823  * \brief Free headers inside message structure, but not the message structure itself.
2824  */
2825 static void astman_free_headers(struct message *m)
2826 {
2827         while (m->hdrcount) {
2828                 --m->hdrcount;
2829                 ast_free((void *) m->headers[m->hdrcount]);
2830                 m->headers[m->hdrcount] = NULL;
2831         }
2832 }
2833
2834 /*!
2835  * \internal
2836  * \brief Process one "Variable:" header value string.
2837  *
2838  * \param head Current list of AMI variables to get new values added.
2839  * \param hdr_val Header value string to process.
2840  *
2841  * \return New variable list head.
2842  */
2843 static struct ast_variable *man_do_variable_value(struct ast_variable *head, const char *hdr_val)
2844 {
2845         char *parse;
2846         AST_DECLARE_APP_ARGS(args,
2847                 AST_APP_ARG(vars)[64];
2848         );
2849
2850         hdr_val = ast_skip_blanks(hdr_val); /* ignore leading spaces in the value */
2851         parse = ast_strdupa(hdr_val);
2852
2853         /* Break the header value string into name=val pair items. */
2854         AST_STANDARD_APP_ARGS(args, parse);
2855         if (args.argc) {
2856                 int y;
2857
2858                 /* Process each name=val pair item. */
2859                 for (y = 0; y < args.argc; y++) {
2860                         struct ast_variable *cur;
2861                         char *var;
2862                         char *val;
2863
2864                         if (!args.vars[y]) {
2865                                 continue;
2866                         }
2867                         var = val = args.vars[y];
2868                         strsep(&val, "=");
2869
2870                         /* XXX We may wish to trim whitespace from the strings. */
2871                         if (!val || ast_strlen_zero(var)) {
2872                                 continue;
2873                         }
2874
2875                         /* Create new variable list node and prepend it to the list. */
2876                         cur = ast_variable_new(var, val, "");
2877                         if (cur) {
2878                                 cur->next = head;
2879                                 head = cur;
2880                         }
2881                 }
2882         }
2883
2884         return head;
2885 }
2886
2887 struct ast_variable *astman_get_variables(const struct message *m)
2888 {
2889         return astman_get_variables_order(m, ORDER_REVERSE);
2890 }
2891
2892 struct ast_variable *astman_get_variables_order(const struct message *m,
2893         enum variable_orders order)
2894 {
2895         int varlen;
2896         int x;
2897         struct ast_variable *head = NULL;
2898
2899         static const char var_hdr[] = "Variable:";
2900
2901         /* Process all "Variable:" headers. */
2902         varlen = strlen(var_hdr);
2903         for (x = 0; x < m->hdrcount; x++) {
2904                 if (strncasecmp(var_hdr, m->headers[x], varlen)) {
2905                         continue;
2906                 }
2907                 head = man_do_variable_value(head, m->headers[x] + varlen);
2908         }
2909
2910         if (order == ORDER_NATURAL) {
2911                 head = ast_variables_reverse(head);
2912         }
2913
2914         return head;
2915 }
2916
2917 /*! \brief access for hooks to send action messages to ami */
2918 int ast_hook_send_action(struct manager_custom_hook *hook, const char *msg)
2919 {
2920         const char *action;
2921         int ret = 0;
2922         struct manager_action *act_found;
2923         struct mansession s = {.session = NULL, };
2924         struct message m = { 0 };
2925         char *dup_str;
2926         char *src;
2927         int x = 0;
2928         int curlen;
2929
2930         if (hook == NULL) {
2931                 return -1;
2932         }
2933
2934         /* Create our own copy of the AMI action msg string. */
2935         src = dup_str = ast_strdup(msg);
2936         if (!dup_str) {
2937                 return -1;
2938         }
2939
2940         /* convert msg string to message struct */
2941         curlen = strlen(src);
2942         for (x = 0; x < curlen; x++) {
2943                 int cr; /* set if we have \r */
2944                 if (src[x] == '\r' && x+1 < curlen && src[x+1] == '\n')
2945                         cr = 2; /* Found. Update length to include \r\n */
2946                 else if (src[x] == '\n')
2947                         cr = 1; /* also accept \n only */
2948                 else
2949                         continue;
2950                 /* don't keep empty lines */
2951                 if (x && m.hdrcount < ARRAY_LEN(m.headers)) {
2952                         /* ... but trim \r\n and terminate the header string */
2953                         src[x] = '\0';
2954                         m.headers[m.hdrcount++] = src;
2955                 }
2956                 x += cr;
2957                 curlen -= x;            /* remaining size */
2958                 src += x;               /* update pointer */
2959                 x = -1;                 /* reset loop */
2960         }
2961
2962         action = astman_get_header(&m, "Action");
2963
2964         do {
2965                 if (!strcasecmp(action, "login")) {
2966                         break;
2967                 }
2968
2969                 act_found = action_find(action);
2970                 if (!act_found) {
2971                         break;
2972                 }
2973
2974                 /*
2975                  * we have to simulate a session for this action request
2976                  * to be able to pass it down for processing
2977                  * This is necessary to meet the previous design of manager.c
2978                  */
2979                 s.hook = hook;
2980
2981                 ret = -1;
2982                 ao2_lock(act_found);
2983                 if (act_found->registered && act_found->func) {
2984                         struct ast_module *mod_ref = ast_module_running_ref(act_found->module);
2985
2986                         ao2_unlock(act_found);
2987                         /* If the action is in a module it must be running. */
2988                         if (!act_found->module || mod_ref) {
2989                                 ret = act_found->func(&s, &m);
2990                                 ast_module_unref(mod_ref);
2991                         }
2992                 } else {
2993                         ao2_unlock(act_found);
2994                 }
2995                 ao2_t_ref(act_found, -1, "done with found action object");
2996         } while (0);
2997
2998         ast_free(dup_str);
2999         return ret;
3000 }
3001
3002 /*!
3003  * helper function to send a string to the socket.
3004  * Return -1 on error (e.g. buffer full).
3005  */
3006 static int send_string(struct mansession *s, char *string)
3007 {
3008         struct ast_iostream *stream;
3009         int len, res;
3010
3011         /* It's a result from one of the hook's action invocation */
3012         if (s->hook) {
3013                 /*
3014                  * to send responses, we're using the same function
3015                  * as for receiving events. We call the event "HookResponse"
3016                  */
3017                 s->hook->helper(EVENT_FLAG_HOOKRESPONSE, "HookResponse", string);
3018                 return 0;
3019         }
3020
3021         stream = s->stream ? s->stream : s->session->stream;
3022
3023         len = strlen(string);
3024         ast_iostream_set_timeout_inactivity(stream, s->session->writetimeout);
3025         res = ast_iostream_write(stream, string, len);
3026         ast_iostream_set_timeout_disable(stream);
3027
3028         if (res < len) {
3029                 s->write_error = 1;
3030         }
3031
3032         return res;
3033 }
3034
3035 /*!
3036  * \brief thread local buffer for astman_append
3037  *
3038  * \note This can not be defined within the astman_append() function
3039  *       because it declares a couple of functions that get used to
3040  *       initialize the thread local storage key.
3041  */
3042 AST_THREADSTORAGE(astman_append_buf);
3043
3044 AST_THREADSTORAGE(userevent_buf);
3045
3046 /*! \brief initial allocated size for the astman_append_buf and astman_send_*_va */
3047 #define ASTMAN_APPEND_BUF_INITSIZE   256
3048
3049 /*!
3050  * utility functions for creating AMI replies
3051  */
3052 void astman_append(struct mansession *s, const char *fmt, ...)
3053 {
3054         int res;
3055         va_list ap;
3056         struct ast_str *buf;
3057
3058         if (!(buf = ast_str_thread_get(&astman_append_buf, ASTMAN_APPEND_BUF_INITSIZE))) {
3059                 return;
3060         }
3061
3062         va_start(ap, fmt);
3063         res = ast_str_set_va(&buf, 0, fmt, ap);
3064         va_end(ap);
3065         if (res == AST_DYNSTR_BUILD_FAILED) {
3066                 return;
3067         }
3068
3069         if (s->hook || (s->tcptls_session != NULL && s->tcptls_session->stream != NULL)) {
3070                 send_string(s, ast_str_buffer(buf));
3071         } else {
3072                 ast_verbose("No connection stream in astman_append, should not happen\n");
3073         }
3074 }
3075
3076 /*! \note NOTE: XXX this comment is unclear and possibly wrong.
3077    Callers of astman_send_error(), astman_send_response() or astman_send_ack() must EITHER
3078    hold the session lock _or_ be running in an action callback (in which case s->session->busy will
3079    be non-zero). In either of these cases, there is no need to lock-protect the session's
3080    fd, since no other output will be sent (events will be queued), and no input will
3081    be read until either the current action finishes or get_input() obtains the session
3082    lock.
3083  */
3084
3085 /*! \todo XXX MSG_MOREDATA should go to a header file. */
3086 #define MSG_MOREDATA    ((char *)astman_send_response)
3087
3088 /*! \brief send a response with an optional message,
3089  * and terminate it with an empty line.
3090  * m is used only to grab the 'ActionID' field.
3091  *
3092  * Use the explicit constant MSG_MOREDATA to remove the empty line.
3093  * XXX MSG_MOREDATA should go to a header file.
3094  */
3095 static void astman_send_response_full(struct mansession *s, const struct message *m, char *resp, char *msg, char *listflag)
3096 {
3097         const char *id = astman_get_header(m, "ActionID");
3098
3099         astman_append(s, "Response: %s\r\n", resp);
3100         if (!ast_strlen_zero(id)) {
3101                 astman_append(s, "ActionID: %s\r\n", id);
3102         }
3103         if (listflag) {
3104                 astman_append(s, "EventList: %s\r\n", listflag);        /* Start, complete, cancelled */
3105         }
3106         if (msg == MSG_MOREDATA) {
3107                 return;
3108         } else if (msg) {
3109                 astman_append(s, "Message: %s\r\n\r\n", msg);
3110         } else {
3111                 astman_append(s, "\r\n");
3112         }
3113 }
3114
3115 void astman_send_response(struct mansession *s, const struct message *m, char *resp, char *msg)
3116 {
3117         astman_send_response_full(s, m, resp, msg, NULL);
3118 }
3119
3120 void astman_send_error(struct mansession *s, const struct message *m, char *error)
3121 {
3122         astman_send_response_full(s, m, "Error", error, NULL);
3123 }
3124
3125 void astman_send_error_va(struct mansession *s, const struct message *m, const char *fmt, ...)
3126 {
3127         int res;
3128         va_list ap;
3129         struct ast_str *buf;
3130         char *msg;
3131
3132         if (!(buf = ast_str_thread_get(&astman_append_buf, ASTMAN_APPEND_BUF_INITSIZE))) {
3133                 return;
3134         }
3135
3136         va_start(ap, fmt);
3137         res = ast_str_set_va(&buf, 0, fmt, ap);
3138         va_end(ap);
3139         if (res == AST_DYNSTR_BUILD_FAILED) {
3140                 return;
3141         }
3142
3143         /* astman_append will use the same underlying buffer, so copy the message out
3144          * before sending the response */
3145         msg = ast_str_buffer(buf);
3146         if (msg) {
3147                 msg = ast_strdupa(msg);
3148         }
3149         astman_send_response_full(s, m, "Error", msg, NULL);
3150 }
3151
3152 void astman_send_ack(struct mansession *s, const struct message *m, char *msg)
3153 {
3154         astman_send_response_full(s, m, "Success", msg, NULL);
3155 }
3156
3157 static void astman_start_ack(struct mansession *s, const struct message *m)
3158 {
3159         astman_send_response_full(s, m, "Success", MSG_MOREDATA, NULL);
3160 }
3161
3162 void astman_send_listack(struct mansession *s, const struct message *m, char *msg, char *listflag)
3163 {
3164         astman_send_response_full(s, m, "Success", msg, listflag);
3165 }
3166
3167 void astman_send_list_complete_start(struct mansession *s, const struct message *m, const char *event_name, int count)
3168 {
3169         const char *id = astman_get_header(m, "ActionID");
3170
3171         astman_append(s, "Event: %s\r\n", event_name);
3172         if (!ast_strlen_zero(id)) {
3173                 astman_append(s, "ActionID: %s\r\n", id);
3174         }
3175         astman_append(s,
3176                 "EventList: Complete\r\n"
3177                 "ListItems: %d\r\n",
3178                 count);
3179 }
3180
3181 void astman_send_list_complete_end(struct mansession *s)
3182 {
3183         astman_append(s, "\r\n");
3184 }
3185
3186 /*! \brief Lock the 'mansession' structure. */
3187 static void mansession_lock(struct mansession *s)
3188 {
3189         ast_mutex_lock(&s->lock);
3190 }
3191
3192 /*! \brief Unlock the 'mansession' structure. */
3193 static void mansession_unlock(struct mansession *s)
3194 {
3195         ast_mutex_unlock(&s->lock);
3196 }
3197
3198 /*! \brief
3199    Rather than braindead on,off this now can also accept a specific int mask value
3200    or a ',' delim list of mask strings (the same as manager.conf) -anthm
3201 */
3202 static int set_eventmask(struct mansession *s, const char *eventmask)
3203 {
3204         int maskint = strings_to_mask(eventmask);
3205
3206         ao2_lock(s->session);
3207         if (maskint >= 0) {
3208                 s->session->send_events = maskint;
3209         }
3210         ao2_unlock(s->session);
3211
3212         return maskint;
3213 }
3214
3215 static enum ast_transport mansession_get_transport(const struct mansession *s)
3216 {
3217         return s->tcptls_session->parent->tls_cfg ? AST_TRANSPORT_TLS :
3218                         AST_TRANSPORT_TCP;
3219 }
3220
3221 static void report_invalid_user(const struct mansession *s, const char *username)
3222 {
3223         char session_id[32];
3224         struct ast_security_event_inval_acct_id inval_acct_id = {
3225                 .common.event_type = AST_SECURITY_EVENT_INVAL_ACCT_ID,
3226                 .common.version    = AST_SECURITY_EVENT_INVAL_ACCT_ID_VERSION,
3227                 .common.service    = "AMI",
3228                 .common.account_id = username,
3229                 .common.session_tv = &s->session->sessionstart_tv,
3230                 .common.local_addr = {
3231                         .addr      = &s->tcptls_session->parent->local_address,
3232                         .transport = mansession_get_transport(s),
3233                 },
3234                 .common.remote_addr = {
3235                         .addr      = &s->session->addr,
3236                         .transport = mansession_get_transport(s),
3237                 },
3238                 .common.session_id = session_id,
3239         };
3240
3241         snprintf(session_id, sizeof(session_id), "%p", s);
3242
3243         ast_security_event_report(AST_SEC_EVT(&inval_acct_id));
3244 }
3245
3246 static void report_failed_acl(const struct mansession *s, const char *username)
3247 {
3248         char session_id[32];
3249         struct ast_security_event_failed_acl failed_acl_event = {
3250                 .common.event_type = AST_SECURITY_EVENT_FAILED_ACL,
3251                 .common.version    = AST_SECURITY_EVENT_FAILED_ACL_VERSION,
3252                 .common.service    = "AMI",
3253                 .common.account_id = username,
3254                 .common.session_tv = &s->session->sessionstart_tv,
3255                 .common.local_addr = {
3256                         .addr      = &s->tcptls_session->parent->local_address,
3257                         .transport = mansession_get_transport(s),
3258                 },
3259                 .common.remote_addr = {
3260                         .addr      = &s->session->addr,
3261                         .transport = mansession_get_transport(s),
3262                 },
3263                 .common.session_id = session_id,
3264         };
3265
3266         snprintf(session_id, sizeof(session_id), "%p", s->session);
3267
3268         ast_security_event_report(AST_SEC_EVT(&failed_acl_event));
3269 }
3270
3271 static void report_inval_password(const struct mansession *s, const char *username)
3272 {
3273         char session_id[32];
3274         struct ast_security_event_inval_password inval_password = {
3275                 .common.event_type = AST_SECURITY_EVENT_INVAL_PASSWORD,
3276                 .common.version    = AST_SECURITY_EVENT_INVAL_PASSWORD_VERSION,
3277                 .common.service    = "AMI",
3278                 .common.account_id = username,
3279                 .common.session_tv = &s->session->sessionstart_tv,
3280                 .common.local_addr = {
3281                         .addr      = &s->tcptls_session->parent->local_address,
3282                         .transport = mansession_get_transport(s),
3283                 },
3284                 .common.remote_addr = {
3285                         .addr      = &s->session->addr,
3286                         .transport = mansession_get_transport(s),
3287                 },
3288                 .common.session_id = session_id,
3289         };
3290
3291         snprintf(session_id, sizeof(session_id), "%p", s->session);
3292
3293         ast_security_event_report(AST_SEC_EVT(&inval_password));
3294 }
3295
3296 static void report_auth_success(const struct mansession *s)
3297 {
3298         char session_id[32];
3299         struct ast_security_event_successful_auth successful_auth = {
3300                 .common.event_type = AST_SECURITY_EVENT_SUCCESSFUL_AUTH,
3301                 .common.version    = AST_SECURITY_EVENT_SUCCESSFUL_AUTH_VERSION,
3302                 .common.service    = "AMI",
3303                 .common.account_id = s->session->username,
3304                 .common.session_tv = &s->session->sessionstart_tv,
3305                 .common.local_addr = {
3306                         .addr      = &s->tcptls_session->parent->local_address,
3307                         .transport = mansession_get_transport(s),
3308                 },
3309                 .common.remote_addr = {
3310                         .addr      = &s->session->addr,
3311                         .transport = mansession_get_transport(s),
3312                 },
3313                 .common.session_id = session_id,
3314         };
3315
3316         snprintf(session_id, sizeof(session_id), "%p", s->session);
3317
3318         ast_security_event_report(AST_SEC_EVT(&successful_auth));
3319 }
3320
3321 static void report_req_not_allowed(const struct mansession *s, const char *action)
3322 {
3323         char session_id[32];
3324         char request_type[64];
3325         struct ast_security_event_req_not_allowed req_not_allowed = {
3326                 .common.event_type = AST_SECURITY_EVENT_REQ_NOT_ALLOWED,
3327                 .common.version    = AST_SECURITY_EVENT_REQ_NOT_ALLOWED_VERSION,
3328                 .common.service    = "AMI",
3329                 .common.account_id = s->session->username,
3330                 .common.session_tv = &s->session->sessionstart_tv,
3331                 .common.local_addr = {
3332                         .addr      = &s->tcptls_session->parent->local_address,
3333                         .transport = mansession_get_transport(s),
3334                 },
3335                 .common.remote_addr = {
3336                         .addr      = &s->session->addr,
3337                         .transport = mansession_get_transport(s),
3338                 },
3339                 .common.session_id = session_id,
3340
3341                 .request_type      = request_type,
3342         };
3343
3344         snprintf(session_id, sizeof(session_id), "%p", s->session);
3345         snprintf(request_type, sizeof(request_type), "Action: %s", action);
3346
3347         ast_security_event_report(AST_SEC_EVT(&req_not_allowed));
3348 }
3349
3350 static void report_req_bad_format(const struct mansession *s, const char *action)