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