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