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