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