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