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