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