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