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