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