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