build_system: Fix some warnings highlighted by clang
[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 enum add_filter_result manager_add_filter(const char *filter_pattern, struct ao2_container *whitefilters, struct ao2_container *blackfilters);
1553
1554 static int match_filter(struct mansession *s, char *eventdata);
1555
1556 /*!
1557  * @{ \brief Define AMI message types.
1558  */
1559 STASIS_MESSAGE_TYPE_DEFN(ast_manager_get_generic_type);
1560 /*! @} */
1561
1562 /*!
1563  * \internal
1564  * \brief Find a registered action object.
1565  *
1566  * \param name Name of AMI action to find.
1567  *
1568  * \return Reffed action found or NULL
1569  */
1570 static struct manager_action *action_find(const char *name)
1571 {
1572         struct manager_action *act;
1573
1574         AST_RWLIST_RDLOCK(&actions);
1575         AST_RWLIST_TRAVERSE(&actions, act, list) {
1576                 if (!strcasecmp(name, act->action)) {
1577                         ao2_t_ref(act, +1, "found action object");
1578                         break;
1579                 }
1580         }
1581         AST_RWLIST_UNLOCK(&actions);
1582
1583         return act;
1584 }
1585
1586 struct stasis_topic *ast_manager_get_topic(void)
1587 {
1588         return manager_topic;
1589 }
1590
1591 struct stasis_message_router *ast_manager_get_message_router(void)
1592 {
1593         return stasis_router;
1594 }
1595
1596 static void manager_json_value_str_append(struct ast_json *value, const char *key,
1597                                           struct ast_str **res)
1598 {
1599         switch (ast_json_typeof(value)) {
1600         case AST_JSON_STRING:
1601                 ast_str_append(res, 0, "%s: %s\r\n", key, ast_json_string_get(value));
1602                 break;
1603         case AST_JSON_INTEGER:
1604                 ast_str_append(res, 0, "%s: %jd\r\n", key, ast_json_integer_get(value));
1605                 break;
1606         case AST_JSON_TRUE:
1607                 ast_str_append(res, 0, "%s: True\r\n", key);
1608                 break;
1609         case AST_JSON_FALSE:
1610                 ast_str_append(res, 0, "%s: False\r\n", key);
1611                 break;
1612         default:
1613                 ast_str_append(res, 0, "%s: \r\n", key);
1614                 break;
1615         }
1616 }
1617
1618 static void manager_json_to_ast_str(struct ast_json *obj, const char *key,
1619                                     struct ast_str **res, key_exclusion_cb exclusion_cb);
1620
1621 static void manager_json_array_with_key(struct ast_json *obj, const char* key,
1622                                         size_t index, struct ast_str **res,
1623                                         key_exclusion_cb exclusion_cb)
1624 {
1625         struct ast_str *key_str = ast_str_alloca(64);
1626         ast_str_set(&key_str, 0, "%s(%zu)", key, index);
1627         manager_json_to_ast_str(obj, ast_str_buffer(key_str),
1628                                 res, exclusion_cb);
1629 }
1630
1631 static void manager_json_obj_with_key(struct ast_json *obj, const char* key,
1632                                       const char *parent_key, struct ast_str **res,
1633                                       key_exclusion_cb exclusion_cb)
1634 {
1635         if (parent_key) {
1636                 struct ast_str *key_str = ast_str_alloca(64);
1637                 ast_str_set(&key_str, 0, "%s/%s", parent_key, key);
1638                 manager_json_to_ast_str(obj, ast_str_buffer(key_str),
1639                                         res, exclusion_cb);
1640                 return;
1641         }
1642
1643         manager_json_to_ast_str(obj, key, res, exclusion_cb);
1644 }
1645
1646 void manager_json_to_ast_str(struct ast_json *obj, const char *key,
1647                              struct ast_str **res, key_exclusion_cb exclusion_cb)
1648 {
1649         struct ast_json_iter *i;
1650
1651         if (!obj || (!res && !(*res) && (!(*res = ast_str_create(1024))))) {
1652                 return;
1653         }
1654
1655         if (exclusion_cb && key && exclusion_cb(key)) {
1656                 return;
1657         }
1658
1659         if (ast_json_typeof(obj) != AST_JSON_OBJECT &&
1660             ast_json_typeof(obj) != AST_JSON_ARRAY) {
1661                 manager_json_value_str_append(obj, key, res);
1662                 return;
1663         }
1664
1665         if (ast_json_typeof(obj) == AST_JSON_ARRAY) {
1666                 size_t j;
1667                 for (j = 0; j < ast_json_array_size(obj); ++j) {
1668                         manager_json_array_with_key(ast_json_array_get(obj, j),
1669                                                     key, j, res, exclusion_cb);
1670                 }
1671                 return;
1672         }
1673
1674         for (i = ast_json_object_iter(obj); i;
1675              i = ast_json_object_iter_next(obj, i)) {
1676                 manager_json_obj_with_key(ast_json_object_iter_value(i),
1677                                           ast_json_object_iter_key(i),
1678                                           key, res, exclusion_cb);
1679         }
1680 }
1681
1682
1683 struct ast_str *ast_manager_str_from_json_object(struct ast_json *blob, key_exclusion_cb exclusion_cb)
1684 {
1685         struct ast_str *res = ast_str_create(1024);
1686         manager_json_to_ast_str(blob, NULL, &res, exclusion_cb);
1687         return res;
1688 }
1689
1690 static void manager_default_msg_cb(void *data, struct stasis_subscription *sub,
1691                                     struct stasis_message *message)
1692 {
1693         RAII_VAR(struct ast_manager_event_blob *, ev, NULL, ao2_cleanup);
1694
1695         ev = stasis_message_to_ami(message);
1696
1697         if (ev == NULL) {
1698                 /* Not and AMI message; disregard */
1699                 return;
1700         }
1701
1702         manager_event(ev->event_flags, ev->manager_event, "%s",
1703                 ev->extra_fields);
1704 }
1705
1706 static void manager_generic_msg_cb(void *data, struct stasis_subscription *sub,
1707                                     struct stasis_message *message)
1708 {
1709         struct ast_json_payload *payload = stasis_message_data(message);
1710         int class_type = ast_json_integer_get(ast_json_object_get(payload->json, "class_type"));
1711         const char *type = ast_json_string_get(ast_json_object_get(payload->json, "type"));
1712         struct ast_json *event = ast_json_object_get(payload->json, "event");
1713         RAII_VAR(struct ast_str *, event_buffer, NULL, ast_free);
1714
1715         event_buffer = ast_manager_str_from_json_object(event, NULL);
1716         if (!event_buffer) {
1717                 ast_log(AST_LOG_WARNING, "Error while creating payload for event %s\n", type);
1718                 return;
1719         }
1720         manager_event(class_type, type, "%s", ast_str_buffer(event_buffer));
1721 }
1722
1723 void ast_manager_publish_event(const char *type, int class_type, struct ast_json *obj)
1724 {
1725         RAII_VAR(struct ast_json *, event_info, NULL, ast_json_unref);
1726         RAII_VAR(struct ast_json_payload *, payload, NULL, ao2_cleanup);
1727         RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
1728
1729         if (!obj || !ast_manager_get_generic_type()) {
1730                 return;
1731         }
1732
1733         ast_json_ref(obj);
1734         event_info = ast_json_pack("{s: s, s: i, s: o}",
1735                         "type", type,
1736                         "class_type", class_type,
1737                         "event", obj);
1738         if (!event_info) {
1739                 return;
1740         }
1741
1742         payload = ast_json_payload_create(event_info);
1743         if (!payload) {
1744                 return;
1745         }
1746         message = stasis_message_create(ast_manager_get_generic_type(), payload);
1747         if (!message) {
1748                 return;
1749         }
1750         stasis_publish(ast_manager_get_topic(), message);
1751 }
1752
1753 /*! \brief Add a custom hook to be called when an event is fired */
1754 void ast_manager_register_hook(struct manager_custom_hook *hook)
1755 {
1756         AST_RWLIST_WRLOCK(&manager_hooks);
1757         AST_RWLIST_INSERT_TAIL(&manager_hooks, hook, list);
1758         AST_RWLIST_UNLOCK(&manager_hooks);
1759 }
1760
1761 /*! \brief Delete a custom hook to be called when an event is fired */
1762 void ast_manager_unregister_hook(struct manager_custom_hook *hook)
1763 {
1764         AST_RWLIST_WRLOCK(&manager_hooks);
1765         AST_RWLIST_REMOVE(&manager_hooks, hook, list);
1766         AST_RWLIST_UNLOCK(&manager_hooks);
1767 }
1768
1769 int check_manager_enabled(void)
1770 {
1771         return manager_enabled;
1772 }
1773
1774 int check_webmanager_enabled(void)
1775 {
1776         return (webmanager_enabled && manager_enabled);
1777 }
1778
1779 /*!
1780  * Grab a reference to the last event, update usecount as needed.
1781  * Can handle a NULL pointer.
1782  */
1783 static struct eventqent *grab_last(void)
1784 {
1785         struct eventqent *ret;
1786
1787         AST_RWLIST_WRLOCK(&all_events);
1788         ret = AST_RWLIST_LAST(&all_events);
1789         /* the list is never empty now, but may become so when
1790          * we optimize it in the future, so be prepared.
1791          */
1792         if (ret) {
1793                 ast_atomic_fetchadd_int(&ret->usecount, 1);
1794         }
1795         AST_RWLIST_UNLOCK(&all_events);
1796         return ret;
1797 }
1798
1799 /*!
1800  * Purge unused events. Remove elements from the head
1801  * as long as their usecount is 0 and there is a next element.
1802  */
1803 static void purge_events(void)
1804 {
1805         struct eventqent *ev;
1806         struct timeval now = ast_tvnow();
1807
1808         AST_RWLIST_WRLOCK(&all_events);
1809         while ( (ev = AST_RWLIST_FIRST(&all_events)) &&
1810             ev->usecount == 0 && AST_RWLIST_NEXT(ev, eq_next)) {
1811                 AST_RWLIST_REMOVE_HEAD(&all_events, eq_next);
1812                 ast_free(ev);
1813         }
1814
1815         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&all_events, ev, eq_next) {
1816                 /* Never release the last event */
1817                 if (!AST_RWLIST_NEXT(ev, eq_next)) {
1818                         break;
1819                 }
1820
1821                 /* 2.5 times whatever the HTTP timeout is (maximum 2.5 hours) is the maximum time that we will definitely cache an event */
1822                 if (ev->usecount == 0 && ast_tvdiff_sec(now, ev->tv) > (httptimeout > 3600 ? 3600 : httptimeout) * 2.5) {
1823                         AST_RWLIST_REMOVE_CURRENT(eq_next);
1824                         ast_free(ev);
1825                 }
1826         }
1827         AST_RWLIST_TRAVERSE_SAFE_END;
1828         AST_RWLIST_UNLOCK(&all_events);
1829 }
1830
1831 /*!
1832  * helper functions to convert back and forth between
1833  * string and numeric representation of set of flags
1834  */
1835 static const struct permalias {
1836         int num;
1837         const char *label;
1838 } perms[] = {
1839         { EVENT_FLAG_SYSTEM, "system" },
1840         { EVENT_FLAG_CALL, "call" },
1841         { EVENT_FLAG_LOG, "log" },
1842         { EVENT_FLAG_VERBOSE, "verbose" },
1843         { EVENT_FLAG_COMMAND, "command" },
1844         { EVENT_FLAG_AGENT, "agent" },
1845         { EVENT_FLAG_USER, "user" },
1846         { EVENT_FLAG_CONFIG, "config" },
1847         { EVENT_FLAG_DTMF, "dtmf" },
1848         { EVENT_FLAG_REPORTING, "reporting" },
1849         { EVENT_FLAG_CDR, "cdr" },
1850         { EVENT_FLAG_DIALPLAN, "dialplan" },
1851         { EVENT_FLAG_ORIGINATE, "originate" },
1852         { EVENT_FLAG_AGI, "agi" },
1853         { EVENT_FLAG_CC, "cc" },
1854         { EVENT_FLAG_AOC, "aoc" },
1855         { EVENT_FLAG_TEST, "test" },
1856         { EVENT_FLAG_SECURITY, "security" },
1857         { EVENT_FLAG_MESSAGE, "message" },
1858         { INT_MAX, "all" },
1859         { 0, "none" },
1860 };
1861
1862 /*! Maximum string length of the AMI authority permission string buildable from perms[]. */
1863 #define MAX_AUTH_PERM_STRING    150
1864
1865 /*! \brief Checks to see if a string which can be used to evaluate functions should be rejected */
1866 static int function_capable_string_allowed_with_auths(const char *evaluating, int writepermlist)
1867 {
1868         if (!(writepermlist & EVENT_FLAG_SYSTEM)
1869                 && (
1870                         strstr(evaluating, "SHELL") ||       /* NoOp(${SHELL(rm -rf /)})  */
1871                         strstr(evaluating, "EVAL")           /* NoOp(${EVAL(${some_var_containing_SHELL})}) */
1872                 )) {
1873                 return 0;
1874         }
1875         return 1;
1876 }
1877
1878 /*! \brief Convert authority code to a list of options for a user. This will only
1879  * display those authority codes that have an explicit match on authority */
1880 static const char *user_authority_to_str(int authority, struct ast_str **res)
1881 {
1882         int i;
1883         char *sep = "";
1884
1885         ast_str_reset(*res);
1886         for (i = 0; i < ARRAY_LEN(perms) - 1; i++) {
1887                 if ((authority & perms[i].num) == perms[i].num) {
1888                         ast_str_append(res, 0, "%s%s", sep, perms[i].label);
1889                         sep = ",";
1890                 }
1891         }
1892
1893         if (ast_str_strlen(*res) == 0) {
1894                 /* replace empty string with something sensible */
1895                 ast_str_append(res, 0, "<none>");
1896         }
1897
1898         return ast_str_buffer(*res);
1899 }
1900
1901
1902 /*! \brief Convert authority code to a list of options. Note that the EVENT_FLAG_ALL
1903  * authority will always be returned. */
1904 static const char *authority_to_str(int authority, struct ast_str **res)
1905 {
1906         int i;
1907         char *sep = "";
1908
1909         ast_str_reset(*res);
1910         if (authority != EVENT_FLAG_SHUTDOWN) {
1911                 for (i = 0; i < ARRAY_LEN(perms) - 1; i++) {
1912                         if (authority & perms[i].num) {
1913                                 ast_str_append(res, 0, "%s%s", sep, perms[i].label);
1914                                 sep = ",";
1915                         }
1916                 }
1917         }
1918
1919         if (ast_str_strlen(*res) == 0) {
1920                 /* replace empty string with something sensible */
1921                 ast_str_append(res, 0, "<none>");
1922         }
1923
1924         return ast_str_buffer(*res);
1925 }
1926
1927 /*! Tells you if smallstr exists inside bigstr
1928    which is delim by delim and uses no buf or stringsep
1929    ast_instring("this|that|more","this",'|') == 1;
1930
1931    feel free to move this to app.c -anthm */
1932 static int ast_instring(const char *bigstr, const char *smallstr, const char delim)
1933 {
1934         const char *val = bigstr, *next;
1935
1936         do {
1937                 if ((next = strchr(val, delim))) {
1938                         if (!strncmp(val, smallstr, (next - val))) {
1939                                 return 1;
1940                         } else {
1941                                 continue;
1942                         }
1943                 } else {
1944                         return !strcmp(smallstr, val);
1945                 }
1946         } while (*(val = (next + 1)));
1947
1948         return 0;
1949 }
1950
1951 static int get_perm(const char *instr)
1952 {
1953         int x = 0, ret = 0;
1954
1955         if (!instr) {
1956                 return 0;
1957         }
1958
1959         for (x = 0; x < ARRAY_LEN(perms); x++) {
1960                 if (ast_instring(instr, perms[x].label, ',')) {
1961                         ret |= perms[x].num;
1962                 }
1963         }
1964
1965         return ret;
1966 }
1967
1968 /*!
1969  * A number returns itself, false returns 0, true returns all flags,
1970  * other strings return the flags that are set.
1971  */
1972 static int strings_to_mask(const char *string)
1973 {
1974         const char *p;
1975
1976         if (ast_strlen_zero(string)) {
1977                 return -1;
1978         }
1979
1980         for (p = string; *p; p++) {
1981                 if (*p < '0' || *p > '9') {
1982                         break;
1983                 }
1984         }
1985         if (!*p) { /* all digits */
1986                 return atoi(string);
1987         }
1988         if (ast_false(string)) {
1989                 return 0;
1990         }
1991         if (ast_true(string)) { /* all permissions */
1992                 int x, ret = 0;
1993                 for (x = 0; x < ARRAY_LEN(perms); x++) {
1994                         ret |= perms[x].num;
1995                 }
1996                 return ret;
1997         }
1998         return get_perm(string);
1999 }
2000
2001 /*! \brief Unreference manager session object.
2002      If no more references, then go ahead and delete it */
2003 static struct mansession_session *unref_mansession(struct mansession_session *s)
2004 {
2005         int refcount = ao2_ref(s, -1);
2006         if (manager_debug) {
2007                 ast_debug(1, "Mansession: %p refcount now %d\n", s, refcount - 1);
2008         }
2009         return NULL;
2010 }
2011
2012 static void event_filter_destructor(void *obj)
2013 {
2014         regex_t *regex_filter = obj;
2015         regfree(regex_filter);
2016 }
2017
2018 static void session_destructor(void *obj)
2019 {
2020         struct mansession_session *session = obj;
2021         struct eventqent *eqe = session->last_ev;
2022         struct ast_datastore *datastore;
2023
2024         /* Get rid of each of the data stores on the session */
2025         while ((datastore = AST_LIST_REMOVE_HEAD(&session->datastores, entry))) {
2026                 /* Free the data store */
2027                 ast_datastore_free(datastore);
2028         }
2029
2030         if (session->f != NULL) {
2031                 fflush(session->f);
2032                 fclose(session->f);
2033         }
2034         if (eqe) {
2035                 ast_atomic_fetchadd_int(&eqe->usecount, -1);
2036         }
2037         if (session->chanvars) {
2038                 ast_variables_destroy(session->chanvars);
2039         }
2040
2041         if (session->whitefilters) {
2042                 ao2_t_ref(session->whitefilters, -1, "decrement ref for white container, should be last one");
2043         }
2044
2045         if (session->blackfilters) {
2046                 ao2_t_ref(session->blackfilters, -1, "decrement ref for black container, should be last one");
2047         }
2048 }
2049
2050 /*! \brief Allocate manager session structure and add it to the list of sessions */
2051 static struct mansession_session *build_mansession(const struct ast_sockaddr *addr)
2052 {
2053         struct ao2_container *sessions;
2054         struct mansession_session *newsession;
2055
2056         newsession = ao2_alloc(sizeof(*newsession), session_destructor);
2057         if (!newsession) {
2058                 return NULL;
2059         }
2060
2061         newsession->whitefilters = ao2_container_alloc(1, NULL, NULL);
2062         newsession->blackfilters = ao2_container_alloc(1, NULL, NULL);
2063         if (!newsession->whitefilters || !newsession->blackfilters) {
2064                 ao2_ref(newsession, -1);
2065                 return NULL;
2066         }
2067
2068         newsession->fd = -1;
2069         newsession->waiting_thread = AST_PTHREADT_NULL;
2070         newsession->writetimeout = 100;
2071         newsession->send_events = -1;
2072         ast_sockaddr_copy(&newsession->addr, addr);
2073
2074         sessions = ao2_global_obj_ref(mgr_sessions);
2075         if (sessions) {
2076                 ao2_link(sessions, newsession);
2077                 ao2_ref(sessions, -1);
2078         }
2079
2080         return newsession;
2081 }
2082
2083 static int mansession_cmp_fn(void *obj, void *arg, int flags)
2084 {
2085         struct mansession_session *s = obj;
2086         char *str = arg;
2087         return !strcasecmp(s->username, str) ? CMP_MATCH : 0;
2088 }
2089
2090 static void session_destroy(struct mansession_session *s)
2091 {
2092         struct ao2_container *sessions;
2093
2094         sessions = ao2_global_obj_ref(mgr_sessions);
2095         if (sessions) {
2096                 ao2_unlink(sessions, s);
2097                 ao2_ref(sessions, -1);
2098         }
2099         unref_mansession(s);
2100 }
2101
2102
2103 static int check_manager_session_inuse(const char *name)
2104 {
2105         struct ao2_container *sessions;
2106         struct mansession_session *session;
2107         int inuse = 0;
2108
2109         sessions = ao2_global_obj_ref(mgr_sessions);
2110         if (sessions) {
2111                 session = ao2_find(sessions, (char *) name, 0);
2112                 ao2_ref(sessions, -1);
2113                 if (session) {
2114                         unref_mansession(session);
2115                         inuse = 1;
2116                 }
2117         }
2118         return inuse;
2119 }
2120
2121
2122 /*!
2123  * lookup an entry in the list of registered users.
2124  * must be called with the list lock held.
2125  */
2126 static struct ast_manager_user *get_manager_by_name_locked(const char *name)
2127 {
2128         struct ast_manager_user *user = NULL;
2129
2130         AST_RWLIST_TRAVERSE(&users, user, list) {
2131                 if (!strcasecmp(user->username, name)) {
2132                         break;
2133                 }
2134         }
2135
2136         return user;
2137 }
2138
2139 /*! \brief Get displayconnects config option.
2140  *  \param session manager session to get parameter from.
2141  *  \return displayconnects config option value.
2142  */
2143 static int manager_displayconnects(struct mansession_session *session)
2144 {
2145         struct ast_manager_user *user = NULL;
2146         int ret = 0;
2147
2148         AST_RWLIST_RDLOCK(&users);
2149         if ((user = get_manager_by_name_locked(session->username))) {
2150                 ret = user->displayconnects;
2151         }
2152         AST_RWLIST_UNLOCK(&users);
2153
2154         return ret;
2155 }
2156
2157 static void print_event_instance(struct ast_cli_args *a, struct ast_xml_doc_item *instance);
2158
2159 static char *handle_showmancmd(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2160 {
2161         struct manager_action *cur;
2162         struct ast_str *authority;
2163         int num, l, which;
2164         const char *auth_str;
2165         char *ret = NULL;
2166 #ifdef AST_XML_DOCS
2167         char syntax_title[64], description_title[64], synopsis_title[64], seealso_title[64];
2168         char arguments_title[64], privilege_title[64], final_response_title[64], list_responses_title[64];
2169 #endif
2170
2171         switch (cmd) {
2172         case CLI_INIT:
2173                 e->command = "manager show command";
2174                 e->usage =
2175                         "Usage: manager show command <actionname> [<actionname> [<actionname> [...]]]\n"
2176                         "       Shows the detailed description for a specific Asterisk manager interface command.\n";
2177                 return NULL;
2178         case CLI_GENERATE:
2179                 l = strlen(a->word);
2180                 which = 0;
2181                 AST_RWLIST_RDLOCK(&actions);
2182                 AST_RWLIST_TRAVERSE(&actions, cur, list) {
2183                         if (!strncasecmp(a->word, cur->action, l) && ++which > a->n) {
2184                                 ret = ast_strdup(cur->action);
2185                                 break;  /* make sure we exit even if ast_strdup() returns NULL */
2186                         }
2187                 }
2188                 AST_RWLIST_UNLOCK(&actions);
2189                 return ret;
2190         }
2191         authority = ast_str_alloca(MAX_AUTH_PERM_STRING);
2192         if (a->argc < 4) {
2193                 return CLI_SHOWUSAGE;
2194         }
2195
2196 #ifdef AST_XML_DOCS
2197         /* setup the titles */
2198         term_color(synopsis_title, "[Synopsis]\n", COLOR_MAGENTA, 0, 40);
2199         term_color(description_title, "[Description]\n", COLOR_MAGENTA, 0, 40);
2200         term_color(syntax_title, "[Syntax]\n", COLOR_MAGENTA, 0, 40);
2201         term_color(seealso_title, "[See Also]\n", COLOR_MAGENTA, 0, 40);
2202         term_color(arguments_title, "[Arguments]\n", COLOR_MAGENTA, 0, 40);
2203         term_color(privilege_title, "[Privilege]\n", COLOR_MAGENTA, 0, 40);
2204         term_color(final_response_title, "[Final Response]\n", COLOR_MAGENTA, 0, 40);
2205         term_color(list_responses_title, "[List Responses]\n", COLOR_MAGENTA, 0, 40);
2206 #endif
2207
2208         AST_RWLIST_RDLOCK(&actions);
2209         AST_RWLIST_TRAVERSE(&actions, cur, list) {
2210                 for (num = 3; num < a->argc; num++) {
2211                         if (!strcasecmp(cur->action, a->argv[num])) {
2212                                 auth_str = authority_to_str(cur->authority, &authority);
2213
2214 #ifdef AST_XML_DOCS
2215                                 if (cur->docsrc == AST_XML_DOC) {
2216                                         char *syntax = ast_xmldoc_printable(S_OR(cur->syntax, "Not available"), 1);
2217                                         char *synopsis = ast_xmldoc_printable(S_OR(cur->synopsis, "Not available"), 1);
2218                                         char *description = ast_xmldoc_printable(S_OR(cur->description, "Not available"), 1);
2219                                         char *arguments = ast_xmldoc_printable(S_OR(cur->arguments, "Not available"), 1);
2220                                         char *seealso = ast_xmldoc_printable(S_OR(cur->seealso, "Not available"), 1);
2221                                         char *privilege = ast_xmldoc_printable(S_OR(auth_str, "Not available"), 1);
2222                                         char *responses = ast_xmldoc_printable("None", 1);
2223                                         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",
2224                                                 syntax_title, syntax,
2225                                                 synopsis_title, synopsis,
2226                                                 description_title, description,
2227                                                 arguments_title, arguments,
2228                                                 seealso_title, seealso,
2229                                                 privilege_title, privilege,
2230                                                 list_responses_title);
2231
2232                                         if (!cur->list_responses) {
2233                                                 ast_cli(a->fd, "%s\n\n", responses);
2234                                         } else {
2235                                                 struct ast_xml_doc_item *temp;
2236                                                 for (temp = cur->list_responses; temp; temp = AST_LIST_NEXT(temp, next)) {
2237                                                         ast_cli(a->fd, "Event: %s\n", temp->name);
2238                                                         print_event_instance(a, temp);
2239                                                 }
2240                                         }
2241
2242                                         ast_cli(a->fd, "%s", final_response_title);
2243
2244                                         if (!cur->final_response) {
2245                                                 ast_cli(a->fd, "%s\n\n", responses);
2246                                         } else {
2247                                                 ast_cli(a->fd, "Event: %s\n", cur->final_response->name);
2248                                                 print_event_instance(a, cur->final_response);
2249                                         }
2250                                 } else
2251 #endif
2252                                 {
2253                                         ast_cli(a->fd, "Action: %s\nSynopsis: %s\nPrivilege: %s\n%s\n",
2254                                                 cur->action, cur->synopsis,
2255                                                 auth_str,
2256                                                 S_OR(cur->description, ""));
2257                                 }
2258                         }
2259                 }
2260         }
2261         AST_RWLIST_UNLOCK(&actions);
2262
2263         return CLI_SUCCESS;
2264 }
2265
2266 static char *handle_mandebug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2267 {
2268         switch (cmd) {
2269         case CLI_INIT:
2270                 e->command = "manager set debug [on|off]";
2271                 e->usage = "Usage: manager set debug [on|off]\n Show, enable, disable debugging of the manager code.\n";
2272                 return NULL;
2273         case CLI_GENERATE:
2274                 return NULL;
2275         }
2276
2277         if (a->argc == 3) {
2278                 ast_cli(a->fd, "manager debug is %s\n", manager_debug? "on" : "off");
2279         } else if (a->argc == 4) {
2280                 if (!strcasecmp(a->argv[3], "on")) {
2281                         manager_debug = 1;
2282                 } else if (!strcasecmp(a->argv[3], "off")) {
2283                         manager_debug = 0;
2284                 } else {
2285                         return CLI_SHOWUSAGE;
2286                 }
2287         }
2288         return CLI_SUCCESS;
2289 }
2290
2291 static char *handle_showmanager(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2292 {
2293         struct ast_manager_user *user = NULL;
2294         int l, which;
2295         char *ret = NULL;
2296         struct ast_str *rauthority = ast_str_alloca(MAX_AUTH_PERM_STRING);
2297         struct ast_str *wauthority = ast_str_alloca(MAX_AUTH_PERM_STRING);
2298         struct ast_variable *v;
2299
2300         switch (cmd) {
2301         case CLI_INIT:
2302                 e->command = "manager show user";
2303                 e->usage =
2304                         " Usage: manager show user <user>\n"
2305                         "        Display all information related to the manager user specified.\n";
2306                 return NULL;
2307         case CLI_GENERATE:
2308                 l = strlen(a->word);
2309                 which = 0;
2310                 if (a->pos != 3) {
2311                         return NULL;
2312                 }
2313                 AST_RWLIST_RDLOCK(&users);
2314                 AST_RWLIST_TRAVERSE(&users, user, list) {
2315                         if ( !strncasecmp(a->word, user->username, l) && ++which > a->n ) {
2316                                 ret = ast_strdup(user->username);
2317                                 break;
2318                         }
2319                 }
2320                 AST_RWLIST_UNLOCK(&users);
2321                 return ret;
2322         }
2323
2324         if (a->argc != 4) {
2325                 return CLI_SHOWUSAGE;
2326         }
2327
2328         AST_RWLIST_RDLOCK(&users);
2329
2330         if (!(user = get_manager_by_name_locked(a->argv[3]))) {
2331                 ast_cli(a->fd, "There is no manager called %s\n", a->argv[3]);
2332                 AST_RWLIST_UNLOCK(&users);
2333                 return CLI_SUCCESS;
2334         }
2335
2336         ast_cli(a->fd, "\n");
2337         ast_cli(a->fd,
2338                 "          username: %s\n"
2339                 "            secret: %s\n"
2340                 "               ACL: %s\n"
2341                 "         read perm: %s\n"
2342                 "        write perm: %s\n"
2343                 "   displayconnects: %s\n"
2344                 "allowmultiplelogin: %s\n",
2345                 S_OR(user->username, "(N/A)"),
2346                 (user->secret ? "<Set>" : "(N/A)"),
2347                 ((user->acl && !ast_acl_list_is_empty(user->acl)) ? "yes" : "no"),
2348                 user_authority_to_str(user->readperm, &rauthority),
2349                 user_authority_to_str(user->writeperm, &wauthority),
2350                 (user->displayconnects ? "yes" : "no"),
2351                 (user->allowmultiplelogin ? "yes" : "no"));
2352         ast_cli(a->fd, "         Variables: \n");
2353                 for (v = user->chanvars ; v ; v = v->next) {
2354                         ast_cli(a->fd, "                 %s = %s\n", v->name, v->value);
2355                 }
2356
2357         AST_RWLIST_UNLOCK(&users);
2358
2359         return CLI_SUCCESS;
2360 }
2361
2362 static char *handle_showmanagers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2363 {
2364         struct ast_manager_user *user = NULL;
2365         int count_amu = 0;
2366         switch (cmd) {
2367         case CLI_INIT:
2368                 e->command = "manager show users";
2369                 e->usage =
2370                         "Usage: manager show users\n"
2371                         "       Prints a listing of all managers that are currently configured on that\n"
2372                         " system.\n";
2373                 return NULL;
2374         case CLI_GENERATE:
2375                 return NULL;
2376         }
2377         if (a->argc != 3) {
2378                 return CLI_SHOWUSAGE;
2379         }
2380
2381         AST_RWLIST_RDLOCK(&users);
2382
2383         /* If there are no users, print out something along those lines */
2384         if (AST_RWLIST_EMPTY(&users)) {
2385                 ast_cli(a->fd, "There are no manager users.\n");
2386                 AST_RWLIST_UNLOCK(&users);
2387                 return CLI_SUCCESS;
2388         }
2389
2390         ast_cli(a->fd, "\nusername\n--------\n");
2391
2392         AST_RWLIST_TRAVERSE(&users, user, list) {
2393                 ast_cli(a->fd, "%s\n", user->username);
2394                 count_amu++;
2395         }
2396
2397         AST_RWLIST_UNLOCK(&users);
2398
2399         ast_cli(a->fd,"-------------------\n"
2400                       "%d manager users configured.\n", count_amu);
2401         return CLI_SUCCESS;
2402 }
2403
2404 /*! \brief  CLI command  manager list commands */
2405 static char *handle_showmancmds(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2406 {
2407         struct manager_action *cur;
2408         int name_len = 1;
2409         int space_remaining;
2410 #define HSMC_FORMAT "  %-*.*s  %-.*s\n"
2411         switch (cmd) {
2412         case CLI_INIT:
2413                 e->command = "manager show commands";
2414                 e->usage =
2415                         "Usage: manager show commands\n"
2416                         "       Prints a listing of all the available Asterisk manager interface commands.\n";
2417                 return NULL;
2418         case CLI_GENERATE:
2419                 return NULL;
2420         }
2421
2422         AST_RWLIST_RDLOCK(&actions);
2423         AST_RWLIST_TRAVERSE(&actions, cur, list) {
2424                 int incoming_len = strlen(cur->action);
2425                 if (incoming_len > name_len) {
2426                         name_len = incoming_len;
2427                 }
2428         }
2429
2430         space_remaining = MGR_SHOW_TERMINAL_WIDTH - name_len - 4;
2431         if (space_remaining < 0) {
2432                 space_remaining = 0;
2433         }
2434
2435         ast_cli(a->fd, HSMC_FORMAT, name_len, name_len, "Action", space_remaining, "Synopsis");
2436         ast_cli(a->fd, HSMC_FORMAT, name_len, name_len, "------", space_remaining, "--------");
2437
2438         AST_RWLIST_TRAVERSE(&actions, cur, list) {
2439                 ast_cli(a->fd, HSMC_FORMAT, name_len, name_len, cur->action, space_remaining, cur->synopsis);
2440         }
2441         AST_RWLIST_UNLOCK(&actions);
2442
2443         return CLI_SUCCESS;
2444 }
2445
2446 /*! \brief CLI command manager list connected */
2447 static char *handle_showmanconn(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2448 {
2449         struct ao2_container *sessions;
2450         struct mansession_session *session;
2451         time_t now = time(NULL);
2452 #define HSMCONN_FORMAT1 "  %-15.15s  %-55.55s  %-10.10s  %-10.10s  %-8.8s  %-8.8s  %-5.5s  %-5.5s\n"
2453 #define HSMCONN_FORMAT2 "  %-15.15s  %-55.55s  %-10d  %-10d  %-8d  %-8d  %-5.5d  %-5.5d\n"
2454         int count = 0;
2455         struct ao2_iterator i;
2456
2457         switch (cmd) {
2458         case CLI_INIT:
2459                 e->command = "manager show connected";
2460                 e->usage =
2461                         "Usage: manager show connected\n"
2462                         "       Prints a listing of the users that are currently connected to the\n"
2463                         "Asterisk manager interface.\n";
2464                 return NULL;
2465         case CLI_GENERATE:
2466                 return NULL;
2467         }
2468
2469         ast_cli(a->fd, HSMCONN_FORMAT1, "Username", "IP Address", "Start", "Elapsed", "FileDes", "HttpCnt", "Read", "Write");
2470
2471         sessions = ao2_global_obj_ref(mgr_sessions);
2472         if (sessions) {
2473                 i = ao2_iterator_init(sessions, 0);
2474                 ao2_ref(sessions, -1);
2475                 while ((session = ao2_iterator_next(&i))) {
2476                         ao2_lock(session);
2477                         ast_cli(a->fd, HSMCONN_FORMAT2, session->username,
2478                                 ast_sockaddr_stringify_addr(&session->addr),
2479                                 (int) (session->sessionstart),
2480                                 (int) (now - session->sessionstart),
2481                                 session->fd,
2482                                 session->inuse,
2483                                 session->readperm,
2484                                 session->writeperm);
2485                         count++;
2486                         ao2_unlock(session);
2487                         unref_mansession(session);
2488                 }
2489                 ao2_iterator_destroy(&i);
2490         }
2491         ast_cli(a->fd, "%d users connected.\n", count);
2492
2493         return CLI_SUCCESS;
2494 }
2495
2496 /*! \brief CLI command manager list eventq */
2497 /* Should change to "manager show connected" */
2498 static char *handle_showmaneventq(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2499 {
2500         struct eventqent *s;
2501         switch (cmd) {
2502         case CLI_INIT:
2503                 e->command = "manager show eventq";
2504                 e->usage =
2505                         "Usage: manager show eventq\n"
2506                         "       Prints a listing of all events pending in the Asterisk manger\n"
2507                         "event queue.\n";
2508                 return NULL;
2509         case CLI_GENERATE:
2510                 return NULL;
2511         }
2512         AST_RWLIST_RDLOCK(&all_events);
2513         AST_RWLIST_TRAVERSE(&all_events, s, eq_next) {
2514                 ast_cli(a->fd, "Usecount: %d\n", s->usecount);
2515                 ast_cli(a->fd, "Category: %d\n", s->category);
2516                 ast_cli(a->fd, "Event:\n%s", s->eventdata);
2517         }
2518         AST_RWLIST_UNLOCK(&all_events);
2519
2520         return CLI_SUCCESS;
2521 }
2522
2523 /*! \brief CLI command manager reload */
2524 static char *handle_manager_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2525 {
2526         switch (cmd) {
2527         case CLI_INIT:
2528                 e->command = "manager reload";
2529                 e->usage =
2530                         "Usage: manager reload\n"
2531                         "       Reloads the manager configuration.\n";
2532                 return NULL;
2533         case CLI_GENERATE:
2534                 return NULL;
2535         }
2536         if (a->argc > 2) {
2537                 return CLI_SHOWUSAGE;
2538         }
2539         reload_manager();
2540         return CLI_SUCCESS;
2541 }
2542
2543 static struct eventqent *advance_event(struct eventqent *e)
2544 {
2545         struct eventqent *next;
2546
2547         AST_RWLIST_RDLOCK(&all_events);
2548         if ((next = AST_RWLIST_NEXT(e, eq_next))) {
2549                 ast_atomic_fetchadd_int(&next->usecount, 1);
2550                 ast_atomic_fetchadd_int(&e->usecount, -1);
2551         }
2552         AST_RWLIST_UNLOCK(&all_events);
2553         return next;
2554 }
2555
2556 #define GET_HEADER_FIRST_MATCH  0
2557 #define GET_HEADER_LAST_MATCH   1
2558 #define GET_HEADER_SKIP_EMPTY   2
2559
2560 /*!
2561  * \brief Return a matching header value.
2562  *
2563  * \details
2564  * Generic function to return either the first or the last
2565  * matching header from a list of variables, possibly skipping
2566  * empty strings.
2567  *
2568  * \note At the moment there is only one use of this function in
2569  * this file, so we make it static.
2570  *
2571  * \note Never returns NULL.
2572  */
2573 static const char *__astman_get_header(const struct message *m, char *var, int mode)
2574 {
2575         int x, l = strlen(var);
2576         const char *result = "";
2577
2578         if (!m) {
2579                 return result;
2580         }
2581
2582         for (x = 0; x < m->hdrcount; x++) {
2583                 const char *h = m->headers[x];
2584                 if (!strncasecmp(var, h, l) && h[l] == ':') {
2585                         const char *value = h + l + 1;
2586                         value = ast_skip_blanks(value); /* ignore leading spaces in the value */
2587                         /* found a potential candidate */
2588                         if ((mode & GET_HEADER_SKIP_EMPTY) && ast_strlen_zero(value)) {
2589                                 continue;       /* not interesting */
2590                         }
2591                         if (mode & GET_HEADER_LAST_MATCH) {
2592                                 result = value; /* record the last match so far */
2593                         } else {
2594                                 return value;
2595                         }
2596                 }
2597         }
2598
2599         return result;
2600 }
2601
2602 /*!
2603  * \brief Return the first matching variable from an array.
2604  *
2605  * \note This is the legacy function and is implemented in
2606  * therms of __astman_get_header().
2607  *
2608  * \note Never returns NULL.
2609  */
2610 const char *astman_get_header(const struct message *m, char *var)
2611 {
2612         return __astman_get_header(m, var, GET_HEADER_FIRST_MATCH);
2613 }
2614
2615 /*!
2616  * \internal
2617  * \brief Process one "Variable:" header value string.
2618  *
2619  * \param head Current list of AMI variables to get new values added.
2620  * \param hdr_val Header value string to process.
2621  *
2622  * \return New variable list head.
2623  */
2624 static struct ast_variable *man_do_variable_value(struct ast_variable *head, const char *hdr_val)
2625 {
2626         char *parse;
2627         AST_DECLARE_APP_ARGS(args,
2628                 AST_APP_ARG(vars)[64];
2629         );
2630
2631         hdr_val = ast_skip_blanks(hdr_val); /* ignore leading spaces in the value */
2632         parse = ast_strdupa(hdr_val);
2633
2634         /* Break the header value string into name=val pair items. */
2635         AST_STANDARD_APP_ARGS(args, parse);
2636         if (args.argc) {
2637                 int y;
2638
2639                 /* Process each name=val pair item. */
2640                 for (y = 0; y < args.argc; y++) {
2641                         struct ast_variable *cur;
2642                         char *var;
2643                         char *val;
2644
2645                         if (!args.vars[y]) {
2646                                 continue;
2647                         }
2648                         var = val = args.vars[y];
2649                         strsep(&val, "=");
2650
2651                         /* XXX We may wish to trim whitespace from the strings. */
2652                         if (!val || ast_strlen_zero(var)) {
2653                                 continue;
2654                         }
2655
2656                         /* Create new variable list node and prepend it to the list. */
2657                         cur = ast_variable_new(var, val, "");
2658                         if (cur) {
2659                                 cur->next = head;
2660                                 head = cur;
2661                         }
2662                 }
2663         }
2664
2665         return head;
2666 }
2667
2668 struct ast_variable *astman_get_variables(const struct message *m)
2669 {
2670         return astman_get_variables_order(m, ORDER_REVERSE);
2671 }
2672
2673 struct ast_variable *astman_get_variables_order(const struct message *m,
2674         enum variable_orders order)
2675 {
2676         int varlen;
2677         int x;
2678         struct ast_variable *head = NULL;
2679
2680         static const char var_hdr[] = "Variable:";
2681
2682         /* Process all "Variable:" headers. */
2683         varlen = strlen(var_hdr);
2684         for (x = 0; x < m->hdrcount; x++) {
2685                 if (strncasecmp(var_hdr, m->headers[x], varlen)) {
2686                         continue;
2687                 }
2688                 head = man_do_variable_value(head, m->headers[x] + varlen);
2689         }
2690
2691         if (order == ORDER_NATURAL) {
2692                 head = ast_variables_reverse(head);
2693         }
2694
2695         return head;
2696 }
2697
2698 /*! \brief access for hooks to send action messages to ami */
2699 int ast_hook_send_action(struct manager_custom_hook *hook, const char *msg)
2700 {
2701         const char *action;
2702         int ret = 0;
2703         struct manager_action *act_found;
2704         struct mansession s = {.session = NULL, };
2705         struct message m = { 0 };
2706         char *dup_str;
2707         char *src;
2708         int x = 0;
2709         int curlen;
2710
2711         if (hook == NULL) {
2712                 return -1;
2713         }
2714
2715         /* Create our own copy of the AMI action msg string. */
2716         src = dup_str = ast_strdup(msg);
2717         if (!dup_str) {
2718                 return -1;
2719         }
2720
2721         /* convert msg string to message struct */
2722         curlen = strlen(src);
2723         for (x = 0; x < curlen; x++) {
2724                 int cr; /* set if we have \r */
2725                 if (src[x] == '\r' && x+1 < curlen && src[x+1] == '\n')
2726                         cr = 2; /* Found. Update length to include \r\n */
2727                 else if (src[x] == '\n')
2728                         cr = 1; /* also accept \n only */
2729                 else
2730                         continue;
2731                 /* don't keep empty lines */
2732                 if (x && m.hdrcount < ARRAY_LEN(m.headers)) {
2733                         /* ... but trim \r\n and terminate the header string */
2734                         src[x] = '\0';
2735                         m.headers[m.hdrcount++] = src;
2736                 }
2737                 x += cr;
2738                 curlen -= x;            /* remaining size */
2739                 src += x;               /* update pointer */
2740                 x = -1;                 /* reset loop */
2741         }
2742
2743         action = astman_get_header(&m, "Action");
2744         if (strcasecmp(action, "login")) {
2745                 act_found = action_find(action);
2746                 if (act_found) {
2747                         /*
2748                          * we have to simulate a session for this action request
2749                          * to be able to pass it down for processing
2750                          * This is necessary to meet the previous design of manager.c
2751                          */
2752                         s.hook = hook;
2753                         s.f = (void*)1; /* set this to something so our request will make it through all functions that test it*/
2754
2755                         ao2_lock(act_found);
2756                         if (act_found->registered && act_found->func) {
2757                                 if (act_found->module) {
2758                                         ast_module_ref(act_found->module);
2759                                 }
2760                                 ao2_unlock(act_found);
2761                                 ret = act_found->func(&s, &m);
2762                                 ao2_lock(act_found);
2763                                 if (act_found->module) {
2764                                         ast_module_unref(act_found->module);
2765                                 }
2766                         } else {
2767                                 ret = -1;
2768                         }
2769                         ao2_unlock(act_found);
2770                         ao2_t_ref(act_found, -1, "done with found action object");
2771                 }
2772         }
2773         ast_free(dup_str);
2774         return ret;
2775 }
2776
2777
2778 /*!
2779  * helper function to send a string to the socket.
2780  * Return -1 on error (e.g. buffer full).
2781  */
2782 static int send_string(struct mansession *s, char *string)
2783 {
2784         int res;
2785         FILE *f = s->f ? s->f : s->session->f;
2786         int fd = s->f ? s->fd : s->session->fd;
2787
2788         /* It's a result from one of the hook's action invocation */
2789         if (s->hook) {
2790                 /*
2791                  * to send responses, we're using the same function
2792                  * as for receiving events. We call the event "HookResponse"
2793                  */
2794                 s->hook->helper(EVENT_FLAG_HOOKRESPONSE, "HookResponse", string);
2795                 return 0;
2796         }
2797
2798         if ((res = ast_careful_fwrite(f, fd, string, strlen(string), s->session->writetimeout))) {
2799                 s->write_error = 1;
2800         }
2801
2802         return res;
2803 }
2804
2805 /*!
2806  * \brief thread local buffer for astman_append
2807  *
2808  * \note This can not be defined within the astman_append() function
2809  *       because it declares a couple of functions that get used to
2810  *       initialize the thread local storage key.
2811  */
2812 AST_THREADSTORAGE(astman_append_buf);
2813
2814 AST_THREADSTORAGE(userevent_buf);
2815
2816 /*! \brief initial allocated size for the astman_append_buf and astman_send_*_va */
2817 #define ASTMAN_APPEND_BUF_INITSIZE   256
2818
2819 /*!
2820  * utility functions for creating AMI replies
2821  */
2822 void astman_append(struct mansession *s, const char *fmt, ...)
2823 {
2824         int res;
2825         va_list ap;
2826         struct ast_str *buf;
2827
2828         if (!(buf = ast_str_thread_get(&astman_append_buf, ASTMAN_APPEND_BUF_INITSIZE))) {
2829                 return;
2830         }
2831
2832         va_start(ap, fmt);
2833         res = ast_str_set_va(&buf, 0, fmt, ap);
2834         va_end(ap);
2835         if (res == AST_DYNSTR_BUILD_FAILED) {
2836                 return;
2837         }
2838
2839         if (s->f != NULL || s->session->f != NULL) {
2840                 send_string(s, ast_str_buffer(buf));
2841         } else {
2842                 ast_verbose("fd == -1 in astman_append, should not happen\n");
2843         }
2844 }
2845
2846 /*! \note NOTE: XXX this comment is unclear and possibly wrong.
2847    Callers of astman_send_error(), astman_send_response() or astman_send_ack() must EITHER
2848    hold the session lock _or_ be running in an action callback (in which case s->session->busy will
2849    be non-zero). In either of these cases, there is no need to lock-protect the session's
2850    fd, since no other output will be sent (events will be queued), and no input will
2851    be read until either the current action finishes or get_input() obtains the session
2852    lock.
2853  */
2854
2855 /*! \todo XXX MSG_MOREDATA should go to a header file. */
2856 #define MSG_MOREDATA    ((char *)astman_send_response)
2857
2858 /*! \brief send a response with an optional message,
2859  * and terminate it with an empty line.
2860  * m is used only to grab the 'ActionID' field.
2861  *
2862  * Use the explicit constant MSG_MOREDATA to remove the empty line.
2863  * XXX MSG_MOREDATA should go to a header file.
2864  */
2865 static void astman_send_response_full(struct mansession *s, const struct message *m, char *resp, char *msg, char *listflag)
2866 {
2867         const char *id = astman_get_header(m, "ActionID");
2868
2869         astman_append(s, "Response: %s\r\n", resp);
2870         if (!ast_strlen_zero(id)) {
2871                 astman_append(s, "ActionID: %s\r\n", id);
2872         }
2873         if (listflag) {
2874                 astman_append(s, "EventList: %s\r\n", listflag);        /* Start, complete, cancelled */
2875         }
2876         if (msg == MSG_MOREDATA) {
2877                 return;
2878         } else if (msg) {
2879                 astman_append(s, "Message: %s\r\n\r\n", msg);
2880         } else {
2881                 astman_append(s, "\r\n");
2882         }
2883 }
2884
2885 void astman_send_response(struct mansession *s, const struct message *m, char *resp, char *msg)
2886 {
2887         astman_send_response_full(s, m, resp, msg, NULL);
2888 }
2889
2890 void astman_send_error(struct mansession *s, const struct message *m, char *error)
2891 {
2892         astman_send_response_full(s, m, "Error", error, NULL);
2893 }
2894
2895 void astman_send_error_va(struct mansession *s, const struct message *m, const char *fmt, ...)
2896 {
2897         int res;
2898         va_list ap;
2899         struct ast_str *buf;
2900         char *msg;
2901
2902         if (!(buf = ast_str_thread_get(&astman_append_buf, ASTMAN_APPEND_BUF_INITSIZE))) {
2903                 return;
2904         }
2905
2906         va_start(ap, fmt);
2907         res = ast_str_set_va(&buf, 0, fmt, ap);
2908         va_end(ap);
2909         if (res == AST_DYNSTR_BUILD_FAILED) {
2910                 return;
2911         }
2912
2913         /* astman_append will use the same underlying buffer, so copy the message out
2914          * before sending the response */
2915         msg = ast_str_buffer(buf);
2916         if (msg) {
2917                 msg = ast_strdupa(msg);
2918         }
2919         astman_send_response_full(s, m, "Error", msg, NULL);
2920 }
2921
2922 void astman_send_ack(struct mansession *s, const struct message *m, char *msg)
2923 {
2924         astman_send_response_full(s, m, "Success", msg, NULL);
2925 }
2926
2927 static void astman_start_ack(struct mansession *s, const struct message *m)
2928 {
2929         astman_send_response_full(s, m, "Success", MSG_MOREDATA, NULL);
2930 }
2931
2932 void astman_send_listack(struct mansession *s, const struct message *m, char *msg, char *listflag)
2933 {
2934         astman_send_response_full(s, m, "Success", msg, listflag);
2935 }
2936
2937 void astman_send_list_complete_start(struct mansession *s, const struct message *m, const char *event_name, int count)
2938 {
2939         const char *id = astman_get_header(m, "ActionID");
2940
2941         astman_append(s, "Event: %s\r\n", event_name);
2942         if (!ast_strlen_zero(id)) {
2943                 astman_append(s, "ActionID: %s\r\n", id);
2944         }
2945         astman_append(s,
2946                 "EventList: Complete\r\n"
2947                 "ListItems: %d\r\n",
2948                 count);
2949 }
2950
2951 void astman_send_list_complete_end(struct mansession *s)
2952 {
2953         astman_append(s, "\r\n");
2954 }
2955
2956 /*! \brief Lock the 'mansession' structure. */
2957 static void mansession_lock(struct mansession *s)
2958 {
2959         ast_mutex_lock(&s->lock);
2960 }
2961
2962 /*! \brief Unlock the 'mansession' structure. */
2963 static void mansession_unlock(struct mansession *s)
2964 {
2965         ast_mutex_unlock(&s->lock);
2966 }
2967
2968 /*! \brief
2969    Rather than braindead on,off this now can also accept a specific int mask value
2970    or a ',' delim list of mask strings (the same as manager.conf) -anthm
2971 */
2972 static int set_eventmask(struct mansession *s, const char *eventmask)
2973 {
2974         int maskint = strings_to_mask(eventmask);
2975
2976         ao2_lock(s->session);
2977         if (maskint >= 0) {
2978                 s->session->send_events = maskint;
2979         }
2980         ao2_unlock(s->session);
2981
2982         return maskint;
2983 }
2984
2985 static enum ast_transport mansession_get_transport(const struct mansession *s)
2986 {
2987         return s->tcptls_session->parent->tls_cfg ? AST_TRANSPORT_TLS :
2988                         AST_TRANSPORT_TCP;
2989 }
2990
2991 static void report_invalid_user(const struct mansession *s, const char *username)
2992 {
2993         char session_id[32];
2994         struct ast_security_event_inval_acct_id inval_acct_id = {
2995                 .common.event_type = AST_SECURITY_EVENT_INVAL_ACCT_ID,
2996                 .common.version    = AST_SECURITY_EVENT_INVAL_ACCT_ID_VERSION,
2997                 .common.service    = "AMI",
2998                 .common.account_id = username,
2999                 .common.session_tv = &s->session->sessionstart_tv,
3000                 .common.local_addr = {
3001                         .addr      = &s->tcptls_session->parent->local_address,
3002                         .transport = mansession_get_transport(s),
3003                 },
3004                 .common.remote_addr = {
3005                         .addr      = &s->session->addr,
3006                         .transport = mansession_get_transport(s),
3007                 },
3008                 .common.session_id = session_id,
3009         };
3010
3011         snprintf(session_id, sizeof(session_id), "%p", s);
3012
3013         ast_security_event_report(AST_SEC_EVT(&inval_acct_id));
3014 }
3015
3016 static void report_failed_acl(const struct mansession *s, const char *username)
3017 {
3018         char session_id[32];
3019         struct ast_security_event_failed_acl failed_acl_event = {
3020                 .common.event_type = AST_SECURITY_EVENT_FAILED_ACL,
3021                 .common.version    = AST_SECURITY_EVENT_FAILED_ACL_VERSION,
3022                 .common.service    = "AMI",
3023                 .common.account_id = username,
3024                 .common.session_tv = &s->session->sessionstart_tv,
3025                 .common.local_addr = {
3026                         .addr      = &s->tcptls_session->parent->local_address,
3027                         .transport = mansession_get_transport(s),
3028                 },
3029                 .common.remote_addr = {
3030                         .addr      = &s->session->addr,
3031                         .transport = mansession_get_transport(s),
3032                 },
3033                 .common.session_id = session_id,
3034         };
3035
3036         snprintf(session_id, sizeof(session_id), "%p", s->session);
3037
3038         ast_security_event_report(AST_SEC_EVT(&failed_acl_event));
3039 }
3040
3041 static void report_inval_password(const struct mansession *s, const char *username)
3042 {
3043         char session_id[32];
3044         struct ast_security_event_inval_password inval_password = {
3045                 .common.event_type = AST_SECURITY_EVENT_INVAL_PASSWORD,
3046                 .common.version    = AST_SECURITY_EVENT_INVAL_PASSWORD_VERSION,
3047                 .common.service    = "AMI",
3048                 .common.account_id = username,
3049                 .common.session_tv = &s->session->sessionstart_tv,
3050                 .common.local_addr = {
3051                         .addr      = &s->tcptls_session->parent->local_address,
3052                         .transport = mansession_get_transport(s),
3053                 },
3054                 .common.remote_addr = {
3055                         .addr      = &s->session->addr,
3056                         .transport = mansession_get_transport(s),
3057                 },
3058                 .common.session_id = session_id,
3059         };
3060
3061         snprintf(session_id, sizeof(session_id), "%p", s->session);
3062
3063         ast_security_event_report(AST_SEC_EVT(&inval_password));
3064 }
3065
3066 static void report_auth_success(const struct mansession *s)
3067 {
3068         char session_id[32];
3069         struct ast_security_event_successful_auth successful_auth = {
3070                 .common.event_type = AST_SECURITY_EVENT_SUCCESSFUL_AUTH,
3071                 .common.version    = AST_SECURITY_EVENT_SUCCESSFUL_AUTH_VERSION,
3072                 .common.service    = "AMI",
3073                 .common.account_id = s->session->username,
3074                 .common.session_tv = &s->session->sessionstart_tv,
3075                 .common.local_addr = {
3076                         .addr      = &s->tcptls_session->parent->local_address,
3077                         .transport = mansession_get_transport(s),
3078                 },
3079                 .common.remote_addr = {
3080                         .addr      = &s->session->addr,
3081                         .transport = mansession_get_transport(s),
3082                 },
3083                 .common.session_id = session_id,
3084         };
3085
3086         snprintf(session_id, sizeof(session_id), "%p", s->session);
3087
3088         ast_security_event_report(AST_SEC_EVT(&successful_auth));
3089 }
3090
3091 static void report_req_not_allowed(const struct mansession *s, const char *action)
3092 {
3093         char session_id[32];
3094         char request_type[64];
3095         struct ast_security_event_req_not_allowed req_not_allowed = {
3096                 .common.event_type = AST_SECURITY_EVENT_REQ_NOT_ALLOWED,
3097                 .common.version    = AST_SECURITY_EVENT_REQ_NOT_ALLOWED_VERSION,
3098                 .common.service    = "AMI",
3099                 .common.account_id = s->session->username,
3100                 .common.session_tv = &s->session->sessionstart_tv,
3101                 .common.local_addr = {
3102                         .addr      = &s->tcptls_session->parent->local_address,
3103                         .transport = mansession_get_transport(s),
3104                 },
3105                 .common.remote_addr = {
3106                         .addr      = &s->session->addr,
3107                         .transport = mansession_get_transport(s),
3108                 },
3109                 .common.session_id = session_id,
3110
3111                 .request_type      = request_type,
3112         };
3113
3114         snprintf(session_id, sizeof(session_id), "%p", s->session);
3115         snprintf(request_type, sizeof(request_type), "Action: %s", action);
3116
3117         ast_security_event_report(AST_SEC_EVT(&req_not_allowed));
3118 }
3119
3120 static void report_req_bad_format(const struct mansession *s, const char *action)
3121 {
3122         char session_id[32];
3123         char request_type[64];
3124         struct ast_security_event_req_bad_format req_bad_format = {
3125                 .common.event_type = AST_SECURITY_EVENT_REQ_BAD_FORMAT,
3126                 .common.version    = AST_SECURITY_EVENT_REQ_BAD_FORMAT_VERSION,
3127                 .common.service    = "AMI",
3128                 .common.account_id = s->session->username,
3129                 .common.session_tv = &s->session->sessionstart_tv,
3130                 .common.local_addr = {
3131                         .addr      = &s->tcptls_session->parent->local_address,
3132                         .transport = mansession_get_transport(s),
3133                 },
3134                 .common.remote_addr = {
3135                         .addr      = &s->session->addr,
3136                         .transport = mansession_get_transport(s),
3137                 },
3138                 .common.session_id = session_id,
3139
3140                 .request_type      = request_type,
3141         };
3142
3143         snprintf(session_id, sizeof(session_id), "%p", s->session);
3144         snprintf(request_type, sizeof(request_type), "Action: %s", action);
3145
3146         ast_security_event_report(AST_SEC_EVT(&req_bad_format));
3147 }
3148
3149 static void report_failed_challenge_response(const struct mansession *s,
3150                 const char *response, const char *expected_response)
3151 {
3152         char session_id[32];
3153         struct ast_security_event_chal_resp_failed chal_resp_failed = {
3154                 .common.event_type = AST_SECURITY_EVENT_CHAL_RESP_FAILED,
3155                 .common.version    = AST_SECURITY_EVENT_CHAL_RESP_FAILED_VERSION,
3156                 .common.service    = "AMI",
3157                 .common.account_id = s->session->username,
3158                 .common.session_tv = &s->session->sessionstart_tv,
3159                 .common.local_addr = {
3160                         .addr      = &s->tcptls_session->parent->local_address,
3161                         .transport = mansession_get_transport(s),
3162                 },
3163                 .common.remote_addr = {
3164                         .addr      = &s->session->addr,
3165                         .transport = mansession_get_transport(s),
3166                 },
3167                 .common.session_id = session_id,
3168
3169                 .challenge         = s->session->challenge,
3170                 .response          = response,
3171                 .expected_response = expected_response,
3172         };
3173
3174         snprintf(session_id, sizeof(session_id), "%p", s->session);
3175
3176         ast_security_event_report(AST_SEC_EVT(&chal_resp_failed));
3177 }
3178
3179 static void report_session_limit(const struct mansession *s)
3180 {
3181         char session_id[32];
3182         struct ast_security_event_session_limit session_limit = {
3183                 .common.event_type = AST_SECURITY_EVENT_SESSION_LIMIT,
3184                 .common.version    = AST_SECURITY_EVENT_SESSION_LIMIT_VERSION,
3185                 .common.service    = "AMI",
3186                 .common.account_id = s->session->username,
3187                 .common.session_tv = &s->session->sessionstart_tv,
3188                 .common.local_addr = {
3189                         .addr      = &s->tcptls_session->parent->local_address,
3190                         .transport = mansession_get_transport(s),
3191                 },
3192                 .common.remote_addr = {
3193                         .addr      = &s->session->addr,
3194                         .transport = mansession_get_transport(s),
3195                 },
3196                 .common.session_id = session_id,
3197         };
3198
3199         snprintf(session_id, sizeof(session_id), "%p", s->session);
3200
3201         ast_security_event_report(AST_SEC_EVT(&session_limit));
3202 }
3203
3204 /*
3205  * Here we start with action_ handlers for AMI actions,
3206  * and the internal functions used by them.
3207  * Generally, the handlers are called action_foo()
3208  */
3209
3210 /* helper function for action_login() */
3211 static int authenticate(struct mansession *s, const struct message *m)
3212 {
3213         const char *username = astman_get_header(m, "Username");
3214         const char *password = astman_get_header(m, "Secret");
3215         int error = -1;
3216         struct ast_manager_user *user = NULL;
3217         regex_t *regex_filter;
3218         struct ao2_iterator filter_iter;
3219
3220         if (ast_strlen_zero(username)) {        /* missing username */
3221                 return -1;
3222         }
3223
3224         /* locate user in locked state */
3225         AST_RWLIST_WRLOCK(&users);
3226
3227         if (!(user = get_manager_by_name_locked(username))) {
3228                 report_invalid_user(s, username);
3229                 ast_log(LOG_NOTICE, "%s tried to authenticate with nonexistent user '%s'\n", ast_sockaddr_stringify_addr(&s->session->addr), username);
3230         } else if (user->acl && (ast_apply_acl(user->acl, &s->session->addr, "Manager User ACL: ") == AST_SENSE_DENY)) {
3231                 report_failed_acl(s, username);
3232                 ast_log(LOG_NOTICE, "%s failed to pass IP ACL as '%s'\n", ast_sockaddr_stringify_addr(&s->session->addr), username);
3233         } else if (!strcasecmp(astman_get_header(m, "AuthType"), "MD5")) {
3234                 const char *key = astman_get_header(m, "Key");
3235                 if (!ast_strlen_zero(key) && !ast_strlen_zero(s->session->challenge) && user->secret) {
3236                         int x;
3237                         int len = 0;
3238                         char md5key[256] = "";
3239                         struct MD5Context md5;
3240                         unsigned char digest[16];
3241
3242                         MD5Init(&md5);
3243                         MD5Update(&md5, (unsigned char *) s->session->challenge, strlen(s->session->challenge));
3244                         MD5Update(&md5, (unsigned char *) user->secret, strlen(user->secret));
3245                         MD5Final(digest, &md5);
3246                         for (x = 0; x < 16; x++)
3247                                 len += sprintf(md5key + len, "%02hhx", digest[x]);
3248                         if (!strcmp(md5key, key)) {
3249                                 error = 0;
3250                         } else {
3251                                 report_failed_challenge_response(s, key, md5key);
3252                         }
3253                 } else {
3254                         ast_debug(1, "MD5 authentication is not possible.  challenge: '%s'\n",
3255                                 S_OR(s->session->challenge, ""));
3256                 }
3257         } else if (user->secret) {
3258                 if (!strcmp(password, user->secret)) {
3259                         error = 0;
3260                 } else {
3261                         report_inval_password(s, username);
3262                 }
3263         }
3264
3265         if (error) {
3266                 ast_log(LOG_NOTICE, "%s failed to authenticate as '%s'\n", ast_sockaddr_stringify_addr(&s->session->addr), username);
3267                 AST_RWLIST_UNLOCK(&users);
3268                 return -1;
3269         }
3270
3271         /* auth complete */
3272
3273         /* All of the user parameters are copied to the session so that in the event
3274         * of a reload and a configuration change, the session parameters are not
3275         * changed. */
3276         ast_copy_string(s->session->username, username, sizeof(s->session->username));
3277         s->session->readperm = user->readperm;
3278         s->session->writeperm = user->writeperm;
3279         s->session->writetimeout = user->writetimeout;
3280         if (user->chanvars) {
3281                 s->session->chanvars = ast_variables_dup(user->chanvars);
3282         }
3283
3284         filter_iter = ao2_iterator_init(user->whitefilters, 0);
3285         while ((regex_filter = ao2_iterator_next(&filter_iter))) {
3286                 ao2_t_link(s->session->whitefilters, regex_filter, "add white user filter to session");
3287                 ao2_t_ref(regex_filter, -1, "remove iterator ref");
3288         }
3289         ao2_iterator_destroy(&filter_iter);
3290
3291         filter_iter = ao2_iterator_init(user->blackfilters, 0);
3292         while ((regex_filter = ao2_iterator_next(&filter_iter))) {
3293                 ao2_t_link(s->session->blackfilters, regex_filter, "add black user filter to session");
3294                 ao2_t_ref(regex_filter, -1, "remove iterator ref");
3295         }
3296         ao2_iterator_destroy(&filter_iter);
3297
3298         s->session->sessionstart = time(NULL);
3299         s->session->sessionstart_tv = ast_tvnow();
3300         set_eventmask(s, astman_get_header(m, "Events"));
3301
3302         report_auth_success(s);
3303
3304         AST_RWLIST_UNLOCK(&users);
3305         return 0;
3306 }
3307
3308 static int action_ping(struct mansession *s, const struct message *m)
3309 {
3310         const char *actionid = astman_get_header(m, "ActionID");
3311         struct timeval now = ast_tvnow();
3312
3313         astman_append(s, "Response: Success\r\n");
3314         if (!ast_strlen_zero(actionid)){
3315                 astman_append(s, "ActionID: %s\r\n", actionid);
3316         }
3317         astman_append(
3318                 s,
3319                 "Ping: Pong\r\n"
3320                 "Timestamp: %ld.%06lu\r\n"
3321                 "\r\n",
3322                 (long) now.tv_sec, (unsigned long) now.tv_usec);
3323         return 0;
3324 }
3325
3326 static int action_getconfig(struct mansession *s, const struct message *m)
3327 {
3328         struct ast_config *cfg;
3329         const char *fn = astman_get_header(m, "Filename");
3330         const char *category = astman_get_header(m, "Category");
3331         const char *filter = astman_get_header(m, "Filter");
3332         const char *category_name;
3333         int catcount = 0;
3334         int lineno = 0;
3335         struct ast_category *cur_category = NULL;
3336         struct ast_variable *v;
3337         struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
3338
3339         if (ast_strlen_zero(fn)) {
3340                 astman_send_error(s, m, "Filename not specified");
3341                 return 0;
3342         }
3343
3344         cfg = ast_config_load2(fn, "manager", config_flags);
3345         if (cfg == CONFIG_STATUS_FILEMISSING) {
3346                 astman_send_error(s, m, "Config file not found");
3347           &