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