96fbdae61ee05fedd855dfa6b43934d79ae92c09
[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 int ast_manager_publish_message(struct ast_json *obj)
1316 {
1317         RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
1318         RAII_VAR(struct ast_json_payload *, payload, NULL, ao2_cleanup);
1319         struct ast_json *type = ast_json_object_get(obj, "type");
1320         struct ast_json *class_type = ast_json_object_get(obj, "class_type");
1321         struct ast_json *event = ast_json_object_get(obj, "event");
1322
1323         if (!type) {
1324                 ast_log(AST_LOG_ERROR, "Attempt to send generic manager event without type field\n");
1325                 return -1;
1326         }
1327         if (!class_type) {
1328                 ast_log(AST_LOG_ERROR, "Attempt to send generic manager event without class type field\n");
1329                 return -1;
1330         }
1331         if (!event) {
1332                 ast_log(AST_LOG_ERROR, "Attempt to send generic manager event without event payload\n");
1333                 return -1;
1334         }
1335
1336         payload = ast_json_payload_create(obj);
1337         if (!payload) {
1338                 return -1;
1339         }
1340         message = stasis_message_create(ast_manager_get_generic_type(), payload);
1341         if (!message) {
1342                 return -1;
1343         }
1344         stasis_publish(ast_manager_get_topic(), message);
1345         return 0;
1346 }
1347
1348 /*! \brief Add a custom hook to be called when an event is fired */
1349 void ast_manager_register_hook(struct manager_custom_hook *hook)
1350 {
1351         AST_RWLIST_WRLOCK(&manager_hooks);
1352         AST_RWLIST_INSERT_TAIL(&manager_hooks, hook, list);
1353         AST_RWLIST_UNLOCK(&manager_hooks);
1354 }
1355
1356 /*! \brief Delete a custom hook to be called when an event is fired */
1357 void ast_manager_unregister_hook(struct manager_custom_hook *hook)
1358 {
1359         AST_RWLIST_WRLOCK(&manager_hooks);
1360         AST_RWLIST_REMOVE(&manager_hooks, hook, list);
1361         AST_RWLIST_UNLOCK(&manager_hooks);
1362 }
1363
1364 int check_manager_enabled(void)
1365 {
1366         return manager_enabled;
1367 }
1368
1369 int check_webmanager_enabled(void)
1370 {
1371         return (webmanager_enabled && manager_enabled);
1372 }
1373
1374 /*!
1375  * Grab a reference to the last event, update usecount as needed.
1376  * Can handle a NULL pointer.
1377  */
1378 static struct eventqent *grab_last(void)
1379 {
1380         struct eventqent *ret;
1381
1382         AST_RWLIST_WRLOCK(&all_events);
1383         ret = AST_RWLIST_LAST(&all_events);
1384         /* the list is never empty now, but may become so when
1385          * we optimize it in the future, so be prepared.
1386          */
1387         if (ret) {
1388                 ast_atomic_fetchadd_int(&ret->usecount, 1);
1389         }
1390         AST_RWLIST_UNLOCK(&all_events);
1391         return ret;
1392 }
1393
1394 /*!
1395  * Purge unused events. Remove elements from the head
1396  * as long as their usecount is 0 and there is a next element.
1397  */
1398 static void purge_events(void)
1399 {
1400         struct eventqent *ev;
1401         struct timeval now = ast_tvnow();
1402
1403         AST_RWLIST_WRLOCK(&all_events);
1404         while ( (ev = AST_RWLIST_FIRST(&all_events)) &&
1405             ev->usecount == 0 && AST_RWLIST_NEXT(ev, eq_next)) {
1406                 AST_RWLIST_REMOVE_HEAD(&all_events, eq_next);
1407                 ast_free(ev);
1408         }
1409
1410         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&all_events, ev, eq_next) {
1411                 /* Never release the last event */
1412                 if (!AST_RWLIST_NEXT(ev, eq_next)) {
1413                         break;
1414                 }
1415
1416                 /* 2.5 times whatever the HTTP timeout is (maximum 2.5 hours) is the maximum time that we will definitely cache an event */
1417                 if (ev->usecount == 0 && ast_tvdiff_sec(now, ev->tv) > (httptimeout > 3600 ? 3600 : httptimeout) * 2.5) {
1418                         AST_RWLIST_REMOVE_CURRENT(eq_next);
1419                         ast_free(ev);
1420                 }
1421         }
1422         AST_RWLIST_TRAVERSE_SAFE_END;
1423         AST_RWLIST_UNLOCK(&all_events);
1424 }
1425
1426 /*!
1427  * helper functions to convert back and forth between
1428  * string and numeric representation of set of flags
1429  */
1430 static const struct permalias {
1431         int num;
1432         const char *label;
1433 } perms[] = {
1434         { EVENT_FLAG_SYSTEM, "system" },
1435         { EVENT_FLAG_CALL, "call" },
1436         { EVENT_FLAG_LOG, "log" },
1437         { EVENT_FLAG_VERBOSE, "verbose" },
1438         { EVENT_FLAG_COMMAND, "command" },
1439         { EVENT_FLAG_AGENT, "agent" },
1440         { EVENT_FLAG_USER, "user" },
1441         { EVENT_FLAG_CONFIG, "config" },
1442         { EVENT_FLAG_DTMF, "dtmf" },
1443         { EVENT_FLAG_REPORTING, "reporting" },
1444         { EVENT_FLAG_CDR, "cdr" },
1445         { EVENT_FLAG_DIALPLAN, "dialplan" },
1446         { EVENT_FLAG_ORIGINATE, "originate" },
1447         { EVENT_FLAG_AGI, "agi" },
1448         { EVENT_FLAG_CC, "cc" },
1449         { EVENT_FLAG_AOC, "aoc" },
1450         { EVENT_FLAG_TEST, "test" },
1451         { EVENT_FLAG_MESSAGE, "message" },
1452         { INT_MAX, "all" },
1453         { 0, "none" },
1454 };
1455
1456 /*! \brief Checks to see if a string which can be used to evaluate functions should be rejected */
1457 static int function_capable_string_allowed_with_auths(const char *evaluating, int writepermlist)
1458 {
1459         if (!(writepermlist & EVENT_FLAG_SYSTEM)
1460                 && (
1461                         strstr(evaluating, "SHELL") ||       /* NoOp(${SHELL(rm -rf /)})  */
1462                         strstr(evaluating, "EVAL")           /* NoOp(${EVAL(${some_var_containing_SHELL})}) */
1463                 )) {
1464                 return 0;
1465         }
1466         return 1;
1467 }
1468
1469 /*! \brief Convert authority code to a list of options for a user. This will only
1470  * display those authority codes that have an explicit match on authority */
1471 static const char *user_authority_to_str(int authority, struct ast_str **res)
1472 {
1473         int i;
1474         char *sep = "";
1475
1476         ast_str_reset(*res);
1477         for (i = 0; i < ARRAY_LEN(perms) - 1; i++) {
1478                 if ((authority & perms[i].num) == perms[i].num) {
1479                         ast_str_append(res, 0, "%s%s", sep, perms[i].label);
1480                         sep = ",";
1481                 }
1482         }
1483
1484         if (ast_str_strlen(*res) == 0)  /* replace empty string with something sensible */
1485                 ast_str_append(res, 0, "<none>");
1486
1487         return ast_str_buffer(*res);
1488 }
1489
1490
1491 /*! \brief Convert authority code to a list of options. Note that the EVENT_FLAG_ALL
1492  * authority will always be returned. */
1493 static const char *authority_to_str(int authority, struct ast_str **res)
1494 {
1495         int i;
1496         char *sep = "";
1497
1498         ast_str_reset(*res);
1499         for (i = 0; i < ARRAY_LEN(perms) - 1; i++) {
1500                 if (authority & perms[i].num) {
1501                         ast_str_append(res, 0, "%s%s", sep, perms[i].label);
1502                         sep = ",";
1503                 }
1504         }
1505
1506         if (ast_str_strlen(*res) == 0)  /* replace empty string with something sensible */
1507                 ast_str_append(res, 0, "<none>");
1508
1509         return ast_str_buffer(*res);
1510 }
1511
1512 /*! Tells you if smallstr exists inside bigstr
1513    which is delim by delim and uses no buf or stringsep
1514    ast_instring("this|that|more","this",'|') == 1;
1515
1516    feel free to move this to app.c -anthm */
1517 static int ast_instring(const char *bigstr, const char *smallstr, const char delim)
1518 {
1519         const char *val = bigstr, *next;
1520
1521         do {
1522                 if ((next = strchr(val, delim))) {
1523                         if (!strncmp(val, smallstr, (next - val))) {
1524                                 return 1;
1525                         } else {
1526                                 continue;
1527                         }
1528                 } else {
1529                         return !strcmp(smallstr, val);
1530                 }
1531         } while (*(val = (next + 1)));
1532
1533         return 0;
1534 }
1535
1536 static int get_perm(const char *instr)
1537 {
1538         int x = 0, ret = 0;
1539
1540         if (!instr) {
1541                 return 0;
1542         }
1543
1544         for (x = 0; x < ARRAY_LEN(perms); x++) {
1545                 if (ast_instring(instr, perms[x].label, ',')) {
1546                         ret |= perms[x].num;
1547                 }
1548         }
1549
1550         return ret;
1551 }
1552
1553 /*!
1554  * A number returns itself, false returns 0, true returns all flags,
1555  * other strings return the flags that are set.
1556  */
1557 static int strings_to_mask(const char *string)
1558 {
1559         const char *p;
1560
1561         if (ast_strlen_zero(string)) {
1562                 return -1;
1563         }
1564
1565         for (p = string; *p; p++) {
1566                 if (*p < '0' || *p > '9') {
1567                         break;
1568                 }
1569         }
1570         if (!*p) { /* all digits */
1571                 return atoi(string);
1572         }
1573         if (ast_false(string)) {
1574                 return 0;
1575         }
1576         if (ast_true(string)) { /* all permissions */
1577                 int x, ret = 0;
1578                 for (x = 0; x < ARRAY_LEN(perms); x++) {
1579                         ret |= perms[x].num;
1580                 }
1581                 return ret;
1582         }
1583         return get_perm(string);
1584 }
1585
1586 /*! \brief Unreference manager session object.
1587      If no more references, then go ahead and delete it */
1588 static struct mansession_session *unref_mansession(struct mansession_session *s)
1589 {
1590         int refcount = ao2_ref(s, -1);
1591         if (manager_debug) {
1592                 ast_debug(1, "Mansession: %p refcount now %d\n", s, refcount - 1);
1593         }
1594         return s;
1595 }
1596
1597 static void event_filter_destructor(void *obj)
1598 {
1599         regex_t *regex_filter = obj;
1600         regfree(regex_filter);
1601 }
1602
1603 static void session_destructor(void *obj)
1604 {
1605         struct mansession_session *session = obj;
1606         struct eventqent *eqe = session->last_ev;
1607         struct ast_datastore *datastore;
1608
1609         /* Get rid of each of the data stores on the session */
1610         while ((datastore = AST_LIST_REMOVE_HEAD(&session->datastores, entry))) {
1611                 /* Free the data store */
1612                 ast_datastore_free(datastore);
1613         }
1614
1615         if (session->f != NULL) {
1616                 fclose(session->f);
1617         }
1618         if (eqe) {
1619                 ast_atomic_fetchadd_int(&eqe->usecount, -1);
1620         }
1621         if (session->chanvars) {
1622                 ast_variables_destroy(session->chanvars);
1623         }
1624
1625         if (session->whitefilters) {
1626                 ao2_t_callback(session->whitefilters, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL, "unlink all white filters");
1627                 ao2_t_ref(session->whitefilters, -1 , "decrement ref for white container, should be last one");
1628         }
1629
1630         if (session->blackfilters) {
1631                 ao2_t_callback(session->blackfilters, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL, "unlink all black filters");
1632                 ao2_t_ref(session->blackfilters, -1 , "decrement ref for black container, should be last one");
1633         }
1634 }
1635
1636 /*! \brief Allocate manager session structure and add it to the list of sessions */
1637 static struct mansession_session *build_mansession(const struct ast_sockaddr *addr)
1638 {
1639         struct mansession_session *newsession;
1640
1641         if (!(newsession = ao2_alloc(sizeof(*newsession), session_destructor))) {
1642                 return NULL;
1643         }
1644
1645         if (!(newsession->whitefilters = ao2_container_alloc(1, NULL, NULL))) {
1646                 ao2_ref(newsession, -1);
1647                 return NULL;
1648         }
1649
1650         if (!(newsession->blackfilters = ao2_container_alloc(1, NULL, NULL))) {
1651                 ao2_ref(newsession, -1); /* session_destructor will cleanup the other filter */
1652                 return NULL;
1653         }
1654
1655         newsession->fd = -1;
1656         newsession->waiting_thread = AST_PTHREADT_NULL;
1657         newsession->writetimeout = 100;
1658         newsession->send_events = -1;
1659         ast_sockaddr_copy(&newsession->addr, addr);
1660
1661         ao2_link(sessions, newsession);
1662
1663         return newsession;
1664 }
1665
1666 static int mansession_cmp_fn(void *obj, void *arg, int flags)
1667 {
1668         struct mansession_session *s = obj;
1669         char *str = arg;
1670         return !strcasecmp(s->username, str) ? CMP_MATCH : 0;
1671 }
1672
1673 static void session_destroy(struct mansession_session *s)
1674 {
1675         unref_mansession(s);
1676         ao2_unlink(sessions, s);
1677 }
1678
1679
1680 static int check_manager_session_inuse(const char *name)
1681 {
1682         struct mansession_session *session = ao2_find(sessions, (char *) name, 0);
1683         int inuse = 0;
1684
1685         if (session) {
1686                 inuse = 1;
1687                 unref_mansession(session);
1688         }
1689         return inuse;
1690 }
1691
1692
1693 /*!
1694  * lookup an entry in the list of registered users.
1695  * must be called with the list lock held.
1696  */
1697 static struct ast_manager_user *get_manager_by_name_locked(const char *name)
1698 {
1699         struct ast_manager_user *user = NULL;
1700
1701         AST_RWLIST_TRAVERSE(&users, user, list) {
1702                 if (!strcasecmp(user->username, name)) {
1703                         break;
1704                 }
1705         }
1706
1707         return user;
1708 }
1709
1710 /*! \brief Get displayconnects config option.
1711  *  \param session manager session to get parameter from.
1712  *  \return displayconnects config option value.
1713  */
1714 static int manager_displayconnects (struct mansession_session *session)
1715 {
1716         struct ast_manager_user *user = NULL;
1717         int ret = 0;
1718
1719         AST_RWLIST_RDLOCK(&users);
1720         if ((user = get_manager_by_name_locked (session->username))) {
1721                 ret = user->displayconnects;
1722         }
1723         AST_RWLIST_UNLOCK(&users);
1724
1725         return ret;
1726 }
1727
1728 static char *handle_showmancmd(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1729 {
1730         struct manager_action *cur;
1731         struct ast_str *authority;
1732         int num, l, which;
1733         char *ret = NULL;
1734 #ifdef AST_XML_DOCS
1735         char syntax_title[64], description_title[64], synopsis_title[64], seealso_title[64], arguments_title[64], privilege_title[64];
1736 #endif
1737
1738         switch (cmd) {
1739         case CLI_INIT:
1740                 e->command = "manager show command";
1741                 e->usage =
1742                         "Usage: manager show command <actionname> [<actionname> [<actionname> [...]]]\n"
1743                         "       Shows the detailed description for a specific Asterisk manager interface command.\n";
1744                 return NULL;
1745         case CLI_GENERATE:
1746                 l = strlen(a->word);
1747                 which = 0;
1748                 AST_RWLIST_RDLOCK(&actions);
1749                 AST_RWLIST_TRAVERSE(&actions, cur, list) {
1750                         if (!strncasecmp(a->word, cur->action, l) && ++which > a->n) {
1751                                 ret = ast_strdup(cur->action);
1752                                 break;  /* make sure we exit even if ast_strdup() returns NULL */
1753                         }
1754                 }
1755                 AST_RWLIST_UNLOCK(&actions);
1756                 return ret;
1757         }
1758         authority = ast_str_alloca(80);
1759         if (a->argc < 4) {
1760                 return CLI_SHOWUSAGE;
1761         }
1762
1763 #ifdef AST_XML_DOCS
1764         /* setup the titles */
1765         term_color(synopsis_title, "[Synopsis]\n", COLOR_MAGENTA, 0, 40);
1766         term_color(description_title, "[Description]\n", COLOR_MAGENTA, 0, 40);
1767         term_color(syntax_title, "[Syntax]\n", COLOR_MAGENTA, 0, 40);
1768         term_color(seealso_title, "[See Also]\n", COLOR_MAGENTA, 0, 40);
1769         term_color(arguments_title, "[Arguments]\n", COLOR_MAGENTA, 0, 40);
1770         term_color(privilege_title, "[Privilege]\n", COLOR_MAGENTA, 0, 40);
1771 #endif
1772
1773         AST_RWLIST_RDLOCK(&actions);
1774         AST_RWLIST_TRAVERSE(&actions, cur, list) {
1775                 for (num = 3; num < a->argc; num++) {
1776                         if (!strcasecmp(cur->action, a->argv[num])) {
1777                                 authority_to_str(cur->authority, &authority);
1778
1779 #ifdef AST_XML_DOCS
1780                                 if (cur->docsrc == AST_XML_DOC) {
1781                                         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",
1782                                                 syntax_title,
1783                                                 ast_xmldoc_printable(S_OR(cur->syntax, "Not available"), 1),
1784                                                 synopsis_title,
1785                                                 ast_xmldoc_printable(S_OR(cur->synopsis, "Not available"), 1),
1786                                                 description_title,
1787                                                 ast_xmldoc_printable(S_OR(cur->description, "Not available"), 1),
1788                                                 arguments_title,
1789                                                 ast_xmldoc_printable(S_OR(cur->arguments, "Not available"), 1),
1790                                                 seealso_title,
1791                                                 ast_xmldoc_printable(S_OR(cur->seealso, "Not available"), 1),
1792                                                 privilege_title,
1793                                                 ast_xmldoc_printable(S_OR(authority->str, "Not available"), 1));
1794                                 } else
1795 #endif
1796                                 {
1797                                         ast_cli(a->fd, "Action: %s\nSynopsis: %s\nPrivilege: %s\n%s\n",
1798                                                 cur->action, cur->synopsis,
1799                                                 authority->str,
1800                                                 S_OR(cur->description, ""));
1801                                 }
1802                         }
1803                 }
1804         }
1805         AST_RWLIST_UNLOCK(&actions);
1806
1807         return CLI_SUCCESS;
1808 }
1809
1810 static char *handle_mandebug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1811 {
1812         switch (cmd) {
1813         case CLI_INIT:
1814                 e->command = "manager set debug [on|off]";
1815                 e->usage = "Usage: manager set debug [on|off]\n Show, enable, disable debugging of the manager code.\n";
1816                 return NULL;
1817         case CLI_GENERATE:
1818                 return NULL;
1819         }
1820
1821         if (a->argc == 3) {
1822                 ast_cli(a->fd, "manager debug is %s\n", manager_debug? "on" : "off");
1823         } else if (a->argc == 4) {
1824                 if (!strcasecmp(a->argv[3], "on")) {
1825                         manager_debug = 1;
1826                 } else if (!strcasecmp(a->argv[3], "off")) {
1827                         manager_debug = 0;
1828                 } else {
1829                         return CLI_SHOWUSAGE;
1830                 }
1831         }
1832         return CLI_SUCCESS;
1833 }
1834
1835 static char *handle_showmanager(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1836 {
1837         struct ast_manager_user *user = NULL;
1838         int l, which;
1839         char *ret = NULL;
1840         struct ast_str *rauthority = ast_str_alloca(128);
1841         struct ast_str *wauthority = ast_str_alloca(128);
1842         struct ast_variable *v;
1843
1844         switch (cmd) {
1845         case CLI_INIT:
1846                 e->command = "manager show user";
1847                 e->usage =
1848                         " Usage: manager show user <user>\n"
1849                         "        Display all information related to the manager user specified.\n";
1850                 return NULL;
1851         case CLI_GENERATE:
1852                 l = strlen(a->word);
1853                 which = 0;
1854                 if (a->pos != 3) {
1855                         return NULL;
1856                 }
1857                 AST_RWLIST_RDLOCK(&users);
1858                 AST_RWLIST_TRAVERSE(&users, user, list) {
1859                         if ( !strncasecmp(a->word, user->username, l) && ++which > a->n ) {
1860                                 ret = ast_strdup(user->username);
1861                                 break;
1862                         }
1863                 }
1864                 AST_RWLIST_UNLOCK(&users);
1865                 return ret;
1866         }
1867
1868         if (a->argc != 4) {
1869                 return CLI_SHOWUSAGE;
1870         }
1871
1872         AST_RWLIST_RDLOCK(&users);
1873
1874         if (!(user = get_manager_by_name_locked(a->argv[3]))) {
1875                 ast_cli(a->fd, "There is no manager called %s\n", a->argv[3]);
1876                 AST_RWLIST_UNLOCK(&users);
1877                 return CLI_SUCCESS;
1878         }
1879
1880         ast_cli(a->fd, "\n");
1881         ast_cli(a->fd,
1882                 "       username: %s\n"
1883                 "         secret: %s\n"
1884                 "            ACL: %s\n"
1885                 "      read perm: %s\n"
1886                 "     write perm: %s\n"
1887                 "displayconnects: %s\n",
1888                 (user->username ? user->username : "(N/A)"),
1889                 (user->secret ? "<Set>" : "(N/A)"),
1890                 ((user->acl && !ast_acl_list_is_empty(user->acl)) ? "yes" : "no"),
1891                 user_authority_to_str(user->readperm, &rauthority),
1892                 user_authority_to_str(user->writeperm, &wauthority),
1893                 (user->displayconnects ? "yes" : "no"));
1894         ast_cli(a->fd, "      Variables: \n");
1895                 for (v = user->chanvars ; v ; v = v->next) {
1896                         ast_cli(a->fd, "                 %s = %s\n", v->name, v->value);
1897                 }
1898
1899         AST_RWLIST_UNLOCK(&users);
1900
1901         return CLI_SUCCESS;
1902 }
1903
1904 static char *handle_showmanagers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1905 {
1906         struct ast_manager_user *user = NULL;
1907         int count_amu = 0;
1908         switch (cmd) {
1909         case CLI_INIT:
1910                 e->command = "manager show users";
1911                 e->usage =
1912                         "Usage: manager show users\n"
1913                         "       Prints a listing of all managers that are currently configured on that\n"
1914                         " system.\n";
1915                 return NULL;
1916         case CLI_GENERATE:
1917                 return NULL;
1918         }
1919         if (a->argc != 3) {
1920                 return CLI_SHOWUSAGE;
1921         }
1922
1923         AST_RWLIST_RDLOCK(&users);
1924
1925         /* If there are no users, print out something along those lines */
1926         if (AST_RWLIST_EMPTY(&users)) {
1927                 ast_cli(a->fd, "There are no manager users.\n");
1928                 AST_RWLIST_UNLOCK(&users);
1929                 return CLI_SUCCESS;
1930         }
1931
1932         ast_cli(a->fd, "\nusername\n--------\n");
1933
1934         AST_RWLIST_TRAVERSE(&users, user, list) {
1935                 ast_cli(a->fd, "%s\n", user->username);
1936                 count_amu++;
1937         }
1938
1939         AST_RWLIST_UNLOCK(&users);
1940
1941         ast_cli(a->fd,"-------------------\n"
1942                       "%d manager users configured.\n", count_amu);
1943         return CLI_SUCCESS;
1944 }
1945
1946 /*! \brief  CLI command  manager list commands */
1947 static char *handle_showmancmds(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1948 {
1949         struct manager_action *cur;
1950         int name_len = 1;
1951         int space_remaining;
1952 #define HSMC_FORMAT "  %-*.*s  %-.*s\n"
1953         switch (cmd) {
1954         case CLI_INIT:
1955                 e->command = "manager show commands";
1956                 e->usage =
1957                         "Usage: manager show commands\n"
1958                         "       Prints a listing of all the available Asterisk manager interface commands.\n";
1959                 return NULL;
1960         case CLI_GENERATE:
1961                 return NULL;
1962         }
1963
1964         AST_RWLIST_RDLOCK(&actions);
1965         AST_RWLIST_TRAVERSE(&actions, cur, list) {
1966                 int incoming_len = strlen(cur->action);
1967                 if (incoming_len > name_len) {
1968                         name_len = incoming_len;
1969                 }
1970         }
1971
1972         space_remaining = MGR_SHOW_TERMINAL_WIDTH - name_len - 4;
1973         if (space_remaining < 0) {
1974                 space_remaining = 0;
1975         }
1976
1977         ast_cli(a->fd, HSMC_FORMAT, name_len, name_len, "Action", space_remaining, "Synopsis");
1978         ast_cli(a->fd, HSMC_FORMAT, name_len, name_len, "------", space_remaining, "--------");
1979
1980         AST_RWLIST_TRAVERSE(&actions, cur, list) {
1981                 ast_cli(a->fd, HSMC_FORMAT, name_len, name_len, cur->action, space_remaining, cur->synopsis);
1982         }
1983         AST_RWLIST_UNLOCK(&actions);
1984
1985         return CLI_SUCCESS;
1986 }
1987
1988 /*! \brief CLI command manager list connected */
1989 static char *handle_showmanconn(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1990 {
1991         struct mansession_session *session;
1992         time_t now = time(NULL);
1993 #define HSMCONN_FORMAT1 "  %-15.15s  %-55.55s  %-10.10s  %-10.10s  %-8.8s  %-8.8s  %-5.5s  %-5.5s\n"
1994 #define HSMCONN_FORMAT2 "  %-15.15s  %-55.55s  %-10d  %-10d  %-8d  %-8d  %-5.5d  %-5.5d\n"
1995         int count = 0;
1996         struct ao2_iterator i;
1997
1998         switch (cmd) {
1999         case CLI_INIT:
2000                 e->command = "manager show connected";
2001                 e->usage =
2002                         "Usage: manager show connected\n"
2003                         "       Prints a listing of the users that are currently connected to the\n"
2004                         "Asterisk manager interface.\n";
2005                 return NULL;
2006         case CLI_GENERATE:
2007                 return NULL;
2008         }
2009
2010         ast_cli(a->fd, HSMCONN_FORMAT1, "Username", "IP Address", "Start", "Elapsed", "FileDes", "HttpCnt", "Read", "Write");
2011
2012         i = ao2_iterator_init(sessions, 0);
2013         while ((session = ao2_iterator_next(&i))) {
2014                 ao2_lock(session);
2015                 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);
2016                 count++;
2017                 ao2_unlock(session);
2018                 unref_mansession(session);
2019         }
2020         ao2_iterator_destroy(&i);
2021         ast_cli(a->fd, "%d users connected.\n", count);
2022
2023         return CLI_SUCCESS;
2024 }
2025
2026 /*! \brief CLI command manager list eventq */
2027 /* Should change to "manager show connected" */
2028 static char *handle_showmaneventq(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2029 {
2030         struct eventqent *s;
2031         switch (cmd) {
2032         case CLI_INIT:
2033                 e->command = "manager show eventq";
2034                 e->usage =
2035                         "Usage: manager show eventq\n"
2036                         "       Prints a listing of all events pending in the Asterisk manger\n"
2037                         "event queue.\n";
2038                 return NULL;
2039         case CLI_GENERATE:
2040                 return NULL;
2041         }
2042         AST_RWLIST_RDLOCK(&all_events);
2043         AST_RWLIST_TRAVERSE(&all_events, s, eq_next) {
2044                 ast_cli(a->fd, "Usecount: %d\n", s->usecount);
2045                 ast_cli(a->fd, "Category: %d\n", s->category);
2046                 ast_cli(a->fd, "Event:\n%s", s->eventdata);
2047         }
2048         AST_RWLIST_UNLOCK(&all_events);
2049
2050         return CLI_SUCCESS;
2051 }
2052
2053 /*! \brief CLI command manager reload */
2054 static char *handle_manager_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2055 {
2056         switch (cmd) {
2057         case CLI_INIT:
2058                 e->command = "manager reload";
2059                 e->usage =
2060                         "Usage: manager reload\n"
2061                         "       Reloads the manager configuration.\n";
2062                 return NULL;
2063         case CLI_GENERATE:
2064                 return NULL;
2065         }
2066         if (a->argc > 2) {
2067                 return CLI_SHOWUSAGE;
2068         }
2069         reload_manager();
2070         return CLI_SUCCESS;
2071 }
2072
2073 static struct eventqent *advance_event(struct eventqent *e)
2074 {
2075         struct eventqent *next;
2076
2077         AST_RWLIST_RDLOCK(&all_events);
2078         if ((next = AST_RWLIST_NEXT(e, eq_next))) {
2079                 ast_atomic_fetchadd_int(&next->usecount, 1);
2080                 ast_atomic_fetchadd_int(&e->usecount, -1);
2081         }
2082         AST_RWLIST_UNLOCK(&all_events);
2083         return next;
2084 }
2085
2086 #define GET_HEADER_FIRST_MATCH  0
2087 #define GET_HEADER_LAST_MATCH   1
2088 #define GET_HEADER_SKIP_EMPTY   2
2089
2090 /*!
2091  * \brief Return a matching header value.
2092  *
2093  * \details
2094  * Generic function to return either the first or the last
2095  * matching header from a list of variables, possibly skipping
2096  * empty strings.
2097  *
2098  * \note At the moment there is only one use of this function in
2099  * this file, so we make it static.
2100  *
2101  * \note Never returns NULL.
2102  */
2103 static const char *__astman_get_header(const struct message *m, char *var, int mode)
2104 {
2105         int x, l = strlen(var);
2106         const char *result = "";
2107
2108         if (!m) {
2109                 return result;
2110         }
2111
2112         for (x = 0; x < m->hdrcount; x++) {
2113                 const char *h = m->headers[x];
2114                 if (!strncasecmp(var, h, l) && h[l] == ':') {
2115                         const char *value = h + l + 1;
2116                         value = ast_skip_blanks(value); /* ignore leading spaces in the value */
2117                         /* found a potential candidate */
2118                         if ((mode & GET_HEADER_SKIP_EMPTY) && ast_strlen_zero(value)) {
2119                                 continue;       /* not interesting */
2120                         }
2121                         if (mode & GET_HEADER_LAST_MATCH) {
2122                                 result = value; /* record the last match so far */
2123                         } else {
2124                                 return value;
2125                         }
2126                 }
2127         }
2128
2129         return result;
2130 }
2131
2132 /*!
2133  * \brief Return the first matching variable from an array.
2134  *
2135  * \note This is the legacy function and is implemented in
2136  * therms of __astman_get_header().
2137  *
2138  * \note Never returns NULL.
2139  */
2140 const char *astman_get_header(const struct message *m, char *var)
2141 {
2142         return __astman_get_header(m, var, GET_HEADER_FIRST_MATCH);
2143 }
2144
2145 /*!
2146  * \internal
2147  * \brief Process one "Variable:" header value string.
2148  *
2149  * \param head Current list of AMI variables to get new values added.
2150  * \param hdr_val Header value string to process.
2151  *
2152  * \return New variable list head.
2153  */
2154 static struct ast_variable *man_do_variable_value(struct ast_variable *head, const char *hdr_val)
2155 {
2156         char *parse;
2157         AST_DECLARE_APP_ARGS(args,
2158                 AST_APP_ARG(vars)[64];
2159         );
2160
2161         hdr_val = ast_skip_blanks(hdr_val); /* ignore leading spaces in the value */
2162         parse = ast_strdupa(hdr_val);
2163
2164         /* Break the header value string into name=val pair items. */
2165         AST_STANDARD_APP_ARGS(args, parse);
2166         if (args.argc) {
2167                 int y;
2168
2169                 /* Process each name=val pair item. */
2170                 for (y = 0; y < args.argc; y++) {
2171                         struct ast_variable *cur;
2172                         char *var;
2173                         char *val;
2174
2175                         if (!args.vars[y]) {
2176                                 continue;
2177                         }
2178                         var = val = args.vars[y];
2179                         strsep(&val, "=");
2180
2181                         /* XXX We may wish to trim whitespace from the strings. */
2182                         if (!val || ast_strlen_zero(var)) {
2183                                 continue;
2184                         }
2185
2186                         /* Create new variable list node and prepend it to the list. */
2187                         cur = ast_variable_new(var, val, "");
2188                         if (cur) {
2189                                 cur->next = head;
2190                                 head = cur;
2191                         }
2192                 }
2193         }
2194
2195         return head;
2196 }
2197
2198 struct ast_variable *astman_get_variables(const struct message *m)
2199 {
2200         int varlen;
2201         int x;
2202         struct ast_variable *head = NULL;
2203
2204         static const char var_hdr[] = "Variable:";
2205
2206         /* Process all "Variable:" headers. */
2207         varlen = strlen(var_hdr);
2208         for (x = 0; x < m->hdrcount; x++) {
2209                 if (strncasecmp(var_hdr, m->headers[x], varlen)) {
2210                         continue;
2211                 }
2212                 head = man_do_variable_value(head, m->headers[x] + varlen);
2213         }
2214
2215         return head;
2216 }
2217
2218 /*! \brief access for hooks to send action messages to ami */
2219 int ast_hook_send_action(struct manager_custom_hook *hook, const char *msg)
2220 {
2221         const char *action;
2222         int ret = 0;
2223         struct manager_action *act_found;
2224         struct mansession s = {.session = NULL, };
2225         struct message m = { 0 };
2226         char *dup_str;
2227         char *src;
2228         int x = 0;
2229         int curlen;
2230
2231         if (hook == NULL) {
2232                 return -1;
2233         }
2234
2235         /* Create our own copy of the AMI action msg string. */
2236         src = dup_str = ast_strdup(msg);
2237         if (!dup_str) {
2238                 return -1;
2239         }
2240
2241         /* convert msg string to message struct */
2242         curlen = strlen(src);
2243         for (x = 0; x < curlen; x++) {
2244                 int cr; /* set if we have \r */
2245                 if (src[x] == '\r' && x+1 < curlen && src[x+1] == '\n')
2246                         cr = 2; /* Found. Update length to include \r\n */
2247                 else if (src[x] == '\n')
2248                         cr = 1; /* also accept \n only */
2249                 else
2250                         continue;
2251                 /* don't keep empty lines */
2252                 if (x && m.hdrcount < ARRAY_LEN(m.headers)) {
2253                         /* ... but trim \r\n and terminate the header string */
2254                         src[x] = '\0';
2255                         m.headers[m.hdrcount++] = src;
2256                 }
2257                 x += cr;
2258                 curlen -= x;            /* remaining size */
2259                 src += x;               /* update pointer */
2260                 x = -1;                 /* reset loop */
2261         }
2262
2263         action = astman_get_header(&m, "Action");
2264         if (strcasecmp(action, "login")) {
2265                 act_found = action_find(action);
2266                 if (act_found) {
2267                         /*
2268                          * we have to simulate a session for this action request
2269                          * to be able to pass it down for processing
2270                          * This is necessary to meet the previous design of manager.c
2271                          */
2272                         s.hook = hook;
2273                         s.f = (void*)1; /* set this to something so our request will make it through all functions that test it*/
2274
2275                         ao2_lock(act_found);
2276                         if (act_found->registered && act_found->func) {
2277                                 if (act_found->module) {
2278                                         ast_module_ref(act_found->module);
2279                                 }
2280                                 ao2_unlock(act_found);
2281                                 ret = act_found->func(&s, &m);
2282                                 ao2_lock(act_found);
2283                                 if (act_found->module) {
2284                                         ast_module_unref(act_found->module);
2285                                 }
2286                         } else {
2287                                 ret = -1;
2288                         }
2289                         ao2_unlock(act_found);
2290                         ao2_t_ref(act_found, -1, "done with found action object");
2291                 }
2292         }
2293         ast_free(dup_str);
2294         return ret;
2295 }
2296
2297
2298 /*!
2299  * helper function to send a string to the socket.
2300  * Return -1 on error (e.g. buffer full).
2301  */
2302 static int send_string(struct mansession *s, char *string)
2303 {
2304         int res;
2305         FILE *f = s->f ? s->f : s->session->f;
2306         int fd = s->f ? s->fd : s->session->fd;
2307
2308         /* It's a result from one of the hook's action invocation */
2309         if (s->hook) {
2310                 /*
2311                  * to send responses, we're using the same function
2312                  * as for receiving events. We call the event "HookResponse"
2313                  */
2314                 s->hook->helper(EVENT_FLAG_HOOKRESPONSE, "HookResponse", string);
2315                 return 0;
2316         }
2317
2318         if ((res = ast_careful_fwrite(f, fd, string, strlen(string), s->session->writetimeout))) {
2319                 s->write_error = 1;
2320         }
2321
2322         return res;
2323 }
2324
2325 /*!
2326  * \brief thread local buffer for astman_append
2327  *
2328  * \note This can not be defined within the astman_append() function
2329  *       because it declares a couple of functions that get used to
2330  *       initialize the thread local storage key.
2331  */
2332 AST_THREADSTORAGE(astman_append_buf);
2333
2334 AST_THREADSTORAGE(userevent_buf);
2335
2336 /*! \brief initial allocated size for the astman_append_buf and astman_send_*_va */
2337 #define ASTMAN_APPEND_BUF_INITSIZE   256
2338
2339 /*!
2340  * utility functions for creating AMI replies
2341  */
2342 void astman_append(struct mansession *s, const char *fmt, ...)
2343 {
2344         va_list ap;
2345         struct ast_str *buf;
2346
2347         if (!(buf = ast_str_thread_get(&astman_append_buf, ASTMAN_APPEND_BUF_INITSIZE))) {
2348                 return;
2349         }
2350
2351         va_start(ap, fmt);
2352         ast_str_set_va(&buf, 0, fmt, ap);
2353         va_end(ap);
2354
2355         if (s->f != NULL || s->session->f != NULL) {
2356                 send_string(s, ast_str_buffer(buf));
2357         } else {
2358                 ast_verbose("fd == -1 in astman_append, should not happen\n");
2359         }
2360 }
2361
2362 /*! \note NOTE: XXX this comment is unclear and possibly wrong.
2363    Callers of astman_send_error(), astman_send_response() or astman_send_ack() must EITHER
2364    hold the session lock _or_ be running in an action callback (in which case s->session->busy will
2365    be non-zero). In either of these cases, there is no need to lock-protect the session's
2366    fd, since no other output will be sent (events will be queued), and no input will
2367    be read until either the current action finishes or get_input() obtains the session
2368    lock.
2369  */
2370
2371 /*! \todo XXX MSG_MOREDATA should go to a header file. */
2372 #define MSG_MOREDATA    ((char *)astman_send_response)
2373
2374 /*! \brief send a response with an optional message,
2375  * and terminate it with an empty line.
2376  * m is used only to grab the 'ActionID' field.
2377  *
2378  * Use the explicit constant MSG_MOREDATA to remove the empty line.
2379  * XXX MSG_MOREDATA should go to a header file.
2380  */
2381 static void astman_send_response_full(struct mansession *s, const struct message *m, char *resp, char *msg, char *listflag)
2382 {
2383         const char *id = astman_get_header(m, "ActionID");
2384
2385         astman_append(s, "Response: %s\r\n", resp);
2386         if (!ast_strlen_zero(id)) {
2387                 astman_append(s, "ActionID: %s\r\n", id);
2388         }
2389         if (listflag) {
2390                 astman_append(s, "EventList: %s\r\n", listflag);        /* Start, complete, cancelled */
2391         }
2392         if (msg == MSG_MOREDATA) {
2393                 return;
2394         } else if (msg) {
2395                 astman_append(s, "Message: %s\r\n\r\n", msg);
2396         } else {
2397                 astman_append(s, "\r\n");
2398         }
2399 }
2400
2401 void astman_send_response(struct mansession *s, const struct message *m, char *resp, char *msg)
2402 {
2403         astman_send_response_full(s, m, resp, msg, NULL);
2404 }
2405
2406 void astman_send_error(struct mansession *s, const struct message *m, char *error)
2407 {
2408         astman_send_response_full(s, m, "Error", error, NULL);
2409 }
2410
2411 void astman_send_error_va(struct mansession *s, const struct message *m, const char *fmt, ...)
2412 {
2413         va_list ap;
2414         struct ast_str *buf;
2415         char *msg;
2416
2417         if (!(buf = ast_str_thread_get(&astman_append_buf, ASTMAN_APPEND_BUF_INITSIZE))) {
2418                 return;
2419         }
2420
2421         va_start(ap, fmt);
2422         ast_str_set_va(&buf, 0, fmt, ap);
2423         va_end(ap);
2424
2425         /* astman_append will use the same underlying buffer, so copy the message out
2426          * before sending the response */
2427         msg = ast_str_buffer(buf);
2428         if (msg) {
2429                 msg = ast_strdupa(msg);
2430         }
2431         astman_send_response_full(s, m, "Error", msg, NULL);
2432 }
2433
2434 void astman_send_ack(struct mansession *s, const struct message *m, char *msg)
2435 {
2436         astman_send_response_full(s, m, "Success", msg, NULL);
2437 }
2438
2439 static void astman_start_ack(struct mansession *s, const struct message *m)
2440 {
2441         astman_send_response_full(s, m, "Success", MSG_MOREDATA, NULL);
2442 }
2443
2444 void astman_send_listack(struct mansession *s, const struct message *m, char *msg, char *listflag)
2445 {
2446         astman_send_response_full(s, m, "Success", msg, listflag);
2447 }
2448
2449 /*! \brief Lock the 'mansession' structure. */
2450 static void mansession_lock(struct mansession *s)
2451 {
2452         ast_mutex_lock(&s->lock);
2453 }
2454
2455 /*! \brief Unlock the 'mansession' structure. */
2456 static void mansession_unlock(struct mansession *s)
2457 {
2458         ast_mutex_unlock(&s->lock);
2459 }
2460
2461 /*! \brief
2462    Rather than braindead on,off this now can also accept a specific int mask value
2463    or a ',' delim list of mask strings (the same as manager.conf) -anthm
2464 */
2465 static int set_eventmask(struct mansession *s, const char *eventmask)
2466 {
2467         int maskint = strings_to_mask(eventmask);
2468
2469         ao2_lock(s->session);
2470         if (maskint >= 0) {
2471                 s->session->send_events = maskint;
2472         }
2473         ao2_unlock(s->session);
2474
2475         return maskint;
2476 }
2477
2478 static enum ast_transport mansession_get_transport(const struct mansession *s)
2479 {
2480         return s->tcptls_session->parent->tls_cfg ? AST_TRANSPORT_TLS :
2481                         AST_TRANSPORT_TCP;
2482 }
2483
2484 static void report_invalid_user(const struct mansession *s, const char *username)
2485 {
2486         char session_id[32];
2487         struct ast_security_event_inval_acct_id inval_acct_id = {
2488                 .common.event_type = AST_SECURITY_EVENT_INVAL_ACCT_ID,
2489                 .common.version    = AST_SECURITY_EVENT_INVAL_ACCT_ID_VERSION,
2490                 .common.service    = "AMI",
2491                 .common.account_id = username,
2492                 .common.session_tv = &s->session->sessionstart_tv,
2493                 .common.local_addr = {
2494                         .addr      = &s->tcptls_session->parent->local_address,
2495                         .transport = mansession_get_transport(s),
2496                 },
2497                 .common.remote_addr = {
2498                         .addr      = &s->session->addr,
2499                         .transport = mansession_get_transport(s),
2500                 },
2501                 .common.session_id = session_id,
2502         };
2503
2504         snprintf(session_id, sizeof(session_id), "%p", s);
2505
2506         ast_security_event_report(AST_SEC_EVT(&inval_acct_id));
2507 }
2508
2509 static void report_failed_acl(const struct mansession *s, const char *username)
2510 {
2511         char session_id[32];
2512         struct ast_security_event_failed_acl failed_acl_event = {
2513                 .common.event_type = AST_SECURITY_EVENT_FAILED_ACL,
2514                 .common.version    = AST_SECURITY_EVENT_FAILED_ACL_VERSION,
2515                 .common.service    = "AMI",
2516                 .common.account_id = username,
2517                 .common.session_tv = &s->session->sessionstart_tv,
2518                 .common.local_addr = {
2519                         .addr      = &s->tcptls_session->parent->local_address,
2520                         .transport = mansession_get_transport(s),
2521                 },
2522                 .common.remote_addr = {
2523                         .addr      = &s->session->addr,
2524                         .transport = mansession_get_transport(s),
2525                 },
2526                 .common.session_id = session_id,
2527         };
2528
2529         snprintf(session_id, sizeof(session_id), "%p", s->session);
2530
2531         ast_security_event_report(AST_SEC_EVT(&failed_acl_event));
2532 }
2533
2534 static void report_inval_password(const struct mansession *s, const char *username)
2535 {
2536         char session_id[32];
2537         struct ast_security_event_inval_password inval_password = {
2538                 .common.event_type = AST_SECURITY_EVENT_INVAL_PASSWORD,
2539                 .common.version    = AST_SECURITY_EVENT_INVAL_PASSWORD_VERSION,
2540                 .common.service    = "AMI",
2541                 .common.account_id = username,
2542                 .common.session_tv = &s->session->sessionstart_tv,
2543                 .common.local_addr = {
2544                         .addr      = &s->tcptls_session->parent->local_address,
2545                         .transport = mansession_get_transport(s),
2546                 },
2547                 .common.remote_addr = {
2548                         .addr      = &s->session->addr,
2549                         .transport = mansession_get_transport(s),
2550                 },
2551                 .common.session_id = session_id,
2552         };
2553
2554         snprintf(session_id, sizeof(session_id), "%p", s->session);
2555
2556         ast_security_event_report(AST_SEC_EVT(&inval_password));
2557 }
2558
2559 static void report_auth_success(const struct mansession *s)
2560 {
2561         char session_id[32];
2562         struct ast_security_event_successful_auth successful_auth = {
2563                 .common.event_type = AST_SECURITY_EVENT_SUCCESSFUL_AUTH,
2564                 .common.version    = AST_SECURITY_EVENT_SUCCESSFUL_AUTH_VERSION,
2565                 .common.service    = "AMI",
2566                 .common.account_id = s->session->username,
2567                 .common.session_tv = &s->session->sessionstart_tv,
2568                 .common.local_addr = {
2569                         .addr      = &s->tcptls_session->parent->local_address,
2570                         .transport = mansession_get_transport(s),
2571                 },
2572                 .common.remote_addr = {
2573                         .addr      = &s->session->addr,
2574                         .transport = mansession_get_transport(s),
2575                 },
2576                 .common.session_id = session_id,
2577         };
2578
2579         snprintf(session_id, sizeof(session_id), "%p", s->session);
2580
2581         ast_security_event_report(AST_SEC_EVT(&successful_auth));
2582 }
2583
2584 static void report_req_not_allowed(const struct mansession *s, const char *action)
2585 {
2586         char session_id[32];
2587         char request_type[64];
2588         struct ast_security_event_req_not_allowed req_not_allowed = {
2589                 .common.event_type = AST_SECURITY_EVENT_REQ_NOT_ALLOWED,
2590                 .common.version    = AST_SECURITY_EVENT_REQ_NOT_ALLOWED_VERSION,
2591                 .common.service    = "AMI",
2592                 .common.account_id = s->session->username,
2593                 .common.session_tv = &s->session->sessionstart_tv,
2594                 .common.local_addr = {
2595                         .addr      = &s->tcptls_session->parent->local_address,
2596                         .transport = mansession_get_transport(s),
2597                 },
2598                 .common.remote_addr = {
2599                         .addr      = &s->session->addr,
2600                         .transport = mansession_get_transport(s),
2601                 },
2602                 .common.session_id = session_id,
2603
2604                 .request_type      = request_type,
2605         };
2606
2607         snprintf(session_id, sizeof(session_id), "%p", s->session);
2608         snprintf(request_type, sizeof(request_type), "Action: %s", action);
2609
2610         ast_security_event_report(AST_SEC_EVT(&req_not_allowed));
2611 }
2612
2613 static void report_req_bad_format(const struct mansession *s, const char *action)
2614 {
2615         char session_id[32];
2616         char request_type[64];
2617         struct ast_security_event_req_bad_format req_bad_format = {
2618                 .common.event_type = AST_SECURITY_EVENT_REQ_BAD_FORMAT,
2619                 .common.version    = AST_SECURITY_EVENT_REQ_BAD_FORMAT_VERSION,
2620                 .common.service    = "AMI",
2621                 .common.account_id = s->session->username,
2622                 .common.session_tv = &s->session->sessionstart_tv,
2623                 .common.local_addr = {
2624                         .addr      = &s->tcptls_session->parent->local_address,
2625                         .transport = mansession_get_transport(s),
2626                 },
2627                 .common.remote_addr = {
2628                         .addr      = &s->session->addr,
2629                         .transport = mansession_get_transport(s),
2630                 },
2631                 .common.session_id = session_id,
2632
2633                 .request_type      = request_type,
2634         };
2635
2636         snprintf(session_id, sizeof(session_id), "%p", s->session);
2637         snprintf(request_type, sizeof(request_type), "Action: %s", action);
2638
2639         ast_security_event_report(AST_SEC_EVT(&req_bad_format));
2640 }
2641
2642 static void report_failed_challenge_response(const struct mansession *s,
2643                 const char *response, const char *expected_response)
2644 {
2645         char session_id[32];
2646         struct ast_security_event_chal_resp_failed chal_resp_failed = {
2647                 .common.event_type = AST_SECURITY_EVENT_CHAL_RESP_FAILED,
2648                 .common.version    = AST_SECURITY_EVENT_CHAL_RESP_FAILED_VERSION,
2649                 .common.service    = "AMI",
2650                 .common.account_id = s->session->username,
2651                 .common.session_tv = &s->session->sessionstart_tv,
2652                 .common.local_addr = {
2653                         .addr      = &s->tcptls_session->parent->local_address,
2654                         .transport = mansession_get_transport(s),
2655                 },
2656                 .common.remote_addr = {
2657                         .addr      = &s->session->addr,
2658                         .transport = mansession_get_transport(s),
2659                 },
2660                 .common.session_id = session_id,
2661
2662                 .challenge         = s->session->challenge,
2663                 .response          = response,
2664                 .expected_response = expected_response,
2665         };
2666
2667         snprintf(session_id, sizeof(session_id), "%p", s->session);
2668
2669         ast_security_event_report(AST_SEC_EVT(&chal_resp_failed));
2670 }
2671
2672 static void report_session_limit(const struct mansession *s)
2673 {
2674         char session_id[32];
2675         struct ast_security_event_session_limit session_limit = {
2676                 .common.event_type = AST_SECURITY_EVENT_SESSION_LIMIT,
2677                 .common.version    = AST_SECURITY_EVENT_SESSION_LIMIT_VERSION,
2678                 .common.service    = "AMI",
2679                 .common.account_id = s->session->username,
2680                 .common.session_tv = &s->session->sessionstart_tv,
2681                 .common.local_addr = {
2682                         .addr      = &s->tcptls_session->parent->local_address,
2683                         .transport = mansession_get_transport(s),
2684                 },
2685                 .common.remote_addr = {
2686                         .addr      = &s->session->addr,
2687                         .transport = mansession_get_transport(s),
2688                 },
2689                 .common.session_id = session_id,
2690         };
2691
2692         snprintf(session_id, sizeof(session_id), "%p", s->session);
2693
2694         ast_security_event_report(AST_SEC_EVT(&session_limit));
2695 }
2696
2697 /*
2698  * Here we start with action_ handlers for AMI actions,
2699  * and the internal functions used by them.
2700  * Generally, the handlers are called action_foo()
2701  */
2702
2703 /* helper function for action_login() */
2704 static int authenticate(struct mansession *s, const struct message *m)
2705 {
2706         const char *username = astman_get_header(m, "Username");
2707         const char *password = astman_get_header(m, "Secret");
2708         int error = -1;
2709         struct ast_manager_user *user = NULL;
2710         regex_t *regex_filter;
2711         struct ao2_iterator filter_iter;
2712
2713         if (ast_strlen_zero(username)) {        /* missing username */
2714                 return -1;
2715         }
2716
2717         /* locate user in locked state */
2718         AST_RWLIST_WRLOCK(&users);
2719
2720         if (!(user = get_manager_by_name_locked(username))) {
2721                 report_invalid_user(s, username);
2722                 ast_log(LOG_NOTICE, "%s tried to authenticate with nonexistent user '%s'\n", ast_sockaddr_stringify_addr(&s->session->addr), username);
2723         } else if (user->acl && (ast_apply_acl(user->acl, &s->session->addr, "Manager User ACL: ") == AST_SENSE_DENY)) {
2724                 report_failed_acl(s, username);
2725                 ast_log(LOG_NOTICE, "%s failed to pass IP ACL as '%s'\n", ast_sockaddr_stringify_addr(&s->session->addr), username);
2726         } else if (!strcasecmp(astman_get_header(m, "AuthType"), "MD5")) {
2727                 const char *key = astman_get_header(m, "Key");
2728                 if (!ast_strlen_zero(key) && !ast_strlen_zero(s->session->challenge) && user->secret) {
2729                         int x;
2730                         int len = 0;
2731                         char md5key[256] = "";
2732                         struct MD5Context md5;
2733                         unsigned char digest[16];
2734
2735                         MD5Init(&md5);
2736                         MD5Update(&md5, (unsigned char *) s->session->challenge, strlen(s->session->challenge));
2737                         MD5Update(&md5, (unsigned char *) user->secret, strlen(user->secret));
2738                         MD5Final(digest, &md5);
2739                         for (x = 0; x < 16; x++)
2740                                 len += sprintf(md5key + len, "%2.2x", digest[x]);
2741                         if (!strcmp(md5key, key)) {
2742                                 error = 0;
2743                         } else {
2744                                 report_failed_challenge_response(s, key, md5key);
2745                         }
2746                 } else {
2747                         ast_debug(1, "MD5 authentication is not possible.  challenge: '%s'\n",
2748                                 S_OR(s->session->challenge, ""));
2749                 }
2750         } else if (user->secret) {
2751                 if (!strcmp(password, user->secret)) {
2752                         error = 0;
2753                 } else {
2754                         report_inval_password(s, username);
2755                 }
2756         }
2757
2758         if (error) {
2759                 ast_log(LOG_NOTICE, "%s failed to authenticate as '%s'\n", ast_sockaddr_stringify_addr(&s->session->addr), username);
2760                 AST_RWLIST_UNLOCK(&users);
2761                 return -1;
2762         }
2763
2764         /* auth complete */
2765
2766         /* All of the user parameters are copied to the session so that in the event
2767         * of a reload and a configuration change, the session parameters are not
2768         * changed. */
2769         ast_copy_string(s->session->username, username, sizeof(s->session->username));
2770         s->session->readperm = user->readperm;
2771         s->session->writeperm = user->writeperm;
2772         s->session->writetimeout = user->writetimeout;
2773         if (user->chanvars) {
2774                 s->session->chanvars = ast_variables_dup(user->chanvars);
2775         }
2776
2777         filter_iter = ao2_iterator_init(user->whitefilters, 0);
2778         while ((regex_filter = ao2_iterator_next(&filter_iter))) {
2779                 ao2_t_link(s->session->whitefilters, regex_filter, "add white user filter to session");
2780                 ao2_t_ref(regex_filter, -1, "remove iterator ref");
2781         }
2782         ao2_iterator_destroy(&filter_iter);
2783
2784         filter_iter = ao2_iterator_init(user->blackfilters, 0);
2785         while ((regex_filter = ao2_iterator_next(&filter_iter))) {
2786                 ao2_t_link(s->session->blackfilters, regex_filter, "add black user filter to session");
2787                 ao2_t_ref(regex_filter, -1, "remove iterator ref");
2788         }
2789         ao2_iterator_destroy(&filter_iter);
2790
2791         s->session->sessionstart = time(NULL);
2792         s->session->sessionstart_tv = ast_tvnow();
2793         set_eventmask(s, astman_get_header(m, "Events"));
2794
2795         report_auth_success(s);
2796
2797         AST_RWLIST_UNLOCK(&users);
2798         return 0;
2799 }
2800
2801 static int action_ping(struct mansession *s, const struct message *m)
2802 {
2803         const char *actionid = astman_get_header(m, "ActionID");
2804         struct timeval now = ast_tvnow();
2805
2806         astman_append(s, "Response: Success\r\n");
2807         if (!ast_strlen_zero(actionid)){
2808                 astman_append(s, "ActionID: %s\r\n", actionid);
2809         }
2810         astman_append(
2811                 s,
2812                 "Ping: Pong\r\n"
2813                 "Timestamp: %ld.%06lu\r\n"
2814                 "\r\n",
2815                 (long) now.tv_sec, (unsigned long) now.tv_usec);
2816         return 0;
2817 }
2818
2819 static int action_getconfig(struct mansession *s, const struct message *m)
2820 {
2821         struct ast_config *cfg;
2822         const char *fn = astman_get_header(m, "Filename");
2823         const char *category = astman_get_header(m, "Category");
2824         int catcount = 0;
2825         int lineno = 0;
2826         char *cur_category = NULL;
2827         struct ast_variable *v;
2828         struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
2829
2830         if (ast_strlen_zero(fn)) {
2831                 astman_send_error(s, m, "Filename not specified");
2832                 return 0;
2833         }
2834         cfg = ast_config_load2(fn, "manager", config_flags);
2835         if (cfg == CONFIG_STATUS_FILEMISSING) {
2836                 astman_send_error(s, m, "Config file not found");
2837                 return 0;
2838         } else if (cfg == CONFIG_STATUS_FILEINVALID) {
2839                 astman_send_error(s, m, "Config file has invalid format");
2840                 return 0;
2841         }
2842
2843         astman_start_ack(s, m);
2844         while ((cur_category = ast_category_browse(cfg, cur_category))) {
2845                 if (ast_strlen_zero(category) || (!ast_strlen_zero(category) && !strcmp(category, cur_category))) {
2846                         lineno = 0;
2847                         astman_append(s, "Category-%06d: %s\r\n", catcount, cur_category);
2848                         for (v = ast_variable_browse(cfg, cur_category); v; v = v->next) {
2849                                 astman_append(s, "Line-%06d-%06d: %s=%s\r\n", catcount, lineno++, v->name, v->value);
2850                         }
2851                         catcount++;
2852                 }
2853         }
2854         if (!ast_strlen_zero(category) && catcount == 0) { /* TODO: actually, a config with no categories doesn't even get loaded */
2855                 astman_append(s, "No categories found\r\n");
2856         }
2857         ast_config_destroy(cfg);
2858         astman_append(s, "\r\n");
2859
2860         return 0;
2861 }
2862
2863 static int action_listcategories(struct mansession *s, const struct message *m)
2864 {
2865         struct ast_config *cfg;
2866         const char *fn = astman_get_header(m, "Filename");
2867         char *category = NULL;
2868         struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
2869         int catcount = 0;
2870
2871         if (ast_strlen_zero(fn)) {
2872                 astman_send_error(s, m, "Filename not specified");
2873                 return 0;
2874         }
2875         if (!(cfg = ast_config_load2(fn, "manager", config_flags))) {
2876                 astman_send_error(s, m, "Config file not found");
2877                 return 0;
2878         } else if (cfg == CONFIG_STATUS_FILEINVALID) {
2879                 astman_send_error(s, m, "Config file has invalid format");
2880                 return 0;
2881         }
2882         astman_start_ack(s, m);
2883         while ((category = ast_category_browse(cfg, category))) {
2884                 astman_append(s, "Category-%06d: %s\r\n", catcount, category);
2885                 catcount++;
2886         }
2887         if (catcount == 0) { /* TODO: actually, a config with no categories doesn't even get loaded */
2888                 astman_append(s, "Error: no categories found\r\n");
2889         }
2890         ast_config_destroy(cfg);
2891         astman_append(s, "\r\n");
2892
2893         return 0;
2894 }
2895
2896
2897
2898
2899 /*! The amount of space in out must be at least ( 2 * strlen(in) + 1 ) */
2900 static void json_escape(char *out, const char *in)
2901 {
2902         for (; *in; in++) {
2903                 if (*in == '\\' || *in == '\"') {
2904                         *out++ = '\\';
2905                 }
2906                 *out++ = *in;
2907         }
2908         *out = '\0';
2909 }
2910
2911 /*!
2912  * \internal
2913  * \brief Append a JSON escaped string to the manager stream.
2914  *
2915  * \param s AMI stream to append a string.
2916  * \param str String to append to the stream after JSON escaping it.
2917  *
2918  * \return Nothing
2919  */
2920 static void astman_append_json(struct mansession *s, const char *str)
2921 {
2922         char *buf;
2923
2924         buf = ast_alloca(2 * strlen(str) + 1);
2925         json_escape(buf, str);
2926         astman_append(s, "%s", buf);
2927 }
2928
2929 static int action_getconfigjson(struct mansession *s, const struct message *m)
2930 {
2931         struct ast_config *cfg;
2932         const char *fn = astman_get_header(m, "Filename");
2933         char *category = NULL;
2934         struct ast_variable *v;
2935         int comma1 = 0;
2936         struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
2937
2938         if (ast_strlen_zero(fn)) {
2939                 astman_send_error(s, m, "Filename not specified");
2940                 return 0;
2941         }
2942
2943         if (!(cfg = ast_config_load2(fn, "manager", config_flags))) {
2944                 astman_send_error(s, m, "Config file not found");
2945                 return 0;
2946         } else if (cfg == CONFIG_STATUS_FILEINVALID) {
2947                 astman_send_error(s, m, "Config file has invalid format");
2948                 return 0;
2949         }
2950
2951         astman_start_ack(s, m);
2952         astman_append(s, "JSON: {");
2953         while ((category = ast_category_browse(cfg, category))) {
2954                 int comma2 = 0;
2955
2956                 astman_append(s, "%s\"", comma1 ? "," : "");
2957                 astman_append_json(s, category);
2958                 astman_append(s, "\":[");
2959                 comma1 = 1;
2960                 for (v = ast_variable_browse(cfg, category); v; v = v->next) {
2961                         astman_append(s, "%s\"", comma2 ? "," : "");
2962                         astman_append_json(s, v->name);
2963                         astman_append(s, "\":\"");
2964                         astman_append_json(s, v->value);
2965                         astman_append(s, "\"");
2966                         comma2 = 1;
2967                 }
2968                 astman_append(s, "]");
2969         }
2970         astman_append(s, "}\r\n\r\n");
2971
2972         ast_config_destroy(cfg);
2973
2974         return 0;
2975 }
2976
2977 /*! \brief helper function for action_updateconfig */
2978 static enum error_type handle_updates(struct mansession *s, const struct message *m, struct ast_config *cfg, const char *dfn)
2979 {
2980         int x;
2981         char hdr[40];
2982         const char *action, *cat, *var, *value, *match, *line;
2983         struct ast_category *category;
2984         struct ast_variable *v;
2985         struct ast_str *str1 = ast_str_create(16), *str2 = ast_str_create(16);
2986         enum error_type result = 0;
2987
2988         for (x = 0; x < 100000; x++) {  /* 100000 = the max number of allowed updates + 1 */
2989                 unsigned int object = 0;
2990
2991                 snprintf(hdr, sizeof(hdr), "Action-%06d", x);
2992                 action = astman_get_header(m, hdr);
2993                 if (ast_strlen_zero(action))            /* breaks the for loop if no action header */
2994                         break;                          /* this could cause problems if actions come in misnumbered */
2995
2996                 snprintf(hdr, sizeof(hdr), "Cat-%06d", x);
2997                 cat = astman_get_header(m, hdr);
2998                 if (ast_strlen_zero(cat)) {             /* every action needs a category */
2999                         result =  UNSPECIFIED_CATEGORY;
3000                         break;
3001                 }
3002
3003                 snprintf(hdr, sizeof(hdr), "Var-%06d", x);
3004                 var = astman_get_header(m, hdr);
3005
3006                 snprintf(hdr, sizeof(hdr), "Value-%06d", x);
3007                 value = astman_get_header(m, hdr);
3008
3009                 if (!ast_strlen_zero(value) && *value == '>') {
3010                         object = 1;
3011                         value++;
3012                 }
3013
3014                 snprintf(hdr, sizeof(hdr), "Match-%06d", x);
3015                 match = astman_get_header(m, hdr);
3016
3017                 snprintf(hdr, sizeof(hdr), "Line-%06d", x);
3018                 line = astman_get_header(m, hdr);
3019
3020                 if (!strcasecmp(action, "newcat")) {
3021                         if (ast_category_get(cfg,cat)) {        /* check to make sure the cat doesn't */
3022                                 result = FAILURE_NEWCAT;        /* already exist */
3023                                 break;
3024                         }
3025                         if (!(category = ast_category_new(cat, dfn, -1))) {
3026                                 result = FAILURE_ALLOCATION;
3027                                 break;
3028                         }
3029                         if (ast_strlen_zero(match)) {
3030                                 ast_category_append(cfg, category);
3031                         } else {
3032                                 ast_category_insert(cfg, category, match);
3033                         }
3034                 } else if (!strcasecmp(action, "renamecat")) {
3035                         if (ast_strlen_zero(value)) {
3036                                 result = UNSPECIFIED_ARGUMENT;
3037                                 break;
3038                         }
3039                         if (!(category = ast_category_get(cfg, cat))) {
3040                                 result = UNKNOWN_CATEGORY;
3041                                 break;
3042                         }
3043                         ast_category_rename(category, value);
3044                 } else if (!strcasecmp(action, "delcat")) {
3045                         if (ast_category_delete(cfg, cat)) {
3046                                 result = FAILURE_DELCAT;
3047                                 break;
3048                         }
3049                 } else if (!strcasecmp(action, "emptycat")) {
3050                         if (ast_category_empty(cfg, cat)) {