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