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