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