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