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