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