manager/config: Support templates and non-unique category names via AMI
[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="Resonse">
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                                 <parameter name="Context" />
1204                                 <parameter name="Hint" />
1205                                 <parameter name="Status" />
1206                                 <parameter name="StatusText" />
1207                         </syntax>
1208                 </managerEventInstance>
1209         </managerEvent>
1210         <managerEvent name="PresenceStatus" language="en_US">
1211                 <managerEventInstance class="EVENT_FLAG_CALL">
1212                         <synopsis>Raised when a hint changes due to a presence state change.</synopsis>
1213                         <syntax>
1214                                 <parameter name="Exten" />
1215                                 <parameter name="Context" />
1216                                 <parameter name="Hint" />
1217                                 <parameter name="Status" />
1218                                 <parameter name="Subtype" />
1219                                 <parameter name="Message" />
1220                         </syntax>
1221                 </managerEventInstance>
1222         </managerEvent>
1223  ***/
1224
1225 /*! \addtogroup Group_AMI AMI functions
1226 */
1227 /*! @{
1228  Doxygen group */
1229
1230 enum error_type {
1231         UNKNOWN_ACTION = 1,
1232         UNKNOWN_CATEGORY,
1233         UNSPECIFIED_CATEGORY,
1234         UNSPECIFIED_ARGUMENT,
1235         FAILURE_ALLOCATION,
1236         FAILURE_NEWCAT,
1237         FAILURE_DELCAT,
1238         FAILURE_EMPTYCAT,
1239         FAILURE_UPDATE,
1240         FAILURE_DELETE,
1241         FAILURE_APPEND,
1242         FAILURE_TEMPLATE
1243 };
1244
1245 enum add_filter_result {
1246         FILTER_SUCCESS,
1247         FILTER_ALLOC_FAILED,
1248         FILTER_COMPILE_FAIL,
1249 };
1250
1251 /*!
1252  * Linked list of events.
1253  * Global events are appended to the list by append_event().
1254  * The usecount is the number of stored pointers to the element,
1255  * excluding the list pointers. So an element that is only in
1256  * the list has a usecount of 0, not 1.
1257  *
1258  * Clients have a pointer to the last event processed, and for each
1259  * of these clients we track the usecount of the elements.
1260  * If we have a pointer to an entry in the list, it is safe to navigate
1261  * it forward because elements will not be deleted, but only appended.
1262  * The worst that can happen is seeing the pointer still NULL.
1263  *
1264  * When the usecount of an element drops to 0, and the element is the
1265  * first in the list, we can remove it. Removal is done within the
1266  * main thread, which is woken up for the purpose.
1267  *
1268  * For simplicity of implementation, we make sure the list is never empty.
1269  */
1270 struct eventqent {
1271         int usecount;           /*!< # of clients who still need the event */
1272         int category;
1273         unsigned int seq;       /*!< sequence number */
1274         struct timeval tv;  /*!< When event was allocated */
1275         AST_RWLIST_ENTRY(eventqent) eq_next;
1276         char eventdata[1];      /*!< really variable size, allocated by append_event() */
1277 };
1278
1279 static AST_RWLIST_HEAD_STATIC(all_events, eventqent);
1280
1281 static int displayconnects = 1;
1282 static int allowmultiplelogin = 1;
1283 static int timestampevents;
1284 static int httptimeout = 60;
1285 static int broken_events_action = 0;
1286 static int manager_enabled = 0;
1287 static int subscribed = 0;
1288 static int webmanager_enabled = 0;
1289 static int manager_debug = 0;   /*!< enable some debugging code in the manager */
1290 static int authtimeout;
1291 static int authlimit;
1292 static char *manager_channelvars;
1293
1294 #define DEFAULT_REALM           "asterisk"
1295 static char global_realm[MAXHOSTNAMELEN];       /*!< Default realm */
1296
1297 static int unauth_sessions = 0;
1298 static struct stasis_subscription *acl_change_sub;
1299
1300 /*! \brief A \ref stasis_topic that all topics AMI cares about will be forwarded to */
1301 static struct stasis_topic *manager_topic;
1302
1303 /*! \brief The \ref stasis_message_router for all \ref stasis messages */
1304 static struct stasis_message_router *stasis_router;
1305
1306 /*! \brief The \ref stasis_subscription for forwarding the RTP topic to the AMI topic */
1307 static struct stasis_forward *rtp_topic_forwarder;
1308
1309 /*! \brief The \ref stasis_subscription for forwarding the Security topic to the AMI topic */
1310 static struct stasis_forward *security_topic_forwarder;
1311
1312 #ifdef TEST_FRAMEWORK
1313 struct stasis_subscription *test_suite_sub;
1314 #endif
1315
1316 #define MGR_SHOW_TERMINAL_WIDTH 80
1317
1318 #define MAX_VARS 128
1319
1320 /*! \brief Fake event class used to end sessions at shutdown */
1321 #define EVENT_FLAG_SHUTDOWN -1
1322
1323 /*! \brief
1324  * Descriptor for a manager session, either on the AMI socket or over HTTP.
1325  *
1326  * \note
1327  * AMI session have managerid == 0; the entry is created upon a connect,
1328  * and destroyed with the socket.
1329  * HTTP sessions have managerid != 0, the value is used as a search key
1330  * to lookup sessions (using the mansession_id cookie, or nonce key from
1331  * Digest Authentication http header).
1332  */
1333 #define MAX_BLACKLIST_CMD_LEN 2
1334 static const struct {
1335         const char *words[AST_MAX_CMD_LEN];
1336 } command_blacklist[] = {
1337         {{ "module", "load", NULL }},
1338         {{ "module", "unload", NULL }},
1339         {{ "restart", "gracefully", NULL }},
1340 };
1341
1342 static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message);
1343
1344 static void acl_change_stasis_subscribe(void)
1345 {
1346         if (!acl_change_sub) {
1347                 acl_change_sub = stasis_subscribe(ast_security_topic(),
1348                         acl_change_stasis_cb, NULL);
1349         }
1350 }
1351
1352 static void acl_change_stasis_unsubscribe(void)
1353 {
1354         acl_change_sub = stasis_unsubscribe_and_join(acl_change_sub);
1355 }
1356
1357 /* In order to understand what the heck is going on with the
1358  * mansession_session and mansession structs, we need to have a bit of a history
1359  * lesson.
1360  *
1361  * In the beginning, there was the mansession. The mansession contained data that was
1362  * intrinsic to a manager session, such as the time that it started, the name of the logged-in
1363  * user, etc. In addition to these parameters were the f and fd parameters. For typical manager
1364  * sessions, these were used to represent the TCP socket over which the AMI session was taking
1365  * place. It makes perfect sense for these fields to be a part of the session-specific data since
1366  * the session actually defines this information.
1367  *
1368  * Then came the HTTP AMI sessions. With these, the f and fd fields need to be opened and closed
1369  * for every single action that occurs. Thus the f and fd fields aren't really specific to the session
1370  * but rather to the action that is being executed. Because a single session may execute many commands
1371  * at once, some sort of safety needed to be added in order to be sure that we did not end up with fd
1372  * leaks from one action overwriting the f and fd fields used by a previous action before the previous action
1373  * has had a chance to properly close its handles.
1374  *
1375  * The initial idea to solve this was to use thread synchronization, but this prevented multiple actions
1376  * from being run at the same time in a single session. Some manager actions may block for a long time, thus
1377  * creating a large queue of actions to execute. In addition, this fix did not address the basic architectural
1378  * issue that for HTTP manager sessions, the f and fd variables are not really a part of the session, but are
1379  * part of the action instead.
1380  *
1381  * The new idea was to create a structure on the stack for each HTTP Manager action. This structure would
1382  * contain the action-specific information, such as which file to write to. In order to maintain expectations
1383  * of action handlers and not have to change the public API of the manager code, we would need to name this
1384  * new stacked structure 'mansession' and contain within it the old mansession struct that we used to use.
1385  * We renamed the old mansession struct 'mansession_session' to hopefully convey that what is in this structure
1386  * is session-specific data. The structure that it is wrapped in, called a 'mansession' really contains action-specific
1387  * data.
1388  */
1389 struct mansession_session {
1390                                 /*! \todo XXX need to document which fields it is protecting */
1391         struct ast_sockaddr addr;       /*!< address we are connecting from */
1392         FILE *f;                /*!< fdopen() on the underlying fd */
1393         int fd;                 /*!< descriptor used for output. Either the socket (AMI) or a temporary file (HTTP) */
1394         int inuse;              /*!< number of HTTP sessions using this entry */
1395         int needdestroy;        /*!< Whether an HTTP session should be destroyed */
1396         pthread_t waiting_thread;       /*!< Sleeping thread using this descriptor */
1397         uint32_t managerid;     /*!< Unique manager identifier, 0 for AMI sessions */
1398         time_t sessionstart;    /*!< Session start time */
1399         struct timeval sessionstart_tv; /*!< Session start time */
1400         time_t sessiontimeout;  /*!< Session timeout if HTTP */
1401         char username[80];      /*!< Logged in username */
1402         char challenge[10];     /*!< Authentication challenge */
1403         int authenticated;      /*!< Authentication status */
1404         int readperm;           /*!< Authorization for reading */
1405         int writeperm;          /*!< Authorization for writing */
1406         char inbuf[1025];       /*!< Buffer -  we use the extra byte to add a '\\0' and simplify parsing */
1407         int inlen;              /*!< number of buffered bytes */
1408         struct ao2_container *whitefilters;     /*!< Manager event filters - white list */
1409         struct ao2_container *blackfilters;     /*!< Manager event filters - black list */
1410         struct ast_variable *chanvars;  /*!< Channel variables to set for originate */
1411         int send_events;        /*!<  XXX what ? */
1412         struct eventqent *last_ev;      /*!< last event processed. */
1413         int writetimeout;       /*!< Timeout for ast_carefulwrite() */
1414         time_t authstart;
1415         int pending_event;         /*!< Pending events indicator in case when waiting_thread is NULL */
1416         time_t noncetime;       /*!< Timer for nonce value expiration */
1417         unsigned long oldnonce; /*!< Stale nonce value */
1418         unsigned long nc;       /*!< incremental  nonce counter */
1419         AST_LIST_HEAD_NOLOCK(mansession_datastores, ast_datastore) datastores; /*!< Data stores on the session */
1420         AST_LIST_ENTRY(mansession_session) list;
1421 };
1422
1423 enum mansession_message_parsing {
1424         MESSAGE_OKAY,
1425         MESSAGE_LINE_TOO_LONG
1426 };
1427
1428 /*! \brief In case you didn't read that giant block of text above the mansession_session struct, the
1429  * \ref struct mansession is named this solely to keep the API the same in Asterisk. This structure really
1430  * represents data that is different from Manager action to Manager action. The mansession_session pointer
1431  * contained within points to session-specific data.
1432  */
1433 struct mansession {
1434         struct mansession_session *session;
1435         struct ast_tcptls_session_instance *tcptls_session;
1436         FILE *f;
1437         int fd;
1438         enum mansession_message_parsing parsing;
1439         int write_error:1;
1440         struct manager_custom_hook *hook;
1441         ast_mutex_t lock;
1442 };
1443
1444 /*! Active manager connection sessions container. */
1445 static AO2_GLOBAL_OBJ_STATIC(mgr_sessions);
1446
1447 /*! \brief user descriptor, as read from the config file.
1448  *
1449  * \note It is still missing some fields -- e.g. we can have multiple permit and deny
1450  * lines which are not supported here, and readperm/writeperm/writetimeout
1451  * are not stored.
1452  */
1453 struct ast_manager_user {
1454         char username[80];
1455         char *secret;                   /*!< Secret for logging in */
1456         int readperm;                   /*!< Authorization for reading */
1457         int writeperm;                  /*!< Authorization for writing */
1458         int writetimeout;               /*!< Per user Timeout for ast_carefulwrite() */
1459         int displayconnects;            /*!< XXX unused */
1460         int allowmultiplelogin; /*!< Per user option*/
1461         int keep;                       /*!< mark entries created on a reload */
1462         struct ao2_container *whitefilters; /*!< Manager event filters - white list */
1463         struct ao2_container *blackfilters; /*!< Manager event filters - black list */
1464         struct ast_acl_list *acl;       /*!< ACL setting */
1465         char *a1_hash;                  /*!< precalculated A1 for Digest auth */
1466         struct ast_variable *chanvars;  /*!< Channel variables to set for originate */
1467         AST_RWLIST_ENTRY(ast_manager_user) list;
1468 };
1469
1470 /*! \brief list of users found in the config file */
1471 static AST_RWLIST_HEAD_STATIC(users, ast_manager_user);
1472
1473 /*! \brief list of actions registered */
1474 static AST_RWLIST_HEAD_STATIC(actions, manager_action);
1475
1476 /*! \brief list of hooks registered */
1477 static AST_RWLIST_HEAD_STATIC(manager_hooks, manager_custom_hook);
1478
1479 /*! \brief A container of event documentation nodes */
1480 static AO2_GLOBAL_OBJ_STATIC(event_docs);
1481
1482 static enum add_filter_result manager_add_filter(const char *filter_pattern, struct ao2_container *whitefilters, struct ao2_container *blackfilters);
1483
1484 static int match_filter(struct mansession *s, char *eventdata);
1485
1486 /*!
1487  * @{ \brief Define AMI message types.
1488  */
1489 STASIS_MESSAGE_TYPE_DEFN(ast_manager_get_generic_type);
1490 /*! @} */
1491
1492 /*!
1493  * \internal
1494  * \brief Find a registered action object.
1495  *
1496  * \param name Name of AMI action to find.
1497  *
1498  * \return Reffed action found or NULL
1499  */
1500 static struct manager_action *action_find(const char *name)
1501 {
1502         struct manager_action *act;
1503
1504         AST_RWLIST_RDLOCK(&actions);
1505         AST_RWLIST_TRAVERSE(&actions, act, list) {
1506                 if (!strcasecmp(name, act->action)) {
1507                         ao2_t_ref(act, +1, "found action object");
1508                         break;
1509                 }
1510         }
1511         AST_RWLIST_UNLOCK(&actions);
1512
1513         return act;
1514 }
1515
1516 struct stasis_topic *ast_manager_get_topic(void)
1517 {
1518         return manager_topic;
1519 }
1520
1521 struct stasis_message_router *ast_manager_get_message_router(void)
1522 {
1523         return stasis_router;
1524 }
1525
1526 static void manager_json_value_str_append(struct ast_json *value, const char *key,
1527                                           struct ast_str **res)
1528 {
1529         switch (ast_json_typeof(value)) {
1530         case AST_JSON_STRING:
1531                 ast_str_append(res, 0, "%s: %s\r\n", key, ast_json_string_get(value));
1532                 break;
1533         case AST_JSON_INTEGER:
1534                 ast_str_append(res, 0, "%s: %jd\r\n", key, ast_json_integer_get(value));
1535                 break;
1536         case AST_JSON_TRUE:
1537                 ast_str_append(res, 0, "%s: True\r\n", key);
1538                 break;
1539         case AST_JSON_FALSE:
1540                 ast_str_append(res, 0, "%s: False\r\n", key);
1541                 break;
1542         default:
1543                 ast_str_append(res, 0, "%s: \r\n", key);
1544                 break;
1545         }
1546 }
1547
1548 static void manager_json_to_ast_str(struct ast_json *obj, const char *key,
1549                                     struct ast_str **res, key_exclusion_cb exclusion_cb);
1550
1551 static void manager_json_array_with_key(struct ast_json *obj, const char* key,
1552                                         size_t index, struct ast_str **res,
1553                                         key_exclusion_cb exclusion_cb)
1554 {
1555         struct ast_str *key_str = ast_str_alloca(64);
1556         ast_str_set(&key_str, 0, "%s(%zu)", key, index);
1557         manager_json_to_ast_str(obj, ast_str_buffer(key_str),
1558                                 res, exclusion_cb);
1559 }
1560
1561 static void manager_json_obj_with_key(struct ast_json *obj, const char* key,
1562                                       const char *parent_key, struct ast_str **res,
1563                                       key_exclusion_cb exclusion_cb)
1564 {
1565         if (parent_key) {
1566                 struct ast_str *key_str = ast_str_alloca(64);
1567                 ast_str_set(&key_str, 0, "%s/%s", parent_key, key);
1568                 manager_json_to_ast_str(obj, ast_str_buffer(key_str),
1569                                         res, exclusion_cb);
1570                 return;
1571         }
1572
1573         manager_json_to_ast_str(obj, key, res, exclusion_cb);
1574 }
1575
1576 void manager_json_to_ast_str(struct ast_json *obj, const char *key,
1577                              struct ast_str **res, key_exclusion_cb exclusion_cb)
1578 {
1579         struct ast_json_iter *i;
1580
1581         if (!obj || (!res && !(*res) && (!(*res = ast_str_create(1024))))) {
1582                 return;
1583         }
1584
1585         if (exclusion_cb && key && exclusion_cb(key)) {
1586                 return;
1587         }
1588
1589         if (ast_json_typeof(obj) != AST_JSON_OBJECT &&
1590             ast_json_typeof(obj) != AST_JSON_ARRAY) {
1591                 manager_json_value_str_append(obj, key, res);
1592                 return;
1593         }
1594
1595         if (ast_json_typeof(obj) == AST_JSON_ARRAY) {
1596                 size_t j;
1597                 for (j = 0; j < ast_json_array_size(obj); ++j) {
1598                         manager_json_array_with_key(ast_json_array_get(obj, j),
1599                                                     key, j, res, exclusion_cb);
1600                 }
1601                 return;
1602         }
1603
1604         for (i = ast_json_object_iter(obj); i;
1605              i = ast_json_object_iter_next(obj, i)) {
1606                 manager_json_obj_with_key(ast_json_object_iter_value(i),
1607                                           ast_json_object_iter_key(i),
1608                                           key, res, exclusion_cb);
1609         }
1610 }
1611
1612
1613 struct ast_str *ast_manager_str_from_json_object(struct ast_json *blob, key_exclusion_cb exclusion_cb)
1614 {
1615         struct ast_str *res = ast_str_create(1024);
1616         manager_json_to_ast_str(blob, NULL, &res, exclusion_cb);
1617         return res;
1618 }
1619
1620 static void manager_default_msg_cb(void *data, struct stasis_subscription *sub,
1621                                     struct stasis_message *message)
1622 {
1623         RAII_VAR(struct ast_manager_event_blob *, ev, NULL, ao2_cleanup);
1624
1625         ev = stasis_message_to_ami(message);
1626
1627         if (ev == NULL) {
1628                 /* Not and AMI message; disregard */
1629                 return;
1630         }
1631
1632         manager_event(ev->event_flags, ev->manager_event, "%s",
1633                 ev->extra_fields);
1634 }
1635
1636 static void manager_generic_msg_cb(void *data, struct stasis_subscription *sub,
1637                                     struct stasis_message *message)
1638 {
1639         struct ast_json_payload *payload = stasis_message_data(message);
1640         int class_type = ast_json_integer_get(ast_json_object_get(payload->json, "class_type"));
1641         const char *type = ast_json_string_get(ast_json_object_get(payload->json, "type"));
1642         struct ast_json *event = ast_json_object_get(payload->json, "event");
1643         RAII_VAR(struct ast_str *, event_buffer, NULL, ast_free);
1644
1645         event_buffer = ast_manager_str_from_json_object(event, NULL);
1646         if (!event_buffer) {
1647                 ast_log(AST_LOG_WARNING, "Error while creating payload for event %s\n", type);
1648                 return;
1649         }
1650         manager_event(class_type, type, "%s", ast_str_buffer(event_buffer));
1651 }
1652
1653 void ast_manager_publish_event(const char *type, int class_type, struct ast_json *obj)
1654 {
1655         RAII_VAR(struct ast_json *, event_info, NULL, ast_json_unref);
1656         RAII_VAR(struct ast_json_payload *, payload, NULL, ao2_cleanup);
1657         RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
1658
1659         if (!obj || !ast_manager_get_generic_type()) {
1660                 return;
1661         }
1662
1663         ast_json_ref(obj);
1664         event_info = ast_json_pack("{s: s, s: i, s: o}",
1665                         "type", type,
1666                         "class_type", class_type,
1667                         "event", obj);
1668         if (!event_info) {
1669                 return;
1670         }
1671
1672         payload = ast_json_payload_create(event_info);
1673         if (!payload) {
1674                 return;
1675         }
1676         message = stasis_message_create(ast_manager_get_generic_type(), payload);
1677         if (!message) {
1678                 return;
1679         }
1680         stasis_publish(ast_manager_get_topic(), message);
1681 }
1682
1683 /*! \brief Add a custom hook to be called when an event is fired */
1684 void ast_manager_register_hook(struct manager_custom_hook *hook)
1685 {
1686         AST_RWLIST_WRLOCK(&manager_hooks);
1687         AST_RWLIST_INSERT_TAIL(&manager_hooks, hook, list);
1688         AST_RWLIST_UNLOCK(&manager_hooks);
1689 }
1690
1691 /*! \brief Delete a custom hook to be called when an event is fired */
1692 void ast_manager_unregister_hook(struct manager_custom_hook *hook)
1693 {
1694         AST_RWLIST_WRLOCK(&manager_hooks);
1695         AST_RWLIST_REMOVE(&manager_hooks, hook, list);
1696         AST_RWLIST_UNLOCK(&manager_hooks);
1697 }
1698
1699 int check_manager_enabled(void)
1700 {
1701         return manager_enabled;
1702 }
1703
1704 int check_webmanager_enabled(void)
1705 {
1706         return (webmanager_enabled && manager_enabled);
1707 }
1708
1709 /*!
1710  * Grab a reference to the last event, update usecount as needed.
1711  * Can handle a NULL pointer.
1712  */
1713 static struct eventqent *grab_last(void)
1714 {
1715         struct eventqent *ret;
1716
1717         AST_RWLIST_WRLOCK(&all_events);
1718         ret = AST_RWLIST_LAST(&all_events);
1719         /* the list is never empty now, but may become so when
1720          * we optimize it in the future, so be prepared.
1721          */
1722         if (ret) {
1723                 ast_atomic_fetchadd_int(&ret->usecount, 1);
1724         }
1725         AST_RWLIST_UNLOCK(&all_events);
1726         return ret;
1727 }
1728
1729 /*!
1730  * Purge unused events. Remove elements from the head
1731  * as long as their usecount is 0 and there is a next element.
1732  */
1733 static void purge_events(void)
1734 {
1735         struct eventqent *ev;
1736         struct timeval now = ast_tvnow();
1737
1738         AST_RWLIST_WRLOCK(&all_events);
1739         while ( (ev = AST_RWLIST_FIRST(&all_events)) &&
1740             ev->usecount == 0 && AST_RWLIST_NEXT(ev, eq_next)) {
1741                 AST_RWLIST_REMOVE_HEAD(&all_events, eq_next);
1742                 ast_free(ev);
1743         }
1744
1745         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&all_events, ev, eq_next) {
1746                 /* Never release the last event */
1747                 if (!AST_RWLIST_NEXT(ev, eq_next)) {
1748                         break;
1749                 }
1750
1751                 /* 2.5 times whatever the HTTP timeout is (maximum 2.5 hours) is the maximum time that we will definitely cache an event */
1752                 if (ev->usecount == 0 && ast_tvdiff_sec(now, ev->tv) > (httptimeout > 3600 ? 3600 : httptimeout) * 2.5) {
1753                         AST_RWLIST_REMOVE_CURRENT(eq_next);
1754                         ast_free(ev);
1755                 }
1756         }
1757         AST_RWLIST_TRAVERSE_SAFE_END;
1758         AST_RWLIST_UNLOCK(&all_events);
1759 }
1760
1761 /*!
1762  * helper functions to convert back and forth between
1763  * string and numeric representation of set of flags
1764  */
1765 static const struct permalias {
1766         int num;
1767         const char *label;
1768 } perms[] = {
1769         { EVENT_FLAG_SYSTEM, "system" },
1770         { EVENT_FLAG_CALL, "call" },
1771         { EVENT_FLAG_LOG, "log" },
1772         { EVENT_FLAG_VERBOSE, "verbose" },
1773         { EVENT_FLAG_COMMAND, "command" },
1774         { EVENT_FLAG_AGENT, "agent" },
1775         { EVENT_FLAG_USER, "user" },
1776         { EVENT_FLAG_CONFIG, "config" },
1777         { EVENT_FLAG_DTMF, "dtmf" },
1778         { EVENT_FLAG_REPORTING, "reporting" },
1779         { EVENT_FLAG_CDR, "cdr" },
1780         { EVENT_FLAG_DIALPLAN, "dialplan" },
1781         { EVENT_FLAG_ORIGINATE, "originate" },
1782         { EVENT_FLAG_AGI, "agi" },
1783         { EVENT_FLAG_CC, "cc" },
1784         { EVENT_FLAG_AOC, "aoc" },
1785         { EVENT_FLAG_TEST, "test" },
1786         { EVENT_FLAG_SECURITY, "security" },
1787         { EVENT_FLAG_MESSAGE, "message" },
1788         { INT_MAX, "all" },
1789         { 0, "none" },
1790 };
1791
1792 /*! \brief Checks to see if a string which can be used to evaluate functions should be rejected */
1793 static int function_capable_string_allowed_with_auths(const char *evaluating, int writepermlist)
1794 {
1795         if (!(writepermlist & EVENT_FLAG_SYSTEM)
1796                 && (
1797                         strstr(evaluating, "SHELL") ||       /* NoOp(${SHELL(rm -rf /)})  */
1798                         strstr(evaluating, "EVAL")           /* NoOp(${EVAL(${some_var_containing_SHELL})}) */
1799                 )) {
1800                 return 0;
1801         }
1802         return 1;
1803 }
1804
1805 /*! \brief Convert authority code to a list of options for a user. This will only
1806  * display those authority codes that have an explicit match on authority */
1807 static const char *user_authority_to_str(int authority, struct ast_str **res)
1808 {
1809         int i;
1810         char *sep = "";
1811
1812         ast_str_reset(*res);
1813         for (i = 0; i < ARRAY_LEN(perms) - 1; i++) {
1814                 if ((authority & perms[i].num) == perms[i].num) {
1815                         ast_str_append(res, 0, "%s%s", sep, perms[i].label);
1816                         sep = ",";
1817                 }
1818         }
1819
1820         if (ast_str_strlen(*res) == 0)  /* replace empty string with something sensible */
1821                 ast_str_append(res, 0, "<none>");
1822
1823         return ast_str_buffer(*res);
1824 }
1825
1826
1827 /*! \brief Convert authority code to a list of options. Note that the EVENT_FLAG_ALL
1828  * authority will always be returned. */
1829 static const char *authority_to_str(int authority, struct ast_str **res)
1830 {
1831         int i;
1832         char *sep = "";
1833
1834         ast_str_reset(*res);
1835         for (i = 0; i < ARRAY_LEN(perms) - 1; i++) {
1836                 if (authority & perms[i].num) {
1837                         ast_str_append(res, 0, "%s%s", sep, perms[i].label);
1838                         sep = ",";
1839                 }
1840         }
1841
1842         if (ast_str_strlen(*res) == 0)  /* replace empty string with something sensible */
1843                 ast_str_append(res, 0, "<none>");
1844
1845         return ast_str_buffer(*res);
1846 }
1847
1848 /*! Tells you if smallstr exists inside bigstr
1849    which is delim by delim and uses no buf or stringsep
1850    ast_instring("this|that|more","this",'|') == 1;
1851
1852    feel free to move this to app.c -anthm */
1853 static int ast_instring(const char *bigstr, const char *smallstr, const char delim)
1854 {
1855         const char *val = bigstr, *next;
1856
1857         do {
1858                 if ((next = strchr(val, delim))) {
1859                         if (!strncmp(val, smallstr, (next - val))) {
1860                                 return 1;
1861                         } else {
1862                                 continue;
1863                         }
1864                 } else {
1865                         return !strcmp(smallstr, val);
1866                 }
1867         } while (*(val = (next + 1)));
1868
1869         return 0;
1870 }
1871
1872 static int get_perm(const char *instr)
1873 {
1874         int x = 0, ret = 0;
1875
1876         if (!instr) {
1877                 return 0;
1878         }
1879
1880         for (x = 0; x < ARRAY_LEN(perms); x++) {
1881                 if (ast_instring(instr, perms[x].label, ',')) {
1882                         ret |= perms[x].num;
1883                 }
1884         }
1885
1886         return ret;
1887 }
1888
1889 /*!
1890  * A number returns itself, false returns 0, true returns all flags,
1891  * other strings return the flags that are set.
1892  */
1893 static int strings_to_mask(const char *string)
1894 {
1895         const char *p;
1896
1897         if (ast_strlen_zero(string)) {
1898                 return -1;
1899         }
1900
1901         for (p = string; *p; p++) {
1902                 if (*p < '0' || *p > '9') {
1903                         break;
1904                 }
1905         }
1906         if (!*p) { /* all digits */
1907                 return atoi(string);
1908         }
1909         if (ast_false(string)) {
1910                 return 0;
1911         }
1912         if (ast_true(string)) { /* all permissions */
1913                 int x, ret = 0;
1914                 for (x = 0; x < ARRAY_LEN(perms); x++) {
1915                         ret |= perms[x].num;
1916                 }
1917                 return ret;
1918         }
1919         return get_perm(string);
1920 }
1921
1922 /*! \brief Unreference manager session object.
1923      If no more references, then go ahead and delete it */
1924 static struct mansession_session *unref_mansession(struct mansession_session *s)
1925 {
1926         int refcount = ao2_ref(s, -1);
1927         if (manager_debug) {
1928                 ast_debug(1, "Mansession: %p refcount now %d\n", s, refcount - 1);
1929         }
1930         return NULL;
1931 }
1932
1933 static void event_filter_destructor(void *obj)
1934 {
1935         regex_t *regex_filter = obj;
1936         regfree(regex_filter);
1937 }
1938
1939 static void session_destructor(void *obj)
1940 {
1941         struct mansession_session *session = obj;
1942         struct eventqent *eqe = session->last_ev;
1943         struct ast_datastore *datastore;
1944
1945         /* Get rid of each of the data stores on the session */
1946         while ((datastore = AST_LIST_REMOVE_HEAD(&session->datastores, entry))) {
1947                 /* Free the data store */
1948                 ast_datastore_free(datastore);
1949         }
1950
1951         if (session->f != NULL) {
1952                 fflush(session->f);
1953                 fclose(session->f);
1954         }
1955         if (eqe) {
1956                 ast_atomic_fetchadd_int(&eqe->usecount, -1);
1957         }
1958         if (session->chanvars) {
1959                 ast_variables_destroy(session->chanvars);
1960         }
1961
1962         if (session->whitefilters) {
1963                 ao2_t_ref(session->whitefilters, -1, "decrement ref for white container, should be last one");
1964         }
1965
1966         if (session->blackfilters) {
1967                 ao2_t_ref(session->blackfilters, -1, "decrement ref for black container, should be last one");
1968         }
1969 }
1970
1971 /*! \brief Allocate manager session structure and add it to the list of sessions */
1972 static struct mansession_session *build_mansession(const struct ast_sockaddr *addr)
1973 {
1974         struct ao2_container *sessions;
1975         struct mansession_session *newsession;
1976
1977         newsession = ao2_alloc(sizeof(*newsession), session_destructor);
1978         if (!newsession) {
1979                 return NULL;
1980         }
1981
1982         newsession->whitefilters = ao2_container_alloc(1, NULL, NULL);
1983         newsession->blackfilters = ao2_container_alloc(1, NULL, NULL);
1984         if (!newsession->whitefilters || !newsession->blackfilters) {
1985                 ao2_ref(newsession, -1);
1986                 return NULL;
1987         }
1988
1989         newsession->fd = -1;
1990         newsession->waiting_thread = AST_PTHREADT_NULL;
1991         newsession->writetimeout = 100;
1992         newsession->send_events = -1;
1993         ast_sockaddr_copy(&newsession->addr, addr);
1994
1995         sessions = ao2_global_obj_ref(mgr_sessions);
1996         if (sessions) {
1997                 ao2_link(sessions, newsession);
1998                 ao2_ref(sessions, -1);
1999         }
2000
2001         return newsession;
2002 }
2003
2004 static int mansession_cmp_fn(void *obj, void *arg, int flags)
2005 {
2006         struct mansession_session *s = obj;
2007         char *str = arg;
2008         return !strcasecmp(s->username, str) ? CMP_MATCH : 0;
2009 }
2010
2011 static void session_destroy(struct mansession_session *s)
2012 {
2013         struct ao2_container *sessions;
2014
2015         sessions = ao2_global_obj_ref(mgr_sessions);
2016         if (sessions) {
2017                 ao2_unlink(sessions, s);
2018                 ao2_ref(sessions, -1);
2019         }
2020         unref_mansession(s);
2021 }
2022
2023
2024 static int check_manager_session_inuse(const char *name)
2025 {
2026         struct ao2_container *sessions;
2027         struct mansession_session *session;
2028         int inuse = 0;
2029
2030         sessions = ao2_global_obj_ref(mgr_sessions);
2031         if (sessions) {
2032                 session = ao2_find(sessions, (char *) name, 0);
2033                 ao2_ref(sessions, -1);
2034                 if (session) {
2035                         unref_mansession(session);
2036                         inuse = 1;
2037                 }
2038         }
2039         return inuse;
2040 }
2041
2042
2043 /*!
2044  * lookup an entry in the list of registered users.
2045  * must be called with the list lock held.
2046  */
2047 static struct ast_manager_user *get_manager_by_name_locked(const char *name)
2048 {
2049         struct ast_manager_user *user = NULL;
2050
2051         AST_RWLIST_TRAVERSE(&users, user, list) {
2052                 if (!strcasecmp(user->username, name)) {
2053                         break;
2054                 }
2055         }
2056
2057         return user;
2058 }
2059
2060 /*! \brief Get displayconnects config option.
2061  *  \param session manager session to get parameter from.
2062  *  \return displayconnects config option value.
2063  */
2064 static int manager_displayconnects(struct mansession_session *session)
2065 {
2066         struct ast_manager_user *user = NULL;
2067         int ret = 0;
2068
2069         AST_RWLIST_RDLOCK(&users);
2070         if ((user = get_manager_by_name_locked(session->username))) {
2071                 ret = user->displayconnects;
2072         }
2073         AST_RWLIST_UNLOCK(&users);
2074
2075         return ret;
2076 }
2077
2078 static void print_event_instance(struct ast_cli_args *a, struct ast_xml_doc_item *instance);
2079
2080 static char *handle_showmancmd(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2081 {
2082         struct manager_action *cur;
2083         struct ast_str *authority;
2084         int num, l, which;
2085         char *ret = NULL;
2086 #ifdef AST_XML_DOCS
2087         char syntax_title[64], description_title[64], synopsis_title[64], seealso_title[64];
2088         char arguments_title[64], privilege_title[64], final_response_title[64], list_responses_title[64];
2089 #endif
2090
2091         switch (cmd) {
2092         case CLI_INIT:
2093                 e->command = "manager show command";
2094                 e->usage =
2095                         "Usage: manager show command <actionname> [<actionname> [<actionname> [...]]]\n"
2096                         "       Shows the detailed description for a specific Asterisk manager interface command.\n";
2097                 return NULL;
2098         case CLI_GENERATE:
2099                 l = strlen(a->word);
2100                 which = 0;
2101                 AST_RWLIST_RDLOCK(&actions);
2102                 AST_RWLIST_TRAVERSE(&actions, cur, list) {
2103                         if (!strncasecmp(a->word, cur->action, l) && ++which > a->n) {
2104                                 ret = ast_strdup(cur->action);
2105                                 break;  /* make sure we exit even if ast_strdup() returns NULL */
2106                         }
2107                 }
2108                 AST_RWLIST_UNLOCK(&actions);
2109                 return ret;
2110         }
2111         authority = ast_str_alloca(80);
2112         if (a->argc < 4) {
2113                 return CLI_SHOWUSAGE;
2114         }
2115
2116 #ifdef AST_XML_DOCS
2117         /* setup the titles */
2118         term_color(synopsis_title, "[Synopsis]\n", COLOR_MAGENTA, 0, 40);
2119         term_color(description_title, "[Description]\n", COLOR_MAGENTA, 0, 40);
2120         term_color(syntax_title, "[Syntax]\n", COLOR_MAGENTA, 0, 40);
2121         term_color(seealso_title, "[See Also]\n", COLOR_MAGENTA, 0, 40);
2122         term_color(arguments_title, "[Arguments]\n", COLOR_MAGENTA, 0, 40);
2123         term_color(privilege_title, "[Privilege]\n", COLOR_MAGENTA, 0, 40);
2124         term_color(final_response_title, "[Final Response]\n", COLOR_MAGENTA, 0, 40);
2125         term_color(list_responses_title, "[List Responses]\n", COLOR_MAGENTA, 0, 40);
2126 #endif
2127
2128         AST_RWLIST_RDLOCK(&actions);
2129         AST_RWLIST_TRAVERSE(&actions, cur, list) {
2130                 for (num = 3; num < a->argc; num++) {
2131                         if (!strcasecmp(cur->action, a->argv[num])) {
2132                                 authority_to_str(cur->authority, &authority);
2133
2134 #ifdef AST_XML_DOCS
2135                                 if (cur->docsrc == AST_XML_DOC) {
2136                                         char *syntax = ast_xmldoc_printable(S_OR(cur->syntax, "Not available"), 1);
2137                                         char *synopsis = ast_xmldoc_printable(S_OR(cur->synopsis, "Not available"), 1);
2138                                         char *description = ast_xmldoc_printable(S_OR(cur->description, "Not available"), 1);
2139                                         char *arguments = ast_xmldoc_printable(S_OR(cur->arguments, "Not available"), 1);
2140                                         char *seealso = ast_xmldoc_printable(S_OR(cur->seealso, "Not available"), 1);
2141                                         char *privilege = ast_xmldoc_printable(S_OR(authority->str, "Not available"), 1);
2142                                         char *responses = ast_xmldoc_printable("None", 1);
2143                                         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",
2144                                                 syntax_title, syntax,
2145                                                 synopsis_title, synopsis,
2146                                                 description_title, description,
2147                                                 arguments_title, arguments,
2148                                                 seealso_title, seealso,
2149                                                 privilege_title, privilege,
2150                                                 list_responses_title);
2151
2152                                         if (!cur->list_responses) {
2153                                                 ast_cli(a->fd, "%s\n\n", responses);
2154                                         } else {
2155                                                 struct ast_xml_doc_item *temp;
2156                                                 for (temp = cur->list_responses; temp; temp = AST_LIST_NEXT(temp, next)) {
2157                                                         ast_cli(a->fd, "Event: %s\n", temp->name);
2158                                                         print_event_instance(a, temp);
2159                                                 }
2160                                         }
2161
2162                                         ast_cli(a->fd, "%s", final_response_title);
2163
2164                                         if (!cur->final_response) {
2165                                                 ast_cli(a->fd, "%s\n\n", responses);
2166                                         } else {
2167                                                 ast_cli(a->fd, "Event: %s\n", cur->final_response->name);
2168                                                 print_event_instance(a, cur->final_response);
2169                                         }
2170                                 } else
2171 #endif
2172                                 {
2173                                         ast_cli(a->fd, "Action: %s\nSynopsis: %s\nPrivilege: %s\n%s\n",
2174                                                 cur->action, cur->synopsis,
2175                                                 authority->str,
2176                                                 S_OR(cur->description, ""));
2177                                 }
2178                         }
2179                 }
2180         }
2181         AST_RWLIST_UNLOCK(&actions);
2182
2183         return CLI_SUCCESS;
2184 }
2185
2186 static char *handle_mandebug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2187 {
2188         switch (cmd) {
2189         case CLI_INIT:
2190                 e->command = "manager set debug [on|off]";
2191                 e->usage = "Usage: manager set debug [on|off]\n Show, enable, disable debugging of the manager code.\n";
2192                 return NULL;
2193         case CLI_GENERATE:
2194                 return NULL;
2195         }
2196
2197         if (a->argc == 3) {
2198                 ast_cli(a->fd, "manager debug is %s\n", manager_debug? "on" : "off");
2199         } else if (a->argc == 4) {
2200                 if (!strcasecmp(a->argv[3], "on")) {
2201                         manager_debug = 1;
2202                 } else if (!strcasecmp(a->argv[3], "off")) {
2203                         manager_debug = 0;
2204                 } else {
2205                         return CLI_SHOWUSAGE;
2206                 }
2207         }
2208         return CLI_SUCCESS;
2209 }
2210
2211 static char *handle_showmanager(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2212 {
2213         struct ast_manager_user *user = NULL;
2214         int l, which;
2215         char *ret = NULL;
2216         struct ast_str *rauthority = ast_str_alloca(128);
2217         struct ast_str *wauthority = ast_str_alloca(128);
2218         struct ast_variable *v;
2219
2220         switch (cmd) {
2221         case CLI_INIT:
2222                 e->command = "manager show user";
2223                 e->usage =
2224                         " Usage: manager show user <user>\n"
2225                         "        Display all information related to the manager user specified.\n";
2226                 return NULL;
2227         case CLI_GENERATE:
2228                 l = strlen(a->word);
2229                 which = 0;
2230                 if (a->pos != 3) {
2231                         return NULL;
2232                 }
2233                 AST_RWLIST_RDLOCK(&users);
2234                 AST_RWLIST_TRAVERSE(&users, user, list) {
2235                         if ( !strncasecmp(a->word, user->username, l) && ++which > a->n ) {
2236                                 ret = ast_strdup(user->username);
2237                                 break;
2238                         }
2239                 }
2240                 AST_RWLIST_UNLOCK(&users);
2241                 return ret;
2242         }
2243
2244         if (a->argc != 4) {
2245                 return CLI_SHOWUSAGE;
2246         }
2247
2248         AST_RWLIST_RDLOCK(&users);
2249
2250         if (!(user = get_manager_by_name_locked(a->argv[3]))) {
2251                 ast_cli(a->fd, "There is no manager called %s\n", a->argv[3]);
2252                 AST_RWLIST_UNLOCK(&users);
2253                 return CLI_SUCCESS;
2254         }
2255
2256         ast_cli(a->fd, "\n");
2257         ast_cli(a->fd,
2258                 "          username: %s\n"
2259                 "            secret: %s\n"
2260                 "               ACL: %s\n"
2261                 "         read perm: %s\n"
2262                 "        write perm: %s\n"
2263                 "   displayconnects: %s\n"
2264                 "allowmultiplelogin: %s\n",
2265                 (user->username ? user->username : "(N/A)"),
2266                 (user->secret ? "<Set>" : "(N/A)"),
2267                 ((user->acl && !ast_acl_list_is_empty(user->acl)) ? "yes" : "no"),
2268                 user_authority_to_str(user->readperm, &rauthority),
2269                 user_authority_to_str(user->writeperm, &wauthority),
2270                 (user->displayconnects ? "yes" : "no"),
2271                 (user->allowmultiplelogin ? "yes" : "no"));
2272         ast_cli(a->fd, "         Variables: \n");
2273                 for (v = user->chanvars ; v ; v = v->next) {
2274                         ast_cli(a->fd, "                 %s = %s\n", v->name, v->value);
2275                 }
2276
2277         AST_RWLIST_UNLOCK(&users);
2278
2279         return CLI_SUCCESS;
2280 }
2281
2282 static char *handle_showmanagers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2283 {
2284         struct ast_manager_user *user = NULL;
2285         int count_amu = 0;
2286         switch (cmd) {
2287         case CLI_INIT:
2288                 e->command = "manager show users";
2289                 e->usage =
2290                         "Usage: manager show users\n"
2291                         "       Prints a listing of all managers that are currently configured on that\n"
2292                         " system.\n";
2293                 return NULL;
2294         case CLI_GENERATE:
2295                 return NULL;
2296         }
2297         if (a->argc != 3) {
2298                 return CLI_SHOWUSAGE;
2299         }
2300
2301         AST_RWLIST_RDLOCK(&users);
2302
2303         /* If there are no users, print out something along those lines */
2304         if (AST_RWLIST_EMPTY(&users)) {
2305                 ast_cli(a->fd, "There are no manager users.\n");
2306                 AST_RWLIST_UNLOCK(&users);
2307                 return CLI_SUCCESS;
2308         }
2309
2310         ast_cli(a->fd, "\nusername\n--------\n");
2311
2312         AST_RWLIST_TRAVERSE(&users, user, list) {
2313                 ast_cli(a->fd, "%s\n", user->username);
2314                 count_amu++;
2315         }
2316
2317         AST_RWLIST_UNLOCK(&users);
2318
2319         ast_cli(a->fd,"-------------------\n"
2320                       "%d manager users configured.\n", count_amu);
2321         return CLI_SUCCESS;
2322 }
2323
2324 /*! \brief  CLI command  manager list commands */
2325 static char *handle_showmancmds(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2326 {
2327         struct manager_action *cur;
2328         int name_len = 1;
2329         int space_remaining;
2330 #define HSMC_FORMAT "  %-*.*s  %-.*s\n"
2331         switch (cmd) {
2332         case CLI_INIT:
2333                 e->command = "manager show commands";
2334                 e->usage =
2335                         "Usage: manager show commands\n"
2336                         "       Prints a listing of all the available Asterisk manager interface commands.\n";
2337                 return NULL;
2338         case CLI_GENERATE:
2339                 return NULL;
2340         }
2341
2342         AST_RWLIST_RDLOCK(&actions);
2343         AST_RWLIST_TRAVERSE(&actions, cur, list) {
2344                 int incoming_len = strlen(cur->action);
2345                 if (incoming_len > name_len) {
2346                         name_len = incoming_len;
2347                 }
2348         }
2349
2350         space_remaining = MGR_SHOW_TERMINAL_WIDTH - name_len - 4;
2351         if (space_remaining < 0) {
2352                 space_remaining = 0;
2353         }
2354
2355         ast_cli(a->fd, HSMC_FORMAT, name_len, name_len, "Action", space_remaining, "Synopsis");
2356         ast_cli(a->fd, HSMC_FORMAT, name_len, name_len, "------", space_remaining, "--------");
2357
2358         AST_RWLIST_TRAVERSE(&actions, cur, list) {
2359                 ast_cli(a->fd, HSMC_FORMAT, name_len, name_len, cur->action, space_remaining, cur->synopsis);
2360         }
2361         AST_RWLIST_UNLOCK(&actions);
2362
2363         return CLI_SUCCESS;
2364 }
2365
2366 /*! \brief CLI command manager list connected */
2367 static char *handle_showmanconn(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2368 {
2369         struct ao2_container *sessions;
2370         struct mansession_session *session;
2371         time_t now = time(NULL);
2372 #define HSMCONN_FORMAT1 "  %-15.15s  %-55.55s  %-10.10s  %-10.10s  %-8.8s  %-8.8s  %-5.5s  %-5.5s\n"
2373 #define HSMCONN_FORMAT2 "  %-15.15s  %-55.55s  %-10d  %-10d  %-8d  %-8d  %-5.5d  %-5.5d\n"
2374         int count = 0;
2375         struct ao2_iterator i;
2376
2377         switch (cmd) {
2378         case CLI_INIT:
2379                 e->command = "manager show connected";
2380                 e->usage =
2381                         "Usage: manager show connected\n"
2382                         "       Prints a listing of the users that are currently connected to the\n"
2383                         "Asterisk manager interface.\n";
2384                 return NULL;
2385         case CLI_GENERATE:
2386                 return NULL;
2387         }
2388
2389         ast_cli(a->fd, HSMCONN_FORMAT1, "Username", "IP Address", "Start", "Elapsed", "FileDes", "HttpCnt", "Read", "Write");
2390
2391         sessions = ao2_global_obj_ref(mgr_sessions);
2392         if (sessions) {
2393                 i = ao2_iterator_init(sessions, 0);
2394                 ao2_ref(sessions, -1);
2395                 while ((session = ao2_iterator_next(&i))) {
2396                         ao2_lock(session);
2397                         ast_cli(a->fd, HSMCONN_FORMAT2, session->username,
2398                                 ast_sockaddr_stringify_addr(&session->addr),
2399                                 (int) (session->sessionstart),
2400                                 (int) (now - session->sessionstart),
2401                                 session->fd,
2402                                 session->inuse,
2403                                 session->readperm,
2404                                 session->writeperm);
2405                         count++;
2406                         ao2_unlock(session);
2407                         unref_mansession(session);
2408                 }
2409                 ao2_iterator_destroy(&i);
2410         }
2411         ast_cli(a->fd, "%d users connected.\n", count);
2412
2413         return CLI_SUCCESS;
2414 }
2415
2416 /*! \brief CLI command manager list eventq */
2417 /* Should change to "manager show connected" */
2418 static char *handle_showmaneventq(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2419 {
2420         struct eventqent *s;
2421         switch (cmd) {
2422         case CLI_INIT:
2423                 e->command = "manager show eventq";
2424                 e->usage =
2425                         "Usage: manager show eventq\n"
2426                         "       Prints a listing of all events pending in the Asterisk manger\n"
2427                         "event queue.\n";
2428                 return NULL;
2429         case CLI_GENERATE:
2430                 return NULL;
2431         }
2432         AST_RWLIST_RDLOCK(&all_events);
2433         AST_RWLIST_TRAVERSE(&all_events, s, eq_next) {
2434                 ast_cli(a->fd, "Usecount: %d\n", s->usecount);
2435                 ast_cli(a->fd, "Category: %d\n", s->category);
2436                 ast_cli(a->fd, "Event:\n%s", s->eventdata);
2437         }
2438         AST_RWLIST_UNLOCK(&all_events);
2439
2440         return CLI_SUCCESS;
2441 }
2442
2443 /*! \brief CLI command manager reload */
2444 static char *handle_manager_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2445 {
2446         switch (cmd) {
2447         case CLI_INIT:
2448                 e->command = "manager reload";
2449                 e->usage =
2450                         "Usage: manager reload\n"
2451                         "       Reloads the manager configuration.\n";
2452                 return NULL;
2453         case CLI_GENERATE:
2454                 return NULL;
2455         }
2456         if (a->argc > 2) {
2457                 return CLI_SHOWUSAGE;
2458         }
2459         reload_manager();
2460         return CLI_SUCCESS;
2461 }
2462
2463 static struct eventqent *advance_event(struct eventqent *e)
2464 {
2465         struct eventqent *next;
2466
2467         AST_RWLIST_RDLOCK(&all_events);
2468         if ((next = AST_RWLIST_NEXT(e, eq_next))) {
2469                 ast_atomic_fetchadd_int(&next->usecount, 1);
2470                 ast_atomic_fetchadd_int(&e->usecount, -1);
2471         }
2472         AST_RWLIST_UNLOCK(&all_events);
2473         return next;
2474 }
2475
2476 #define GET_HEADER_FIRST_MATCH  0
2477 #define GET_HEADER_LAST_MATCH   1
2478 #define GET_HEADER_SKIP_EMPTY   2
2479
2480 /*!
2481  * \brief Return a matching header value.
2482  *
2483  * \details
2484  * Generic function to return either the first or the last
2485  * matching header from a list of variables, possibly skipping
2486  * empty strings.
2487  *
2488  * \note At the moment there is only one use of this function in
2489  * this file, so we make it static.
2490  *
2491  * \note Never returns NULL.
2492  */
2493 static const char *__astman_get_header(const struct message *m, char *var, int mode)
2494 {
2495         int x, l = strlen(var);
2496         const char *result = "";
2497
2498         if (!m) {
2499                 return result;
2500         }
2501
2502         for (x = 0; x < m->hdrcount; x++) {
2503                 const char *h = m->headers[x];
2504                 if (!strncasecmp(var, h, l) && h[l] == ':') {
2505                         const char *value = h + l + 1;
2506                         value = ast_skip_blanks(value); /* ignore leading spaces in the value */
2507                         /* found a potential candidate */
2508                         if ((mode & GET_HEADER_SKIP_EMPTY) && ast_strlen_zero(value)) {
2509                                 continue;       /* not interesting */
2510                         }
2511                         if (mode & GET_HEADER_LAST_MATCH) {
2512                                 result = value; /* record the last match so far */
2513                         } else {
2514                                 return value;
2515                         }
2516                 }
2517         }
2518
2519         return result;
2520 }
2521
2522 /*!
2523  * \brief Return the first matching variable from an array.
2524  *
2525  * \note This is the legacy function and is implemented in
2526  * therms of __astman_get_header().
2527  *
2528  * \note Never returns NULL.
2529  */
2530 const char *astman_get_header(const struct message *m, char *var)
2531 {
2532         return __astman_get_header(m, var, GET_HEADER_FIRST_MATCH);
2533 }
2534
2535 /*!
2536  * \internal
2537  * \brief Process one "Variable:" header value string.
2538  *
2539  * \param head Current list of AMI variables to get new values added.
2540  * \param hdr_val Header value string to process.
2541  *
2542  * \return New variable list head.
2543  */
2544 static struct ast_variable *man_do_variable_value(struct ast_variable *head, const char *hdr_val)
2545 {
2546         char *parse;
2547         AST_DECLARE_APP_ARGS(args,
2548                 AST_APP_ARG(vars)[64];
2549         );
2550
2551         hdr_val = ast_skip_blanks(hdr_val); /* ignore leading spaces in the value */
2552         parse = ast_strdupa(hdr_val);
2553
2554         /* Break the header value string into name=val pair items. */
2555         AST_STANDARD_APP_ARGS(args, parse);
2556         if (args.argc) {
2557                 int y;
2558
2559                 /* Process each name=val pair item. */
2560                 for (y = 0; y < args.argc; y++) {
2561                         struct ast_variable *cur;
2562                         char *var;
2563                         char *val;
2564
2565                         if (!args.vars[y]) {
2566                                 continue;
2567                         }
2568                         var = val = args.vars[y];
2569                         strsep(&val, "=");
2570
2571                         /* XXX We may wish to trim whitespace from the strings. */
2572                         if (!val || ast_strlen_zero(var)) {
2573                                 continue;
2574                         }
2575
2576                         /* Create new variable list node and prepend it to the list. */
2577                         cur = ast_variable_new(var, val, "");
2578                         if (cur) {
2579                                 cur->next = head;
2580                                 head = cur;
2581                         }
2582                 }
2583         }
2584
2585         return head;
2586 }
2587
2588 struct ast_variable *astman_get_variables(const struct message *m)
2589 {
2590         return astman_get_variables_order(m, ORDER_REVERSE);
2591 }
2592
2593 struct ast_variable *astman_get_variables_order(const struct message *m,
2594         enum variable_orders order)
2595 {
2596         int varlen;
2597         int x;
2598         struct ast_variable *head = NULL;
2599
2600         static const char var_hdr[] = "Variable:";
2601
2602         /* Process all "Variable:" headers. */
2603         varlen = strlen(var_hdr);
2604         for (x = 0; x < m->hdrcount; x++) {
2605                 if (strncasecmp(var_hdr, m->headers[x], varlen)) {
2606                         continue;
2607                 }
2608                 head = man_do_variable_value(head, m->headers[x] + varlen);
2609         }
2610
2611         if (order == ORDER_NATURAL) {
2612                 head = ast_variables_reverse(head);
2613         }
2614
2615         return head;
2616 }
2617
2618 /*! \brief access for hooks to send action messages to ami */
2619 int ast_hook_send_action(struct manager_custom_hook *hook, const char *msg)
2620 {
2621         const char *action;
2622         int ret = 0;
2623         struct manager_action *act_found;
2624         struct mansession s = {.session = NULL, };
2625         struct message m = { 0 };
2626         char *dup_str;
2627         char *src;
2628         int x = 0;
2629         int curlen;
2630
2631         if (hook == NULL) {
2632                 return -1;
2633         }
2634
2635         /* Create our own copy of the AMI action msg string. */
2636         src = dup_str = ast_strdup(msg);
2637         if (!dup_str) {
2638                 return -1;
2639         }
2640
2641         /* convert msg string to message struct */
2642         curlen = strlen(src);
2643         for (x = 0; x < curlen; x++) {
2644                 int cr; /* set if we have \r */
2645                 if (src[x] == '\r' && x+1 < curlen && src[x+1] == '\n')
2646                         cr = 2; /* Found. Update length to include \r\n */
2647                 else if (src[x] == '\n')
2648                         cr = 1; /* also accept \n only */
2649                 else
2650                         continue;
2651                 /* don't keep empty lines */
2652                 if (x && m.hdrcount < ARRAY_LEN(m.headers)) {
2653                         /* ... but trim \r\n and terminate the header string */
2654                         src[x] = '\0';
2655                         m.headers[m.hdrcount++] = src;
2656                 }
2657                 x += cr;
2658                 curlen -= x;            /* remaining size */
2659                 src += x;               /* update pointer */
2660                 x = -1;                 /* reset loop */
2661         }
2662
2663         action = astman_get_header(&m, "Action");
2664         if (strcasecmp(action, "login")) {
2665                 act_found = action_find(action);
2666                 if (act_found) {
2667                         /*
2668                          * we have to simulate a session for this action request
2669                          * to be able to pass it down for processing
2670                          * This is necessary to meet the previous design of manager.c
2671                          */
2672                         s.hook = hook;
2673                         s.f = (void*)1; /* set this to something so our request will make it through all functions that test it*/
2674
2675                         ao2_lock(act_found);
2676                         if (act_found->registered && act_found->func) {
2677                                 if (act_found->module) {
2678                                         ast_module_ref(act_found->module);
2679                                 }
2680                                 ao2_unlock(act_found);
2681                                 ret = act_found->func(&s, &m);
2682                                 ao2_lock(act_found);
2683                                 if (act_found->module) {
2684                                         ast_module_unref(act_found->module);
2685                                 }
2686                         } else {
2687                                 ret = -1;
2688                         }
2689                         ao2_unlock(act_found);
2690                         ao2_t_ref(act_found, -1, "done with found action object");
2691                 }
2692         }
2693         ast_free(dup_str);
2694         return ret;
2695 }
2696
2697
2698 /*!
2699  * helper function to send a string to the socket.
2700  * Return -1 on error (e.g. buffer full).
2701  */
2702 static int send_string(struct mansession *s, char *string)
2703 {
2704         int res;
2705         FILE *f = s->f ? s->f : s->session->f;
2706         int fd = s->f ? s->fd : s->session->fd;
2707
2708         /* It's a result from one of the hook's action invocation */
2709         if (s->hook) {
2710                 /*
2711                  * to send responses, we're using the same function
2712                  * as for receiving events. We call the event "HookResponse"
2713                  */
2714                 s->hook->helper(EVENT_FLAG_HOOKRESPONSE, "HookResponse", string);
2715                 return 0;
2716         }
2717
2718         if ((res = ast_careful_fwrite(f, fd, string, strlen(string), s->session->writetimeout))) {
2719                 s->write_error = 1;
2720         }
2721
2722         return res;
2723 }
2724
2725 /*!
2726  * \brief thread local buffer for astman_append
2727  *
2728  * \note This can not be defined within the astman_append() function
2729  *       because it declares a couple of functions that get used to
2730  *       initialize the thread local storage key.
2731  */
2732 AST_THREADSTORAGE(astman_append_buf);
2733
2734 AST_THREADSTORAGE(userevent_buf);
2735
2736 /*! \brief initial allocated size for the astman_append_buf and astman_send_*_va */
2737 #define ASTMAN_APPEND_BUF_INITSIZE   256
2738
2739 /*!
2740  * utility functions for creating AMI replies
2741  */
2742 void astman_append(struct mansession *s, const char *fmt, ...)
2743 {
2744         va_list ap;
2745         struct ast_str *buf;
2746
2747         if (!(buf = ast_str_thread_get(&astman_append_buf, ASTMAN_APPEND_BUF_INITSIZE))) {
2748                 return;
2749         }
2750
2751         va_start(ap, fmt);
2752         ast_str_set_va(&buf, 0, fmt, ap);
2753         va_end(ap);
2754
2755         if (s->f != NULL || s->session->f != NULL) {
2756                 send_string(s, ast_str_buffer(buf));
2757         } else {
2758                 ast_verbose("fd == -1 in astman_append, should not happen\n");
2759         }
2760 }
2761
2762 /*! \note NOTE: XXX this comment is unclear and possibly wrong.
2763    Callers of astman_send_error(), astman_send_response() or astman_send_ack() must EITHER
2764    hold the session lock _or_ be running in an action callback (in which case s->session->busy will
2765    be non-zero). In either of these cases, there is no need to lock-protect the session's
2766    fd, since no other output will be sent (events will be queued), and no input will
2767    be read until either the current action finishes or get_input() obtains the session
2768    lock.
2769  */
2770
2771 /*! \todo XXX MSG_MOREDATA should go to a header file. */
2772 #define MSG_MOREDATA    ((char *)astman_send_response)
2773
2774 /*! \brief send a response with an optional message,
2775  * and terminate it with an empty line.
2776  * m is used only to grab the 'ActionID' field.
2777  *
2778  * Use the explicit constant MSG_MOREDATA to remove the empty line.
2779  * XXX MSG_MOREDATA should go to a header file.
2780  */
2781 static void astman_send_response_full(struct mansession *s, const struct message *m, char *resp, char *msg, char *listflag)
2782 {
2783         const char *id = astman_get_header(m, "ActionID");
2784
2785         astman_append(s, "Response: %s\r\n", resp);
2786         if (!ast_strlen_zero(id)) {
2787                 astman_append(s, "ActionID: %s\r\n", id);
2788         }
2789         if (listflag) {
2790                 astman_append(s, "EventList: %s\r\n", listflag);        /* Start, complete, cancelled */
2791         }
2792         if (msg == MSG_MOREDATA) {
2793                 return;
2794         } else if (msg) {
2795                 astman_append(s, "Message: %s\r\n\r\n", msg);
2796         } else {
2797                 astman_append(s, "\r\n");
2798         }
2799 }
2800
2801 void astman_send_response(struct mansession *s, const struct message *m, char *resp, char *msg)
2802 {
2803         astman_send_response_full(s, m, resp, msg, NULL);
2804 }
2805
2806 void astman_send_error(struct mansession *s, const struct message *m, char *error)
2807 {
2808         astman_send_response_full(s, m, "Error", error, NULL);
2809 }
2810
2811 void astman_send_error_va(struct mansession *s, const struct message *m, const char *fmt, ...)
2812 {
2813         va_list ap;
2814         struct ast_str *buf;
2815         char *msg;
2816
2817         if (!(buf = ast_str_thread_get(&astman_append_buf, ASTMAN_APPEND_BUF_INITSIZE))) {
2818                 return;
2819         }
2820
2821         va_start(ap, fmt);
2822         ast_str_set_va(&buf, 0, fmt, ap);
2823         va_end(ap);
2824
2825         /* astman_append will use the same underlying buffer, so copy the message out
2826          * before sending the response */
2827         msg = ast_str_buffer(buf);
2828         if (msg) {
2829                 msg = ast_strdupa(msg);
2830         }
2831         astman_send_response_full(s, m, "Error", msg, NULL);
2832 }
2833
2834 void astman_send_ack(struct mansession *s, const struct message *m, char *msg)
2835 {
2836         astman_send_response_full(s, m, "Success", msg, NULL);
2837 }
2838
2839 static void astman_start_ack(struct mansession *s, const struct message *m)
2840 {
2841         astman_send_response_full(s, m, "Success", MSG_MOREDATA, NULL);
2842 }
2843
2844 void astman_send_listack(struct mansession *s, const struct message *m, char *msg, char *listflag)
2845 {
2846         astman_send_response_full(s, m, "Success", msg, listflag);
2847 }
2848
2849 /*! \brief Lock the 'mansession' structure. */
2850 static void mansession_lock(struct mansession *s)
2851 {
2852         ast_mutex_lock(&s->lock);
2853 }
2854
2855 /*! \brief Unlock the 'mansession' structure. */
2856 static void mansession_unlock(struct mansession *s)
2857 {
2858         ast_mutex_unlock(&s->lock);
2859 }
2860
2861 /*! \brief
2862    Rather than braindead on,off this now can also accept a specific int mask value
2863    or a ',' delim list of mask strings (the same as manager.conf) -anthm
2864 */
2865 static int set_eventmask(struct mansession *s, const char *eventmask)
2866 {
2867         int maskint = strings_to_mask(eventmask);
2868
2869         ao2_lock(s->session);
2870         if (maskint >= 0) {
2871                 s->session->send_events = maskint;
2872         }
2873         ao2_unlock(s->session);
2874
2875         return maskint;
2876 }
2877
2878 static enum ast_transport mansession_get_transport(const struct mansession *s)
2879 {
2880         return s->tcptls_session->parent->tls_cfg ? AST_TRANSPORT_TLS :
2881                         AST_TRANSPORT_TCP;
2882 }
2883
2884 static void report_invalid_user(const struct mansession *s, const char *username)
2885 {
2886         char session_id[32];
2887         struct ast_security_event_inval_acct_id inval_acct_id = {
2888                 .common.event_type = AST_SECURITY_EVENT_INVAL_ACCT_ID,
2889                 .common.version    = AST_SECURITY_EVENT_INVAL_ACCT_ID_VERSION,
2890                 .common.service    = "AMI",
2891                 .common.account_id = username,
2892                 .common.session_tv = &s->session->sessionstart_tv,
2893                 .common.local_addr = {
2894                         .addr      = &s->tcptls_session->parent->local_address,
2895                         .transport = mansession_get_transport(s),
2896                 },
2897                 .common.remote_addr = {
2898                         .addr      = &s->session->addr,
2899                         .transport = mansession_get_transport(s),
2900                 },
2901                 .common.session_id = session_id,
2902         };
2903
2904         snprintf(session_id, sizeof(session_id), "%p", s);
2905
2906         ast_security_event_report(AST_SEC_EVT(&inval_acct_id));
2907 }
2908
2909 static void report_failed_acl(const struct mansession *s, const char *username)
2910 {
2911         char session_id[32];
2912         struct ast_security_event_failed_acl failed_acl_event = {
2913                 .common.event_type = AST_SECURITY_EVENT_FAILED_ACL,
2914                 .common.version    = AST_SECURITY_EVENT_FAILED_ACL_VERSION,
2915                 .common.service    = "AMI",
2916                 .common.account_id = username,
2917                 .common.session_tv = &s->session->sessionstart_tv,
2918                 .common.local_addr = {
2919                         .addr      = &s->tcptls_session->parent->local_address,
2920                         .transport = mansession_get_transport(s),
2921                 },
2922                 .common.remote_addr = {
2923                         .addr      = &s->session->addr,
2924                         .transport = mansession_get_transport(s),
2925                 },
2926                 .common.session_id = session_id,
2927         };
2928
2929         snprintf(session_id, sizeof(session_id), "%p", s->session);
2930
2931         ast_security_event_report(AST_SEC_EVT(&failed_acl_event));
2932 }
2933
2934 static void report_inval_password(const struct mansession *s, const char *username)
2935 {
2936         char session_id[32];
2937         struct ast_security_event_inval_password inval_password = {
2938                 .common.event_type = AST_SECURITY_EVENT_INVAL_PASSWORD,
2939                 .common.version    = AST_SECURITY_EVENT_INVAL_PASSWORD_VERSION,
2940                 .common.service    = "AMI",
2941                 .common.account_id = username,
2942                 .common.session_tv = &s->session->sessionstart_tv,
2943                 .common.local_addr = {
2944                         .addr      = &s->tcptls_session->parent->local_address,
2945                         .transport = mansession_get_transport(s),
2946                 },
2947                 .common.remote_addr = {
2948                         .addr      = &s->session->addr,
2949                         .transport = mansession_get_transport(s),
2950                 },
2951                 .common.session_id = session_id,
2952         };
2953
2954         snprintf(session_id, sizeof(session_id), "%p", s->session);