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