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