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