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