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