Don't display the AMI ALL class authorization for users if they don't have it
[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 whether there are messages waiting.</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 for a user. This will only
1361  * display those authority codes that have an explicit match on authority */
1362 static const char *user_authority_to_str(int authority, struct ast_str **res)
1363 {
1364         int i;
1365         char *sep = "";
1366
1367         ast_str_reset(*res);
1368         for (i = 0; i < ARRAY_LEN(perms) - 1; i++) {
1369                 if ((authority & perms[i].num) == perms[i].num) {
1370                         ast_str_append(res, 0, "%s%s", sep, perms[i].label);
1371                         sep = ",";
1372                 }
1373         }
1374
1375         if (ast_str_strlen(*res) == 0)  /* replace empty string with something sensible */
1376                 ast_str_append(res, 0, "<none>");
1377
1378         return ast_str_buffer(*res);
1379 }
1380
1381
1382 /*! \brief Convert authority code to a list of options. Note that the EVENT_FLAG_ALL
1383  * authority will always be returned. */
1384 static const char *authority_to_str(int authority, struct ast_str **res)
1385 {
1386         int i;
1387         char *sep = "";
1388
1389         ast_str_reset(*res);
1390         for (i = 0; i < ARRAY_LEN(perms) - 1; i++) {
1391                 if (authority & perms[i].num) {
1392                         ast_str_append(res, 0, "%s%s", sep, perms[i].label);
1393                         sep = ",";
1394                 }
1395         }
1396
1397         if (ast_str_strlen(*res) == 0)  /* replace empty string with something sensible */
1398                 ast_str_append(res, 0, "<none>");
1399
1400         return ast_str_buffer(*res);
1401 }
1402
1403 /*! Tells you if smallstr exists inside bigstr
1404    which is delim by delim and uses no buf or stringsep
1405    ast_instring("this|that|more","this",'|') == 1;
1406
1407    feel free to move this to app.c -anthm */
1408 static int ast_instring(const char *bigstr, const char *smallstr, const char delim)
1409 {
1410         const char *val = bigstr, *next;
1411
1412         do {
1413                 if ((next = strchr(val, delim))) {
1414                         if (!strncmp(val, smallstr, (next - val))) {
1415                                 return 1;
1416                         } else {
1417                                 continue;
1418                         }
1419                 } else {
1420                         return !strcmp(smallstr, val);
1421                 }
1422         } while (*(val = (next + 1)));
1423
1424         return 0;
1425 }
1426
1427 static int get_perm(const char *instr)
1428 {
1429         int x = 0, ret = 0;
1430
1431         if (!instr) {
1432                 return 0;
1433         }
1434
1435         for (x = 0; x < ARRAY_LEN(perms); x++) {
1436                 if (ast_instring(instr, perms[x].label, ',')) {
1437                         ret |= perms[x].num;
1438                 }
1439         }
1440
1441         return ret;
1442 }
1443
1444 /*!
1445  * A number returns itself, false returns 0, true returns all flags,
1446  * other strings return the flags that are set.
1447  */
1448 static int strings_to_mask(const char *string)
1449 {
1450         const char *p;
1451
1452         if (ast_strlen_zero(string)) {
1453                 return -1;
1454         }
1455
1456         for (p = string; *p; p++) {
1457                 if (*p < '0' || *p > '9') {
1458                         break;
1459                 }
1460         }
1461         if (!*p) { /* all digits */
1462                 return atoi(string);
1463         }
1464         if (ast_false(string)) {
1465                 return 0;
1466         }
1467         if (ast_true(string)) { /* all permissions */
1468                 int x, ret = 0;
1469                 for (x = 0; x < ARRAY_LEN(perms); x++) {
1470                         ret |= perms[x].num;
1471                 }
1472                 return ret;
1473         }
1474         return get_perm(string);
1475 }
1476
1477 /*! \brief Unreference manager session object.
1478      If no more references, then go ahead and delete it */
1479 static struct mansession_session *unref_mansession(struct mansession_session *s)
1480 {
1481         int refcount = ao2_ref(s, -1);
1482         if (manager_debug) {
1483                 ast_debug(1, "Mansession: %p refcount now %d\n", s, refcount - 1);
1484         }
1485         return s;
1486 }
1487
1488 static void event_filter_destructor(void *obj)
1489 {
1490         regex_t *regex_filter = obj;
1491         regfree(regex_filter);
1492 }
1493
1494 static void session_destructor(void *obj)
1495 {
1496         struct mansession_session *session = obj;
1497         struct eventqent *eqe = session->last_ev;
1498         struct ast_datastore *datastore;
1499
1500         /* Get rid of each of the data stores on the session */
1501         while ((datastore = AST_LIST_REMOVE_HEAD(&session->datastores, entry))) {
1502                 /* Free the data store */
1503                 ast_datastore_free(datastore);
1504         }
1505
1506         if (session->f != NULL) {
1507                 fclose(session->f);
1508         }
1509         if (eqe) {
1510                 ast_atomic_fetchadd_int(&eqe->usecount, -1);
1511         }
1512         if (session->chanvars) {
1513                 ast_variables_destroy(session->chanvars);
1514         }
1515
1516         if (session->whitefilters) {
1517                 ao2_t_callback(session->whitefilters, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL, "unlink all white filters");
1518                 ao2_t_ref(session->whitefilters, -1 , "decrement ref for white container, should be last one");
1519         }
1520
1521         if (session->blackfilters) {
1522                 ao2_t_callback(session->blackfilters, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL, "unlink all black filters");
1523                 ao2_t_ref(session->blackfilters, -1 , "decrement ref for black container, should be last one");
1524         }
1525 }
1526
1527 /*! \brief Allocate manager session structure and add it to the list of sessions */
1528 static struct mansession_session *build_mansession(const struct ast_sockaddr *addr)
1529 {
1530         struct mansession_session *newsession;
1531
1532         if (!(newsession = ao2_alloc(sizeof(*newsession), session_destructor))) {
1533                 return NULL;
1534         }
1535
1536         if (!(newsession->whitefilters = ao2_container_alloc(1, NULL, NULL))) {
1537                 ao2_ref(newsession, -1);
1538                 return NULL;
1539         }
1540
1541         if (!(newsession->blackfilters = ao2_container_alloc(1, NULL, NULL))) {
1542                 ao2_ref(newsession, -1); /* session_destructor will cleanup the other filter */
1543                 return NULL;
1544         }
1545
1546         newsession->fd = -1;
1547         newsession->waiting_thread = AST_PTHREADT_NULL;
1548         newsession->writetimeout = 100;
1549         newsession->send_events = -1;
1550         ast_sockaddr_copy(&newsession->addr, addr);
1551
1552         ao2_link(sessions, newsession);
1553
1554         return newsession;
1555 }
1556
1557 static int mansession_cmp_fn(void *obj, void *arg, int flags)
1558 {
1559         struct mansession_session *s = obj;
1560         char *str = arg;
1561         return !strcasecmp(s->username, str) ? CMP_MATCH : 0;
1562 }
1563
1564 static void session_destroy(struct mansession_session *s)
1565 {
1566         unref_mansession(s);
1567         ao2_unlink(sessions, s);
1568 }
1569
1570
1571 static int check_manager_session_inuse(const char *name)
1572 {
1573         struct mansession_session *session = ao2_find(sessions, (char *) name, 0);
1574         int inuse = 0;
1575
1576         if (session) {
1577                 inuse = 1;
1578                 unref_mansession(session);
1579         }
1580         return inuse;
1581 }
1582
1583
1584 /*!
1585  * lookup an entry in the list of registered users.
1586  * must be called with the list lock held.
1587  */
1588 static struct ast_manager_user *get_manager_by_name_locked(const char *name)
1589 {
1590         struct ast_manager_user *user = NULL;
1591
1592         AST_RWLIST_TRAVERSE(&users, user, list) {
1593                 if (!strcasecmp(user->username, name)) {
1594                         break;
1595                 }
1596         }
1597
1598         return user;
1599 }
1600
1601 /*! \brief Get displayconnects config option.
1602  *  \param session manager session to get parameter from.
1603  *  \return displayconnects config option value.
1604  */
1605 static int manager_displayconnects (struct mansession_session *session)
1606 {
1607         struct ast_manager_user *user = NULL;
1608         int ret = 0;
1609
1610         AST_RWLIST_RDLOCK(&users);
1611         if ((user = get_manager_by_name_locked (session->username))) {
1612                 ret = user->displayconnects;
1613         }
1614         AST_RWLIST_UNLOCK(&users);
1615
1616         return ret;
1617 }
1618
1619 static char *handle_showmancmd(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1620 {
1621         struct manager_action *cur;
1622         struct ast_str *authority;
1623         int num, l, which;
1624         char *ret = NULL;
1625 #ifdef AST_XML_DOCS
1626         char syntax_title[64], description_title[64], synopsis_title[64], seealso_title[64], arguments_title[64], privilege_title[64];
1627 #endif
1628
1629         switch (cmd) {
1630         case CLI_INIT:
1631                 e->command = "manager show command";
1632                 e->usage =
1633                         "Usage: manager show command <actionname> [<actionname> [<actionname> [...]]]\n"
1634                         "       Shows the detailed description for a specific Asterisk manager interface command.\n";
1635                 return NULL;
1636         case CLI_GENERATE:
1637                 l = strlen(a->word);
1638                 which = 0;
1639                 AST_RWLIST_RDLOCK(&actions);
1640                 AST_RWLIST_TRAVERSE(&actions, cur, list) {
1641                         if (!strncasecmp(a->word, cur->action, l) && ++which > a->n) {
1642                                 ret = ast_strdup(cur->action);
1643                                 break;  /* make sure we exit even if ast_strdup() returns NULL */
1644                         }
1645                 }
1646                 AST_RWLIST_UNLOCK(&actions);
1647                 return ret;
1648         }
1649         authority = ast_str_alloca(80);
1650         if (a->argc < 4) {
1651                 return CLI_SHOWUSAGE;
1652         }
1653
1654 #ifdef AST_XML_DOCS
1655         /* setup the titles */
1656         term_color(synopsis_title, "[Synopsis]\n", COLOR_MAGENTA, 0, 40);
1657         term_color(description_title, "[Description]\n", COLOR_MAGENTA, 0, 40);
1658         term_color(syntax_title, "[Syntax]\n", COLOR_MAGENTA, 0, 40);
1659         term_color(seealso_title, "[See Also]\n", COLOR_MAGENTA, 0, 40);
1660         term_color(arguments_title, "[Arguments]\n", COLOR_MAGENTA, 0, 40);
1661         term_color(privilege_title, "[Privilege]\n", COLOR_MAGENTA, 0, 40);
1662 #endif
1663
1664         AST_RWLIST_RDLOCK(&actions);
1665         AST_RWLIST_TRAVERSE(&actions, cur, list) {
1666                 for (num = 3; num < a->argc; num++) {
1667                         if (!strcasecmp(cur->action, a->argv[num])) {
1668                                 authority_to_str(cur->authority, &authority);
1669
1670 #ifdef AST_XML_DOCS
1671                                 if (cur->docsrc == AST_XML_DOC) {
1672                                         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",
1673                                                 syntax_title,
1674                                                 ast_xmldoc_printable(S_OR(cur->syntax, "Not available"), 1),
1675                                                 synopsis_title,
1676                                                 ast_xmldoc_printable(S_OR(cur->synopsis, "Not available"), 1),
1677                                                 description_title,
1678                                                 ast_xmldoc_printable(S_OR(cur->description, "Not available"), 1),
1679                                                 arguments_title,
1680                                                 ast_xmldoc_printable(S_OR(cur->arguments, "Not available"), 1),
1681                                                 seealso_title,
1682                                                 ast_xmldoc_printable(S_OR(cur->seealso, "Not available"), 1),
1683                                                 privilege_title,
1684                                                 ast_xmldoc_printable(S_OR(authority->str, "Not available"), 1));
1685                                 } else
1686 #endif
1687                                 {
1688                                         ast_cli(a->fd, "Action: %s\nSynopsis: %s\nPrivilege: %s\n%s\n",
1689                                                 cur->action, cur->synopsis,
1690                                                 authority->str,
1691                                                 S_OR(cur->description, ""));
1692                                 }
1693                         }
1694                 }
1695         }
1696         AST_RWLIST_UNLOCK(&actions);
1697
1698         return CLI_SUCCESS;
1699 }
1700
1701 static char *handle_mandebug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1702 {
1703         switch (cmd) {
1704         case CLI_INIT:
1705                 e->command = "manager set debug [on|off]";
1706                 e->usage = "Usage: manager set debug [on|off]\n Show, enable, disable debugging of the manager code.\n";
1707                 return NULL;
1708         case CLI_GENERATE:
1709                 return NULL;
1710         }
1711
1712         if (a->argc == 3) {
1713                 ast_cli(a->fd, "manager debug is %s\n", manager_debug? "on" : "off");
1714         } else if (a->argc == 4) {
1715                 if (!strcasecmp(a->argv[3], "on")) {
1716                         manager_debug = 1;
1717                 } else if (!strcasecmp(a->argv[3], "off")) {
1718                         manager_debug = 0;
1719                 } else {
1720                         return CLI_SHOWUSAGE;
1721                 }
1722         }
1723         return CLI_SUCCESS;
1724 }
1725
1726 static char *handle_showmanager(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1727 {
1728         struct ast_manager_user *user = NULL;
1729         int l, which;
1730         char *ret = NULL;
1731         struct ast_str *rauthority = ast_str_alloca(128);
1732         struct ast_str *wauthority = ast_str_alloca(128);
1733         struct ast_variable *v;
1734
1735         switch (cmd) {
1736         case CLI_INIT:
1737                 e->command = "manager show user";
1738                 e->usage =
1739                         " Usage: manager show user <user>\n"
1740                         "        Display all information related to the manager user specified.\n";
1741                 return NULL;
1742         case CLI_GENERATE:
1743                 l = strlen(a->word);
1744                 which = 0;
1745                 if (a->pos != 3) {
1746                         return NULL;
1747                 }
1748                 AST_RWLIST_RDLOCK(&users);
1749                 AST_RWLIST_TRAVERSE(&users, user, list) {
1750                         if ( !strncasecmp(a->word, user->username, l) && ++which > a->n ) {
1751                                 ret = ast_strdup(user->username);
1752                                 break;
1753                         }
1754                 }
1755                 AST_RWLIST_UNLOCK(&users);
1756                 return ret;
1757         }
1758
1759         if (a->argc != 4) {
1760                 return CLI_SHOWUSAGE;
1761         }
1762
1763         AST_RWLIST_RDLOCK(&users);
1764
1765         if (!(user = get_manager_by_name_locked(a->argv[3]))) {
1766                 ast_cli(a->fd, "There is no manager called %s\n", a->argv[3]);
1767                 AST_RWLIST_UNLOCK(&users);
1768                 return CLI_SUCCESS;
1769         }
1770
1771         ast_cli(a->fd, "\n");
1772         ast_cli(a->fd,
1773                 "       username: %s\n"
1774                 "         secret: %s\n"
1775                 "            ACL: %s\n"
1776                 "      read perm: %s\n"
1777                 "     write perm: %s\n"
1778                 "displayconnects: %s\n",
1779                 (user->username ? user->username : "(N/A)"),
1780                 (user->secret ? "<Set>" : "(N/A)"),
1781                 ((user->acl && !ast_acl_list_is_empty(user->acl)) ? "yes" : "no"),
1782                 user_authority_to_str(user->readperm, &rauthority),
1783                 user_authority_to_str(user->writeperm, &wauthority),
1784                 (user->displayconnects ? "yes" : "no"));
1785         ast_cli(a->fd, "      Variables: \n");
1786                 for (v = user->chanvars ; v ; v = v->next) {
1787                         ast_cli(a->fd, "                 %s = %s\n", v->name, v->value);
1788                 }
1789
1790         AST_RWLIST_UNLOCK(&users);
1791
1792         return CLI_SUCCESS;
1793 }
1794
1795 static char *handle_showmanagers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1796 {
1797         struct ast_manager_user *user = NULL;
1798         int count_amu = 0;
1799         switch (cmd) {
1800         case CLI_INIT:
1801                 e->command = "manager show users";
1802                 e->usage =
1803                         "Usage: manager show users\n"
1804                         "       Prints a listing of all managers that are currently configured on that\n"
1805                         " system.\n";
1806                 return NULL;
1807         case CLI_GENERATE:
1808                 return NULL;
1809         }
1810         if (a->argc != 3) {
1811                 return CLI_SHOWUSAGE;
1812         }
1813
1814         AST_RWLIST_RDLOCK(&users);
1815
1816         /* If there are no users, print out something along those lines */
1817         if (AST_RWLIST_EMPTY(&users)) {
1818                 ast_cli(a->fd, "There are no manager users.\n");
1819                 AST_RWLIST_UNLOCK(&users);
1820                 return CLI_SUCCESS;
1821         }
1822
1823         ast_cli(a->fd, "\nusername\n--------\n");
1824
1825         AST_RWLIST_TRAVERSE(&users, user, list) {
1826                 ast_cli(a->fd, "%s\n", user->username);
1827                 count_amu++;
1828         }
1829
1830         AST_RWLIST_UNLOCK(&users);
1831
1832         ast_cli(a->fd,"-------------------\n"
1833                       "%d manager users configured.\n", count_amu);
1834         return CLI_SUCCESS;
1835 }
1836
1837 /*! \brief  CLI command  manager list commands */
1838 static char *handle_showmancmds(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1839 {
1840         struct manager_action *cur;
1841         int name_len = 1;
1842         int space_remaining;
1843 #define HSMC_FORMAT "  %-*.*s  %-.*s\n"
1844         switch (cmd) {
1845         case CLI_INIT:
1846                 e->command = "manager show commands";
1847                 e->usage =
1848                         "Usage: manager show commands\n"
1849                         "       Prints a listing of all the available Asterisk manager interface commands.\n";
1850                 return NULL;
1851         case CLI_GENERATE:
1852                 return NULL;
1853         }
1854
1855         AST_RWLIST_RDLOCK(&actions);
1856         AST_RWLIST_TRAVERSE(&actions, cur, list) {
1857                 int incoming_len = strlen(cur->action);
1858                 if (incoming_len > name_len) {
1859                         name_len = incoming_len;
1860                 }
1861         }
1862
1863         space_remaining = MGR_SHOW_TERMINAL_WIDTH - name_len - 4;
1864         if (space_remaining < 0) {
1865                 space_remaining = 0;
1866         }
1867
1868         ast_cli(a->fd, HSMC_FORMAT, name_len, name_len, "Action", space_remaining, "Synopsis");
1869         ast_cli(a->fd, HSMC_FORMAT, name_len, name_len, "------", space_remaining, "--------");
1870
1871         AST_RWLIST_TRAVERSE(&actions, cur, list) {
1872                 ast_cli(a->fd, HSMC_FORMAT, name_len, name_len, cur->action, space_remaining, cur->synopsis);
1873         }
1874         AST_RWLIST_UNLOCK(&actions);
1875
1876         return CLI_SUCCESS;
1877 }
1878
1879 /*! \brief CLI command manager list connected */
1880 static char *handle_showmanconn(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1881 {
1882         struct mansession_session *session;
1883         time_t now = time(NULL);
1884 #define HSMCONN_FORMAT1 "  %-15.15s  %-55.55s  %-10.10s  %-10.10s  %-8.8s  %-8.8s  %-5.5s  %-5.5s\n"
1885 #define HSMCONN_FORMAT2 "  %-15.15s  %-55.55s  %-10d  %-10d  %-8d  %-8d  %-5.5d  %-5.5d\n"
1886         int count = 0;
1887         struct ao2_iterator i;
1888
1889         switch (cmd) {
1890         case CLI_INIT:
1891                 e->command = "manager show connected";
1892                 e->usage =
1893                         "Usage: manager show connected\n"
1894                         "       Prints a listing of the users that are currently connected to the\n"
1895                         "Asterisk manager interface.\n";
1896                 return NULL;
1897         case CLI_GENERATE:
1898                 return NULL;
1899         }
1900
1901         ast_cli(a->fd, HSMCONN_FORMAT1, "Username", "IP Address", "Start", "Elapsed", "FileDes", "HttpCnt", "Read", "Write");
1902
1903         i = ao2_iterator_init(sessions, 0);
1904         while ((session = ao2_iterator_next(&i))) {
1905                 ao2_lock(session);
1906                 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);
1907                 count++;
1908                 ao2_unlock(session);
1909                 unref_mansession(session);
1910         }
1911         ao2_iterator_destroy(&i);
1912         ast_cli(a->fd, "%d users connected.\n", count);
1913
1914         return CLI_SUCCESS;
1915 }
1916
1917 /*! \brief CLI command manager list eventq */
1918 /* Should change to "manager show connected" */
1919 static char *handle_showmaneventq(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1920 {
1921         struct eventqent *s;
1922         switch (cmd) {
1923         case CLI_INIT:
1924                 e->command = "manager show eventq";
1925                 e->usage =
1926                         "Usage: manager show eventq\n"
1927                         "       Prints a listing of all events pending in the Asterisk manger\n"
1928                         "event queue.\n";
1929                 return NULL;
1930         case CLI_GENERATE:
1931                 return NULL;
1932         }
1933         AST_RWLIST_RDLOCK(&all_events);
1934         AST_RWLIST_TRAVERSE(&all_events, s, eq_next) {
1935                 ast_cli(a->fd, "Usecount: %d\n", s->usecount);
1936                 ast_cli(a->fd, "Category: %d\n", s->category);
1937                 ast_cli(a->fd, "Event:\n%s", s->eventdata);
1938         }
1939         AST_RWLIST_UNLOCK(&all_events);
1940
1941         return CLI_SUCCESS;
1942 }
1943
1944 /*! \brief CLI command manager reload */
1945 static char *handle_manager_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1946 {
1947         switch (cmd) {
1948         case CLI_INIT:
1949                 e->command = "manager reload";
1950                 e->usage =
1951                         "Usage: manager reload\n"
1952                         "       Reloads the manager configuration.\n";
1953                 return NULL;
1954         case CLI_GENERATE:
1955                 return NULL;
1956         }
1957         if (a->argc > 2) {
1958                 return CLI_SHOWUSAGE;
1959         }
1960         reload_manager();
1961         return CLI_SUCCESS;
1962 }
1963
1964 static struct eventqent *advance_event(struct eventqent *e)
1965 {
1966         struct eventqent *next;
1967
1968         AST_RWLIST_RDLOCK(&all_events);
1969         if ((next = AST_RWLIST_NEXT(e, eq_next))) {
1970                 ast_atomic_fetchadd_int(&next->usecount, 1);
1971                 ast_atomic_fetchadd_int(&e->usecount, -1);
1972         }
1973         AST_RWLIST_UNLOCK(&all_events);
1974         return next;
1975 }
1976
1977 #define GET_HEADER_FIRST_MATCH  0
1978 #define GET_HEADER_LAST_MATCH   1
1979 #define GET_HEADER_SKIP_EMPTY   2
1980
1981 /*!
1982  * \brief Return a matching header value.
1983  *
1984  * \details
1985  * Generic function to return either the first or the last
1986  * matching header from a list of variables, possibly skipping
1987  * empty strings.
1988  *
1989  * \note At the moment there is only one use of this function in
1990  * this file, so we make it static.
1991  *
1992  * \note Never returns NULL.
1993  */
1994 static const char *__astman_get_header(const struct message *m, char *var, int mode)
1995 {
1996         int x, l = strlen(var);
1997         const char *result = "";
1998
1999         if (!m) {
2000                 return result;
2001         }
2002
2003         for (x = 0; x < m->hdrcount; x++) {
2004                 const char *h = m->headers[x];
2005                 if (!strncasecmp(var, h, l) && h[l] == ':') {
2006                         const char *value = h + l + 1;
2007                         value = ast_skip_blanks(value); /* ignore leading spaces in the value */
2008                         /* found a potential candidate */
2009                         if ((mode & GET_HEADER_SKIP_EMPTY) && ast_strlen_zero(value)) {
2010                                 continue;       /* not interesting */
2011                         }
2012                         if (mode & GET_HEADER_LAST_MATCH) {
2013                                 result = value; /* record the last match so far */
2014                         } else {
2015                                 return value;
2016                         }
2017                 }
2018         }
2019
2020         return result;
2021 }
2022
2023 /*!
2024  * \brief Return the first matching variable from an array.
2025  *
2026  * \note This is the legacy function and is implemented in
2027  * therms of __astman_get_header().
2028  *
2029  * \note Never returns NULL.
2030  */
2031 const char *astman_get_header(const struct message *m, char *var)
2032 {
2033         return __astman_get_header(m, var, GET_HEADER_FIRST_MATCH);
2034 }
2035
2036 /*!
2037  * \internal
2038  * \brief Process one "Variable:" header value string.
2039  *
2040  * \param head Current list of AMI variables to get new values added.
2041  * \param hdr_val Header value string to process.
2042  *
2043  * \return New variable list head.
2044  */
2045 static struct ast_variable *man_do_variable_value(struct ast_variable *head, const char *hdr_val)
2046 {
2047         char *parse;
2048         AST_DECLARE_APP_ARGS(args,
2049                 AST_APP_ARG(vars)[64];
2050         );
2051
2052         hdr_val = ast_skip_blanks(hdr_val); /* ignore leading spaces in the value */
2053         parse = ast_strdupa(hdr_val);
2054
2055         /* Break the header value string into name=val pair items. */
2056         AST_STANDARD_APP_ARGS(args, parse);
2057         if (args.argc) {
2058                 int y;
2059
2060                 /* Process each name=val pair item. */
2061                 for (y = 0; y < args.argc; y++) {
2062                         struct ast_variable *cur;
2063                         char *var;
2064                         char *val;
2065
2066                         if (!args.vars[y]) {
2067                                 continue;
2068                         }
2069                         var = val = args.vars[y];
2070                         strsep(&val, "=");
2071
2072                         /* XXX We may wish to trim whitespace from the strings. */
2073                         if (!val || ast_strlen_zero(var)) {
2074                                 continue;
2075                         }
2076
2077                         /* Create new variable list node and prepend it to the list. */
2078                         cur = ast_variable_new(var, val, "");
2079                         if (cur) {
2080                                 cur->next = head;
2081                                 head = cur;
2082                         }
2083                 }
2084         }
2085
2086         return head;
2087 }
2088
2089 struct ast_variable *astman_get_variables(const struct message *m)
2090 {
2091         int varlen;
2092         int x;
2093         struct ast_variable *head = NULL;
2094
2095         static const char var_hdr[] = "Variable:";
2096
2097         /* Process all "Variable:" headers. */
2098         varlen = strlen(var_hdr);
2099         for (x = 0; x < m->hdrcount; x++) {
2100                 if (strncasecmp(var_hdr, m->headers[x], varlen)) {
2101                         continue;
2102                 }
2103                 head = man_do_variable_value(head, m->headers[x] + varlen);
2104         }
2105
2106         return head;
2107 }
2108
2109 /*! \brief access for hooks to send action messages to ami */
2110 int ast_hook_send_action(struct manager_custom_hook *hook, const char *msg)
2111 {
2112         const char *action;
2113         int ret = 0;
2114         struct manager_action *act_found;
2115         struct mansession s = {.session = NULL, };
2116         struct message m = { 0 };
2117         char *dup_str;
2118         char *src;
2119         int x = 0;
2120         int curlen;
2121
2122         if (hook == NULL) {
2123                 return -1;
2124         }
2125
2126         /* Create our own copy of the AMI action msg string. */
2127         src = dup_str = ast_strdup(msg);
2128         if (!dup_str) {
2129                 return -1;
2130         }
2131
2132         /* convert msg string to message struct */
2133         curlen = strlen(src);
2134         for (x = 0; x < curlen; x++) {
2135                 int cr; /* set if we have \r */
2136                 if (src[x] == '\r' && x+1 < curlen && src[x+1] == '\n')
2137                         cr = 2; /* Found. Update length to include \r\n */
2138                 else if (src[x] == '\n')
2139                         cr = 1; /* also accept \n only */
2140                 else
2141                         continue;
2142                 /* don't keep empty lines */
2143                 if (x && m.hdrcount < ARRAY_LEN(m.headers)) {
2144                         /* ... but trim \r\n and terminate the header string */
2145                         src[x] = '\0';
2146                         m.headers[m.hdrcount++] = src;
2147                 }
2148                 x += cr;
2149                 curlen -= x;            /* remaining size */
2150                 src += x;               /* update pointer */
2151                 x = -1;                 /* reset loop */
2152         }
2153
2154         action = astman_get_header(&m, "Action");
2155         if (strcasecmp(action, "login")) {
2156                 act_found = action_find(action);
2157                 if (act_found) {
2158                         /*
2159                          * we have to simulate a session for this action request
2160                          * to be able to pass it down for processing
2161                          * This is necessary to meet the previous design of manager.c
2162                          */
2163                         s.hook = hook;
2164                         s.f = (void*)1; /* set this to something so our request will make it through all functions that test it*/
2165
2166                         ao2_lock(act_found);
2167                         if (act_found->registered && act_found->func) {
2168                                 if (act_found->module) {
2169                                         ast_module_ref(act_found->module);
2170                                 }
2171                                 ao2_unlock(act_found);
2172                                 ret = act_found->func(&s, &m);
2173                                 ao2_lock(act_found);
2174                                 if (act_found->module) {
2175                                         ast_module_unref(act_found->module);
2176                                 }
2177                         } else {
2178                                 ret = -1;
2179                         }
2180                         ao2_unlock(act_found);
2181                         ao2_t_ref(act_found, -1, "done with found action object");
2182                 }
2183         }
2184         ast_free(dup_str);
2185         return ret;
2186 }
2187
2188
2189 /*!
2190  * helper function to send a string to the socket.
2191  * Return -1 on error (e.g. buffer full).
2192  */
2193 static int send_string(struct mansession *s, char *string)
2194 {
2195         int res;
2196         FILE *f = s->f ? s->f : s->session->f;
2197         int fd = s->f ? s->fd : s->session->fd;
2198
2199         /* It's a result from one of the hook's action invocation */
2200         if (s->hook) {
2201                 /*
2202                  * to send responses, we're using the same function
2203                  * as for receiving events. We call the event "HookResponse"
2204                  */
2205                 s->hook->helper(EVENT_FLAG_HOOKRESPONSE, "HookResponse", string);
2206                 return 0;
2207         }
2208
2209         if ((res = ast_careful_fwrite(f, fd, string, strlen(string), s->session->writetimeout))) {
2210                 s->write_error = 1;
2211         }
2212
2213         return res;
2214 }
2215
2216 /*!
2217  * \brief thread local buffer for astman_append
2218  *
2219  * \note This can not be defined within the astman_append() function
2220  *       because it declares a couple of functions that get used to
2221  *       initialize the thread local storage key.
2222  */
2223 AST_THREADSTORAGE(astman_append_buf);
2224
2225 AST_THREADSTORAGE(userevent_buf);
2226
2227 /*! \brief initial allocated size for the astman_append_buf and astman_send_*_va */
2228 #define ASTMAN_APPEND_BUF_INITSIZE   256
2229
2230 /*!
2231  * utility functions for creating AMI replies
2232  */
2233 void astman_append(struct mansession *s, const char *fmt, ...)
2234 {
2235         va_list ap;
2236         struct ast_str *buf;
2237
2238         if (!(buf = ast_str_thread_get(&astman_append_buf, ASTMAN_APPEND_BUF_INITSIZE))) {
2239                 return;
2240         }
2241
2242         va_start(ap, fmt);
2243         ast_str_set_va(&buf, 0, fmt, ap);
2244         va_end(ap);
2245
2246         if (s->f != NULL || s->session->f != NULL) {
2247                 send_string(s, ast_str_buffer(buf));
2248         } else {
2249                 ast_verbose("fd == -1 in astman_append, should not happen\n");
2250         }
2251 }
2252
2253 /*! \note NOTE: XXX this comment is unclear and possibly wrong.
2254    Callers of astman_send_error(), astman_send_response() or astman_send_ack() must EITHER
2255    hold the session lock _or_ be running in an action callback (in which case s->session->busy will
2256    be non-zero). In either of these cases, there is no need to lock-protect the session's
2257    fd, since no other output will be sent (events will be queued), and no input will
2258    be read until either the current action finishes or get_input() obtains the session
2259    lock.
2260  */
2261
2262 /*! \todo XXX MSG_MOREDATA should go to a header file. */
2263 #define MSG_MOREDATA    ((char *)astman_send_response)
2264
2265 /*! \brief send a response with an optional message,
2266  * and terminate it with an empty line.
2267  * m is used only to grab the 'ActionID' field.
2268  *
2269  * Use the explicit constant MSG_MOREDATA to remove the empty line.
2270  * XXX MSG_MOREDATA should go to a header file.
2271  */
2272 static void astman_send_response_full(struct mansession *s, const struct message *m, char *resp, char *msg, char *listflag)
2273 {
2274         const char *id = astman_get_header(m, "ActionID");
2275
2276         astman_append(s, "Response: %s\r\n", resp);
2277         if (!ast_strlen_zero(id)) {
2278                 astman_append(s, "ActionID: %s\r\n", id);
2279         }
2280         if (listflag) {
2281                 astman_append(s, "EventList: %s\r\n", listflag);        /* Start, complete, cancelled */
2282         }
2283         if (msg == MSG_MOREDATA) {
2284                 return;
2285         } else if (msg) {
2286                 astman_append(s, "Message: %s\r\n\r\n", msg);
2287         } else {
2288                 astman_append(s, "\r\n");
2289         }
2290 }
2291
2292 void astman_send_response(struct mansession *s, const struct message *m, char *resp, char *msg)
2293 {
2294         astman_send_response_full(s, m, resp, msg, NULL);
2295 }
2296
2297 void astman_send_error(struct mansession *s, const struct message *m, char *error)
2298 {
2299         astman_send_response_full(s, m, "Error", error, NULL);
2300 }
2301
2302 void astman_send_error_va(struct mansession *s, const struct message *m, const char *fmt, ...)
2303 {
2304         va_list ap;
2305         struct ast_str *buf;
2306         char *msg;
2307
2308         if (!(buf = ast_str_thread_get(&astman_append_buf, ASTMAN_APPEND_BUF_INITSIZE))) {
2309                 return;
2310         }
2311
2312         va_start(ap, fmt);
2313         ast_str_set_va(&buf, 0, fmt, ap);
2314         va_end(ap);
2315
2316         /* astman_append will use the same underlying buffer, so copy the message out
2317          * before sending the response */
2318         msg = ast_str_buffer(buf);
2319         if (msg) {
2320                 msg = ast_strdupa(msg);
2321         }
2322         astman_send_response_full(s, m, "Error", msg, NULL);
2323 }
2324
2325 void astman_send_ack(struct mansession *s, const struct message *m, char *msg)
2326 {
2327         astman_send_response_full(s, m, "Success", msg, NULL);
2328 }
2329
2330 static void astman_start_ack(struct mansession *s, const struct message *m)
2331 {
2332         astman_send_response_full(s, m, "Success", MSG_MOREDATA, NULL);
2333 }
2334
2335 void astman_send_listack(struct mansession *s, const struct message *m, char *msg, char *listflag)
2336 {
2337         astman_send_response_full(s, m, "Success", msg, listflag);
2338 }
2339
2340 /*! \brief Lock the 'mansession' structure. */
2341 static void mansession_lock(struct mansession *s)
2342 {
2343         ast_mutex_lock(&s->lock);
2344 }
2345
2346 /*! \brief Unlock the 'mansession' structure. */
2347 static void mansession_unlock(struct mansession *s)
2348 {
2349         ast_mutex_unlock(&s->lock);
2350 }
2351
2352 /*! \brief
2353    Rather than braindead on,off this now can also accept a specific int mask value
2354    or a ',' delim list of mask strings (the same as manager.conf) -anthm
2355 */
2356 static int set_eventmask(struct mansession *s, const char *eventmask)
2357 {
2358         int maskint = strings_to_mask(eventmask);
2359
2360         ao2_lock(s->session);
2361         if (maskint >= 0) {
2362                 s->session->send_events = maskint;
2363         }
2364         ao2_unlock(s->session);
2365
2366         return maskint;
2367 }
2368
2369 static enum ast_security_event_transport_type mansession_get_transport(const struct mansession *s)
2370 {
2371         return s->tcptls_session->parent->tls_cfg ? AST_SECURITY_EVENT_TRANSPORT_TLS :
2372                         AST_SECURITY_EVENT_TRANSPORT_TCP;
2373 }
2374
2375 static void report_invalid_user(const struct mansession *s, const char *username)
2376 {
2377         char session_id[32];
2378         struct ast_security_event_inval_acct_id inval_acct_id = {
2379                 .common.event_type = AST_SECURITY_EVENT_INVAL_ACCT_ID,
2380                 .common.version    = AST_SECURITY_EVENT_INVAL_ACCT_ID_VERSION,
2381                 .common.service    = "AMI",
2382                 .common.account_id = username,
2383                 .common.session_tv = &s->session->sessionstart_tv,
2384                 .common.local_addr = {
2385                         .addr      = &s->tcptls_session->parent->local_address,
2386                         .transport = mansession_get_transport(s),
2387                 },
2388                 .common.remote_addr = {
2389                         .addr      = &s->session->addr,
2390                         .transport = mansession_get_transport(s),
2391                 },
2392                 .common.session_id = session_id,
2393         };
2394
2395         snprintf(session_id, sizeof(session_id), "%p", s);
2396
2397         ast_security_event_report(AST_SEC_EVT(&inval_acct_id));
2398 }
2399
2400 static void report_failed_acl(const struct mansession *s, const char *username)
2401 {
2402         char session_id[32];
2403         struct ast_security_event_failed_acl failed_acl_event = {
2404                 .common.event_type = AST_SECURITY_EVENT_FAILED_ACL,
2405                 .common.version    = AST_SECURITY_EVENT_FAILED_ACL_VERSION,
2406                 .common.service    = "AMI",
2407                 .common.account_id = username,
2408                 .common.session_tv = &s->session->sessionstart_tv,
2409                 .common.local_addr = {
2410                         .addr      = &s->tcptls_session->parent->local_address,
2411                         .transport = mansession_get_transport(s),
2412                 },
2413                 .common.remote_addr = {
2414                         .addr      = &s->session->addr,
2415                         .transport = mansession_get_transport(s),
2416                 },
2417                 .common.session_id = session_id,
2418         };
2419
2420         snprintf(session_id, sizeof(session_id), "%p", s->session);
2421
2422         ast_security_event_report(AST_SEC_EVT(&failed_acl_event));
2423 }
2424
2425 static void report_inval_password(const struct mansession *s, const char *username)
2426 {
2427         char session_id[32];
2428         struct ast_security_event_inval_password inval_password = {
2429                 .common.event_type = AST_SECURITY_EVENT_INVAL_PASSWORD,
2430                 .common.version    = AST_SECURITY_EVENT_INVAL_PASSWORD_VERSION,
2431                 .common.service    = "AMI",
2432                 .common.account_id = username,
2433                 .common.session_tv = &s->session->sessionstart_tv,
2434                 .common.local_addr = {
2435                         .addr      = &s->tcptls_session->parent->local_address,
2436                         .transport = mansession_get_transport(s),
2437                 },
2438                 .common.remote_addr = {
2439                         .addr      = &s->session->addr,
2440                         .transport = mansession_get_transport(s),
2441                 },
2442                 .common.session_id = session_id,
2443         };
2444
2445         snprintf(session_id, sizeof(session_id), "%p", s->session);
2446
2447         ast_security_event_report(AST_SEC_EVT(&inval_password));
2448 }
2449
2450 static void report_auth_success(const struct mansession *s)
2451 {
2452         char session_id[32];
2453         struct ast_security_event_successful_auth successful_auth = {
2454                 .common.event_type = AST_SECURITY_EVENT_SUCCESSFUL_AUTH,
2455                 .common.version    = AST_SECURITY_EVENT_SUCCESSFUL_AUTH_VERSION,
2456                 .common.service    = "AMI",
2457                 .common.account_id = s->session->username,
2458                 .common.session_tv = &s->session->sessionstart_tv,
2459                 .common.local_addr = {
2460                         .addr      = &s->tcptls_session->parent->local_address,
2461                         .transport = mansession_get_transport(s),
2462                 },
2463                 .common.remote_addr = {
2464                         .addr      = &s->session->addr,
2465                         .transport = mansession_get_transport(s),
2466                 },
2467                 .common.session_id = session_id,
2468         };
2469
2470         snprintf(session_id, sizeof(session_id), "%p", s->session);
2471
2472         ast_security_event_report(AST_SEC_EVT(&successful_auth));
2473 }
2474
2475 static void report_req_not_allowed(const struct mansession *s, const char *action)
2476 {
2477         char session_id[32];
2478         char request_type[64];
2479         struct ast_security_event_req_not_allowed req_not_allowed = {
2480                 .common.event_type = AST_SECURITY_EVENT_REQ_NOT_ALLOWED,
2481                 .common.version    = AST_SECURITY_EVENT_REQ_NOT_ALLOWED_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_not_allowed));
2502 }
2503
2504 static void report_req_bad_format(const struct mansession *s, const char *action)
2505 {
2506         char session_id[32];
2507         char request_type[64];
2508         struct ast_security_event_req_bad_format req_bad_format = {
2509                 .common.event_type = AST_SECURITY_EVENT_REQ_BAD_FORMAT,
2510                 .common.version    = AST_SECURITY_EVENT_REQ_BAD_FORMAT_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                 .request_type      = request_type,
2525         };
2526
2527         snprintf(session_id, sizeof(session_id), "%p", s->session);
2528         snprintf(request_type, sizeof(request_type), "Action: %s", action);
2529
2530         ast_security_event_report(AST_SEC_EVT(&req_bad_format));
2531 }
2532
2533 static void report_failed_challenge_response(const struct mansession *s,
2534                 const char *response, const char *expected_response)
2535 {
2536         char session_id[32];
2537         struct ast_security_event_chal_resp_failed chal_resp_failed = {
2538                 .common.event_type = AST_SECURITY_EVENT_CHAL_RESP_FAILED,
2539                 .common.version    = AST_SECURITY_EVENT_CHAL_RESP_FAILED_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                 .challenge         = s->session->challenge,
2554                 .response          = response,
2555                 .expected_response = expected_response,
2556         };
2557
2558         snprintf(session_id, sizeof(session_id), "%p", s->session);
2559
2560         ast_security_event_report(AST_SEC_EVT(&chal_resp_failed));
2561 }
2562
2563 static void report_session_limit(const struct mansession *s)
2564 {
2565         char session_id[32];
2566         struct ast_security_event_session_limit session_limit = {
2567                 .common.event_type = AST_SECURITY_EVENT_SESSION_LIMIT,
2568                 .common.version    = AST_SECURITY_EVENT_SESSION_LIMIT_VERSION,
2569                 .common.service    = "AMI",
2570                 .common.account_id = s->session->username,
2571                 .common.session_tv = &s->session->sessionstart_tv,
2572                 .common.local_addr = {
2573                         .addr      = &s->tcptls_session->parent->local_address,
2574                         .transport = mansession_get_transport(s),
2575                 },
2576                 .common.remote_addr = {
2577                         .addr      = &s->session->addr,
2578                         .transport = mansession_get_transport(s),
2579                 },
2580                 .common.session_id = session_id,
2581         };
2582
2583         snprintf(session_id, sizeof(session_id), "%p", s->session);
2584
2585         ast_security_event_report(AST_SEC_EVT(&session_limit));
2586 }
2587
2588 /*
2589  * Here we start with action_ handlers for AMI actions,
2590  * and the internal functions used by them.
2591  * Generally, the handlers are called action_foo()
2592  */
2593
2594 /* helper function for action_login() */
2595 static int authenticate(struct mansession *s, const struct message *m)
2596 {
2597         const char *username = astman_get_header(m, "Username");
2598         const char *password = astman_get_header(m, "Secret");
2599         int error = -1;
2600         struct ast_manager_user *user = NULL;
2601         regex_t *regex_filter;
2602         struct ao2_iterator filter_iter;
2603
2604         if (ast_strlen_zero(username)) {        /* missing username */
2605                 return -1;
2606         }
2607
2608         /* locate user in locked state */
2609         AST_RWLIST_WRLOCK(&users);
2610
2611         if (!(user = get_manager_by_name_locked(username))) {
2612                 report_invalid_user(s, username);
2613                 ast_log(LOG_NOTICE, "%s tried to authenticate with nonexistent user '%s'\n", ast_sockaddr_stringify_addr(&s->session->addr), username);
2614         } else if (user->acl && (ast_apply_acl(user->acl, &s->session->addr, "Manager User ACL: ") == AST_SENSE_DENY)) {
2615                 report_failed_acl(s, username);
2616                 ast_log(LOG_NOTICE, "%s failed to pass IP ACL as '%s'\n", ast_sockaddr_stringify_addr(&s->session->addr), username);
2617         } else if (!strcasecmp(astman_get_header(m, "AuthType"), "MD5")) {
2618                 const char *key = astman_get_header(m, "Key");
2619                 if (!ast_strlen_zero(key) && !ast_strlen_zero(s->session->challenge) && user->secret) {
2620                         int x;
2621                         int len = 0;
2622                         char md5key[256] = "";
2623                         struct MD5Context md5;
2624                         unsigned char digest[16];
2625
2626                         MD5Init(&md5);
2627                         MD5Update(&md5, (unsigned char *) s->session->challenge, strlen(s->session->challenge));
2628                         MD5Update(&md5, (unsigned char *) user->secret, strlen(user->secret));
2629                         MD5Final(digest, &md5);
2630                         for (x = 0; x < 16; x++)
2631                                 len += sprintf(md5key + len, "%2.2x", digest[x]);
2632                         if (!strcmp(md5key, key)) {
2633                                 error = 0;
2634                         } else {
2635                                 report_failed_challenge_response(s, key, md5key);
2636                         }
2637                 } else {
2638                         ast_debug(1, "MD5 authentication is not possible.  challenge: '%s'\n",
2639                                 S_OR(s->session->challenge, ""));
2640                 }
2641         } else if (user->secret) {
2642                 if (!strcmp(password, user->secret)) {
2643                         error = 0;
2644                 } else {
2645                         report_inval_password(s, username);
2646                 }
2647         }
2648
2649         if (error) {
2650                 ast_log(LOG_NOTICE, "%s failed to authenticate as '%s'\n", ast_sockaddr_stringify_addr(&s->session->addr), username);
2651                 AST_RWLIST_UNLOCK(&users);
2652                 return -1;
2653         }
2654
2655         /* auth complete */
2656
2657         /* All of the user parameters are copied to the session so that in the event
2658         * of a reload and a configuration change, the session parameters are not
2659         * changed. */
2660         ast_copy_string(s->session->username, username, sizeof(s->session->username));
2661         s->session->readperm = user->readperm;
2662         s->session->writeperm = user->writeperm;
2663         s->session->writetimeout = user->writetimeout;
2664         if (user->chanvars) {
2665                 s->session->chanvars = ast_variables_dup(user->chanvars);
2666         }
2667
2668         filter_iter = ao2_iterator_init(user->whitefilters, 0);
2669         while ((regex_filter = ao2_iterator_next(&filter_iter))) {
2670                 ao2_t_link(s->session->whitefilters, regex_filter, "add white user filter to session");
2671                 ao2_t_ref(regex_filter, -1, "remove iterator ref");
2672         }
2673         ao2_iterator_destroy(&filter_iter);
2674
2675         filter_iter = ao2_iterator_init(user->blackfilters, 0);
2676         while ((regex_filter = ao2_iterator_next(&filter_iter))) {
2677                 ao2_t_link(s->session->blackfilters, regex_filter, "add black user filter to session");
2678                 ao2_t_ref(regex_filter, -1, "remove iterator ref");
2679         }
2680         ao2_iterator_destroy(&filter_iter);
2681
2682         s->session->sessionstart = time(NULL);
2683         s->session->sessionstart_tv = ast_tvnow();
2684         set_eventmask(s, astman_get_header(m, "Events"));
2685
2686         report_auth_success(s);
2687
2688         AST_RWLIST_UNLOCK(&users);
2689         return 0;
2690 }
2691
2692 static int action_ping(struct mansession *s, const struct message *m)
2693 {
2694         const char *actionid = astman_get_header(m, "ActionID");
2695         struct timeval now = ast_tvnow();
2696
2697         astman_append(s, "Response: Success\r\n");
2698         if (!ast_strlen_zero(actionid)){
2699                 astman_append(s, "ActionID: %s\r\n", actionid);
2700         }
2701         astman_append(
2702                 s,
2703                 "Ping: Pong\r\n"
2704                 "Timestamp: %ld.%06lu\r\n"
2705                 "\r\n",
2706                 (long) now.tv_sec, (unsigned long) now.tv_usec);
2707         return 0;
2708 }
2709
2710 static int action_getconfig(struct mansession *s, const struct message *m)
2711 {
2712         struct ast_config *cfg;
2713         const char *fn = astman_get_header(m, "Filename");
2714         const char *category = astman_get_header(m, "Category");
2715         int catcount = 0;
2716         int lineno = 0;
2717         char *cur_category = NULL;
2718         struct ast_variable *v;
2719         struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
2720
2721         if (ast_strlen_zero(fn)) {
2722                 astman_send_error(s, m, "Filename not specified");
2723                 return 0;
2724         }
2725         cfg = ast_config_load2(fn, "manager", config_flags);
2726         if (cfg == CONFIG_STATUS_FILEMISSING) {
2727                 astman_send_error(s, m, "Config file not found");
2728                 return 0;
2729         } else if (cfg == CONFIG_STATUS_FILEINVALID) {
2730                 astman_send_error(s, m, "Config file has invalid format");
2731                 return 0;
2732         }
2733
2734         astman_start_ack(s, m);
2735         while ((cur_category = ast_category_browse(cfg, cur_category))) {
2736                 if (ast_strlen_zero(category) || (!ast_strlen_zero(category) && !strcmp(category, cur_category))) {
2737                         lineno = 0;
2738                         astman_append(s, "Category-%06d: %s\r\n", catcount, cur_category);
2739                         for (v = ast_variable_browse(cfg, cur_category); v; v = v->next) {
2740                                 astman_append(s, "Line-%06d-%06d: %s=%s\r\n", catcount, lineno++, v->name, v->value);
2741                         }
2742                         catcount++;
2743                 }
2744         }
2745         if (!ast_strlen_zero(category) && catcount == 0) { /* TODO: actually, a config with no categories doesn't even get loaded */
2746                 astman_append(s, "No categories found\r\n");
2747         }
2748         ast_config_destroy(cfg);
2749         astman_append(s, "\r\n");
2750
2751         return 0;
2752 }
2753
2754 static int action_listcategories(struct mansession *s, const struct message *m)
2755 {
2756         struct ast_config *cfg;
2757         const char *fn = astman_get_header(m, "Filename");
2758         char *category = NULL;
2759         struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
2760         int catcount = 0;
2761
2762         if (ast_strlen_zero(fn)) {
2763                 astman_send_error(s, m, "Filename not specified");
2764                 return 0;
2765         }
2766         if (!(cfg = ast_config_load2(fn, "manager", config_flags))) {
2767                 astman_send_error(s, m, "Config file not found");
2768                 return 0;
2769         } else if (cfg == CONFIG_STATUS_FILEINVALID) {
2770                 astman_send_error(s, m, "Config file has invalid format");
2771                 return 0;
2772         }
2773         astman_start_ack(s, m);
2774         while ((category = ast_category_browse(cfg, category))) {
2775                 astman_append(s, "Category-%06d: %s\r\n", catcount, category);
2776                 catcount++;
2777         }
2778         if (catcount == 0) { /* TODO: actually, a config with no categories doesn't even get loaded */
2779                 astman_append(s, "Error: no categories found\r\n");
2780         }
2781         ast_config_destroy(cfg);
2782         astman_append(s, "\r\n");
2783
2784         return 0;
2785 }
2786
2787
2788
2789
2790 /*! The amount of space in out must be at least ( 2 * strlen(in) + 1 ) */
2791 static void json_escape(char *out, const char *in)
2792 {
2793         for (; *in; in++) {
2794                 if (*in == '\\' || *in == '\"') {
2795                         *out++ = '\\';
2796                 }
2797                 *out++ = *in;
2798         }
2799         *out = '\0';
2800 }
2801
2802 /*!
2803  * \internal
2804  * \brief Append a JSON escaped string to the manager stream.
2805  *
2806  * \param s AMI stream to append a string.
2807  * \param str String to append to the stream after JSON escaping it.
2808  *
2809  * \return Nothing
2810  */
2811 static void astman_append_json(struct mansession *s, const char *str)
2812 {
2813         char *buf;
2814
2815         buf = ast_alloca(2 * strlen(str) + 1);
2816         json_escape(buf, str);
2817         astman_append(s, "%s", buf);
2818 }
2819
2820 static int action_getconfigjson(struct mansession *s, const struct message *m)
2821 {
2822         struct ast_config *cfg;
2823         const char *fn = astman_get_header(m, "Filename");
2824         char *category = NULL;
2825         struct ast_variable *v;
2826         int comma1 = 0;
2827         struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
2828
2829         if (ast_strlen_zero(fn)) {
2830                 astman_send_error(s, m, "Filename not specified");
2831                 return 0;
2832         }
2833
2834         if (!(cfg = ast_config_load2(fn, "manager", config_flags))) {
2835                 astman_send_error(s, m, "Config file not found");
2836                 return 0;
2837         } else if (cfg == CONFIG_STATUS_FILEINVALID) {
2838                 astman_send_error(s, m, "Config file has invalid format");
2839                 return 0;
2840         }
2841
2842         astman_start_ack(s, m);
2843         astman_append(s, "JSON: {");
2844         while ((category = ast_category_browse(cfg, category))) {
2845                 int comma2 = 0;
2846
2847                 astman_append(s, "%s\"", comma1 ? "," : "");
2848                 astman_append_json(s, category);
2849                 astman_append(s, "\":[");
2850                 comma1 = 1;
2851                 for (v = ast_variable_browse(cfg, category); v; v = v->next) {
2852                         astman_append(s, "%s\"", comma2 ? "," : "");
2853                         astman_append_json(s, v->name);
2854                         astman_append(s, "\":\"");
2855                         astman_append_json(s, v->value);
2856                         astman_append(s, "\"");
2857                         comma2 = 1;
2858                 }
2859                 astman_append(s, "]");
2860         }
2861         astman_append(s, "}\r\n\r\n");
2862
2863         ast_config_destroy(cfg);
2864
2865         return 0;
2866 }
2867
2868 /*! \brief helper function for action_updateconfig */
2869 static enum error_type handle_updates(struct mansession *s, const struct message *m, struct ast_config *cfg, const char *dfn)
2870 {
2871         int x;
2872         char hdr[40];
2873         const char *action, *cat, *var, *value, *match, *line;
2874         struct ast_category *category;
2875         struct ast_variable *v;
2876         struct ast_str *str1 = ast_str_create(16), *str2 = ast_str_create(16);
2877         enum error_type result = 0;
2878
2879         for (x = 0; x < 100000; x++) {  /* 100000 = the max number of allowed updates + 1 */
2880                 unsigned int object = 0;
2881
2882                 snprintf(hdr, sizeof(hdr), "Action-%06d", x);
2883                 action = astman_get_header(m, hdr);
2884                 if (ast_strlen_zero(action))            /* breaks the for loop if no action header */
2885                         break;                          /* this could cause problems if actions come in misnumbered */
2886
2887                 snprintf(hdr, sizeof(hdr), "Cat-%06d", x);
2888                 cat = astman_get_header(m, hdr);
2889                 if (ast_strlen_zero(cat)) {             /* every action needs a category */
2890                         result =  UNSPECIFIED_CATEGORY;
2891                         break;
2892                 }
2893
2894                 snprintf(hdr, sizeof(hdr), "Var-%06d", x);
2895                 var = astman_get_header(m, hdr);
2896
2897                 snprintf(hdr, sizeof(hdr), "Value-%06d", x);
2898                 value = astman_get_header(m, hdr);
2899
2900                 if (!ast_strlen_zero(value) && *value == '>') {
2901                         object = 1;
2902                         value++;
2903                 }
2904
2905                 snprintf(hdr, sizeof(hdr), "Match-%06d", x);
2906                 match = astman_get_header(m, hdr);
2907
2908                 snprintf(hdr, sizeof(hdr), "Line-%06d", x);
2909                 line = astman_get_header(m, hdr);
2910
2911                 if (!strcasecmp(action, "newcat")) {
2912                         if (ast_category_get(cfg,cat)) {        /* check to make sure the cat doesn't */
2913                                 result = FAILURE_NEWCAT;        /* already exist */
2914                                 break;
2915                         }
2916                         if (!(category = ast_category_new(cat, dfn, -1))) {
2917                                 result = FAILURE_ALLOCATION;
2918                                 break;
2919                         }
2920                         if (ast_strlen_zero(match)) {
2921                                 ast_category_append(cfg, category);
2922                         } else {
2923                                 ast_category_insert(cfg, category, match);
2924                         }
2925                 } else if (!strcasecmp(action, "renamecat")) {
2926                         if (ast_strlen_zero(value)) {
2927                                 result = UNSPECIFIED_ARGUMENT;
2928                                 break;
2929                         }
2930                         if (!(category = ast_category_get(cfg, cat))) {
2931                                 result = UNKNOWN_CATEGORY;
2932                                 break;
2933                         }
2934                         ast_category_rename(category, value);
2935                 } else if (!strcasecmp(action, "delcat")) {
2936                         if (ast_category_delete(cfg, cat)) {
2937                                 result = FAILURE_DELCAT;
2938                                 break;
2939                         }
2940                 } else if (!strcasecmp(action, "emptycat")) {
2941                         if (ast_category_empty(cfg, cat)) {
2942                                 result = FAILURE_EMPTYCAT;
2943                                 break;
2944                         }
2945                 } else if (!strcasecmp(action, "update")) {
2946                         if (ast_strlen_zero(var)) {
2947                                 result = UNSPECIFIED_ARGUMENT;
2948                                 break;
2949                         }
2950                         if (!(category = ast_category_get(cfg,cat))) {
2951                                 result = UNKNOWN_CATEGORY;
2952                                 break;
2953                         }
2954                         if (ast_variable_update(category, var, value, match, object)) {
2955                                 result = FAILURE_UPDATE;
2956                                 break;
2957                         }
2958                 } else if (!strcasecmp(action, "delete")) {
2959                         if ((ast_strlen_zero(var) && ast_strlen_zero(line))) {
2960                                 result = UNSPECIFIED_ARGUMENT;
2961                                 break;
2962                         }
2963                         if (!(category = ast_category_get(cfg, cat))) {
2964                                 result = UNKNOWN_CATEGORY;
2965                                 break;
2966                         }
2967                         if (ast_variable_delete(category, var, match, line)) {
2968                                 result = FAILURE_DELETE;
2969                                 break;
2970                         }
2971                 } else if (!strcasecmp(action, "append")) {
2972                         if (ast_strlen_zero(var)) {
2973                                 result = UNSPECIFIED_ARGUMENT;
2974                                 break;
2975                         }
2976                         if (!(category = ast_category_get(cfg, cat))) {
2977                                 result = UNKNOWN_CATEGORY;
2978                                 break;
2979                         }
2980                         if (!(v = ast_variable_new(var, value, dfn))) {
2981                                 result = FAILURE_ALLOCATION;
2982                                 break;
2983                         }
2984                         if (object || (match && !strcasecmp(match, "object"))) {
2985                                 v->object = 1;
2986                         }
2987                         ast_variable_append(category, v);
2988                 } else if (!strcasecmp(action, "insert")) {
2989                         if (ast_strlen_zero(var) || ast_strlen_zero(line)) {
2990                                 result = UNSPECIFIED_ARGUMENT;
2991                                 break;
2992                         }
2993                         if (!(category = ast_category_get(cfg, cat))) {
2994                                 result = UNKNOWN_CATEGORY;
2995                                 break;
2996                         }
2997                         if (!(v = ast_variable_new(var, value, dfn))) {
2998                                 result = FAILURE_ALLOCATION;
2999                                 break;
3000                         }
3001                         ast_variable_insert(category, v, line);
3002                 }
3003                 else {
3004                         ast_log(LOG_WARNING, "Action-%06d: %s not handled\n", x, action);
3005                         result = UNKNOWN_ACTION;
3006                         break;
3007                 }
3008         }
3009         ast_free(str1);
3010         ast_free(str2);
3011         return result;
3012 }
3013
3014 static int action_updateconfig(struct mansession *s, const struct message *m)
3015 {
3016         struct ast_config *cfg;
3017         const char *sfn = astman_get_header(m, "SrcFilename");
3018         const char *dfn = astman_get_header(m, "DstFilename");
3019         int res;
3020         const char *rld = astman_get_header(m, "Reload");
3021         struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
3022         enum error_type result;
3023
3024         if (ast_strlen_zero(sfn) || ast_strlen_zero(dfn)) {
3025                 astman_send_error(s, m, "Filename not specified");
3026                 return 0;
3027         }