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