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