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