e1bf19f680a6cdfec55194b75b7bc75b6ff2b9c1
[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: <replaceable>count</replaceable>.</para>
595                 </description>
596         </manager>
597         <manager name="MailboxCount" language="en_US">
598                 <synopsis>
599                         Check Mailbox Message Count.
600                 </synopsis>
601                 <syntax>
602                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
603                         <parameter name="Mailbox" required="true">
604                                 <para>Full mailbox ID <replaceable>mailbox</replaceable>@<replaceable>vm-context</replaceable>.</para>
605                         </parameter>
606                 </syntax>
607                 <description>
608                         <para>Checks a voicemail account for new messages.</para>
609                         <para>Returns number of urgent, new and old messages.</para>
610                         <para>Message: Mailbox Message Count</para>
611                         <para>Mailbox: <replaceable>mailboxid</replaceable></para>
612                         <para>UrgentMessages: <replaceable>count</replaceable></para>
613                         <para>NewMessages: <replaceable>count</replaceable></para>
614                         <para>OldMessages: <replaceable>count</replaceable></para>
615                 </description>
616         </manager>
617         <manager name="ListCommands" language="en_US">
618                 <synopsis>
619                         List available manager commands.
620                 </synopsis>
621                 <syntax>
622                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
623                 </syntax>
624                 <description>
625                         <para>Returns the action name and synopsis for every action that
626                         is available to the user.</para>
627                 </description>
628         </manager>
629         <manager name="SendText" language="en_US">
630                 <synopsis>
631                         Send text message to channel.
632                 </synopsis>
633                 <syntax>
634                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
635                         <parameter name="Channel" required="true">
636                                 <para>Channel to send message to.</para>
637                         </parameter>
638                         <parameter name="Message" required="true">
639                                 <para>Message to send.</para>
640                         </parameter>
641                 </syntax>
642                 <description>
643                         <para>Sends A Text Message to a channel while in a call.</para>
644                 </description>
645         </manager>
646         <manager name="UserEvent" language="en_US">
647                 <synopsis>
648                         Send an arbitrary event.
649                 </synopsis>
650                 <syntax>
651                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
652                         <parameter name="UserEvent" required="true">
653                                 <para>Event string to send.</para>
654                         </parameter>
655                         <parameter name="Header1">
656                                 <para>Content1.</para>
657                         </parameter>
658                         <parameter name="HeaderN">
659                                 <para>ContentN.</para>
660                         </parameter>
661                 </syntax>
662                 <description>
663                         <para>Send an event to manager sessions.</para>
664                 </description>
665         </manager>
666         <manager name="WaitEvent" language="en_US">
667                 <synopsis>
668                         Wait for an event to occur.
669                 </synopsis>
670                 <syntax>
671                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
672                         <parameter name="Timeout" required="true">
673                                 <para>Maximum time (in seconds) to wait for events, <literal>-1</literal> means forever.</para>
674                         </parameter>
675                 </syntax>
676                 <description>
677                         <para>This action will ellicit a <literal>Success</literal> response. Whenever
678                         a manager event is queued. Once WaitEvent has been called on an HTTP manager
679                         session, events will be generated and queued.</para>
680                 </description>
681         </manager>
682         <manager name="CoreSettings" language="en_US">
683                 <synopsis>
684                         Show PBX core settings (version etc).
685                 </synopsis>
686                 <syntax>
687                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
688                 </syntax>
689                 <description>
690                         <para>Query for Core PBX settings.</para>
691                 </description>
692         </manager>
693         <manager name="CoreStatus" language="en_US">
694                 <synopsis>
695                         Show PBX core status variables.
696                 </synopsis>
697                 <syntax>
698                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
699                 </syntax>
700                 <description>
701                         <para>Query for Core PBX status.</para>
702                 </description>
703         </manager>
704         <manager name="Reload" language="en_US">
705                 <synopsis>
706                         Send a reload event.
707                 </synopsis>
708                 <syntax>
709                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
710                         <parameter name="Module">
711                                 <para>Name of the module to reload.</para>
712                         </parameter>
713                 </syntax>
714                 <description>
715                         <para>Send a reload event.</para>
716                 </description>
717         </manager>
718         <manager name="CoreShowChannels" language="en_US">
719                 <synopsis>
720                         List currently active channels.
721                 </synopsis>
722                 <syntax>
723                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
724                 </syntax>
725                 <description>
726                         <para>List currently defined channels and some information about them.</para>
727                 </description>
728         </manager>
729         <manager name="ModuleLoad" language="en_US">
730                 <synopsis>
731                         Module management.
732                 </synopsis>
733                 <syntax>
734                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
735                         <parameter name="Module">
736                                 <para>Asterisk module name (including .so extension) or subsystem identifier:</para>
737                                 <enumlist>
738                                         <enum name="cdr" />
739                                         <enum name="enum" />
740                                         <enum name="dnsmgr" />
741                                         <enum name="extconfig" />
742                                         <enum name="manager" />
743                                         <enum name="rtp" />
744                                         <enum name="http" />
745                                 </enumlist>
746                         </parameter>
747                         <parameter name="LoadType" required="true">
748                                 <para>The operation to be done on module.</para>
749                                 <enumlist>
750                                         <enum name="load" />
751                                         <enum name="unload" />
752                                         <enum name="reload" />
753                                 </enumlist>
754                                 <para>If no module is specified for a <literal>reload</literal> loadtype,
755                                 all modules are reloaded.</para>
756                         </parameter>
757                 </syntax>
758                 <description>
759                         <para>Loads, unloads or reloads an Asterisk module in a running system.</para>
760                 </description>
761         </manager>
762         <manager name="ModuleCheck" language="en_US">
763                 <synopsis>
764                         Check if module is loaded.
765                 </synopsis>
766                 <syntax>
767                         <parameter name="Module" required="true">
768                                 <para>Asterisk module name (not including extension).</para>
769                         </parameter>
770                 </syntax>
771                 <description>
772                         <para>Checks if Asterisk module is loaded. Will return Success/Failure.
773                         For success returns, the module revision number is included.</para>
774                 </description>
775         </manager>
776         <manager name="AOCMessage" language="en_US">
777                 <synopsis>
778                         Generate an Advice of Charge message on a channel.
779                 </synopsis>
780                 <syntax>
781                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
782                         <parameter name="Channel" required="true">
783                                 <para>Channel name to generate the AOC message on.</para>
784                         </parameter>
785                         <parameter name="ChannelPrefix">
786                                 <para>Partial channel prefix.  By using this option one can match the beginning part
787                                 of a channel name without having to put the entire name in.  For example
788                                 if a channel name is SIP/snom-00000001 and this value is set to SIP/snom, then
789                                 that channel matches and the message will be sent.  Note however that only
790                                 the first matched channel has the message sent on it. </para>
791                         </parameter>
792                         <parameter name="MsgType" required="true">
793                                 <para>Defines what type of AOC message to create, AOC-D or AOC-E</para>
794                                 <enumlist>
795                                         <enum name="D" />
796                                         <enum name="E" />
797                                 </enumlist>
798                         </parameter>
799                         <parameter name="ChargeType" required="true">
800                                 <para>Defines what kind of charge this message represents.</para>
801                                 <enumlist>
802                                         <enum name="NA" />
803                                         <enum name="FREE" />
804                                         <enum name="Currency" />
805                                         <enum name="Unit" />
806                                 </enumlist>
807                         </parameter>
808                         <parameter name="UnitAmount(0)">
809                                 <para>This represents the amount of units charged. The ETSI AOC standard specifies that
810                                 this value along with the optional UnitType value are entries in a list.  To accommodate this
811                                 these values take an index value starting at 0 which can be used to generate this list of
812                                 unit entries.  For Example, If two unit entires were required this could be achieved by setting the
813                                 paramter UnitAmount(0)=1234 and UnitAmount(1)=5678.  Note that UnitAmount at index 0 is
814                                 required when ChargeType=Unit, all other entries in the list are optional.
815                                 </para>
816                         </parameter>
817                         <parameter name="UnitType(0)">
818                                 <para>Defines the type of unit.  ETSI AOC standard specifies this as an integer
819                                 value between 1 and 16, but this value is left open to accept any positive
820                                 integer.  Like the UnitAmount parameter, this value represents a list entry
821                                 and has an index parameter that starts at 0.
822                                 </para>
823                         </parameter>
824                         <parameter name="CurrencyName">
825                                 <para>Specifies the currency's name.  Note that this value is truncated after 10 characters.</para>
826                         </parameter>
827                         <parameter name="CurrencyAmount">
828                                 <para>Specifies the charge unit amount as a positive integer.  This value is required
829                                 when ChargeType==Currency.</para>
830                         </parameter>
831                         <parameter name="CurrencyMultiplier">
832                                 <para>Specifies the currency multiplier.  This value is required when ChargeType==Currency.</para>
833                                 <enumlist>
834                                         <enum name="OneThousandth" />
835                                         <enum name="OneHundredth" />
836                                         <enum name="OneTenth" />
837                                         <enum name="One" />
838                                         <enum name="Ten" />
839                                         <enum name="Hundred" />
840                                         <enum name="Thousand" />
841                                 </enumlist>
842                         </parameter>
843                         <parameter name="TotalType" default="Total">
844                                 <para>Defines what kind of AOC-D total is represented.</para>
845                                 <enumlist>
846                                         <enum name="Total" />
847                                         <enum name="SubTotal" />
848                                 </enumlist>
849                         </parameter>
850                         <parameter name="AOCBillingId">
851                                 <para>Represents a billing ID associated with an AOC-D or AOC-E message. Note
852                                 that only the first 3 items of the enum are valid AOC-D billing IDs</para>
853                                 <enumlist>
854                                         <enum name="Normal" />
855                                         <enum name="ReverseCharge" />
856                                         <enum name="CreditCard" />
857                                         <enum name="CallFwdUnconditional" />
858                                         <enum name="CallFwdBusy" />
859                                         <enum name="CallFwdNoReply" />
860                                         <enum name="CallDeflection" />
861                                         <enum name="CallTransfer" />
862                                 </enumlist>
863                         </parameter>
864                         <parameter name="ChargingAssociationId">
865                                 <para>Charging association identifier.  This is optional for AOC-E and can be
866                                 set to any value between -32768 and 32767</para>
867                         </parameter>
868                         <parameter name="ChargingAssociationNumber">
869                                 <para>Represents the charging association party number.  This value is optional
870                                 for AOC-E.</para>
871                         </parameter>
872                         <parameter name="ChargingAssociationPlan">
873                                 <para>Integer representing the charging plan associated with the ChargingAssociationNumber.
874                                 The value is bits 7 through 1 of the Q.931 octet containing the type-of-number and
875                                 numbering-plan-identification fields.</para>
876                         </parameter>
877                 </syntax>
878                 <description>
879                         <para>Generates an AOC-D or AOC-E message on a channel.</para>
880                 </description>
881         </manager>
882         <function name="AMI_CLIENT" language="en_US">
883                 <synopsis>
884                         Checks attributes of manager accounts
885                 </synopsis>
886                 <syntax>
887                         <parameter name="loginname" required="true">
888                                 <para>Login name, specified in manager.conf</para>
889                         </parameter>
890                         <parameter name="field" required="true">
891                                 <para>The manager account attribute to return</para>
892                                 <enumlist>
893                                         <enum name="sessions"><para>The number of sessions for this AMI account</para></enum>
894                                 </enumlist>
895                         </parameter>
896                 </syntax>
897                 <description>
898                         <para>
899                                 Currently, the only supported  parameter is "sessions" which will return the current number of
900                                 active sessions for this AMI account.
901                         </para>
902                 </description>
903         </function>
904         <manager name="Filter" language="en_US">
905                 <synopsis>
906                         Dynamically add filters for the current manager session.
907                 </synopsis>
908                 <syntax>
909                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
910                         <parameter name="Operation">
911                                 <enumlist>
912                                         <enum name="Add">
913                                                 <para>Add a filter.</para>
914                                         </enum>
915                                 </enumlist>
916                         </parameter>
917                         <parameter name="Filter">
918                                 <para>Filters can be whitelist or blacklist</para>
919                                 <para>Example whitelist filter: "Event: Newchannel"</para>
920                                 <para>Example blacklist filter: "!Channel: DAHDI.*"</para>
921                                 <para>This filter option is used to whitelist or blacklist events per user to be
922                                 reported with regular expressions and are allowed if both the regex matches
923                                 and the user has read access as defined in manager.conf. Filters are assumed to be for whitelisting
924                                 unless preceeded by an exclamation point, which marks it as being black.
925                                 Evaluation of the filters is as follows:</para>
926                                 <para>- If no filters are configured all events are reported as normal.</para>
927                                 <para>- If there are white filters only: implied black all filter processed first, then white filters.</para>
928                                 <para>- If there are black filters only: implied white all filter processed first, then black filters.</para>
929                                 <para>- If there are both white and black filters: implied black all filter processed first, then white
930                                 filters, and lastly black filters.</para>
931                         </parameter>
932                 </syntax>
933                 <description>
934                         <para>The filters added are only used for the current session.
935                         Once the connection is closed the filters are removed.</para>
936                         <para>This comand requires the system permission because
937                         this command can be used to create filters that may bypass
938                         filters defined in manager.conf</para>
939                 </description>
940         </manager>
941         <manager name="FilterList" language="en_US">
942                 <synopsis>
943                         Show current event filters for this session
944                 </synopsis>
945                 <description>
946                         <para>The filters displayed are for the current session.  Only those filters defined in
947                         manager.conf will be present upon starting a new session.</para>
948                 </description>
949         </manager>
950  ***/
951
952 enum error_type {
953         UNKNOWN_ACTION = 1,
954         UNKNOWN_CATEGORY,
955         UNSPECIFIED_CATEGORY,
956         UNSPECIFIED_ARGUMENT,
957         FAILURE_ALLOCATION,
958         FAILURE_NEWCAT,
959         FAILURE_DELCAT,
960         FAILURE_EMPTYCAT,
961         FAILURE_UPDATE,
962         FAILURE_DELETE,
963         FAILURE_APPEND
964 };
965
966 enum add_filter_result {
967         FILTER_SUCCESS,
968         FILTER_ALLOC_FAILED,
969         FILTER_COMPILE_FAIL,
970 };
971
972 /*!
973  * Linked list of events.
974  * Global events are appended to the list by append_event().
975  * The usecount is the number of stored pointers to the element,
976  * excluding the list pointers. So an element that is only in
977  * the list has a usecount of 0, not 1.
978  *
979  * Clients have a pointer to the last event processed, and for each
980  * of these clients we track the usecount of the elements.
981  * If we have a pointer to an entry in the list, it is safe to navigate
982  * it forward because elements will not be deleted, but only appended.
983  * The worst that can happen is seeing the pointer still NULL.
984  *
985  * When the usecount of an element drops to 0, and the element is the
986  * first in the list, we can remove it. Removal is done within the
987  * main thread, which is woken up for the purpose.
988  *
989  * For simplicity of implementation, we make sure the list is never empty.
990  */
991 struct eventqent {
992         int usecount;           /*!< # of clients who still need the event */
993         int category;
994         unsigned int seq;       /*!< sequence number */
995         struct timeval tv;  /*!< When event was allocated */
996         AST_RWLIST_ENTRY(eventqent) eq_next;
997         char eventdata[1];      /*!< really variable size, allocated by append_event() */
998 };
999
1000 static AST_RWLIST_HEAD_STATIC(all_events, eventqent);
1001
1002 static int displayconnects = 1;
1003 static int allowmultiplelogin = 1;
1004 static int timestampevents;
1005 static int httptimeout = 60;
1006 static int broken_events_action = 0;
1007 static int manager_enabled = 0;
1008 static int webmanager_enabled = 0;
1009 static int manager_debug = 0;   /*!< enable some debugging code in the manager */
1010 static int authtimeout;
1011 static int authlimit;
1012 static char *manager_channelvars;
1013
1014 #define DEFAULT_REALM           "asterisk"
1015 static char global_realm[MAXHOSTNAMELEN];       /*!< Default realm */
1016
1017 static int block_sockets;
1018 static int unauth_sessions = 0;
1019 static struct ast_event_sub *acl_change_event_subscription;
1020
1021 /*! \brief
1022  * Descriptor for a manager session, either on the AMI socket or over HTTP.
1023  *
1024  * \note
1025  * AMI session have managerid == 0; the entry is created upon a connect,
1026  * and destroyed with the socket.
1027  * HTTP sessions have managerid != 0, the value is used as a search key
1028  * to lookup sessions (using the mansession_id cookie, or nonce key from
1029  * Digest Authentication http header).
1030  */
1031 #define MAX_BLACKLIST_CMD_LEN 2
1032 static const struct {
1033         const char *words[AST_MAX_CMD_LEN];
1034 } command_blacklist[] = {
1035         {{ "module", "load", NULL }},
1036         {{ "module", "unload", NULL }},
1037         {{ "restart", "gracefully", NULL }},
1038 };
1039
1040 static void acl_change_event_cb(const struct ast_event *event, void *userdata);
1041
1042 static void acl_change_event_subscribe(void)
1043 {
1044         if (!acl_change_event_subscription) {
1045                 acl_change_event_subscription = ast_event_subscribe(AST_EVENT_ACL_CHANGE,
1046                         acl_change_event_cb, "Manager must react to Named ACL changes", NULL, AST_EVENT_IE_END);
1047         }
1048 }
1049
1050 static void acl_change_event_unsubscribe(void)
1051 {
1052         if (acl_change_event_subscription) {
1053                 acl_change_event_subscription = ast_event_unsubscribe(acl_change_event_subscription);
1054         }
1055 }
1056
1057 /* In order to understand what the heck is going on with the
1058  * mansession_session and mansession structs, we need to have a bit of a history
1059  * lesson.
1060  *
1061  * In the beginning, there was the mansession. The mansession contained data that was
1062  * intrinsic to a manager session, such as the time that it started, the name of the logged-in
1063  * user, etc. In addition to these parameters were the f and fd parameters. For typical manager
1064  * sessions, these were used to represent the TCP socket over which the AMI session was taking
1065  * place. It makes perfect sense for these fields to be a part of the session-specific data since
1066  * the session actually defines this information.
1067  *
1068  * Then came the HTTP AMI sessions. With these, the f and fd fields need to be opened and closed
1069  * for every single action that occurs. Thus the f and fd fields aren't really specific to the session
1070  * but rather to the action that is being executed. Because a single session may execute many commands
1071  * at once, some sort of safety needed to be added in order to be sure that we did not end up with fd
1072  * leaks from one action overwriting the f and fd fields used by a previous action before the previous action
1073  * has had a chance to properly close its handles.
1074  *
1075  * The initial idea to solve this was to use thread synchronization, but this prevented multiple actions
1076  * from being run at the same time in a single session. Some manager actions may block for a long time, thus
1077  * creating a large queue of actions to execute. In addition, this fix did not address the basic architectural
1078  * issue that for HTTP manager sessions, the f and fd variables are not really a part of the session, but are
1079  * part of the action instead.
1080  *
1081  * The new idea was to create a structure on the stack for each HTTP Manager action. This structure would
1082  * contain the action-specific information, such as which file to write to. In order to maintain expectations
1083  * of action handlers and not have to change the public API of the manager code, we would need to name this
1084  * new stacked structure 'mansession' and contain within it the old mansession struct that we used to use.
1085  * We renamed the old mansession struct 'mansession_session' to hopefully convey that what is in this structure
1086  * is session-specific data. The structure that it is wrapped in, called a 'mansession' really contains action-specific
1087  * data.
1088  */
1089 struct mansession_session {
1090                                 /*! \todo XXX need to document which fields it is protecting */
1091         struct ast_sockaddr addr;       /*!< address we are connecting from */
1092         FILE *f;                /*!< fdopen() on the underlying fd */
1093         int fd;                 /*!< descriptor used for output. Either the socket (AMI) or a temporary file (HTTP) */
1094         int inuse;              /*!< number of HTTP sessions using this entry */
1095         int needdestroy;        /*!< Whether an HTTP session should be destroyed */
1096         pthread_t waiting_thread;       /*!< Sleeping thread using this descriptor */
1097         uint32_t managerid;     /*!< Unique manager identifier, 0 for AMI sessions */
1098         time_t sessionstart;    /*!< Session start time */
1099         struct timeval sessionstart_tv; /*!< Session start time */
1100         time_t sessiontimeout;  /*!< Session timeout if HTTP */
1101         char username[80];      /*!< Logged in username */
1102         char challenge[10];     /*!< Authentication challenge */
1103         int authenticated;      /*!< Authentication status */
1104         int readperm;           /*!< Authorization for reading */
1105         int writeperm;          /*!< Authorization for writing */
1106         char inbuf[1025];       /*!< Buffer -  we use the extra byte to add a '\0' and simplify parsing */
1107         int inlen;              /*!< number of buffered bytes */
1108         struct ao2_container *whitefilters;     /*!< Manager event filters - white list */
1109         struct ao2_container *blackfilters;     /*!< Manager event filters - black list */
1110         struct ast_variable *chanvars;  /*!< Channel variables to set for originate */
1111         int send_events;        /*!<  XXX what ? */
1112         struct eventqent *last_ev;      /*!< last event processed. */
1113         int writetimeout;       /*!< Timeout for ast_carefulwrite() */
1114         time_t authstart;
1115         int pending_event;         /*!< Pending events indicator in case when waiting_thread is NULL */
1116         time_t noncetime;       /*!< Timer for nonce value expiration */
1117         unsigned long oldnonce; /*!< Stale nonce value */
1118         unsigned long nc;       /*!< incremental  nonce counter */
1119         AST_LIST_HEAD_NOLOCK(mansession_datastores, ast_datastore) datastores; /*!< Data stores on the session */
1120         AST_LIST_ENTRY(mansession_session) list;
1121 };
1122
1123 /*! \brief In case you didn't read that giant block of text above the mansession_session struct, the
1124  * \ref struct mansession is named this solely to keep the API the same in Asterisk. This structure really
1125  * represents data that is different from Manager action to Manager action. The mansession_session pointer
1126  * contained within points to session-specific data.
1127  */
1128 struct mansession {
1129         struct mansession_session *session;
1130         struct ast_tcptls_session_instance *tcptls_session;
1131         FILE *f;
1132         int fd;
1133         int write_error:1;
1134         struct manager_custom_hook *hook;
1135         ast_mutex_t lock;
1136 };
1137
1138 static struct ao2_container *sessions = NULL;
1139
1140 struct manager_channel_variable {
1141         AST_LIST_ENTRY(manager_channel_variable) entry;
1142         unsigned int isfunc:1;
1143         char name[0]; /* allocate off the end the real size. */
1144 };
1145
1146 static AST_RWLIST_HEAD_STATIC(channelvars, manager_channel_variable);
1147
1148 /*! \brief user descriptor, as read from the config file.
1149  *
1150  * \note It is still missing some fields -- e.g. we can have multiple permit and deny
1151  * lines which are not supported here, and readperm/writeperm/writetimeout
1152  * are not stored.
1153  */
1154 struct ast_manager_user {
1155         char username[80];
1156         char *secret;                   /*!< Secret for logging in */
1157         int readperm;                   /*!< Authorization for reading */
1158         int writeperm;                  /*!< Authorization for writing */
1159         int writetimeout;               /*!< Per user Timeout for ast_carefulwrite() */
1160         int displayconnects;            /*!< XXX unused */
1161         int keep;                       /*!< mark entries created on a reload */
1162         struct ao2_container *whitefilters; /*!< Manager event filters - white list */
1163         struct ao2_container *blackfilters; /*!< Manager event filters - black list */
1164         struct ast_acl_list *acl;       /*!< ACL setting */
1165         char *a1_hash;                  /*!< precalculated A1 for Digest auth */
1166         struct ast_variable *chanvars;  /*!< Channel variables to set for originate */
1167         AST_RWLIST_ENTRY(ast_manager_user) list;
1168 };
1169
1170 /*! \brief list of users found in the config file */
1171 static AST_RWLIST_HEAD_STATIC(users, ast_manager_user);
1172
1173 /*! \brief list of actions registered */
1174 static AST_RWLIST_HEAD_STATIC(actions, manager_action);
1175
1176 /*! \brief list of hooks registered */
1177 static AST_RWLIST_HEAD_STATIC(manager_hooks, manager_custom_hook);
1178
1179 /*! \brief A container of event documentation nodes */
1180 AO2_GLOBAL_OBJ_STATIC(event_docs);
1181
1182 static void free_channelvars(void);
1183
1184 static enum add_filter_result manager_add_filter(const char *filter_pattern, struct ao2_container *whitefilters, struct ao2_container *blackfilters);
1185
1186 /*!
1187  * \internal
1188  * \brief Find a registered action object.
1189  *
1190  * \param name Name of AMI action to find.
1191  *
1192  * \return Reffed action found or NULL
1193  */
1194 static struct manager_action *action_find(const char *name)
1195 {
1196         struct manager_action *act;
1197
1198         AST_RWLIST_RDLOCK(&actions);
1199         AST_RWLIST_TRAVERSE(&actions, act, list) {
1200                 if (!strcasecmp(name, act->action)) {
1201                         ao2_t_ref(act, +1, "found action object");
1202                         break;
1203                 }
1204         }
1205         AST_RWLIST_UNLOCK(&actions);
1206
1207         return act;
1208 }
1209
1210 /*! \brief Add a custom hook to be called when an event is fired */
1211 void ast_manager_register_hook(struct manager_custom_hook *hook)
1212 {
1213         AST_RWLIST_WRLOCK(&manager_hooks);
1214         AST_RWLIST_INSERT_TAIL(&manager_hooks, hook, list);
1215         AST_RWLIST_UNLOCK(&manager_hooks);
1216 }
1217
1218 /*! \brief Delete a custom hook to be called when an event is fired */
1219 void ast_manager_unregister_hook(struct manager_custom_hook *hook)
1220 {
1221         AST_RWLIST_WRLOCK(&manager_hooks);
1222         AST_RWLIST_REMOVE(&manager_hooks, hook, list);
1223         AST_RWLIST_UNLOCK(&manager_hooks);
1224 }
1225
1226 int check_manager_enabled(void)
1227 {
1228         return manager_enabled;
1229 }
1230
1231 int check_webmanager_enabled(void)
1232 {
1233         return (webmanager_enabled && manager_enabled);
1234 }
1235
1236 /*!
1237  * Grab a reference to the last event, update usecount as needed.
1238  * Can handle a NULL pointer.
1239  */
1240 static struct eventqent *grab_last(void)
1241 {
1242         struct eventqent *ret;
1243
1244         AST_RWLIST_WRLOCK(&all_events);
1245         ret = AST_RWLIST_LAST(&all_events);
1246         /* the list is never empty now, but may become so when
1247          * we optimize it in the future, so be prepared.
1248          */
1249         if (ret) {
1250                 ast_atomic_fetchadd_int(&ret->usecount, 1);
1251         }
1252         AST_RWLIST_UNLOCK(&all_events);
1253         return ret;
1254 }
1255
1256 /*!
1257  * Purge unused events. Remove elements from the head
1258  * as long as their usecount is 0 and there is a next element.
1259  */
1260 static void purge_events(void)
1261 {
1262         struct eventqent *ev;
1263         struct timeval now = ast_tvnow();
1264
1265         AST_RWLIST_WRLOCK(&all_events);
1266         while ( (ev = AST_RWLIST_FIRST(&all_events)) &&
1267             ev->usecount == 0 && AST_RWLIST_NEXT(ev, eq_next)) {
1268                 AST_RWLIST_REMOVE_HEAD(&all_events, eq_next);
1269                 ast_free(ev);
1270         }
1271
1272         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&all_events, ev, eq_next) {
1273                 /* Never release the last event */
1274                 if (!AST_RWLIST_NEXT(ev, eq_next)) {
1275                         break;
1276                 }
1277
1278                 /* 2.5 times whatever the HTTP timeout is (maximum 2.5 hours) is the maximum time that we will definitely cache an event */
1279                 if (ev->usecount == 0 && ast_tvdiff_sec(now, ev->tv) > (httptimeout > 3600 ? 3600 : httptimeout) * 2.5) {
1280                         AST_RWLIST_REMOVE_CURRENT(eq_next);
1281                         ast_free(ev);
1282                 }
1283         }
1284         AST_RWLIST_TRAVERSE_SAFE_END;
1285         AST_RWLIST_UNLOCK(&all_events);
1286 }
1287
1288 /*!
1289  * helper functions to convert back and forth between
1290  * string and numeric representation of set of flags
1291  */
1292 static const struct permalias {
1293         int num;
1294         const char *label;
1295 } perms[] = {
1296         { EVENT_FLAG_SYSTEM, "system" },
1297         { EVENT_FLAG_CALL, "call" },
1298         { EVENT_FLAG_LOG, "log" },
1299         { EVENT_FLAG_VERBOSE, "verbose" },
1300         { EVENT_FLAG_COMMAND, "command" },
1301         { EVENT_FLAG_AGENT, "agent" },
1302         { EVENT_FLAG_USER, "user" },
1303         { EVENT_FLAG_CONFIG, "config" },
1304         { EVENT_FLAG_DTMF, "dtmf" },
1305         { EVENT_FLAG_REPORTING, "reporting" },
1306         { EVENT_FLAG_CDR, "cdr" },
1307         { EVENT_FLAG_DIALPLAN, "dialplan" },
1308         { EVENT_FLAG_ORIGINATE, "originate" },
1309         { EVENT_FLAG_AGI, "agi" },
1310         { EVENT_FLAG_CC, "cc" },
1311         { EVENT_FLAG_AOC, "aoc" },
1312         { EVENT_FLAG_TEST, "test" },
1313         { EVENT_FLAG_MESSAGE, "message" },
1314         { INT_MAX, "all" },
1315         { 0, "none" },
1316 };
1317
1318 /*! \brief Checks to see if a string which can be used to evaluate functions should be rejected */
1319 static int function_capable_string_allowed_with_auths(const char *evaluating, int writepermlist)
1320 {
1321         if (!(writepermlist & EVENT_FLAG_SYSTEM)
1322                 && (
1323                         strstr(evaluating, "SHELL") ||       /* NoOp(${SHELL(rm -rf /)})  */
1324                         strstr(evaluating, "EVAL")           /* NoOp(${EVAL(${some_var_containing_SHELL})}) */
1325                 )) {
1326                 return 0;
1327         }
1328         return 1;
1329 }
1330
1331 /*! \brief Convert authority code to a list of options */
1332 static const char *authority_to_str(int authority, struct ast_str **res)
1333 {
1334         int i;
1335         char *sep = "";
1336
1337         ast_str_reset(*res);
1338         for (i = 0; i < ARRAY_LEN(perms) - 1; i++) {
1339                 if (authority & perms[i].num) {
1340                         ast_str_append(res, 0, "%s%s", sep, perms[i].label);
1341                         sep = ",";
1342                 }
1343         }
1344
1345         if (ast_str_strlen(*res) == 0)  /* replace empty string with something sensible */
1346                 ast_str_append(res, 0, "<none>");
1347
1348         return ast_str_buffer(*res);
1349 }
1350
1351 /*! Tells you if smallstr exists inside bigstr
1352    which is delim by delim and uses no buf or stringsep
1353    ast_instring("this|that|more","this",'|') == 1;
1354
1355    feel free to move this to app.c -anthm */
1356 static int ast_instring(const char *bigstr, const char *smallstr, const char delim)
1357 {
1358         const char *val = bigstr, *next;
1359
1360         do {
1361                 if ((next = strchr(val, delim))) {
1362                         if (!strncmp(val, smallstr, (next - val))) {
1363                                 return 1;
1364                         } else {
1365                                 continue;
1366                         }
1367                 } else {
1368                         return !strcmp(smallstr, val);
1369                 }
1370         } while (*(val = (next + 1)));
1371
1372         return 0;
1373 }
1374
1375 static int get_perm(const char *instr)
1376 {
1377         int x = 0, ret = 0;
1378
1379         if (!instr) {
1380                 return 0;
1381         }
1382
1383         for (x = 0; x < ARRAY_LEN(perms); x++) {
1384                 if (ast_instring(instr, perms[x].label, ',')) {
1385                         ret |= perms[x].num;
1386                 }
1387         }
1388
1389         return ret;
1390 }
1391
1392 /*!
1393  * A number returns itself, false returns 0, true returns all flags,
1394  * other strings return the flags that are set.
1395  */
1396 static int strings_to_mask(const char *string)
1397 {
1398         const char *p;
1399
1400         if (ast_strlen_zero(string)) {
1401                 return -1;
1402         }
1403
1404         for (p = string; *p; p++) {
1405                 if (*p < '0' || *p > '9') {
1406                         break;
1407                 }
1408         }
1409         if (!*p) { /* all digits */
1410                 return atoi(string);
1411         }
1412         if (ast_false(string)) {
1413                 return 0;
1414         }
1415         if (ast_true(string)) { /* all permissions */
1416                 int x, ret = 0;
1417                 for (x = 0; x < ARRAY_LEN(perms); x++) {
1418                         ret |= perms[x].num;
1419                 }
1420                 return ret;
1421         }
1422         return get_perm(string);
1423 }
1424
1425 /*! \brief Unreference manager session object.
1426      If no more references, then go ahead and delete it */
1427 static struct mansession_session *unref_mansession(struct mansession_session *s)
1428 {
1429         int refcount = ao2_ref(s, -1);
1430         if (manager_debug) {
1431                 ast_debug(1, "Mansession: %p refcount now %d\n", s, refcount - 1);
1432         }
1433         return s;
1434 }
1435
1436 static void event_filter_destructor(void *obj)
1437 {
1438         regex_t *regex_filter = obj;
1439         regfree(regex_filter);
1440 }
1441
1442 static void session_destructor(void *obj)
1443 {
1444         struct mansession_session *session = obj;
1445         struct eventqent *eqe = session->last_ev;
1446         struct ast_datastore *datastore;
1447
1448         /* Get rid of each of the data stores on the session */
1449         while ((datastore = AST_LIST_REMOVE_HEAD(&session->datastores, entry))) {
1450                 /* Free the data store */
1451                 ast_datastore_free(datastore);
1452         }
1453
1454         if (session->f != NULL) {
1455                 fclose(session->f);
1456         }
1457         if (eqe) {
1458                 ast_atomic_fetchadd_int(&eqe->usecount, -1);
1459         }
1460         if (session->chanvars) {
1461                 ast_variables_destroy(session->chanvars);
1462         }
1463
1464         if (session->whitefilters) {
1465                 ao2_t_callback(session->whitefilters, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL, "unlink all white filters");
1466                 ao2_t_ref(session->whitefilters, -1 , "decrement ref for white container, should be last one");
1467         }
1468
1469         if (session->blackfilters) {
1470                 ao2_t_callback(session->blackfilters, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL, "unlink all black filters");
1471                 ao2_t_ref(session->blackfilters, -1 , "decrement ref for black container, should be last one");
1472         }
1473 }
1474
1475 /*! \brief Allocate manager session structure and add it to the list of sessions */
1476 static struct mansession_session *build_mansession(const struct ast_sockaddr *addr)
1477 {
1478         struct mansession_session *newsession;
1479
1480         if (!(newsession = ao2_alloc(sizeof(*newsession), session_destructor))) {
1481                 return NULL;
1482         }
1483
1484         if (!(newsession->whitefilters = ao2_container_alloc(1, NULL, NULL))) {
1485                 ao2_ref(newsession, -1);
1486                 return NULL;
1487         }
1488
1489         if (!(newsession->blackfilters = ao2_container_alloc(1, NULL, NULL))) {
1490                 ao2_ref(newsession, -1); /* session_destructor will cleanup the other filter */
1491                 return NULL;
1492         }
1493
1494         newsession->fd = -1;
1495         newsession->waiting_thread = AST_PTHREADT_NULL;
1496         newsession->writetimeout = 100;
1497         newsession->send_events = -1;
1498         ast_sockaddr_copy(&newsession->addr, addr);
1499
1500         ao2_link(sessions, newsession);
1501
1502         return newsession;
1503 }
1504
1505 static int mansession_cmp_fn(void *obj, void *arg, int flags)
1506 {
1507         struct mansession_session *s = obj;
1508         char *str = arg;
1509         return !strcasecmp(s->username, str) ? CMP_MATCH : 0;
1510 }
1511
1512 static void session_destroy(struct mansession_session *s)
1513 {
1514         unref_mansession(s);
1515         ao2_unlink(sessions, s);
1516 }
1517
1518
1519 static int check_manager_session_inuse(const char *name)
1520 {
1521         struct mansession_session *session = ao2_find(sessions, (char *) name, 0);
1522         int inuse = 0;
1523
1524         if (session) {
1525                 inuse = 1;
1526                 unref_mansession(session);
1527         }
1528         return inuse;
1529 }
1530
1531
1532 /*!
1533  * lookup an entry in the list of registered users.
1534  * must be called with the list lock held.
1535  */
1536 static struct ast_manager_user *get_manager_by_name_locked(const char *name)
1537 {
1538         struct ast_manager_user *user = NULL;
1539
1540         AST_RWLIST_TRAVERSE(&users, user, list) {
1541                 if (!strcasecmp(user->username, name)) {
1542                         break;
1543                 }
1544         }
1545
1546         return user;
1547 }
1548
1549 /*! \brief Get displayconnects config option.
1550  *  \param session manager session to get parameter from.
1551  *  \return displayconnects config option value.
1552  */
1553 static int manager_displayconnects (struct mansession_session *session)
1554 {
1555         struct ast_manager_user *user = NULL;
1556         int ret = 0;
1557
1558         AST_RWLIST_RDLOCK(&users);
1559         if ((user = get_manager_by_name_locked (session->username))) {
1560                 ret = user->displayconnects;
1561         }
1562         AST_RWLIST_UNLOCK(&users);
1563
1564         return ret;
1565 }
1566
1567 static char *handle_showmancmd(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1568 {
1569         struct manager_action *cur;
1570         struct ast_str *authority;
1571         int num, l, which;
1572         char *ret = NULL;
1573 #ifdef AST_XML_DOCS
1574         char syntax_title[64], description_title[64], synopsis_title[64], seealso_title[64], arguments_title[64];
1575 #endif
1576
1577         switch (cmd) {
1578         case CLI_INIT:
1579                 e->command = "manager show command";
1580                 e->usage =
1581                         "Usage: manager show command <actionname> [<actionname> [<actionname> [...]]]\n"
1582                         "       Shows the detailed description for a specific Asterisk manager interface command.\n";
1583                 return NULL;
1584         case CLI_GENERATE:
1585                 l = strlen(a->word);
1586                 which = 0;
1587                 AST_RWLIST_RDLOCK(&actions);
1588                 AST_RWLIST_TRAVERSE(&actions, cur, list) {
1589                         if (!strncasecmp(a->word, cur->action, l) && ++which > a->n) {
1590                                 ret = ast_strdup(cur->action);
1591                                 break;  /* make sure we exit even if ast_strdup() returns NULL */
1592                         }
1593                 }
1594                 AST_RWLIST_UNLOCK(&actions);
1595                 return ret;
1596         }
1597         authority = ast_str_alloca(80);
1598         if (a->argc < 4) {
1599                 return CLI_SHOWUSAGE;
1600         }
1601
1602 #ifdef AST_XML_DOCS
1603         /* setup the titles */
1604         term_color(synopsis_title, "[Synopsis]\n", COLOR_MAGENTA, 0, 40);
1605         term_color(description_title, "[Description]\n", COLOR_MAGENTA, 0, 40);
1606         term_color(syntax_title, "[Syntax]\n", COLOR_MAGENTA, 0, 40);
1607         term_color(seealso_title, "[See Also]\n", COLOR_MAGENTA, 0, 40);
1608         term_color(arguments_title, "[Arguments]\n", COLOR_MAGENTA, 0, 40);
1609 #endif
1610
1611         AST_RWLIST_RDLOCK(&actions);
1612         AST_RWLIST_TRAVERSE(&actions, cur, list) {
1613                 for (num = 3; num < a->argc; num++) {
1614                         if (!strcasecmp(cur->action, a->argv[num])) {
1615 #ifdef AST_XML_DOCS
1616                                 if (cur->docsrc == AST_XML_DOC) {
1617                                         ast_cli(a->fd, "%s%s\n\n%s%s\n\n%s%s\n\n%s%s\n\n%s%s\n\n",
1618                                                 syntax_title,
1619                                                 ast_xmldoc_printable(S_OR(cur->syntax, "Not available"), 1),
1620                                                 synopsis_title,
1621                                                 ast_xmldoc_printable(S_OR(cur->synopsis, "Not available"), 1),
1622                                                 description_title,
1623                                                 ast_xmldoc_printable(S_OR(cur->description, "Not available"), 1),
1624                                                 arguments_title,
1625                                                 ast_xmldoc_printable(S_OR(cur->arguments, "Not available"), 1),
1626                                                 seealso_title,
1627                                                 ast_xmldoc_printable(S_OR(cur->seealso, "Not available"), 1));
1628                                 } else
1629 #endif
1630                                 {
1631                                         ast_cli(a->fd, "Action: %s\nSynopsis: %s\nPrivilege: %s\n%s\n",
1632                                                 cur->action, cur->synopsis,
1633                                                 authority_to_str(cur->authority, &authority),
1634                                                 S_OR(cur->description, ""));
1635                                 }
1636                         }
1637                 }
1638         }
1639         AST_RWLIST_UNLOCK(&actions);
1640
1641         return CLI_SUCCESS;
1642 }
1643
1644 static char *handle_mandebug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1645 {
1646         switch (cmd) {
1647         case CLI_INIT:
1648                 e->command = "manager set debug [on|off]";
1649                 e->usage = "Usage: manager set debug [on|off]\n Show, enable, disable debugging of the manager code.\n";
1650                 return NULL;
1651         case CLI_GENERATE:
1652                 return NULL;
1653         }
1654
1655         if (a->argc == 3) {
1656                 ast_cli(a->fd, "manager debug is %s\n", manager_debug? "on" : "off");
1657         } else if (a->argc == 4) {
1658                 if (!strcasecmp(a->argv[3], "on")) {
1659                         manager_debug = 1;
1660                 } else if (!strcasecmp(a->argv[3], "off")) {
1661                         manager_debug = 0;
1662                 } else {
1663                         return CLI_SHOWUSAGE;
1664                 }
1665         }
1666         return CLI_SUCCESS;
1667 }
1668
1669 static char *handle_showmanager(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1670 {
1671         struct ast_manager_user *user = NULL;
1672         int l, which;
1673         char *ret = NULL;
1674         struct ast_str *rauthority = ast_str_alloca(128);
1675         struct ast_str *wauthority = ast_str_alloca(128);
1676         struct ast_variable *v;
1677
1678         switch (cmd) {
1679         case CLI_INIT:
1680                 e->command = "manager show user";
1681                 e->usage =
1682                         " Usage: manager show user <user>\n"
1683                         "        Display all information related to the manager user specified.\n";
1684                 return NULL;
1685         case CLI_GENERATE:
1686                 l = strlen(a->word);
1687                 which = 0;
1688                 if (a->pos != 3) {
1689                         return NULL;
1690                 }
1691                 AST_RWLIST_RDLOCK(&users);
1692                 AST_RWLIST_TRAVERSE(&users, user, list) {
1693                         if ( !strncasecmp(a->word, user->username, l) && ++which > a->n ) {
1694                                 ret = ast_strdup(user->username);
1695                                 break;
1696                         }
1697                 }
1698                 AST_RWLIST_UNLOCK(&users);
1699                 return ret;
1700         }
1701
1702         if (a->argc != 4) {
1703                 return CLI_SHOWUSAGE;
1704         }
1705
1706         AST_RWLIST_RDLOCK(&users);
1707
1708         if (!(user = get_manager_by_name_locked(a->argv[3]))) {
1709                 ast_cli(a->fd, "There is no manager called %s\n", a->argv[3]);
1710                 AST_RWLIST_UNLOCK(&users);
1711                 return CLI_SUCCESS;
1712         }
1713
1714         ast_cli(a->fd, "\n");
1715         ast_cli(a->fd,
1716                 "       username: %s\n"
1717                 "         secret: %s\n"
1718                 "            ACL: %s\n"
1719                 "      read perm: %s\n"
1720                 "     write perm: %s\n"
1721                 "displayconnects: %s\n",
1722                 (user->username ? user->username : "(N/A)"),
1723                 (user->secret ? "<Set>" : "(N/A)"),
1724                 ((user->acl && !ast_acl_list_is_empty(user->acl)) ? "yes" : "no"),
1725                 authority_to_str(user->readperm, &rauthority),
1726                 authority_to_str(user->writeperm, &wauthority),
1727                 (user->displayconnects ? "yes" : "no"));
1728         ast_cli(a->fd, "      Variables: \n");
1729                 for (v = user->chanvars ; v ; v = v->next) {
1730                         ast_cli(a->fd, "                 %s = %s\n", v->name, v->value);
1731                 }
1732
1733         AST_RWLIST_UNLOCK(&users);
1734
1735         return CLI_SUCCESS;
1736 }
1737
1738 static char *handle_showmanagers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1739 {
1740         struct ast_manager_user *user = NULL;
1741         int count_amu = 0;
1742         switch (cmd) {
1743         case CLI_INIT:
1744                 e->command = "manager show users";
1745                 e->usage =
1746                         "Usage: manager show users\n"
1747                         "       Prints a listing of all managers that are currently configured on that\n"
1748                         " system.\n";
1749                 return NULL;
1750         case CLI_GENERATE:
1751                 return NULL;
1752         }
1753         if (a->argc != 3) {
1754                 return CLI_SHOWUSAGE;
1755         }
1756
1757         AST_RWLIST_RDLOCK(&users);
1758
1759         /* If there are no users, print out something along those lines */
1760         if (AST_RWLIST_EMPTY(&users)) {
1761                 ast_cli(a->fd, "There are no manager users.\n");
1762                 AST_RWLIST_UNLOCK(&users);
1763                 return CLI_SUCCESS;
1764         }
1765
1766         ast_cli(a->fd, "\nusername\n--------\n");
1767
1768         AST_RWLIST_TRAVERSE(&users, user, list) {
1769                 ast_cli(a->fd, "%s\n", user->username);
1770                 count_amu++;
1771         }
1772
1773         AST_RWLIST_UNLOCK(&users);
1774
1775         ast_cli(a->fd,"-------------------\n"
1776                       "%d manager users configured.\n", count_amu);
1777         return CLI_SUCCESS;
1778 }
1779
1780 /*! \brief  CLI command  manager list commands */
1781 static char *handle_showmancmds(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1782 {
1783         struct manager_action *cur;
1784         struct ast_str *authority;
1785 #define HSMC_FORMAT "  %-15.15s  %-15.15s  %-55.55s\n"
1786         switch (cmd) {
1787         case CLI_INIT:
1788                 e->command = "manager show commands";
1789                 e->usage =
1790                         "Usage: manager show commands\n"
1791                         "       Prints a listing of all the available Asterisk manager interface commands.\n";
1792                 return NULL;
1793         case CLI_GENERATE:
1794                 return NULL;
1795         }
1796         authority = ast_str_alloca(80);
1797         ast_cli(a->fd, HSMC_FORMAT, "Action", "Privilege", "Synopsis");
1798         ast_cli(a->fd, HSMC_FORMAT, "------", "---------", "--------");
1799
1800         AST_RWLIST_RDLOCK(&actions);
1801         AST_RWLIST_TRAVERSE(&actions, cur, list) {
1802                 ast_cli(a->fd, HSMC_FORMAT, cur->action, authority_to_str(cur->authority, &authority), cur->synopsis);
1803         }
1804         AST_RWLIST_UNLOCK(&actions);
1805
1806         return CLI_SUCCESS;
1807 }
1808
1809 /*! \brief CLI command manager list connected */
1810 static char *handle_showmanconn(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1811 {
1812         struct mansession_session *session;
1813         time_t now = time(NULL);
1814 #define HSMCONN_FORMAT1 "  %-15.15s  %-55.55s  %-10.10s  %-10.10s  %-8.8s  %-8.8s  %-5.5s  %-5.5s\n"
1815 #define HSMCONN_FORMAT2 "  %-15.15s  %-55.55s  %-10d  %-10d  %-8d  %-8d  %-5.5d  %-5.5d\n"
1816         int count = 0;
1817         struct ao2_iterator i;
1818
1819         switch (cmd) {
1820         case CLI_INIT:
1821                 e->command = "manager show connected";
1822                 e->usage =
1823                         "Usage: manager show connected\n"
1824                         "       Prints a listing of the users that are currently connected to the\n"
1825                         "Asterisk manager interface.\n";
1826                 return NULL;
1827         case CLI_GENERATE:
1828                 return NULL;
1829         }
1830
1831         ast_cli(a->fd, HSMCONN_FORMAT1, "Username", "IP Address", "Start", "Elapsed", "FileDes", "HttpCnt", "Read", "Write");
1832
1833         i = ao2_iterator_init(sessions, 0);
1834         while ((session = ao2_iterator_next(&i))) {
1835                 ao2_lock(session);
1836                 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);
1837                 count++;
1838                 ao2_unlock(session);
1839                 unref_mansession(session);
1840         }
1841         ao2_iterator_destroy(&i);
1842         ast_cli(a->fd, "%d users connected.\n", count);
1843
1844         return CLI_SUCCESS;
1845 }
1846
1847 /*! \brief CLI command manager list eventq */
1848 /* Should change to "manager show connected" */
1849 static char *handle_showmaneventq(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1850 {
1851         struct eventqent *s;
1852         switch (cmd) {
1853         case CLI_INIT:
1854                 e->command = "manager show eventq";
1855                 e->usage =
1856                         "Usage: manager show eventq\n"
1857                         "       Prints a listing of all events pending in the Asterisk manger\n"
1858                         "event queue.\n";
1859                 return NULL;
1860         case CLI_GENERATE:
1861                 return NULL;
1862         }
1863         AST_RWLIST_RDLOCK(&all_events);
1864         AST_RWLIST_TRAVERSE(&all_events, s, eq_next) {
1865                 ast_cli(a->fd, "Usecount: %d\n", s->usecount);
1866                 ast_cli(a->fd, "Category: %d\n", s->category);
1867                 ast_cli(a->fd, "Event:\n%s", s->eventdata);
1868         }
1869         AST_RWLIST_UNLOCK(&all_events);
1870
1871         return CLI_SUCCESS;
1872 }
1873
1874 /*! \brief CLI command manager reload */
1875 static char *handle_manager_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1876 {
1877         switch (cmd) {
1878         case CLI_INIT:
1879                 e->command = "manager reload";
1880                 e->usage =
1881                         "Usage: manager reload\n"
1882                         "       Reloads the manager configuration.\n";
1883                 return NULL;
1884         case CLI_GENERATE:
1885                 return NULL;
1886         }
1887         if (a->argc > 2) {
1888                 return CLI_SHOWUSAGE;
1889         }
1890         reload_manager();
1891         return CLI_SUCCESS;
1892 }
1893
1894 static struct eventqent *advance_event(struct eventqent *e)
1895 {
1896         struct eventqent *next;
1897
1898         AST_RWLIST_RDLOCK(&all_events);
1899         if ((next = AST_RWLIST_NEXT(e, eq_next))) {
1900                 ast_atomic_fetchadd_int(&next->usecount, 1);
1901                 ast_atomic_fetchadd_int(&e->usecount, -1);
1902         }
1903         AST_RWLIST_UNLOCK(&all_events);
1904         return next;
1905 }
1906
1907 #define GET_HEADER_FIRST_MATCH  0
1908 #define GET_HEADER_LAST_MATCH   1
1909 #define GET_HEADER_SKIP_EMPTY   2
1910
1911 /*!
1912  * \brief Return a matching header value.
1913  *
1914  * \details
1915  * Generic function to return either the first or the last
1916  * matching header from a list of variables, possibly skipping
1917  * empty strings.
1918  *
1919  * \note At the moment there is only one use of this function in
1920  * this file, so we make it static.
1921  *
1922  * \note Never returns NULL.
1923  */
1924 static const char *__astman_get_header(const struct message *m, char *var, int mode)
1925 {
1926         int x, l = strlen(var);
1927         const char *result = "";
1928
1929         for (x = 0; x < m->hdrcount; x++) {
1930                 const char *h = m->headers[x];
1931                 if (!strncasecmp(var, h, l) && h[l] == ':') {
1932                         const char *value = h + l + 1;
1933                         value = ast_skip_blanks(value); /* ignore leading spaces in the value */
1934                         /* found a potential candidate */
1935                         if ((mode & GET_HEADER_SKIP_EMPTY) && ast_strlen_zero(value)) {
1936                                 continue;       /* not interesting */
1937                         }
1938                         if (mode & GET_HEADER_LAST_MATCH) {
1939                                 result = value; /* record the last match so far */
1940                         } else {
1941                                 return value;
1942                         }
1943                 }
1944         }
1945
1946         return result;
1947 }
1948
1949 /*!
1950  * \brief Return the first matching variable from an array.
1951  *
1952  * \note This is the legacy function and is implemented in
1953  * therms of __astman_get_header().
1954  *
1955  * \note Never returns NULL.
1956  */
1957 const char *astman_get_header(const struct message *m, char *var)
1958 {
1959         return __astman_get_header(m, var, GET_HEADER_FIRST_MATCH);
1960 }
1961
1962 /*!
1963  * \internal
1964  * \brief Process one "Variable:" header value string.
1965  *
1966  * \param head Current list of AMI variables to get new values added.
1967  * \param hdr_val Header value string to process.
1968  *
1969  * \return New variable list head.
1970  */
1971 static struct ast_variable *man_do_variable_value(struct ast_variable *head, const char *hdr_val)
1972 {
1973         char *parse;
1974         AST_DECLARE_APP_ARGS(args,
1975                 AST_APP_ARG(vars)[64];
1976         );
1977
1978         hdr_val = ast_skip_blanks(hdr_val); /* ignore leading spaces in the value */
1979         parse = ast_strdupa(hdr_val);
1980
1981         /* Break the header value string into name=val pair items. */
1982         AST_STANDARD_APP_ARGS(args, parse);
1983         if (args.argc) {
1984                 int y;
1985
1986                 /* Process each name=val pair item. */
1987                 for (y = 0; y < args.argc; y++) {
1988                         struct ast_variable *cur;
1989                         char *var;
1990                         char *val;
1991
1992                         if (!args.vars[y]) {
1993                                 continue;
1994                         }
1995                         var = val = args.vars[y];
1996                         strsep(&val, "=");
1997
1998                         /* XXX We may wish to trim whitespace from the strings. */
1999                         if (!val || ast_strlen_zero(var)) {
2000                                 continue;
2001                         }
2002
2003                         /* Create new variable list node and prepend it to the list. */
2004                         cur = ast_variable_new(var, val, "");
2005                         if (cur) {
2006                                 cur->next = head;
2007                                 head = cur;
2008                         }
2009                 }
2010         }
2011
2012         return head;
2013 }
2014
2015 struct ast_variable *astman_get_variables(const struct message *m)
2016 {
2017         int varlen;
2018         int x;
2019         struct ast_variable *head = NULL;
2020
2021         static const char var_hdr[] = "Variable:";
2022
2023         /* Process all "Variable:" headers. */
2024         varlen = strlen(var_hdr);
2025         for (x = 0; x < m->hdrcount; x++) {
2026                 if (strncasecmp(var_hdr, m->headers[x], varlen)) {
2027                         continue;
2028                 }
2029                 head = man_do_variable_value(head, m->headers[x] + varlen);
2030         }
2031
2032         return head;
2033 }
2034
2035 /*! \brief access for hooks to send action messages to ami */
2036 int ast_hook_send_action(struct manager_custom_hook *hook, const char *msg)
2037 {
2038         const char *action;
2039         int ret = 0;
2040         struct manager_action *act_found;
2041         struct mansession s = {.session = NULL, };
2042         struct message m = { 0 };
2043         char *dup_str;
2044         char *src;
2045         int x = 0;
2046         int curlen;
2047
2048         if (hook == NULL) {
2049                 return -1;
2050         }
2051
2052         /* Create our own copy of the AMI action msg string. */
2053         src = dup_str = ast_strdup(msg);
2054         if (!dup_str) {
2055                 return -1;
2056         }
2057
2058         /* convert msg string to message struct */
2059         curlen = strlen(src);
2060         for (x = 0; x < curlen; x++) {
2061                 int cr; /* set if we have \r */
2062                 if (src[x] == '\r' && x+1 < curlen && src[x+1] == '\n')
2063                         cr = 2; /* Found. Update length to include \r\n */
2064                 else if (src[x] == '\n')
2065                         cr = 1; /* also accept \n only */
2066                 else
2067                         continue;
2068                 /* don't keep empty lines */
2069                 if (x && m.hdrcount < ARRAY_LEN(m.headers)) {
2070                         /* ... but trim \r\n and terminate the header string */
2071                         src[x] = '\0';
2072                         m.headers[m.hdrcount++] = src;
2073                 }
2074                 x += cr;
2075                 curlen -= x;            /* remaining size */
2076                 src += x;               /* update pointer */
2077                 x = -1;                 /* reset loop */
2078         }
2079
2080         action = astman_get_header(&m, "Action");
2081         if (strcasecmp(action, "login")) {
2082                 act_found = action_find(action);
2083                 if (act_found) {
2084                         /*
2085                          * we have to simulate a session for this action request
2086                          * to be able to pass it down for processing
2087                          * This is necessary to meet the previous design of manager.c
2088                          */
2089                         s.hook = hook;
2090                         s.f = (void*)1; /* set this to something so our request will make it through all functions that test it*/
2091
2092                         ao2_lock(act_found);
2093                         if (act_found->registered && act_found->func) {
2094                                 if (act_found->module) {
2095                                         ast_module_ref(act_found->module);
2096                                 }
2097                                 ao2_unlock(act_found);
2098                                 ret = act_found->func(&s, &m);
2099                                 ao2_lock(act_found);
2100                                 if (act_found->module) {
2101                                         ast_module_unref(act_found->module);
2102                                 }
2103                         } else {
2104                                 ret = -1;
2105                         }
2106                         ao2_unlock(act_found);
2107                         ao2_t_ref(act_found, -1, "done with found action object");
2108                 }
2109         }
2110         ast_free(dup_str);
2111         return ret;
2112 }
2113
2114
2115 /*!
2116  * helper function to send a string to the socket.
2117  * Return -1 on error (e.g. buffer full).
2118  */
2119 static int send_string(struct mansession *s, char *string)
2120 {
2121         int res;
2122         FILE *f = s->f ? s->f : s->session->f;
2123         int fd = s->f ? s->fd : s->session->fd;
2124
2125         /* It's a result from one of the hook's action invocation */
2126         if (s->hook) {
2127                 /*
2128                  * to send responses, we're using the same function
2129                  * as for receiving events. We call the event "HookResponse"
2130                  */
2131                 s->hook->helper(EVENT_FLAG_HOOKRESPONSE, "HookResponse", string);
2132                 return 0;
2133         }
2134
2135         if ((res = ast_careful_fwrite(f, fd, string, strlen(string), s->session->writetimeout))) {
2136                 s->write_error = 1;
2137         }
2138
2139         return res;
2140 }
2141
2142 /*!
2143  * \brief thread local buffer for astman_append
2144  *
2145  * \note This can not be defined within the astman_append() function
2146  *       because it declares a couple of functions that get used to
2147  *       initialize the thread local storage key.
2148  */
2149 AST_THREADSTORAGE(astman_append_buf);
2150
2151 AST_THREADSTORAGE(userevent_buf);
2152
2153 /*! \brief initial allocated size for the astman_append_buf and astman_send_*_va */
2154 #define ASTMAN_APPEND_BUF_INITSIZE   256
2155
2156 /*!
2157  * utility functions for creating AMI replies
2158  */
2159 void astman_append(struct mansession *s, const char *fmt, ...)
2160 {
2161         va_list ap;
2162         struct ast_str *buf;
2163
2164         if (!(buf = ast_str_thread_get(&astman_append_buf, ASTMAN_APPEND_BUF_INITSIZE))) {
2165                 return;
2166         }
2167
2168         va_start(ap, fmt);
2169         ast_str_set_va(&buf, 0, fmt, ap);
2170         va_end(ap);
2171
2172         if (s->f != NULL || s->session->f != NULL) {
2173                 send_string(s, ast_str_buffer(buf));
2174         } else {
2175                 ast_verbose("fd == -1 in astman_append, should not happen\n");
2176         }
2177 }
2178
2179 /*! \note NOTE: XXX this comment is unclear and possibly wrong.
2180    Callers of astman_send_error(), astman_send_response() or astman_send_ack() must EITHER
2181    hold the session lock _or_ be running in an action callback (in which case s->session->busy will
2182    be non-zero). In either of these cases, there is no need to lock-protect the session's
2183    fd, since no other output will be sent (events will be queued), and no input will
2184    be read until either the current action finishes or get_input() obtains the session
2185    lock.
2186  */
2187
2188 /*! \todo XXX MSG_MOREDATA should go to a header file. */
2189 #define MSG_MOREDATA    ((char *)astman_send_response)
2190
2191 /*! \brief send a response with an optional message,
2192  * and terminate it with an empty line.
2193  * m is used only to grab the 'ActionID' field.
2194  *
2195  * Use the explicit constant MSG_MOREDATA to remove the empty line.
2196  * XXX MSG_MOREDATA should go to a header file.
2197  */
2198 static void astman_send_response_full(struct mansession *s, const struct message *m, char *resp, char *msg, char *listflag)
2199 {
2200         const char *id = astman_get_header(m, "ActionID");
2201
2202         astman_append(s, "Response: %s\r\n", resp);
2203         if (!ast_strlen_zero(id)) {
2204                 astman_append(s, "ActionID: %s\r\n", id);
2205         }
2206         if (listflag) {
2207                 astman_append(s, "EventList: %s\r\n", listflag);        /* Start, complete, cancelled */
2208         }
2209         if (msg == MSG_MOREDATA) {
2210                 return;
2211         } else if (msg) {
2212                 astman_append(s, "Message: %s\r\n\r\n", msg);
2213         } else {
2214                 astman_append(s, "\r\n");
2215         }
2216 }
2217
2218 void astman_send_response(struct mansession *s, const struct message *m, char *resp, char *msg)
2219 {
2220         astman_send_response_full(s, m, resp, msg, NULL);
2221 }
2222
2223 void astman_send_error(struct mansession *s, const struct message *m, char *error)
2224 {
2225         astman_send_response_full(s, m, "Error", error, NULL);
2226 }
2227
2228 void astman_send_error_va(struct mansession *s, const struct message *m, const char *fmt, ...)
2229 {
2230         va_list ap;
2231         struct ast_str *buf;
2232
2233         if (!(buf = ast_str_thread_get(&astman_append_buf, ASTMAN_APPEND_BUF_INITSIZE))) {
2234                 return;
2235         }
2236
2237         va_start(ap, fmt);
2238         ast_str_set_va(&buf, 0, fmt, ap);
2239         va_end(ap);
2240
2241         astman_send_response_full(s, m, "Error", ast_str_buffer(buf), NULL);
2242         ast_free(buf);
2243 }
2244
2245 void astman_send_ack(struct mansession *s, const struct message *m, char *msg)
2246 {
2247         astman_send_response_full(s, m, "Success", msg, NULL);
2248 }
2249
2250 static void astman_start_ack(struct mansession *s, const struct message *m)
2251 {
2252         astman_send_response_full(s, m, "Success", MSG_MOREDATA, NULL);
2253 }
2254
2255 void astman_send_listack(struct mansession *s, const struct message *m, char *msg, char *listflag)
2256 {
2257         astman_send_response_full(s, m, "Success", msg, listflag);
2258 }
2259
2260 /*! \brief Lock the 'mansession' structure. */
2261 static void mansession_lock(struct mansession *s)
2262 {
2263         ast_mutex_lock(&s->lock);
2264 }
2265
2266 /*! \brief Unlock the 'mansession' structure. */
2267 static void mansession_unlock(struct mansession *s)
2268 {
2269         ast_mutex_unlock(&s->lock);
2270 }
2271
2272 /*! \brief
2273    Rather than braindead on,off this now can also accept a specific int mask value
2274    or a ',' delim list of mask strings (the same as manager.conf) -anthm
2275 */
2276 static int set_eventmask(struct mansession *s, const char *eventmask)
2277 {
2278         int maskint = strings_to_mask(eventmask);
2279
2280         ao2_lock(s->session);
2281         if (maskint >= 0) {
2282                 s->session->send_events = maskint;
2283         }
2284         ao2_unlock(s->session);
2285
2286         return maskint;
2287 }
2288
2289 static enum ast_security_event_transport_type mansession_get_transport(const struct mansession *s)
2290 {
2291         return s->tcptls_session->parent->tls_cfg ? AST_SECURITY_EVENT_TRANSPORT_TLS :
2292                         AST_SECURITY_EVENT_TRANSPORT_TCP;
2293 }
2294
2295 static void report_invalid_user(const struct mansession *s, const char *username)
2296 {
2297         char session_id[32];
2298         struct ast_security_event_inval_acct_id inval_acct_id = {
2299                 .common.event_type = AST_SECURITY_EVENT_INVAL_ACCT_ID,
2300                 .common.version    = AST_SECURITY_EVENT_INVAL_ACCT_ID_VERSION,
2301                 .common.service    = "AMI",
2302                 .common.account_id = username,
2303                 .common.session_tv = &s->session->sessionstart_tv,
2304                 .common.local_addr = {
2305                         .addr      = &s->tcptls_session->parent->local_address,
2306                         .transport = mansession_get_transport(s),
2307                 },
2308                 .common.remote_addr = {
2309                         .addr      = &s->session->addr,
2310                         .transport = mansession_get_transport(s),
2311                 },
2312                 .common.session_id = session_id,
2313         };
2314
2315         snprintf(session_id, sizeof(session_id), "%p", s);
2316
2317         ast_security_event_report(AST_SEC_EVT(&inval_acct_id));
2318 }
2319
2320 static void report_failed_acl(const struct mansession *s, const char *username)
2321 {
2322         char session_id[32];
2323         struct ast_security_event_failed_acl failed_acl_event = {
2324                 .common.event_type = AST_SECURITY_EVENT_FAILED_ACL,
2325                 .common.version    = AST_SECURITY_EVENT_FAILED_ACL_VERSION,
2326                 .common.service    = "AMI",
2327                 .common.account_id = username,
2328                 .common.session_tv = &s->session->sessionstart_tv,
2329                 .common.local_addr = {
2330                         .addr      = &s->tcptls_session->parent->local_address,
2331                         .transport = mansession_get_transport(s),
2332                 },
2333                 .common.remote_addr = {
2334                         .addr      = &s->session->addr,
2335                         .transport = mansession_get_transport(s),
2336                 },
2337                 .common.session_id = session_id,
2338         };
2339
2340         snprintf(session_id, sizeof(session_id), "%p", s->session);
2341
2342         ast_security_event_report(AST_SEC_EVT(&failed_acl_event));
2343 }
2344
2345 static void report_inval_password(const struct mansession *s, const char *username)
2346 {
2347         char session_id[32];
2348         struct ast_security_event_inval_password inval_password = {
2349                 .common.event_type = AST_SECURITY_EVENT_INVAL_PASSWORD,
2350                 .common.version    = AST_SECURITY_EVENT_INVAL_PASSWORD_VERSION,
2351                 .common.service    = "AMI",
2352                 .common.account_id = username,
2353                 .common.session_tv = &s->session->sessionstart_tv,
2354                 .common.local_addr = {
2355                         .addr      = &s->tcptls_session->parent->local_address,
2356                         .transport = mansession_get_transport(s),
2357                 },
2358                 .common.remote_addr = {
2359                         .addr      = &s->session->addr,
2360                         .transport = mansession_get_transport(s),
2361                 },
2362                 .common.session_id = session_id,
2363         };
2364
2365         snprintf(session_id, sizeof(session_id), "%p", s->session);
2366
2367         ast_security_event_report(AST_SEC_EVT(&inval_password));
2368 }
2369
2370 static void report_auth_success(const struct mansession *s)
2371 {
2372         char session_id[32];
2373         struct ast_security_event_successful_auth successful_auth = {
2374                 .common.event_type = AST_SECURITY_EVENT_SUCCESSFUL_AUTH,
2375                 .common.version    = AST_SECURITY_EVENT_SUCCESSFUL_AUTH_VERSION,
2376                 .common.service    = "AMI",
2377                 .common.account_id = s->session->username,
2378                 .common.session_tv = &s->session->sessionstart_tv,
2379                 .common.local_addr = {
2380                         .addr      = &s->tcptls_session->parent->local_address,
2381                         .transport = mansession_get_transport(s),
2382                 },
2383                 .common.remote_addr = {
2384                         .addr      = &s->session->addr,
2385                         .transport = mansession_get_transport(s),
2386                 },
2387                 .common.session_id = session_id,
2388         };
2389
2390         snprintf(session_id, sizeof(session_id), "%p", s->session);
2391
2392         ast_security_event_report(AST_SEC_EVT(&successful_auth));
2393 }
2394
2395 static void report_req_not_allowed(const struct mansession *s, const char *action)
2396 {
2397         char session_id[32];
2398         char request_type[64];
2399         struct ast_security_event_req_not_allowed req_not_allowed = {
2400                 .common.event_type = AST_SECURITY_EVENT_REQ_NOT_ALLOWED,
2401                 .common.version    = AST_SECURITY_EVENT_REQ_NOT_ALLOWED_VERSION,
2402                 .common.service    = "AMI",
2403                 .common.account_id = s->session->username,
2404                 .common.session_tv = &s->session->sessionstart_tv,
2405                 .common.local_addr = {
2406                         .addr      = &s->tcptls_session->parent->local_address,
2407                         .transport = mansession_get_transport(s),
2408                 },
2409                 .common.remote_addr = {
2410                         .addr      = &s->session->addr,
2411                         .transport = mansession_get_transport(s),
2412                 },
2413                 .common.session_id = session_id,
2414
2415                 .request_type      = request_type,
2416         };
2417
2418         snprintf(session_id, sizeof(session_id), "%p", s->session);
2419         snprintf(request_type, sizeof(request_type), "Action: %s", action);
2420
2421         ast_security_event_report(AST_SEC_EVT(&req_not_allowed));
2422 }
2423
2424 static void report_req_bad_format(const struct mansession *s, const char *action)
2425 {
2426         char session_id[32];
2427         char request_type[64];
2428         struct ast_security_event_req_bad_format req_bad_format = {
2429                 .common.event_type = AST_SECURITY_EVENT_REQ_BAD_FORMAT,
2430                 .common.version    = AST_SECURITY_EVENT_REQ_BAD_FORMAT_VERSION,
2431                 .common.service    = "AMI",
2432                 .common.account_id = s->session->username,
2433                 .common.session_tv = &s->session->sessionstart_tv,
2434                 .common.local_addr = {
2435                         .addr      = &s->tcptls_session->parent->local_address,
2436                         .transport = mansession_get_transport(s),
2437                 },
2438                 .common.remote_addr = {
2439                         .addr      = &s->session->addr,
2440                         .transport = mansession_get_transport(s),
2441                 },
2442                 .common.session_id = session_id,
2443
2444                 .request_type      = request_type,
2445         };
2446
2447         snprintf(session_id, sizeof(session_id), "%p", s->session);
2448         snprintf(request_type, sizeof(request_type), "Action: %s", action);
2449
2450         ast_security_event_report(AST_SEC_EVT(&req_bad_format));
2451 }
2452
2453 static void report_failed_challenge_response(const struct mansession *s,
2454                 const char *response, const char *expected_response)
2455 {
2456         char session_id[32];
2457         struct ast_security_event_chal_resp_failed chal_resp_failed = {
2458                 .common.event_type = AST_SECURITY_EVENT_CHAL_RESP_FAILED,
2459                 .common.version    = AST_SECURITY_EVENT_CHAL_RESP_FAILED_VERSION,
2460                 .common.service    = "AMI",
2461                 .common.account_id = s->session->username,
2462                 .common.session_tv = &s->session->sessionstart_tv,
2463                 .common.local_addr = {
2464                         .addr      = &s->tcptls_session->parent->local_address,
2465                         .transport = mansession_get_transport(s),
2466                 },
2467                 .common.remote_addr = {
2468                         .addr      = &s->session->addr,
2469                         .transport = mansession_get_transport(s),
2470                 },
2471                 .common.session_id = session_id,
2472
2473                 .challenge         = s->session->challenge,
2474                 .response          = response,
2475                 .expected_response = expected_response,
2476         };
2477
2478         snprintf(session_id, sizeof(session_id), "%p", s->session);
2479
2480         ast_security_event_report(AST_SEC_EVT(&chal_resp_failed));
2481 }
2482
2483 static void report_session_limit(const struct mansession *s)
2484 {
2485         char session_id[32];
2486         struct ast_security_event_session_limit session_limit = {
2487                 .common.event_type = AST_SECURITY_EVENT_SESSION_LIMIT,
2488                 .common.version    = AST_SECURITY_EVENT_SESSION_LIMIT_VERSION,
2489                 .common.service    = "AMI",
2490                 .common.account_id = s->session->username,
2491                 .common.session_tv = &s->session->sessionstart_tv,
2492                 .common.local_addr = {
2493                         .addr      = &s->tcptls_session->parent->local_address,
2494                         .transport = mansession_get_transport(s),
2495                 },
2496                 .common.remote_addr = {
2497                         .addr      = &s->session->addr,
2498                         .transport = mansession_get_transport(s),
2499                 },
2500                 .common.session_id = session_id,
2501         };
2502
2503         snprintf(session_id, sizeof(session_id), "%p", s->session);
2504
2505         ast_security_event_report(AST_SEC_EVT(&session_limit));
2506 }
2507
2508 /*
2509  * Here we start with action_ handlers for AMI actions,
2510  * and the internal functions used by them.
2511  * Generally, the handlers are called action_foo()
2512  */
2513
2514 /* helper function for action_login() */
2515 static int authenticate(struct mansession *s, const struct message *m)
2516 {
2517         const char *username = astman_get_header(m, "Username");
2518         const char *password = astman_get_header(m, "Secret");
2519         int error = -1;
2520         struct ast_manager_user *user = NULL;
2521         regex_t *regex_filter;
2522         struct ao2_iterator filter_iter;
2523
2524         if (ast_strlen_zero(username)) {        /* missing username */
2525                 return -1;
2526         }
2527
2528         /* locate user in locked state */
2529         AST_RWLIST_WRLOCK(&users);
2530
2531         if (!(user = get_manager_by_name_locked(username))) {
2532                 report_invalid_user(s, username);
2533                 ast_log(LOG_NOTICE, "%s tried to authenticate with nonexistent user '%s'\n", ast_sockaddr_stringify_addr(&s->session->addr), username);
2534         } else if (user->acl && (ast_apply_acl(user->acl, &s->session->addr, "Manager User ACL: ") == AST_SENSE_DENY)) {
2535                 report_failed_acl(s, username);
2536                 ast_log(LOG_NOTICE, "%s failed to pass IP ACL as '%s'\n", ast_sockaddr_stringify_addr(&s->session->addr), username);
2537         } else if (!strcasecmp(astman_get_header(m, "AuthType"), "MD5")) {
2538                 const char *key = astman_get_header(m, "Key");
2539                 if (!ast_strlen_zero(key) && !ast_strlen_zero(s->session->challenge) && user->secret) {
2540                         int x;
2541                         int len = 0;
2542                         char md5key[256] = "";
2543                         struct MD5Context md5;
2544                         unsigned char digest[16];
2545
2546                         MD5Init(&md5);
2547                         MD5Update(&md5, (unsigned char *) s->session->challenge, strlen(s->session->challenge));
2548                         MD5Update(&md5, (unsigned char *) user->secret, strlen(user->secret));
2549                         MD5Final(digest, &md5);
2550                         for (x = 0; x < 16; x++)
2551                                 len += sprintf(md5key + len, "%2.2x", digest[x]);
2552                         if (!strcmp(md5key, key)) {
2553                                 error = 0;
2554                         } else {
2555                                 report_failed_challenge_response(s, key, md5key);
2556                         }
2557                 } else {
2558                         ast_debug(1, "MD5 authentication is not possible.  challenge: '%s'\n",
2559                                 S_OR(s->session->challenge, ""));
2560                 }
2561         } else if (user->secret) {
2562                 if (!strcmp(password, user->secret)) {
2563                         error = 0;
2564                 } else {
2565                         report_inval_password(s, username);
2566                 }
2567         }
2568
2569         if (error) {
2570                 ast_log(LOG_NOTICE, "%s failed to authenticate as '%s'\n", ast_sockaddr_stringify_addr(&s->session->addr), username);
2571                 AST_RWLIST_UNLOCK(&users);
2572                 return -1;
2573         }
2574
2575         /* auth complete */
2576
2577         /* All of the user parameters are copied to the session so that in the event
2578         * of a reload and a configuration change, the session parameters are not
2579         * changed. */
2580         ast_copy_string(s->session->username, username, sizeof(s->session->username));
2581         s->session->readperm = user->readperm;
2582         s->session->writeperm = user->writeperm;
2583         s->session->writetimeout = user->writetimeout;
2584         if (user->chanvars) {
2585                 s->session->chanvars = ast_variables_dup(user->chanvars);
2586         }
2587
2588         filter_iter = ao2_iterator_init(user->whitefilters, 0);
2589         while ((regex_filter = ao2_iterator_next(&filter_iter))) {
2590                 ao2_t_link(s->session->whitefilters, regex_filter, "add white user filter to session");
2591                 ao2_t_ref(regex_filter, -1, "remove iterator ref");
2592         }
2593         ao2_iterator_destroy(&filter_iter);
2594
2595         filter_iter = ao2_iterator_init(user->blackfilters, 0);
2596         while ((regex_filter = ao2_iterator_next(&filter_iter))) {
2597                 ao2_t_link(s->session->blackfilters, regex_filter, "add black user filter to session");
2598                 ao2_t_ref(regex_filter, -1, "remove iterator ref");
2599         }
2600         ao2_iterator_destroy(&filter_iter);
2601
2602         s->session->sessionstart = time(NULL);
2603         s->session->sessionstart_tv = ast_tvnow();
2604         set_eventmask(s, astman_get_header(m, "Events"));
2605
2606         report_auth_success(s);
2607
2608         AST_RWLIST_UNLOCK(&users);
2609         return 0;
2610 }
2611
2612 static int action_ping(struct mansession *s, const struct message *m)
2613 {
2614         const char *actionid = astman_get_header(m, "ActionID");
2615         struct timeval now = ast_tvnow();
2616
2617         astman_append(s, "Response: Success\r\n");
2618         if (!ast_strlen_zero(actionid)){
2619                 astman_append(s, "ActionID: %s\r\n", actionid);
2620         }
2621         astman_append(
2622                 s,
2623                 "Ping: Pong\r\n"
2624                 "Timestamp: %ld.%06lu\r\n"
2625                 "\r\n",
2626                 (long) now.tv_sec, (unsigned long) now.tv_usec);
2627         return 0;
2628 }
2629
2630 static int action_getconfig(struct mansession *s, const struct message *m)
2631 {
2632         struct ast_config *cfg;
2633         const char *fn = astman_get_header(m, "Filename");
2634         const char *category = astman_get_header(m, "Category");
2635         int catcount = 0;
2636         int lineno = 0;
2637         char *cur_category = NULL;
2638         struct ast_variable *v;
2639         struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
2640
2641         if (ast_strlen_zero(fn)) {
2642                 astman_send_error(s, m, "Filename not specified");
2643                 return 0;
2644         }
2645         cfg = ast_config_load2(fn, "manager", config_flags);
2646         if (cfg == CONFIG_STATUS_FILEMISSING) {
2647                 astman_send_error(s, m, "Config file not found");
2648                 return 0;
2649         } else if (cfg == CONFIG_STATUS_FILEINVALID) {
2650                 astman_send_error(s, m, "Config file has invalid format");
2651                 return 0;
2652         }
2653
2654         astman_start_ack(s, m);
2655         while ((cur_category = ast_category_browse(cfg, cur_category))) {
2656                 if (ast_strlen_zero(category) || (!ast_strlen_zero(category) && !strcmp(category, cur_category))) {
2657                         lineno = 0;
2658                         astman_append(s, "Category-%06d: %s\r\n", catcount, cur_category);
2659                         for (v = ast_variable_browse(cfg, cur_category); v; v = v->next) {
2660                                 astman_append(s, "Line-%06d-%06d: %s=%s\r\n", catcount, lineno++, v->name, v->value);
2661                         }
2662                         catcount++;
2663                 }
2664         }
2665         if (!ast_strlen_zero(category) && catcount == 0) { /* TODO: actually, a config with no categories doesn't even get loaded */
2666                 astman_append(s, "No categories found\r\n");
2667         }
2668         ast_config_destroy(cfg);
2669         astman_append(s, "\r\n");
2670
2671         return 0;
2672 }
2673
2674 static int action_listcategories(struct mansession *s, const struct message *m)
2675 {
2676         struct ast_config *cfg;
2677         const char *fn = astman_get_header(m, "Filename");
2678         char *category = NULL;
2679         struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
2680         int catcount = 0;
2681
2682         if (ast_strlen_zero(fn)) {
2683                 astman_send_error(s, m, "Filename not specified");
2684                 return 0;
2685         }
2686         if (!(cfg = ast_config_load2(fn, "manager", config_flags))) {
2687                 astman_send_error(s, m, "Config file not found");
2688                 return 0;
2689         } else if (cfg == CONFIG_STATUS_FILEINVALID) {
2690                 astman_send_error(s, m, "Config file has invalid format");
2691                 return 0;
2692         }
2693         astman_start_ack(s, m);
2694         while ((category = ast_category_browse(cfg, category))) {
2695                 astman_append(s, "Category-%06d: %s\r\n", catcount, category);
2696                 catcount++;
2697         }
2698         if (catcount == 0) { /* TODO: actually, a config with no categories doesn't even get loaded */
2699                 astman_append(s, "Error: no categories found\r\n");
2700         }
2701         ast_config_destroy(cfg);
2702         astman_append(s, "\r\n");
2703
2704         return 0;
2705 }
2706
2707
2708
2709
2710 /*! The amount of space in out must be at least ( 2 * strlen(in) + 1 ) */
2711 static void json_escape(char *out, const char *in)
2712 {
2713         for (; *in; in++) {
2714                 if (*in == '\\' || *in == '\"') {
2715                         *out++ = '\\';
2716                 }
2717                 *out++ = *in;
2718         }
2719         *out = '\0';
2720 }
2721
2722 /*!
2723  * \internal
2724  * \brief Append a JSON escaped string to the manager stream.
2725  *
2726  * \param s AMI stream to append a string.
2727  * \param str String to append to the stream after JSON escaping it.
2728  *
2729  * \return Nothing
2730  */
2731 static void astman_append_json(struct mansession *s, const char *str)
2732 {
2733         char *buf;
2734
2735         buf = ast_alloca(2 * strlen(str) + 1);
2736         json_escape(buf, str);
2737         astman_append(s, "%s", buf);
2738 }
2739
2740 static int action_getconfigjson(struct mansession *s, const struct message *m)
2741 {
2742         struct ast_config *cfg;
2743         const char *fn = astman_get_header(m, "Filename");
2744         char *category = NULL;
2745         struct ast_variable *v;
2746         int comma1 = 0;
2747         struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
2748
2749         if (ast_strlen_zero(fn)) {
2750                 astman_send_error(s, m, "Filename not specified");
2751                 return 0;
2752         }
2753
2754         if (!(cfg = ast_config_load2(fn, "manager", config_flags))) {
2755                 astman_send_error(s, m, "Config file not found");
2756                 return 0;
2757         } else if (cfg == CONFIG_STATUS_FILEINVALID) {
2758                 astman_send_error(s, m, "Config file has invalid format");
2759                 return 0;
2760         }
2761
2762         astman_start_ack(s, m);
2763         astman_append(s, "JSON: {");
2764         while ((category = ast_category_browse(cfg, category))) {
2765                 int comma2 = 0;
2766
2767                 astman_append(s, "%s\"", comma1 ? "," : "");
2768                 astman_append_json(s, category);
2769                 astman_append(s, "\":[");
2770                 comma1 = 1;
2771                 for (v = ast_variable_browse(cfg, category); v; v = v->next) {
2772                         astman_append(s, "%s\"", comma2 ? "," : "");
2773                         astman_append_json(s, v->name);
2774                         astman_append(s, "\":\"");
2775                         astman_append_json(s, v->value);
2776                         astman_append(s, "\"");
2777                         comma2 = 1;
2778                 }
2779                 astman_append(s, "]");
2780         }
2781         astman_append(s, "}\r\n\r\n");
2782
2783         ast_config_destroy(cfg);
2784
2785         return 0;
2786 }
2787
2788 /*! \brief helper function for action_updateconfig */
2789 static enum error_type handle_updates(struct mansession *s, const struct message *m, struct ast_config *cfg, const char *dfn)
2790 {
2791         int x;
2792         char hdr[40];
2793         const char *action, *cat, *var, *value, *match, *line;
2794         struct ast_category *category;
2795         struct ast_variable *v;
2796         struct ast_str *str1 = ast_str_create(16), *str2 = ast_str_create(16);
2797         enum error_type result = 0;
2798
2799         for (x = 0; x < 100000; x++) {  /* 100000 = the max number of allowed updates + 1 */
2800                 unsigned int object = 0;
2801
2802                 snprintf(hdr, sizeof(hdr), "Action-%06d", x);
2803                 action = astman_get_header(m, hdr);
2804                 if (ast_strlen_zero(action))            /* breaks the for loop if no action header */
2805                         break;                          /* this could cause problems if actions come in misnumbered */
2806
2807                 snprintf(hdr, sizeof(hdr), "Cat-%06d", x);
2808                 cat = astman_get_header(m, hdr);
2809                 if (ast_strlen_zero(cat)) {             /* every action needs a category */
2810                         result =  UNSPECIFIED_CATEGORY;
2811                         break;
2812                 }
2813
2814                 snprintf(hdr, sizeof(hdr), "Var-%06d", x);
2815                 var = astman_get_header(m, hdr);
2816
2817                 snprintf(hdr, sizeof(hdr), "Value-%06d", x);
2818                 value = astman_get_header(m, hdr);
2819
2820                 if (!ast_strlen_zero(value) && *value == '>') {
2821                         object = 1;
2822                         value++;
2823                 }
2824
2825                 snprintf(hdr, sizeof(hdr), "Match-%06d", x);
2826                 match = astman_get_header(m, hdr);
2827
2828                 snprintf(hdr, sizeof(hdr), "Line-%06d", x);
2829                 line = astman_get_header(m, hdr);
2830
2831                 if (!strcasecmp(action, "newcat")) {
2832                         if (ast_category_get(cfg,cat)) {        /* check to make sure the cat doesn't */
2833                                 result = FAILURE_NEWCAT;        /* already exist */
2834                                 break;
2835                         }
2836                         if (!(category = ast_category_new(cat, dfn, -1))) {
2837                                 result = FAILURE_ALLOCATION;
2838                                 break;
2839                         }
2840                         if (ast_strlen_zero(match)) {
2841                                 ast_category_append(cfg, category);
2842                         } else {
2843                                 ast_category_insert(cfg, category, match);
2844                         }
2845                 } else if (!strcasecmp(action, "renamecat")) {
2846                         if (ast_strlen_zero(value)) {
2847                                 result = UNSPECIFIED_ARGUMENT;
2848                                 break;
2849                         }
2850                         if (!(category = ast_category_get(cfg, cat))) {
2851                                 result = UNKNOWN_CATEGORY;
2852                                 break;
2853                         }
2854                         ast_category_rename(category, value);
2855                 } else if (!strcasecmp(action, "delcat")) {
2856                         if (ast_category_delete(cfg, cat)) {
2857                                 result = FAILURE_DELCAT;
2858                                 break;
2859                         }
2860                 } else if (!strcasecmp(action, "emptycat")) {
2861                         if (ast_category_empty(cfg, cat)) {
2862                                 result = FAILURE_EMPTYCAT;
2863                                 break;
2864                         }
2865                 } else if (!strcasecmp(action, "update")) {
2866                         if (ast_strlen_zero(var)) {
2867                                 result = UNSPECIFIED_ARGUMENT;
2868                                 break;
2869                         }
2870                         if (!(category = ast_category_get(cfg,cat))) {
2871                                 result = UNKNOWN_CATEGORY;
2872                                 break;
2873                         }
2874                         if (ast_variable_update(category, var, value, match, object)) {
2875                                 result = FAILURE_UPDATE;
2876                                 break;
2877                         }
2878                 } else if (!strcasecmp(action, "delete")) {
2879                         if ((ast_strlen_zero(var) && ast_strlen_zero(line))) {
2880                                 result = UNSPECIFIED_ARGUMENT;
2881                                 break;
2882                         }
2883                         if (!(category = ast_category_get(cfg, cat))) {
2884                                 result = UNKNOWN_CATEGORY;
2885                                 break;
2886                         }
2887                         if (ast_variable_delete(category, var, match, line)) {
2888                                 result = FAILURE_DELETE;
2889                                 break;
2890                         }
2891                 } else if (!strcasecmp(action, "append")) {
2892                         if (ast_strlen_zero(var)) {
2893                                 result = UNSPECIFIED_ARGUMENT;
2894                                 break;
2895                         }
2896                         if (!(category = ast_category_get(cfg, cat))) {
2897                                 result = UNKNOWN_CATEGORY;
2898                                 break;
2899                         }
2900                         if (!(v = ast_variable_new(var, value, dfn))) {
2901                                 result = FAILURE_ALLOCATION;
2902                                 break;
2903                         }
2904                         if (object || (match && !strcasecmp(match, "object"))) {
2905                                 v->object = 1;
2906                         }
2907                         ast_variable_append(category, v);
2908                 } else if (!strcasecmp(action, "insert")) {
2909                         if (ast_strlen_zero(var) || ast_strlen_zero(line)) {
2910                                 result = UNSPECIFIED_ARGUMENT;
2911                                 break;
2912                         }
2913                         if (!(category = ast_category_get(cfg, cat))) {
2914                                 result = UNKNOWN_CATEGORY;
2915                                 break;
2916                         }
2917                         if (!(v = ast_variable_new(var, value, dfn))) {
2918                                 result = FAILURE_ALLOCATION;
2919                                 break;
2920                         }
2921                         ast_variable_insert(category, v, line);
2922                 }
2923                 else {
2924                         ast_log(LOG_WARNING, "Action-%06d: %s not handled\n", x, action);
2925                         result = UNKNOWN_ACTION;
2926                         break;
2927                 }
2928         }
2929         ast_free(str1);
2930         ast_free(str2);
2931         return result;
2932 }
2933
2934 static int action_updateconfig(struct mansession *s, const struct message *m)
2935 {
2936         struct ast_config *cfg;
2937         const char *sfn = astman_get_header(m, "SrcFilename");
2938         const char *dfn = astman_get_header(m, "DstFilename");
2939         int res;
2940         const char *rld = astman_get_header(m, "Reload");
2941         struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
2942         enum error_type result;
2943
2944         if (ast_strlen_zero(sfn) || ast_strlen_zero(dfn)) {
2945                 astman_send_error(s, m, "Filename not specified");
2946                 return 0;
2947         }
2948         if (!(cfg = ast_config_load2(sfn, "manager", config_flags))) {
2949                 astman_send_error(s, m, "Config file not found");
2950                 return 0;
2951         } else if (cfg == CONFIG_STATUS_FILEINVALID) {
2952                 astman_send_error(s, m, "Config file has invalid format");
2953                 return 0;
2954         }
2955         result = handle_updates(s, m, cfg, dfn);
2956         if (!result) {
2957                 ast_include_rename(cfg, sfn, dfn); /* change the include references from dfn to sfn, so things match up */
2958                 res = ast_config_text_file_save(dfn, cfg, "Manager");
2959                 ast_config_destroy(cfg);
2960                 if (res) {
2961                         astman_send_error(s, m, "Save of config failed");
2962                         return 0;
2963                 }
2964                 astman_send_ack(s, m, NULL);
2965                 if (!ast_strlen_zero(rld)) {
2966                         if (ast_true(rld)) {
2967                                 rld = NULL;
2968                         }
2969                         ast_module_reload(rld);
2970                 }
2971         } else {
2972                 ast_config_destroy(cfg);
2973                 switch(result) {
2974                 case UNKNOWN_ACTION:
2975                         astman_send_error(s, m, "Unknown action command");
2976                         break;
2977                 case UNKNOWN_CATEGORY:
2978                         astman_send_error(s, m, "Given category does not exist");
2979                         break;
2980                 case UNSPECIFIED_CATEGORY:
2981                         astman_send_error(s, m, "Category not specified");
2982                         break;
2983                 case UNSPECIFIED_ARGUMENT:
2984                         astman_send_error(s, m, "Problem with category, value, or line (if required)");
2985                         break;
2986                 case FAILURE_ALLOCATION:
2987                         astman_send_error(s, m, "Memory allocation failure, this should not happen");
2988                         break;
2989                 case FAILURE_NEWCAT:
2990                         astman_send_error(s, m, "Create category did not complete successfully");
2991                         break;
2992                 case FAILURE_DELCAT:
2993                         astman_send_error(s, m, "Delete category did not complete successfully");
2994                         break;
2995                 case FAILURE_EMPTYCAT:
2996                         astman_send_error(s, m, "Empty category did not complete successfully");
2997                         break;
2998                 case FAILURE_UPDATE:
2999                         astman_send_error(s, m, "Update did not complete successfully");
3000                         break;
3001                 case FAILURE_DELETE:
3002                         astman_send_error(s, m, "Delete did not complete successfully");
3003                         break;
3004                 case FAILURE_APPEND:
3005                         astman_send_error(s, m, "Append did not complete successfully");
3006                         break;
3007                 }
3008         }
3009         return 0;
3010 }
3011
3012 static int action_createconfig(struct mansession *s, const struct message *m)
3013 {
3014         int fd;
3015         const char *fn = astman_get_header(m, "Filename");
3016         struct ast_str *filepath = ast_str_alloca(PATH_MAX);
3017         ast_str_set(&filepath, 0, "%s/", ast_config_AST_CONFIG_DIR);
3018         ast_str_append(&filepath, 0, "%s", fn);
3019
3020         if ((fd = open(ast_str_buffer(filepath), O_CREAT | O_EXCL, AST_FILE_MODE)) != -1) {
3021                 close(fd);
3022                 astman_send_ack(s, m, "New configuration file created successfully");
3023         } else {
3024                 astman_send_error(s, m, strerror(errno));
3025         }
3026
3027         return 0;
3028 }
3029
3030 static int action_waitevent(struct mansession *s, const struct message *m)
3031 {
3032         const char *timeouts = astman_get_header(m, "Timeout");
3033         int timeout = -1;
3034         int x;
3035         int needexit = 0;
3036         const char *id = astman_get_header(m, "ActionID");
3037         char idText[256];
3038
3039         if (!ast_strlen_zero(id)) {
3040                 snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
3041         } else {
3042                 idText[0] = '\0';
3043         }
3044
3045         if (!ast_strlen_zero(timeouts)) {
3046                 sscanf(timeouts, "%30i", &timeout);
3047                 if (timeout < -1) {
3048                         timeout = -1;
3049                 }
3050                 /* XXX maybe put an upper bound, or prevent the use of 0 ? */
3051         }
3052
3053         ao2_lock(s->session);
3054         if (s->session->waiting_thread != AST_PTHREADT_NULL) {
3055                 pthread_kill(s->session->waiting_thread, SIGURG);
3056         }
3057
3058         if (s->session->managerid) { /* AMI-over-HTTP session */
3059                 /*
3060                  * Make sure the timeout is within the expire time of the session,
3061                  * as the client will likely abort the request if it does not see
3062                  * data coming after some amount of time.
3063                  */
3064                 time_t now = time(NULL);
3065                 int max = s->session->sessiontimeout - now - 10;
3066
3067                 if (max < 0) {  /* We are already late. Strange but possible. */
3068                         max = 0;
3069                 }
3070                 if (timeout < 0 || timeout > max) {
3071                         timeout = max;
3072                 }
3073                 if (!s->session->send_events) { /* make sure we record events */
3074                         s->session->send_events = -1;
3075                 }
3076         }
3077         ao2_unlock(s->session);
3078
3079         /* XXX should this go inside the lock ? */
3080         s->session->waiting_thread = pthread_self();    /* let new events wake up this thread */
3081         ast_debug(1, "Starting waiting for an event!\n");
3082
3083         for (x = 0; x < timeout || timeout < 0; x++) {
3084                 ao2_lock(s->session);
3085                 if (AST_RWLIST_NEXT(s->session->last_ev, eq_next)) {
3086                         needexit = 1;
3087                 }
3088                 /* We can have multiple HTTP session point to the same mansession entry.
3089                  * The way we deal with it is not very nice: newcomers kick out the previous
3090                  * HTTP session. XXX this needs to be improved.
3091                  */
3092                 if (s->session->waiting_thread != pthread_self()) {
3093                         needexit = 1;
3094                 }
3095                 if (s->session->needdestroy) {
3096                         needexit = 1;
3097                 }
3098                 ao2_unlock(s->session);
3099                 if (needexit) {
3100                         break;
3101                 }
3102                 if (s->session->managerid == 0) {       /* AMI session */
3103                         if (ast_wait_for_input(s->session->fd, 1000)) {
3104                                 break;
3105                         }
3106                 } else {        /* HTTP session */
3107                         sleep(1);
3108                 }
3109         }
3110         ast_debug(1, "Finished waiting for an event!\n");
3111
3112         ao2_lock(s->session);
3113         if (s->session->waiting_thread == pthread_self()) {
3114                 struct eventqent *eqe = s->session->last_ev;
3115                 astman_send_response(s, m, "Success", "Waiting for Event completed.");
3116                 while ((eqe = advance_event(eqe))) {
3117                         if (((s->session->readperm & eqe->category) == eqe->category) &&
3118                             ((s->session->send_events & eqe->category) == eqe->category)) {
3119                                 astman_append(s, "%s", eqe->eventdata);
3120                         }
3121                         s->session->last_ev = eqe;
3122                 }
3123                 astman_append(s,
3124                         "Event: WaitEventComplete\r\n"
3125                         "%s"
3126                         "\r\n", idText);
3127                 s->session->waiting_thread = AST_PTHREADT_NULL;
3128         } else {
3129                 ast_debug(1, "Abandoning event request!\n");
3130         }
3131         ao2_unlock(s->session);
3132
3133         return 0;
3134 }
3135
3136 static int action_listcommands(struct mansession *s, const struct message *m)
3137 {
3138         struct manager_action *cur;
3139         struct ast_str *temp = ast_str_alloca(256);
3140
3141         astman_start_ack(s, m);
3142         AST_RWLIST_RDLOCK(&actions);
3143         AST_RWLIST_TRAVERSE(&actions, cur, list) {
3144                 if ((s->session->writeperm & cur->authority) || cur->authority == 0) {
3145                         astman_append(s, "%s: %s (Priv: %s)\r\n",
3146                                 cur->action, cur->synopsis, authority_to_str(cur->authority, &temp));
3147                 }
3148         }
3149         AST_RWLIST_UNLOCK(&actions);
3150         astman_append(s, "\r\n");
3151
3152         return 0;
3153 }
3154
3155 static int action_events(struct mansession *s, const struct message *m)
3156 {
3157         const char *mask = astman_get_header(m, "EventMask");
3158         int res, x;
3159         const char *id = astman_get_header(m, "ActionID");
3160         char id_text[256];
3161
3162         if (!ast_strlen_zero(id)) {
3163                 snprintf(id_text, sizeof(id_text), "ActionID: %s\r\n", id);
3164         } else {
3165                 id_text[0] = '\0';
3166         }
3167
3168         res = set_eventmask(s, mask);
3169         if (broken_events_action) {
3170                 /* if this option is set we should not return a response on
3171                  * error, or when all events are set */
3172
3173                 if (res > 0) {
3174                         for (x = 0; x < ARRAY_LEN(perms); x++) {
3175                                 if (!strcasecmp(perms[x].label, "all") && res == perms[x].num) {
3176                                         return 0;
3177                                 }
3178                         }
3179                         astman_append(s, "Response: Success\r\n%s"
3180                                          "Events: On\r\n\r\n", id_text);
3181                 } else if (res == 0)
3182                         astman_append(s, "Response: Success\r\n%s"
3183                                          "Events: Off\r\n\r\n", id_text);
3184                 return 0;
3185         }
3186
3187         if (res > 0)
3188                 astman_append(s, "Response: Success\r\n%s"
3189                                  "Events: On\r\n\r\n", id_text);
3190         else if (res == 0)
3191                 astman_append(s, "Response: Success\r\n%s"
3192                                  "Events: Off\r\n\r\n", id_text);
3193         else
3194                 astman_send_error(s, m, "Invalid event mask");
3195
3196         return 0;
3197 }
3198
3199 static int action_logoff(struct mansession *s, const struct message *m)
3200 {
3201         astman_send_response(s, m, "Goodbye", "Thanks for all the fish.");
3202         return -1;
3203 }
3204
3205 static int action_login(struct mansession *s, const struct message *m)
3206 {
3207
3208         /* still authenticated - don't process again */
3209         if (s->session->authenticated) {
3210                 astman_send_ack(s, m, "Already authenticated");
3211                 return 0;
3212         }
3213
3214         if (authenticate(s, m)) {
3215                 sleep(1);
3216                 astman_send_error(s, m, "Authentication failed");
3217                 return -1;
3218         }
3219         s->session->authenticated = 1;
3220         ast_atomic_fetchadd_int(&unauth_sessions, -1);
3221         if (manager_displayconnects(s->session)) {
3222                 ast_verb(2, "%sManager '%s' logged on from %s\n", (s->session->managerid ? "HTTP " : ""), s->session->username, ast_sockaddr_stringify_addr(&s->session->addr));
3223         }
3224         astman_send_ack(s, m, "Authentication accepted");
3225         if ((s->session->send_events & EVENT_FLAG_SYSTEM)
3226                 && ast_test_flag(&ast_options, AST_OPT_FLAG_FULLY_BOOTED)) {
3227                 struct ast_str *auth = ast_str_alloca(80);
3228                 const char *cat_str = authority_to_str(EVENT_FLAG_SYSTEM, &auth);
3229                 astman_append(s, "Event: FullyBooted\r\n"
3230                         "Privilege: %s\r\n"
3231                         "Status: Fully Booted\r\n\r\n", cat_str);
3232         }
3233         return 0;
3234 }
3235
3236 static int action_challenge(struct mansession *s, const struct message *m)
3237 {
3238         const char *authtype = astman_get_header(m, "AuthType");
3239
3240         if (!strcasecmp(authtype, "MD5")) {
3241                 if (ast_strlen_zero(s->session->challenge)) {
3242                         snprintf(s->session->challenge, sizeof(s->session->challenge), "%ld", ast_random());
3243                 }
3244                 mansession_lock(s);
3245                 astman_start_ack(s, m);
3246                 astman_append(s, "Challenge: %s\r\n\r\n", s->session->challenge);
3247                 mansession_unlock(s);
3248         } else {
3249                 astman_send_error(s, m, "Must specify AuthType");
3250         }
3251         return 0;
3252 }
3253
3254 static int action_hangup(struct mansession *s, const struct message *m)
3255 {
3256         struct ast_channel *c = NULL;
3257         int causecode = 0; /* all values <= 0 mean 'do not set hangupcause in channel' */
3258         const char *id = astman_get_header(m, "ActionID");
3259         const char *name_or_regex = astman_get_header(m, "Channel");
3260         const char *cause = astman_get_header(m, "Cause");
3261         char idText[256];
3262         regex_t regexbuf;
3263         struct ast_channel_iterator *iter = NULL;
3264         struct ast_str *regex_string;
3265         int channels_matched = 0;
3266
3267         if (ast_strlen_zero(name_or_regex)) {
3268                 astman_send_error(s, m, "No channel specified");
3269                 return 0;
3270         }
3271
3272         if (!ast_strlen_zero(id)) {
3273                 snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
3274         } else {
3275                 idText[0] = '\0';
3276         }
3277
3278         if (!ast_strlen_zero(cause)) {
3279                 char *endptr;
3280                 causecode = strtol(cause, &endptr, 10);
3281                 if (causecode < 0 || causecode > 127 || *endptr != '\0') {
3282                         ast_log(LOG_NOTICE, "Invalid 'Cause: %s' in manager action Hangup\n", cause);
3283                         /* keep going, better to hangup without cause than to not hang up at all */
3284                         causecode = 0; /* do not set channel's hangupcause */
3285                 }
3286         }
3287
3288         /************************************************/
3289         /* Regular explicit match channel byname hangup */
3290
3291         if (name_or_regex[0] != '/') {
3292                 if (!(c = ast_channel_get_by_name(name_or_regex))) {
3293                         ast_log(LOG_NOTICE, "!!!!!!!!!! Can't find channel to hang up!\n");
3294                         astman_send_error(s, m, "No such channel");
3295                         return 0;
3296                 }
3297
3298                 ast_verb(3, "%sManager '%s' from %s, hanging up channel: %s\n",
3299                         (s->session->managerid ? "HTTP " : ""),
3300                         s->session->username,
3301                         ast_sockaddr_stringify_addr(&s->session->addr),
3302                         ast_channel_name(c));
3303
3304                 ast_channel_softhangup_withcause_locked(c, causecode);
3305                 c = ast_channel_unref(c);
3306
3307                 astman_send_ack(s, m, "Channel Hungup");
3308
3309                 return 0;
3310         }
3311
3312         /***********************************************/
3313         /* find and hangup any channels matching regex */
3314
3315         regex_string = ast_str_create(strlen(name_or_regex));
3316         if (!regex_string) {
3317                 astman_send_error(s, m, "Memory Allocation Failure");
3318                 return 0;
3319         }
3320
3321         /* Make "/regex/" into "regex" */
3322         if (ast_regex_string_to_regex_pattern(name_or_regex, &regex_string) != 0) {
3323                 astman_send_error(s, m, "Regex format invalid, Channel param should be /regex/");
3324                 ast_free(regex_string);
3325                 return 0;
3326         }
3327
3328         /* if regex compilation fails, hangup fails */
3329         if (regcomp(&regexbuf, ast_str_buffer(regex_string), REG_EXTENDED | REG_NOSUB)) {
3330                 astman_send_error_va(s, m, "Regex compile failed on: %s\n", name_or_regex);
3331                 ast_free(regex_string);
3332                 return 0;
3333         }
3334
3335         astman_send_listack(s, m, "Channels hung up will follow", "start");
3336
3337         iter = ast_channel_iterator_all_new();
3338         if (iter) {
3339                 for (; (c = ast_channel_iterator_next(iter)); ast_channel_unref(c)) {
3340                         if (regexec(&regexbuf, ast_channel_name(c), 0, NULL, 0)) {
3341                                 continue;
3342                         }
3343
3344                         ast_verb(3, "%sManager '%s' from %s, hanging up channel: %s\n",
3345                                 (s->session->managerid ? "HTTP " : ""),
3346                                 s->session->username,
3347                                 ast_sockaddr_stringify_addr(&s->session->addr),
3348                                 ast_channel_name(c));
3349
3350                         ast_channel_softhangup_withcause_locked(c, causecode);
3351                         channels_matched++;
3352
3353                         astman_append(s,
3354                                 "Event: ChannelHungup\r\n"
3355                                 "Channel: %s\r\n"
3356                                 "%s"
3357                                 "\r\n", ast_channel_name(c), idText);
3358                 }
3359                 ast_channel_iterator_destroy(iter);
3360         }
3361
3362         regfree(&regexbuf);
3363         ast_free(regex_string);
3364
3365         astman_append(s,
3366                 "Event: ChannelsHungupListComplete\r\n"
3367                 "EventList: Complete\r\n"
3368                 "ListItems: %d\r\n"
3369                 "%s"
3370                 "\r\n", channels_matched, idText);
3371
3372         return 0;
3373 }
3374
3375 static int action_setvar(struct mansession *s, const struct message *m)
3376 {
3377         struct ast_channel *c = NULL;
3378         const char *name = astman_get_header(m, "Channel");
3379         const char *varname = astman_get_header(m, "Variable");
3380         const char *varval = astman_get_header(m, "Value");
3381         int res = 0;
3382
3383         if (ast_strlen_zero(varname)) {
3384                 astman_send_error(s, m, "No variable specified");
3385                 return 0;
3386         }
3387
3388         if (!ast_strlen_zero(name)) {
3389                 if (!(c = ast_channel_get_by_name(name))) {
3390                         astman_send_error(s, m, "No such channel");
3391                         return 0;
3392                 }
3393         }
3394
3395         res = pbx_builtin_setvar_helper(c, varname, S_OR(varval, ""));
3396
3397         if (c) {
3398                 c = ast_channel_unref(c);
3399         }
3400         if (res == 0) {
3401                 astman_send_ack(s, m, "Variable Set");
3402         } else {
3403                 astman_send_error(s, m, "Variable not set");
3404         }
3405         return 0;
3406 }
3407
3408 static int action_getvar(struct mansession *s, const struct message *m)
3409 {
3410         struct ast_channel *c = NULL;
3411         const char *name = astman_get_header(m, "Channel");
3412         const char *varname = astman_get_header(m, "Variable");
3413         char *varval;
3414         char workspace[1024];
3415
3416         if (ast_strlen_zero(varname)) {
3417                 astman_send_error(s, m, "No variable specified");
3418                 return 0;
3419         }
3420
3421         /* We don't want users with insufficient permissions using certain functions. */
3422         if (!(function_capable_string_allowed_with_auths(varname, s->session->writeperm))) {
3423                 astman_send_error(s, m, "GetVar Access Forbidden: Variable");
3424                 return 0;
3425         }
3426
3427         if (!ast_strlen_zero(name)) {
3428                 if (!(c = ast_channel_get_by_name(name))) {
3429                         astman_send_error(s, m, "No such channel");
3430                         return 0;
3431                 }
3432         }
3433
3434         workspace[0] = '\0';
3435         if (varname[strlen(varname) - 1] == ')') {
3436                 if (!c) {
3437                         c = ast_dummy_channel_alloc();
3438                         if (c) {
3439                                 ast_func_read(c, (char *) varname, workspace, sizeof(workspace));
3440                         } else
3441                                 ast_log(LOG_ERROR, "Unable to allocate bogus channel for variable substitution.  Function results may be blank.\n");
3442                 } else {
3443                         ast_func_read(c, (char *) varname, workspace, sizeof(workspace));
3444                 }
3445                 varval = workspace;
3446         } else {
3447                 pbx_retrieve_variable(c, varname, &varval, workspace, sizeof(workspace), NULL);
3448         }
3449
3450         if (c) {
3451                 c = ast_channel_unref(c);
3452         }
3453
3454         astman_start_ack(s, m);
3455         astman_append(s, "Variable: %s\r\nValue: %s\r\n\r\n", varname, S_OR(varval, ""));
3456
3457         return 0;
3458 }
3459
3460 /*! \brief Manager "status" command to show channels */
3461 /* Needs documentation... */
3462 static int action_status(struct mansession *s, const struct message *m)
3463 {
3464         const char *name = astman_get_header(m, "Channel");
3465         const char *cvariables = astman_get_header(m, "Variables");
3466         char *variables = ast_strdupa(S_OR(cvariables, ""));
3467         struct ast_channel *c;
3468         char bridge[256];
3469         struct timeval now = ast_tvnow();
3470         long elapsed_seconds = 0;
3471         int channels = 0;
3472         int all = ast_strlen_zero(name); /* set if we want all channels */
3473         const char *id = astman_get_header(m, "ActionID");
3474         char idText[256];
3475         AST_DECLARE_APP_ARGS(vars,
3476                 AST_APP_ARG(name)[100];
3477         );
3478         struct ast_str *str = ast_str_create(1000);
3479         struct ast_channel_iterator *iter = NULL;
3480
3481         if (!ast_strlen_zero(id)) {
3482                 snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
3483         } else {
3484                 idText[0] = '\0';
3485         }
3486
3487         if (!(function_capable_string_allowed_with_auths(variables, s->session->writeperm))) {
3488                 astman_send_error(s, m, "Status Access Forbidden: Variables");
3489                 return 0;