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