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