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