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