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