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