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