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