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