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